gathergate 1.0.0-rc.1 → 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.
package/dist/app.js CHANGED
@@ -12,7 +12,7 @@ import { SENSITIVE_DEFAULT_PURGE_DAYS, } from "./config.js";
12
12
  import { ClientWriteConflictError, SetupAlreadyCompletedError, slugify, Store, } from "./db/queries.js";
13
13
  import { emailBrand, inviteEmail, isHexColor, otpEmail, reminderEmail, revisionEmail, testDeliveryEmail, } from "./emails/templates.js";
14
14
  import { seedDemoWorkspace } from "./jobs/demo.js";
15
- import { dispatchCompletionWebhook, dispatchTestWebhook } from "./jobs/webhook.js";
15
+ import { dispatchCompletionWebhook, dispatchTestWebhook, resolveWebhookSecret } from "./jobs/webhook.js";
16
16
  import { generateOtpCode, hashPassword, verifyOtpCode, verifyPassword } from "./security/auth.js";
17
17
  import { decryptBuffer, decryptField, encryptBuffer, encryptField, generateId, sha256Hex, } from "./security/crypto.js";
18
18
  import { detectFileSignature, resolveAllowedMimes } from "./security/magic-bytes.js";
@@ -247,6 +247,12 @@ export function createApp(deps) {
247
247
  const resolved = ws ? resolveWorkspaceEmail(ws, config, config.masterKey) : null;
248
248
  const { subject, text, html } = params.message;
249
249
  if (resolved && resolved.source === "workspace") {
250
+ if (config.multiTenant && resolved.backend === "smtp" && resolved.smtp?.host) {
251
+ const dnsErr = await assertPublicHostname(resolved.smtp.host, deps.lookupImpl);
252
+ if (dnsErr) {
253
+ throw new Error("SMTP host must resolve to a public address in multi-tenant mode.");
254
+ }
255
+ }
250
256
  const adapter = createEmailAdapterFromOptions({
251
257
  backend: resolved.backend,
252
258
  from: resolved.from,
@@ -595,26 +601,40 @@ export function createApp(deps) {
595
601
  masterKey: config.masterKey,
596
602
  });
597
603
  const portalUrl = `${config.baseUrl}/c/${magicToken}`;
604
+ let inviteError;
598
605
  if (sendInvite) {
599
- await sendEmailTracked({
600
- workspaceId: auth.workspace.id,
601
- requestId: request.id,
602
- to: clientEmail,
603
- message: inviteEmail({
604
- brand: emailBrand(auth.workspace, config.baseUrl),
605
- clientName,
606
- title,
607
- portalUrl,
608
- itemCount: items.length,
609
- welcomeNote,
610
- dueAt,
611
- subject: clientSubject,
612
- }),
613
- kind: "invite",
614
- });
615
- store.logAudit(auth.workspace.id, request.id, "system", "invite.sent", { to: clientEmail });
606
+ try {
607
+ await sendEmailTracked({
608
+ workspaceId: auth.workspace.id,
609
+ requestId: request.id,
610
+ to: clientEmail,
611
+ message: inviteEmail({
612
+ brand: emailBrand(auth.workspace, config.baseUrl),
613
+ clientName,
614
+ title,
615
+ portalUrl,
616
+ itemCount: items.length,
617
+ welcomeNote,
618
+ dueAt,
619
+ subject: clientSubject,
620
+ }),
621
+ kind: "invite",
622
+ });
623
+ store.logAudit(auth.workspace.id, request.id, "system", "invite.sent", { to: clientEmail });
624
+ }
625
+ catch (err) {
626
+ inviteError = config.multiTenant
627
+ ? "Invite email failed to send. Check your outbound email settings."
628
+ : err instanceof Error
629
+ ? err.message
630
+ : "Invite email failed to send.";
631
+ store.logAudit(auth.workspace.id, request.id, "system", "invite.failed", {
632
+ to: clientEmail,
633
+ error: err instanceof Error ? err.message : String(err),
634
+ });
635
+ }
616
636
  }
617
- return c.json({ id: request.id, portalUrl }, 201);
637
+ return c.json({ id: request.id, portalUrl, ...(inviteError ? { inviteError } : {}) }, 201);
618
638
  });
619
639
  app.get("/api/requests/:id", (c) => {
620
640
  const auth = requireAuth(c);
@@ -674,9 +694,10 @@ export function createApp(deps) {
674
694
  })),
675
695
  };
676
696
  });
697
+ const { token_hash: _tokenHash, token_encrypted: _tokenEncrypted, ...safeRequest } = request;
677
698
  return c.json({
678
699
  request: {
679
- ...request,
700
+ ...safeRequest,
680
701
  require_otp: request.require_otp === 1,
681
702
  reminders_paused: request.reminders_paused === 1,
682
703
  is_demo: request.is_demo === 1,
@@ -755,7 +776,7 @@ export function createApp(deps) {
755
776
  }
756
777
  const cooldownMs = deps.manualReminderCooldownMs ?? DEFAULT_MANUAL_REMINDER_COOLDOWN_MS;
757
778
  if (req.last_manual_reminder_at && cooldownMs > 0) {
758
- const elapsed = Date.now() - Date.parse(req.last_manual_reminder_at);
779
+ const elapsed = nowFn() - Date.parse(req.last_manual_reminder_at);
759
780
  if (elapsed >= 0 && elapsed < cooldownMs) {
760
781
  const retryAfterSeconds = Math.max(1, Math.ceil((cooldownMs - elapsed) / 1000));
761
782
  c.header("Retry-After", String(retryAfterSeconds));
@@ -777,14 +798,24 @@ export function createApp(deps) {
777
798
  note: i.review_note,
778
799
  })),
779
800
  });
780
- await sendEmailTracked({
781
- workspaceId: auth.workspace.id,
782
- requestId: req.id,
783
- to: req.client_email,
784
- message,
785
- kind: "reminder",
786
- isDemo: req.is_demo === 1,
787
- });
801
+ try {
802
+ await sendEmailTracked({
803
+ workspaceId: auth.workspace.id,
804
+ requestId: req.id,
805
+ to: req.client_email,
806
+ message,
807
+ kind: "reminder",
808
+ isDemo: req.is_demo === 1,
809
+ });
810
+ }
811
+ catch (err) {
812
+ const detail = config.multiTenant
813
+ ? "Reminder email failed to send. Check your outbound email settings."
814
+ : err instanceof Error
815
+ ? err.message
816
+ : "Reminder email failed to send.";
817
+ return c.json({ error: detail }, 502);
818
+ }
788
819
  const updated = store.recordManualReminderSent(auth.workspace.id, req.id, auth.user.email, outstanding.length);
789
820
  return c.json({
790
821
  ok: true,
@@ -893,24 +924,38 @@ export function createApp(deps) {
893
924
  decision,
894
925
  note,
895
926
  });
927
+ let emailError;
896
928
  if (decision === "rejected") {
897
929
  const magicToken = decryptField(config.masterKey, request.token_encrypted, request.id);
898
930
  const portalUrl = `${config.baseUrl}/c/${magicToken}`;
899
- await sendEmailTracked({
900
- workspaceId: auth.workspace.id,
901
- requestId: request.id,
902
- to: request.client_email,
903
- message: revisionEmail({
904
- brand: emailBrand(auth.workspace, config.baseUrl),
905
- clientName: request.client_name,
906
- title: request.title,
907
- itemLabel: item.label,
908
- note: note || "Please review and re-upload.",
909
- portalUrl,
910
- }),
911
- kind: "revision",
912
- isDemo: request.is_demo === 1,
913
- });
931
+ try {
932
+ await sendEmailTracked({
933
+ workspaceId: auth.workspace.id,
934
+ requestId: request.id,
935
+ to: request.client_email,
936
+ message: revisionEmail({
937
+ brand: emailBrand(auth.workspace, config.baseUrl),
938
+ clientName: request.client_name,
939
+ title: request.title,
940
+ itemLabel: item.label,
941
+ note: note || "Please review and re-upload.",
942
+ portalUrl,
943
+ }),
944
+ kind: "revision",
945
+ isDemo: request.is_demo === 1,
946
+ });
947
+ }
948
+ catch (err) {
949
+ emailError = config.multiTenant
950
+ ? "Revision saved, but notification email failed to send."
951
+ : err instanceof Error
952
+ ? err.message
953
+ : "Revision notification email failed to send.";
954
+ store.logAudit(auth.workspace.id, request.id, "system", "revision.email_failed", {
955
+ itemId,
956
+ error: err instanceof Error ? err.message : String(err),
957
+ });
958
+ }
914
959
  }
915
960
  if (justCompleted) {
916
961
  await dispatchCompletionWebhook({
@@ -924,7 +969,12 @@ export function createApp(deps) {
924
969
  lookupImpl: deps.lookupImpl,
925
970
  });
926
971
  }
927
- return c.json({ ok: true, status: request.status, justCompleted });
972
+ return c.json({
973
+ ok: true,
974
+ status: request.status,
975
+ justCompleted,
976
+ ...(emailError ? { emailError } : {}),
977
+ });
928
978
  });
929
979
  app.post("/api/requests/:id/approve-all-submitted", async (c) => {
930
980
  const auth = requireAuth(c);
@@ -1166,7 +1216,7 @@ export function createApp(deps) {
1166
1216
  const emailSummary = summarizeWorkspaceEmail(auth.workspace);
1167
1217
  return c.json({
1168
1218
  webhookUrl: auth.workspace.webhook_url || "",
1169
- webhookSecret: auth.workspace.webhook_secret || "",
1219
+ webhookSecret: resolveWebhookSecret(auth.workspace, config.masterKey) || "",
1170
1220
  branding: publicBranding(auth.workspace),
1171
1221
  account: {
1172
1222
  id: auth.user.id,
@@ -1257,7 +1307,10 @@ export function createApp(deps) {
1257
1307
  if (urlErr)
1258
1308
  return c.json({ error: urlErr }, 400);
1259
1309
  }
1260
- store.updateWorkspaceWebhook(auth.workspace.id, webhookUrl || null, webhookSecret || null);
1310
+ const encryptedSecret = webhookSecret
1311
+ ? encryptField(config.masterKey, webhookSecret, `${auth.workspace.id}:webhook`)
1312
+ : null;
1313
+ store.updateWorkspaceWebhook(auth.workspace.id, webhookUrl || null, encryptedSecret);
1261
1314
  return c.json({ ok: true });
1262
1315
  });
1263
1316
  app.post("/api/settings/webhook/test", async (c) => {
@@ -1275,6 +1328,7 @@ export function createApp(deps) {
1275
1328
  }
1276
1329
  const result = await dispatchTestWebhook({
1277
1330
  workspace: auth.workspace,
1331
+ masterKey: config.masterKey,
1278
1332
  multiTenant: config.multiTenant,
1279
1333
  fetchImpl: deps.fetchImpl,
1280
1334
  lookupImpl: deps.lookupImpl,
@@ -1663,24 +1717,35 @@ export function createApp(deps) {
1663
1717
  if (!request || request.status === "purged" || request.status === "expired") {
1664
1718
  return c.json({ error: "Not found" }, 404);
1665
1719
  }
1720
+ if (request.require_otp !== 1) {
1721
+ return c.json({ error: "Verification code is not required for this checklist." }, 400);
1722
+ }
1666
1723
  const workspace = store.getWorkspaceById(request.workspace_id);
1667
1724
  if (!workspace)
1668
1725
  return c.json({ error: "Not found" }, 404);
1669
1726
  const { code, hash } = generateOtpCode();
1670
1727
  store.createOtpCode(request.id, hash, 15, nowFn());
1671
- await sendEmailTracked({
1672
- workspaceId: request.workspace_id,
1673
- requestId: request.id,
1674
- to: request.client_email,
1675
- message: otpEmail({
1676
- brand: emailBrand(workspace, config.baseUrl),
1677
- clientName: request.client_name,
1678
- title: request.title,
1679
- code,
1680
- }),
1681
- kind: "otp",
1682
- isDemo: request.is_demo === 1,
1683
- });
1728
+ try {
1729
+ await sendEmailTracked({
1730
+ workspaceId: request.workspace_id,
1731
+ requestId: request.id,
1732
+ to: request.client_email,
1733
+ message: otpEmail({
1734
+ brand: emailBrand(workspace, config.baseUrl),
1735
+ clientName: request.client_name,
1736
+ title: request.title,
1737
+ code,
1738
+ }),
1739
+ kind: "otp",
1740
+ isDemo: request.is_demo === 1,
1741
+ });
1742
+ }
1743
+ catch (err) {
1744
+ store.logAudit(request.workspace_id, request.id, "system", "otp.send_failed", {
1745
+ error: err instanceof Error ? err.message : String(err),
1746
+ });
1747
+ return c.json({ error: "Could not send verification code. Please try again shortly." }, 502);
1748
+ }
1684
1749
  store.logAudit(request.workspace_id, request.id, "client", "otp.sent", {});
1685
1750
  return c.json({ ok: true, maskedEmail: maskEmail(request.client_email) });
1686
1751
  });
@@ -1698,6 +1763,9 @@ export function createApp(deps) {
1698
1763
  if (!request || request.status === "purged" || request.status === "expired") {
1699
1764
  return c.json({ error: "Not found" }, 404);
1700
1765
  }
1766
+ if (request.require_otp !== 1) {
1767
+ return c.json({ error: "Verification code is not required for this checklist." }, 400);
1768
+ }
1701
1769
  const body = (await c.req.json().catch(() => ({})));
1702
1770
  const submitted = String(body.code || "");
1703
1771
  const active = store.getActiveOtpCode(request.id);
@@ -1868,12 +1936,13 @@ export function createApp(deps) {
1868
1936
  pendingBytes += buf.byteLength;
1869
1937
  preparedFiles.push({ name: file.name, buf, detected });
1870
1938
  }
1871
- // Pass 2: encrypt and persist; roll back written blobs if a concurrent request lock occurs.
1872
- const savedUploads = [];
1939
+ // Pass 2: encrypt and write all blobs first, then commit all DB rows in one atomic transaction.
1873
1940
  const writtenStorageKeys = [];
1941
+ const stagedUploads = [];
1874
1942
  const clientSlug = slugify(request.client_name, "client");
1875
1943
  const itemSlug = slugify(cfg.slug || item.label, "doc");
1876
1944
  let seq = store.nextUploadSeqForItem(item.id);
1945
+ let savedUploads;
1877
1946
  try {
1878
1947
  for (const pf of preparedFiles) {
1879
1948
  const uploadId = generateId("upl");
@@ -1883,7 +1952,7 @@ export function createApp(deps) {
1883
1952
  const { ciphertext, meta } = encryptBuffer(config.masterKey, pf.buf, storageKey);
1884
1953
  await storage.put(storageKey, ciphertext);
1885
1954
  writtenStorageKeys.push(storageKey);
1886
- const uploadRow = store.addUpload({
1955
+ stagedUploads.push({
1887
1956
  id: uploadId,
1888
1957
  itemId: item.id,
1889
1958
  requestId: request.id,
@@ -1898,15 +1967,16 @@ export function createApp(deps) {
1898
1967
  saltHex: meta.saltHex,
1899
1968
  sha256Hex: meta.sha256Hex,
1900
1969
  });
1901
- savedUploads.push({
1902
- id: uploadRow.id,
1903
- original_name: uploadRow.original_name,
1904
- canonical_name: uploadRow.canonical_name,
1905
- detected_mime: uploadRow.detected_mime,
1906
- size_bytes: uploadRow.size_bytes,
1907
- created_at: uploadRow.created_at,
1908
- });
1909
1970
  }
1971
+ const uploadRows = store.addUploads(stagedUploads);
1972
+ savedUploads = uploadRows.map((uploadRow) => ({
1973
+ id: uploadRow.id,
1974
+ original_name: uploadRow.original_name,
1975
+ canonical_name: uploadRow.canonical_name,
1976
+ detected_mime: uploadRow.detected_mime,
1977
+ size_bytes: uploadRow.size_bytes,
1978
+ created_at: uploadRow.created_at,
1979
+ }));
1910
1980
  }
1911
1981
  catch (err) {
1912
1982
  for (const k of writtenStorageKeys) {
@@ -452,26 +452,36 @@ export class Store {
452
452
  return rows.map((r) => r.storage_key);
453
453
  });
454
454
  }
455
- addUpload(params) {
455
+ addUploads(entries) {
456
+ if (entries.length === 0)
457
+ return [];
456
458
  return this.inTransaction(() => {
457
- this.assertClientWriteOpenAndUnlocked(params.requestId, params.itemId);
458
- const id = params.id ?? generateId("upl");
459
+ const { requestId, itemId } = entries[0];
460
+ this.assertClientWriteOpenAndUnlocked(requestId, itemId);
459
461
  const now = new Date().toISOString();
460
- this.db
461
- .prepare(`INSERT INTO uploads (
462
- id, request_item_id, original_name, canonical_name, detected_mime,
463
- size_bytes, storage_key, enc_version, enc_iv, enc_tag, enc_salt, sha256, created_at
464
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
465
- .run(id, params.itemId, params.originalName, params.canonicalName, params.detectedMime, params.sizeBytes, params.storageKey, params.encVersion ?? "v1", params.ivHex, params.tagHex, params.saltHex, params.sha256Hex, now);
462
+ const insertStmt = this.db.prepare(`INSERT INTO uploads (
463
+ id, request_item_id, original_name, canonical_name, detected_mime,
464
+ size_bytes, storage_key, enc_version, enc_iv, enc_tag, enc_salt, sha256, created_at
465
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
466
+ const selectStmt = this.db.prepare("SELECT * FROM uploads WHERE id = ?");
467
+ const rows = [];
468
+ for (const params of entries) {
469
+ const id = params.id ?? generateId("upl");
470
+ insertStmt.run(id, params.itemId, params.originalName, params.canonicalName, params.detectedMime, params.sizeBytes, params.storageKey, params.encVersion ?? "v1", params.ivHex, params.tagHex, params.saltHex, params.sha256Hex, now);
471
+ rows.push(selectStmt.get(id));
472
+ }
466
473
  this.db
467
474
  .prepare(`UPDATE request_items
468
475
  SET status = 'submitted', review_note = NULL, client_na = 0, updated_at = ?
469
476
  WHERE id = ? AND request_id = ?`)
470
- .run(now, params.itemId, params.requestId);
471
- this.recomputeRequestStatus(params.requestId);
472
- return this.db.prepare("SELECT * FROM uploads WHERE id = ?").get(id);
477
+ .run(now, itemId, requestId);
478
+ this.recomputeRequestStatus(requestId);
479
+ return rows;
473
480
  });
474
481
  }
482
+ addUpload(params) {
483
+ return this.addUploads([params])[0];
484
+ }
475
485
  reviewItem(params) {
476
486
  return this.inTransaction(() => {
477
487
  const now = new Date().toISOString();
@@ -1,6 +1,7 @@
1
1
  import { createEmailAdapterFromOptions, resolveWorkspaceEmail } from "../adapters/email.js";
2
2
  import { emailBrand, reminderEmail } from "../emails/templates.js";
3
3
  import { decryptField } from "../security/crypto.js";
4
+ import { assertPublicHostname } from "../security/ssrf.js";
4
5
  export async function runReminderSweep(params) {
5
6
  const nowIso = params.nowIso ?? new Date().toISOString();
6
7
  const due = params.store.listDueReminders(nowIso);
@@ -33,6 +34,16 @@ export async function runReminderSweep(params) {
33
34
  const resolved = params.config
34
35
  ? resolveWorkspaceEmail(workspace, params.config, params.masterKey)
35
36
  : null;
37
+ if (params.config?.multiTenant &&
38
+ resolved &&
39
+ resolved.source === "workspace" &&
40
+ resolved.backend === "smtp" &&
41
+ resolved.smtp?.host) {
42
+ const dnsErr = await assertPublicHostname(resolved.smtp.host, params.lookupImpl);
43
+ if (dnsErr) {
44
+ throw new Error("SMTP host must resolve to a public address in multi-tenant mode.");
45
+ }
46
+ }
36
47
  const adapter = resolved && resolved.source === "workspace"
37
48
  ? createEmailAdapterFromOptions(resolved)
38
49
  : params.email;
@@ -1,6 +1,20 @@
1
1
  import { decryptField, hmacSha256Hex } from "../security/crypto.js";
2
2
  import { validateWebhookEndpointRuntime } from "../security/ssrf.js";
3
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
+ }
4
18
  function buildSignedHeaders(secret, event, body) {
5
19
  const ts = Math.floor(Date.now() / 1000).toString();
6
20
  const headers = {
@@ -80,7 +94,8 @@ export async function dispatchCompletionWebhook(params) {
80
94
  }),
81
95
  };
82
96
  const body = JSON.stringify(payload);
83
- const headers = buildSignedHeaders(params.workspace.webhook_secret, "request.completed", body);
97
+ const webhookSecret = resolveWebhookSecret(params.workspace, params.masterKey);
98
+ const headers = buildSignedHeaders(webhookSecret, "request.completed", body);
84
99
  const doFetch = params.fetchImpl ?? fetch;
85
100
  try {
86
101
  const res = await doFetch(url, {
@@ -119,7 +134,8 @@ export async function dispatchTestWebhook(params) {
119
134
  workspace: { id: params.workspace.id, name: params.workspace.name },
120
135
  message: "GatherGate HMAC-SHA256 webhook verification test.",
121
136
  });
122
- const headers = buildSignedHeaders(params.workspace.webhook_secret, "webhook.test", body);
137
+ const webhookSecret = resolveWebhookSecret(params.workspace, params.masterKey);
138
+ const headers = buildSignedHeaders(webhookSecret, "webhook.test", body);
123
139
  const doFetch = params.fetchImpl ?? fetch;
124
140
  try {
125
141
  const res = await doFetch(url, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gathergate",
3
- "version": "1.0.0-rc.1",
3
+ "version": "1.0.0",
4
4
  "description": "Self-hosted magic-link client document checklist, deterministic validator, and auto-chaser.",
5
5
  "type": "module",
6
6
  "license": "MIT",