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.
- package/LICENSE +21 -0
- package/README.md +212 -2
- package/client/dist/assets/geist-mono-cyrillic-400-normal-C51Di1Mf.woff2 +0 -0
- package/client/dist/assets/geist-mono-cyrillic-400-normal-CPJFfJgk.woff +0 -0
- package/client/dist/assets/geist-mono-cyrillic-500-normal-D2cXvDHF.woff2 +0 -0
- package/client/dist/assets/geist-mono-cyrillic-500-normal-DfuvdVgn.woff +0 -0
- package/client/dist/assets/geist-mono-cyrillic-600-normal-Dfv53e6N.woff2 +0 -0
- package/client/dist/assets/geist-mono-cyrillic-600-normal-DzvMIgFZ.woff +0 -0
- package/client/dist/assets/geist-mono-latin-400-normal-B2yvC1Cq.woff +0 -0
- package/client/dist/assets/geist-mono-latin-400-normal-DTRLJnHl.woff2 +0 -0
- package/client/dist/assets/geist-mono-latin-500-normal-D-GG86Jb.woff +0 -0
- package/client/dist/assets/geist-mono-latin-500-normal-YINYabwD.woff2 +0 -0
- package/client/dist/assets/geist-mono-latin-600-normal-V-KvD_pi.woff2 +0 -0
- package/client/dist/assets/geist-mono-latin-600-normal-bZn07FKM.woff +0 -0
- package/client/dist/assets/geist-mono-latin-ext-400-normal-CfzLURNc.woff +0 -0
- package/client/dist/assets/geist-mono-latin-ext-400-normal-DI-rJ0UV.woff2 +0 -0
- package/client/dist/assets/geist-mono-latin-ext-500-normal-Buglb9-a.woff2 +0 -0
- package/client/dist/assets/geist-mono-latin-ext-500-normal-CrWEgvU_.woff +0 -0
- package/client/dist/assets/geist-mono-latin-ext-600-normal-B7ybHiTt.woff +0 -0
- package/client/dist/assets/geist-mono-latin-ext-600-normal-TphwrhF8.woff2 +0 -0
- package/client/dist/assets/geist-mono-symbols2-400-normal-DjbiTEEA.woff +0 -0
- package/client/dist/assets/geist-mono-symbols2-500-normal-CmnCPGa0.woff +0 -0
- package/client/dist/assets/geist-mono-symbols2-600-normal-D7I4D0GJ.woff +0 -0
- package/client/dist/assets/geist-mono-vietnamese-400-normal-CZEPLOgu.woff +0 -0
- package/client/dist/assets/geist-mono-vietnamese-500-normal-Dx9-epDo.woff +0 -0
- package/client/dist/assets/geist-mono-vietnamese-600-normal-BLL01lwa.woff +0 -0
- package/client/dist/assets/index-BWbZAfMJ.js +80 -0
- package/client/dist/assets/index-ZnG2njjK.css +2 -0
- package/client/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
- package/client/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
- package/client/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
- package/client/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
- package/client/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
- package/client/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
- package/client/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
- package/client/dist/favicon.svg +12 -0
- package/client/dist/index.html +16 -0
- package/client/dist/site.webmanifest +16 -0
- package/dist/adapters/email.js +125 -0
- package/dist/adapters/storage.js +106 -0
- package/dist/app.js +2126 -0
- package/dist/config.js +106 -0
- package/dist/db/client.js +294 -0
- package/dist/db/queries.js +898 -0
- package/dist/emails/templates.js +221 -0
- package/dist/index.js +77 -0
- package/dist/jobs/chaser.js +81 -0
- package/dist/jobs/demo.js +329 -0
- package/dist/jobs/purge.js +22 -0
- package/dist/jobs/webhook.js +153 -0
- package/dist/security/auth.js +69 -0
- package/dist/security/crypto.js +91 -0
- package/dist/security/magic-bytes.js +131 -0
- package/dist/security/rate-limit.js +72 -0
- package/dist/security/ssrf.js +181 -0
- package/dist/templates/presets.js +341 -0
- package/dist/validators/index.js +52 -0
- package/dist/validators/packs/au.js +108 -0
- package/dist/validators/packs/eu.js +85 -0
- package/dist/validators/packs/generic.js +57 -0
- package/dist/validators/packs/types.js +1 -0
- package/dist/validators/packs/uk.js +58 -0
- package/dist/validators/packs/us.js +82 -0
- package/package.json +55 -4
package/dist/app.js
ADDED
|
@@ -0,0 +1,2126 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { Readable } from "node:stream";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { serveStatic } from "@hono/node-server/serve-static";
|
|
6
|
+
import { Hono } from "hono";
|
|
7
|
+
import { bodyLimit } from "hono/body-limit";
|
|
8
|
+
import { deleteCookie, getCookie, setCookie } from "hono/cookie";
|
|
9
|
+
import { ZipFile } from "yazl";
|
|
10
|
+
import { createEmailAdapterFromOptions, resolveWorkspaceEmail, } from "./adapters/email.js";
|
|
11
|
+
import { SENSITIVE_DEFAULT_PURGE_DAYS, } from "./config.js";
|
|
12
|
+
import { ClientWriteConflictError, SetupAlreadyCompletedError, slugify, Store, } from "./db/queries.js";
|
|
13
|
+
import { emailBrand, inviteEmail, isHexColor, otpEmail, reminderEmail, revisionEmail, testDeliveryEmail, } from "./emails/templates.js";
|
|
14
|
+
import { seedDemoWorkspace } from "./jobs/demo.js";
|
|
15
|
+
import { dispatchCompletionWebhook, dispatchTestWebhook, resolveWebhookSecret } from "./jobs/webhook.js";
|
|
16
|
+
import { generateOtpCode, hashPassword, verifyOtpCode, verifyPassword } from "./security/auth.js";
|
|
17
|
+
import { decryptBuffer, decryptField, encryptBuffer, encryptField, generateId, sha256Hex, } from "./security/crypto.js";
|
|
18
|
+
import { detectFileSignature, resolveAllowedMimes } from "./security/magic-bytes.js";
|
|
19
|
+
import { extractClientIp, RateLimiter } from "./security/rate-limit.js";
|
|
20
|
+
import { assertPublicHostname, isPrivateOrLocalHost, validateWebhookEndpoint, } from "./security/ssrf.js";
|
|
21
|
+
import { getValidatorHint, isKnownValidator, listValidators, maskSensitiveValue, SENSITIVE_VALIDATORS, validateTextValue, } from "./validators/index.js";
|
|
22
|
+
const SESSION_COOKIE = "gg_session";
|
|
23
|
+
const CLIENT_COOKIE_PREFIX = "gg_c_";
|
|
24
|
+
const MAX_LOGO_BYTES = 200 * 1024;
|
|
25
|
+
const LOGO_MIMES = new Set(["image/png", "image/jpeg", "image/webp"]);
|
|
26
|
+
const MAX_CLIENT_NOTE_CHARS = 1000;
|
|
27
|
+
const MAX_TEXT_ITEM_CHARS = 2000;
|
|
28
|
+
const MAX_TEXTAREA_ITEM_CHARS = 20_000;
|
|
29
|
+
const MAX_PASSWORD_CHARS = 256;
|
|
30
|
+
const MAX_FILES_PER_UPLOAD = 10;
|
|
31
|
+
const MAX_ITEM_FILE_MB = 50;
|
|
32
|
+
const DEFAULT_MANUAL_REMINDER_COOLDOWN_MS = 15 * 60_000;
|
|
33
|
+
const MULTI_TENANT_SMTP_PORTS = new Set([25, 465, 587, 2525]);
|
|
34
|
+
function isValidEmailAddress(email) {
|
|
35
|
+
return Boolean(email && !hasCrLf(email) && !/[,\s;<>]/.test(email) && validateTextValue("email", email).valid);
|
|
36
|
+
}
|
|
37
|
+
async function readStreamToBuffer(stream) {
|
|
38
|
+
const chunks = [];
|
|
39
|
+
for await (const chunk of stream) {
|
|
40
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
41
|
+
}
|
|
42
|
+
return Buffer.concat(chunks);
|
|
43
|
+
}
|
|
44
|
+
async function decryptStoredUpload(storage, masterKey, upload) {
|
|
45
|
+
const encStream = await storage.getStream(upload.storage_key);
|
|
46
|
+
const ciphertext = await readStreamToBuffer(encStream);
|
|
47
|
+
return decryptBuffer(masterKey, ciphertext, {
|
|
48
|
+
version: upload.enc_version,
|
|
49
|
+
ivHex: upload.enc_iv,
|
|
50
|
+
tagHex: upload.enc_tag,
|
|
51
|
+
saltHex: upload.enc_salt,
|
|
52
|
+
}, upload.storage_key);
|
|
53
|
+
}
|
|
54
|
+
const DEFAULT_RATE_LIMITS = {
|
|
55
|
+
otpSendToken: { limit: 5, windowMs: 15 * 60_000 },
|
|
56
|
+
otpSendIp: { limit: 15, windowMs: 15 * 60_000 },
|
|
57
|
+
otpVerifyToken: { limit: 10, windowMs: 15 * 60_000 },
|
|
58
|
+
otpVerifyIp: { limit: 30, windowMs: 15 * 60_000 },
|
|
59
|
+
uploadToken: { limit: 30, windowMs: 15 * 60_000 },
|
|
60
|
+
uploadIp: { limit: 60, windowMs: 15 * 60_000 },
|
|
61
|
+
loginIp: { limit: 20, windowMs: 15 * 60_000 },
|
|
62
|
+
loginAccount: { limit: 20, windowMs: 15 * 60_000 },
|
|
63
|
+
signupIp: { limit: 5, windowMs: 15 * 60_000 },
|
|
64
|
+
setupIp: { limit: 10, windowMs: 15 * 60_000 },
|
|
65
|
+
settingsTest: { limit: 10, windowMs: 15 * 60_000 },
|
|
66
|
+
};
|
|
67
|
+
function maskEmail(email) {
|
|
68
|
+
const [local, domain] = email.split("@");
|
|
69
|
+
if (!local || !domain)
|
|
70
|
+
return "***";
|
|
71
|
+
const prefix = local.slice(0, Math.min(2, local.length));
|
|
72
|
+
return `${prefix}***@${domain}`;
|
|
73
|
+
}
|
|
74
|
+
function sanitizeWorkspace(ws) {
|
|
75
|
+
return {
|
|
76
|
+
id: ws.id,
|
|
77
|
+
name: ws.name,
|
|
78
|
+
slug: ws.slug,
|
|
79
|
+
plan: ws.plan,
|
|
80
|
+
max_active_requests: ws.max_active_requests,
|
|
81
|
+
max_storage_bytes: ws.max_storage_bytes,
|
|
82
|
+
webhook_url: ws.webhook_url,
|
|
83
|
+
has_webhook_secret: Boolean(ws.webhook_secret),
|
|
84
|
+
brand_color: ws.brand_color,
|
|
85
|
+
has_logo: Boolean(ws.logo_b64),
|
|
86
|
+
support_email: ws.support_email,
|
|
87
|
+
support_phone: ws.support_phone,
|
|
88
|
+
created_at: ws.created_at,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
/** Branding shown to end clients; never includes secrets or plan details. */
|
|
92
|
+
function publicBranding(ws) {
|
|
93
|
+
return {
|
|
94
|
+
name: ws.name,
|
|
95
|
+
brandColor: ws.brand_color,
|
|
96
|
+
logoDataUrl: ws.logo_b64 && ws.logo_mime ? `data:${ws.logo_mime};base64,${ws.logo_b64}` : null,
|
|
97
|
+
supportEmail: ws.support_email,
|
|
98
|
+
supportPhone: ws.support_phone,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
function hasCrLf(value) {
|
|
102
|
+
return /[\r\n]/.test(value);
|
|
103
|
+
}
|
|
104
|
+
function extractAddress(raw) {
|
|
105
|
+
const match = raw.match(/^[^<>]*<([^<>]+)>$/);
|
|
106
|
+
return (match ? match[1] : raw).trim();
|
|
107
|
+
}
|
|
108
|
+
function resolveDefaultClientDistDir() {
|
|
109
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
110
|
+
return path.resolve(here, "..", "client", "dist");
|
|
111
|
+
}
|
|
112
|
+
function normalizeTemplateItems(raw) {
|
|
113
|
+
if (!Array.isArray(raw) || raw.length === 0) {
|
|
114
|
+
throw new Error("At least one checklist item is required.");
|
|
115
|
+
}
|
|
116
|
+
return raw.map((entry, idx) => {
|
|
117
|
+
const item = entry;
|
|
118
|
+
const label = String(item.label || "").trim();
|
|
119
|
+
if (!label)
|
|
120
|
+
throw new Error(`Item #${idx + 1} is missing a label.`);
|
|
121
|
+
const kind = item.kind;
|
|
122
|
+
if (kind !== "file" && kind !== "text" && kind !== "textarea" && kind !== "checkbox") {
|
|
123
|
+
throw new Error(`Item "${label}" has invalid kind.`);
|
|
124
|
+
}
|
|
125
|
+
const validator = item.validator || "none";
|
|
126
|
+
if (!isKnownValidator(validator)) {
|
|
127
|
+
throw new Error(`Item "${label}" uses unknown validator "${validator}".`);
|
|
128
|
+
}
|
|
129
|
+
return {
|
|
130
|
+
section: String(item.section || "General").trim() || "General",
|
|
131
|
+
label,
|
|
132
|
+
helpText: String(item.helpText || "").trim(),
|
|
133
|
+
kind,
|
|
134
|
+
required: Boolean(item.required),
|
|
135
|
+
validator,
|
|
136
|
+
allowedGroups: Array.isArray(item.allowedGroups) ? item.allowedGroups : undefined,
|
|
137
|
+
maxFileMb: typeof item.maxFileMb === "number" && item.maxFileMb > 0
|
|
138
|
+
? Math.min(MAX_ITEM_FILE_MB, Math.max(1, Math.floor(item.maxFileMb)))
|
|
139
|
+
: 20,
|
|
140
|
+
multiple: Boolean(item.multiple),
|
|
141
|
+
slug: item.slug ? slugify(item.slug) : slugify(label, `item-${idx + 1}`),
|
|
142
|
+
};
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
export function createApp(deps) {
|
|
146
|
+
const { config, storage, email } = deps;
|
|
147
|
+
const store = new Store(deps.db);
|
|
148
|
+
const app = new Hono();
|
|
149
|
+
const secureCookie = config.baseUrl.startsWith("https://");
|
|
150
|
+
const clientDistDir = deps.clientDistDir ?? resolveDefaultClientDistDir();
|
|
151
|
+
const nowFn = deps.now ?? (() => Date.now());
|
|
152
|
+
const limiter = new RateLimiter(nowFn);
|
|
153
|
+
const limits = { ...DEFAULT_RATE_LIMITS, ...(deps.rateLimits ?? {}) };
|
|
154
|
+
function enforceRateLimit(c, checks, message) {
|
|
155
|
+
for (const check of checks) {
|
|
156
|
+
const rule = limits[check.bucket];
|
|
157
|
+
const res = limiter.check(`${check.bucket}:${check.key}`, rule.limit, rule.windowMs);
|
|
158
|
+
if (!res.allowed) {
|
|
159
|
+
c.header("Retry-After", String(res.retryAfterSeconds));
|
|
160
|
+
return c.json({ error: message, retryAfterSeconds: res.retryAfterSeconds }, 429);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
// Tiered request body limits before parsing JSON or multipart payloads.
|
|
166
|
+
const uploadLimit = bodyLimit({
|
|
167
|
+
maxSize: (MAX_ITEM_FILE_MB + 5) * 1024 * 1024,
|
|
168
|
+
onError: (c) => c.json({ error: "Request payload too large." }, 413),
|
|
169
|
+
});
|
|
170
|
+
const brandingLimit = bodyLimit({
|
|
171
|
+
maxSize: 512 * 1024,
|
|
172
|
+
onError: (c) => c.json({ error: "Branding payload too large." }, 413),
|
|
173
|
+
});
|
|
174
|
+
const defaultJsonLimit = bodyLimit({
|
|
175
|
+
maxSize: 256 * 1024,
|
|
176
|
+
onError: (c) => c.json({ error: "Request payload too large." }, 413),
|
|
177
|
+
});
|
|
178
|
+
app.use("/api/*", async (c, next) => {
|
|
179
|
+
if (c.req.method === "GET" || c.req.method === "HEAD" || c.req.method === "OPTIONS") {
|
|
180
|
+
return next();
|
|
181
|
+
}
|
|
182
|
+
if (/^\/api\/client\/[^/]+\/items\/[^/]+$/.test(c.req.path)) {
|
|
183
|
+
return uploadLimit(c, next);
|
|
184
|
+
}
|
|
185
|
+
if (c.req.path === "/api/settings/branding") {
|
|
186
|
+
return brandingLimit(c, next);
|
|
187
|
+
}
|
|
188
|
+
return defaultJsonLimit(c, next);
|
|
189
|
+
});
|
|
190
|
+
// Hardened response headers; Referrer-Policy: no-referrer protects magic-link URLs.
|
|
191
|
+
app.use("*", async (c, next) => {
|
|
192
|
+
await next();
|
|
193
|
+
c.header("X-Content-Type-Options", "nosniff");
|
|
194
|
+
c.header("Referrer-Policy", "no-referrer");
|
|
195
|
+
c.header("Permissions-Policy", "camera=(), microphone=(), geolocation=()");
|
|
196
|
+
const isPreview = c.req.path.startsWith("/api/uploads/") && c.req.path.endsWith("/preview");
|
|
197
|
+
if (!isPreview) {
|
|
198
|
+
c.header("X-Frame-Options", "DENY");
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
app.get("/healthz", (c) => c.json({ ok: true, service: "gathergate" }));
|
|
202
|
+
function requireAuth(c) {
|
|
203
|
+
const token = getCookie(c, SESSION_COOKIE);
|
|
204
|
+
if (!token)
|
|
205
|
+
return null;
|
|
206
|
+
return store.getUserBySessionToken(token);
|
|
207
|
+
}
|
|
208
|
+
function summarizeWorkspaceEmail(ws) {
|
|
209
|
+
const resolved = resolveWorkspaceEmail(ws, config, config.masterKey);
|
|
210
|
+
if (config.multiTenant && resolved.source === "env") {
|
|
211
|
+
return {
|
|
212
|
+
source: resolved.source,
|
|
213
|
+
backend: resolved.backend,
|
|
214
|
+
from: resolved.from,
|
|
215
|
+
replyTo: "",
|
|
216
|
+
smtp: {
|
|
217
|
+
host: "",
|
|
218
|
+
port: 587,
|
|
219
|
+
secure: false,
|
|
220
|
+
user: "",
|
|
221
|
+
hasPass: false,
|
|
222
|
+
},
|
|
223
|
+
resend: {
|
|
224
|
+
hasApiKey: false,
|
|
225
|
+
},
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
return {
|
|
229
|
+
source: resolved.source,
|
|
230
|
+
backend: resolved.backend,
|
|
231
|
+
from: resolved.from,
|
|
232
|
+
replyTo: resolved.replyTo,
|
|
233
|
+
smtp: {
|
|
234
|
+
host: resolved.smtp?.host || "",
|
|
235
|
+
port: resolved.smtp?.port ?? 587,
|
|
236
|
+
secure: Boolean(resolved.smtp?.secure),
|
|
237
|
+
user: resolved.smtp?.user || "",
|
|
238
|
+
hasPass: Boolean(resolved.smtp?.pass),
|
|
239
|
+
},
|
|
240
|
+
resend: {
|
|
241
|
+
hasApiKey: Boolean(resolved.resendApiKey),
|
|
242
|
+
},
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
async function sendEmailTracked(params) {
|
|
246
|
+
const ws = params.workspace ?? store.getWorkspaceById(params.workspaceId);
|
|
247
|
+
const resolved = ws ? resolveWorkspaceEmail(ws, config, config.masterKey) : null;
|
|
248
|
+
const { subject, text, html } = params.message;
|
|
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
|
+
}
|
|
256
|
+
const adapter = createEmailAdapterFromOptions({
|
|
257
|
+
backend: resolved.backend,
|
|
258
|
+
from: resolved.from,
|
|
259
|
+
resendApiKey: resolved.resendApiKey,
|
|
260
|
+
smtp: resolved.smtp,
|
|
261
|
+
fetchImpl: deps.fetchImpl,
|
|
262
|
+
});
|
|
263
|
+
await adapter.send({
|
|
264
|
+
to: params.to,
|
|
265
|
+
subject,
|
|
266
|
+
text,
|
|
267
|
+
html,
|
|
268
|
+
replyTo: resolved.replyTo || undefined,
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
else {
|
|
272
|
+
await email.send({ to: params.to, subject, text, html });
|
|
273
|
+
}
|
|
274
|
+
const effectiveBackend = resolved?.backend ?? config.emailBackend;
|
|
275
|
+
if (effectiveBackend === "console") {
|
|
276
|
+
store.saveOutboxEmail({
|
|
277
|
+
workspaceId: params.workspaceId,
|
|
278
|
+
requestId: params.requestId,
|
|
279
|
+
recipient: params.to,
|
|
280
|
+
subject,
|
|
281
|
+
textBody: text,
|
|
282
|
+
htmlBody: html,
|
|
283
|
+
kind: params.kind,
|
|
284
|
+
isDemo: params.isDemo,
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
// ---------------------------------------------------------------------------
|
|
289
|
+
// Session & Operator Auth (/api/*)
|
|
290
|
+
// ---------------------------------------------------------------------------
|
|
291
|
+
app.get("/api/session", (c) => {
|
|
292
|
+
const needsSetup = store.countUsers() === 0;
|
|
293
|
+
const auth = needsSetup ? null : requireAuth(c);
|
|
294
|
+
const resolvedEmail = auth ? resolveWorkspaceEmail(auth.workspace, config, config.masterKey) : null;
|
|
295
|
+
return c.json({
|
|
296
|
+
needsSetup,
|
|
297
|
+
multiTenant: config.multiTenant,
|
|
298
|
+
user: auth ? { id: auth.user.id, email: auth.user.email, displayName: auth.user.display_name } : null,
|
|
299
|
+
workspace: auth ? sanitizeWorkspace(auth.workspace) : null,
|
|
300
|
+
readiness: {
|
|
301
|
+
storageBackend: config.storageBackend,
|
|
302
|
+
emailBackend: resolvedEmail ? resolvedEmail.backend : config.emailBackend,
|
|
303
|
+
cronIntervalMinutes: config.cronIntervalMinutes,
|
|
304
|
+
defaultPurgeDays: config.defaultPurgeDays,
|
|
305
|
+
masterKeyAutoGenerated: auth ? config.masterKeySource === "file" : false,
|
|
306
|
+
hasDemoData: auth ? store.hasDemoData(auth.workspace.id) : false,
|
|
307
|
+
outboxCount: auth ? store.countOutboxEmails(auth.workspace.id) : 0,
|
|
308
|
+
awaitingReviewCount: auth ? store.countAwaitingReview(auth.workspace.id) : 0,
|
|
309
|
+
},
|
|
310
|
+
});
|
|
311
|
+
});
|
|
312
|
+
app.post("/api/setup", async (c) => {
|
|
313
|
+
const ip = extractClientIp(c, config.trustProxy);
|
|
314
|
+
const limited = enforceRateLimit(c, [{ bucket: "setupIp", key: ip }], "Too many setup attempts. Please wait and try again.");
|
|
315
|
+
if (limited)
|
|
316
|
+
return limited;
|
|
317
|
+
const body = (await c.req.json().catch(() => ({})));
|
|
318
|
+
const workspaceName = String(body.workspaceName || "").trim();
|
|
319
|
+
const userEmail = String(body.email || "").trim().toLowerCase();
|
|
320
|
+
const password = String(body.password || "");
|
|
321
|
+
const loadDemo = body.loadDemo !== false;
|
|
322
|
+
if (!workspaceName ||
|
|
323
|
+
hasCrLf(workspaceName) ||
|
|
324
|
+
!isValidEmailAddress(userEmail) ||
|
|
325
|
+
password.length < 10 ||
|
|
326
|
+
password.length > MAX_PASSWORD_CHARS) {
|
|
327
|
+
return c.json({ error: "Provide workspace name, valid email, and password (10 to 256 characters)." }, 400);
|
|
328
|
+
}
|
|
329
|
+
let created;
|
|
330
|
+
try {
|
|
331
|
+
created = store.createInitialWorkspaceWithUser({
|
|
332
|
+
workspaceName,
|
|
333
|
+
email: userEmail,
|
|
334
|
+
passwordHash: hashPassword(password),
|
|
335
|
+
plan: config.multiTenant ? "pro" : "self_hosted",
|
|
336
|
+
maxActiveRequests: 0,
|
|
337
|
+
maxStorageBytes: 0,
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
catch (err) {
|
|
341
|
+
if (err instanceof SetupAlreadyCompletedError || String(err).includes("UNIQUE")) {
|
|
342
|
+
return c.json({ error: "Setup has already been completed." }, 409);
|
|
343
|
+
}
|
|
344
|
+
throw err;
|
|
345
|
+
}
|
|
346
|
+
const { user, workspace } = created;
|
|
347
|
+
if (loadDemo) {
|
|
348
|
+
await seedDemoWorkspace({
|
|
349
|
+
store,
|
|
350
|
+
storage,
|
|
351
|
+
workspaceId: workspace.id,
|
|
352
|
+
masterKey: config.masterKey,
|
|
353
|
+
baseUrl: config.baseUrl,
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
const sessionToken = store.createSession(user.id);
|
|
357
|
+
setCookie(c, SESSION_COOKIE, sessionToken, {
|
|
358
|
+
httpOnly: true,
|
|
359
|
+
sameSite: "Lax",
|
|
360
|
+
secure: secureCookie,
|
|
361
|
+
path: "/",
|
|
362
|
+
maxAge: 14 * 86400,
|
|
363
|
+
});
|
|
364
|
+
return c.json({
|
|
365
|
+
ok: true,
|
|
366
|
+
user: { id: user.id, email: user.email, displayName: user.display_name },
|
|
367
|
+
workspace: sanitizeWorkspace(workspace),
|
|
368
|
+
});
|
|
369
|
+
});
|
|
370
|
+
app.post("/api/login", async (c) => {
|
|
371
|
+
const ip = extractClientIp(c, config.trustProxy);
|
|
372
|
+
const ipLimited = enforceRateLimit(c, [{ bucket: "loginIp", key: ip }], "Too many sign-in attempts. Please wait and try again.");
|
|
373
|
+
if (ipLimited)
|
|
374
|
+
return ipLimited;
|
|
375
|
+
const body = (await c.req.json().catch(() => ({})));
|
|
376
|
+
const userEmail = String(body.email || "").trim().toLowerCase();
|
|
377
|
+
const password = String(body.password || "");
|
|
378
|
+
if (password.length > MAX_PASSWORD_CHARS) {
|
|
379
|
+
return c.json({ error: "Invalid email or password." }, 401);
|
|
380
|
+
}
|
|
381
|
+
if (userEmail) {
|
|
382
|
+
const acctLimited = enforceRateLimit(c, [{ bucket: "loginAccount", key: userEmail }], "Too many sign-in attempts. Please wait and try again.");
|
|
383
|
+
if (acctLimited)
|
|
384
|
+
return acctLimited;
|
|
385
|
+
}
|
|
386
|
+
const user = store.getUserByEmail(userEmail);
|
|
387
|
+
if (!user || !verifyPassword(password, user.password_hash)) {
|
|
388
|
+
return c.json({ error: "Invalid email or password." }, 401);
|
|
389
|
+
}
|
|
390
|
+
const sessionToken = store.createSession(user.id);
|
|
391
|
+
setCookie(c, SESSION_COOKIE, sessionToken, {
|
|
392
|
+
httpOnly: true,
|
|
393
|
+
sameSite: "Lax",
|
|
394
|
+
secure: secureCookie,
|
|
395
|
+
path: "/",
|
|
396
|
+
maxAge: 14 * 86400,
|
|
397
|
+
});
|
|
398
|
+
const workspace = store.getWorkspaceById(user.workspace_id);
|
|
399
|
+
return c.json({
|
|
400
|
+
ok: true,
|
|
401
|
+
user: { id: user.id, email: user.email, displayName: user.display_name },
|
|
402
|
+
workspace: sanitizeWorkspace(workspace),
|
|
403
|
+
});
|
|
404
|
+
});
|
|
405
|
+
app.post("/api/signup", async (c) => {
|
|
406
|
+
if (!config.multiTenant) {
|
|
407
|
+
return c.json({ error: "Multi-tenant signup is disabled." }, 403);
|
|
408
|
+
}
|
|
409
|
+
const ip = extractClientIp(c, config.trustProxy);
|
|
410
|
+
const limited = enforceRateLimit(c, [{ bucket: "signupIp", key: ip }], "Too many signup attempts. Please wait and try again.");
|
|
411
|
+
if (limited)
|
|
412
|
+
return limited;
|
|
413
|
+
const body = (await c.req.json().catch(() => ({})));
|
|
414
|
+
const workspaceName = String(body.workspaceName || "").trim();
|
|
415
|
+
const userEmail = String(body.email || "").trim().toLowerCase();
|
|
416
|
+
const password = String(body.password || "");
|
|
417
|
+
if (!workspaceName ||
|
|
418
|
+
hasCrLf(workspaceName) ||
|
|
419
|
+
!isValidEmailAddress(userEmail) ||
|
|
420
|
+
password.length < 10 ||
|
|
421
|
+
password.length > MAX_PASSWORD_CHARS) {
|
|
422
|
+
return c.json({ error: "Provide workspace name, valid email, and password (10 to 256 characters)." }, 400);
|
|
423
|
+
}
|
|
424
|
+
if (store.getUserByEmail(userEmail)) {
|
|
425
|
+
return c.json({ error: "An account with this email already exists." }, 409);
|
|
426
|
+
}
|
|
427
|
+
let created;
|
|
428
|
+
try {
|
|
429
|
+
created = store.createWorkspaceWithUser({
|
|
430
|
+
workspaceName,
|
|
431
|
+
email: userEmail,
|
|
432
|
+
passwordHash: hashPassword(password),
|
|
433
|
+
plan: "free",
|
|
434
|
+
maxActiveRequests: config.freeMaxActiveRequests,
|
|
435
|
+
maxStorageBytes: config.freeMaxStorageBytes,
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
catch (err) {
|
|
439
|
+
if (String(err).includes("UNIQUE")) {
|
|
440
|
+
return c.json({ error: "An account with this email already exists." }, 409);
|
|
441
|
+
}
|
|
442
|
+
throw err;
|
|
443
|
+
}
|
|
444
|
+
const { user, workspace } = created;
|
|
445
|
+
const sessionToken = store.createSession(user.id);
|
|
446
|
+
setCookie(c, SESSION_COOKIE, sessionToken, {
|
|
447
|
+
httpOnly: true,
|
|
448
|
+
sameSite: "Lax",
|
|
449
|
+
secure: secureCookie,
|
|
450
|
+
path: "/",
|
|
451
|
+
maxAge: 14 * 86400,
|
|
452
|
+
});
|
|
453
|
+
return c.json({
|
|
454
|
+
ok: true,
|
|
455
|
+
user: { id: user.id, email: user.email, displayName: user.display_name },
|
|
456
|
+
workspace: sanitizeWorkspace(workspace),
|
|
457
|
+
});
|
|
458
|
+
});
|
|
459
|
+
app.post("/api/logout", (c) => {
|
|
460
|
+
const token = getCookie(c, SESSION_COOKIE);
|
|
461
|
+
if (token)
|
|
462
|
+
store.deleteSessionByToken(token);
|
|
463
|
+
deleteCookie(c, SESSION_COOKIE, { path: "/" });
|
|
464
|
+
return c.json({ ok: true });
|
|
465
|
+
});
|
|
466
|
+
// ---------------------------------------------------------------------------
|
|
467
|
+
// Requests, Review & Exports
|
|
468
|
+
// ---------------------------------------------------------------------------
|
|
469
|
+
app.get("/api/clients", (c) => {
|
|
470
|
+
const auth = requireAuth(c);
|
|
471
|
+
if (!auth)
|
|
472
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
473
|
+
return c.json({ clients: store.listClients(auth.workspace.id) });
|
|
474
|
+
});
|
|
475
|
+
app.get("/api/requests", (c) => {
|
|
476
|
+
const auth = requireAuth(c);
|
|
477
|
+
if (!auth)
|
|
478
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
479
|
+
const rows = store.listRequests(auth.workspace.id);
|
|
480
|
+
const enriched = rows.map((r) => {
|
|
481
|
+
const magicToken = r.status === "purged" || !r.token_encrypted
|
|
482
|
+
? ""
|
|
483
|
+
: decryptField(config.masterKey, r.token_encrypted, r.id);
|
|
484
|
+
return {
|
|
485
|
+
id: r.id,
|
|
486
|
+
title: r.title,
|
|
487
|
+
client_name: r.client_name,
|
|
488
|
+
client_email: r.client_email,
|
|
489
|
+
status: r.status,
|
|
490
|
+
require_otp: r.require_otp === 1,
|
|
491
|
+
reminders_sent: r.reminders_sent,
|
|
492
|
+
max_reminders: r.max_reminders,
|
|
493
|
+
reminders_paused: r.reminders_paused === 1,
|
|
494
|
+
next_reminder_at: r.next_reminder_at,
|
|
495
|
+
purge_at: r.purge_at,
|
|
496
|
+
due_at: r.due_at,
|
|
497
|
+
last_opened_at: r.last_opened_at,
|
|
498
|
+
is_demo: r.is_demo === 1,
|
|
499
|
+
created_at: r.created_at,
|
|
500
|
+
total_items: Number(r.total_items || 0),
|
|
501
|
+
approved_items: Number(r.approved_items || 0),
|
|
502
|
+
submitted_items: Number(r.submitted_items || 0),
|
|
503
|
+
rejected_items: Number(r.rejected_items || 0),
|
|
504
|
+
portal_url: magicToken ? `${config.baseUrl}/c/${magicToken}` : "",
|
|
505
|
+
};
|
|
506
|
+
});
|
|
507
|
+
const kpis = {
|
|
508
|
+
active: enriched.filter((r) => r.status === "open" || r.status === "in_review").length,
|
|
509
|
+
awaitingReview: enriched.filter((r) => r.submitted_items > 0 && r.status !== "purged").length,
|
|
510
|
+
needsRevision: enriched.filter((r) => r.rejected_items > 0 && r.status !== "purged").length,
|
|
511
|
+
completed: enriched.filter((r) => r.status === "completed").length,
|
|
512
|
+
};
|
|
513
|
+
const demoCandidate = enriched.find((r) => r.is_demo && !r.require_otp && r.status !== "completed" && r.status !== "purged") ??
|
|
514
|
+
enriched.find((r) => r.is_demo && r.status !== "purged");
|
|
515
|
+
return c.json({
|
|
516
|
+
requests: enriched,
|
|
517
|
+
kpis,
|
|
518
|
+
storageBytes: store.getWorkspaceStorageBytes(auth.workspace.id),
|
|
519
|
+
activeCount: store.countActiveRequests(auth.workspace.id),
|
|
520
|
+
workspace: sanitizeWorkspace(auth.workspace),
|
|
521
|
+
hasDemoData: enriched.some((r) => r.is_demo),
|
|
522
|
+
demoPortalUrl: demoCandidate?.portal_url ?? null,
|
|
523
|
+
});
|
|
524
|
+
});
|
|
525
|
+
app.post("/api/requests", async (c) => {
|
|
526
|
+
const auth = requireAuth(c);
|
|
527
|
+
if (!auth)
|
|
528
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
529
|
+
if (auth.workspace.max_active_requests > 0 &&
|
|
530
|
+
store.countActiveRequests(auth.workspace.id, true) >= auth.workspace.max_active_requests) {
|
|
531
|
+
return c.json({
|
|
532
|
+
error: `Active request cap (${auth.workspace.max_active_requests}) reached on current plan.`,
|
|
533
|
+
}, 403);
|
|
534
|
+
}
|
|
535
|
+
const body = (await c.req.json().catch(() => ({})));
|
|
536
|
+
const templateId = String(body.templateId || "");
|
|
537
|
+
const title = String(body.title || "").trim();
|
|
538
|
+
const clientName = String(body.clientName || "").trim();
|
|
539
|
+
const clientEmail = String(body.clientEmail || "").trim().toLowerCase();
|
|
540
|
+
const requireOtp = Boolean(body.requireOtp);
|
|
541
|
+
const sendInvite = body.sendInvite !== false;
|
|
542
|
+
const rawInterval = Number(body.reminderIntervalDays ?? 3);
|
|
543
|
+
const reminderIntervalDays = Number.isFinite(rawInterval)
|
|
544
|
+
? Math.min(90, Math.max(0, Math.floor(rawInterval)))
|
|
545
|
+
: 3;
|
|
546
|
+
const rawMaxRem = Number(body.maxReminders ?? 4);
|
|
547
|
+
const maxReminders = Number.isFinite(rawMaxRem) ? Math.min(20, Math.max(0, Math.floor(rawMaxRem))) : 4;
|
|
548
|
+
let dueAt = null;
|
|
549
|
+
if (body.dueAt !== undefined && body.dueAt !== null && String(body.dueAt).trim() !== "") {
|
|
550
|
+
const parsedDue = new Date(String(body.dueAt));
|
|
551
|
+
if (Number.isNaN(parsedDue.getTime())) {
|
|
552
|
+
return c.json({ error: "Invalid due date." }, 400);
|
|
553
|
+
}
|
|
554
|
+
dueAt = parsedDue.toISOString();
|
|
555
|
+
}
|
|
556
|
+
const clientSubject = body.clientSubject ? String(body.clientSubject).trim() : null;
|
|
557
|
+
const welcomeNote = body.welcomeNote ? String(body.welcomeNote).trim() : null;
|
|
558
|
+
const template = templateId ? store.getTemplate(auth.workspace.id, templateId) : undefined;
|
|
559
|
+
if ((!template && !body.items) ||
|
|
560
|
+
!title ||
|
|
561
|
+
hasCrLf(title) ||
|
|
562
|
+
!clientName ||
|
|
563
|
+
hasCrLf(clientName) ||
|
|
564
|
+
(clientSubject && hasCrLf(clientSubject)) ||
|
|
565
|
+
!isValidEmailAddress(clientEmail)) {
|
|
566
|
+
return c.json({ error: "Select a template and fill in title, client name, and valid client email." }, 400);
|
|
567
|
+
}
|
|
568
|
+
let items;
|
|
569
|
+
try {
|
|
570
|
+
items = body.items
|
|
571
|
+
? normalizeTemplateItems(body.items)
|
|
572
|
+
: normalizeTemplateItems(JSON.parse(template.items_json));
|
|
573
|
+
}
|
|
574
|
+
catch (err) {
|
|
575
|
+
return c.json({ error: err instanceof Error ? err.message : "Invalid checklist items." }, 400);
|
|
576
|
+
}
|
|
577
|
+
const hasSensitiveItems = items.some((i) => SENSITIVE_VALIDATORS.has(i.validator));
|
|
578
|
+
const defaultPurge = hasSensitiveItems
|
|
579
|
+
? Math.min(config.defaultPurgeDays, SENSITIVE_DEFAULT_PURGE_DAYS)
|
|
580
|
+
: config.defaultPurgeDays;
|
|
581
|
+
const hasExplicitPurge = body.purgeAfterDays !== undefined &&
|
|
582
|
+
body.purgeAfterDays !== null &&
|
|
583
|
+
String(body.purgeAfterDays).trim() !== "";
|
|
584
|
+
const purgeAfterDays = hasExplicitPurge
|
|
585
|
+
? Math.max(1, Math.min(365, Math.floor(Number(body.purgeAfterDays)) || defaultPurge))
|
|
586
|
+
: defaultPurge;
|
|
587
|
+
const { request, magicToken } = store.createRequest({
|
|
588
|
+
workspaceId: auth.workspace.id,
|
|
589
|
+
templateId: template?.id ?? null,
|
|
590
|
+
title,
|
|
591
|
+
clientSubject,
|
|
592
|
+
welcomeNote,
|
|
593
|
+
clientName,
|
|
594
|
+
clientEmail,
|
|
595
|
+
items,
|
|
596
|
+
requireOtp,
|
|
597
|
+
reminderIntervalDays,
|
|
598
|
+
maxReminders,
|
|
599
|
+
purgeAfterDays,
|
|
600
|
+
dueAt,
|
|
601
|
+
masterKey: config.masterKey,
|
|
602
|
+
});
|
|
603
|
+
const portalUrl = `${config.baseUrl}/c/${magicToken}`;
|
|
604
|
+
let inviteError;
|
|
605
|
+
if (sendInvite) {
|
|
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
|
+
}
|
|
636
|
+
}
|
|
637
|
+
return c.json({ id: request.id, portalUrl, ...(inviteError ? { inviteError } : {}) }, 201);
|
|
638
|
+
});
|
|
639
|
+
app.get("/api/requests/:id", (c) => {
|
|
640
|
+
const auth = requireAuth(c);
|
|
641
|
+
if (!auth)
|
|
642
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
643
|
+
const request = store.getRequestById(auth.workspace.id, c.req.param("id"));
|
|
644
|
+
if (!request)
|
|
645
|
+
return c.json({ error: "Not found" }, 404);
|
|
646
|
+
const magicToken = request.status === "purged" || !request.token_encrypted
|
|
647
|
+
? ""
|
|
648
|
+
: decryptField(config.masterKey, request.token_encrypted, request.id);
|
|
649
|
+
const portalUrl = magicToken ? `${config.baseUrl}/c/${magicToken}` : "";
|
|
650
|
+
const rawItems = store.listRequestItems(request.id);
|
|
651
|
+
const allUploads = store.listUploadsForRequest(request.id);
|
|
652
|
+
const items = rawItems.map((item) => {
|
|
653
|
+
let displayValue = null;
|
|
654
|
+
let isSensitiveMasked = false;
|
|
655
|
+
if (item.value_encrypted) {
|
|
656
|
+
const plain = decryptField(config.masterKey, item.value_encrypted, item.id);
|
|
657
|
+
if (SENSITIVE_VALIDATORS.has(item.validator)) {
|
|
658
|
+
displayValue = maskSensitiveValue(item.validator, plain);
|
|
659
|
+
isSensitiveMasked = true;
|
|
660
|
+
}
|
|
661
|
+
else {
|
|
662
|
+
displayValue = plain;
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
return {
|
|
666
|
+
id: item.id,
|
|
667
|
+
position: item.position,
|
|
668
|
+
section: item.section,
|
|
669
|
+
label: item.label,
|
|
670
|
+
help_text: item.help_text,
|
|
671
|
+
kind: item.kind,
|
|
672
|
+
required: item.required === 1,
|
|
673
|
+
validator: item.validator,
|
|
674
|
+
config: JSON.parse(item.config_json),
|
|
675
|
+
status: item.status,
|
|
676
|
+
displayValue,
|
|
677
|
+
isSensitiveMasked,
|
|
678
|
+
review_note: item.review_note,
|
|
679
|
+
client_note: item.client_note_encrypted
|
|
680
|
+
? decryptField(config.masterKey, item.client_note_encrypted, `${item.id}:note`)
|
|
681
|
+
: null,
|
|
682
|
+
client_na: item.client_na === 1,
|
|
683
|
+
updated_at: item.updated_at,
|
|
684
|
+
uploads: allUploads
|
|
685
|
+
.filter((u) => u.request_item_id === item.id)
|
|
686
|
+
.map((u) => ({
|
|
687
|
+
id: u.id,
|
|
688
|
+
original_name: u.original_name,
|
|
689
|
+
canonical_name: u.canonical_name,
|
|
690
|
+
detected_mime: u.detected_mime,
|
|
691
|
+
size_bytes: u.size_bytes,
|
|
692
|
+
sha256: u.sha256,
|
|
693
|
+
created_at: u.created_at,
|
|
694
|
+
})),
|
|
695
|
+
};
|
|
696
|
+
});
|
|
697
|
+
const { token_hash: _tokenHash, token_encrypted: _tokenEncrypted, ...safeRequest } = request;
|
|
698
|
+
return c.json({
|
|
699
|
+
request: {
|
|
700
|
+
...safeRequest,
|
|
701
|
+
require_otp: request.require_otp === 1,
|
|
702
|
+
reminders_paused: request.reminders_paused === 1,
|
|
703
|
+
is_demo: request.is_demo === 1,
|
|
704
|
+
},
|
|
705
|
+
portalUrl,
|
|
706
|
+
items,
|
|
707
|
+
auditEvents: store.listAuditEvents(request.id),
|
|
708
|
+
});
|
|
709
|
+
});
|
|
710
|
+
app.post("/api/requests/:id/items/:itemId/reveal", (c) => {
|
|
711
|
+
const auth = requireAuth(c);
|
|
712
|
+
if (!auth)
|
|
713
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
714
|
+
const requestId = c.req.param("id");
|
|
715
|
+
const itemId = c.req.param("itemId");
|
|
716
|
+
const req = store.getRequestById(auth.workspace.id, requestId);
|
|
717
|
+
const item = req ? store.getRequestItem(requestId, itemId) : undefined;
|
|
718
|
+
if (!req || !item)
|
|
719
|
+
return c.json({ error: "Not found" }, 404);
|
|
720
|
+
if (!item.value_encrypted)
|
|
721
|
+
return c.json({ error: "No value stored" }, 404);
|
|
722
|
+
store.logAudit(auth.workspace.id, requestId, "operator", "item.sensitive_revealed", {
|
|
723
|
+
itemId,
|
|
724
|
+
by: auth.user.email,
|
|
725
|
+
});
|
|
726
|
+
return c.json({
|
|
727
|
+
itemId,
|
|
728
|
+
value: decryptField(config.masterKey, item.value_encrypted, item.id),
|
|
729
|
+
});
|
|
730
|
+
});
|
|
731
|
+
app.post("/api/requests/bulk-reminders", async (c) => {
|
|
732
|
+
const auth = requireAuth(c);
|
|
733
|
+
if (!auth)
|
|
734
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
735
|
+
const body = (await c.req.json().catch(() => ({})));
|
|
736
|
+
if (!Array.isArray(body.ids) ||
|
|
737
|
+
body.ids.length === 0 ||
|
|
738
|
+
body.ids.length > 200 ||
|
|
739
|
+
!body.ids.every((x) => typeof x === "string" && x.length > 0) ||
|
|
740
|
+
typeof body.paused !== "boolean") {
|
|
741
|
+
return c.json({ error: "Provide 1 to 200 request IDs and a paused boolean." }, 400);
|
|
742
|
+
}
|
|
743
|
+
const updatedIds = store.setRemindersPausedBulk(auth.workspace.id, body.ids, body.paused);
|
|
744
|
+
return c.json({ ok: true, updatedIds, paused: body.paused });
|
|
745
|
+
});
|
|
746
|
+
app.post("/api/requests/:id/toggle-reminders", (c) => {
|
|
747
|
+
const auth = requireAuth(c);
|
|
748
|
+
if (!auth)
|
|
749
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
750
|
+
const req = store.getRequestById(auth.workspace.id, c.req.param("id"));
|
|
751
|
+
if (!req)
|
|
752
|
+
return c.json({ error: "Not found" }, 404);
|
|
753
|
+
if (req.status === "completed" || req.status === "purged" || req.status === "expired") {
|
|
754
|
+
return c.json({ error: "Checklist is closed." }, 409);
|
|
755
|
+
}
|
|
756
|
+
const paused = req.reminders_paused === 0;
|
|
757
|
+
store.toggleRemindersPaused(auth.workspace.id, req.id, paused);
|
|
758
|
+
return c.json({ ok: true, reminders_paused: paused });
|
|
759
|
+
});
|
|
760
|
+
app.post("/api/requests/:id/remind-now", async (c) => {
|
|
761
|
+
const auth = requireAuth(c);
|
|
762
|
+
if (!auth)
|
|
763
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
764
|
+
const req = store.getRequestById(auth.workspace.id, c.req.param("id"));
|
|
765
|
+
if (!req)
|
|
766
|
+
return c.json({ error: "Not found" }, 404);
|
|
767
|
+
if (req.status === "completed" || req.status === "purged" || req.status === "expired") {
|
|
768
|
+
return c.json({ error: "Checklist is closed." }, 409);
|
|
769
|
+
}
|
|
770
|
+
const items = store.listRequestItems(req.id);
|
|
771
|
+
const requiredItems = items.filter((i) => i.required === 1);
|
|
772
|
+
const checkSet = new Set((requiredItems.length > 0 ? requiredItems : items).map((i) => i.id));
|
|
773
|
+
const outstanding = items.filter((i) => (checkSet.has(i.id) || i.status === "rejected") && (i.status === "pending" || i.status === "rejected"));
|
|
774
|
+
if (outstanding.length === 0) {
|
|
775
|
+
return c.json({ error: "No outstanding items to remind the client about." }, 400);
|
|
776
|
+
}
|
|
777
|
+
const cooldownMs = deps.manualReminderCooldownMs ?? DEFAULT_MANUAL_REMINDER_COOLDOWN_MS;
|
|
778
|
+
if (req.last_manual_reminder_at && cooldownMs > 0) {
|
|
779
|
+
const elapsed = nowFn() - Date.parse(req.last_manual_reminder_at);
|
|
780
|
+
if (elapsed >= 0 && elapsed < cooldownMs) {
|
|
781
|
+
const retryAfterSeconds = Math.max(1, Math.ceil((cooldownMs - elapsed) / 1000));
|
|
782
|
+
c.header("Retry-After", String(retryAfterSeconds));
|
|
783
|
+
return c.json({
|
|
784
|
+
error: "Reminder sent recently. Please wait before sending another.",
|
|
785
|
+
retryAfterSeconds,
|
|
786
|
+
}, 429);
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
const magicToken = decryptField(config.masterKey, req.token_encrypted, req.id);
|
|
790
|
+
const message = reminderEmail({
|
|
791
|
+
brand: emailBrand(auth.workspace, config.baseUrl),
|
|
792
|
+
clientName: req.client_name,
|
|
793
|
+
title: req.title,
|
|
794
|
+
portalUrl: `${config.baseUrl}/c/${magicToken}`,
|
|
795
|
+
outstanding: outstanding.map((i) => ({
|
|
796
|
+
label: i.label,
|
|
797
|
+
needsRevision: i.status === "rejected",
|
|
798
|
+
note: i.review_note,
|
|
799
|
+
})),
|
|
800
|
+
});
|
|
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
|
+
}
|
|
819
|
+
const updated = store.recordManualReminderSent(auth.workspace.id, req.id, auth.user.email, outstanding.length);
|
|
820
|
+
return c.json({
|
|
821
|
+
ok: true,
|
|
822
|
+
reminders_sent: updated.reminders_sent,
|
|
823
|
+
last_manual_reminder_at: updated.last_manual_reminder_at,
|
|
824
|
+
next_reminder_at: updated.next_reminder_at,
|
|
825
|
+
});
|
|
826
|
+
});
|
|
827
|
+
app.patch("/api/requests/:id", async (c) => {
|
|
828
|
+
const auth = requireAuth(c);
|
|
829
|
+
if (!auth)
|
|
830
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
831
|
+
const req = store.getRequestById(auth.workspace.id, c.req.param("id"));
|
|
832
|
+
if (!req)
|
|
833
|
+
return c.json({ error: "Not found" }, 404);
|
|
834
|
+
if (req.status === "completed" || req.status === "purged" || req.status === "expired") {
|
|
835
|
+
return c.json({ error: "Checklist is closed." }, 409);
|
|
836
|
+
}
|
|
837
|
+
const body = (await c.req.json().catch(() => ({})));
|
|
838
|
+
let nextDue;
|
|
839
|
+
if (body.dueAt === null || body.dueAt === "") {
|
|
840
|
+
nextDue = null;
|
|
841
|
+
}
|
|
842
|
+
else if (typeof body.dueAt === "string") {
|
|
843
|
+
const parsed = new Date(body.dueAt);
|
|
844
|
+
if (Number.isNaN(parsed.getTime())) {
|
|
845
|
+
return c.json({ error: "Invalid due date." }, 400);
|
|
846
|
+
}
|
|
847
|
+
nextDue = parsed.toISOString();
|
|
848
|
+
}
|
|
849
|
+
else {
|
|
850
|
+
return c.json({ error: "Invalid due date." }, 400);
|
|
851
|
+
}
|
|
852
|
+
store.updateRequestDueAt(auth.workspace.id, req.id, nextDue, auth.user.email);
|
|
853
|
+
return c.json({ ok: true, due_at: nextDue });
|
|
854
|
+
});
|
|
855
|
+
app.post("/api/requests/:id/items", async (c) => {
|
|
856
|
+
const auth = requireAuth(c);
|
|
857
|
+
if (!auth)
|
|
858
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
859
|
+
const req = store.getRequestById(auth.workspace.id, c.req.param("id"));
|
|
860
|
+
if (!req)
|
|
861
|
+
return c.json({ error: "Not found" }, 404);
|
|
862
|
+
if (req.status === "completed" || req.status === "purged" || req.status === "expired") {
|
|
863
|
+
return c.json({ error: "Checklist is closed." }, 409);
|
|
864
|
+
}
|
|
865
|
+
const raw = await c.req.json().catch(() => ({}));
|
|
866
|
+
let spec;
|
|
867
|
+
try {
|
|
868
|
+
spec = normalizeTemplateItems([raw && typeof raw === "object" ? raw : {}])[0];
|
|
869
|
+
}
|
|
870
|
+
catch (err) {
|
|
871
|
+
return c.json({ error: err instanceof Error ? err.message : "Invalid checklist item." }, 400);
|
|
872
|
+
}
|
|
873
|
+
const added = store.addRequestItem(auth.workspace.id, req.id, spec);
|
|
874
|
+
return c.json({
|
|
875
|
+
ok: true,
|
|
876
|
+
requestStatus: added.request.status,
|
|
877
|
+
item: {
|
|
878
|
+
id: added.item.id,
|
|
879
|
+
position: added.item.position,
|
|
880
|
+
section: added.item.section,
|
|
881
|
+
label: added.item.label,
|
|
882
|
+
help_text: added.item.help_text,
|
|
883
|
+
kind: added.item.kind,
|
|
884
|
+
required: added.item.required === 1,
|
|
885
|
+
validator: added.item.validator,
|
|
886
|
+
config: JSON.parse(added.item.config_json),
|
|
887
|
+
status: added.item.status,
|
|
888
|
+
displayValue: null,
|
|
889
|
+
isSensitiveMasked: false,
|
|
890
|
+
review_note: null,
|
|
891
|
+
client_note: null,
|
|
892
|
+
client_na: false,
|
|
893
|
+
updated_at: added.item.updated_at,
|
|
894
|
+
uploads: [],
|
|
895
|
+
},
|
|
896
|
+
}, 201);
|
|
897
|
+
});
|
|
898
|
+
app.post("/api/requests/:id/items/:itemId/review", async (c) => {
|
|
899
|
+
const auth = requireAuth(c);
|
|
900
|
+
if (!auth)
|
|
901
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
902
|
+
const requestId = c.req.param("id");
|
|
903
|
+
const itemId = c.req.param("itemId");
|
|
904
|
+
const body = (await c.req.json().catch(() => ({})));
|
|
905
|
+
if (body.decision !== "approved" && body.decision !== "rejected") {
|
|
906
|
+
return c.json({ error: "Decision must be 'approved' or 'rejected'." }, 400);
|
|
907
|
+
}
|
|
908
|
+
const decision = body.decision;
|
|
909
|
+
const note = String(body.note || "").trim();
|
|
910
|
+
const item = store.getRequestItem(requestId, itemId);
|
|
911
|
+
const reqBefore = store.getRequestById(auth.workspace.id, requestId);
|
|
912
|
+
if (!reqBefore || !item)
|
|
913
|
+
return c.json({ error: "Not found" }, 404);
|
|
914
|
+
if (reqBefore.status === "purged" || reqBefore.status === "expired") {
|
|
915
|
+
return c.json({ error: "Checklist is closed." }, 409);
|
|
916
|
+
}
|
|
917
|
+
if (decision === "approved" && item.status === "pending") {
|
|
918
|
+
return c.json({ error: "Cannot approve an item that has not been submitted." }, 409);
|
|
919
|
+
}
|
|
920
|
+
const { justCompleted, request } = store.reviewItem({
|
|
921
|
+
workspaceId: auth.workspace.id,
|
|
922
|
+
requestId,
|
|
923
|
+
itemId,
|
|
924
|
+
decision,
|
|
925
|
+
note,
|
|
926
|
+
});
|
|
927
|
+
let emailError;
|
|
928
|
+
if (decision === "rejected") {
|
|
929
|
+
const magicToken = decryptField(config.masterKey, request.token_encrypted, request.id);
|
|
930
|
+
const portalUrl = `${config.baseUrl}/c/${magicToken}`;
|
|
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
|
+
}
|
|
959
|
+
}
|
|
960
|
+
if (justCompleted) {
|
|
961
|
+
await dispatchCompletionWebhook({
|
|
962
|
+
store,
|
|
963
|
+
workspace: auth.workspace,
|
|
964
|
+
request,
|
|
965
|
+
masterKey: config.masterKey,
|
|
966
|
+
baseUrl: config.baseUrl,
|
|
967
|
+
multiTenant: config.multiTenant,
|
|
968
|
+
fetchImpl: deps.fetchImpl,
|
|
969
|
+
lookupImpl: deps.lookupImpl,
|
|
970
|
+
});
|
|
971
|
+
}
|
|
972
|
+
return c.json({
|
|
973
|
+
ok: true,
|
|
974
|
+
status: request.status,
|
|
975
|
+
justCompleted,
|
|
976
|
+
...(emailError ? { emailError } : {}),
|
|
977
|
+
});
|
|
978
|
+
});
|
|
979
|
+
app.post("/api/requests/:id/approve-all-submitted", async (c) => {
|
|
980
|
+
const auth = requireAuth(c);
|
|
981
|
+
if (!auth)
|
|
982
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
983
|
+
const requestId = c.req.param("id");
|
|
984
|
+
const existing = store.getRequestById(auth.workspace.id, requestId);
|
|
985
|
+
if (!existing)
|
|
986
|
+
return c.json({ error: "Not found" }, 404);
|
|
987
|
+
if (existing.status === "purged" || existing.status === "expired") {
|
|
988
|
+
return c.json({ error: "Checklist is closed." }, 409);
|
|
989
|
+
}
|
|
990
|
+
const { approvedCount, justCompleted, request } = store.approveAllSubmitted(auth.workspace.id, requestId);
|
|
991
|
+
if (justCompleted) {
|
|
992
|
+
await dispatchCompletionWebhook({
|
|
993
|
+
store,
|
|
994
|
+
workspace: auth.workspace,
|
|
995
|
+
request,
|
|
996
|
+
masterKey: config.masterKey,
|
|
997
|
+
baseUrl: config.baseUrl,
|
|
998
|
+
multiTenant: config.multiTenant,
|
|
999
|
+
fetchImpl: deps.fetchImpl,
|
|
1000
|
+
lookupImpl: deps.lookupImpl,
|
|
1001
|
+
});
|
|
1002
|
+
}
|
|
1003
|
+
return c.json({ ok: true, approvedCount, status: request.status, justCompleted });
|
|
1004
|
+
});
|
|
1005
|
+
async function streamDecryptedUpload(c, uploadId, inline) {
|
|
1006
|
+
const auth = requireAuth(c);
|
|
1007
|
+
if (!auth)
|
|
1008
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
1009
|
+
const upload = store.getUploadForWorkspace(auth.workspace.id, uploadId);
|
|
1010
|
+
if (!upload)
|
|
1011
|
+
return c.json({ error: "Not found" }, 404);
|
|
1012
|
+
let plaintext;
|
|
1013
|
+
try {
|
|
1014
|
+
plaintext = await decryptStoredUpload(storage, config.masterKey, upload);
|
|
1015
|
+
}
|
|
1016
|
+
catch {
|
|
1017
|
+
return c.json({ error: "Could not decrypt file." }, 500);
|
|
1018
|
+
}
|
|
1019
|
+
store.logAudit(auth.workspace.id, upload.request_id, "operator", inline ? "upload.previewed" : "upload.downloaded", { uploadId: upload.id, canonicalName: upload.canonical_name });
|
|
1020
|
+
const headers = {
|
|
1021
|
+
"content-type": upload.detected_mime,
|
|
1022
|
+
"content-disposition": `${inline ? "inline" : "attachment"}; filename="${upload.canonical_name}"`,
|
|
1023
|
+
"x-content-type-options": "nosniff",
|
|
1024
|
+
"cache-control": "private, no-store",
|
|
1025
|
+
};
|
|
1026
|
+
if (inline) {
|
|
1027
|
+
headers["content-security-policy"] = "default-src 'none'; sandbox; frame-ancestors 'self'";
|
|
1028
|
+
headers["x-frame-options"] = "SAMEORIGIN";
|
|
1029
|
+
}
|
|
1030
|
+
return new Response(new Uint8Array(plaintext), { status: 200, headers });
|
|
1031
|
+
}
|
|
1032
|
+
app.get("/api/uploads/:uploadId/download", (c) => streamDecryptedUpload(c, c.req.param("uploadId"), false));
|
|
1033
|
+
app.get("/api/uploads/:uploadId/preview", (c) => streamDecryptedUpload(c, c.req.param("uploadId"), true));
|
|
1034
|
+
app.get("/api/requests/:id/export.zip", async (c) => {
|
|
1035
|
+
const auth = requireAuth(c);
|
|
1036
|
+
if (!auth)
|
|
1037
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
1038
|
+
const request = store.getRequestById(auth.workspace.id, c.req.param("id"));
|
|
1039
|
+
if (!request || request.status === "purged")
|
|
1040
|
+
return c.json({ error: "Not found" }, 404);
|
|
1041
|
+
const items = store.listRequestItems(request.id);
|
|
1042
|
+
const uploads = store.listUploadsForRequest(request.id);
|
|
1043
|
+
const decryptedFiles = [];
|
|
1044
|
+
const usedNames = new Set();
|
|
1045
|
+
try {
|
|
1046
|
+
for (const u of uploads) {
|
|
1047
|
+
const data = await decryptStoredUpload(storage, config.masterKey, u);
|
|
1048
|
+
let entryName = `files/${u.canonical_name}`;
|
|
1049
|
+
if (usedNames.has(entryName)) {
|
|
1050
|
+
const ext = path.extname(u.canonical_name);
|
|
1051
|
+
const stem = u.canonical_name.slice(0, u.canonical_name.length - ext.length);
|
|
1052
|
+
entryName = `files/${stem}_${u.id.slice(-4)}${ext}`;
|
|
1053
|
+
}
|
|
1054
|
+
usedNames.add(entryName);
|
|
1055
|
+
decryptedFiles.push({ entryName, data });
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
catch {
|
|
1059
|
+
return c.json({ error: "Could not decrypt one or more pack files." }, 500);
|
|
1060
|
+
}
|
|
1061
|
+
const zip = new ZipFile();
|
|
1062
|
+
const manifest = {
|
|
1063
|
+
request_id: request.id,
|
|
1064
|
+
title: request.title,
|
|
1065
|
+
client_name: request.client_name,
|
|
1066
|
+
client_email: request.client_email,
|
|
1067
|
+
status: request.status,
|
|
1068
|
+
exported_at: new Date().toISOString(),
|
|
1069
|
+
items: items.map((it) => ({
|
|
1070
|
+
section: it.section,
|
|
1071
|
+
label: it.label,
|
|
1072
|
+
kind: it.kind,
|
|
1073
|
+
validator: it.validator,
|
|
1074
|
+
status: it.status,
|
|
1075
|
+
value: it.value_encrypted
|
|
1076
|
+
? decryptField(config.masterKey, it.value_encrypted, it.id)
|
|
1077
|
+
: null,
|
|
1078
|
+
client_na: it.client_na === 1,
|
|
1079
|
+
client_note: it.client_note_encrypted
|
|
1080
|
+
? decryptField(config.masterKey, it.client_note_encrypted, `${it.id}:note`)
|
|
1081
|
+
: null,
|
|
1082
|
+
files: uploads
|
|
1083
|
+
.filter((u) => u.request_item_id === it.id)
|
|
1084
|
+
.map((u) => ({ canonical_name: u.canonical_name, sha256: u.sha256, mime: u.detected_mime })),
|
|
1085
|
+
})),
|
|
1086
|
+
};
|
|
1087
|
+
zip.addBuffer(Buffer.from(JSON.stringify(manifest, null, 2), "utf8"), "summary.json");
|
|
1088
|
+
for (const file of decryptedFiles) {
|
|
1089
|
+
zip.addBuffer(file.data, file.entryName, { compress: false });
|
|
1090
|
+
}
|
|
1091
|
+
zip.end();
|
|
1092
|
+
store.logAudit(auth.workspace.id, request.id, "operator", "request.exported_zip", {
|
|
1093
|
+
fileCount: uploads.length,
|
|
1094
|
+
});
|
|
1095
|
+
const filename = `${slugify(request.client_name, "client")}-${slugify(request.title, "pack")}.zip`;
|
|
1096
|
+
const webStream = Readable.toWeb(zip.outputStream);
|
|
1097
|
+
return new Response(webStream, {
|
|
1098
|
+
status: 200,
|
|
1099
|
+
headers: {
|
|
1100
|
+
"content-type": "application/zip",
|
|
1101
|
+
"content-disposition": `attachment; filename="${filename}"`,
|
|
1102
|
+
"x-content-type-options": "nosniff",
|
|
1103
|
+
"cache-control": "private, no-store",
|
|
1104
|
+
},
|
|
1105
|
+
});
|
|
1106
|
+
});
|
|
1107
|
+
// ---------------------------------------------------------------------------
|
|
1108
|
+
// Templates CRUD
|
|
1109
|
+
// ---------------------------------------------------------------------------
|
|
1110
|
+
app.get("/api/templates", (c) => {
|
|
1111
|
+
const auth = requireAuth(c);
|
|
1112
|
+
if (!auth)
|
|
1113
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
1114
|
+
const list = store.listTemplates(auth.workspace.id).map((t) => ({
|
|
1115
|
+
id: t.id,
|
|
1116
|
+
name: t.name,
|
|
1117
|
+
description: t.description,
|
|
1118
|
+
is_builtin: t.is_builtin === 1,
|
|
1119
|
+
items: JSON.parse(t.items_json),
|
|
1120
|
+
created_at: t.created_at,
|
|
1121
|
+
}));
|
|
1122
|
+
return c.json({ templates: list, branding: publicBranding(auth.workspace) });
|
|
1123
|
+
});
|
|
1124
|
+
app.post("/api/templates/:id/duplicate", async (c) => {
|
|
1125
|
+
const auth = requireAuth(c);
|
|
1126
|
+
if (!auth)
|
|
1127
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
1128
|
+
const body = (await c.req.json().catch(() => ({})));
|
|
1129
|
+
const dup = store.duplicateTemplate(auth.workspace.id, c.req.param("id"), body.name);
|
|
1130
|
+
if (!dup)
|
|
1131
|
+
return c.json({ error: "Template not found" }, 404);
|
|
1132
|
+
return c.json({
|
|
1133
|
+
template: {
|
|
1134
|
+
id: dup.id,
|
|
1135
|
+
name: dup.name,
|
|
1136
|
+
description: dup.description,
|
|
1137
|
+
is_builtin: dup.is_builtin === 1,
|
|
1138
|
+
items: JSON.parse(dup.items_json),
|
|
1139
|
+
created_at: dup.created_at,
|
|
1140
|
+
},
|
|
1141
|
+
}, 201);
|
|
1142
|
+
});
|
|
1143
|
+
app.post("/api/templates", async (c) => {
|
|
1144
|
+
const auth = requireAuth(c);
|
|
1145
|
+
if (!auth)
|
|
1146
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
1147
|
+
const body = (await c.req.json().catch(() => ({})));
|
|
1148
|
+
const name = String(body.name || "").trim();
|
|
1149
|
+
const description = String(body.description || "").trim();
|
|
1150
|
+
if (!name)
|
|
1151
|
+
return c.json({ error: "Template name is required." }, 400);
|
|
1152
|
+
try {
|
|
1153
|
+
const items = normalizeTemplateItems(body.items);
|
|
1154
|
+
const created = store.createTemplate(auth.workspace.id, name, description, items);
|
|
1155
|
+
return c.json({
|
|
1156
|
+
template: {
|
|
1157
|
+
id: created.id,
|
|
1158
|
+
name: created.name,
|
|
1159
|
+
description: created.description,
|
|
1160
|
+
is_builtin: created.is_builtin === 1,
|
|
1161
|
+
items,
|
|
1162
|
+
created_at: created.created_at,
|
|
1163
|
+
},
|
|
1164
|
+
}, 201);
|
|
1165
|
+
}
|
|
1166
|
+
catch (err) {
|
|
1167
|
+
return c.json({ error: err instanceof Error ? err.message : "Invalid template payload" }, 400);
|
|
1168
|
+
}
|
|
1169
|
+
});
|
|
1170
|
+
app.put("/api/templates/:id", async (c) => {
|
|
1171
|
+
const auth = requireAuth(c);
|
|
1172
|
+
if (!auth)
|
|
1173
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
1174
|
+
const body = (await c.req.json().catch(() => ({})));
|
|
1175
|
+
const name = String(body.name || "").trim();
|
|
1176
|
+
const description = String(body.description || "").trim();
|
|
1177
|
+
if (!name)
|
|
1178
|
+
return c.json({ error: "Template name is required." }, 400);
|
|
1179
|
+
try {
|
|
1180
|
+
const items = normalizeTemplateItems(body.items);
|
|
1181
|
+
const updated = store.updateTemplate(auth.workspace.id, c.req.param("id"), name, description, items);
|
|
1182
|
+
if (!updated)
|
|
1183
|
+
return c.json({ error: "Template not found" }, 404);
|
|
1184
|
+
return c.json({
|
|
1185
|
+
template: {
|
|
1186
|
+
id: updated.id,
|
|
1187
|
+
name: updated.name,
|
|
1188
|
+
description: updated.description,
|
|
1189
|
+
is_builtin: updated.is_builtin === 1,
|
|
1190
|
+
items,
|
|
1191
|
+
created_at: updated.created_at,
|
|
1192
|
+
},
|
|
1193
|
+
});
|
|
1194
|
+
}
|
|
1195
|
+
catch (err) {
|
|
1196
|
+
return c.json({ error: err instanceof Error ? err.message : "Invalid template payload" }, 400);
|
|
1197
|
+
}
|
|
1198
|
+
});
|
|
1199
|
+
app.delete("/api/templates/:id", (c) => {
|
|
1200
|
+
const auth = requireAuth(c);
|
|
1201
|
+
if (!auth)
|
|
1202
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
1203
|
+
const result = store.deleteTemplate(auth.workspace.id, c.req.param("id"));
|
|
1204
|
+
if (!result.deleted) {
|
|
1205
|
+
return c.json({ error: result.reason || "Cannot delete template" }, result.reason?.includes("Built-in") ? 400 : 404);
|
|
1206
|
+
}
|
|
1207
|
+
return c.json({ ok: true });
|
|
1208
|
+
});
|
|
1209
|
+
// ---------------------------------------------------------------------------
|
|
1210
|
+
// Settings, Readiness, Local Email Outbox & Demo Controls
|
|
1211
|
+
// ---------------------------------------------------------------------------
|
|
1212
|
+
app.get("/api/settings", (c) => {
|
|
1213
|
+
const auth = requireAuth(c);
|
|
1214
|
+
if (!auth)
|
|
1215
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
1216
|
+
const emailSummary = summarizeWorkspaceEmail(auth.workspace);
|
|
1217
|
+
return c.json({
|
|
1218
|
+
webhookUrl: auth.workspace.webhook_url || "",
|
|
1219
|
+
webhookSecret: resolveWebhookSecret(auth.workspace, config.masterKey) || "",
|
|
1220
|
+
branding: publicBranding(auth.workspace),
|
|
1221
|
+
account: {
|
|
1222
|
+
id: auth.user.id,
|
|
1223
|
+
email: auth.user.email,
|
|
1224
|
+
displayName: auth.user.display_name || "",
|
|
1225
|
+
workspaceName: auth.workspace.name,
|
|
1226
|
+
},
|
|
1227
|
+
email: emailSummary,
|
|
1228
|
+
readiness: {
|
|
1229
|
+
masterKeyConfigured: Boolean(config.masterKey && config.masterKey.byteLength === 32),
|
|
1230
|
+
masterKeySource: config.masterKeySource,
|
|
1231
|
+
masterKeyAutoGenerated: config.masterKeySource === "file",
|
|
1232
|
+
storageBackend: config.storageBackend,
|
|
1233
|
+
emailBackend: emailSummary.backend,
|
|
1234
|
+
emailFrom: emailSummary.from,
|
|
1235
|
+
cronIntervalMinutes: config.cronIntervalMinutes,
|
|
1236
|
+
defaultPurgeDays: config.defaultPurgeDays,
|
|
1237
|
+
hasDemoData: store.hasDemoData(auth.workspace.id),
|
|
1238
|
+
storageBytes: store.getWorkspaceStorageBytes(auth.workspace.id),
|
|
1239
|
+
outboxCount: store.countOutboxEmails(auth.workspace.id),
|
|
1240
|
+
},
|
|
1241
|
+
});
|
|
1242
|
+
});
|
|
1243
|
+
app.put("/api/settings/branding", async (c) => {
|
|
1244
|
+
const auth = requireAuth(c);
|
|
1245
|
+
if (!auth)
|
|
1246
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
1247
|
+
const body = (await c.req.json().catch(() => ({})));
|
|
1248
|
+
const brandColor = body.brandColor ? String(body.brandColor).trim() : null;
|
|
1249
|
+
if (brandColor && !isHexColor(brandColor)) {
|
|
1250
|
+
return c.json({ error: "Brand colour must be a hex value like #0F5243." }, 400);
|
|
1251
|
+
}
|
|
1252
|
+
const supportEmail = body.supportEmail ? String(body.supportEmail).trim().slice(0, 200) : null;
|
|
1253
|
+
if (supportEmail && !validateTextValue("email", supportEmail).valid) {
|
|
1254
|
+
return c.json({ error: "Support email is not a valid email address." }, 400);
|
|
1255
|
+
}
|
|
1256
|
+
const supportPhone = body.supportPhone ? String(body.supportPhone).trim().slice(0, 40) : null;
|
|
1257
|
+
if (supportPhone && !/^[+\d][\d\s()-]{5,}$/.test(supportPhone)) {
|
|
1258
|
+
return c.json({ error: "Support phone may only contain digits, spaces, +, ( ) and -." }, 400);
|
|
1259
|
+
}
|
|
1260
|
+
let logo;
|
|
1261
|
+
if (body.logoDataUrl === null) {
|
|
1262
|
+
logo = null;
|
|
1263
|
+
}
|
|
1264
|
+
else if (typeof body.logoDataUrl === "string") {
|
|
1265
|
+
const match = body.logoDataUrl.match(/^data:[\w/+.-]+;base64,([A-Za-z0-9+/=]+)$/);
|
|
1266
|
+
if (!match)
|
|
1267
|
+
return c.json({ error: "Logo must be a base64 data URL." }, 400);
|
|
1268
|
+
const buf = Buffer.from(match[1], "base64");
|
|
1269
|
+
if (buf.byteLength > MAX_LOGO_BYTES) {
|
|
1270
|
+
return c.json({ error: "Logo must be 200 KB or smaller." }, 400);
|
|
1271
|
+
}
|
|
1272
|
+
// Trust the bytes, not the declared type. SVG is rejected because it can carry script.
|
|
1273
|
+
const detected = detectFileSignature(buf, "logo");
|
|
1274
|
+
if (!detected || !LOGO_MIMES.has(detected.mime)) {
|
|
1275
|
+
return c.json({ error: "Logo must be a PNG, JPEG or WebP image." }, 400);
|
|
1276
|
+
}
|
|
1277
|
+
logo = { mime: detected.mime, b64: buf.toString("base64") };
|
|
1278
|
+
}
|
|
1279
|
+
store.updateWorkspaceBranding(auth.workspace.id, { brandColor, supportEmail, supportPhone, logo });
|
|
1280
|
+
return c.json({ ok: true, branding: publicBranding(store.getWorkspaceById(auth.workspace.id)) });
|
|
1281
|
+
});
|
|
1282
|
+
// Public so email clients can load it; workspace ids are unguessable and logos are not sensitive.
|
|
1283
|
+
app.get("/api/public/workspaces/:id/logo", (c) => {
|
|
1284
|
+
const ws = store.getWorkspaceById(c.req.param("id"));
|
|
1285
|
+
if (!ws?.logo_b64 || !ws.logo_mime)
|
|
1286
|
+
return c.json({ error: "Not found" }, 404);
|
|
1287
|
+
return c.body(Buffer.from(ws.logo_b64, "base64"), 200, {
|
|
1288
|
+
"content-type": ws.logo_mime,
|
|
1289
|
+
"cache-control": "public, max-age=3600",
|
|
1290
|
+
"content-security-policy": "default-src 'none'; sandbox",
|
|
1291
|
+
});
|
|
1292
|
+
});
|
|
1293
|
+
app.get("/api/validators", (c) => {
|
|
1294
|
+
if (!requireAuth(c))
|
|
1295
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
1296
|
+
return c.json({ validators: listValidators() });
|
|
1297
|
+
});
|
|
1298
|
+
app.put("/api/settings/webhook", async (c) => {
|
|
1299
|
+
const auth = requireAuth(c);
|
|
1300
|
+
if (!auth)
|
|
1301
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
1302
|
+
const body = (await c.req.json().catch(() => ({})));
|
|
1303
|
+
const webhookUrl = String(body.webhookUrl || "").trim();
|
|
1304
|
+
const webhookSecret = String(body.webhookSecret || "").trim();
|
|
1305
|
+
if (webhookUrl) {
|
|
1306
|
+
const urlErr = validateWebhookEndpoint(webhookUrl, config.multiTenant);
|
|
1307
|
+
if (urlErr)
|
|
1308
|
+
return c.json({ error: urlErr }, 400);
|
|
1309
|
+
}
|
|
1310
|
+
const encryptedSecret = webhookSecret
|
|
1311
|
+
? encryptField(config.masterKey, webhookSecret, `${auth.workspace.id}:webhook`)
|
|
1312
|
+
: null;
|
|
1313
|
+
store.updateWorkspaceWebhook(auth.workspace.id, webhookUrl || null, encryptedSecret);
|
|
1314
|
+
return c.json({ ok: true });
|
|
1315
|
+
});
|
|
1316
|
+
app.post("/api/settings/webhook/test", async (c) => {
|
|
1317
|
+
const auth = requireAuth(c);
|
|
1318
|
+
if (!auth)
|
|
1319
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
1320
|
+
const limited = enforceRateLimit(c, [{ bucket: "settingsTest", key: auth.workspace.id }], "Too many webhook test requests. Please wait and try again.");
|
|
1321
|
+
if (limited)
|
|
1322
|
+
return limited;
|
|
1323
|
+
const savedUrl = auth.workspace.webhook_url?.trim();
|
|
1324
|
+
if (savedUrl) {
|
|
1325
|
+
const urlErr = validateWebhookEndpoint(savedUrl, config.multiTenant);
|
|
1326
|
+
if (urlErr)
|
|
1327
|
+
return c.json({ ok: false, error: urlErr }, 400);
|
|
1328
|
+
}
|
|
1329
|
+
const result = await dispatchTestWebhook({
|
|
1330
|
+
workspace: auth.workspace,
|
|
1331
|
+
masterKey: config.masterKey,
|
|
1332
|
+
multiTenant: config.multiTenant,
|
|
1333
|
+
fetchImpl: deps.fetchImpl,
|
|
1334
|
+
lookupImpl: deps.lookupImpl,
|
|
1335
|
+
});
|
|
1336
|
+
if (!result.ok) {
|
|
1337
|
+
return c.json({ ok: false, status: result.status, error: result.error || `HTTP ${result.status}` }, 400);
|
|
1338
|
+
}
|
|
1339
|
+
return c.json({ ok: true, status: result.status });
|
|
1340
|
+
});
|
|
1341
|
+
app.put("/api/settings/email", async (c) => {
|
|
1342
|
+
const auth = requireAuth(c);
|
|
1343
|
+
if (!auth)
|
|
1344
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
1345
|
+
const body = (await c.req.json().catch(() => ({})));
|
|
1346
|
+
const backend = String(body.backend || "");
|
|
1347
|
+
if (backend !== "console" && backend !== "smtp" && backend !== "resend") {
|
|
1348
|
+
return c.json({ error: "Choose console, smtp, or resend for email delivery." }, 400);
|
|
1349
|
+
}
|
|
1350
|
+
const from = String(body.from || "").trim();
|
|
1351
|
+
const replyTo = String(body.replyTo || "").trim();
|
|
1352
|
+
if (hasCrLf(from) || hasCrLf(replyTo)) {
|
|
1353
|
+
return c.json({ error: "Email headers cannot contain line breaks." }, 400);
|
|
1354
|
+
}
|
|
1355
|
+
if (backend !== "console") {
|
|
1356
|
+
const fromAddr = extractAddress(from);
|
|
1357
|
+
if (!from || !validateTextValue("email", fromAddr).valid) {
|
|
1358
|
+
return c.json({ error: "Enter a valid sender email (e.g. Practice <hello@domain.com>)." }, 400);
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
else if (from && !validateTextValue("email", extractAddress(from)).valid) {
|
|
1362
|
+
return c.json({ error: "Sender email format is invalid." }, 400);
|
|
1363
|
+
}
|
|
1364
|
+
if (replyTo && !validateTextValue("email", extractAddress(replyTo)).valid) {
|
|
1365
|
+
return c.json({ error: "Reply-to address is invalid." }, 400);
|
|
1366
|
+
}
|
|
1367
|
+
const existing = resolveWorkspaceEmail(auth.workspace, config, config.masterKey);
|
|
1368
|
+
const existingWorkspace = existing.source === "workspace" ? existing : null;
|
|
1369
|
+
let encryptedSecrets = null;
|
|
1370
|
+
if (backend === "smtp") {
|
|
1371
|
+
const host = String(body.smtp?.host || "").trim();
|
|
1372
|
+
const user = String(body.smtp?.user || "").trim();
|
|
1373
|
+
const port = Number(body.smtp?.port ?? 587);
|
|
1374
|
+
const secure = Boolean(body.smtp?.secure);
|
|
1375
|
+
if (!host || hasCrLf(host) || /\s/.test(host)) {
|
|
1376
|
+
return c.json({ error: "Enter a valid SMTP host." }, 400);
|
|
1377
|
+
}
|
|
1378
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
1379
|
+
return c.json({ error: "SMTP port must be between 1 and 65535." }, 400);
|
|
1380
|
+
}
|
|
1381
|
+
if (config.multiTenant && (isPrivateOrLocalHost(host) || !MULTI_TENANT_SMTP_PORTS.has(port))) {
|
|
1382
|
+
return c.json({ error: "SMTP host must be a public hostname on a standard port (25, 465, 587, 2525) in multi-tenant mode." }, 400);
|
|
1383
|
+
}
|
|
1384
|
+
if (hasCrLf(user)) {
|
|
1385
|
+
return c.json({ error: "SMTP username cannot contain line breaks." }, 400);
|
|
1386
|
+
}
|
|
1387
|
+
const clearPass = body.smtp?.clearPass === true;
|
|
1388
|
+
const rawPass = typeof body.smtp?.pass === "string" ? body.smtp.pass : "";
|
|
1389
|
+
const sameSmtpIdentity = Boolean(existingWorkspace?.smtp &&
|
|
1390
|
+
existingWorkspace.smtp.host === host &&
|
|
1391
|
+
existingWorkspace.smtp.port === port &&
|
|
1392
|
+
existingWorkspace.smtp.user === user);
|
|
1393
|
+
const pass = clearPass
|
|
1394
|
+
? ""
|
|
1395
|
+
: rawPass.length > 0
|
|
1396
|
+
? rawPass
|
|
1397
|
+
: sameSmtpIdentity
|
|
1398
|
+
? existingWorkspace?.smtp?.pass || ""
|
|
1399
|
+
: "";
|
|
1400
|
+
const secrets = {
|
|
1401
|
+
smtpHost: host,
|
|
1402
|
+
smtpPort: port,
|
|
1403
|
+
smtpSecure: secure,
|
|
1404
|
+
smtpUser: user,
|
|
1405
|
+
smtpPass: pass,
|
|
1406
|
+
};
|
|
1407
|
+
encryptedSecrets = encryptField(config.masterKey, JSON.stringify(secrets), `${auth.workspace.id}:email`);
|
|
1408
|
+
}
|
|
1409
|
+
else if (backend === "resend") {
|
|
1410
|
+
const rawKey = typeof body.resend?.apiKey === "string" ? body.resend.apiKey.trim() : "";
|
|
1411
|
+
const apiKey = rawKey || existingWorkspace?.resendApiKey || "";
|
|
1412
|
+
if (!apiKey) {
|
|
1413
|
+
return c.json({ error: "Resend API key is required." }, 400);
|
|
1414
|
+
}
|
|
1415
|
+
if (hasCrLf(apiKey)) {
|
|
1416
|
+
return c.json({ error: "Resend API key cannot contain line breaks." }, 400);
|
|
1417
|
+
}
|
|
1418
|
+
const secrets = { resendApiKey: apiKey };
|
|
1419
|
+
encryptedSecrets = encryptField(config.masterKey, JSON.stringify(secrets), `${auth.workspace.id}:email`);
|
|
1420
|
+
}
|
|
1421
|
+
store.updateWorkspaceEmailConfig(auth.workspace.id, {
|
|
1422
|
+
emailBackend: backend,
|
|
1423
|
+
emailFrom: from || null,
|
|
1424
|
+
emailReplyTo: replyTo || null,
|
|
1425
|
+
emailConfigEncrypted: encryptedSecrets,
|
|
1426
|
+
});
|
|
1427
|
+
store.logAudit(auth.workspace.id, null, "operator", "settings.email_updated", {
|
|
1428
|
+
actorEmail: auth.user.email,
|
|
1429
|
+
backend,
|
|
1430
|
+
});
|
|
1431
|
+
const updated = store.getWorkspaceById(auth.workspace.id);
|
|
1432
|
+
return c.json({ ok: true, email: summarizeWorkspaceEmail(updated) });
|
|
1433
|
+
});
|
|
1434
|
+
app.post("/api/settings/email/test", async (c) => {
|
|
1435
|
+
const auth = requireAuth(c);
|
|
1436
|
+
if (!auth)
|
|
1437
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
1438
|
+
const limited = enforceRateLimit(c, [{ bucket: "settingsTest", key: auth.workspace.id }], "Too many test email requests. Please wait and try again.");
|
|
1439
|
+
if (limited)
|
|
1440
|
+
return limited;
|
|
1441
|
+
const body = (await c.req.json().catch(() => ({})));
|
|
1442
|
+
const to = String(body.to || auth.user.email).trim();
|
|
1443
|
+
if (!to || hasCrLf(to) || !validateTextValue("email", to).valid) {
|
|
1444
|
+
return c.json({ error: "Enter a valid recipient email." }, 400);
|
|
1445
|
+
}
|
|
1446
|
+
const resolved = resolveWorkspaceEmail(auth.workspace, config, config.masterKey);
|
|
1447
|
+
if (resolved.backend === "smtp" && !resolved.smtp?.host) {
|
|
1448
|
+
return c.json({ error: "Configure an SMTP host before sending a test email." }, 400);
|
|
1449
|
+
}
|
|
1450
|
+
if (resolved.backend === "smtp" && resolved.source === "workspace" && config.multiTenant) {
|
|
1451
|
+
const dnsErr = await assertPublicHostname(resolved.smtp.host, deps.lookupImpl);
|
|
1452
|
+
if (dnsErr) {
|
|
1453
|
+
return c.json({ ok: false, error: "SMTP host must resolve to a public address in multi-tenant mode." }, 400);
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
if (resolved.backend === "resend" && !resolved.resendApiKey) {
|
|
1457
|
+
return c.json({ error: "Configure a Resend API key before sending a test email." }, 400);
|
|
1458
|
+
}
|
|
1459
|
+
const backendLabel = resolved.backend === "console"
|
|
1460
|
+
? "Local Outbox"
|
|
1461
|
+
: resolved.backend === "smtp"
|
|
1462
|
+
? `SMTP (${resolved.smtp?.host})`
|
|
1463
|
+
: "Resend";
|
|
1464
|
+
const msg = testDeliveryEmail({
|
|
1465
|
+
brand: emailBrand(auth.workspace, config.baseUrl),
|
|
1466
|
+
backendLabel,
|
|
1467
|
+
});
|
|
1468
|
+
try {
|
|
1469
|
+
await sendEmailTracked({
|
|
1470
|
+
workspace: auth.workspace,
|
|
1471
|
+
workspaceId: auth.workspace.id,
|
|
1472
|
+
requestId: null,
|
|
1473
|
+
to,
|
|
1474
|
+
message: msg,
|
|
1475
|
+
kind: "test",
|
|
1476
|
+
});
|
|
1477
|
+
return c.json({ ok: true, backend: resolved.backend, to });
|
|
1478
|
+
}
|
|
1479
|
+
catch (err) {
|
|
1480
|
+
const detail = config.multiTenant && resolved.backend === "smtp"
|
|
1481
|
+
? "Email delivery failed. Check your SMTP host, port, credentials, and TLS settings."
|
|
1482
|
+
: err instanceof Error
|
|
1483
|
+
? err.message
|
|
1484
|
+
: "Email send failed";
|
|
1485
|
+
return c.json({ ok: false, error: detail }, 400);
|
|
1486
|
+
}
|
|
1487
|
+
});
|
|
1488
|
+
app.put("/api/account", async (c) => {
|
|
1489
|
+
const auth = requireAuth(c);
|
|
1490
|
+
if (!auth)
|
|
1491
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
1492
|
+
const body = (await c.req.json().catch(() => ({})));
|
|
1493
|
+
if (body.workspaceName !== undefined) {
|
|
1494
|
+
const nextWsName = String(body.workspaceName || "").trim();
|
|
1495
|
+
if (!nextWsName || nextWsName.length > 100) {
|
|
1496
|
+
return c.json({ error: "Practice name must be between 1 and 100 characters." }, 400);
|
|
1497
|
+
}
|
|
1498
|
+
store.updateWorkspaceName(auth.workspace.id, nextWsName);
|
|
1499
|
+
}
|
|
1500
|
+
let nextDisplayName = auth.user.display_name;
|
|
1501
|
+
if (body.displayName !== undefined) {
|
|
1502
|
+
const trimmed = String(body.displayName || "").trim();
|
|
1503
|
+
if (trimmed.length > 100) {
|
|
1504
|
+
return c.json({ error: "Display name cannot exceed 100 characters." }, 400);
|
|
1505
|
+
}
|
|
1506
|
+
nextDisplayName = trimmed || null;
|
|
1507
|
+
}
|
|
1508
|
+
let nextEmail = auth.user.email;
|
|
1509
|
+
if (body.email !== undefined) {
|
|
1510
|
+
const candidate = String(body.email || "").trim().toLowerCase();
|
|
1511
|
+
if (!candidate || hasCrLf(candidate) || !validateTextValue("email", candidate).valid) {
|
|
1512
|
+
return c.json({ error: "Enter a valid email address." }, 400);
|
|
1513
|
+
}
|
|
1514
|
+
if (candidate !== auth.user.email) {
|
|
1515
|
+
const conflict = store.getUserByEmail(candidate);
|
|
1516
|
+
if (conflict && conflict.id !== auth.user.id) {
|
|
1517
|
+
return c.json({ error: "An account with this email already exists." }, 409);
|
|
1518
|
+
}
|
|
1519
|
+
}
|
|
1520
|
+
nextEmail = candidate;
|
|
1521
|
+
}
|
|
1522
|
+
store.updateUserProfile(auth.user.id, { displayName: nextDisplayName, email: nextEmail });
|
|
1523
|
+
const updatedUser = store.getUserById(auth.user.id);
|
|
1524
|
+
const updatedWorkspace = store.getWorkspaceById(auth.workspace.id);
|
|
1525
|
+
return c.json({
|
|
1526
|
+
ok: true,
|
|
1527
|
+
user: {
|
|
1528
|
+
id: updatedUser.id,
|
|
1529
|
+
email: updatedUser.email,
|
|
1530
|
+
displayName: updatedUser.display_name,
|
|
1531
|
+
},
|
|
1532
|
+
workspace: sanitizeWorkspace(updatedWorkspace),
|
|
1533
|
+
});
|
|
1534
|
+
});
|
|
1535
|
+
app.put("/api/account/password", async (c) => {
|
|
1536
|
+
const auth = requireAuth(c);
|
|
1537
|
+
if (!auth)
|
|
1538
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
1539
|
+
const body = (await c.req.json().catch(() => ({})));
|
|
1540
|
+
const currentPassword = String(body.currentPassword || "");
|
|
1541
|
+
const newPassword = String(body.newPassword || "");
|
|
1542
|
+
if (currentPassword.length > MAX_PASSWORD_CHARS || !verifyPassword(currentPassword, auth.user.password_hash)) {
|
|
1543
|
+
return c.json({ error: "Current password is incorrect." }, 400);
|
|
1544
|
+
}
|
|
1545
|
+
if (newPassword.length < 10 || newPassword.length > MAX_PASSWORD_CHARS) {
|
|
1546
|
+
return c.json({ error: "New password must be between 10 and 256 characters." }, 400);
|
|
1547
|
+
}
|
|
1548
|
+
store.updateUserPassword(auth.user.id, hashPassword(newPassword));
|
|
1549
|
+
const currentToken = getCookie(c, SESSION_COOKIE) || "";
|
|
1550
|
+
if (currentToken) {
|
|
1551
|
+
store.deleteOtherSessions(auth.user.id, currentToken);
|
|
1552
|
+
}
|
|
1553
|
+
store.logAudit(auth.workspace.id, null, "operator", "account.password_changed", {
|
|
1554
|
+
actorEmail: auth.user.email,
|
|
1555
|
+
});
|
|
1556
|
+
return c.json({ ok: true });
|
|
1557
|
+
});
|
|
1558
|
+
app.get("/api/outbox", (c) => {
|
|
1559
|
+
const auth = requireAuth(c);
|
|
1560
|
+
if (!auth)
|
|
1561
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
1562
|
+
const resolvedEmail = resolveWorkspaceEmail(auth.workspace, config, config.masterKey);
|
|
1563
|
+
return c.json({
|
|
1564
|
+
emailBackend: resolvedEmail.backend,
|
|
1565
|
+
emails: store.listOutboxEmails(auth.workspace.id, 100),
|
|
1566
|
+
});
|
|
1567
|
+
});
|
|
1568
|
+
app.post("/api/demo/seed", async (c) => {
|
|
1569
|
+
const auth = requireAuth(c);
|
|
1570
|
+
if (!auth)
|
|
1571
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
1572
|
+
const res = await seedDemoWorkspace({
|
|
1573
|
+
store,
|
|
1574
|
+
storage,
|
|
1575
|
+
workspaceId: auth.workspace.id,
|
|
1576
|
+
masterKey: config.masterKey,
|
|
1577
|
+
baseUrl: config.baseUrl,
|
|
1578
|
+
});
|
|
1579
|
+
return c.json({ ok: true, seeded: res.seeded });
|
|
1580
|
+
});
|
|
1581
|
+
app.post("/api/demo/clear", async (c) => {
|
|
1582
|
+
const auth = requireAuth(c);
|
|
1583
|
+
if (!auth)
|
|
1584
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
1585
|
+
const { storageKeys, deletedRequests } = store.clearDemoData(auth.workspace.id);
|
|
1586
|
+
for (const key of storageKeys) {
|
|
1587
|
+
await storage.delete(key);
|
|
1588
|
+
}
|
|
1589
|
+
return c.json({ ok: true, deletedRequests, deletedFiles: storageKeys.length });
|
|
1590
|
+
});
|
|
1591
|
+
// ---------------------------------------------------------------------------
|
|
1592
|
+
// Client Magic-Link API (/api/client/:token)
|
|
1593
|
+
// ---------------------------------------------------------------------------
|
|
1594
|
+
function isClientVerified(c, req) {
|
|
1595
|
+
if (req.require_otp === 0)
|
|
1596
|
+
return true;
|
|
1597
|
+
const cookieVal = getCookie(c, `${CLIENT_COOKIE_PREFIX}${req.id}`);
|
|
1598
|
+
return store.hasValidClientSession(req.id, cookieVal);
|
|
1599
|
+
}
|
|
1600
|
+
app.get("/api/client/:token", (c) => {
|
|
1601
|
+
const token = c.req.param("token");
|
|
1602
|
+
const request = store.getRequestByMagicToken(token);
|
|
1603
|
+
if (!request)
|
|
1604
|
+
return c.json({ error: "Invalid or expired checklist link." }, 404);
|
|
1605
|
+
const workspace = store.getWorkspaceById(request.workspace_id);
|
|
1606
|
+
if (!workspace)
|
|
1607
|
+
return c.json({ error: "Not found" }, 404);
|
|
1608
|
+
if (request.status === "expired") {
|
|
1609
|
+
return c.json({ error: "This checklist link has expired." }, 410);
|
|
1610
|
+
}
|
|
1611
|
+
if (request.status === "purged") {
|
|
1612
|
+
return c.json({
|
|
1613
|
+
requiresOtp: false,
|
|
1614
|
+
workspaceName: workspace.name,
|
|
1615
|
+
branding: publicBranding(workspace),
|
|
1616
|
+
request: {
|
|
1617
|
+
id: request.id,
|
|
1618
|
+
title: request.title,
|
|
1619
|
+
status: request.status,
|
|
1620
|
+
purge_at: request.purge_at,
|
|
1621
|
+
},
|
|
1622
|
+
items: [],
|
|
1623
|
+
});
|
|
1624
|
+
}
|
|
1625
|
+
if (!isClientVerified(c, request)) {
|
|
1626
|
+
return c.json({
|
|
1627
|
+
requiresOtp: true,
|
|
1628
|
+
workspaceName: workspace.name,
|
|
1629
|
+
branding: publicBranding(workspace),
|
|
1630
|
+
request: {
|
|
1631
|
+
id: request.id,
|
|
1632
|
+
title: request.title,
|
|
1633
|
+
client_name: request.client_name,
|
|
1634
|
+
maskedEmail: maskEmail(request.client_email),
|
|
1635
|
+
status: request.status,
|
|
1636
|
+
due_at: request.due_at,
|
|
1637
|
+
},
|
|
1638
|
+
});
|
|
1639
|
+
}
|
|
1640
|
+
store.touchRequestOpened(request.id);
|
|
1641
|
+
const rawItems = store.listRequestItems(request.id);
|
|
1642
|
+
const allUploads = store.listUploadsForRequest(request.id);
|
|
1643
|
+
const items = rawItems.map((item) => {
|
|
1644
|
+
let currentValue = null;
|
|
1645
|
+
let isSensitiveMasked = false;
|
|
1646
|
+
if (item.value_encrypted) {
|
|
1647
|
+
const plain = decryptField(config.masterKey, item.value_encrypted, item.id);
|
|
1648
|
+
if (SENSITIVE_VALIDATORS.has(item.validator)) {
|
|
1649
|
+
currentValue = maskSensitiveValue(item.validator, plain);
|
|
1650
|
+
isSensitiveMasked = true;
|
|
1651
|
+
}
|
|
1652
|
+
else {
|
|
1653
|
+
currentValue = plain;
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1656
|
+
return {
|
|
1657
|
+
id: item.id,
|
|
1658
|
+
position: item.position,
|
|
1659
|
+
section: item.section,
|
|
1660
|
+
label: item.label,
|
|
1661
|
+
help_text: item.help_text,
|
|
1662
|
+
kind: item.kind,
|
|
1663
|
+
required: item.required === 1,
|
|
1664
|
+
validator: item.validator,
|
|
1665
|
+
validator_hint: getValidatorHint(item.validator) ?? null,
|
|
1666
|
+
config: JSON.parse(item.config_json),
|
|
1667
|
+
status: item.status,
|
|
1668
|
+
currentValue,
|
|
1669
|
+
isSensitiveMasked,
|
|
1670
|
+
review_note: item.review_note,
|
|
1671
|
+
client_note: item.client_note_encrypted
|
|
1672
|
+
? decryptField(config.masterKey, item.client_note_encrypted, `${item.id}:note`)
|
|
1673
|
+
: null,
|
|
1674
|
+
client_na: item.client_na === 1,
|
|
1675
|
+
updated_at: item.updated_at,
|
|
1676
|
+
uploads: allUploads
|
|
1677
|
+
.filter((u) => u.request_item_id === item.id)
|
|
1678
|
+
.map((u) => ({
|
|
1679
|
+
id: u.id,
|
|
1680
|
+
original_name: u.original_name,
|
|
1681
|
+
canonical_name: u.canonical_name,
|
|
1682
|
+
detected_mime: u.detected_mime,
|
|
1683
|
+
size_bytes: u.size_bytes,
|
|
1684
|
+
created_at: u.created_at,
|
|
1685
|
+
})),
|
|
1686
|
+
};
|
|
1687
|
+
});
|
|
1688
|
+
return c.json({
|
|
1689
|
+
requiresOtp: false,
|
|
1690
|
+
workspaceName: workspace.name,
|
|
1691
|
+
branding: publicBranding(workspace),
|
|
1692
|
+
request: {
|
|
1693
|
+
id: request.id,
|
|
1694
|
+
title: request.title,
|
|
1695
|
+
client_name: request.client_name,
|
|
1696
|
+
client_subject: request.client_subject,
|
|
1697
|
+
welcome_note: request.welcome_note,
|
|
1698
|
+
status: request.status,
|
|
1699
|
+
due_at: request.due_at,
|
|
1700
|
+
completed_at: request.completed_at,
|
|
1701
|
+
purge_at: request.purge_at,
|
|
1702
|
+
},
|
|
1703
|
+
items,
|
|
1704
|
+
});
|
|
1705
|
+
});
|
|
1706
|
+
app.post("/api/client/:token/otp/send", async (c) => {
|
|
1707
|
+
const token = c.req.param("token");
|
|
1708
|
+
const ip = extractClientIp(c, config.trustProxy);
|
|
1709
|
+
const tokenHash = sha256Hex(token);
|
|
1710
|
+
const limited = enforceRateLimit(c, [
|
|
1711
|
+
{ bucket: "otpSendIp", key: ip },
|
|
1712
|
+
{ bucket: "otpSendToken", key: tokenHash },
|
|
1713
|
+
], "Too many verification code requests. Please wait before trying again.");
|
|
1714
|
+
if (limited)
|
|
1715
|
+
return limited;
|
|
1716
|
+
const request = store.getRequestByMagicToken(token);
|
|
1717
|
+
if (!request || request.status === "purged" || request.status === "expired") {
|
|
1718
|
+
return c.json({ error: "Not found" }, 404);
|
|
1719
|
+
}
|
|
1720
|
+
if (request.require_otp !== 1) {
|
|
1721
|
+
return c.json({ error: "Verification code is not required for this checklist." }, 400);
|
|
1722
|
+
}
|
|
1723
|
+
const workspace = store.getWorkspaceById(request.workspace_id);
|
|
1724
|
+
if (!workspace)
|
|
1725
|
+
return c.json({ error: "Not found" }, 404);
|
|
1726
|
+
const { code, hash } = generateOtpCode();
|
|
1727
|
+
store.createOtpCode(request.id, hash, 15, nowFn());
|
|
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
|
+
}
|
|
1749
|
+
store.logAudit(request.workspace_id, request.id, "client", "otp.sent", {});
|
|
1750
|
+
return c.json({ ok: true, maskedEmail: maskEmail(request.client_email) });
|
|
1751
|
+
});
|
|
1752
|
+
app.post("/api/client/:token/otp/verify", async (c) => {
|
|
1753
|
+
const token = c.req.param("token");
|
|
1754
|
+
const ip = extractClientIp(c, config.trustProxy);
|
|
1755
|
+
const tokenHash = sha256Hex(token);
|
|
1756
|
+
const limited = enforceRateLimit(c, [
|
|
1757
|
+
{ bucket: "otpVerifyIp", key: ip },
|
|
1758
|
+
{ bucket: "otpVerifyToken", key: tokenHash },
|
|
1759
|
+
], "Too many verification attempts. Please wait before trying again.");
|
|
1760
|
+
if (limited)
|
|
1761
|
+
return limited;
|
|
1762
|
+
const request = store.getRequestByMagicToken(token);
|
|
1763
|
+
if (!request || request.status === "purged" || request.status === "expired") {
|
|
1764
|
+
return c.json({ error: "Not found" }, 404);
|
|
1765
|
+
}
|
|
1766
|
+
if (request.require_otp !== 1) {
|
|
1767
|
+
return c.json({ error: "Verification code is not required for this checklist." }, 400);
|
|
1768
|
+
}
|
|
1769
|
+
const body = (await c.req.json().catch(() => ({})));
|
|
1770
|
+
const submitted = String(body.code || "");
|
|
1771
|
+
const active = store.getActiveOtpCode(request.id);
|
|
1772
|
+
if (!active || active.expires_at <= new Date(nowFn()).toISOString()) {
|
|
1773
|
+
return c.json({ error: "Verification code expired. Request a new code." }, 400);
|
|
1774
|
+
}
|
|
1775
|
+
if (active.attempts >= 5) {
|
|
1776
|
+
return c.json({ error: "Too many attempts. Request a new code." }, 429);
|
|
1777
|
+
}
|
|
1778
|
+
if (!verifyOtpCode(submitted, active.code_hash)) {
|
|
1779
|
+
store.incrementOtpAttempts(active.id);
|
|
1780
|
+
if (active.attempts + 1 >= 5) {
|
|
1781
|
+
return c.json({ error: "Too many attempts. Request a new code." }, 429);
|
|
1782
|
+
}
|
|
1783
|
+
return c.json({ error: "Incorrect 6-digit code." }, 400);
|
|
1784
|
+
}
|
|
1785
|
+
store.markOtpVerified(active.id);
|
|
1786
|
+
const clientSessToken = store.createClientSession(request.id, 12);
|
|
1787
|
+
setCookie(c, `${CLIENT_COOKIE_PREFIX}${request.id}`, clientSessToken, {
|
|
1788
|
+
httpOnly: true,
|
|
1789
|
+
sameSite: "Lax",
|
|
1790
|
+
secure: secureCookie,
|
|
1791
|
+
path: "/api/client/",
|
|
1792
|
+
maxAge: 12 * 3600,
|
|
1793
|
+
});
|
|
1794
|
+
store.logAudit(request.workspace_id, request.id, "client", "otp.verified", {});
|
|
1795
|
+
return c.json({ ok: true });
|
|
1796
|
+
});
|
|
1797
|
+
app.post("/api/client/:token/items/:itemId", async (c) => {
|
|
1798
|
+
const token = c.req.param("token");
|
|
1799
|
+
const itemId = c.req.param("itemId");
|
|
1800
|
+
const request = store.getRequestByMagicToken(token);
|
|
1801
|
+
if (!request ||
|
|
1802
|
+
request.status === "purged" ||
|
|
1803
|
+
request.status === "completed" ||
|
|
1804
|
+
request.status === "expired") {
|
|
1805
|
+
return c.json({ error: "Checklist is closed." }, 403);
|
|
1806
|
+
}
|
|
1807
|
+
if (!isClientVerified(c, request)) {
|
|
1808
|
+
return c.json({ error: "Email verification required." }, 401);
|
|
1809
|
+
}
|
|
1810
|
+
const item = store.getRequestItem(request.id, itemId);
|
|
1811
|
+
if (!item)
|
|
1812
|
+
return c.json({ error: "Item not found" }, 404);
|
|
1813
|
+
if (item.status === "approved") {
|
|
1814
|
+
return c.json({ error: "Approved items are locked and cannot be modified." }, 409);
|
|
1815
|
+
}
|
|
1816
|
+
const workspace = store.getWorkspaceById(request.workspace_id);
|
|
1817
|
+
if (item.kind === "checkbox") {
|
|
1818
|
+
const body = (await c.req.json().catch(() => ({})));
|
|
1819
|
+
const isChecked = body.checked === true || body.checked === "1" || body.checked === "true";
|
|
1820
|
+
if (!isChecked) {
|
|
1821
|
+
return c.json({ error: "Please confirm the declaration checkbox." }, 400);
|
|
1822
|
+
}
|
|
1823
|
+
try {
|
|
1824
|
+
store.saveTextOrCheckboxSubmission(item.id, request.id, encryptField(config.masterKey, "confirmed", item.id));
|
|
1825
|
+
}
|
|
1826
|
+
catch (err) {
|
|
1827
|
+
if (err instanceof ClientWriteConflictError) {
|
|
1828
|
+
return c.json({ error: err.message }, err.statusCode);
|
|
1829
|
+
}
|
|
1830
|
+
throw err;
|
|
1831
|
+
}
|
|
1832
|
+
store.logAudit(request.workspace_id, request.id, "client", "item.submitted", {
|
|
1833
|
+
itemId: item.id,
|
|
1834
|
+
kind: "checkbox",
|
|
1835
|
+
});
|
|
1836
|
+
const updated = store.getRequestItem(request.id, item.id);
|
|
1837
|
+
const reqAfter = store.getRequestById(request.workspace_id, request.id);
|
|
1838
|
+
return c.json({
|
|
1839
|
+
ok: true,
|
|
1840
|
+
requestStatus: reqAfter.status,
|
|
1841
|
+
item: { status: updated.status, currentValue: "confirmed", isSensitiveMasked: false },
|
|
1842
|
+
});
|
|
1843
|
+
}
|
|
1844
|
+
if (item.kind === "text" || item.kind === "textarea") {
|
|
1845
|
+
const body = (await c.req.json().catch(() => ({})));
|
|
1846
|
+
const rawValue = String(body.value || "");
|
|
1847
|
+
const maxChars = item.kind === "textarea" ? MAX_TEXTAREA_ITEM_CHARS : MAX_TEXT_ITEM_CHARS;
|
|
1848
|
+
if (rawValue.length > maxChars) {
|
|
1849
|
+
return c.json({ error: `Value exceeds maximum length of ${maxChars} characters.` }, 400);
|
|
1850
|
+
}
|
|
1851
|
+
const check = validateTextValue(item.validator, rawValue);
|
|
1852
|
+
if (!check.valid || !check.normalised) {
|
|
1853
|
+
return c.json({ error: check.error || "Invalid value" }, 400);
|
|
1854
|
+
}
|
|
1855
|
+
try {
|
|
1856
|
+
store.saveTextOrCheckboxSubmission(item.id, request.id, encryptField(config.masterKey, check.normalised, item.id));
|
|
1857
|
+
}
|
|
1858
|
+
catch (err) {
|
|
1859
|
+
if (err instanceof ClientWriteConflictError) {
|
|
1860
|
+
return c.json({ error: err.message }, err.statusCode);
|
|
1861
|
+
}
|
|
1862
|
+
throw err;
|
|
1863
|
+
}
|
|
1864
|
+
store.logAudit(request.workspace_id, request.id, "client", "item.submitted", {
|
|
1865
|
+
itemId: item.id,
|
|
1866
|
+
kind: item.kind,
|
|
1867
|
+
validator: item.validator,
|
|
1868
|
+
});
|
|
1869
|
+
const updated = store.getRequestItem(request.id, item.id);
|
|
1870
|
+
const reqAfter = store.getRequestById(request.workspace_id, request.id);
|
|
1871
|
+
const isSensitiveMasked = SENSITIVE_VALIDATORS.has(item.validator);
|
|
1872
|
+
return c.json({
|
|
1873
|
+
ok: true,
|
|
1874
|
+
requestStatus: reqAfter.status,
|
|
1875
|
+
item: {
|
|
1876
|
+
status: updated.status,
|
|
1877
|
+
currentValue: isSensitiveMasked
|
|
1878
|
+
? maskSensitiveValue(item.validator, check.normalised)
|
|
1879
|
+
: check.normalised,
|
|
1880
|
+
isSensitiveMasked,
|
|
1881
|
+
},
|
|
1882
|
+
});
|
|
1883
|
+
}
|
|
1884
|
+
// File upload flow
|
|
1885
|
+
const ip = extractClientIp(c, config.trustProxy);
|
|
1886
|
+
const limited = enforceRateLimit(c, [
|
|
1887
|
+
{ bucket: "uploadIp", key: ip },
|
|
1888
|
+
{ bucket: "uploadToken", key: sha256Hex(token) },
|
|
1889
|
+
], "Too many file uploads. Please wait before trying again.");
|
|
1890
|
+
if (limited)
|
|
1891
|
+
return limited;
|
|
1892
|
+
const formData = await c.req.formData().catch(() => null);
|
|
1893
|
+
if (!formData) {
|
|
1894
|
+
return c.json({ error: "Invalid multipart upload payload." }, 400);
|
|
1895
|
+
}
|
|
1896
|
+
const rawFiles = formData.getAll("file").filter((v) => v instanceof File && v.size > 0);
|
|
1897
|
+
if (rawFiles.length === 0) {
|
|
1898
|
+
return c.json({ error: "Please choose at least one file to upload." }, 400);
|
|
1899
|
+
}
|
|
1900
|
+
const cfg = JSON.parse(item.config_json);
|
|
1901
|
+
if (!cfg.multiple && rawFiles.length > 1) {
|
|
1902
|
+
return c.json({ error: "This item only accepts one file at a time." }, 400);
|
|
1903
|
+
}
|
|
1904
|
+
if (rawFiles.length > MAX_FILES_PER_UPLOAD) {
|
|
1905
|
+
return c.json({ error: `Upload up to ${MAX_FILES_PER_UPLOAD} files at a time.` }, 400);
|
|
1906
|
+
}
|
|
1907
|
+
const maxFileMb = Math.min(MAX_ITEM_FILE_MB, Math.max(1, cfg.maxFileMb ?? 20));
|
|
1908
|
+
const maxBytes = maxFileMb * 1024 * 1024;
|
|
1909
|
+
const allowedMimes = resolveAllowedMimes(cfg.allowedGroups);
|
|
1910
|
+
const currentStorage = store.getWorkspaceStorageBytes(workspace.id);
|
|
1911
|
+
// Pass 1: validate every file's size, workspace quota, and magic bytes before persisting anything.
|
|
1912
|
+
let pendingBytes = 0;
|
|
1913
|
+
const preparedFiles = [];
|
|
1914
|
+
for (const file of rawFiles) {
|
|
1915
|
+
if (file.size > maxBytes) {
|
|
1916
|
+
return c.json({ error: `"${file.name}" exceeds max size of ${maxFileMb} MB.` }, 400);
|
|
1917
|
+
}
|
|
1918
|
+
if (workspace.max_storage_bytes > 0 &&
|
|
1919
|
+
currentStorage + pendingBytes + file.size > workspace.max_storage_bytes) {
|
|
1920
|
+
return c.json({ error: "Workspace storage limit reached." }, 403);
|
|
1921
|
+
}
|
|
1922
|
+
const buf = Buffer.from(await file.arrayBuffer());
|
|
1923
|
+
if (buf.byteLength > maxBytes) {
|
|
1924
|
+
return c.json({ error: `"${file.name}" exceeds max size of ${maxFileMb} MB.` }, 400);
|
|
1925
|
+
}
|
|
1926
|
+
if (workspace.max_storage_bytes > 0 &&
|
|
1927
|
+
currentStorage + pendingBytes + buf.byteLength > workspace.max_storage_bytes) {
|
|
1928
|
+
return c.json({ error: "Workspace storage limit reached." }, 403);
|
|
1929
|
+
}
|
|
1930
|
+
const detected = detectFileSignature(buf, file.name);
|
|
1931
|
+
if (!detected || !allowedMimes.includes(detected.mime)) {
|
|
1932
|
+
return c.json({
|
|
1933
|
+
error: `"${file.name}" failed file-type verification. Upload an allowed PDF, image, spreadsheet, or document.`,
|
|
1934
|
+
}, 400);
|
|
1935
|
+
}
|
|
1936
|
+
pendingBytes += buf.byteLength;
|
|
1937
|
+
preparedFiles.push({ name: file.name, buf, detected });
|
|
1938
|
+
}
|
|
1939
|
+
// Pass 2: encrypt and write all blobs first, then commit all DB rows in one atomic transaction.
|
|
1940
|
+
const writtenStorageKeys = [];
|
|
1941
|
+
const stagedUploads = [];
|
|
1942
|
+
const clientSlug = slugify(request.client_name, "client");
|
|
1943
|
+
const itemSlug = slugify(cfg.slug || item.label, "doc");
|
|
1944
|
+
let seq = store.nextUploadSeqForItem(item.id);
|
|
1945
|
+
let savedUploads;
|
|
1946
|
+
try {
|
|
1947
|
+
for (const pf of preparedFiles) {
|
|
1948
|
+
const uploadId = generateId("upl");
|
|
1949
|
+
const canonicalName = `${clientSlug}_${itemSlug}_${String(seq).padStart(2, "0")}.${pf.detected.ext}`;
|
|
1950
|
+
seq += 1;
|
|
1951
|
+
const storageKey = `${workspace.id}/${request.id}/${item.id}/${uploadId}_${canonicalName}.enc`;
|
|
1952
|
+
const { ciphertext, meta } = encryptBuffer(config.masterKey, pf.buf, storageKey);
|
|
1953
|
+
await storage.put(storageKey, ciphertext);
|
|
1954
|
+
writtenStorageKeys.push(storageKey);
|
|
1955
|
+
stagedUploads.push({
|
|
1956
|
+
id: uploadId,
|
|
1957
|
+
itemId: item.id,
|
|
1958
|
+
requestId: request.id,
|
|
1959
|
+
originalName: pf.name.slice(0, 200),
|
|
1960
|
+
canonicalName,
|
|
1961
|
+
detectedMime: pf.detected.mime,
|
|
1962
|
+
sizeBytes: meta.sizeBytes,
|
|
1963
|
+
storageKey,
|
|
1964
|
+
encVersion: meta.version,
|
|
1965
|
+
ivHex: meta.ivHex,
|
|
1966
|
+
tagHex: meta.tagHex,
|
|
1967
|
+
saltHex: meta.saltHex,
|
|
1968
|
+
sha256Hex: meta.sha256Hex,
|
|
1969
|
+
});
|
|
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
|
+
}));
|
|
1980
|
+
}
|
|
1981
|
+
catch (err) {
|
|
1982
|
+
for (const k of writtenStorageKeys) {
|
|
1983
|
+
await storage.delete(k).catch(() => { });
|
|
1984
|
+
}
|
|
1985
|
+
if (err instanceof ClientWriteConflictError) {
|
|
1986
|
+
return c.json({ error: err.message }, err.statusCode);
|
|
1987
|
+
}
|
|
1988
|
+
throw err;
|
|
1989
|
+
}
|
|
1990
|
+
if (!cfg.multiple && savedUploads.length > 0) {
|
|
1991
|
+
const oldKeys = store.deleteOtherUploadsForItem(request.id, item.id, savedUploads[0].id);
|
|
1992
|
+
for (const oldKey of oldKeys) {
|
|
1993
|
+
await storage.delete(oldKey).catch(() => { });
|
|
1994
|
+
}
|
|
1995
|
+
}
|
|
1996
|
+
store.logAudit(request.workspace_id, request.id, "client", "item.files_uploaded", {
|
|
1997
|
+
itemId: item.id,
|
|
1998
|
+
count: savedUploads.length,
|
|
1999
|
+
});
|
|
2000
|
+
const reqAfter = store.getRequestById(request.workspace_id, request.id);
|
|
2001
|
+
return c.json({
|
|
2002
|
+
ok: true,
|
|
2003
|
+
requestStatus: reqAfter.status,
|
|
2004
|
+
uploads: savedUploads,
|
|
2005
|
+
});
|
|
2006
|
+
});
|
|
2007
|
+
/** Shared guard for client writes: open request, verified client, item not locked. */
|
|
2008
|
+
function resolveClientWrite(c, itemId) {
|
|
2009
|
+
const request = store.getRequestByMagicToken(c.req.param("token") ?? "");
|
|
2010
|
+
if (!request ||
|
|
2011
|
+
request.status === "purged" ||
|
|
2012
|
+
request.status === "completed" ||
|
|
2013
|
+
request.status === "expired") {
|
|
2014
|
+
return { error: c.json({ error: "Checklist is closed." }, 403) };
|
|
2015
|
+
}
|
|
2016
|
+
if (!isClientVerified(c, request)) {
|
|
2017
|
+
return { error: c.json({ error: "Email verification required." }, 401) };
|
|
2018
|
+
}
|
|
2019
|
+
const item = store.getRequestItem(request.id, itemId);
|
|
2020
|
+
if (!item)
|
|
2021
|
+
return { error: c.json({ error: "Item not found" }, 404) };
|
|
2022
|
+
if (item.status === "approved") {
|
|
2023
|
+
return { error: c.json({ error: "Approved items are locked and cannot be modified." }, 409) };
|
|
2024
|
+
}
|
|
2025
|
+
return { request, item };
|
|
2026
|
+
}
|
|
2027
|
+
app.put("/api/client/:token/items/:itemId/note", async (c) => {
|
|
2028
|
+
const resolved = resolveClientWrite(c, c.req.param("itemId"));
|
|
2029
|
+
if (resolved.error)
|
|
2030
|
+
return resolved.error;
|
|
2031
|
+
const { request, item } = resolved;
|
|
2032
|
+
const body = (await c.req.json().catch(() => ({})));
|
|
2033
|
+
const note = String(body.note ?? "").trim();
|
|
2034
|
+
const notApplicable = body.notApplicable === true;
|
|
2035
|
+
if (note.length > MAX_CLIENT_NOTE_CHARS) {
|
|
2036
|
+
return c.json({ error: `Notes are limited to ${MAX_CLIENT_NOTE_CHARS} characters.` }, 400);
|
|
2037
|
+
}
|
|
2038
|
+
if (notApplicable && !note) {
|
|
2039
|
+
return c.json({ error: "Tell us briefly why this does not apply." }, 400);
|
|
2040
|
+
}
|
|
2041
|
+
try {
|
|
2042
|
+
store.setClientNote(item.id, request.id, note ? encryptField(config.masterKey, note, `${item.id}:note`) : null, notApplicable);
|
|
2043
|
+
}
|
|
2044
|
+
catch (err) {
|
|
2045
|
+
if (err instanceof ClientWriteConflictError) {
|
|
2046
|
+
return c.json({ error: err.message }, err.statusCode);
|
|
2047
|
+
}
|
|
2048
|
+
throw err;
|
|
2049
|
+
}
|
|
2050
|
+
store.logAudit(request.workspace_id, request.id, "client", notApplicable ? "item.marked_na" : "item.note_saved", {
|
|
2051
|
+
itemId: item.id,
|
|
2052
|
+
});
|
|
2053
|
+
const updated = store.getRequestItem(request.id, item.id);
|
|
2054
|
+
const reqAfter = store.getRequestById(request.workspace_id, request.id);
|
|
2055
|
+
return c.json({
|
|
2056
|
+
ok: true,
|
|
2057
|
+
requestStatus: reqAfter.status,
|
|
2058
|
+
item: { status: updated.status, client_note: note || null, client_na: updated.client_na === 1 },
|
|
2059
|
+
});
|
|
2060
|
+
});
|
|
2061
|
+
app.delete("/api/client/:token/uploads/:uploadId", async (c) => {
|
|
2062
|
+
const request = store.getRequestByMagicToken(c.req.param("token"));
|
|
2063
|
+
if (!request)
|
|
2064
|
+
return c.json({ error: "File not found" }, 404);
|
|
2065
|
+
if (request.status === "purged" || request.status === "completed" || request.status === "expired") {
|
|
2066
|
+
return c.json({ error: "Checklist is closed." }, 403);
|
|
2067
|
+
}
|
|
2068
|
+
if (!isClientVerified(c, request)) {
|
|
2069
|
+
return c.json({ error: "Email verification required." }, 401);
|
|
2070
|
+
}
|
|
2071
|
+
const upload = store.getUploadForRequest(request.id, c.req.param("uploadId"));
|
|
2072
|
+
if (!upload)
|
|
2073
|
+
return c.json({ error: "File not found" }, 404);
|
|
2074
|
+
const resolved = resolveClientWrite(c, upload.request_item_id);
|
|
2075
|
+
if (resolved.error)
|
|
2076
|
+
return resolved.error;
|
|
2077
|
+
let removed;
|
|
2078
|
+
try {
|
|
2079
|
+
removed = store.deleteUpload(request.id, upload.id);
|
|
2080
|
+
}
|
|
2081
|
+
catch (err) {
|
|
2082
|
+
if (err instanceof ClientWriteConflictError) {
|
|
2083
|
+
return c.json({ error: err.message }, err.statusCode);
|
|
2084
|
+
}
|
|
2085
|
+
throw err;
|
|
2086
|
+
}
|
|
2087
|
+
if (removed)
|
|
2088
|
+
await storage.delete(removed.storageKey);
|
|
2089
|
+
store.logAudit(request.workspace_id, request.id, "client", "item.file_removed", {
|
|
2090
|
+
itemId: upload.request_item_id,
|
|
2091
|
+
originalName: upload.original_name,
|
|
2092
|
+
});
|
|
2093
|
+
const updated = store.getRequestItem(request.id, upload.request_item_id);
|
|
2094
|
+
const reqAfter = store.getRequestById(request.workspace_id, request.id);
|
|
2095
|
+
return c.json({ ok: true, requestStatus: reqAfter.status, item: { status: updated.status } });
|
|
2096
|
+
});
|
|
2097
|
+
app.all("/api/*", (c) => c.json({ error: "Not found" }, 404));
|
|
2098
|
+
// ---------------------------------------------------------------------------
|
|
2099
|
+
// Compiled Vite SPA Static Assets + Deep-Link Fallback
|
|
2100
|
+
// ---------------------------------------------------------------------------
|
|
2101
|
+
if (fs.existsSync(clientDistDir)) {
|
|
2102
|
+
app.use("/*", serveStatic({
|
|
2103
|
+
root: clientDistDir,
|
|
2104
|
+
onFound: (filePath, c) => {
|
|
2105
|
+
const normalized = filePath.replace(/\\/g, "/");
|
|
2106
|
+
if (normalized.includes("/assets/")) {
|
|
2107
|
+
c.header("Cache-Control", "public, max-age=31536000, immutable");
|
|
2108
|
+
}
|
|
2109
|
+
else if (normalized.endsWith("/index.html")) {
|
|
2110
|
+
c.header("Cache-Control", "no-cache");
|
|
2111
|
+
}
|
|
2112
|
+
},
|
|
2113
|
+
}));
|
|
2114
|
+
}
|
|
2115
|
+
app.get("*", (c) => {
|
|
2116
|
+
const indexPath = path.join(clientDistDir, "index.html");
|
|
2117
|
+
if (!fs.existsSync(indexPath)) {
|
|
2118
|
+
return c.text("GatherGate frontend bundle not built. Run npm run build.", 503);
|
|
2119
|
+
}
|
|
2120
|
+
return c.body(fs.readFileSync(indexPath), 200, {
|
|
2121
|
+
"content-type": "text/html; charset=utf-8",
|
|
2122
|
+
"cache-control": "no-cache",
|
|
2123
|
+
});
|
|
2124
|
+
});
|
|
2125
|
+
return { app, store };
|
|
2126
|
+
}
|