-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver.js
More file actions
1968 lines (1720 loc) · 77 KB
/
server.js
File metadata and controls
1968 lines (1720 loc) · 77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import express from 'express';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { networkInterfaces } from 'node:os';
import { randomUUID, timingSafeEqual } from 'node:crypto';
import { loadConfig } from './src/config.js';
import { parseShlUri } from './src/shl/uri-parser.js';
import { fetchManifest } from './src/shl/manifest.js';
import { extractHealthData, validateFhirBundles } from './src/shl/fhir-extractor.js';
import { writeToFiles } from './src/output/file-writer.js';
import { postToApi } from './src/output/api-poster.js';
import { uploadToDrive, getOAuth2Client, parseFolderId } from './src/output/drive-uploader.js';
import { sendEmail } from './src/output/email-sender.js';
import { uploadToOnedrive, getOnedriveAuthUrl, exchangeOnedriveCode } from './src/output/onedrive-uploader.js';
import { uploadToBox, getBoxAuthUrl, exchangeBoxCode } from './src/output/box-uploader.js';
import { sendViaGmail, getGmailAuthUrl, exchangeGmailCode, getGmailUserEmail } from './src/output/gmail-sender.js';
import { sendViaOutlook, getOutlookMailAuthUrl, exchangeOutlookMailCode, getOutlookUserEmail } from './src/output/outlook-sender.js';
import { initDb, getDb, createOrg, getOrgBySlug, getOrgById, updateOrgSettings, slugExists, listAllOrgs, deleteOrgById, countOrgs, createApprovalRequest, listApprovalRequests, updateApprovalRequest, getDecryptedToken, prepareTokenForStorage, logAuditEvent, listAuditLog, listAllAuditLog } from './src/db.js';
import { hashPassword, verifyPassword, createToken, authMiddleware } from './src/auth.js';
import { readFileSync } from 'node:fs';
import rateLimit from 'express-rate-limit';
// Load version from package.json at startup
const pkg = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'package.json'), 'utf-8'));
const APP_VERSION = pkg.version;
const __dirname = dirname(fileURLToPath(import.meta.url));
const app = express();
const config = loadConfig();
const PORT = process.env.PORT || config.server?.port || 3000;
const HOST = process.env.HOST || config.server?.host || '0.0.0.0';
const RESERVED_SLUGS = ['register', 'admin', 'api', 'auth', 'public', 'static', 'assets', 'health', 'index.html', 'privacy', 'terms', 'super-admin', 'setup-guide', 'test-qr-codes'];
// ── CMS Health Tech Ecosystem — Kill the Clipboard Approved Apps ──
const APPROVED_APPS = [
// Early Adopters (12)
{ appId: 'apple', name: 'Apple', tier: 'early-adopter' },
{ appId: 'bwell', name: 'b.well Connected Health', tier: 'early-adopter' },
{ appId: 'citizen-health', name: 'Citizen Health', tier: 'early-adopter' },
{ appId: 'cvs-health', name: 'CVS Health', tier: 'early-adopter' },
{ appId: 'fasten-health', name: 'Fasten Health', tier: 'early-adopter' },
{ appId: 'flexpa', name: 'Flexpa', tier: 'early-adopter' },
{ appId: 'google', name: 'Google', tier: 'early-adopter' },
{ appId: 'nanthealth', name: 'NantHealth', tier: 'early-adopter' },
{ appId: 'samsung', name: 'Samsung', tier: 'early-adopter' },
{ appId: 'sharecare', name: 'Sharecare', tier: 'early-adopter' },
{ appId: 'unitedhealth-group', name: 'UnitedHealth Group', tier: 'early-adopter' },
{ appId: 'zocdoc', name: 'Zocdoc', tier: 'early-adopter' },
// Pledgees (71)
{ appId: '1kosmos', name: '1Kosmos', tier: 'pledgee' },
{ appId: 'actuvi', name: 'Actuvi LLC', tier: 'pledgee' },
{ appId: 'andor-health', name: 'Andor Health', tier: 'pledgee' },
{ appId: 'andromeda-health', name: 'Andromeda Health Corp', tier: 'pledgee' },
{ appId: 'capital-rx', name: 'Capital Rx Inc.', tier: 'pledgee' },
{ appId: 'coco-health', name: 'Coco Health', tier: 'pledgee' },
{ appId: 'coligomed', name: 'ColigoMed', tier: 'pledgee' },
{ appId: 'connxus', name: 'Connxus', tier: 'pledgee' },
{ appId: 'credibl', name: 'Credibl', tier: 'pledgee' },
{ appId: 'cuezen', name: 'CueZen Inc.', tier: 'pledgee' },
{ appId: 'cyrencare', name: 'CyrenCare', tier: 'pledgee' },
{ appId: 'docusign', name: 'Docusign', tier: 'pledgee' },
{ appId: 'edwin-health', name: 'Edwin Health', tier: 'pledgee' },
{ appId: 'es-digital-health', name: 'ES Digital Health', tier: 'pledgee' },
{ appId: 'evisit', name: 'eVisit', tier: 'pledgee' },
{ appId: 'exammed', name: 'ExamMed LLC', tier: 'pledgee' },
{ appId: 'fabric', name: 'Fabric', tier: 'pledgee' },
{ appId: 'fawkes-biodata', name: 'Fawkes Biodata', tier: 'pledgee' },
{ appId: 'flagler-health', name: 'Flagler Health', tier: 'pledgee' },
{ appId: 'formdr', name: 'FormDr', tier: 'pledgee' },
{ appId: 'genoplex', name: 'Genoplex', tier: 'pledgee' },
{ appId: 'goodrx', name: 'GoodRx', tier: 'pledgee' },
{ appId: 'guava-health', name: 'Guava Health', tier: 'pledgee' },
{ appId: 'haau3', name: 'haau3', tier: 'pledgee' },
{ appId: 'health-bank-one', name: 'Health Bank One Inc.', tier: 'pledgee' },
{ appId: 'health-note', name: 'Health Note', tier: 'pledgee' },
{ appId: 'healthbookplus', name: 'HealthBook+', tier: 'pledgee' },
{ appId: 'healthex', name: 'HealthEx', tier: 'pledgee' },
{ appId: 'healthhive', name: 'HealthHive', tier: 'pledgee' },
{ appId: 'healthtree', name: 'HealthTree Foundation', tier: 'pledgee' },
{ appId: 'healthy-insights', name: 'Healthy Insights Inc.', tier: 'pledgee' },
{ appId: 'healthyr', name: 'Healthyr', tier: 'pledgee' },
{ appId: 'humetrix', name: 'Humetrix Health', tier: 'pledgee' },
{ appId: 'imprivata', name: 'Imprivata Inc.', tier: 'pledgee' },
{ appId: 'inpursuit-health', name: 'InPursuit Health LLC', tier: 'pledgee' },
{ appId: 'intelichart', name: 'InteliChart', tier: 'pledgee' },
{ appId: 'january-ai', name: 'January AI', tier: 'pledgee' },
{ appId: 'jeeva-ai', name: 'Jeeva AI Health Systems LLC', tier: 'pledgee' },
{ appId: 'kintsugi', name: 'Kintsugi Mindful Wellness', tier: 'pledgee' },
{ appId: 'login-health', name: 'Login.Health', tier: 'pledgee' },
{ appId: 'luma-health', name: 'Luma Health', tier: 'pledgee' },
{ appId: 'lymeless', name: 'LymeLess Health', tier: 'pledgee' },
{ appId: 'magical', name: 'Magical', tier: 'pledgee' },
{ appId: 'marsha-health', name: 'MARSHA Health', tier: 'pledgee' },
{ appId: 'massive-bio', name: 'Massive Bio Inc.', tier: 'pledgee' },
{ appId: 'mhdg', name: 'Medical Home Development Group', tier: 'pledgee' },
{ appId: 'medicasoft', name: 'MedicaSoft', tier: 'pledgee' },
{ appId: 'medthread', name: 'MedThread', tier: 'pledgee' },
{ appId: 'mihin', name: 'MiHIN', tier: 'pledgee' },
{ appId: 'miracural', name: 'Miracural AI', tier: 'pledgee' },
{ appId: 'nourish', name: 'Nourish', tier: 'pledgee' },
{ appId: 'orion-health', name: 'Orion Health', tier: 'pledgee' },
{ appId: 'otis-health', name: 'Otis Health', tier: 'pledgee' },
{ appId: 'patient-centric', name: 'Patient Centric Solutions', tier: 'pledgee' },
{ appId: 'patient-com', name: 'Patient.com', tier: 'pledgee' },
{ appId: 'patientory', name: 'Patientory Inc.', tier: 'pledgee' },
{ appId: 'pfps-us', name: 'Patients for Patient Safety US', tier: 'pledgee' },
{ appId: 'penn-medicine', name: 'Penn Medicine', tier: 'pledgee' },
{ appId: 'phreesia', name: 'Phreesia', tier: 'pledgee' },
{ appId: 'primary-record', name: 'Primary Record', tier: 'pledgee' },
{ appId: 'pulsar-health', name: 'Pulsar Health Inc', tier: 'pledgee' },
{ appId: 'seqster', name: 'SEQSTER', tier: 'pledgee' },
{ appId: 'sprinter-health', name: 'Sprinter Health', tier: 'pledgee' },
{ appId: 'sync-md', name: 'Sync.MD', tier: 'pledgee' },
{ appId: 'commons-project', name: 'The Commons Project Foundation', tier: 'pledgee' },
{ appId: 'trialcliniq', name: 'TrialClinIQ', tier: 'pledgee' },
{ appId: 'vinyl-health', name: 'Vinyl Health', tier: 'pledgee' },
{ appId: 'wellconnector', name: 'WellConnector', tier: 'pledgee' },
{ appId: 'wellnavigator', name: 'WellNavigator LLC', tier: 'pledgee' },
{ appId: 'xcures', name: 'xCures', tier: 'pledgee' },
{ appId: 'yosi-health', name: 'Yosi Health', tier: 'pledgee' },
];
app.use(express.json({ limit: '10mb' }));
// ── Server-side HTML escaping (for OAuth error pages) ──
function escapeHtml(str) {
if (str == null) return '';
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
// ── Slug validation (for OAuth state parameters) ──
function isValidSlug(slug) {
return typeof slug === 'string' && /^[a-z][a-z0-9-]{1,49}$/.test(slug);
}
// ── HMAC-signed OAuth state (CSRF protection) ──
// Prevents attackers from forging state to link their storage to a victim's org.
import { createHmac as _createHmac } from 'node:crypto';
function createSignedOAuthState(slug, orgId) {
const payload = JSON.stringify({ slug, orgId });
const secret = process.env.SESSION_SECRET || 'oauth-state-fallback';
const sig = _createHmac('sha256', secret).update(payload).digest('base64url');
return JSON.stringify({ slug, orgId, sig });
}
function verifyOAuthState(stateString) {
if (!stateString) return null;
try {
const parsed = JSON.parse(stateString);
if (!parsed.sig || !parsed.slug) return null;
const payload = JSON.stringify({ slug: parsed.slug, orgId: parsed.orgId });
const secret = process.env.SESSION_SECRET || 'oauth-state-fallback';
const expectedSig = _createHmac('sha256', secret).update(payload).digest('base64url');
const sigBuf = Buffer.from(parsed.sig);
const expectedBuf = Buffer.from(expectedSig);
if (sigBuf.length !== expectedBuf.length || !timingSafeEqual(sigBuf, expectedBuf)) {
return null;
}
if (!isValidSlug(parsed.slug)) return null;
return { slug: parsed.slug, orgId: parsed.orgId };
} catch {
return null;
}
}
// ── Rate Limiting ──
// Protect auth endpoints against brute-force and proxy endpoints against abuse.
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 20, // 20 attempts per window per IP
standardHeaders: true,
legacyHeaders: false,
message: { error: 'Too many authentication attempts. Please try again later.' },
});
const proxyLimiter = rateLimit({
windowMs: 1 * 60 * 1000, // 1 minute
max: 30, // 30 requests per minute per IP
standardHeaders: true,
legacyHeaders: false,
message: { error: 'Too many requests. Please slow down.' },
});
const registrationLimiter = rateLimit({
windowMs: 60 * 60 * 1000, // 1 hour
max: 5, // 5 registrations per hour per IP
standardHeaders: true,
legacyHeaders: false,
message: { error: 'Too many registration attempts. Please try again later.' },
});
// ── Content Security Policy ──
// Mitigates XSS by restricting which scripts, styles, and connections are allowed.
// CDN scripts are pinned to specific versions and verified via Subresource Integrity (SRI) hashes.
// Note: 'unsafe-inline' is required for onclick handlers in HTML; all innerHTML uses escapeHtml().
app.use((req, res, next) => {
res.setHeader('Content-Security-Policy', [
"default-src 'self'",
"script-src 'self' 'unsafe-inline' https://unpkg.com https://cdnjs.cloudflare.com https://cdn.jsdelivr.net",
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
"font-src 'self' https://fonts.gstatic.com",
"img-src 'self' data: blob:",
"connect-src 'self'",
"media-src 'self' blob:",
"frame-src 'self' blob: data:",
"object-src 'none'",
"base-uri 'self'",
].join('; '));
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
next();
});
// ── Explicit page routes (before static, so they override index.html default) ──
app.get('/', (req, res) => {
res.sendFile(join(__dirname, 'public', 'landing.html'));
});
app.get('/register', (req, res) => {
res.sendFile(join(__dirname, 'public', 'register.html'));
});
app.get('/privacy', (req, res) => {
res.sendFile(join(__dirname, 'public', 'privacy.html'));
});
app.get('/terms', (req, res) => {
res.sendFile(join(__dirname, 'public', 'terms.html'));
});
app.get('/super-admin', (req, res) => {
res.sendFile(join(__dirname, 'public', 'super-admin.html'));
});
app.get('/setup-guide', (req, res) => {
res.sendFile(join(__dirname, 'public', 'setup-guide.html'));
});
app.get('/test-qr-codes', (req, res) => {
res.sendFile(join(__dirname, 'public', 'test-qr-codes.html'));
});
// Static files (CSS, JS, fonts, images — but NOT index.html as the default for /)
app.use(express.static(join(__dirname, 'public')));
// ── Version endpoint ──
app.get('/api/version', (req, res) => {
res.json({ version: APP_VERSION, name: 'Kill the Clipboard' });
});
// ══════════════════════════════════════════════════════════════════
// LEGACY ROUTES — single-tenant, env-var config (unchanged)
// ══════════════════════════════════════════════════════════════════
// API: process a scanned QR code string (legacy)
app.post('/api/scan', async (req, res) => {
const { qrText, passcode } = req.body;
if (!qrText) {
return res.status(400).json({ error: 'No QR text provided' });
}
let shlPayload;
try {
shlPayload = parseShlUri(qrText);
} catch (err) {
return res.status(400).json({ error: err.message });
}
if (!shlPayload) {
return res.json({ status: 'not_shl', message: 'QR code does not contain a SMART Health Link.' });
}
if (shlPayload.flag.includes('P') && !passcode && !config.passcode) {
return res.json({
status: 'need_passcode',
label: shlPayload.label,
message: 'This link requires a passcode.',
});
}
try {
const manifest = await fetchManifest(shlPayload, {
recipient: config.recipient,
passcode: passcode || config.passcode,
});
const results = await extractHealthData(manifest, shlPayload.key, {
maxDecompressedSize: config.processing?.maxDecompressedSize,
verbose: false,
});
// Validate FHIR data
if (results.fhirBundles.length > 0) {
const validation = validateFhirBundles(results.fhirBundles);
if (!validation.valid) {
return res.json({
status: 'validation_failed',
error: `Invalid FHIR data: ${validation.errors.join('; ')}`,
label: shlPayload.label,
});
}
}
let savedTo = null;
if (['file', 'both', 'all'].includes(config.output.mode)) {
await writeToFiles(results, config.output.directory, { verbose: false });
savedTo = config.output.directory;
}
if (['api', 'both', 'all'].includes(config.output.mode)) {
if (config.output.api.url || config.output.api.fhirServerBase) {
await postToApi(results, config.output.api, { verbose: false });
}
}
let driveLink = null;
let driveError = null;
if (['drive', 'all'].includes(config.output.mode)) {
if (config.output.drive.folderId) {
try {
const driveSummary = await uploadToDrive(results, config.output.drive, { verbose: false });
driveLink = driveSummary.driveFolder;
} catch (err) {
driveError = err.message;
console.error(`Drive upload failed: ${err.message}`);
}
}
}
const response = {
status: 'success',
label: shlPayload.label,
savedTo,
driveLink,
driveError,
summary: {
fhirBundles: results.fhirBundles.length,
pdfs: results.pdfs.length,
rawEntries: results.raw.length,
},
fhirBundles: results.fhirBundles,
pdfs: results.pdfs.map((p) => ({
filename: p.filename,
hasData: !!p.data,
dataBase64: p.data ? p.data.toString('base64') : null,
url: p.url || null,
})),
};
res.json(response);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// API: get current config (legacy, non-sensitive)
app.get('/api/config', (req, res) => {
res.json({
outputMode: config.output.mode,
outputDirectory: config.output.directory,
hasApiUrl: !!config.output.api.url,
hasFhirServer: !!config.output.api.fhirServerBase,
hasDriveConfig: !!config.output.drive.folderId,
recipient: config.recipient,
orgName: config.organization?.name || null,
orgId: config.organization?.id || null,
});
});
// Legacy OAuth2: Start Google Drive authorization
app.get('/auth/google', (req, res) => {
const oauth2 = getOAuth2Client(config);
if (!oauth2) {
return res.status(500).send('Google OAuth2 not configured. Set GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET.');
}
const authUrl = oauth2.generateAuthUrl({
access_type: 'offline',
prompt: 'consent',
scope: ['https://www.googleapis.com/auth/drive.file'],
});
res.redirect(authUrl);
});
// OAuth2: Callback after Google authorization (handles both legacy and per-org)
app.get('/auth/google/callback', async (req, res) => {
const { code, state } = req.query;
if (!code) {
return res.status(400).send('No authorization code received.');
}
const oauth2 = getOAuth2Client(config);
if (!oauth2) {
return res.status(500).send('Google OAuth2 not configured.');
}
// Parse state to check if this is a per-org OAuth flow
// State is HMAC-signed to prevent CSRF — attacker can't forge valid state.
let orgSlug = null;
let orgId = null;
if (state) {
const verified = verifyOAuthState(state);
if (verified) { orgSlug = verified.slug; orgId = verified.orgId; }
}
try {
const { tokens } = await oauth2.getToken(code);
const refreshToken = tokens.refresh_token;
if (!refreshToken) {
const backUrl = orgSlug ? `/${escapeHtml(orgSlug)}/admin` : '/';
return res.send(`
<html><body style="font-family: Inter, sans-serif; max-width: 600px; margin: 40px auto; padding: 20px;">
<h2 style="color: #e31c3d;">No Refresh Token Received</h2>
<p>Google did not return a refresh token. This usually means you've already authorized this app before.</p>
<p>To fix this: go to <a href="https://myaccount.google.com/permissions">Google Account Permissions</a>,
remove "Kill the Clipboard", then try connecting again.</p>
<a href="${backUrl}">Go back</a>
</body></html>
`);
}
// Per-org flow: save refresh token to database (encrypted at rest)
if (orgSlug && orgId) {
updateOrgSettings(orgId, { drive_refresh_token: prepareTokenForStorage(refreshToken, orgId), storage_type: 'drive' });
return res.send(`
<html><body style="font-family: Inter, sans-serif; max-width: 600px; margin: 40px auto; padding: 20px;">
<h2 style="color: #2e8540;">Google Drive Connected!</h2>
<p>Your organization's Google Drive has been connected successfully.</p>
<p>You can now configure the Drive folder in your admin settings.</p>
<a href="/${escapeHtml(orgSlug)}/admin" style="display:inline-block;margin-top:12px;padding:10px 20px;background:#0071bc;color:#fff;border-radius:4px;text-decoration:none;font-weight:600;">Back to Admin Settings</a>
</body></html>
`);
}
// Legacy flow: show flyctl command (token escaped to prevent HTML breakout)
res.send(`
<html><body style="font-family: Inter, sans-serif; max-width: 600px; margin: 40px auto; padding: 20px;">
<h2 style="color: #2e8540;">Google Drive Connected!</h2>
<p>Your refresh token has been generated. Run this command to save it to your deployment:</p>
<pre style="background: #f1f1f1; padding: 16px; border-radius: 4px; overflow-x: auto; font-size: 0.85rem;">flyctl secrets set GOOGLE_REFRESH_TOKEN="${escapeHtml(refreshToken)}"</pre>
<p style="margin-top: 16px;">After running that command, the app will automatically upload scanned data to your Google Drive folder.</p>
<a href="/">Back to scanner</a>
</body></html>
`);
} catch (err) {
const backUrl = orgSlug ? `/${escapeHtml(orgSlug)}/admin` : '/';
res.status(500).send(`
<html><body style="font-family: Inter, sans-serif; max-width: 600px; margin: 40px auto; padding: 20px;">
<h2 style="color: #e31c3d;">Authorization Failed</h2>
<p>${escapeHtml(err.message)}</p>
<a href="${backUrl}">Go back</a>
</body></html>
`);
}
});
// Legacy: Check Google Drive connection status
app.get('/api/drive-status', (req, res) => {
const hasOAuth = !!(config.output.drive.clientId && config.output.drive.clientSecret);
const hasRefreshToken = !!config.output.drive.refreshToken;
const hasServiceAccount = !!config.output.drive.serviceAccountKey;
const hasFolderId = !!config.output.drive.folderId;
res.json({
configured: (hasRefreshToken || hasServiceAccount) && hasFolderId,
needsAuth: hasOAuth && !hasRefreshToken && !hasServiceAccount,
hasFolderId,
authMethod: hasRefreshToken ? 'oauth2' : hasServiceAccount ? 'service_account' : 'none',
});
});
// ── App Validation Endpoints ──
// Get approved apps list (public)
app.get('/api/approved-apps', (req, res) => {
res.json(APPROVED_APPS);
});
// Verify an app by appId (public)
app.get('/api/verify-app', (req, res) => {
const { appId } = req.query;
if (!appId) return res.status(400).json({ error: 'appId is required' });
const app = APPROVED_APPS.find(a => a.appId === appId.toLowerCase());
if (app) {
res.json({ approved: true, app });
} else {
res.json({ approved: false });
}
});
// ══════════════════════════════════════════════════════════════════
// MULTI-TENANT ROUTES — per-org database-backed
// ══════════════════════════════════════════════════════════════════
// Register a new organization
app.post('/api/orgs', registrationLimiter, async (req, res) => {
const { slug, name, adminPassword, staffPassword } = req.body;
if (!slug || !name || !adminPassword || !staffPassword) {
return res.status(400).json({ error: 'All fields are required.' });
}
if (!/^[a-z][a-z0-9-]{2,49}$/.test(slug)) {
return res.status(400).json({ error: 'Slug must be 3-50 characters, lowercase letters/numbers/hyphens, starting with a letter.' });
}
if (RESERVED_SLUGS.includes(slug)) {
return res.status(400).json({ error: 'That URL is reserved.' });
}
if (slugExists(slug)) {
return res.status(409).json({ error: 'That URL is already taken.' });
}
if (adminPassword.length < 8) {
return res.status(400).json({ error: 'Admin password must be at least 8 characters.' });
}
if (staffPassword.length < 4) {
return res.status(400).json({ error: 'Staff password must be at least 4 characters.' });
}
try {
const adminHash = await hashPassword(adminPassword);
const staffHash = await hashPassword(staffPassword);
const org = createOrg({
id: randomUUID(),
slug,
name,
adminPasswordHash: adminHash,
staffPasswordHash: staffHash,
});
const token = createToken({ slug: org.slug, role: 'admin', orgId: org.id });
res.status(201).json({ slug: org.slug, token });
} catch (err) {
console.error('Org creation failed:', err.message);
res.status(500).json({ error: 'Failed to create organization.' });
}
});
// Check slug availability
app.get('/api/orgs/check-slug', (req, res) => {
const { slug } = req.query;
if (!slug) return res.json({ available: false });
if (RESERVED_SLUGS.includes(slug)) return res.json({ available: false });
if (!/^[a-z][a-z0-9-]{2,49}$/.test(slug)) return res.json({ available: false });
res.json({ available: !slugExists(slug) });
});
// Authenticate as admin or staff
app.post('/api/orgs/:slug/auth', authLimiter, async (req, res) => {
const { password, role } = req.body;
const org = getOrgBySlug(req.params.slug);
if (!org) return res.status(404).json({ error: 'Organization not found.' });
if (!password) return res.status(400).json({ error: 'Password required.' });
if (!['admin', 'staff'].includes(role)) {
return res.status(400).json({ error: 'Role must be admin or staff.' });
}
const hash = role === 'admin' ? org.admin_password_hash : org.staff_password_hash;
const valid = await verifyPassword(password, hash);
if (!valid) return res.status(401).json({ error: 'Invalid password.' });
const timeoutMinutes = org.session_timeout_minutes || 720;
const token = createToken({ slug: org.slug, role, orgId: org.id, timeoutMinutes });
res.json({ token, role, slug: org.slug, orgName: org.name });
});
// Public org config (no auth needed)
app.get('/api/orgs/:slug/config', (req, res) => {
const org = getOrgBySlug(req.params.slug);
if (!org) return res.status(404).json({ error: 'Organization not found.' });
res.json({
name: org.name,
slug: org.slug,
storageType: org.storage_type,
saveFormat: org.save_format || 'both',
hasDrive: !!org.drive_refresh_token,
hasOnedrive: !!org.onedrive_refresh_token,
hasBox: !!org.box_refresh_token,
hasApi: !!org.api_url,
hasEmail: !!org.email_to,
hasGmail: !!org.gmail_refresh_token,
hasOutlook: !!org.outlook_refresh_token,
requireAppValidation: !!org.require_app_validation,
sessionTimeoutMinutes: org.session_timeout_minutes || 720,
});
});
// Get full settings (admin only)
app.get('/api/orgs/:slug/settings', authMiddleware('admin'), (req, res) => {
const org = getOrgBySlug(req.params.slug);
if (!org) return res.status(404).json({ error: 'Organization not found.' });
res.json({
name: org.name,
slug: org.slug,
storageType: org.storage_type,
saveFormat: org.save_format || 'both',
driveFolderId: org.drive_folder_id || null,
hasDriveToken: !!org.drive_refresh_token,
hasOnedriveToken: !!org.onedrive_refresh_token,
onedriveFolderPath: org.onedrive_folder_path || null,
hasBoxToken: !!org.box_refresh_token,
boxFolderId: org.box_folder_id || null,
apiUrl: org.api_url || null,
apiHeaders: org.api_headers ? JSON.parse(org.api_headers) : {},
emailTo: org.email_to || null,
hasGmailToken: !!org.gmail_refresh_token,
gmailEmail: org.gmail_email || null,
hasOutlookToken: !!org.outlook_refresh_token,
outlookEmail: org.outlook_email || null,
requireAppValidation: !!org.require_app_validation,
sessionTimeoutMinutes: org.session_timeout_minutes || 720,
});
});
// Update settings (admin only)
app.put('/api/orgs/:slug/settings', authMiddleware('admin'), (req, res) => {
const org = getOrgBySlug(req.params.slug);
if (!org) return res.status(404).json({ error: 'Organization not found.' });
const { storageType, saveFormat, driveFolderId, apiUrl, apiHeaders, emailTo, onedriveFolderPath, boxFolderId, requireAppValidation, sessionTimeoutMinutes } = req.body;
const updates = {};
if (storageType && ['download', 'drive', 'onedrive', 'box', 'api', 'email', 'gmail', 'outlook'].includes(storageType)) {
updates.storage_type = storageType;
}
if (saveFormat && ['pdf', 'fhir', 'both'].includes(saveFormat)) {
updates.save_format = saveFormat;
}
if (driveFolderId !== undefined) updates.drive_folder_id = driveFolderId;
if (onedriveFolderPath !== undefined) updates.onedrive_folder_path = onedriveFolderPath;
if (boxFolderId !== undefined) updates.box_folder_id = boxFolderId;
if (apiUrl !== undefined) updates.api_url = apiUrl;
if (apiHeaders !== undefined) updates.api_headers = JSON.stringify(apiHeaders);
if (emailTo !== undefined) updates.email_to = emailTo;
if (requireAppValidation !== undefined) updates.require_app_validation = requireAppValidation ? 1 : 0;
if (sessionTimeoutMinutes !== undefined) {
const validTimeouts = [60, 240, 480, 720, 1440];
const val = parseInt(sessionTimeoutMinutes);
if (validTimeouts.includes(val)) updates.session_timeout_minutes = val;
}
updateOrgSettings(org.id, updates);
res.json({ ok: true });
});
// Change passwords (admin only)
app.put('/api/orgs/:slug/passwords', authMiddleware('admin'), async (req, res) => {
const { currentAdminPassword, newAdminPassword, newStaffPassword } = req.body;
const org = getOrgBySlug(req.params.slug);
if (!org) return res.status(404).json({ error: 'Organization not found.' });
const valid = await verifyPassword(currentAdminPassword, org.admin_password_hash);
if (!valid) return res.status(401).json({ error: 'Current admin password is incorrect.' });
const updates = {};
if (newAdminPassword) {
if (newAdminPassword.length < 8) return res.status(400).json({ error: 'Admin password must be at least 8 characters.' });
updates.admin_password_hash = await hashPassword(newAdminPassword);
}
if (newStaffPassword) {
if (newStaffPassword.length < 4) return res.status(400).json({ error: 'Staff password must be at least 4 characters.' });
updates.staff_password_hash = await hashPassword(newStaffPassword);
}
if (Object.keys(updates).length === 0) {
return res.status(400).json({ error: 'No new passwords provided.' });
}
updateOrgSettings(org.id, updates);
res.json({ ok: true });
});
// Test storage connectivity (admin only)
app.post('/api/orgs/:slug/test-connection', authMiddleware('admin'), async (req, res) => {
const org = getOrgBySlug(req.params.slug);
if (!org) return res.status(404).json({ error: 'Organization not found.' });
const { storageType } = req.body;
try {
if (storageType === 'drive' || storageType === 'google_drive') {
if (!org.drive_refresh_token) {
return res.json({ ok: false, error: 'Google Drive not connected. Please connect your Drive account first.' });
}
// Test Drive access by listing files in the folder
const { google } = await import('googleapis');
const oauth2 = new google.auth.OAuth2(
config.output.drive.clientId,
config.output.drive.clientSecret
);
oauth2.setCredentials({ refresh_token: getDecryptedToken(org, 'drive_refresh_token') });
const drive = google.drive({ version: 'v3', auth: oauth2 });
const folderId = parseFolderId(org.drive_folder_id);
if (!folderId) {
return res.json({ ok: false, error: 'No Drive folder configured. Enter a folder URL.' });
}
// Try to list folder contents as a permissions check
await drive.files.list({
q: `'${folderId}' in parents`,
pageSize: 1,
fields: 'files(id)',
});
return res.json({ ok: true, message: 'Google Drive connected and folder accessible.' });
}
if (storageType === 'api') {
const apiUrl = org.api_url;
if (!apiUrl) return res.json({ ok: false, error: 'No API URL configured.' });
const headers = org.api_headers ? JSON.parse(org.api_headers) : {};
const testResp = await fetch(apiUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...headers },
body: JSON.stringify({ test: true, source: 'kill-the-clipboard', timestamp: new Date().toISOString() }),
signal: AbortSignal.timeout(10000),
});
if (testResp.ok) {
return res.json({ ok: true, message: `API endpoint responded (${testResp.status}).` });
} else {
return res.json({ ok: false, error: `API endpoint returned ${testResp.status}.` });
}
}
if (storageType === 'email') {
if (!org.email_to) return res.json({ ok: false, error: 'No email recipient configured.' });
if (!process.env.SMTP_HOST) return res.json({ ok: false, error: 'SMTP not configured by system administrator.' });
// Test SMTP connection
const nodemailer = await import('nodemailer');
const transporter = nodemailer.default.createTransport({
host: process.env.SMTP_HOST,
port: parseInt(process.env.SMTP_PORT, 10) || 587,
secure: parseInt(process.env.SMTP_PORT, 10) === 465,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS,
},
});
await transporter.verify();
return res.json({ ok: true, message: 'SMTP connection verified.' });
}
if (storageType === 'gmail') {
if (!org.gmail_refresh_token) {
return res.json({ ok: false, error: 'Gmail not connected. Please connect your Gmail account first.' });
}
if (!org.email_to) {
return res.json({ ok: false, error: 'No email recipient configured.' });
}
try {
const testResp = await fetch('https://oauth2.googleapis.com/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
client_id: process.env.GOOGLE_CLIENT_ID,
client_secret: process.env.GOOGLE_CLIENT_SECRET,
refresh_token: getDecryptedToken(org, 'gmail_refresh_token'),
grant_type: 'refresh_token',
}).toString(),
});
if (testResp.ok) {
return res.json({ ok: true, message: 'Gmail connected and authorized.' });
} else {
return res.json({ ok: false, error: 'Gmail token may be expired. Try reconnecting.' });
}
} catch (err) {
return res.json({ ok: false, error: err.message });
}
}
if (storageType === 'outlook') {
if (!org.outlook_refresh_token) {
return res.json({ ok: false, error: 'Outlook not connected. Please connect your Microsoft account first.' });
}
if (!org.email_to) {
return res.json({ ok: false, error: 'No email recipient configured.' });
}
try {
const testResp = await fetch('https://login.microsoftonline.com/common/oauth2/v2.0/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
client_id: process.env.ONEDRIVE_CLIENT_ID,
client_secret: process.env.ONEDRIVE_CLIENT_SECRET,
refresh_token: getDecryptedToken(org, 'outlook_refresh_token'),
grant_type: 'refresh_token',
scope: 'Mail.Send offline_access',
}).toString(),
});
if (testResp.ok) {
return res.json({ ok: true, message: 'Outlook email connected and authorized.' });
} else {
return res.json({ ok: false, error: 'Outlook token may be expired. Try reconnecting.' });
}
} catch (err) {
return res.json({ ok: false, error: err.message });
}
}
if (storageType === 'onedrive') {
if (!org.onedrive_refresh_token) {
return res.json({ ok: false, error: 'OneDrive not connected. Please connect your OneDrive account first.' });
}
// Test by getting user's drive info
try {
const { uploadToOnedrive: _unused, ...mod } = await import('./src/output/onedrive-uploader.js');
// Simple test: try to get access token (which verifies the refresh token)
const testResp = await fetch('https://login.microsoftonline.com/common/oauth2/v2.0/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
client_id: process.env.ONEDRIVE_CLIENT_ID,
client_secret: process.env.ONEDRIVE_CLIENT_SECRET,
refresh_token: getDecryptedToken(org, 'onedrive_refresh_token'),
grant_type: 'refresh_token',
scope: 'Files.ReadWrite.All offline_access',
}).toString(),
});
if (testResp.ok) {
return res.json({ ok: true, message: 'OneDrive connected and accessible.' });
} else {
return res.json({ ok: false, error: 'OneDrive token may be expired. Try reconnecting.' });
}
} catch (err) {
return res.json({ ok: false, error: err.message });
}
}
if (storageType === 'box') {
if (!org.box_refresh_token) {
return res.json({ ok: false, error: 'Box not connected. Please connect your Box account first.' });
}
if (!org.box_folder_id) {
return res.json({ ok: false, error: 'No Box folder ID configured.' });
}
// Test by refreshing token and verifying folder access
try {
const testResp = await fetch('https://api.box.com/oauth2/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
client_id: process.env.BOX_CLIENT_ID,
client_secret: process.env.BOX_CLIENT_SECRET,
refresh_token: getDecryptedToken(org, 'box_refresh_token'),
grant_type: 'refresh_token',
}).toString(),
});
if (!testResp.ok) {
return res.json({ ok: false, error: 'Box token may be expired. Try reconnecting.' });
}
const tokens = await testResp.json();
// Save new refresh token (Box rotates them on every use — encrypt before storing)
if (tokens.refresh_token) {
updateOrgSettings(org.id, { box_refresh_token: prepareTokenForStorage(tokens.refresh_token, org.id) });
}
// Verify folder access
const folderResp = await fetch(`https://api.box.com/2.0/folders/${org.box_folder_id}`, {
headers: { Authorization: `Bearer ${tokens.access_token}` },
});
if (folderResp.ok) {
return res.json({ ok: true, message: 'Box connected and folder accessible.' });
} else {
return res.json({ ok: false, error: `Box folder "${org.box_folder_id}" not found. Use "0" for root folder, or enter a valid folder ID from your Box URL.` });
}
} catch (err) {
return res.json({ ok: false, error: err.message });
}
}
if (storageType === 'download') {
return res.json({ ok: true, message: 'Direct download requires no server connectivity.' });
}
return res.json({ ok: false, error: 'Unknown storage type.' });
} catch (err) {
return res.json({ ok: false, error: err.message });
}
});
// Per-org Drive OAuth connect (admin must be logged in via UI)
app.get('/api/orgs/:slug/drive-connect', (req, res) => {
const org = getOrgBySlug(req.params.slug);
if (!org) return res.status(404).send('Organization not found.');
const oauth2 = getOAuth2Client(config);
if (!oauth2) return res.status(500).send('Google OAuth2 not configured. Contact the system administrator.');
const authUrl = oauth2.generateAuthUrl({
access_type: 'offline',
prompt: 'consent',
scope: ['https://www.googleapis.com/auth/drive.file'],
state: createSignedOAuthState(org.slug, org.id),
});
res.redirect(authUrl);
});
// Per-org OneDrive OAuth connect
app.get('/api/orgs/:slug/onedrive-connect', (req, res) => {
const org = getOrgBySlug(req.params.slug);
if (!org) return res.status(404).send('Organization not found.');
const publicUrl = config.server.publicUrl || `http://localhost:${PORT}`;
const redirectUri = `${publicUrl}/auth/onedrive/callback`;
const state = createSignedOAuthState(org.slug, org.id);
const authUrl = getOnedriveAuthUrl(redirectUri, state);
if (!authUrl) return res.status(500).send('OneDrive not configured. Set ONEDRIVE_CLIENT_ID env var.');
res.redirect(authUrl);
});
// OneDrive OAuth callback
app.get('/auth/onedrive/callback', async (req, res) => {
const { code, state } = req.query;
if (!code) return res.status(400).send('No authorization code received.');
let orgSlug = null, orgId = null;
if (state) {
const verified = verifyOAuthState(state);
if (verified) { orgSlug = verified.slug; orgId = verified.orgId; }
}
try {
const publicUrl = config.server.publicUrl || `http://localhost:${PORT}`;
const redirectUri = `${publicUrl}/auth/onedrive/callback`;
const tokens = await exchangeOnedriveCode(code, redirectUri);
if (orgId && tokens.refresh_token) {
updateOrgSettings(orgId, { onedrive_refresh_token: prepareTokenForStorage(tokens.refresh_token, orgId), storage_type: 'onedrive' });
}
const backUrl = orgSlug ? `/${orgSlug}/admin` : '/';
res.send(`
<html><body style="font-family: Inter, sans-serif; max-width: 600px; margin: 40px auto; padding: 20px;">
<h2 style="color: #2e8540;">OneDrive Connected!</h2>
<p>Your organization's OneDrive has been connected successfully.</p>
<a href="${backUrl}" style="display:inline-block;margin-top:12px;padding:10px 20px;background:#0071bc;color:#fff;border-radius:4px;text-decoration:none;font-weight:600;">Back to Admin Settings</a>
</body></html>
`);
} catch (err) {
const backUrl = orgSlug ? `/${escapeHtml(orgSlug)}/admin` : '/';
res.status(500).send(`
<html><body style="font-family: Inter, sans-serif; max-width: 600px; margin: 40px auto; padding: 20px;">
<h2 style="color: #e31c3d;">OneDrive Authorization Failed</h2>
<p>${escapeHtml(err.message)}</p>
<a href="${backUrl}">Go back</a>
</body></html>
`);
}
});
// Per-org Box OAuth connect
app.get('/api/orgs/:slug/box-connect', (req, res) => {
const org = getOrgBySlug(req.params.slug);
if (!org) return res.status(404).send('Organization not found.');
const publicUrl = config.server.publicUrl || `http://localhost:${PORT}`;
const redirectUri = `${publicUrl}/auth/box/callback`;
const state = createSignedOAuthState(org.slug, org.id);
const authUrl = getBoxAuthUrl(redirectUri, state);
if (!authUrl) return res.status(500).send('Box not configured. Set BOX_CLIENT_ID env var.');
res.redirect(authUrl);
});