@formancy/server 0.1.0 → 0.2.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.
@@ -0,0 +1,1464 @@
1
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
2
+ import Fastify from "fastify";
3
+ import rateLimit from "@fastify/rate-limit";
4
+ import { auditedBy, authenticateApiKey, authenticateLocal, can, collectAbandonedFiles, createApiKey, createLocalUser, createSubmission, decodeSolution, exportCsv, healthOf, listForms, listSubmissions, listVersions, mintChallenge, offerUpload, publishForm, replayDelivery, resolveForm, resumeDraft, saveDraft, setFormAccess, startDraft, verifySolution } from "@formancy/server-core";
5
+ import { hash, verify } from "@node-rs/argon2";
6
+ import { SignJWT, jwtVerify } from "jose";
7
+ import { and, desc, eq, inArray, lt, lte, max, ne } from "drizzle-orm";
8
+ import { drizzle } from "drizzle-orm/postgres-js";
9
+ import { integer, jsonb, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
10
+ import { createReadStream } from "node:fs";
11
+ import { mkdir, rm, stat, writeFile } from "node:fs/promises";
12
+ import { dirname, join, resolve, sep } from "node:path";
13
+ //#region src/auth-runtime.ts
14
+ /**
15
+ * The real cryptography, confined to the composition root: argon2id for
16
+ * secrets at rest, an HMAC-signed short-lived access token for sessions, and
17
+ * a CSPRNG for API keys. server-core never sees any of this — it is handed
18
+ * hash/verify/random functions and stays deterministic under test.
19
+ *
20
+ * HS256 rather than EdDSA for the session token, deliberately for this phase:
21
+ * one secret in one env var is the self-hosting story a single-container
22
+ * deployment can operate, and the signing scheme is an implementation detail
23
+ * of a token that lives fifteen minutes. Revisit with key rotation.
24
+ */
25
+ function realSecretHashing() {
26
+ return {
27
+ hashSecret: (secret) => hash(secret),
28
+ verifySecret: async (secret, digest) => {
29
+ try {
30
+ return await verify(digest, secret);
31
+ } catch {
32
+ return false;
33
+ }
34
+ }
35
+ };
36
+ }
37
+ function realRandomToken() {
38
+ return randomBytes(30).toString("base64url");
39
+ }
40
+ const TOKEN_LIFETIME = "15m";
41
+ function createSessionTokens(secret) {
42
+ if (secret.length < 32) throw new Error("FORMANCY_AUTH_SECRET must be at least 32 characters. Generate one: openssl rand -base64 33");
43
+ const key = new TextEncoder().encode(secret);
44
+ return {
45
+ async issue(actor) {
46
+ return new SignJWT({
47
+ role: actor.role,
48
+ kind: actor.kind
49
+ }).setProtectedHeader({ alg: "HS256" }).setSubject(actor.id).setIssuedAt().setExpirationTime(TOKEN_LIFETIME).sign(key);
50
+ },
51
+ async verify(token) {
52
+ try {
53
+ const { payload } = await jwtVerify(token, key, { algorithms: ["HS256"] });
54
+ const role = payload["role"];
55
+ const kind = payload["kind"];
56
+ if (typeof payload.sub !== "string" || role !== "admin" && role !== "editor" && role !== "viewer" || kind !== "user" && kind !== "apiKey") return;
57
+ return {
58
+ id: payload.sub,
59
+ role,
60
+ kind
61
+ };
62
+ } catch {
63
+ return;
64
+ }
65
+ }
66
+ };
67
+ }
68
+ //#endregion
69
+ //#region src/app.ts
70
+ const SCHEMA_HASH_HEADER = "x-formancy-schema-hash";
71
+ /** Base64 JSON, the shape an ALTCHA client already produces. */
72
+ const CHALLENGE_HEADER = "x-formancy-challenge";
73
+ /** Proves the bearer started this draft. Lower-case: Fastify normalises. */
74
+ const DRAFT_TOKEN_HEADER = "x-formancy-draft-token";
75
+ const API_KEY_HEADER = "x-formancy-api-key";
76
+ /**
77
+ * The HTTP surface, split into two planes.
78
+ *
79
+ * PUBLIC — what a person filling a form needs: resolve, submit, drafts. These
80
+ * stay unauthenticated by design; anonymous-submission hardening is its own
81
+ * upcoming step and is opt-in per form.
82
+ *
83
+ * MANAGEMENT — everything an operator does: publish, catalog, submissions,
84
+ * export, users, keys. Authenticated via a session token (login) or an API
85
+ * key header, authorized through server-core's one-table can().
86
+ *
87
+ * This file is the composition root, so THIS is where ambient reality enters:
88
+ * randomUUID, the real clock, argon2 and the CSPRNG. Everything below stays
89
+ * injected and replayable.
90
+ */
91
+ async function createApp(storage, options) {
92
+ const app = Fastify({
93
+ logger: false,
94
+ bodyLimit: options.bodyLimitBytes ?? 262144
95
+ });
96
+ const maxFileBytes = options.maxFileBytes ?? 10485760;
97
+ const fileStore = options.fileStore;
98
+ app.addContentTypeParser("*", {
99
+ parseAs: "buffer",
100
+ bodyLimit: maxFileBytes
101
+ }, (_request, body, done) => {
102
+ done(null, body);
103
+ });
104
+ const submissionLimit = options.submissionRateLimit ?? {
105
+ max: 30,
106
+ timeWindowMs: 6e4
107
+ };
108
+ const loginLimit = options.loginRateLimit ?? {
109
+ max: 10,
110
+ timeWindowMs: 6e4
111
+ };
112
+ const challengeSecret = options.challengeSecret;
113
+ await app.register(rateLimit, {
114
+ global: false,
115
+ max: submissionLimit.max,
116
+ timeWindow: submissionLimit.timeWindowMs
117
+ });
118
+ const deps = {
119
+ storage,
120
+ newId: () => randomUUID(),
121
+ nowIso: () => (/* @__PURE__ */ new Date()).toISOString(),
122
+ draftSecret: options.authSecret,
123
+ ...options.optionsSources === void 0 ? {} : { optionsSources: options.optionsSources },
124
+ capabilities: {
125
+ now: () => Date.now(),
126
+ today: () => (/* @__PURE__ */ new Date()).toISOString().slice(0, 10),
127
+ random: () => Math.random()
128
+ }
129
+ };
130
+ const authDeps = {
131
+ storage,
132
+ newId: deps.newId,
133
+ nowIso: deps.nowIso,
134
+ randomToken: realRandomToken,
135
+ ...realSecretHashing()
136
+ };
137
+ const sessions = createSessionTokens(options.authSecret);
138
+ if (options.bootstrapAdmin !== void 0) {
139
+ if (await storage.getUserByEmail(options.bootstrapAdmin.email) === void 0) {
140
+ const outcome = await createLocalUser(authDeps, {
141
+ ...options.bootstrapAdmin,
142
+ role: "admin"
143
+ });
144
+ if (!outcome.ok) throw new Error(`Bootstrap admin rejected: ${outcome.message}`);
145
+ }
146
+ }
147
+ async function actorOf(request) {
148
+ const bearer = request.headers.authorization;
149
+ if (typeof bearer === "string" && bearer.startsWith("Bearer ")) return sessions.verify(bearer.slice(7));
150
+ const apiKey = request.headers[API_KEY_HEADER];
151
+ if (typeof apiKey === "string" && apiKey !== "") {
152
+ const outcome = await authenticateApiKey(authDeps, apiKey);
153
+ return outcome.ok ? outcome.actor : void 0;
154
+ }
155
+ }
156
+ /** 401 without an identity, 403 with one that lacks the permission — the
157
+ * difference tells a client whether to log in or to give up. */
158
+ function requires(action) {
159
+ return async (request, reply) => {
160
+ const actor = await actorOf(request);
161
+ if (actor === void 0) return reply.code(401).send({ error: "unauthenticated" });
162
+ if (!can(actor, action)) return reply.code(403).send({
163
+ error: "forbidden",
164
+ action
165
+ });
166
+ request.actor = actor;
167
+ };
168
+ }
169
+ /**
170
+ * Append an audit row for something that has already happened.
171
+ *
172
+ * Never throws. An export that succeeded and an audit row that did not is
173
+ * bad; an export that 500s because the audit row failed, after the rows have
174
+ * already been written to the response, is worse and helps nobody. So the
175
+ * failure is logged loudly at error level and the request stands.
176
+ *
177
+ * For a mutation that HAS a transaction, do not use this — pass the entry
178
+ * into that call so the two commit together. `insertSubmission` is currently
179
+ * the only one.
180
+ */
181
+ async function audit(request, draft) {
182
+ const actor = request.actor;
183
+ try {
184
+ await deps.storage.recordAudit({
185
+ id: deps.newId(),
186
+ at: deps.nowIso(),
187
+ requestId: request.id,
188
+ ...auditedBy(actor, draft)
189
+ });
190
+ } catch (error) {
191
+ request.log.error({
192
+ err: error,
193
+ action: draft.action
194
+ }, "audit row could not be written");
195
+ }
196
+ }
197
+ app.post("/auth/login", { config: { rateLimit: {
198
+ max: loginLimit.max,
199
+ timeWindow: loginLimit.timeWindowMs
200
+ } } }, async (request, reply) => {
201
+ const body = request.body;
202
+ if (body === null || typeof body.email !== "string" || typeof body.password !== "string") return reply.code(400).send({
203
+ error: "bad_request",
204
+ message: "Body needs { email, password }."
205
+ });
206
+ const outcome = await authenticateLocal(authDeps, {
207
+ email: body.email,
208
+ password: body.password
209
+ });
210
+ if (!outcome.ok) {
211
+ await audit(request, {
212
+ action: "auth.login.failed",
213
+ subject: body.email
214
+ });
215
+ return reply.code(401).send({ error: "invalid_credentials" });
216
+ }
217
+ await audit(request, {
218
+ action: "auth.login",
219
+ subject: body.email,
220
+ actorKind: "user",
221
+ actorId: outcome.actor.id
222
+ });
223
+ return reply.send({
224
+ token: await sessions.issue(outcome.actor),
225
+ role: outcome.actor.role
226
+ });
227
+ });
228
+ app.post("/users", { preHandler: requires("user.create") }, async (request, reply) => {
229
+ const body = request.body;
230
+ if (body === null || typeof body.email !== "string" || typeof body.password !== "string" || body.role !== "admin" && body.role !== "editor" && body.role !== "viewer") return reply.code(400).send({
231
+ error: "bad_request",
232
+ message: "Body needs { email, password, role }."
233
+ });
234
+ const outcome = await createLocalUser(authDeps, {
235
+ email: body.email,
236
+ password: body.password,
237
+ role: body.role
238
+ });
239
+ if (!outcome.ok) return reply.code(422).send({
240
+ error: "rejected",
241
+ message: outcome.message
242
+ });
243
+ return reply.code(201).send({ id: outcome.id });
244
+ });
245
+ app.post("/api-keys", { preHandler: requires("apiKey.create") }, async (request, reply) => {
246
+ const body = request.body;
247
+ if (body === null || typeof body.name !== "string" || body.role !== "admin" && body.role !== "editor" && body.role !== "viewer") return reply.code(400).send({
248
+ error: "bad_request",
249
+ message: "Body needs { name, role }."
250
+ });
251
+ const outcome = await createApiKey(authDeps, {
252
+ name: body.name,
253
+ role: body.role
254
+ });
255
+ if (!outcome.ok) return reply.code(422).send({
256
+ error: "rejected",
257
+ message: outcome.message
258
+ });
259
+ return reply.code(201).send({
260
+ id: outcome.id,
261
+ secret: outcome.secret
262
+ });
263
+ });
264
+ app.post("/forms", { preHandler: requires("form.publish") }, async (request, reply) => {
265
+ const body = request.body;
266
+ if (body === null || typeof body.path !== "string" || body.path === "" || body.schema === void 0) return reply.code(400).send({
267
+ error: "bad_request",
268
+ message: "Body needs { path, schema }."
269
+ });
270
+ const outcome = await publishForm(deps, {
271
+ path: body.path,
272
+ schema: body.schema,
273
+ actor: request.actor
274
+ });
275
+ if (!outcome.ok) switch (outcome.kind) {
276
+ case "invalid_schema": return reply.code(422).send({
277
+ error: outcome.kind,
278
+ errors: outcome.errors
279
+ });
280
+ case "unsafe_pattern": return reply.code(422).send({
281
+ error: outcome.kind,
282
+ patterns: outcome.patterns
283
+ });
284
+ case "invalid_logic": return reply.code(422).send({
285
+ error: outcome.kind,
286
+ message: outcome.message
287
+ });
288
+ case "unknown_options_source": return reply.code(422).send({
289
+ error: outcome.kind,
290
+ sources: outcome.sources
291
+ });
292
+ }
293
+ return reply.code(201).send({
294
+ version: outcome.version,
295
+ schemaHash: outcome.schemaHash
296
+ });
297
+ });
298
+ app.put("/f/:path/access", { preHandler: requires("form.publish") }, async (request, reply) => {
299
+ const { path } = request.params;
300
+ const body = request.body;
301
+ const submit = body?.submit;
302
+ if (submit !== "authenticated" && submit !== "public") return reply.code(400).send({
303
+ error: "invalid_access",
304
+ message: "submit must be \"authenticated\" or \"public\"."
305
+ });
306
+ const origins = body?.allowedOrigins;
307
+ if (origins !== void 0 && !(Array.isArray(origins) && origins.every((o) => typeof o === "string"))) return reply.code(400).send({
308
+ error: "invalid_access",
309
+ message: "allowedOrigins must be an array of strings, or absent for no allowlist."
310
+ });
311
+ if (!(await setFormAccess(deps, {
312
+ path,
313
+ submit,
314
+ ...origins === void 0 ? {} : { allowedOrigins: origins }
315
+ })).ok) return reply.code(404).send({ error: "unknown_form" });
316
+ await audit(request, {
317
+ action: "form.access.changed",
318
+ subject: path,
319
+ detail: {
320
+ submit,
321
+ allowedOrigins: origins === void 0 ? "unchanged" : origins.join(" ")
322
+ }
323
+ });
324
+ return reply.code(204).send();
325
+ });
326
+ /**
327
+ * The log itself.
328
+ *
329
+ * Admin only, and reading it is NOT audited. A log that records its own
330
+ * reads grows without bound from a dashboard that polls it, and the entry
331
+ * would say nothing an access log does not — the events worth recording
332
+ * are the ones that touch somebody else's data.
333
+ */
334
+ app.get("/audit", { preHandler: requires("user.create") }, async (request, reply) => {
335
+ const raw = request.query?.limit;
336
+ const asked = typeof raw === "string" ? Number.parseInt(raw, 10) : 100;
337
+ const limit = Number.isFinite(asked) ? Math.min(Math.max(asked, 1), 500) : 100;
338
+ return reply.send({ entries: await deps.storage.listAudit(limit) });
339
+ });
340
+ /**
341
+ * Webhook health, and the deliveries that died.
342
+ *
343
+ * The reason the breaker keeps its counters on the row rather than in the
344
+ * worker's memory. A self-hoster has no operations team watching a
345
+ * dashboard, so a destination refusing deliveries since Tuesday has to be
346
+ * answerable from the product — otherwise it is found when somebody asks
347
+ * why the CRM has no leads this week.
348
+ */
349
+ app.get("/webhooks", { preHandler: requires("form.publish") }, async (_request, reply) => {
350
+ const now = new Date(deps.nowIso());
351
+ const hooks = await deps.storage.listWebhooks();
352
+ return reply.send({ webhooks: hooks.map((hook) => healthOf(hook, now)) });
353
+ });
354
+ app.get("/deliveries/dead", { preHandler: requires("form.publish") }, async (request, reply) => {
355
+ const raw = request.query?.limit;
356
+ const asked = typeof raw === "string" ? Number.parseInt(raw, 10) : 50;
357
+ const limit = Number.isFinite(asked) ? Math.min(Math.max(asked, 1), 200) : 50;
358
+ const dead = await deps.storage.deadDeliveries(limit);
359
+ return reply.send({ deliveries: dead.map((delivery) => ({
360
+ id: delivery.id,
361
+ webhookId: delivery.webhookId,
362
+ submissionId: delivery.submissionId,
363
+ eventId: delivery.eventId,
364
+ attempt: delivery.attempt,
365
+ lastError: delivery.lastError
366
+ })) });
367
+ });
368
+ app.post("/deliveries/:id/replay", { preHandler: requires("form.publish") }, async (request, reply) => {
369
+ const { id } = request.params;
370
+ const outcome = await replayDelivery({
371
+ storage: deps.storage,
372
+ now: () => new Date(deps.nowIso())
373
+ }, id);
374
+ if (!outcome.ok) return outcome.kind === "unknown" ? reply.code(404).send({ error: "unknown_delivery" }) : reply.code(409).send({
375
+ error: "not_dead",
376
+ state: outcome.state,
377
+ message: "Only a dead delivery can be replayed. A pending one is already queued, and a delivered one would be sent twice."
378
+ });
379
+ await audit(request, {
380
+ action: "delivery.replayed",
381
+ subject: id,
382
+ detail: { webhookId: outcome.delivery.webhookId }
383
+ });
384
+ return reply.code(202).send({
385
+ id,
386
+ state: outcome.delivery.state
387
+ });
388
+ });
389
+ /**
390
+ * A puzzle for an anonymous visitor to solve before submitting.
391
+ *
392
+ * Public because the form is: requiring a session to obtain a challenge for
393
+ * an unauthenticated submission would be a circle. It is cheap to mint and
394
+ * stateless, so handing one out costs this server a hash.
395
+ */
396
+ app.get("/f/:path/challenge", { config: { rateLimit: {
397
+ max: submissionLimit.max,
398
+ timeWindow: submissionLimit.timeWindowMs
399
+ } } }, async (request, reply) => {
400
+ if (challengeSecret === void 0) return reply.code(404).send({ error: "challenge_not_enabled" });
401
+ const { path } = request.params;
402
+ if (await deps.storage.getFormByPath(path) === void 0) return reply.code(404).send({ error: "unknown_form" });
403
+ return reply.send(await mintChallenge({
404
+ secret: challengeSecret,
405
+ nowSeconds: Math.floor(new Date(deps.nowIso()).getTime() / 1e3)
406
+ }));
407
+ });
408
+ /**
409
+ * Check a submitted solution, and spend it.
410
+ *
411
+ * Returns the refusal to send, or undefined when it passed. The spend is
412
+ * separate from the verification and comes last: the stateless checks say
413
+ * the solution is correct, and only the database can say it has not been
414
+ * used — a correct solution stays correct, so without this one puzzle
415
+ * would buy a thousand submissions.
416
+ */
417
+ async function checkChallenge(request) {
418
+ const header = request.headers[CHALLENGE_HEADER];
419
+ if (typeof header !== "string" || header === "") return {
420
+ error: "challenge_required",
421
+ message: `This form needs a solved challenge. Ask GET /f/:path/challenge for one and return it in ${CHALLENGE_HEADER}.`
422
+ };
423
+ const solution = decodeSolution(header);
424
+ if (solution === void 0) return {
425
+ error: "challenge_malformed",
426
+ message: "The challenge header is not base64 JSON."
427
+ };
428
+ const nowSeconds = Math.floor(new Date(deps.nowIso()).getTime() / 1e3);
429
+ const verified = await verifySolution(challengeSecret, solution, nowSeconds);
430
+ if (!verified.ok) return {
431
+ error: `challenge_${verified.reason}`,
432
+ message: "The challenge was not solved. Ask for a new one and try again."
433
+ };
434
+ if (!await deps.storage.spendChallenge(verified.challenge, (/* @__PURE__ */ new Date(verified.expiresAtSeconds * 1e3)).toISOString())) return {
435
+ error: "challenge_spent",
436
+ message: "That challenge has already been used. Each one is good for one submission."
437
+ };
438
+ }
439
+ app.get("/forms", { preHandler: requires("form.read") }, async (_request, reply) => {
440
+ return reply.send({ forms: await listForms(deps) });
441
+ });
442
+ app.get("/f/:path/versions", { preHandler: requires("form.read") }, async (request, reply) => {
443
+ const { path } = request.params;
444
+ const versions = await listVersions(deps, path);
445
+ if (versions === void 0) return reply.code(404).send({ error: "unknown_form" });
446
+ return reply.send({ versions });
447
+ });
448
+ app.get("/f/:path/submissions", { preHandler: requires("submission.read") }, async (request, reply) => {
449
+ const { path } = request.params;
450
+ const listed = await listSubmissions(deps, path);
451
+ if (listed === void 0) return reply.code(404).send({ error: "unknown_form" });
452
+ await audit(request, {
453
+ action: "submission.read",
454
+ subject: path,
455
+ detail: { count: listed.length }
456
+ });
457
+ return reply.send({ submissions: listed });
458
+ });
459
+ app.get("/f/:path/submissions/export.csv", { preHandler: requires("submission.export") }, async (request, reply) => {
460
+ const { path } = request.params;
461
+ const csv = await exportCsv(deps, path);
462
+ if (csv === void 0) return reply.code(404).send({ error: "unknown_form" });
463
+ await audit(request, {
464
+ action: "submission.exported",
465
+ subject: path,
466
+ detail: { bytes: Buffer.byteLength(csv, "utf8") }
467
+ });
468
+ return reply.header("content-type", "text/csv; charset=utf-8").header("content-disposition", `attachment; filename="${path}-submissions.csv"`).send(csv);
469
+ });
470
+ /**
471
+ * Fetch a published form. The one public route deliberately NOT rate-limited.
472
+ *
473
+ * Every other unauthenticated route is: submitting, starting a draft, writing
474
+ * one, reading one, minting a challenge, asking for an upload target. Those are
475
+ * writes, or guesses, or work somebody can demand of the server. This is the
476
+ * read every visitor has to make before they can do anything at all.
477
+ *
478
+ * Limiting it by IP would refuse the form to real people sharing an address —
479
+ * an office, a school, a phone network behind CGNAT — and the failure would
480
+ * look like the form being broken rather than like a limit. That is a worse
481
+ * outcome than the cheap read it would prevent, and the read is cached by
482
+ * `schemaHash` anyway.
483
+ *
484
+ * Written down because the asymmetry is deliberate and looks like an omission.
485
+ */
486
+ app.get("/f/:path", async (request, reply) => {
487
+ const { path } = request.params;
488
+ const resolved = await resolveForm(deps, path);
489
+ if (resolved === void 0) return reply.code(404).send({ error: "unknown_form" });
490
+ return reply.send({
491
+ version: resolved.version,
492
+ schemaHash: resolved.schemaHash,
493
+ schema: resolved.schema
494
+ });
495
+ });
496
+ /**
497
+ * Start a draft, and get the only key to it.
498
+ *
499
+ * The public plane is anonymous, so a draft has no account behind it. It was
500
+ * previously addressed by an id the CALLER chose, with no check on either
501
+ * route: anybody who knew or guessed an id could read a stranger's part-filled
502
+ * form, and overwrite it — after which that person submits the substituted
503
+ * content under their own name and nothing says otherwise
504
+ * ([0062](../../../docs/decisions/0062-a-draft-carries-its-own-key.md)).
505
+ *
506
+ * So the server picks the id and signs it, and the token comes back exactly
507
+ * once. Losing it means losing the draft, which is the correct trade for the
508
+ * alternative.
509
+ */
510
+ app.post("/f/:path/drafts", { config: { rateLimit: {
511
+ max: submissionLimit.max,
512
+ timeWindow: submissionLimit.timeWindowMs
513
+ } } }, async (request, reply) => {
514
+ const { path } = request.params;
515
+ const started = await startDraft(deps, { path });
516
+ if (started === void 0) return reply.code(404).send({ error: "unknown_form" });
517
+ return reply.code(201).send(started);
518
+ });
519
+ app.put("/f/:path/drafts/:draftId", { config: { rateLimit: {
520
+ max: submissionLimit.max,
521
+ timeWindow: submissionLimit.timeWindowMs
522
+ } } }, async (request, reply) => {
523
+ const { path, draftId } = request.params;
524
+ const token = request.headers[DRAFT_TOKEN_HEADER];
525
+ if (typeof token !== "string") return reply.code(401).send({ error: "draft_token_required" });
526
+ const saved = await saveDraft(deps, {
527
+ path,
528
+ draftId,
529
+ token,
530
+ data: request.body ?? {}
531
+ });
532
+ if (saved === void 0) return reply.code(404).send({ error: "unknown_form" });
533
+ if (!saved.saved) return reply.code(403).send({ error: "draft_token_invalid" });
534
+ return reply.send({ version: saved.version });
535
+ });
536
+ app.get("/f/:path/drafts/:draftId", { config: { rateLimit: {
537
+ max: submissionLimit.max,
538
+ timeWindow: submissionLimit.timeWindowMs
539
+ } } }, async (request, reply) => {
540
+ const { path, draftId } = request.params;
541
+ const token = request.headers[DRAFT_TOKEN_HEADER];
542
+ if (typeof token !== "string") return reply.code(401).send({ error: "draft_token_required" });
543
+ const resumed = await resumeDraft(deps, {
544
+ path,
545
+ draftId,
546
+ token
547
+ });
548
+ if (resumed === void 0) return reply.code(404).send({ error: "unknown_draft" });
549
+ return reply.send(resumed);
550
+ });
551
+ /**
552
+ * Ask where to put a file.
553
+ *
554
+ * Refusing here, before a byte is sent, is the difference between rejecting
555
+ * a 2 GB upload and receiving one first. The reply carries the id the
556
+ * submission will reference and the URL to PUT the bytes to.
557
+ */
558
+ app.post("/f/:path/files", { config: { rateLimit: {
559
+ max: submissionLimit.max,
560
+ timeWindow: submissionLimit.timeWindowMs
561
+ } } }, async (request, reply) => {
562
+ if (fileStore === void 0) return reply.code(501).send({
563
+ error: "uploads_unavailable",
564
+ message: "This deployment has no file store configured, so it cannot accept uploads."
565
+ });
566
+ const { path } = request.params;
567
+ const resolved = await resolveForm(deps, path);
568
+ if (resolved === void 0) return reply.code(404).send({ error: "unknown_form" });
569
+ const form = await storage.getFormByPath(path);
570
+ if (form === void 0) return reply.code(404).send({ error: "unknown_form" });
571
+ const actor = await actorOf(request);
572
+ const origin = request.headers.origin;
573
+ const body = request.body ?? {};
574
+ const field = typeof body.field === "string" ? body.field : void 0;
575
+ const name = typeof body.name === "string" ? body.name : void 0;
576
+ const size = typeof body.size === "number" ? body.size : void 0;
577
+ const contentType = typeof body.contentType === "string" ? body.contentType : "application/octet-stream";
578
+ if (field === void 0 || name === void 0 || size === void 0) return reply.code(400).send({
579
+ error: "invalid_request",
580
+ message: "Send the field, the name and the size of the file you want to upload."
581
+ });
582
+ if (size > maxFileBytes) return reply.code(413).send({
583
+ error: "too_large",
584
+ message: `This deployment accepts files up to ${String(maxFileBytes)} bytes.`
585
+ });
586
+ const outcome = await offerUpload({
587
+ storage,
588
+ now: () => /* @__PURE__ */ new Date(),
589
+ newId: () => randomUUID()
590
+ }, {
591
+ schema: resolved.schema,
592
+ form,
593
+ actor: actor === void 0 ? "anonymous" : "authenticated",
594
+ origin: typeof origin === "string" ? origin : void 0,
595
+ field,
596
+ name,
597
+ size,
598
+ contentType
599
+ });
600
+ if (!outcome.ok) {
601
+ const status = outcome.reason === "not_allowed" ? 403 : outcome.reason === "too_large" ? 413 : 400;
602
+ return reply.code(status).send({ error: outcome.reason });
603
+ }
604
+ return reply.code(201).send({
605
+ id: outcome.file.id,
606
+ name: outcome.file.name,
607
+ size: outcome.file.size,
608
+ contentType: outcome.file.contentType,
609
+ storageKey: outcome.file.storageKey,
610
+ uploadUrl: `/f/${encodeURIComponent(path)}/files/${outcome.file.id}`
611
+ });
612
+ });
613
+ /** Receive the bytes for a file that was offered. */
614
+ app.put("/f/:path/files/:id", async (request, reply) => {
615
+ if (fileStore === void 0) return reply.code(501).send({ error: "uploads_unavailable" });
616
+ const { path, id } = request.params;
617
+ const form = await storage.getFormByPath(path);
618
+ if (form === void 0) return reply.code(404).send({ error: "unknown_form" });
619
+ const file = await storage.getFile(id);
620
+ if (file === void 0 || file.formId !== form.id) return reply.code(404).send({ error: "unknown_file" });
621
+ if (file.state !== "offered") return reply.code(409).send({ error: "already_uploaded" });
622
+ const bytes = request.body;
623
+ if (!Buffer.isBuffer(bytes)) return reply.code(400).send({ error: "no_body" });
624
+ if (bytes.byteLength > maxFileBytes) return reply.code(413).send({ error: "too_large" });
625
+ if (bytes.byteLength !== file.size) return reply.code(400).send({
626
+ error: "size_mismatch",
627
+ message: `This upload was offered as ${String(file.size)} bytes and ${String(bytes.byteLength)} arrived.`
628
+ });
629
+ await fileStore.put(file.storageKey, bytes);
630
+ await storage.updateFile({
631
+ ...file,
632
+ state: "stored"
633
+ });
634
+ return reply.code(204).send();
635
+ });
636
+ /**
637
+ * Serve a file back.
638
+ *
639
+ * Always as an attachment, never inline, and `nosniff` alongside it. Stored
640
+ * cross-site scripting through an uploaded HTML or SVG file is the most
641
+ * commonly exploited vulnerability in this product category, and the real
642
+ * answer is a separate hostname — which a single-container deployment does
643
+ * not have. Forcing a download is the accommodation, and it is the one place
644
+ * this deployment model genuinely costs something.
645
+ */
646
+ app.get("/f/:path/files/:id", async (request, reply) => {
647
+ if (fileStore === void 0) return reply.code(501).send({ error: "uploads_unavailable" });
648
+ const { path, id } = request.params;
649
+ if (await actorOf(request) === void 0) return reply.code(401).send({ error: "unauthenticated" });
650
+ const form = await storage.getFormByPath(path);
651
+ const file = await storage.getFile(id);
652
+ if (form === void 0 || file === void 0 || file.formId !== form.id) return reply.code(404).send({ error: "unknown_file" });
653
+ const stream = await fileStore.open(file.storageKey);
654
+ if (stream === void 0) return reply.code(404).send({ error: "unknown_file" });
655
+ return reply.header("content-type", "application/octet-stream").header("x-content-type-options", "nosniff").header("content-security-policy", "default-src 'none'; sandbox").header("content-disposition", `attachment; filename="${file.name.replace(/["\r\n]/g, "")}"`).send(stream);
656
+ });
657
+ app.post("/f/:path/submissions", { config: { rateLimit: {
658
+ max: submissionLimit.max,
659
+ timeWindow: submissionLimit.timeWindowMs
660
+ } } }, async (request, reply) => {
661
+ const { path } = request.params;
662
+ const declaredSchemaHash = request.headers[SCHEMA_HASH_HEADER];
663
+ if (typeof declaredSchemaHash !== "string" || declaredSchemaHash === "") return reply.code(400).send({
664
+ error: "missing_schema_hash",
665
+ message: `Send the schema hash you rendered in the ${SCHEMA_HASH_HEADER} header.`
666
+ });
667
+ const actor = await actorOf(request);
668
+ const origin = request.headers.origin;
669
+ if (challengeSecret !== void 0 && actor === void 0) {
670
+ const refusal = await checkChallenge(request);
671
+ if (refusal !== void 0) return reply.code(400).send(refusal);
672
+ }
673
+ const outcome = await createSubmission(deps, {
674
+ path,
675
+ declaredSchemaHash,
676
+ data: request.body ?? {},
677
+ actor: actor === void 0 ? "anonymous" : "authenticated",
678
+ ...typeof origin === "string" ? { origin } : {}
679
+ });
680
+ if (outcome.ok) return reply.code(201).send({
681
+ id: outcome.id,
682
+ data: outcome.canonicalData
683
+ });
684
+ switch (outcome.kind) {
685
+ case "unknown_form": return reply.code(404).send({ error: "unknown_form" });
686
+ case "version_changed": return reply.code(409).send({
687
+ error: "FORM_VERSION_CHANGED",
688
+ current: outcome.current === void 0 ? void 0 : {
689
+ version: outcome.current.version,
690
+ schemaHash: outcome.current.schemaHash,
691
+ schema: outcome.current.schema
692
+ }
693
+ });
694
+ case "invalid": return reply.code(422).send({
695
+ error: "invalid",
696
+ errors: outcome.errors
697
+ });
698
+ case "forbidden": return reply.code(403).send({ error: "forbidden" });
699
+ case "source_unavailable": return reply.code(503).send({
700
+ error: "source_unavailable",
701
+ source: outcome.source
702
+ });
703
+ }
704
+ });
705
+ return app;
706
+ }
707
+ //#endregion
708
+ //#region src/db.ts
709
+ /**
710
+ * The thin slice's tables. Three rules from the design spec are enforced HERE,
711
+ * in the database, because application code can be bypassed and these must not
712
+ * be:
713
+ *
714
+ * - published versions are immutable (a trigger refuses UPDATE),
715
+ * - a submission binds to its exact version by real foreign key,
716
+ * - that key is ON DELETE RESTRICT, so orphaning a submission from the schema
717
+ * that produced it is structurally impossible.
718
+ */
719
+ const forms = pgTable("forms", {
720
+ id: uuid("id").primaryKey(),
721
+ path: text("path").notNull().unique(),
722
+ currentVersionId: uuid("current_version_id"),
723
+ accessSubmit: text("access_submit").notNull().default("authenticated"),
724
+ allowedOrigins: text("allowed_origins").array(),
725
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
726
+ });
727
+ const formVersions = pgTable("form_versions", {
728
+ id: uuid("id").primaryKey(),
729
+ formId: uuid("form_id").notNull().references(() => forms.id),
730
+ version: integer("version").notNull(),
731
+ schema: jsonb("schema").notNull(),
732
+ schemaHash: text("schema_hash").notNull(),
733
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
734
+ });
735
+ const users = pgTable("users", {
736
+ id: uuid("id").primaryKey(),
737
+ email: text("email").notNull().unique(),
738
+ passwordHash: text("password_hash").notNull(),
739
+ role: text("role").notNull(),
740
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull()
741
+ });
742
+ const apiKeys = pgTable("api_keys", {
743
+ id: uuid("id").primaryKey(),
744
+ name: text("name").notNull(),
745
+ prefix: text("prefix").notNull(),
746
+ secretHash: text("secret_hash").notNull(),
747
+ role: text("role").notNull(),
748
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
749
+ revokedAt: timestamp("revoked_at", { withTimezone: true })
750
+ });
751
+ const drafts = pgTable("drafts", {
752
+ id: text("id").notNull(),
753
+ formId: uuid("form_id").notNull().references(() => forms.id),
754
+ formVersionId: uuid("form_version_id").notNull().references(() => formVersions.id),
755
+ data: jsonb("data").notNull(),
756
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull()
757
+ });
758
+ const webhooks = pgTable("webhooks", {
759
+ id: uuid("id").primaryKey(),
760
+ formId: uuid("form_id").notNull().references(() => forms.id),
761
+ url: text("url").notNull(),
762
+ secret: text("secret").notNull(),
763
+ consecutiveFailures: integer("consecutive_failures").notNull().default(0),
764
+ openedAt: timestamp("opened_at", { withTimezone: true })
765
+ });
766
+ /**
767
+ * The outbox. A row here and the submission that caused it are written by the
768
+ * same transaction, which is what makes "accepted" and "will be delivered" one
769
+ * decision rather than two.
770
+ */
771
+ const deliveries = pgTable("deliveries", {
772
+ id: uuid("id").primaryKey(),
773
+ webhookId: uuid("webhook_id").notNull(),
774
+ submissionId: uuid("submission_id").notNull(),
775
+ eventId: uuid("event_id").notNull(),
776
+ body: text("body").notNull(),
777
+ attempt: integer("attempt").notNull().default(0),
778
+ nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true }).notNull(),
779
+ state: text("state").notNull().default("pending"),
780
+ lastError: text("last_error")
781
+ });
782
+ const spentChallenges = pgTable("spent_challenges", {
783
+ challenge: text("challenge").primaryKey(),
784
+ expiresAt: timestamp("expires_at", { withTimezone: true }).notNull()
785
+ });
786
+ const auditLog = pgTable("audit_log", {
787
+ id: uuid("id").primaryKey(),
788
+ at: timestamp("at", { withTimezone: true }).notNull(),
789
+ action: text("action").notNull(),
790
+ actorKind: text("actor_kind"),
791
+ actorId: text("actor_id"),
792
+ subject: text("subject"),
793
+ requestId: text("request_id"),
794
+ detail: jsonb("detail")
795
+ });
796
+ const files = pgTable("files", {
797
+ id: uuid("id").primaryKey(),
798
+ formId: uuid("form_id").notNull(),
799
+ name: text("name").notNull(),
800
+ size: integer("size").notNull(),
801
+ contentType: text("content_type").notNull(),
802
+ storageKey: text("storage_key").notNull(),
803
+ state: text("state").notNull().default("offered"),
804
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
805
+ submissionId: uuid("submission_id")
806
+ });
807
+ const submissions = pgTable("submissions", {
808
+ id: uuid("id").primaryKey(),
809
+ formId: uuid("form_id").notNull().references(() => forms.id),
810
+ formVersionId: uuid("form_version_id").notNull().references(() => formVersions.id, { onDelete: "restrict" }),
811
+ data: jsonb("data").notNull(),
812
+ submittedAt: timestamp("submitted_at", { withTimezone: true }).notNull()
813
+ });
814
+ /**
815
+ * Bootstrap DDL for the thin slice — drizzle-kit migrations arrive with the
816
+ * lifecycle work; a self-hosted skeleton that creates its own tables on first
817
+ * start is worth more right now than a migration pipeline.
818
+ */
819
+ async function bootstrapSchema(sql) {
820
+ await sql`
821
+ CREATE TABLE IF NOT EXISTS forms (
822
+ id uuid PRIMARY KEY,
823
+ path text NOT NULL UNIQUE,
824
+ current_version_id uuid,
825
+ -- Private by default in the DATABASE, not only in the code, so a row
826
+ -- inserted by a migration or a fixture is not accidentally open.
827
+ access_submit text NOT NULL DEFAULT 'authenticated'
828
+ CHECK (access_submit IN ('authenticated', 'public')),
829
+ -- NULL: no allowlist in force. Empty array: nothing allowed. Different
830
+ -- things, which is why this is nullable rather than defaulting to '{}'.
831
+ allowed_origins text[],
832
+ created_at timestamptz NOT NULL DEFAULT now()
833
+ )`;
834
+ await sql`
835
+ ALTER TABLE forms
836
+ ADD COLUMN IF NOT EXISTS access_submit text NOT NULL DEFAULT 'authenticated'`;
837
+ await sql`ALTER TABLE forms ADD COLUMN IF NOT EXISTS allowed_origins text[]`;
838
+ await sql`
839
+ CREATE TABLE IF NOT EXISTS form_versions (
840
+ id uuid PRIMARY KEY,
841
+ form_id uuid NOT NULL REFERENCES forms(id),
842
+ version integer NOT NULL,
843
+ schema jsonb NOT NULL,
844
+ schema_hash text NOT NULL,
845
+ created_at timestamptz NOT NULL DEFAULT now(),
846
+ UNIQUE (form_id, version),
847
+ UNIQUE (form_id, schema_hash)
848
+ )`;
849
+ await sql`
850
+ CREATE TABLE IF NOT EXISTS submissions (
851
+ id uuid PRIMARY KEY,
852
+ form_id uuid NOT NULL REFERENCES forms(id),
853
+ form_version_id uuid NOT NULL REFERENCES form_versions(id) ON DELETE RESTRICT,
854
+ data jsonb NOT NULL,
855
+ submitted_at timestamptz NOT NULL
856
+ )`;
857
+ await sql`
858
+ CREATE TABLE IF NOT EXISTS webhooks (
859
+ id uuid PRIMARY KEY,
860
+ form_id uuid NOT NULL REFERENCES forms(id) ON DELETE CASCADE,
861
+ url text NOT NULL,
862
+ secret text NOT NULL
863
+ )`;
864
+ await sql`
865
+ ALTER TABLE webhooks
866
+ ADD COLUMN IF NOT EXISTS consecutive_failures integer NOT NULL DEFAULT 0,
867
+ -- When the breaker opened, null while the destination is answering. On
868
+ -- the row rather than in the worker's memory: memory does not survive a
869
+ -- restart, and a self-hoster with no operations team needs a failing
870
+ -- webhook to be visible on a screen rather than in a log nobody tails.
871
+ ADD COLUMN IF NOT EXISTS opened_at timestamptz`;
872
+ await sql`
873
+ CREATE TABLE IF NOT EXISTS deliveries (
874
+ id uuid PRIMARY KEY,
875
+ webhook_id uuid NOT NULL REFERENCES webhooks(id) ON DELETE CASCADE,
876
+ -- RESTRICT, not CASCADE: a delivery is the record that something was
877
+ -- sent about this submission, and deleting the submission must not
878
+ -- quietly erase it.
879
+ submission_id uuid NOT NULL REFERENCES submissions(id) ON DELETE RESTRICT,
880
+ event_id uuid NOT NULL,
881
+ body text NOT NULL,
882
+ attempt integer NOT NULL DEFAULT 0,
883
+ next_attempt_at timestamptz NOT NULL,
884
+ state text NOT NULL DEFAULT 'pending'
885
+ CHECK (state IN ('pending', 'delivered', 'dead')),
886
+ last_error text
887
+ )`;
888
+ await sql`
889
+ CREATE INDEX IF NOT EXISTS deliveries_due
890
+ ON deliveries (next_attempt_at) WHERE state = 'pending'`;
891
+ await sql`
892
+ CREATE TABLE IF NOT EXISTS files (
893
+ id uuid PRIMARY KEY,
894
+ form_id uuid NOT NULL REFERENCES forms(id) ON DELETE RESTRICT,
895
+ -- What the reader called it. Display only: the storage key is minted by
896
+ -- the server, because a key built from a submitted filename is a path
897
+ -- traversal waiting for somebody to try it.
898
+ name text NOT NULL,
899
+ size integer NOT NULL,
900
+ content_type text NOT NULL,
901
+ storage_key text NOT NULL,
902
+ state text NOT NULL DEFAULT 'offered'
903
+ CHECK (state IN ('offered', 'stored', 'claimed')),
904
+ created_at timestamptz NOT NULL,
905
+ -- RESTRICT for the same reason a delivery uses it: the row is the record
906
+ -- that something was attached, and deleting the submission must not
907
+ -- quietly erase what it carried.
908
+ submission_id uuid REFERENCES submissions(id) ON DELETE RESTRICT,
909
+ -- One file, one submission. Enforced here rather than in application
910
+ -- code, because two concurrent submissions claiming the same file is
911
+ -- exactly the race application code loses — and the loser would be a
912
+ -- submission referencing bytes another submission owns.
913
+ CONSTRAINT files_one_submission UNIQUE (id, submission_id)
914
+ )`;
915
+ await sql`
916
+ CREATE INDEX IF NOT EXISTS files_abandoned
917
+ ON files (created_at) WHERE state <> 'claimed'`;
918
+ await sql`
919
+ CREATE TABLE IF NOT EXISTS users (
920
+ id uuid PRIMARY KEY,
921
+ email text NOT NULL UNIQUE,
922
+ password_hash text NOT NULL,
923
+ role text NOT NULL,
924
+ created_at timestamptz NOT NULL
925
+ )`;
926
+ await sql`
927
+ CREATE TABLE IF NOT EXISTS api_keys (
928
+ id uuid PRIMARY KEY,
929
+ name text NOT NULL,
930
+ prefix text NOT NULL,
931
+ secret_hash text NOT NULL,
932
+ role text NOT NULL,
933
+ created_at timestamptz NOT NULL,
934
+ revoked_at timestamptz
935
+ )`;
936
+ await sql`CREATE INDEX IF NOT EXISTS api_keys_prefix ON api_keys (prefix)`;
937
+ await sql`
938
+ CREATE TABLE IF NOT EXISTS spent_challenges (
939
+ -- The primary key IS the mechanism. Two requests arriving with one
940
+ -- solution both pass every stateless check — the signature is ours
941
+ -- and the hash is right — and only the database can decide which of
942
+ -- them spends it. A read-then-write would race exactly where somebody
943
+ -- is looking.
944
+ challenge text PRIMARY KEY,
945
+ expires_at timestamptz NOT NULL
946
+ )`;
947
+ await sql`CREATE INDEX IF NOT EXISTS spent_challenges_expiry ON spent_challenges (expires_at)`;
948
+ await sql`
949
+ CREATE TABLE IF NOT EXISTS audit_log (
950
+ id uuid PRIMARY KEY,
951
+ at timestamptz NOT NULL,
952
+ action text NOT NULL,
953
+ -- Null for an anonymous public submission, which is an answer rather
954
+ -- than a gap: the form was open and nobody was signed in.
955
+ actor_kind text CHECK (actor_kind IN ('user', 'apiKey')),
956
+ actor_id text,
957
+ subject text,
958
+ request_id text,
959
+ -- Identifiers and counts. NEVER a submission's answers: an audit log is
960
+ -- read by more people and kept longer than the data it describes, so
961
+ -- data inside it is a second copy of the thing being protected.
962
+ detail jsonb
963
+ )`;
964
+ await sql`CREATE INDEX IF NOT EXISTS audit_log_at ON audit_log (at DESC)`;
965
+ await sql`CREATE INDEX IF NOT EXISTS audit_log_subject ON audit_log (subject, at DESC)`;
966
+ await sql`
967
+ CREATE TABLE IF NOT EXISTS drafts (
968
+ id text NOT NULL,
969
+ form_id uuid NOT NULL REFERENCES forms(id),
970
+ form_version_id uuid NOT NULL REFERENCES form_versions(id),
971
+ data jsonb NOT NULL,
972
+ updated_at timestamptz NOT NULL,
973
+ PRIMARY KEY (form_id, id)
974
+ )`;
975
+ await sql`
976
+ CREATE OR REPLACE FUNCTION refuse_version_update() RETURNS trigger AS $$
977
+ BEGIN
978
+ RAISE EXCEPTION 'form_versions rows are immutable; publish a new version instead';
979
+ END
980
+ $$ LANGUAGE plpgsql`;
981
+ await sql`DROP TRIGGER IF EXISTS form_versions_immutable ON form_versions`;
982
+ await sql`
983
+ CREATE TRIGGER form_versions_immutable
984
+ BEFORE UPDATE ON form_versions
985
+ FOR EACH ROW EXECUTE FUNCTION refuse_version_update()`;
986
+ await sql`
987
+ CREATE OR REPLACE FUNCTION refuse_audit_change() RETURNS trigger AS $$
988
+ BEGIN
989
+ RAISE EXCEPTION 'audit_log is append-only';
990
+ END
991
+ $$ LANGUAGE plpgsql`;
992
+ await sql`DROP TRIGGER IF EXISTS audit_log_append_only ON audit_log`;
993
+ await sql`
994
+ CREATE TRIGGER audit_log_append_only
995
+ BEFORE UPDATE OR DELETE ON audit_log
996
+ FOR EACH ROW EXECUTE FUNCTION refuse_audit_change()`;
997
+ }
998
+ //#endregion
999
+ //#region src/postgres-storage.ts
1000
+ /** The Storage port over Postgres — the mirror of server-core's in-memory one. */
1001
+ function createPostgresStorage(sql) {
1002
+ const db = drizzle(sql);
1003
+ return {
1004
+ async getFormByPath(path) {
1005
+ const row = (await db.select().from(forms).where(eq(forms.path, path)).limit(1))[0];
1006
+ if (row === void 0) return void 0;
1007
+ return {
1008
+ id: row.id,
1009
+ path: row.path,
1010
+ currentVersionId: row.currentVersionId,
1011
+ accessSubmit: row.accessSubmit === "public" ? "public" : "authenticated",
1012
+ allowedOrigins: row.allowedOrigins
1013
+ };
1014
+ },
1015
+ async listForms() {
1016
+ return (await db.select().from(forms)).map((row) => ({
1017
+ id: row.id,
1018
+ path: row.path,
1019
+ currentVersionId: row.currentVersionId,
1020
+ accessSubmit: row.accessSubmit === "public" ? "public" : "authenticated",
1021
+ allowedOrigins: row.allowedOrigins
1022
+ }));
1023
+ },
1024
+ async createForm(record) {
1025
+ await db.insert(forms).values({
1026
+ id: record.id,
1027
+ path: record.path,
1028
+ currentVersionId: record.currentVersionId,
1029
+ accessSubmit: record.accessSubmit,
1030
+ allowedOrigins: record.allowedOrigins
1031
+ });
1032
+ },
1033
+ async updateFormAccess(formId, access) {
1034
+ await db.update(forms).set({
1035
+ accessSubmit: access.accessSubmit,
1036
+ allowedOrigins: access.allowedOrigins
1037
+ }).where(eq(forms.id, formId));
1038
+ },
1039
+ async setCurrentVersion(formId, versionId) {
1040
+ await db.update(forms).set({ currentVersionId: versionId }).where(eq(forms.id, formId));
1041
+ },
1042
+ async insertVersion(record) {
1043
+ await db.insert(formVersions).values({
1044
+ id: record.id,
1045
+ formId: record.formId,
1046
+ version: record.version,
1047
+ schema: record.schema,
1048
+ schemaHash: record.schemaHash
1049
+ });
1050
+ },
1051
+ async publishVersion({ form, version, audit }) {
1052
+ await db.transaction(async (tx) => {
1053
+ if (form !== void 0) await tx.insert(forms).values({
1054
+ id: form.id,
1055
+ path: form.path,
1056
+ currentVersionId: form.currentVersionId,
1057
+ accessSubmit: form.accessSubmit,
1058
+ allowedOrigins: form.allowedOrigins
1059
+ });
1060
+ await tx.insert(formVersions).values({
1061
+ id: version.id,
1062
+ formId: version.formId,
1063
+ version: version.version,
1064
+ schema: version.schema,
1065
+ schemaHash: version.schemaHash
1066
+ });
1067
+ if ((await tx.update(forms).set({ currentVersionId: version.id }).where(eq(forms.id, version.formId)).returning({ id: forms.id })).length !== 1) throw new Error(`Publishing to form ${version.formId} matched no form row. Rolling back, so there is no version pointing at a form that is not there.`);
1068
+ if (audit !== void 0) await tx.insert(auditLog).values(auditRow(audit));
1069
+ });
1070
+ },
1071
+ async getVersionById(id) {
1072
+ const row = (await db.select().from(formVersions).where(eq(formVersions.id, id)).limit(1))[0];
1073
+ if (row === void 0) return void 0;
1074
+ return {
1075
+ id: row.id,
1076
+ formId: row.formId,
1077
+ version: row.version,
1078
+ schema: row.schema,
1079
+ schemaHash: row.schemaHash
1080
+ };
1081
+ },
1082
+ async findVersionByHash(formId, schemaHash) {
1083
+ const row = (await db.select().from(formVersions).where(eq(formVersions.formId, formId))).find((candidate) => candidate.schemaHash === schemaHash);
1084
+ if (row === void 0) return void 0;
1085
+ return {
1086
+ id: row.id,
1087
+ formId: row.formId,
1088
+ version: row.version,
1089
+ schema: row.schema,
1090
+ schemaHash: row.schemaHash
1091
+ };
1092
+ },
1093
+ async latestVersionNumber(formId) {
1094
+ return (await db.select({ latest: max(formVersions.version) }).from(formVersions).where(eq(formVersions.formId, formId)))[0]?.latest ?? 0;
1095
+ },
1096
+ async insertSubmission(record, queued, claimFileIds, audit) {
1097
+ await db.transaction(async (tx) => {
1098
+ await tx.insert(submissions).values({
1099
+ id: record.id,
1100
+ formId: record.formId,
1101
+ formVersionId: record.formVersionId,
1102
+ data: record.data,
1103
+ submittedAt: new Date(record.submittedAt)
1104
+ });
1105
+ if (queued !== void 0 && queued.length > 0) await tx.insert(deliveries).values(queued.map((delivery) => ({
1106
+ id: delivery.id,
1107
+ webhookId: delivery.webhookId,
1108
+ submissionId: delivery.submissionId,
1109
+ eventId: delivery.eventId,
1110
+ body: delivery.body,
1111
+ attempt: delivery.attempt,
1112
+ nextAttemptAt: new Date(delivery.nextAttemptAt),
1113
+ state: delivery.state,
1114
+ lastError: delivery.lastError
1115
+ })));
1116
+ if (claimFileIds !== void 0 && claimFileIds.length > 0) {
1117
+ if ((await tx.update(files).set({
1118
+ state: "claimed",
1119
+ submissionId: record.id
1120
+ }).where(and(inArray(files.id, [...claimFileIds]), eq(files.state, "stored"))).returning({ id: files.id })).length !== claimFileIds.length) throw new Error("A file this submission names was claimed by another one first. Rolling back, so the submission does not reference bytes it does not own.");
1121
+ }
1122
+ if (audit !== void 0) await tx.insert(auditLog).values(auditRow(audit));
1123
+ });
1124
+ },
1125
+ async spendChallenge(challenge, expiresAtIso) {
1126
+ return (await db.insert(spentChallenges).values({
1127
+ challenge,
1128
+ expiresAt: new Date(expiresAtIso)
1129
+ }).onConflictDoNothing().returning({ challenge: spentChallenges.challenge })).length === 1;
1130
+ },
1131
+ async forgetExpiredChallenges(beforeIso) {
1132
+ return (await db.delete(spentChallenges).where(lt(spentChallenges.expiresAt, new Date(beforeIso))).returning({ challenge: spentChallenges.challenge })).length;
1133
+ },
1134
+ async recordAudit(entry) {
1135
+ await db.insert(auditLog).values(auditRow(entry));
1136
+ },
1137
+ async listAudit(limit) {
1138
+ return (await db.select().from(auditLog).orderBy(desc(auditLog.at)).limit(limit)).map((row) => ({
1139
+ id: row.id,
1140
+ at: row.at.toISOString(),
1141
+ action: row.action,
1142
+ ...row.actorKind === null ? {} : { actorKind: row.actorKind },
1143
+ ...row.actorId === null ? {} : { actorId: row.actorId },
1144
+ ...row.subject === null ? {} : { subject: row.subject },
1145
+ ...row.requestId === null ? {} : { requestId: row.requestId },
1146
+ ...row.detail === null ? {} : { detail: row.detail }
1147
+ }));
1148
+ },
1149
+ async insertFile(record) {
1150
+ await db.insert(files).values({
1151
+ ...record,
1152
+ createdAt: new Date(record.createdAt)
1153
+ });
1154
+ },
1155
+ async getFile(id) {
1156
+ const [row] = await db.select().from(files).where(eq(files.id, id)).limit(1);
1157
+ return row === void 0 ? void 0 : toFileRecord(row);
1158
+ },
1159
+ async updateFile(record) {
1160
+ await db.update(files).set({
1161
+ state: record.state,
1162
+ submissionId: record.submissionId
1163
+ }).where(eq(files.id, record.id));
1164
+ },
1165
+ async abandonedFiles(beforeIso) {
1166
+ return (await db.select().from(files).where(and(ne(files.state, "claimed"), lt(files.createdAt, new Date(beforeIso))))).map(toFileRecord);
1167
+ },
1168
+ async deleteFiles(ids) {
1169
+ if (ids.length === 0) return;
1170
+ await db.delete(files).where(inArray(files.id, [...ids]));
1171
+ },
1172
+ async webhooksForForm(formId) {
1173
+ return (await db.select().from(webhooks).where(eq(webhooks.formId, formId))).map(toWebhookRecord);
1174
+ },
1175
+ async insertWebhook(record) {
1176
+ await db.insert(webhooks).values({
1177
+ id: record.id,
1178
+ formId: record.formId,
1179
+ url: record.url,
1180
+ secret: record.secret,
1181
+ consecutiveFailures: record.consecutiveFailures,
1182
+ openedAt: record.openedAt === null ? null : new Date(record.openedAt)
1183
+ });
1184
+ },
1185
+ async updateWebhook(record) {
1186
+ await db.update(webhooks).set({
1187
+ consecutiveFailures: record.consecutiveFailures,
1188
+ openedAt: record.openedAt === null ? null : new Date(record.openedAt)
1189
+ }).where(eq(webhooks.id, record.id));
1190
+ },
1191
+ async listWebhooks() {
1192
+ return (await db.select().from(webhooks)).map(toWebhookRecord);
1193
+ },
1194
+ async deadDeliveries(limit) {
1195
+ return (await db.select().from(deliveries).where(eq(deliveries.state, "dead")).orderBy(desc(deliveries.nextAttemptAt)).limit(limit)).map(toDeliveryRecord);
1196
+ },
1197
+ async getDelivery(id) {
1198
+ const [row] = await db.select().from(deliveries).where(eq(deliveries.id, id)).limit(1);
1199
+ return row === void 0 ? void 0 : toDeliveryRecord(row);
1200
+ },
1201
+ async claimDueDeliveries(nowIso, limit) {
1202
+ return (await db.select().from(deliveries).where(and(eq(deliveries.state, "pending"), lte(deliveries.nextAttemptAt, new Date(nowIso)))).orderBy(deliveries.nextAttemptAt).limit(limit)).map(toDeliveryRecord);
1203
+ },
1204
+ async updateDelivery(record) {
1205
+ await db.update(deliveries).set({
1206
+ attempt: record.attempt,
1207
+ nextAttemptAt: new Date(record.nextAttemptAt),
1208
+ state: record.state,
1209
+ lastError: record.lastError
1210
+ }).where(eq(deliveries.id, record.id));
1211
+ },
1212
+ async listSubmissions() {
1213
+ return (await db.select().from(submissions)).map(toSubmissionRecord);
1214
+ },
1215
+ async listSubmissionsByForm(formId) {
1216
+ return (await db.select().from(submissions).where(eq(submissions.formId, formId)).orderBy(desc(submissions.submittedAt), desc(submissions.id))).map(toSubmissionRecord);
1217
+ },
1218
+ async listVersionsByForm(formId) {
1219
+ return (await db.select().from(formVersions).where(eq(formVersions.formId, formId)).orderBy(desc(formVersions.version))).map((row) => ({
1220
+ id: row.id,
1221
+ formId: row.formId,
1222
+ version: row.version,
1223
+ schema: row.schema,
1224
+ schemaHash: row.schemaHash
1225
+ }));
1226
+ },
1227
+ async upsertDraft(record) {
1228
+ await db.insert(drafts).values({
1229
+ id: record.id,
1230
+ formId: record.formId,
1231
+ formVersionId: record.formVersionId,
1232
+ data: record.data,
1233
+ updatedAt: new Date(record.updatedAt)
1234
+ }).onConflictDoUpdate({
1235
+ target: [drafts.formId, drafts.id],
1236
+ set: {
1237
+ formVersionId: record.formVersionId,
1238
+ data: record.data,
1239
+ updatedAt: new Date(record.updatedAt)
1240
+ }
1241
+ });
1242
+ },
1243
+ async getDraft(formId, draftId) {
1244
+ const row = (await db.select().from(drafts).where(and(eq(drafts.formId, formId), eq(drafts.id, draftId))).limit(1))[0];
1245
+ if (row === void 0) return void 0;
1246
+ return {
1247
+ id: row.id,
1248
+ formId: row.formId,
1249
+ formVersionId: row.formVersionId,
1250
+ data: row.data,
1251
+ updatedAt: row.updatedAt.toISOString()
1252
+ };
1253
+ },
1254
+ async insertUser(record) {
1255
+ await db.insert(users).values({
1256
+ id: record.id,
1257
+ email: record.email,
1258
+ passwordHash: record.passwordHash,
1259
+ role: record.role,
1260
+ createdAt: new Date(record.createdAt)
1261
+ });
1262
+ },
1263
+ async getUserByEmail(email) {
1264
+ const row = (await db.select().from(users).where(eq(users.email, email)).limit(1))[0];
1265
+ if (row === void 0) return void 0;
1266
+ return {
1267
+ id: row.id,
1268
+ email: row.email,
1269
+ passwordHash: row.passwordHash,
1270
+ role: row.role,
1271
+ createdAt: row.createdAt.toISOString()
1272
+ };
1273
+ },
1274
+ async insertApiKey(record) {
1275
+ await db.insert(apiKeys).values({
1276
+ id: record.id,
1277
+ name: record.name,
1278
+ prefix: record.prefix,
1279
+ secretHash: record.secretHash,
1280
+ role: record.role,
1281
+ createdAt: new Date(record.createdAt),
1282
+ revokedAt: record.revokedAt === null ? null : new Date(record.revokedAt)
1283
+ });
1284
+ },
1285
+ async listApiKeys() {
1286
+ return (await db.select().from(apiKeys)).map(toApiKeyRecord);
1287
+ },
1288
+ async findApiKeysByPrefix(prefix) {
1289
+ return (await db.select().from(apiKeys).where(eq(apiKeys.prefix, prefix))).map(toApiKeyRecord);
1290
+ },
1291
+ async revokeApiKey(id, atIso) {
1292
+ await db.update(apiKeys).set({ revokedAt: new Date(atIso) }).where(eq(apiKeys.id, id));
1293
+ }
1294
+ };
1295
+ }
1296
+ function toApiKeyRecord(row) {
1297
+ return {
1298
+ id: row.id,
1299
+ name: row.name,
1300
+ prefix: row.prefix,
1301
+ secretHash: row.secretHash,
1302
+ role: row.role,
1303
+ createdAt: row.createdAt.toISOString(),
1304
+ revokedAt: row.revokedAt === null ? null : row.revokedAt.toISOString()
1305
+ };
1306
+ }
1307
+ function toSubmissionRecord(row) {
1308
+ return {
1309
+ id: row.id,
1310
+ formId: row.formId,
1311
+ formVersionId: row.formVersionId,
1312
+ data: row.data,
1313
+ submittedAt: row.submittedAt.toISOString()
1314
+ };
1315
+ }
1316
+ /** A delivery row as the port describes it. */
1317
+ function toDeliveryRecord(row) {
1318
+ return {
1319
+ id: row.id,
1320
+ webhookId: row.webhookId,
1321
+ submissionId: row.submissionId,
1322
+ eventId: row.eventId,
1323
+ body: row.body,
1324
+ attempt: row.attempt,
1325
+ nextAttemptAt: row.nextAttemptAt.toISOString(),
1326
+ state: row.state,
1327
+ lastError: row.lastError
1328
+ };
1329
+ }
1330
+ /** A files row as the port describes it: timestamps as ISO strings. */
1331
+ function toFileRecord(row) {
1332
+ return {
1333
+ id: row.id,
1334
+ formId: row.formId,
1335
+ name: row.name,
1336
+ size: row.size,
1337
+ contentType: row.contentType,
1338
+ storageKey: row.storageKey,
1339
+ state: row.state,
1340
+ createdAt: row.createdAt.toISOString(),
1341
+ submissionId: row.submissionId
1342
+ };
1343
+ }
1344
+ /** A webhook row as the port describes it, health included. */
1345
+ function toWebhookRecord(row) {
1346
+ return {
1347
+ id: row.id,
1348
+ formId: row.formId,
1349
+ url: row.url,
1350
+ secret: row.secret,
1351
+ consecutiveFailures: row.consecutiveFailures,
1352
+ openedAt: row.openedAt === null ? null : row.openedAt.toISOString()
1353
+ };
1354
+ }
1355
+ /**
1356
+ * An entry as the table holds it.
1357
+ *
1358
+ * Absent and null are the same thing here, and the conversion is in one place
1359
+ * so two call sites cannot disagree about which they write.
1360
+ */
1361
+ function auditRow(entry) {
1362
+ return {
1363
+ id: entry.id,
1364
+ at: new Date(entry.at),
1365
+ action: entry.action,
1366
+ actorKind: entry.actorKind ?? null,
1367
+ actorId: entry.actorId ?? null,
1368
+ subject: entry.subject ?? null,
1369
+ requestId: entry.requestId ?? null,
1370
+ detail: entry.detail ?? null
1371
+ };
1372
+ }
1373
+ //#endregion
1374
+ //#region src/file-store.ts
1375
+ /**
1376
+ * Bytes under one directory, one file per key.
1377
+ *
1378
+ * **Keys are checked, not trusted.** A key is minted by the server from a form
1379
+ * id and a file id, so it cannot contain a traversal — but this resolves it
1380
+ * and refuses anything landing outside the root regardless. A path check that
1381
+ * only runs when the input is untrusted is a path check that stops running the
1382
+ * day somebody adds a caller.
1383
+ */
1384
+ function createLocalFileStore(root) {
1385
+ const base = resolve(root);
1386
+ const pathFor = (key) => {
1387
+ if (key.includes("\\")) throw new Error(`Refusing a storage key that could resolve outside the store: ${key}`);
1388
+ const full = resolve(join(base, key));
1389
+ if (full !== base && !full.startsWith(base + sep)) throw new Error(`Refusing a storage key that resolves outside the store: ${key}`);
1390
+ return full;
1391
+ };
1392
+ return {
1393
+ async put(key, bytes) {
1394
+ const full = pathFor(key);
1395
+ await mkdir(dirname(full), { recursive: true });
1396
+ await writeFile(full, bytes);
1397
+ },
1398
+ async open(key) {
1399
+ const full = pathFor(key);
1400
+ try {
1401
+ await stat(full);
1402
+ } catch {
1403
+ return;
1404
+ }
1405
+ return createReadStream(full);
1406
+ },
1407
+ async remove(key) {
1408
+ await rm(pathFor(key), { force: true });
1409
+ },
1410
+ async sizeOf(key) {
1411
+ try {
1412
+ return (await stat(pathFor(key))).size;
1413
+ } catch {
1414
+ return;
1415
+ }
1416
+ }
1417
+ };
1418
+ }
1419
+ /**
1420
+ * The checksum a receiver can compare against.
1421
+ *
1422
+ * Returned when the bytes are stored and never asked of the client: a checksum
1423
+ * the uploader computed is a checksum the uploader can lie about, so this one
1424
+ * is only useful for telling a *later* reader that the bytes have not changed.
1425
+ */
1426
+ function sha256(bytes) {
1427
+ return createHash("sha256").update(bytes).digest("hex");
1428
+ }
1429
+ //#endregion
1430
+ //#region src/file-collector.ts
1431
+ function startFileCollector(storage, store, options = {}) {
1432
+ const interval = options.intervalMs ?? 9e5;
1433
+ const afterHours = options.afterHours ?? 24;
1434
+ let stopped = false;
1435
+ let running = false;
1436
+ const tick = async () => {
1437
+ if (running || stopped) return;
1438
+ running = true;
1439
+ try {
1440
+ const abandoned = await collectAbandonedFiles(storage, /* @__PURE__ */ new Date(), afterHours);
1441
+ if (abandoned.length === 0) return;
1442
+ const removed = [];
1443
+ for (const file of abandoned) {
1444
+ await store.remove(file.storageKey);
1445
+ removed.push(file.id);
1446
+ }
1447
+ await storage.deleteFiles(removed);
1448
+ } catch (error) {
1449
+ console.error("files: a collection pass failed", error);
1450
+ } finally {
1451
+ running = false;
1452
+ }
1453
+ };
1454
+ const timer = setInterval(() => void tick(), interval);
1455
+ timer.unref?.();
1456
+ return { stop: () => {
1457
+ stopped = true;
1458
+ clearInterval(timer);
1459
+ } };
1460
+ }
1461
+ //#endregion
1462
+ export { bootstrapSchema as a, createPostgresStorage as i, createLocalFileStore as n, SCHEMA_HASH_HEADER as o, sha256 as r, createApp as s, startFileCollector as t };
1463
+
1464
+ //# sourceMappingURL=file-collector-WWc-eo8h.mjs.map