gathergate 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +212 -2
  3. package/client/dist/assets/geist-mono-cyrillic-400-normal-C51Di1Mf.woff2 +0 -0
  4. package/client/dist/assets/geist-mono-cyrillic-400-normal-CPJFfJgk.woff +0 -0
  5. package/client/dist/assets/geist-mono-cyrillic-500-normal-D2cXvDHF.woff2 +0 -0
  6. package/client/dist/assets/geist-mono-cyrillic-500-normal-DfuvdVgn.woff +0 -0
  7. package/client/dist/assets/geist-mono-cyrillic-600-normal-Dfv53e6N.woff2 +0 -0
  8. package/client/dist/assets/geist-mono-cyrillic-600-normal-DzvMIgFZ.woff +0 -0
  9. package/client/dist/assets/geist-mono-latin-400-normal-B2yvC1Cq.woff +0 -0
  10. package/client/dist/assets/geist-mono-latin-400-normal-DTRLJnHl.woff2 +0 -0
  11. package/client/dist/assets/geist-mono-latin-500-normal-D-GG86Jb.woff +0 -0
  12. package/client/dist/assets/geist-mono-latin-500-normal-YINYabwD.woff2 +0 -0
  13. package/client/dist/assets/geist-mono-latin-600-normal-V-KvD_pi.woff2 +0 -0
  14. package/client/dist/assets/geist-mono-latin-600-normal-bZn07FKM.woff +0 -0
  15. package/client/dist/assets/geist-mono-latin-ext-400-normal-CfzLURNc.woff +0 -0
  16. package/client/dist/assets/geist-mono-latin-ext-400-normal-DI-rJ0UV.woff2 +0 -0
  17. package/client/dist/assets/geist-mono-latin-ext-500-normal-Buglb9-a.woff2 +0 -0
  18. package/client/dist/assets/geist-mono-latin-ext-500-normal-CrWEgvU_.woff +0 -0
  19. package/client/dist/assets/geist-mono-latin-ext-600-normal-B7ybHiTt.woff +0 -0
  20. package/client/dist/assets/geist-mono-latin-ext-600-normal-TphwrhF8.woff2 +0 -0
  21. package/client/dist/assets/geist-mono-symbols2-400-normal-DjbiTEEA.woff +0 -0
  22. package/client/dist/assets/geist-mono-symbols2-500-normal-CmnCPGa0.woff +0 -0
  23. package/client/dist/assets/geist-mono-symbols2-600-normal-D7I4D0GJ.woff +0 -0
  24. package/client/dist/assets/geist-mono-vietnamese-400-normal-CZEPLOgu.woff +0 -0
  25. package/client/dist/assets/geist-mono-vietnamese-500-normal-Dx9-epDo.woff +0 -0
  26. package/client/dist/assets/geist-mono-vietnamese-600-normal-BLL01lwa.woff +0 -0
  27. package/client/dist/assets/index-BWbZAfMJ.js +80 -0
  28. package/client/dist/assets/index-ZnG2njjK.css +2 -0
  29. package/client/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  30. package/client/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  31. package/client/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  32. package/client/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  33. package/client/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  34. package/client/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  35. package/client/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  36. package/client/dist/favicon.svg +12 -0
  37. package/client/dist/index.html +16 -0
  38. package/client/dist/site.webmanifest +16 -0
  39. package/dist/adapters/email.js +125 -0
  40. package/dist/adapters/storage.js +106 -0
  41. package/dist/app.js +2126 -0
  42. package/dist/config.js +106 -0
  43. package/dist/db/client.js +294 -0
  44. package/dist/db/queries.js +898 -0
  45. package/dist/emails/templates.js +221 -0
  46. package/dist/index.js +77 -0
  47. package/dist/jobs/chaser.js +81 -0
  48. package/dist/jobs/demo.js +329 -0
  49. package/dist/jobs/purge.js +22 -0
  50. package/dist/jobs/webhook.js +153 -0
  51. package/dist/security/auth.js +69 -0
  52. package/dist/security/crypto.js +91 -0
  53. package/dist/security/magic-bytes.js +131 -0
  54. package/dist/security/rate-limit.js +72 -0
  55. package/dist/security/ssrf.js +181 -0
  56. package/dist/templates/presets.js +341 -0
  57. package/dist/validators/index.js +52 -0
  58. package/dist/validators/packs/au.js +108 -0
  59. package/dist/validators/packs/eu.js +85 -0
  60. package/dist/validators/packs/generic.js +57 -0
  61. package/dist/validators/packs/types.js +1 -0
  62. package/dist/validators/packs/uk.js +58 -0
  63. package/dist/validators/packs/us.js +82 -0
  64. package/package.json +55 -4
@@ -0,0 +1,329 @@
1
+ import { addDaysIso, slugify } from "../db/queries.js";
2
+ import { emailBrand, inviteEmail, reminderEmail, revisionEmail } from "../emails/templates.js";
3
+ import { encryptBuffer, encryptField } from "../security/crypto.js";
4
+ function escapePdfText(input) {
5
+ return input
6
+ .replace(/[^\x20-\x7e]/g, " ")
7
+ .replace(/\\/g, "\\\\")
8
+ .replace(/\(/g, "\\(")
9
+ .replace(/\)/g, "\\)");
10
+ }
11
+ export function createSamplePdf(title, lines) {
12
+ const ops = [
13
+ "BT",
14
+ "/F1 16 Tf",
15
+ "54 736 Td",
16
+ `(${escapePdfText(title)}) Tj`,
17
+ "/F1 10 Tf",
18
+ "0 -22 Td",
19
+ "(GatherGate Sample Encrypted Document Fixture - Non-Production) Tj",
20
+ "0 -24 Td",
21
+ "/F1 11 Tf",
22
+ ];
23
+ for (const line of lines) {
24
+ ops.push(`(${escapePdfText(line)}) Tj`);
25
+ ops.push("0 -18 Td");
26
+ }
27
+ ops.push("ET");
28
+ const streamBody = ops.join("\n");
29
+ const objects = [
30
+ "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n",
31
+ "2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n",
32
+ "3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>\nendobj\n",
33
+ "4 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\n",
34
+ `5 0 obj\n<< /Length ${Buffer.byteLength(streamBody, "utf8")} >>\nstream\n${streamBody}\nendstream\nendobj\n`,
35
+ ];
36
+ const chunks = ["%PDF-1.4\n"];
37
+ const offsets = [0];
38
+ let byteOffset = Buffer.byteLength(chunks[0], "utf8");
39
+ for (const obj of objects) {
40
+ offsets.push(byteOffset);
41
+ chunks.push(obj);
42
+ byteOffset += Buffer.byteLength(obj, "utf8");
43
+ }
44
+ const xrefStart = byteOffset;
45
+ chunks.push(`xref\n0 ${objects.length + 1}\n`);
46
+ chunks.push("0000000000 65535 f \n");
47
+ for (let i = 1; i <= objects.length; i++) {
48
+ chunks.push(`${String(offsets[i]).padStart(10, "0")} 00000 n \n`);
49
+ }
50
+ chunks.push(`trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xrefStart}\n%%EOF\n`);
51
+ return Buffer.from(chunks.join(""), "utf8");
52
+ }
53
+ async function storeDemoUpload(params) {
54
+ const buf = createSamplePdf(params.pdfTitle, params.pdfLines);
55
+ const seq = params.store.countUploadsForItem(params.itemId) + 1;
56
+ const canonicalName = `${slugify(params.clientName, "client")}_${slugify(params.itemSlug, "doc")}_${String(seq).padStart(2, "0")}.pdf`;
57
+ const storageKey = `${params.workspaceId}/${params.requestId}/${params.itemId}/${Date.now()}_${canonicalName}.enc`;
58
+ const { ciphertext, meta } = encryptBuffer(params.masterKey, buf, storageKey);
59
+ await params.storage.put(storageKey, ciphertext);
60
+ params.store.addUpload({
61
+ itemId: params.itemId,
62
+ requestId: params.requestId,
63
+ originalName: params.originalName,
64
+ canonicalName,
65
+ detectedMime: "application/pdf",
66
+ sizeBytes: meta.sizeBytes,
67
+ storageKey,
68
+ encVersion: meta.version,
69
+ ivHex: meta.ivHex,
70
+ tagHex: meta.tagHex,
71
+ saltHex: meta.saltHex,
72
+ sha256Hex: meta.sha256Hex,
73
+ });
74
+ }
75
+ export async function seedDemoWorkspace(params) {
76
+ const { store, storage, workspaceId, masterKey, baseUrl } = params;
77
+ if (store.hasDemoData(workspaceId)) {
78
+ return { seeded: false };
79
+ }
80
+ const workspace = store.getWorkspaceById(workspaceId);
81
+ if (!workspace)
82
+ return { seeded: false };
83
+ const templates = store.listTemplates(workspaceId);
84
+ const eofyTpl = templates.find((t) => t.name.includes("AU Individual Tax Return")) ?? templates[0];
85
+ const basTpl = templates.find((t) => t.name.includes("AU Company / BAS")) ?? templates[0];
86
+ const healthTpl = templates.find((t) => t.name.includes("AU Allied Health")) ?? templates[0];
87
+ const now = new Date();
88
+ // 1. Claire Nguyen - Partial + 1 rejected blurry scan + OTP enabled
89
+ const eofyItems = JSON.parse(eofyTpl.items_json);
90
+ const r1 = store.createRequest({
91
+ workspaceId,
92
+ templateId: eofyTpl.id,
93
+ title: "FY26 Individual Tax Return Pack",
94
+ clientSubject: "Documents for your FY26 tax return",
95
+ welcomeNote: "Please upload your receipts and confirm your bank BSB before Friday.",
96
+ clientName: "Claire Nguyen",
97
+ clientEmail: "claire.nguyen@example.com.au",
98
+ items: eofyItems,
99
+ requireOtp: true,
100
+ reminderIntervalDays: 3,
101
+ maxReminders: 4,
102
+ purgeAfterDays: 14,
103
+ masterKey,
104
+ dueAt: addDaysIso(now.toISOString(), 5),
105
+ lastOpenedAt: new Date(now.getTime() - 2 * 3600_000).toISOString(),
106
+ isDemo: true,
107
+ });
108
+ const r1Items = store.listRequestItems(r1.request.id);
109
+ const r1Tfn = r1Items.find((i) => i.validator === "au_tfn_mod11");
110
+ const r1Bsb = r1Items.find((i) => i.validator === "au_bsb");
111
+ const r1Phone = r1Items.find((i) => i.validator === "au_phone_e164");
112
+ const r1Health = r1Items.find((i) => i.label.includes("Private Health"));
113
+ const r1Receipts = r1Items.find((i) => i.label.includes("Work-Related Expense"));
114
+ const r1Decl = r1Items.find((i) => i.kind === "checkbox");
115
+ if (r1Tfn) {
116
+ store.saveTextOrCheckboxSubmission(r1Tfn.id, r1.request.id, encryptField(masterKey, "876 543 210", r1Tfn.id));
117
+ store.reviewItem({ workspaceId, requestId: r1.request.id, itemId: r1Tfn.id, decision: "approved" });
118
+ }
119
+ if (r1Bsb) {
120
+ store.saveTextOrCheckboxSubmission(r1Bsb.id, r1.request.id, encryptField(masterKey, "062-000", r1Bsb.id));
121
+ store.reviewItem({ workspaceId, requestId: r1.request.id, itemId: r1Bsb.id, decision: "approved" });
122
+ }
123
+ if (r1Phone) {
124
+ store.saveTextOrCheckboxSubmission(r1Phone.id, r1.request.id, encryptField(masterKey, "+61412345678", r1Phone.id));
125
+ }
126
+ if (r1Receipts) {
127
+ await storeDemoUpload({
128
+ store,
129
+ storage,
130
+ masterKey,
131
+ workspaceId,
132
+ requestId: r1.request.id,
133
+ itemId: r1Receipts.id,
134
+ clientName: "Claire Nguyen",
135
+ itemSlug: "deduction-receipts",
136
+ originalName: "FY26-Work-Deductions-Summary.pdf",
137
+ pdfTitle: "Claire Nguyen - FY26 Work Deductions",
138
+ pdfLines: [
139
+ "Taxpayer: Claire Nguyen",
140
+ "Period: 01 Jul 2025 - 30 Jun 2026",
141
+ "Home Office Hours Log: 1,140 hrs (fixed rate)",
142
+ "Professional Membership (CPA): $790.00 AUD",
143
+ "Equipment & Laptop Depreciation: $1,420.00 AUD",
144
+ ],
145
+ });
146
+ }
147
+ if (r1Health) {
148
+ await storeDemoUpload({
149
+ store,
150
+ storage,
151
+ masterKey,
152
+ workspaceId,
153
+ requestId: r1.request.id,
154
+ itemId: r1Health.id,
155
+ clientName: "Claire Nguyen",
156
+ itemSlug: "private-health-statement",
157
+ originalName: "Bupa-Tax-Statement-Page1.pdf",
158
+ pdfTitle: "Private Health Insurance Statement (Page 1 of 2)",
159
+ pdfLines: [
160
+ "Member: Claire Nguyen",
161
+ "Policy Tier: Gold Hospital",
162
+ "Note: Rebate summary table appears on page 2 (omitted in scan).",
163
+ ],
164
+ });
165
+ store.reviewItem({
166
+ workspaceId,
167
+ requestId: r1.request.id,
168
+ itemId: r1Health.id,
169
+ decision: "rejected",
170
+ note: "Uploaded page 1 only. Please include the rebate summary on page 2.",
171
+ });
172
+ }
173
+ if (r1Decl) {
174
+ store.saveTextOrCheckboxSubmission(r1Decl.id, r1.request.id, encryptField(masterKey, "confirmed", r1Decl.id));
175
+ store.reviewItem({ workspaceId, requestId: r1.request.id, itemId: r1Decl.id, decision: "approved" });
176
+ }
177
+ const r1PortalUrl = `${baseUrl}/c/${r1.magicToken}`;
178
+ const brand = emailBrand(workspace, baseUrl);
179
+ const saveDemoEmail = (requestId, recipient, kind, message) => store.saveOutboxEmail({
180
+ workspaceId,
181
+ requestId,
182
+ recipient,
183
+ subject: message.subject,
184
+ textBody: message.text,
185
+ htmlBody: message.html,
186
+ kind,
187
+ isDemo: true,
188
+ });
189
+ saveDemoEmail(r1.request.id, r1.request.client_email, "invite", inviteEmail({
190
+ brand,
191
+ clientName: "Claire Nguyen",
192
+ title: r1.request.title,
193
+ portalUrl: r1PortalUrl,
194
+ itemCount: r1Items.length,
195
+ welcomeNote: r1.request.welcome_note,
196
+ dueAt: r1.request.due_at,
197
+ subject: r1.request.client_subject,
198
+ }));
199
+ saveDemoEmail(r1.request.id, r1.request.client_email, "revision", revisionEmail({
200
+ brand,
201
+ clientName: "Claire Nguyen",
202
+ title: r1.request.title,
203
+ itemLabel: "Private Health Insurance Tax Statement",
204
+ note: "Uploaded page 1 only. Please include the rebate summary on page 2.",
205
+ portalUrl: r1PortalUrl,
206
+ }));
207
+ // 2. Harbourline Plumbing Pty Ltd - Active BAS pack with chaser sent
208
+ const basItems = JSON.parse(basTpl.items_json);
209
+ const r2 = store.createRequest({
210
+ workspaceId,
211
+ templateId: basTpl.id,
212
+ title: "Q3 BAS & Supplier Pack",
213
+ clientSubject: "Q3 BAS records due in 2 days",
214
+ clientName: "Harbourline Plumbing Pty Ltd",
215
+ clientEmail: "accounts@harbourline.example.com.au",
216
+ items: basItems,
217
+ requireOtp: false,
218
+ reminderIntervalDays: 3,
219
+ maxReminders: 4,
220
+ purgeAfterDays: 30,
221
+ masterKey,
222
+ dueAt: addDaysIso(now.toISOString(), 2),
223
+ remindersSent: 1,
224
+ lastOpenedAt: new Date(now.getTime() - 26 * 3600_000).toISOString(),
225
+ isDemo: true,
226
+ });
227
+ const r2Items = store.listRequestItems(r2.request.id);
228
+ const r2Abn = r2Items.find((i) => i.validator === "au_abn_mod89");
229
+ const r2Bsb = r2Items.find((i) => i.validator === "au_bsb");
230
+ const r2Stmts = r2Items.find((i) => i.label.includes("Bank Statements"));
231
+ if (r2Abn) {
232
+ store.saveTextOrCheckboxSubmission(r2Abn.id, r2.request.id, encryptField(masterKey, "51 824 753 556", r2Abn.id));
233
+ }
234
+ if (r2Bsb) {
235
+ store.saveTextOrCheckboxSubmission(r2Bsb.id, r2.request.id, encryptField(masterKey, "083-170", r2Bsb.id));
236
+ }
237
+ if (r2Stmts) {
238
+ await storeDemoUpload({
239
+ store,
240
+ storage,
241
+ masterKey,
242
+ workspaceId,
243
+ requestId: r2.request.id,
244
+ itemId: r2Stmts.id,
245
+ clientName: "Harbourline Plumbing Pty Ltd",
246
+ itemSlug: "bank-statements",
247
+ originalName: "NAB-Business-Q3-Statement.pdf",
248
+ pdfTitle: "Harbourline Plumbing Pty Ltd - Q3 Business Statement",
249
+ pdfLines: [
250
+ "ABN: 51 824 753 556 | BSB: 083-170",
251
+ "Opening Balance (01 Jan): $48,210.45 AUD",
252
+ "Closing Balance (31 Mar): $62,940.10 AUD",
253
+ "GST Collected Summary Verified",
254
+ ],
255
+ });
256
+ }
257
+ const r2PortalUrl = `${baseUrl}/c/${r2.magicToken}`;
258
+ const r2Outstanding = store
259
+ .listRequestItems(r2.request.id)
260
+ .filter((i) => i.required === 1 && i.status === "pending")
261
+ .map((i) => ({ label: i.label, needsRevision: false }));
262
+ saveDemoEmail(r2.request.id, r2.request.client_email, "reminder", reminderEmail({
263
+ brand,
264
+ clientName: "Harbourline Plumbing Pty Ltd",
265
+ title: r2.request.title,
266
+ portalUrl: r2PortalUrl,
267
+ outstanding: r2Outstanding,
268
+ }));
269
+ // 3. Marcus Okafor - Completed Allied Health pack ready for ZIP export
270
+ const healthItems = JSON.parse(healthTpl.items_json);
271
+ const r3 = store.createRequest({
272
+ workspaceId,
273
+ templateId: healthTpl.id,
274
+ title: "Allied Health New Patient Intake",
275
+ clientName: "Marcus Okafor",
276
+ clientEmail: "marcus.okafor@example.com.au",
277
+ items: healthItems,
278
+ requireOtp: false,
279
+ reminderIntervalDays: 3,
280
+ maxReminders: 4,
281
+ purgeAfterDays: 14,
282
+ masterKey,
283
+ lastOpenedAt: new Date(now.getTime() - 48 * 3600_000).toISOString(),
284
+ isDemo: true,
285
+ });
286
+ const r3Items = store.listRequestItems(r3.request.id);
287
+ const r3Med = r3Items.find((i) => i.validator === "au_medicare_mod10");
288
+ const r3Phone = r3Items.find((i) => i.validator === "au_phone_e164");
289
+ const r3Ref = r3Items.find((i) => i.kind === "file");
290
+ const r3Consent = r3Items.find((i) => i.kind === "checkbox");
291
+ if (r3Med) {
292
+ store.saveTextOrCheckboxSubmission(r3Med.id, r3.request.id, encryptField(masterKey, "2123 45670 1 / 1", r3Med.id));
293
+ }
294
+ if (r3Phone) {
295
+ store.saveTextOrCheckboxSubmission(r3Phone.id, r3.request.id, encryptField(masterKey, "+61438901244", r3Phone.id));
296
+ }
297
+ if (r3Ref) {
298
+ await storeDemoUpload({
299
+ store,
300
+ storage,
301
+ masterKey,
302
+ workspaceId,
303
+ requestId: r3.request.id,
304
+ itemId: r3Ref.id,
305
+ clientName: "Marcus Okafor",
306
+ itemSlug: "gp-referral",
307
+ originalName: "GP-EPC-Referral-Marcus-Okafor.pdf",
308
+ pdfTitle: "GP Chronic Disease Management Referral (EPC)",
309
+ pdfLines: [
310
+ "Patient: Marcus Okafor",
311
+ "Medicare Card: 2123 45670 1 / 1",
312
+ "Referring GP: Dr. Priya Sharma (Provider 2426621B)",
313
+ "Approved Sessions: 5 Allied Health Visits",
314
+ ],
315
+ });
316
+ }
317
+ if (r3Consent) {
318
+ store.saveTextOrCheckboxSubmission(r3Consent.id, r3.request.id, encryptField(masterKey, "confirmed", r3Consent.id));
319
+ }
320
+ store.approveAllSubmitted(workspaceId, r3.request.id);
321
+ saveDemoEmail(r3.request.id, r3.request.client_email, "invite", inviteEmail({
322
+ brand,
323
+ clientName: "Marcus Okafor",
324
+ title: r3.request.title,
325
+ portalUrl: `${baseUrl}/c/${r3.magicToken}`,
326
+ itemCount: r3Items.length,
327
+ }));
328
+ return { seeded: true };
329
+ }
@@ -0,0 +1,22 @@
1
+ export async function runPurgeSweep(params) {
2
+ const nowIso = params.nowIso ?? new Date().toISOString();
3
+ const due = params.store.listPurgeDueRequests(nowIso);
4
+ let requestsPurged = 0;
5
+ let filesDeleted = 0;
6
+ for (const req of due) {
7
+ try {
8
+ const uploads = params.store.listUploadsForRequest(req.id);
9
+ for (const u of uploads) {
10
+ await params.storage.delete(u.storage_key);
11
+ params.store.markUploadPurged(u.id, nowIso);
12
+ filesDeleted += 1;
13
+ }
14
+ params.store.markRequestPurged(req.id, nowIso);
15
+ requestsPurged += 1;
16
+ }
17
+ catch (err) {
18
+ console.error(`[GatherGate Cron] purge failed for request ${req.id}:`, err);
19
+ }
20
+ }
21
+ return { requestsPurged, filesDeleted };
22
+ }
@@ -0,0 +1,153 @@
1
+ import { decryptField, hmacSha256Hex } from "../security/crypto.js";
2
+ import { validateWebhookEndpointRuntime } from "../security/ssrf.js";
3
+ import { maskSensitiveValue, SENSITIVE_VALIDATORS } from "../validators/index.js";
4
+ export function resolveWebhookSecret(workspace, masterKey) {
5
+ const raw = workspace.webhook_secret?.trim();
6
+ if (!raw)
7
+ return null;
8
+ if (raw.startsWith("v1:") && masterKey) {
9
+ try {
10
+ return decryptField(masterKey, raw, `${workspace.id}:webhook`);
11
+ }
12
+ catch {
13
+ return null;
14
+ }
15
+ }
16
+ return raw;
17
+ }
18
+ function buildSignedHeaders(secret, event, body) {
19
+ const ts = Math.floor(Date.now() / 1000).toString();
20
+ const headers = {
21
+ "content-type": "application/json",
22
+ "user-agent": "GatherGate/1.0 (TensorForge; contact@tensorforge.dev)",
23
+ "x-gathergate-event": event,
24
+ "x-gathergate-timestamp": ts,
25
+ };
26
+ if (secret) {
27
+ const sig = hmacSha256Hex(secret, `${ts}.${body}`);
28
+ headers["x-gathergate-signature"] = `t=${ts},v1=${sig}`;
29
+ }
30
+ return headers;
31
+ }
32
+ export async function dispatchCompletionWebhook(params) {
33
+ const url = params.workspace.webhook_url?.trim();
34
+ if (!url)
35
+ return { dispatched: false };
36
+ const ssrfErr = await validateWebhookEndpointRuntime(url, Boolean(params.multiTenant), {
37
+ skipDns: Boolean(params.fetchImpl) && !params.lookupImpl,
38
+ lookupImpl: params.lookupImpl,
39
+ });
40
+ if (ssrfErr) {
41
+ params.store.logAudit(params.workspace.id, params.request.id, "system", "webhook.blocked", {
42
+ reason: ssrfErr,
43
+ });
44
+ return { dispatched: false };
45
+ }
46
+ const items = params.store.listRequestItems(params.request.id);
47
+ const uploads = params.store.listUploadsForRequest(params.request.id);
48
+ // Never emit raw sensitive national IDs over third-party webhooks; mask sensitive fields.
49
+ const payload = {
50
+ event: "request.completed",
51
+ timestamp: new Date().toISOString(),
52
+ workspace: { id: params.workspace.id, name: params.workspace.name },
53
+ request: {
54
+ id: params.request.id,
55
+ title: params.request.title,
56
+ client_name: params.request.client_name,
57
+ client_email: params.request.client_email,
58
+ completed_at: params.request.completed_at,
59
+ purge_at: params.request.purge_at,
60
+ export_url: `${params.baseUrl}/api/requests/${params.request.id}/export.zip`,
61
+ },
62
+ items: items.map((item) => {
63
+ let value = null;
64
+ if (item.value_encrypted) {
65
+ const plain = decryptField(params.masterKey, item.value_encrypted, item.id);
66
+ value = SENSITIVE_VALIDATORS.has(item.validator)
67
+ ? maskSensitiveValue(item.validator, plain)
68
+ : plain;
69
+ }
70
+ const client_note = item.client_note_encrypted
71
+ ? decryptField(params.masterKey, item.client_note_encrypted, `${item.id}:note`)
72
+ : null;
73
+ const itemFiles = uploads
74
+ .filter((u) => u.request_item_id === item.id)
75
+ .map((u) => ({
76
+ id: u.id,
77
+ canonical_name: u.canonical_name,
78
+ detected_mime: u.detected_mime,
79
+ size_bytes: u.size_bytes,
80
+ sha256: u.sha256,
81
+ }));
82
+ return {
83
+ id: item.id,
84
+ section: item.section,
85
+ label: item.label,
86
+ kind: item.kind,
87
+ validator: item.validator,
88
+ status: item.status,
89
+ value,
90
+ client_na: item.client_na === 1,
91
+ client_note,
92
+ files: itemFiles,
93
+ };
94
+ }),
95
+ };
96
+ const body = JSON.stringify(payload);
97
+ const webhookSecret = resolveWebhookSecret(params.workspace, params.masterKey);
98
+ const headers = buildSignedHeaders(webhookSecret, "request.completed", body);
99
+ const doFetch = params.fetchImpl ?? fetch;
100
+ try {
101
+ const res = await doFetch(url, {
102
+ method: "POST",
103
+ headers,
104
+ body,
105
+ redirect: "error",
106
+ signal: AbortSignal.timeout(10_000),
107
+ });
108
+ params.store.logAudit(params.workspace.id, params.request.id, "system", "webhook.dispatched", {
109
+ status: res.status,
110
+ ok: res.ok,
111
+ });
112
+ return { dispatched: true, status: res.status };
113
+ }
114
+ catch (err) {
115
+ params.store.logAudit(params.workspace.id, params.request.id, "system", "webhook.failed", {
116
+ error: err instanceof Error ? err.message : String(err),
117
+ });
118
+ return { dispatched: false };
119
+ }
120
+ }
121
+ export async function dispatchTestWebhook(params) {
122
+ const url = params.workspace.webhook_url?.trim();
123
+ if (!url)
124
+ return { ok: false, error: "No webhook URL configured" };
125
+ const ssrfErr = await validateWebhookEndpointRuntime(url, Boolean(params.multiTenant), {
126
+ skipDns: Boolean(params.fetchImpl) && !params.lookupImpl,
127
+ lookupImpl: params.lookupImpl,
128
+ });
129
+ if (ssrfErr)
130
+ return { ok: false, error: ssrfErr };
131
+ const body = JSON.stringify({
132
+ event: "webhook.test",
133
+ timestamp: new Date().toISOString(),
134
+ workspace: { id: params.workspace.id, name: params.workspace.name },
135
+ message: "GatherGate HMAC-SHA256 webhook verification test.",
136
+ });
137
+ const webhookSecret = resolveWebhookSecret(params.workspace, params.masterKey);
138
+ const headers = buildSignedHeaders(webhookSecret, "webhook.test", body);
139
+ const doFetch = params.fetchImpl ?? fetch;
140
+ try {
141
+ const res = await doFetch(url, {
142
+ method: "POST",
143
+ headers,
144
+ body,
145
+ redirect: "error",
146
+ signal: AbortSignal.timeout(10_000),
147
+ });
148
+ return { ok: res.ok, status: res.status };
149
+ }
150
+ catch (err) {
151
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
152
+ }
153
+ }
@@ -0,0 +1,69 @@
1
+ import crypto from "node:crypto";
2
+ import { safeEqualHex, sha256Hex } from "./crypto.js";
3
+ const ARGON2_MEMORY = 19456; // 19 MiB (OWASP minimum for Argon2id)
4
+ const ARGON2_PASSES = 2;
5
+ const ARGON2_PARALLELISM = 1;
6
+ const ARGON2_TAG_LEN = 32;
7
+ function getNativeArgon2() {
8
+ const fn = crypto.argon2Sync;
9
+ return typeof fn === "function" ? fn : null;
10
+ }
11
+ export function hashPassword(password) {
12
+ const salt = crypto.randomBytes(16);
13
+ const argon2Sync = getNativeArgon2();
14
+ if (argon2Sync) {
15
+ const hash = argon2Sync("argon2id", {
16
+ message: password,
17
+ nonce: salt,
18
+ parallelism: ARGON2_PARALLELISM,
19
+ tagLength: ARGON2_TAG_LEN,
20
+ memory: ARGON2_MEMORY,
21
+ passes: ARGON2_PASSES,
22
+ });
23
+ return `argon2id$${ARGON2_MEMORY}$${ARGON2_PASSES}$${ARGON2_PARALLELISM}$${salt.toString("hex")}$${hash.toString("hex")}`;
24
+ }
25
+ // Fallback for Node 22 runtimes lacking built-in crypto.argon2Sync
26
+ const hash = crypto.scryptSync(password, salt, 32, { N: 16384, r: 8, p: 1 });
27
+ return `scrypt$16384$8$1$${salt.toString("hex")}$${hash.toString("hex")}`;
28
+ }
29
+ export function verifyPassword(password, encoded) {
30
+ const parts = encoded.split("$");
31
+ if (parts.length !== 6)
32
+ return false;
33
+ const [algo, p1, p2, p3, saltHex, expectedHex] = parts;
34
+ const salt = Buffer.from(saltHex, "hex");
35
+ if (algo === "argon2id") {
36
+ const argon2Sync = getNativeArgon2();
37
+ if (!argon2Sync)
38
+ return false;
39
+ const derived = argon2Sync("argon2id", {
40
+ message: password,
41
+ nonce: salt,
42
+ memory: Number(p1),
43
+ passes: Number(p2),
44
+ parallelism: Number(p3),
45
+ tagLength: Buffer.from(expectedHex, "hex").byteLength,
46
+ });
47
+ return safeEqualHex(derived.toString("hex"), expectedHex);
48
+ }
49
+ if (algo === "scrypt") {
50
+ const derived = crypto.scryptSync(password, salt, Buffer.from(expectedHex, "hex").byteLength, {
51
+ N: Number(p1),
52
+ r: Number(p2),
53
+ p: Number(p3),
54
+ });
55
+ return safeEqualHex(derived.toString("hex"), expectedHex);
56
+ }
57
+ return false;
58
+ }
59
+ export function generateOtpCode() {
60
+ const num = crypto.randomInt(0, 1_000_000);
61
+ const code = String(num).padStart(6, "0");
62
+ return { code, hash: sha256Hex(`otp:${code}`) };
63
+ }
64
+ export function verifyOtpCode(code, expectedHash) {
65
+ const cleaned = code.replace(/\s+/g, "");
66
+ if (!/^\d{6}$/.test(cleaned))
67
+ return false;
68
+ return safeEqualHex(sha256Hex(`otp:${cleaned}`), expectedHash);
69
+ }
@@ -0,0 +1,91 @@
1
+ import crypto from "node:crypto";
2
+ export const CURRENT_ENC_VERSION = "v1";
3
+ export function generateId(prefix = "") {
4
+ const raw = crypto.randomBytes(12).toString("base64url");
5
+ return prefix ? `${prefix}_${raw}` : raw;
6
+ }
7
+ export function generateMagicToken() {
8
+ return crypto.randomBytes(32).toString("base64url");
9
+ }
10
+ export function sha256Hex(value) {
11
+ return crypto.createHash("sha256").update(value).digest("hex");
12
+ }
13
+ export function hmacSha256Hex(secret, payload) {
14
+ return crypto.createHmac("sha256", secret).update(payload).digest("hex");
15
+ }
16
+ export function safeEqualHex(a, b) {
17
+ if (a.length !== b.length)
18
+ return false;
19
+ const bufA = Buffer.from(a, "utf8");
20
+ const bufB = Buffer.from(b, "utf8");
21
+ return bufA.length === bufB.length && crypto.timingSafeEqual(bufA, bufB);
22
+ }
23
+ function deriveKey(masterKey, salt, purpose, version = CURRENT_ENC_VERSION) {
24
+ if (version !== CURRENT_ENC_VERSION) {
25
+ throw new Error(`Unsupported encryption version: ${version}`);
26
+ }
27
+ return Buffer.from(crypto.hkdfSync("sha256", masterKey, salt, Buffer.from(`gathergate:${purpose}:${version}`, "utf8"), 32));
28
+ }
29
+ export function encryptField(masterKey, plaintext, aad = "") {
30
+ const salt = crypto.randomBytes(16);
31
+ const iv = crypto.randomBytes(12);
32
+ const key = deriveKey(masterKey, salt, "field");
33
+ const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
34
+ if (aad)
35
+ cipher.setAAD(Buffer.from(aad, "utf8"));
36
+ const encrypted = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
37
+ const tag = cipher.getAuthTag();
38
+ return `v1:${salt.toString("hex")}:${iv.toString("hex")}:${tag.toString("hex")}:${encrypted.toString("base64")}`;
39
+ }
40
+ export function decryptField(masterKey, encoded, aad = "") {
41
+ const parts = encoded.split(":");
42
+ if (parts.length !== 5 || parts[0] !== "v1") {
43
+ throw new Error("Unsupported encrypted field format");
44
+ }
45
+ const [, saltHex, ivHex, tagHex, dataB64] = parts;
46
+ const key = deriveKey(masterKey, Buffer.from(saltHex, "hex"), "field");
47
+ const decipher = crypto.createDecipheriv("aes-256-gcm", key, Buffer.from(ivHex, "hex"));
48
+ if (aad)
49
+ decipher.setAAD(Buffer.from(aad, "utf8"));
50
+ decipher.setAuthTag(Buffer.from(tagHex, "hex"));
51
+ const decrypted = Buffer.concat([decipher.update(Buffer.from(dataB64, "base64")), decipher.final()]);
52
+ return decrypted.toString("utf8");
53
+ }
54
+ export function encryptBuffer(masterKey, plaintext, aad = "") {
55
+ const salt = crypto.randomBytes(16);
56
+ const iv = crypto.randomBytes(12);
57
+ const key = deriveKey(masterKey, salt, "blob");
58
+ const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
59
+ if (aad)
60
+ cipher.setAAD(Buffer.from(aad, "utf8"));
61
+ const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
62
+ const tag = cipher.getAuthTag();
63
+ return {
64
+ ciphertext,
65
+ meta: {
66
+ version: CURRENT_ENC_VERSION,
67
+ ivHex: iv.toString("hex"),
68
+ tagHex: tag.toString("hex"),
69
+ saltHex: salt.toString("hex"),
70
+ sha256Hex: sha256Hex(plaintext),
71
+ sizeBytes: plaintext.byteLength,
72
+ },
73
+ };
74
+ }
75
+ export function createDecryptStream(masterKey, encryptedStream, meta, aad = "") {
76
+ const key = deriveKey(masterKey, Buffer.from(meta.saltHex, "hex"), "blob", meta.version ?? CURRENT_ENC_VERSION);
77
+ const decipher = crypto.createDecipheriv("aes-256-gcm", key, Buffer.from(meta.ivHex, "hex"));
78
+ if (aad)
79
+ decipher.setAAD(Buffer.from(aad, "utf8"));
80
+ decipher.setAuthTag(Buffer.from(meta.tagHex, "hex"));
81
+ encryptedStream.on("error", (err) => decipher.destroy(err));
82
+ return encryptedStream.pipe(decipher);
83
+ }
84
+ export async function decryptBuffer(masterKey, ciphertext, meta, aad = "") {
85
+ const key = deriveKey(masterKey, Buffer.from(meta.saltHex, "hex"), "blob", meta.version ?? CURRENT_ENC_VERSION);
86
+ const decipher = crypto.createDecipheriv("aes-256-gcm", key, Buffer.from(meta.ivHex, "hex"));
87
+ if (aad)
88
+ decipher.setAAD(Buffer.from(aad, "utf8"));
89
+ decipher.setAuthTag(Buffer.from(meta.tagHex, "hex"));
90
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
91
+ }