@formancy/server 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{file-collector-LmfD8Y_d.mjs → file-collector-CGSJAtGO.mjs} +148 -107
- package/dist/file-collector-CGSJAtGO.mjs.map +1 -0
- package/dist/index.d.mts +3 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/main.mjs +109 -1
- package/dist/main.mjs.map +1 -1
- package/package.json +3 -3
- package/dist/file-collector-LmfD8Y_d.mjs.map +0 -1
package/dist/main.mjs
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import { a as bootstrapSchema, i as createPostgresStorage, n as createLocalFileStore, o as createApp, t as startFileCollector } from "./file-collector-
|
|
1
|
+
import { a as bootstrapSchema, i as createPostgresStorage, n as createLocalFileStore, o as createApp, t as startFileCollector } from "./file-collector-CGSJAtGO.mjs";
|
|
2
2
|
import { createHash, createHmac, randomBytes } from "node:crypto";
|
|
3
3
|
import { deliveryHeaders, drainOutbox, isIpLiteral, isPrivateAddress } from "@formancy/server-core";
|
|
4
4
|
import postgres from "postgres";
|
|
5
5
|
import { lookup } from "node:dns/promises";
|
|
6
6
|
import { Agent, fetch as fetch$1 } from "undici";
|
|
7
7
|
import { Readable } from "node:stream";
|
|
8
|
+
import { connect } from "node:net";
|
|
8
9
|
//#region src/webhook-url.ts
|
|
9
10
|
/**
|
|
10
11
|
* What is wrong with this webhook URL, or undefined when nothing is.
|
|
@@ -392,6 +393,92 @@ function encodeSegment(value) {
|
|
|
392
393
|
return encodeURIComponent(value).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
393
394
|
}
|
|
394
395
|
//#endregion
|
|
396
|
+
//#region src/clamd-scanner.ts
|
|
397
|
+
/** How much is sent per INSTREAM chunk. clamd takes chunks of any size up to its stream limit. */
|
|
398
|
+
const CHUNK = 65536;
|
|
399
|
+
/**
|
|
400
|
+
* clamd's own default `StreamMaxLength`, 100 MiB — as the `clamd.conf` ClamAV 1.5.4 ships
|
|
401
|
+
* says, and as measured against it: a 90 MiB stream was answered, a 110 MiB one refused.
|
|
402
|
+
*/
|
|
403
|
+
const CLAMD_DEFAULT_MAX_BYTES = 104857600;
|
|
404
|
+
/**
|
|
405
|
+
* ClamAV's daemon, asked over its INSTREAM command
|
|
406
|
+
* ([0131](../../../docs/decisions/0131-an-upload-is-scanned-before-it-is-kept.md)).
|
|
407
|
+
*
|
|
408
|
+
* The protocol is clamd's own and small enough to speak directly — the command, the bytes in
|
|
409
|
+
* length-prefixed chunks, a zero-length chunk to end them, and one line back — so this adds
|
|
410
|
+
* no dependency to the server. Its tests run against a stand-in that speaks the protocol as
|
|
411
|
+
* clamd's manual describes it; it was run once against ClamAV 1.5.4 itself, and the
|
|
412
|
+
* documentation says what that showed and what it did not.
|
|
413
|
+
*
|
|
414
|
+
* **Only `stream: OK` is clean.** A finding is refused by its name. A file over clamd's size
|
|
415
|
+
* limit is refused too, because sending it again changes nothing. Anything else — an answer
|
|
416
|
+
* this does not understand, no answer, no daemon — rejects, which the use-case reads as a
|
|
417
|
+
* scanner that cannot be asked, and refuses the file for.
|
|
418
|
+
*
|
|
419
|
+
* **`maxBytes` is clamd's `StreamMaxLength`, and is checked before a byte is sent.** Past
|
|
420
|
+
* it, clamd says so and closes the connection while bytes may still be arriving. Against the
|
|
421
|
+
* stand-in the bytes in flight reset it and the answer was lost to `ECONNRESET`, which reads
|
|
422
|
+
* as a scanner that is down and would tell the person to try again forever; the real clamd
|
|
423
|
+
* measured here answered intact. Checked first, the outcome does not depend on which.
|
|
424
|
+
* Set it to what clamd is configured with.
|
|
425
|
+
*/
|
|
426
|
+
function createClamdScanner({ host, port, maxBytes = CLAMD_DEFAULT_MAX_BYTES, timeoutMs = 3e4 }) {
|
|
427
|
+
return { scan: (_file, bytes) => new Promise((resolve, reject) => {
|
|
428
|
+
if (bytes.byteLength > maxBytes) {
|
|
429
|
+
resolve({
|
|
430
|
+
clean: false,
|
|
431
|
+
finding: `could not be scanned: larger than the scanner accepts (${String(maxBytes)} bytes)`
|
|
432
|
+
});
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
const socket = connect({
|
|
436
|
+
host,
|
|
437
|
+
port
|
|
438
|
+
});
|
|
439
|
+
const answer = [];
|
|
440
|
+
let failure;
|
|
441
|
+
socket.setTimeout(timeoutMs, () => socket.destroy(/* @__PURE__ */ new Error(`clamd at ${host}:${String(port)} did not answer within ${String(timeoutMs)} ms`)));
|
|
442
|
+
socket.on("connect", () => {
|
|
443
|
+
socket.write("zINSTREAM\0");
|
|
444
|
+
for (let at = 0; at < bytes.byteLength; at += CHUNK) {
|
|
445
|
+
const piece = bytes.subarray(at, at + CHUNK);
|
|
446
|
+
const length = Buffer.alloc(4);
|
|
447
|
+
length.writeUInt32BE(piece.byteLength);
|
|
448
|
+
socket.write(length);
|
|
449
|
+
socket.write(piece);
|
|
450
|
+
}
|
|
451
|
+
socket.write(Buffer.alloc(4));
|
|
452
|
+
});
|
|
453
|
+
socket.on("data", (data) => answer.push(data));
|
|
454
|
+
socket.on("error", (error) => {
|
|
455
|
+
failure = error;
|
|
456
|
+
});
|
|
457
|
+
socket.on("close", () => {
|
|
458
|
+
const reply = Buffer.concat(answer).toString("utf8").replace(/\0+$/, "").trim();
|
|
459
|
+
if (reply === "") {
|
|
460
|
+
reject(failure ?? /* @__PURE__ */ new Error(`clamd at ${host}:${String(port)} closed without answering`));
|
|
461
|
+
return;
|
|
462
|
+
}
|
|
463
|
+
const verdict = verdictOf(reply);
|
|
464
|
+
if (verdict === void 0) reject(/* @__PURE__ */ new Error(`clamd answered something unexpected: ${reply}`));
|
|
465
|
+
else resolve(verdict);
|
|
466
|
+
});
|
|
467
|
+
}) };
|
|
468
|
+
}
|
|
469
|
+
function verdictOf(reply) {
|
|
470
|
+
if (reply === "stream: OK") return { clean: true };
|
|
471
|
+
const found = /^stream: (.+) FOUND$/.exec(reply);
|
|
472
|
+
if (found !== null) return {
|
|
473
|
+
clean: false,
|
|
474
|
+
finding: found[1]
|
|
475
|
+
};
|
|
476
|
+
if (/size limit exceeded/i.test(reply)) return {
|
|
477
|
+
clean: false,
|
|
478
|
+
finding: `could not be scanned: ${reply.replace(/\.?\s*ERROR$/, "")}`
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
//#endregion
|
|
395
482
|
//#region src/main.ts
|
|
396
483
|
process.env["RECHECK_BACKEND"] ??= "pure";
|
|
397
484
|
/**
|
|
@@ -447,6 +534,26 @@ const fileStore = (() => {
|
|
|
447
534
|
const maxFileBytes = Number(process.env["FORMANCY_MAX_FILE_BYTES"] ?? 10485760);
|
|
448
535
|
if (!Number.isFinite(maxFileBytes) || maxFileBytes <= 0) throw new Error("FORMANCY_MAX_FILE_BYTES must be a positive number of bytes.");
|
|
449
536
|
/**
|
|
537
|
+
* A ClamAV daemon to ask about every upload before its bytes are kept.
|
|
538
|
+
*
|
|
539
|
+
* Unset is a supported state: no file is scanned, which the documentation says. Set, a
|
|
540
|
+
* file is kept only once clamd has called it clean, and refused when clamd cannot be
|
|
541
|
+
* reached — the point of configuring a scanner is that nothing unscanned gets in
|
|
542
|
+
* ([0131](../../../docs/decisions/0131-an-upload-is-scanned-before-it-is-kept.md)).
|
|
543
|
+
* Not checked at startup: clamd takes minutes to load its signatures, and a server that
|
|
544
|
+
* refused to start until then would turn a slow scanner into an outage of everything.
|
|
545
|
+
*/
|
|
546
|
+
const clamdHost = process.env["FORMANCY_CLAMD_HOST"];
|
|
547
|
+
const clamdPort = Number(process.env["FORMANCY_CLAMD_PORT"] ?? 3310);
|
|
548
|
+
const clamdMaxBytes = Number(process.env["FORMANCY_CLAMD_MAX_BYTES"] ?? 104857600);
|
|
549
|
+
if (!Number.isInteger(clamdPort) || clamdPort <= 0 || clamdPort > 65535) throw new Error("FORMANCY_CLAMD_PORT must be a port number.");
|
|
550
|
+
if (!Number.isFinite(clamdMaxBytes) || clamdMaxBytes <= 0) throw new Error("FORMANCY_CLAMD_MAX_BYTES must be a positive number of bytes: clamd's StreamMaxLength.");
|
|
551
|
+
const scanner = clamdHost === void 0 || clamdHost === "" ? void 0 : createClamdScanner({
|
|
552
|
+
host: clamdHost,
|
|
553
|
+
port: clamdPort,
|
|
554
|
+
maxBytes: clamdMaxBytes
|
|
555
|
+
});
|
|
556
|
+
/**
|
|
450
557
|
* Turns the proof-of-work challenge on for anonymous submissions.
|
|
451
558
|
*
|
|
452
559
|
* Unset is a supported state rather than a misconfiguration: a deployment
|
|
@@ -472,6 +579,7 @@ const app = await createApp(storage, {
|
|
|
472
579
|
} } : {},
|
|
473
580
|
...fileStore === void 0 ? {} : { fileStore },
|
|
474
581
|
...challengeSecret === void 0 ? {} : { challengeSecret },
|
|
582
|
+
...scanner === void 0 ? {} : { scanner },
|
|
475
583
|
maxFileBytes
|
|
476
584
|
});
|
|
477
585
|
const outbox = startOutboxWorker(storage, {
|
package/dist/main.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main.mjs","names":["dnsLookup","undiciFetch"],"sources":["../src/webhook-url.ts","../src/deliver.ts","../src/outbox-worker.ts","../src/challenge-sweeper.ts","../src/sigv4.ts","../src/s3-file-store.ts","../src/main.ts"],"sourcesContent":["import { isIpLiteral, isPrivateAddress } from '@formancy/server-core'\n\n/**\n * URL-level checks on a webhook destination.\n *\n * Here rather than in @formancy/server-core because it needs `URL`, and that\n * package deliberately has no DOM or Node types — see\n * docs/decisions/0008-layered-packages.md. Hand-rolling a URL parser to keep it\n * there would be the wrong trade: a security check built on an approximate\n * parser is the kind that is quietly wrong.\n *\n * The address classification it calls IS pure and lives there, tested\n * exhaustively.\n */\n\nexport interface WebhookUrlOptions {\n /**\n * Allow plain http. Off by default: a signature over a body anybody can read\n * and rewrite in flight is theatre. A deployment posting to a sidecar on the\n * same host may reasonably turn it on.\n */\n allowHttp?: boolean\n /**\n * Allow delivery to a private address.\n *\n * OFF by default, and the only reason it exists is the case the design\n * itself names: a receiver running as a sidecar on the same host or the same\n * private network. Without it that deployment simply cannot use webhooks,\n * which is a worse outcome than an escape hatch nobody has to touch.\n *\n * Turning it on gives up the confused-deputy protection entirely — the\n * server will then fetch whatever URL a form author writes, including the\n * cloud metadata service. A deployment that enables it should also be one\n * where form authors are trusted.\n */\n allowPrivateAddresses?: boolean\n}\n\n/**\n * What is wrong with this webhook URL, or undefined when nothing is.\n *\n * Checked when the URL is saved, so an author finds out immediately rather\n * than through a delivery that silently never works.\n */\nexport function webhookUrlProblem(\n raw: string,\n options: WebhookUrlOptions = {},\n): string | undefined {\n let url: URL\n try {\n url = new URL(raw)\n } catch {\n return 'That is not a URL.'\n }\n\n if (url.protocol !== 'https:' && url.protocol !== 'http:') {\n return `Only http and https can be delivered to, not ${url.protocol.replace(':', '')}.`\n }\n\n if (url.protocol === 'http:' && options.allowHttp !== true) {\n return 'Use https. A signature over a body that anyone can read and rewrite proves nothing.'\n }\n\n if (url.username !== '' || url.password !== '') {\n return 'Remove the credentials from the URL: they would be sent to whatever the host resolves to, and they end up in logs.'\n }\n\n // Only a LITERAL address can be judged here. A hostname is checked after\n // resolution, at delivery time, by the caller — and running the fail-closed\n // address check against one would refuse every hostname in the world.\n if (\n options.allowPrivateAddresses !== true &&\n isIpLiteral(url.hostname) &&\n isPrivateAddress(url.hostname)\n ) {\n return `${url.hostname} is not an address this server may be pointed at.`\n }\n\n return undefined\n}\n","import { lookup as dnsLookup } from 'node:dns/promises'\n// fetch from undici, NOT the global one. Node's global fetch is undici too,\n// but a DIFFERENT instance, and handing it an Agent from this one fails at\n// connect time with \"invalid onRequestStart method\" — a mismatch no unit test\n// reaches, because none of them get as far as opening a socket.\nimport { Agent, fetch as undiciFetch } from 'undici'\nimport { deliveryHeaders, isPrivateAddress } from '@formancy/server-core'\nimport { webhookUrlProblem } from './webhook-url.js'\n\n/**\n * Delivering one webhook, without letting the server be pointed at itself.\n *\n * The hard part is not checking the address. It is making sure the address\n * that was checked is the address that gets connected to.\n *\n * \"Validate the URL, then fetch it\" is defeated by DNS rebinding: the name\n * resolves to a public address while we check, and to 169.254.169.254 a\n * moment later when fetch resolves it again. The two lookups are independent,\n * and an attacker only has to win the second one. So this resolves the name\n * itself, checks every address that comes back, and then connects to a\n * checked address — while still sending the original Host header and SNI, so\n * TLS and virtual hosting keep working.\n *\n * That difference is the whole feature. Everything else here is hygiene.\n */\n\nexport interface DeliveryResult {\n ok: boolean\n status?: number\n /** Why it failed, for the admin's action log. Never the response body. */\n error?: string\n}\n\nexport interface DeliveryOptions {\n /** Hard ceiling on the whole attempt, including connect and read. */\n timeoutMs?: number\n /** Plain http, for a sidecar on the same host. Off by default. */\n allowHttp?: boolean\n /**\n * Deliver to a private address. Off by default — see webhook-url.ts. This\n * gives up the confused-deputy protection, so it is opt-in per deployment\n * and never per form.\n */\n allowPrivateAddresses?: boolean\n /** Swappable so tests do not depend on the network. */\n resolve?: (hostname: string) => Promise<string[]>\n}\n\nconst RESPONSE_CAP_BYTES = 64 * 1024\n\nasync function resolveAll(hostname: string): Promise<string[]> {\n const records = await dnsLookup(hostname, { all: true, verbatim: true })\n return records.map((record) => record.address)\n}\n\nexport async function deliver(\n input: {\n url: string\n body: string\n secret: string\n eventId: string\n attempt: number\n nowSeconds: number\n },\n options: DeliveryOptions = {},\n): Promise<DeliveryResult> {\n const problem = webhookUrlProblem(input.url, {\n allowHttp: options.allowHttp ?? false,\n allowPrivateAddresses: options.allowPrivateAddresses ?? false,\n })\n if (problem !== undefined) return { ok: false, error: problem }\n\n const url = new URL(input.url)\n const resolve = options.resolve ?? resolveAll\n\n let addresses: string[]\n try {\n addresses = await resolve(url.hostname)\n } catch (error) {\n return { ok: false, error: `Could not resolve ${url.hostname}: ${String(error)}` }\n }\n\n if (addresses.length === 0) return { ok: false, error: `${url.hostname} resolved to nothing.` }\n\n // EVERY address, not the first. A name that returns one public and one\n // private address is the rebinding attack spelled out, and picking the\n // public one to validate while the stack might use either is no check at all.\n const forbidden = options.allowPrivateAddresses === true\n ? undefined\n : addresses.find((address) => isPrivateAddress(address))\n if (forbidden !== undefined) {\n return { ok: false, error: `${url.hostname} resolves to ${forbidden}, which is not reachable from here.` }\n }\n\n const pinned = addresses[0]!\n\n // The agent connects to the address we checked and nothing else. The\n // original hostname stays in the Host header and in SNI, so TLS validates\n // against the certificate the site actually has.\n const family = pinned.includes(':') ? 6 : 4\n const agent = new Agent({\n connect: {\n // undici calls this with `all: true` and then expects an ARRAY of\n // { address, family }; the plain `(err, address, family)` form that\n // node:net uses comes back as \"Invalid IP address: undefined\". Both\n // shapes are handled because which one arrives depends on undici's\n // internals, and getting it wrong fails only at connect time — where no\n // unit test looks.\n lookup: (_hostname, opts: { all?: boolean | undefined }, callback: (...args: never[]) => void) => {\n const done = callback as unknown as (\n error: Error | null,\n result: string | Array<{ address: string; family: number }>,\n family?: number,\n ) => void\n if (opts.all === true) done(null, [{ address: pinned, family }])\n else done(null, pinned, family)\n },\n },\n })\n\n try {\n const response = await undiciFetch(url, {\n method: 'POST',\n headers: deliveryHeaders({\n eventId: input.eventId,\n secret: input.secret,\n body: input.body,\n timestampSeconds: input.nowSeconds,\n attempt: input.attempt,\n }),\n body: input.body,\n // A redirect is a second destination that nothing has checked. Following\n // one would hand an attacker the whole guard back.\n redirect: 'manual',\n signal: AbortSignal.timeout(options.timeoutMs ?? 10_000),\n dispatcher: agent,\n })\n\n if (response.status >= 300 && response.status < 400) {\n return { ok: false, status: response.status, error: 'Redirects are not followed.' }\n }\n\n // Read a bounded amount and never interpret it. A receiver's body is not\n // ours to parse, and an unbounded read is a memory exhaustion the receiver\n // controls.\n await drain(response, RESPONSE_CAP_BYTES)\n\n return response.ok\n ? { ok: true, status: response.status }\n : { ok: false, status: response.status, error: `Receiver answered ${String(response.status)}.` }\n } catch (error) {\n // `fetch failed` on its own tells an operator nothing. The cause carries\n // the refused connection, the TLS failure or the timeout.\n const cause = error instanceof Error && error.cause instanceof Error ? `: ${error.cause.message}` : ''\n return { ok: false, error: `${error instanceof Error ? error.message : String(error)}${cause}` }\n } finally {\n await agent.close()\n }\n}\n\n/** Consume at most `cap` bytes so the connection can be reused, then stop. */\nasync function drain(response: { body?: unknown }, cap: number): Promise<void> {\n const body = response.body as ReadableStream<Uint8Array> | null | undefined\n const reader = body?.getReader()\n if (reader === undefined) return\n\n let read = 0\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n read += value?.byteLength ?? 0\n if (read >= cap) break\n }\n } finally {\n await reader.cancel().catch(() => undefined)\n }\n}\n","import { drainOutbox } from '@formancy/server-core'\nimport type { Storage } from '@formancy/server-core'\nimport { deliver } from './deliver.js'\n\n/**\n * Runs the outbox on a timer.\n *\n * Everything that decides anything — whether to retry, when, when to give up —\n * is in @formancy/server-core and tested without a network. This is only the\n * clock and the wiring, which is why it is short.\n *\n * NOT a distributed queue. `claimDueDeliveries` does not lock rows, so two\n * replicas would both pick up the same delivery and send it twice. The event\n * id is stable across attempts precisely so a receiver can dedupe that, but a\n * multi-replica deployment should still run exactly one worker until the claim\n * takes a lock. Said plainly here rather than discovered in production.\n */\nexport interface WorkerHandle {\n stop: () => void\n}\n\nexport function startOutboxWorker(\n storage: Storage,\n options: { intervalMs?: number; allowHttp?: boolean; allowPrivateAddresses?: boolean } = {},\n): WorkerHandle {\n const interval = options.intervalMs ?? 5_000\n let stopped = false\n let running = false\n\n const tick = async (): Promise<void> => {\n // One pass at a time. Overlapping passes would let a slow receiver cause\n // the same delivery to be picked up twice by this very process.\n if (running || stopped) return\n running = true\n try {\n await drainOutbox({\n storage,\n now: () => new Date(),\n random: () => Math.random(),\n send: async (delivery, webhook, nowSeconds) =>\n deliver(\n {\n url: webhook.url,\n body: delivery.body,\n secret: webhook.secret,\n eventId: delivery.eventId,\n attempt: delivery.attempt + 1,\n nowSeconds,\n },\n {\n allowHttp: options.allowHttp ?? false,\n allowPrivateAddresses: options.allowPrivateAddresses ?? false,\n },\n ),\n })\n } catch (error) {\n // A worker that throws is a worker that stops. Deliveries retry on their\n // own schedule, so the right response to an unexpected failure is to\n // complain and come back.\n console.error('outbox: pass failed', error)\n } finally {\n running = false\n }\n }\n\n const timer = setInterval(() => void tick(), interval)\n // Do not hold the process open: a server whose only remaining work is an\n // empty poll should be able to exit.\n timer.unref?.()\n\n return {\n stop: () => {\n stopped = true\n clearInterval(timer)\n },\n }\n}\n","import type { Storage } from '@formancy/server-core'\n\n/**\n * Forgetting challenges that can no longer be replayed anyway.\n *\n * A solved challenge is recorded so it cannot be spent twice. Once it has\n * expired the record is doing nothing: the stateless expiry check refuses the\n * solution before the spend is ever consulted. Keeping the row past that point\n * only grows a table.\n *\n * Its own timer rather than a job on the file collector, because the two are\n * configured independently: a deployment can have public forms and no uploads,\n * and that deployment still accumulates spent challenges. Hanging this off the\n * collector would make sweeping conditional on a setting that has nothing to\n * do with it.\n *\n * The same shape as the collector and the outbox worker: a timer in the\n * process, one pass at a time, and a thrown pass complains and comes back\n * rather than stopping the timer. Also not a distributed job — running two is\n * harmless, because deleting an expired row twice is deleting it once.\n */\nexport interface SweeperHandle {\n stop: () => void\n}\n\nexport function startChallengeSweeper(\n storage: Storage,\n options: { intervalMs?: number } = {},\n): SweeperHandle {\n // Hourly. The rows expire in ten minutes and are a challenge hash each, so\n // an hour's worth of them is nothing; sweeping more often would be work\n // nobody asked for.\n const interval = options.intervalMs ?? 60 * 60_000\n let stopped = false\n let running = false\n\n const tick = async (): Promise<void> => {\n if (running || stopped) return\n running = true\n try {\n await storage.forgetExpiredChallenges(new Date().toISOString())\n } catch (error) {\n // A sweeper that throws is a sweeper that stops, and a table that grows\n // for a reason nobody is watching.\n console.error('challenges: a sweep failed', error)\n } finally {\n running = false\n }\n }\n\n const timer = setInterval(() => void tick(), interval)\n timer.unref?.()\n\n return {\n stop: () => {\n stopped = true\n clearInterval(timer)\n },\n }\n}\n","import { createHash, createHmac } from 'node:crypto'\n\n/**\n * AWS Signature Version 4, for the four requests an object store needs.\n *\n * Ours rather than an SDK: sixty lines against a frozen specification, with the\n * algorithm's own vocabulary in the names so it can be read beside AWS's description of\n * it. It signs requests for **any** S3-compatible endpoint, so Garage, real S3 and\n * Backblaze take the same code path\n * ([0064](../../../docs/decisions/0064-an-object-store-behind-the-same-interface.md)).\n *\n * **What verifies it is a real S3 implementation in a container**, refusing a wrong\n * signature with a 403. The unit tests pin the mechanical properties; they cannot tell\n * whether the canonical request is *right*, only that it is consistent with itself.\n */\n\n/** The SHA-256 of an empty body, which a GET or DELETE carries. */\nexport const EMPTY_PAYLOAD_SHA256 =\n 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'\n\nexport interface SignArgs {\n readonly method: 'GET' | 'PUT' | 'DELETE' | 'HEAD'\n readonly url: URL\n /** Headers to sign and send. `host` is required; casing does not matter. */\n readonly headers: Readonly<Record<string, string>>\n /** Hex SHA-256 of the body. S3 sends it as a header as well as signing it. */\n readonly payloadHash: string\n readonly service: string\n readonly region: string\n readonly accessKeyId: string\n readonly secretAccessKey: string\n /** Injected so a test is not a test of the clock. */\n readonly now: Date\n}\n\n/**\n * The headers to send, including `authorization`.\n *\n * Returns headers rather than mutating a request so that the caller's `fetch`\n * options stay the caller's business, and so the signature is inspectable in a\n * test without a server.\n */\nexport function signRequest(args: SignArgs): Record<string, string> {\n const { method, url, payloadHash, service, region, accessKeyId, secretAccessKey, now } = args\n\n // Lowercase every name once, here, so nothing below has to wonder. A header\n // signed under one casing and sent under another is a 403 with no clue in it.\n const headers: Record<string, string> = {}\n for (const [name, value] of Object.entries(args.headers)) {\n headers[name.toLowerCase()] = value\n }\n\n if (headers['host'] === undefined) {\n // AWS requires host in the signature. Failing here, where the message can\n // say so, beats a server rejecting it for a reason it will not explain.\n throw new Error('Refusing to sign a request with no host header.')\n }\n\n const amzDate = basicIso8601(now)\n const dateStamp = amzDate.slice(0, 8)\n\n headers['x-amz-date'] = amzDate\n // S3 requires this header and requires it to equal the hash in the canonical\n // request. Set from the same value rather than computed twice: two routes to\n // one number is how they come to disagree.\n headers['x-amz-content-sha256'] = payloadHash\n\n // Sorted by name, because \"canonical\" means both sides sort identically.\n const names = Object.keys(headers).sort()\n const canonicalHeaders = names\n // Sequential spaces collapse and the value is trimmed, per the spec. A\n // header a proxy reformatted must still hash to the same bytes.\n .map((name) => `${name}:${(headers[name] ?? '').trim().replace(/\\s+/g, ' ')}\\n`)\n .join('')\n const signedHeaders = names.join(';')\n\n const canonicalRequest = [\n method,\n canonicalPath(url, service),\n canonicalQuery(url),\n canonicalHeaders,\n signedHeaders,\n payloadHash,\n ].join('\\n')\n\n const scope = `${dateStamp}/${region}/${service}/aws4_request`\n const stringToSign = [\n 'AWS4-HMAC-SHA256',\n amzDate,\n scope,\n sha256Hex(canonicalRequest),\n ].join('\\n')\n\n // The key is derived per date, region and service, so a leaked signing key is\n // useless tomorrow, elsewhere, or for another service. That is the whole\n // reason for the four-step chain rather than signing with the secret.\n const dateKey = hmac(`AWS4${secretAccessKey}`, dateStamp)\n const regionKey = hmac(dateKey, region)\n const serviceKey = hmac(regionKey, service)\n const signingKey = hmac(serviceKey, 'aws4_request')\n const signature = hmac(signingKey, stringToSign).toString('hex')\n\n headers['authorization'] =\n `AWS4-HMAC-SHA256 Credential=${accessKeyId}/${scope}, ` +\n `SignedHeaders=${signedHeaders}, Signature=${signature}`\n\n return headers\n}\n\n/**\n * `20150830T123600Z` — basic ISO 8601, not the extended form.\n *\n * `toISOString()` gives `2015-08-30T12:36:00.000Z`, which is rejected. Stripping\n * the punctuation is the whole conversion, and the credential scope then wants\n * the same instant as `20150830`, which is why this returns the long one and the\n * caller slices it.\n */\nfunction basicIso8601(at: Date): string {\n return `${at.toISOString().replace(/[-:]/g, '').split('.')[0] ?? ''}Z`\n}\n\n/**\n * The path, encoded **once** for s3 and twice for everything else.\n *\n * This is the one place where s3 departs from the general rule, and getting it\n * wrong produces a signature that is valid for every other AWS service and\n * refused by the only one we call -- and refused only for keys containing a\n * character that needs encoding, which is the worst possible way to find out.\n */\nfunction canonicalPath(url: URL, service: string): string {\n // `url.pathname` is already percent-encoded by URL parsing, which is exactly\n // the single encoding s3 wants.\n const once = url.pathname === '' ? '/' : url.pathname\n if (service === 's3') return once\n return once\n .split('/')\n .map((segment) => uriEncode(decodeURIComponent(segment)))\n .join('/')\n}\n\n/** Sorted by encoded name, values encoded, `=` even when empty. */\nfunction canonicalQuery(url: URL): string {\n const pairs: Array<readonly [string, string]> = []\n for (const [name, value] of url.searchParams) pairs.push([uriEncode(name), uriEncode(value)])\n // Sorted after encoding, per the spec: sorting the raw names orders them\n // differently whenever an encoded byte changes the comparison.\n pairs.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n return pairs.map(([name, value]) => `${name}=${value}`).join('&')\n}\n\n/**\n * AWS's `UriEncode`, which is not `encodeURIComponent`.\n *\n * The differences are small and each one is a 403: `!`, `'`, `(`, `)` and `*`\n * are left alone by `encodeURIComponent` and must be encoded, hex digits must be\n * uppercase, and a space is `%20` rather than `+`.\n */\nfunction uriEncode(value: string): string {\n return encodeURIComponent(value).replace(\n /[!'()*]/g,\n (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,\n )\n}\n\nfunction sha256Hex(value: string): string {\n return createHash('sha256').update(value, 'utf8').digest('hex')\n}\n\nfunction hmac(key: string | Buffer, data: string): Buffer {\n return createHmac('sha256', key).update(data, 'utf8').digest()\n}\n","import { createHash } from 'node:crypto'\nimport { Readable } from 'node:stream'\n\nimport type { FileStore } from './file-store.js'\nimport { EMPTY_PAYLOAD_SHA256, signRequest } from './sigv4.js'\n\n/**\n * Uploaded bytes in an S3-compatible object store.\n *\n * The second implementation of `FileStore`. The local one is right for a single\n * container with a volume and is the ceiling on everything above it: two replicas with\n * two volumes each accept uploads the other cannot serve, so any deployment past one\n * server needs this.\n *\n * **Not tied to Amazon.** The design calls for Garage, which is what the\n * integration test runs and what belongs in the compose file; the same code path\n * serves MinIO, Backblaze, Cloudflare R2 and real S3, because the only thing they\n * need in common is SigV4 and path-style addressing.\n *\n * **Bytes still pass through the server**, so the request body cap is the ceiling on a\n * file. A presigned PUT straight from the browser is the roadmap item that removes the\n * server from the data path; this replaces where the bytes land without touching how\n * they arrive.\n *\n * **No multipart.** A single PUT is one request, so the practical ceiling is whatever\n * the store accepts in one -- 5 GB for S3, and far above `FORMANCY_MAX_FILE_BYTES`.\n */\nexport interface S3FileStoreConfig {\n /** Base URL of the endpoint, e.g. `http://garage:3900` or an S3 regional URL. */\n readonly endpoint: string\n readonly bucket: string\n /** Garage answers to any region name; real S3 does not. */\n readonly region: string\n readonly accessKeyId: string\n readonly secretAccessKey: string\n /**\n * How long one request may take before it is abandoned, in milliseconds.\n *\n * An object store that stops answering must not become a server that stops\n * answering. Defaults to thirty seconds, which is generous for one object and\n * still bounded.\n */\n readonly timeoutMs?: number\n}\n\nexport function createS3FileStore(config: S3FileStoreConfig): FileStore {\n const endpoint = config.endpoint.replace(/\\/+$/, '')\n const timeoutMs = config.timeoutMs ?? 30_000\n\n /**\n * The object's URL, with the key's slashes kept and everything else encoded.\n *\n * A key is a path inside the bucket, so its separators are structural. Every\n * other character has to be encoded or the request line is invalid -- and a\n * space encoded as `+`, which is what form encoding would do, names a\n * different object.\n */\n const urlFor = (key: string): URL => {\n if (key === '' || key.includes('\\\\') || key.split('/').includes('..')) {\n // Keys are minted by the server today. Checked anyway, because the local\n // store checks it and the two must not disagree about what is legal.\n throw new Error(`Refusing a storage key that could address another bucket: ${key}`)\n }\n const path = key.split('/').map(encodeSegment).join('/')\n return new URL(`${endpoint}/${encodeSegment(config.bucket)}/${path}`)\n }\n\n const send = async (\n method: 'GET' | 'PUT' | 'DELETE' | 'HEAD',\n key: string,\n body?: Buffer,\n ): Promise<Response> => {\n const url = urlFor(key)\n const payloadHash =\n body === undefined\n ? EMPTY_PAYLOAD_SHA256\n : createHash('sha256').update(body).digest('hex')\n\n // `content-length` is deliberately neither signed nor set. undici refuses a\n // manually supplied one -- `InvalidArgumentError: invalid content-length\n // header` -- and computes its own from the body, so setting it is both\n // impossible and unnecessary. Nothing is lost by not signing it: AWS requires\n // only `host` and the `x-amz-*` headers in the signature, and\n // `x-amz-content-sha256` is a hash of the exact bytes, which constrains the\n // length far more tightly than a signed length would.\n const headers = signRequest({\n method,\n url,\n headers: { host: url.host },\n payloadHash,\n service: 's3',\n region: config.region,\n accessKeyId: config.accessKeyId,\n secretAccessKey: config.secretAccessKey,\n now: new Date(),\n })\n\n return fetch(url, {\n method,\n headers,\n ...(body === undefined ? {} : { body: new Uint8Array(body) }),\n signal: AbortSignal.timeout(timeoutMs),\n })\n }\n\n /**\n * A status that means \"there is no such object\", as opposed to one that means\n * the store could not answer.\n *\n * The distinction is the whole reason this is a named function. Reading a\n * could-not-answer as absence makes the collector delete the row for bytes that\n * still exist and makes a download return nothing for a file the person can see\n * listed.\n *\n * **404 only, and 403 deliberately not.** S3 answers 403 for an object a caller may\n * not list, but this caller owns the bucket -- so 403 means the credentials are\n * wrong, and reading that as absence would make a misconfigured deployment look like\n * one where every file has vanished and have the collector delete every row.\n */\n const isAbsent = (response: Response): boolean => response.status === 404\n\n const failed = (method: string, key: string, response: Response): Error =>\n new Error(`S3 ${method} of ${key} failed: ${String(response.status)} ${response.statusText}`)\n\n return {\n async put(key, bytes) {\n const response = await send('PUT', key, bytes)\n if (!response.ok) throw failed('PUT', key, response)\n // The body is an error document or nothing. Reading it releases the\n // connection back to the pool, which an undrained response does not.\n await response.arrayBuffer()\n },\n\n async open(key) {\n const response = await send('GET', key)\n if (isAbsent(response)) {\n await response.arrayBuffer()\n return undefined\n }\n if (!response.ok || response.body === null) throw failed('GET', key, response)\n // Streamed rather than buffered: a large attachment should not be held in\n // memory on its way to one downloader.\n return Readable.fromWeb(response.body)\n },\n\n async remove(key) {\n const response = await send('DELETE', key)\n // Absent is success. A collector that crashed between deleting the bytes\n // and deleting the row has to be safe to run again.\n if (response.ok || isAbsent(response)) {\n await response.arrayBuffer()\n return\n }\n throw failed('DELETE', key, response)\n },\n\n async sizeOf(key) {\n const response = await send('HEAD', key)\n if (isAbsent(response)) return undefined\n if (!response.ok) throw failed('HEAD', key, response)\n const length = response.headers.get('content-length')\n // A store that answered without a length cannot be used to check that the\n // bytes match what was promised, and pretending it said zero would fail\n // that check by declaring the file empty.\n if (length === null) throw new Error(`S3 HEAD of ${key} returned no content-length.`)\n return Number(length)\n },\n }\n}\n\n/**\n * AWS's `UriEncode` for one path segment.\n *\n * `encodeURIComponent` leaves `!'()*` alone and S3 wants them encoded, and its\n * hex digits are already uppercase. Duplicated from the signer rather than\n * shared, because the signer's copy is about hashing and this one is about the\n * request line: if they ever need to differ, they differ, and a shared helper\n * would make that a conversation instead of an edit.\n */\nfunction encodeSegment(value: string): string {\n return encodeURIComponent(value).replace(\n /[!'()*]/g,\n (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,\n )\n}\n","import { randomBytes } from 'node:crypto'\nimport postgres from 'postgres'\nimport { createApp } from './app.js'\nimport { bootstrapSchema } from './db.js'\nimport { createPostgresStorage } from './postgres-storage.js'\nimport { startOutboxWorker } from './outbox-worker.js'\nimport { startFileCollector } from './file-collector.js'\nimport { startChallengeSweeper } from './challenge-sweeper.js'\nimport { createLocalFileStore } from './file-store.js'\nimport type { FileStore } from './file-store.js'\nimport { createS3FileStore } from './s3-file-store.js'\n\n// recheck ships a 23 MB JVM jar and a native binary per platform as OPTIONAL\n// dependencies and falls back to a pure-JavaScript engine without them. For\n// one static analysis at publish time, the jar is a large thing to carry in a\n// self-hosted container and the per-platform binaries are an awkward thing to\n// pin in an SBOM. Choosing the pure engine explicitly also makes the verdict\n// deterministic rather than dependent on what happened to install.\nprocess.env['RECHECK_BACKEND'] ??= 'pure'\n\n/**\n * The runnable server: `node dist/main.mjs` with DATABASE_URL set, or\n * `docker compose up` from the repo root, which supplies both.\n *\n * Bootstraps its own tables on start — a self-hosted skeleton that works five\n * minutes after `git clone` is the adoption funnel; migrations arrive with the\n * lifecycle work.\n */\nconst databaseUrl = process.env['DATABASE_URL']\nif (databaseUrl === undefined || databaseUrl === '') {\n console.error('DATABASE_URL is required, e.g. postgres://formancy:formancy@localhost:5432/formancy')\n process.exit(1)\n}\n\nconst port = Number(process.env['PORT'] ?? 4380)\nconst sql = postgres(databaseUrl)\n\nlet authSecret = process.env['FORMANCY_AUTH_SECRET']\nif (authSecret === undefined || authSecret === '') {\n // A generated secret keeps `docker compose up` working, at the cost of every\n // session dying on restart. Say so loudly rather than failing dev cold.\n authSecret = randomBytes(33).toString('base64url')\n console.warn(\n 'FORMANCY_AUTH_SECRET is not set: generated an ephemeral one, sessions will not survive a restart.',\n )\n}\n\nconst adminEmail = process.env['FORMANCY_ADMIN_EMAIL']\nconst adminPassword = process.env['FORMANCY_ADMIN_PASSWORD']\n\n/**\n * Where uploaded bytes go.\n *\n * Absent means this deployment accepts no files, and that is a supported\n * state rather than a misconfiguration: a form with a file field still renders\n * and still submits, and the field says plainly that there is nowhere to put\n * one. Turning uploads on is naming a directory, which in a container is\n * naming a volume — and a volume is the one thing a self-hoster has to think\n * about, so it is not defaulted.\n */\nconst filesDirectory = process.env['FORMANCY_FILES_DIR']\nconst s3Endpoint = process.env['FORMANCY_S3_ENDPOINT']\n\nif (filesDirectory !== undefined && s3Endpoint !== undefined) {\n // Two stores means half the files are in one and half in the other, and\n // nothing records which -- so a later reader gets \"no such file\" for bytes\n // that exist in the store it did not ask. Refusing at startup is the only\n // point at which this is cheap to fix.\n throw new Error(\n 'Set FORMANCY_FILES_DIR or FORMANCY_S3_ENDPOINT, not both: two stores means ' +\n 'files land in one and are looked for in the other.',\n )\n}\n\n/**\n * The object store, when one is configured.\n *\n * Every field is required once the endpoint is set, and none is defaulted. A\n * bucket name guessed wrong is a deployment that accepts uploads into nothing;\n * credentials guessed wrong are a deployment where every file reads as missing.\n * Both fail here instead.\n */\nconst s3Store = ((): FileStore | undefined => {\n if (s3Endpoint === undefined) return undefined\n\n const required = (name: string): string => {\n const value = process.env[name]\n if (value === undefined || value === '') {\n throw new Error(`${name} is required when FORMANCY_S3_ENDPOINT is set.`)\n }\n return value\n }\n\n return createS3FileStore({\n endpoint: s3Endpoint,\n bucket: required('FORMANCY_S3_BUCKET'),\n // Part of the credential scope, so a wrong region is a signature the store\n // computes differently and rejects. Garage answers to any name and real S3\n // does not, which is why there is no default.\n region: required('FORMANCY_S3_REGION'),\n accessKeyId: required('FORMANCY_S3_ACCESS_KEY_ID'),\n secretAccessKey: required('FORMANCY_S3_SECRET_ACCESS_KEY'),\n })\n})()\n\nconst fileStore =\n s3Store ?? (filesDirectory === undefined ? undefined : createLocalFileStore(filesDirectory))\n\nconst maxFileBytes = Number(process.env['FORMANCY_MAX_FILE_BYTES'] ?? 10 * 1024 * 1024)\nif (!Number.isFinite(maxFileBytes) || maxFileBytes <= 0) {\n throw new Error('FORMANCY_MAX_FILE_BYTES must be a positive number of bytes.')\n}\n\n/**\n * Turns the proof-of-work challenge on for anonymous submissions.\n *\n * Unset is a supported state rather than a misconfiguration: a deployment\n * whose forms all require a session has no anonymous surface to protect, and\n * the challenge route says so with a 404 rather than failing. A deployment\n * with public forms should set it — the other layers are rate limits, an\n * origin allowlist and a body cap, all of which an attacker with a few\n * addresses walks past.\n *\n * Separate from FORMANCY_AUTH_SECRET so that rotating one does not invalidate\n * the other: rotating this one costs an unsolved puzzle, rotating that one\n * costs everybody their session.\n */\nconst challengeSecret = process.env['FORMANCY_CHALLENGE_SECRET']\nif (challengeSecret !== undefined && challengeSecret.length < 32) {\n throw new Error('FORMANCY_CHALLENGE_SECRET must be at least 32 characters, or unset.')\n}\n\nawait bootstrapSchema(sql)\nconst storage = createPostgresStorage(sql)\nconst app = await createApp(storage, {\n authSecret,\n ...(adminEmail !== undefined && adminPassword !== undefined\n ? { bootstrapAdmin: { email: adminEmail, password: adminPassword } }\n : {}),\n ...(fileStore === undefined ? {} : { fileStore }),\n ...(challengeSecret === undefined ? {} : { challengeSecret }),\n maxFileBytes,\n})\n\n// Queued deliveries are useless until something sends them.\nconst outbox = startOutboxWorker(storage, {\n ...(process.env['FORMANCY_WEBHOOK_ALLOW_HTTP'] === 'true' ? { allowHttp: true } : {}),\n // Gives up the SSRF guard. For a sidecar receiver on a trusted network, and\n // for nothing else.\n ...(process.env['FORMANCY_WEBHOOK_ALLOW_PRIVATE'] === 'true'\n ? { allowPrivateAddresses: true }\n : {}),\n})\n// Somebody who attaches a file and closes the tab leaves bytes behind. A disk\n// that fills up for a reason nobody is watching is the most tedious outage\n// there is.\nconst collector =\n fileStore === undefined ? undefined : startFileCollector(storage, fileStore)\n\n// Independent of the collector: a deployment can have public forms and no\n// uploads, and that deployment still accumulates spent challenges.\nconst sweeper = challengeSecret === undefined ? undefined : startChallengeSweeper(storage)\n\nfor (const signal of ['SIGINT', 'SIGTERM'] as const) {\n process.once(signal, () => {\n outbox.stop()\n collector?.stop()\n sweeper?.stop()\n void app.close().then(() => process.exit(0))\n })\n}\n\nawait app.listen({ port, host: process.env['HOST'] ?? '0.0.0.0' })\nconsole.log(`formancy server listening on :${port}`)\n\nfor (const signal of ['SIGINT', 'SIGTERM'] as const) {\n process.on(signal, () => {\n void app\n .close()\n .then(() => sql.end())\n .then(() => process.exit(0))\n })\n}\n"],"mappings":";;;;;;;;;;;;;;AA4CA,SAAgB,kBACd,KACA,UAA6B,CAAC,GACV;CACpB,IAAI;CACJ,IAAI;EACF,MAAM,IAAI,IAAI,GAAG;CACnB,QAAQ;EACN,OAAO;CACT;CAEA,IAAI,IAAI,aAAa,YAAY,IAAI,aAAa,SAChD,OAAO,gDAAgD,IAAI,SAAS,QAAQ,KAAK,EAAE,EAAE;CAGvF,IAAI,IAAI,aAAa,WAAW,QAAQ,cAAc,MACpD,OAAO;CAGT,IAAI,IAAI,aAAa,MAAM,IAAI,aAAa,IAC1C,OAAO;CAMT,IACE,QAAQ,0BAA0B,QAClC,YAAY,IAAI,QAAQ,KACxB,iBAAiB,IAAI,QAAQ,GAE7B,OAAO,GAAG,IAAI,SAAS;AAI3B;;;AC/BA,MAAM,qBAAqB;AAE3B,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AI,CAAC;CAGnF,GAAI,QAAQ,IAAI,sCAAsC,SAClD,EAAE,uBAAuB,KAAK,IAC9B,CAAC;AACP,CAAC;AAID,MAAM,YACJ,cAAc,KAAA,IAAY,KAAA,IAAY,mBAAmB,SAAS,SAAS;AAI7E,MAAM,UAAU,oBAAoB,KAAA,IAAY,KAAA,IAAY,sBAAsB,OAAO;AAEzF,KAAK,MAAM,UAAU,CAAC,UAAU,SAAS,GACvC,QAAQ,KAAK,cAAc;CACzB,OAAO,KAAK;CACZ,WAAW,KAAK;CAChB,SAAS,KAAK;CACd,IAAS,MAAM,CAAC,CAAC,WAAW,QAAQ,KAAK,CAAC,CAAC;AAC7C,CAAC;AAGH,MAAM,IAAI,OAAO;CAAE;CAAM,MAAM,QAAQ,IAAI,WAAW;AAAU,CAAC;AACjE,QAAQ,IAAI,iCAAiC,MAAM;AAEnD,KAAK,MAAM,UAAU,CAAC,UAAU,SAAS,GACvC,QAAQ,GAAG,cAAc;CACvB,IACG,MAAM,CAAC,CACP,WAAW,IAAI,IAAI,CAAC,CAAC,CACrB,WAAW,QAAQ,KAAK,CAAC,CAAC;AAC/B,CAAC"}
|
|
1
|
+
{"version":3,"file":"main.mjs","names":["dnsLookup","undiciFetch"],"sources":["../src/webhook-url.ts","../src/deliver.ts","../src/outbox-worker.ts","../src/challenge-sweeper.ts","../src/sigv4.ts","../src/s3-file-store.ts","../src/clamd-scanner.ts","../src/main.ts"],"sourcesContent":["import { isIpLiteral, isPrivateAddress } from '@formancy/server-core'\n\n/**\n * URL-level checks on a webhook destination.\n *\n * Here rather than in @formancy/server-core because it needs `URL`, and that\n * package deliberately has no DOM or Node types — see\n * docs/decisions/0008-layered-packages.md. Hand-rolling a URL parser to keep it\n * there would be the wrong trade: a security check built on an approximate\n * parser is the kind that is quietly wrong.\n *\n * The address classification it calls IS pure and lives there, tested\n * exhaustively.\n */\n\nexport interface WebhookUrlOptions {\n /**\n * Allow plain http. Off by default: a signature over a body anybody can read\n * and rewrite in flight is theatre. A deployment posting to a sidecar on the\n * same host may reasonably turn it on.\n */\n allowHttp?: boolean\n /**\n * Allow delivery to a private address.\n *\n * OFF by default, and the only reason it exists is the case the design\n * itself names: a receiver running as a sidecar on the same host or the same\n * private network. Without it that deployment simply cannot use webhooks,\n * which is a worse outcome than an escape hatch nobody has to touch.\n *\n * Turning it on gives up the confused-deputy protection entirely — the\n * server will then fetch whatever URL a form author writes, including the\n * cloud metadata service. A deployment that enables it should also be one\n * where form authors are trusted.\n */\n allowPrivateAddresses?: boolean\n}\n\n/**\n * What is wrong with this webhook URL, or undefined when nothing is.\n *\n * Checked when the URL is saved, so an author finds out immediately rather\n * than through a delivery that silently never works.\n */\nexport function webhookUrlProblem(\n raw: string,\n options: WebhookUrlOptions = {},\n): string | undefined {\n let url: URL\n try {\n url = new URL(raw)\n } catch {\n return 'That is not a URL.'\n }\n\n if (url.protocol !== 'https:' && url.protocol !== 'http:') {\n return `Only http and https can be delivered to, not ${url.protocol.replace(':', '')}.`\n }\n\n if (url.protocol === 'http:' && options.allowHttp !== true) {\n return 'Use https. A signature over a body that anyone can read and rewrite proves nothing.'\n }\n\n if (url.username !== '' || url.password !== '') {\n return 'Remove the credentials from the URL: they would be sent to whatever the host resolves to, and they end up in logs.'\n }\n\n // Only a LITERAL address can be judged here. A hostname is checked after\n // resolution, at delivery time, by the caller — and running the fail-closed\n // address check against one would refuse every hostname in the world.\n if (\n options.allowPrivateAddresses !== true &&\n isIpLiteral(url.hostname) &&\n isPrivateAddress(url.hostname)\n ) {\n return `${url.hostname} is not an address this server may be pointed at.`\n }\n\n return undefined\n}\n","import { lookup as dnsLookup } from 'node:dns/promises'\n// fetch from undici, NOT the global one. Node's global fetch is undici too,\n// but a DIFFERENT instance, and handing it an Agent from this one fails at\n// connect time with \"invalid onRequestStart method\" — a mismatch no unit test\n// reaches, because none of them get as far as opening a socket.\nimport { Agent, fetch as undiciFetch } from 'undici'\nimport { deliveryHeaders, isPrivateAddress } from '@formancy/server-core'\nimport { webhookUrlProblem } from './webhook-url.js'\n\n/**\n * Delivering one webhook, without letting the server be pointed at itself.\n *\n * The hard part is not checking the address. It is making sure the address\n * that was checked is the address that gets connected to.\n *\n * \"Validate the URL, then fetch it\" is defeated by DNS rebinding: the name\n * resolves to a public address while we check, and to 169.254.169.254 a\n * moment later when fetch resolves it again. The two lookups are independent,\n * and an attacker only has to win the second one. So this resolves the name\n * itself, checks every address that comes back, and then connects to a\n * checked address — while still sending the original Host header and SNI, so\n * TLS and virtual hosting keep working.\n *\n * That difference is the whole feature. Everything else here is hygiene.\n */\n\nexport interface DeliveryResult {\n ok: boolean\n status?: number\n /** Why it failed, for the admin's action log. Never the response body. */\n error?: string\n}\n\nexport interface DeliveryOptions {\n /** Hard ceiling on the whole attempt, including connect and read. */\n timeoutMs?: number\n /** Plain http, for a sidecar on the same host. Off by default. */\n allowHttp?: boolean\n /**\n * Deliver to a private address. Off by default — see webhook-url.ts. This\n * gives up the confused-deputy protection, so it is opt-in per deployment\n * and never per form.\n */\n allowPrivateAddresses?: boolean\n /** Swappable so tests do not depend on the network. */\n resolve?: (hostname: string) => Promise<string[]>\n}\n\nconst RESPONSE_CAP_BYTES = 64 * 1024\n\nasync function resolveAll(hostname: string): Promise<string[]> {\n const records = await dnsLookup(hostname, { all: true, verbatim: true })\n return records.map((record) => record.address)\n}\n\nexport async function deliver(\n input: {\n url: string\n body: string\n secret: string\n eventId: string\n attempt: number\n nowSeconds: number\n },\n options: DeliveryOptions = {},\n): Promise<DeliveryResult> {\n const problem = webhookUrlProblem(input.url, {\n allowHttp: options.allowHttp ?? false,\n allowPrivateAddresses: options.allowPrivateAddresses ?? false,\n })\n if (problem !== undefined) return { ok: false, error: problem }\n\n const url = new URL(input.url)\n const resolve = options.resolve ?? resolveAll\n\n let addresses: string[]\n try {\n addresses = await resolve(url.hostname)\n } catch (error) {\n return { ok: false, error: `Could not resolve ${url.hostname}: ${String(error)}` }\n }\n\n if (addresses.length === 0) return { ok: false, error: `${url.hostname} resolved to nothing.` }\n\n // EVERY address, not the first. A name that returns one public and one\n // private address is the rebinding attack spelled out, and picking the\n // public one to validate while the stack might use either is no check at all.\n const forbidden = options.allowPrivateAddresses === true\n ? undefined\n : addresses.find((address) => isPrivateAddress(address))\n if (forbidden !== undefined) {\n return { ok: false, error: `${url.hostname} resolves to ${forbidden}, which is not reachable from here.` }\n }\n\n const pinned = addresses[0]!\n\n // The agent connects to the address we checked and nothing else. The\n // original hostname stays in the Host header and in SNI, so TLS validates\n // against the certificate the site actually has.\n const family = pinned.includes(':') ? 6 : 4\n const agent = new Agent({\n connect: {\n // undici calls this with `all: true` and then expects an ARRAY of\n // { address, family }; the plain `(err, address, family)` form that\n // node:net uses comes back as \"Invalid IP address: undefined\". Both\n // shapes are handled because which one arrives depends on undici's\n // internals, and getting it wrong fails only at connect time — where no\n // unit test looks.\n lookup: (_hostname, opts: { all?: boolean | undefined }, callback: (...args: never[]) => void) => {\n const done = callback as unknown as (\n error: Error | null,\n result: string | Array<{ address: string; family: number }>,\n family?: number,\n ) => void\n if (opts.all === true) done(null, [{ address: pinned, family }])\n else done(null, pinned, family)\n },\n },\n })\n\n try {\n const response = await undiciFetch(url, {\n method: 'POST',\n headers: deliveryHeaders({\n eventId: input.eventId,\n secret: input.secret,\n body: input.body,\n timestampSeconds: input.nowSeconds,\n attempt: input.attempt,\n }),\n body: input.body,\n // A redirect is a second destination that nothing has checked. Following\n // one would hand an attacker the whole guard back.\n redirect: 'manual',\n signal: AbortSignal.timeout(options.timeoutMs ?? 10_000),\n dispatcher: agent,\n })\n\n if (response.status >= 300 && response.status < 400) {\n return { ok: false, status: response.status, error: 'Redirects are not followed.' }\n }\n\n // Read a bounded amount and never interpret it. A receiver's body is not\n // ours to parse, and an unbounded read is a memory exhaustion the receiver\n // controls.\n await drain(response, RESPONSE_CAP_BYTES)\n\n return response.ok\n ? { ok: true, status: response.status }\n : { ok: false, status: response.status, error: `Receiver answered ${String(response.status)}.` }\n } catch (error) {\n // `fetch failed` on its own tells an operator nothing. The cause carries\n // the refused connection, the TLS failure or the timeout.\n const cause = error instanceof Error && error.cause instanceof Error ? `: ${error.cause.message}` : ''\n return { ok: false, error: `${error instanceof Error ? error.message : String(error)}${cause}` }\n } finally {\n await agent.close()\n }\n}\n\n/** Consume at most `cap` bytes so the connection can be reused, then stop. */\nasync function drain(response: { body?: unknown }, cap: number): Promise<void> {\n const body = response.body as ReadableStream<Uint8Array> | null | undefined\n const reader = body?.getReader()\n if (reader === undefined) return\n\n let read = 0\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n read += value?.byteLength ?? 0\n if (read >= cap) break\n }\n } finally {\n await reader.cancel().catch(() => undefined)\n }\n}\n","import { drainOutbox } from '@formancy/server-core'\nimport type { Storage } from '@formancy/server-core'\nimport { deliver } from './deliver.js'\n\n/**\n * Runs the outbox on a timer.\n *\n * Everything that decides anything — whether to retry, when, when to give up —\n * is in @formancy/server-core and tested without a network. This is only the\n * clock and the wiring, which is why it is short.\n *\n * NOT a distributed queue. `claimDueDeliveries` does not lock rows, so two\n * replicas would both pick up the same delivery and send it twice. The event\n * id is stable across attempts precisely so a receiver can dedupe that, but a\n * multi-replica deployment should still run exactly one worker until the claim\n * takes a lock. Said plainly here rather than discovered in production.\n */\nexport interface WorkerHandle {\n stop: () => void\n}\n\nexport function startOutboxWorker(\n storage: Storage,\n options: { intervalMs?: number; allowHttp?: boolean; allowPrivateAddresses?: boolean } = {},\n): WorkerHandle {\n const interval = options.intervalMs ?? 5_000\n let stopped = false\n let running = false\n\n const tick = async (): Promise<void> => {\n // One pass at a time. Overlapping passes would let a slow receiver cause\n // the same delivery to be picked up twice by this very process.\n if (running || stopped) return\n running = true\n try {\n await drainOutbox({\n storage,\n now: () => new Date(),\n random: () => Math.random(),\n send: async (delivery, webhook, nowSeconds) =>\n deliver(\n {\n url: webhook.url,\n body: delivery.body,\n secret: webhook.secret,\n eventId: delivery.eventId,\n attempt: delivery.attempt + 1,\n nowSeconds,\n },\n {\n allowHttp: options.allowHttp ?? false,\n allowPrivateAddresses: options.allowPrivateAddresses ?? false,\n },\n ),\n })\n } catch (error) {\n // A worker that throws is a worker that stops. Deliveries retry on their\n // own schedule, so the right response to an unexpected failure is to\n // complain and come back.\n console.error('outbox: pass failed', error)\n } finally {\n running = false\n }\n }\n\n const timer = setInterval(() => void tick(), interval)\n // Do not hold the process open: a server whose only remaining work is an\n // empty poll should be able to exit.\n timer.unref?.()\n\n return {\n stop: () => {\n stopped = true\n clearInterval(timer)\n },\n }\n}\n","import type { Storage } from '@formancy/server-core'\n\n/**\n * Forgetting challenges that can no longer be replayed anyway.\n *\n * A solved challenge is recorded so it cannot be spent twice. Once it has\n * expired the record is doing nothing: the stateless expiry check refuses the\n * solution before the spend is ever consulted. Keeping the row past that point\n * only grows a table.\n *\n * Its own timer rather than a job on the file collector, because the two are\n * configured independently: a deployment can have public forms and no uploads,\n * and that deployment still accumulates spent challenges. Hanging this off the\n * collector would make sweeping conditional on a setting that has nothing to\n * do with it.\n *\n * The same shape as the collector and the outbox worker: a timer in the\n * process, one pass at a time, and a thrown pass complains and comes back\n * rather than stopping the timer. Also not a distributed job — running two is\n * harmless, because deleting an expired row twice is deleting it once.\n */\nexport interface SweeperHandle {\n stop: () => void\n}\n\nexport function startChallengeSweeper(\n storage: Storage,\n options: { intervalMs?: number } = {},\n): SweeperHandle {\n // Hourly. The rows expire in ten minutes and are a challenge hash each, so\n // an hour's worth of them is nothing; sweeping more often would be work\n // nobody asked for.\n const interval = options.intervalMs ?? 60 * 60_000\n let stopped = false\n let running = false\n\n const tick = async (): Promise<void> => {\n if (running || stopped) return\n running = true\n try {\n await storage.forgetExpiredChallenges(new Date().toISOString())\n } catch (error) {\n // A sweeper that throws is a sweeper that stops, and a table that grows\n // for a reason nobody is watching.\n console.error('challenges: a sweep failed', error)\n } finally {\n running = false\n }\n }\n\n const timer = setInterval(() => void tick(), interval)\n timer.unref?.()\n\n return {\n stop: () => {\n stopped = true\n clearInterval(timer)\n },\n }\n}\n","import { createHash, createHmac } from 'node:crypto'\n\n/**\n * AWS Signature Version 4, for the four requests an object store needs.\n *\n * Ours rather than an SDK: sixty lines against a frozen specification, with the\n * algorithm's own vocabulary in the names so it can be read beside AWS's description of\n * it. It signs requests for **any** S3-compatible endpoint, so Garage, real S3 and\n * Backblaze take the same code path\n * ([0064](../../../docs/decisions/0064-an-object-store-behind-the-same-interface.md)).\n *\n * **What verifies it is a real S3 implementation in a container**, refusing a wrong\n * signature with a 403. The unit tests pin the mechanical properties; they cannot tell\n * whether the canonical request is *right*, only that it is consistent with itself.\n */\n\n/** The SHA-256 of an empty body, which a GET or DELETE carries. */\nexport const EMPTY_PAYLOAD_SHA256 =\n 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'\n\nexport interface SignArgs {\n readonly method: 'GET' | 'PUT' | 'DELETE' | 'HEAD'\n readonly url: URL\n /** Headers to sign and send. `host` is required; casing does not matter. */\n readonly headers: Readonly<Record<string, string>>\n /** Hex SHA-256 of the body. S3 sends it as a header as well as signing it. */\n readonly payloadHash: string\n readonly service: string\n readonly region: string\n readonly accessKeyId: string\n readonly secretAccessKey: string\n /** Injected so a test is not a test of the clock. */\n readonly now: Date\n}\n\n/**\n * The headers to send, including `authorization`.\n *\n * Returns headers rather than mutating a request so that the caller's `fetch`\n * options stay the caller's business, and so the signature is inspectable in a\n * test without a server.\n */\nexport function signRequest(args: SignArgs): Record<string, string> {\n const { method, url, payloadHash, service, region, accessKeyId, secretAccessKey, now } = args\n\n // Lowercase every name once, here, so nothing below has to wonder. A header\n // signed under one casing and sent under another is a 403 with no clue in it.\n const headers: Record<string, string> = {}\n for (const [name, value] of Object.entries(args.headers)) {\n headers[name.toLowerCase()] = value\n }\n\n if (headers['host'] === undefined) {\n // AWS requires host in the signature. Failing here, where the message can\n // say so, beats a server rejecting it for a reason it will not explain.\n throw new Error('Refusing to sign a request with no host header.')\n }\n\n const amzDate = basicIso8601(now)\n const dateStamp = amzDate.slice(0, 8)\n\n headers['x-amz-date'] = amzDate\n // S3 requires this header and requires it to equal the hash in the canonical\n // request. Set from the same value rather than computed twice: two routes to\n // one number is how they come to disagree.\n headers['x-amz-content-sha256'] = payloadHash\n\n // Sorted by name, because \"canonical\" means both sides sort identically.\n const names = Object.keys(headers).sort()\n const canonicalHeaders = names\n // Sequential spaces collapse and the value is trimmed, per the spec. A\n // header a proxy reformatted must still hash to the same bytes.\n .map((name) => `${name}:${(headers[name] ?? '').trim().replace(/\\s+/g, ' ')}\\n`)\n .join('')\n const signedHeaders = names.join(';')\n\n const canonicalRequest = [\n method,\n canonicalPath(url, service),\n canonicalQuery(url),\n canonicalHeaders,\n signedHeaders,\n payloadHash,\n ].join('\\n')\n\n const scope = `${dateStamp}/${region}/${service}/aws4_request`\n const stringToSign = [\n 'AWS4-HMAC-SHA256',\n amzDate,\n scope,\n sha256Hex(canonicalRequest),\n ].join('\\n')\n\n // The key is derived per date, region and service, so a leaked signing key is\n // useless tomorrow, elsewhere, or for another service. That is the whole\n // reason for the four-step chain rather than signing with the secret.\n const dateKey = hmac(`AWS4${secretAccessKey}`, dateStamp)\n const regionKey = hmac(dateKey, region)\n const serviceKey = hmac(regionKey, service)\n const signingKey = hmac(serviceKey, 'aws4_request')\n const signature = hmac(signingKey, stringToSign).toString('hex')\n\n headers['authorization'] =\n `AWS4-HMAC-SHA256 Credential=${accessKeyId}/${scope}, ` +\n `SignedHeaders=${signedHeaders}, Signature=${signature}`\n\n return headers\n}\n\n/**\n * `20150830T123600Z` — basic ISO 8601, not the extended form.\n *\n * `toISOString()` gives `2015-08-30T12:36:00.000Z`, which is rejected. Stripping\n * the punctuation is the whole conversion, and the credential scope then wants\n * the same instant as `20150830`, which is why this returns the long one and the\n * caller slices it.\n */\nfunction basicIso8601(at: Date): string {\n return `${at.toISOString().replace(/[-:]/g, '').split('.')[0] ?? ''}Z`\n}\n\n/**\n * The path, encoded **once** for s3 and twice for everything else.\n *\n * This is the one place where s3 departs from the general rule, and getting it\n * wrong produces a signature that is valid for every other AWS service and\n * refused by the only one we call -- and refused only for keys containing a\n * character that needs encoding, which is the worst possible way to find out.\n */\nfunction canonicalPath(url: URL, service: string): string {\n // `url.pathname` is already percent-encoded by URL parsing, which is exactly\n // the single encoding s3 wants.\n const once = url.pathname === '' ? '/' : url.pathname\n if (service === 's3') return once\n return once\n .split('/')\n .map((segment) => uriEncode(decodeURIComponent(segment)))\n .join('/')\n}\n\n/** Sorted by encoded name, values encoded, `=` even when empty. */\nfunction canonicalQuery(url: URL): string {\n const pairs: Array<readonly [string, string]> = []\n for (const [name, value] of url.searchParams) pairs.push([uriEncode(name), uriEncode(value)])\n // Sorted after encoding, per the spec: sorting the raw names orders them\n // differently whenever an encoded byte changes the comparison.\n pairs.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n return pairs.map(([name, value]) => `${name}=${value}`).join('&')\n}\n\n/**\n * AWS's `UriEncode`, which is not `encodeURIComponent`.\n *\n * The differences are small and each one is a 403: `!`, `'`, `(`, `)` and `*`\n * are left alone by `encodeURIComponent` and must be encoded, hex digits must be\n * uppercase, and a space is `%20` rather than `+`.\n */\nfunction uriEncode(value: string): string {\n return encodeURIComponent(value).replace(\n /[!'()*]/g,\n (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,\n )\n}\n\nfunction sha256Hex(value: string): string {\n return createHash('sha256').update(value, 'utf8').digest('hex')\n}\n\nfunction hmac(key: string | Buffer, data: string): Buffer {\n return createHmac('sha256', key).update(data, 'utf8').digest()\n}\n","import { createHash } from 'node:crypto'\nimport { Readable } from 'node:stream'\n\nimport type { FileStore } from './file-store.js'\nimport { EMPTY_PAYLOAD_SHA256, signRequest } from './sigv4.js'\n\n/**\n * Uploaded bytes in an S3-compatible object store.\n *\n * The second implementation of `FileStore`. The local one is right for a single\n * container with a volume and is the ceiling on everything above it: two replicas with\n * two volumes each accept uploads the other cannot serve, so any deployment past one\n * server needs this.\n *\n * **Not tied to Amazon.** The design calls for Garage, which is what the\n * integration test runs and what belongs in the compose file; the same code path\n * serves MinIO, Backblaze, Cloudflare R2 and real S3, because the only thing they\n * need in common is SigV4 and path-style addressing.\n *\n * **Bytes still pass through the server**, so the request body cap is the ceiling on a\n * file. A presigned PUT straight from the browser is the roadmap item that removes the\n * server from the data path; this replaces where the bytes land without touching how\n * they arrive.\n *\n * **No multipart.** A single PUT is one request, so the practical ceiling is whatever\n * the store accepts in one -- 5 GB for S3, and far above `FORMANCY_MAX_FILE_BYTES`.\n */\nexport interface S3FileStoreConfig {\n /** Base URL of the endpoint, e.g. `http://garage:3900` or an S3 regional URL. */\n readonly endpoint: string\n readonly bucket: string\n /** Garage answers to any region name; real S3 does not. */\n readonly region: string\n readonly accessKeyId: string\n readonly secretAccessKey: string\n /**\n * How long one request may take before it is abandoned, in milliseconds.\n *\n * An object store that stops answering must not become a server that stops\n * answering. Defaults to thirty seconds, which is generous for one object and\n * still bounded.\n */\n readonly timeoutMs?: number\n}\n\nexport function createS3FileStore(config: S3FileStoreConfig): FileStore {\n const endpoint = config.endpoint.replace(/\\/+$/, '')\n const timeoutMs = config.timeoutMs ?? 30_000\n\n /**\n * The object's URL, with the key's slashes kept and everything else encoded.\n *\n * A key is a path inside the bucket, so its separators are structural. Every\n * other character has to be encoded or the request line is invalid -- and a\n * space encoded as `+`, which is what form encoding would do, names a\n * different object.\n */\n const urlFor = (key: string): URL => {\n if (key === '' || key.includes('\\\\') || key.split('/').includes('..')) {\n // Keys are minted by the server today. Checked anyway, because the local\n // store checks it and the two must not disagree about what is legal.\n throw new Error(`Refusing a storage key that could address another bucket: ${key}`)\n }\n const path = key.split('/').map(encodeSegment).join('/')\n return new URL(`${endpoint}/${encodeSegment(config.bucket)}/${path}`)\n }\n\n const send = async (\n method: 'GET' | 'PUT' | 'DELETE' | 'HEAD',\n key: string,\n body?: Buffer,\n ): Promise<Response> => {\n const url = urlFor(key)\n const payloadHash =\n body === undefined\n ? EMPTY_PAYLOAD_SHA256\n : createHash('sha256').update(body).digest('hex')\n\n // `content-length` is deliberately neither signed nor set. undici refuses a\n // manually supplied one -- `InvalidArgumentError: invalid content-length\n // header` -- and computes its own from the body, so setting it is both\n // impossible and unnecessary. Nothing is lost by not signing it: AWS requires\n // only `host` and the `x-amz-*` headers in the signature, and\n // `x-amz-content-sha256` is a hash of the exact bytes, which constrains the\n // length far more tightly than a signed length would.\n const headers = signRequest({\n method,\n url,\n headers: { host: url.host },\n payloadHash,\n service: 's3',\n region: config.region,\n accessKeyId: config.accessKeyId,\n secretAccessKey: config.secretAccessKey,\n now: new Date(),\n })\n\n return fetch(url, {\n method,\n headers,\n ...(body === undefined ? {} : { body: new Uint8Array(body) }),\n signal: AbortSignal.timeout(timeoutMs),\n })\n }\n\n /**\n * A status that means \"there is no such object\", as opposed to one that means\n * the store could not answer.\n *\n * The distinction is the whole reason this is a named function. Reading a\n * could-not-answer as absence makes the collector delete the row for bytes that\n * still exist and makes a download return nothing for a file the person can see\n * listed.\n *\n * **404 only, and 403 deliberately not.** S3 answers 403 for an object a caller may\n * not list, but this caller owns the bucket -- so 403 means the credentials are\n * wrong, and reading that as absence would make a misconfigured deployment look like\n * one where every file has vanished and have the collector delete every row.\n */\n const isAbsent = (response: Response): boolean => response.status === 404\n\n const failed = (method: string, key: string, response: Response): Error =>\n new Error(`S3 ${method} of ${key} failed: ${String(response.status)} ${response.statusText}`)\n\n return {\n async put(key, bytes) {\n const response = await send('PUT', key, bytes)\n if (!response.ok) throw failed('PUT', key, response)\n // The body is an error document or nothing. Reading it releases the\n // connection back to the pool, which an undrained response does not.\n await response.arrayBuffer()\n },\n\n async open(key) {\n const response = await send('GET', key)\n if (isAbsent(response)) {\n await response.arrayBuffer()\n return undefined\n }\n if (!response.ok || response.body === null) throw failed('GET', key, response)\n // Streamed rather than buffered: a large attachment should not be held in\n // memory on its way to one downloader.\n return Readable.fromWeb(response.body)\n },\n\n async remove(key) {\n const response = await send('DELETE', key)\n // Absent is success. A collector that crashed between deleting the bytes\n // and deleting the row has to be safe to run again.\n if (response.ok || isAbsent(response)) {\n await response.arrayBuffer()\n return\n }\n throw failed('DELETE', key, response)\n },\n\n async sizeOf(key) {\n const response = await send('HEAD', key)\n if (isAbsent(response)) return undefined\n if (!response.ok) throw failed('HEAD', key, response)\n const length = response.headers.get('content-length')\n // A store that answered without a length cannot be used to check that the\n // bytes match what was promised, and pretending it said zero would fail\n // that check by declaring the file empty.\n if (length === null) throw new Error(`S3 HEAD of ${key} returned no content-length.`)\n return Number(length)\n },\n }\n}\n\n/**\n * AWS's `UriEncode` for one path segment.\n *\n * `encodeURIComponent` leaves `!'()*` alone and S3 wants them encoded, and its\n * hex digits are already uppercase. Duplicated from the signer rather than\n * shared, because the signer's copy is about hashing and this one is about the\n * request line: if they ever need to differ, they differ, and a shared helper\n * would make that a conversation instead of an edit.\n */\nfunction encodeSegment(value: string): string {\n return encodeURIComponent(value).replace(\n /[!'()*]/g,\n (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,\n )\n}\n","import { connect } from 'node:net'\nimport type { Scanner, ScanVerdict } from '@formancy/server-core'\n\n/** How much is sent per INSTREAM chunk. clamd takes chunks of any size up to its stream limit. */\nconst CHUNK = 64 * 1024\n\n/**\n * clamd's own default `StreamMaxLength`, 100 MiB — as the `clamd.conf` ClamAV 1.5.4 ships\n * says, and as measured against it: a 90 MiB stream was answered, a 110 MiB one refused.\n */\nexport const CLAMD_DEFAULT_MAX_BYTES = 100 * 1024 * 1024\n\n/**\n * ClamAV's daemon, asked over its INSTREAM command\n * ([0131](../../../docs/decisions/0131-an-upload-is-scanned-before-it-is-kept.md)).\n *\n * The protocol is clamd's own and small enough to speak directly — the command, the bytes in\n * length-prefixed chunks, a zero-length chunk to end them, and one line back — so this adds\n * no dependency to the server. Its tests run against a stand-in that speaks the protocol as\n * clamd's manual describes it; it was run once against ClamAV 1.5.4 itself, and the\n * documentation says what that showed and what it did not.\n *\n * **Only `stream: OK` is clean.** A finding is refused by its name. A file over clamd's size\n * limit is refused too, because sending it again changes nothing. Anything else — an answer\n * this does not understand, no answer, no daemon — rejects, which the use-case reads as a\n * scanner that cannot be asked, and refuses the file for.\n *\n * **`maxBytes` is clamd's `StreamMaxLength`, and is checked before a byte is sent.** Past\n * it, clamd says so and closes the connection while bytes may still be arriving. Against the\n * stand-in the bytes in flight reset it and the answer was lost to `ECONNRESET`, which reads\n * as a scanner that is down and would tell the person to try again forever; the real clamd\n * measured here answered intact. Checked first, the outcome does not depend on which.\n * Set it to what clamd is configured with.\n */\nexport function createClamdScanner({\n host,\n port,\n maxBytes = CLAMD_DEFAULT_MAX_BYTES,\n timeoutMs = 30_000,\n}: {\n host: string\n port: number\n maxBytes?: number\n timeoutMs?: number\n}): Scanner {\n return {\n scan: (_file, bytes) =>\n new Promise<ScanVerdict>((resolve, reject) => {\n if (bytes.byteLength > maxBytes) {\n resolve({\n clean: false,\n finding: `could not be scanned: larger than the scanner accepts (${String(maxBytes)} bytes)`,\n })\n return\n }\n const socket = connect({ host, port })\n const answer: Buffer[] = []\n let failure: Error | undefined\n\n socket.setTimeout(timeoutMs, () =>\n socket.destroy(\n new Error(\n `clamd at ${host}:${String(port)} did not answer within ${String(timeoutMs)} ms`,\n ),\n ),\n )\n socket.on('connect', () => {\n socket.write('zINSTREAM\\0')\n for (let at = 0; at < bytes.byteLength; at += CHUNK) {\n const piece = bytes.subarray(at, at + CHUNK)\n const length = Buffer.alloc(4)\n length.writeUInt32BE(piece.byteLength)\n socket.write(length)\n socket.write(piece)\n }\n // The zero-length chunk that ends the stream. Written, not `end()`ed: clamd\n // answers on the same connection and closes it itself.\n socket.write(Buffer.alloc(4))\n })\n socket.on('data', (data) => answer.push(data))\n // Kept rather than rejected on: clamd past its size limit answers and hangs up\n // while bytes are still being written, and the answer is what counts.\n socket.on('error', (error) => {\n failure = error\n })\n socket.on('close', () => {\n const reply = Buffer.concat(answer).toString('utf8').replace(/\\0+$/, '').trim()\n if (reply === '') {\n reject(\n failure ?? new Error(`clamd at ${host}:${String(port)} closed without answering`),\n )\n return\n }\n const verdict = verdictOf(reply)\n if (verdict === undefined)\n reject(new Error(`clamd answered something unexpected: ${reply}`))\n else resolve(verdict)\n })\n }),\n }\n}\n\nfunction verdictOf(reply: string): ScanVerdict | undefined {\n if (reply === 'stream: OK') return { clean: true }\n const found = /^stream: (.+) FOUND$/.exec(reply)\n if (found !== null) return { clean: false, finding: found[1]! }\n if (/size limit exceeded/i.test(reply)) {\n return { clean: false, finding: `could not be scanned: ${reply.replace(/\\.?\\s*ERROR$/, '')}` }\n }\n return undefined\n}\n","import { randomBytes } from 'node:crypto'\nimport postgres from 'postgres'\nimport { createApp } from './app.js'\nimport { bootstrapSchema } from './db.js'\nimport { createPostgresStorage } from './postgres-storage.js'\nimport { startOutboxWorker } from './outbox-worker.js'\nimport { startFileCollector } from './file-collector.js'\nimport { startChallengeSweeper } from './challenge-sweeper.js'\nimport { createLocalFileStore } from './file-store.js'\nimport type { FileStore } from './file-store.js'\nimport { createS3FileStore } from './s3-file-store.js'\nimport { CLAMD_DEFAULT_MAX_BYTES, createClamdScanner } from './clamd-scanner.js'\n\n// recheck ships a 23 MB JVM jar and a native binary per platform as OPTIONAL\n// dependencies and falls back to a pure-JavaScript engine without them. For\n// one static analysis at publish time, the jar is a large thing to carry in a\n// self-hosted container and the per-platform binaries are an awkward thing to\n// pin in an SBOM. Choosing the pure engine explicitly also makes the verdict\n// deterministic rather than dependent on what happened to install.\nprocess.env['RECHECK_BACKEND'] ??= 'pure'\n\n/**\n * The runnable server: `node dist/main.mjs` with DATABASE_URL set, or\n * `docker compose up` from the repo root, which supplies both.\n *\n * Bootstraps its own tables on start — a self-hosted skeleton that works five\n * minutes after `git clone` is the adoption funnel; migrations arrive with the\n * lifecycle work.\n */\nconst databaseUrl = process.env['DATABASE_URL']\nif (databaseUrl === undefined || databaseUrl === '') {\n console.error('DATABASE_URL is required, e.g. postgres://formancy:formancy@localhost:5432/formancy')\n process.exit(1)\n}\n\nconst port = Number(process.env['PORT'] ?? 4380)\nconst sql = postgres(databaseUrl)\n\nlet authSecret = process.env['FORMANCY_AUTH_SECRET']\nif (authSecret === undefined || authSecret === '') {\n // A generated secret keeps `docker compose up` working, at the cost of every\n // session dying on restart. Say so loudly rather than failing dev cold.\n authSecret = randomBytes(33).toString('base64url')\n console.warn(\n 'FORMANCY_AUTH_SECRET is not set: generated an ephemeral one, sessions will not survive a restart.',\n )\n}\n\nconst adminEmail = process.env['FORMANCY_ADMIN_EMAIL']\nconst adminPassword = process.env['FORMANCY_ADMIN_PASSWORD']\n\n/**\n * Where uploaded bytes go.\n *\n * Absent means this deployment accepts no files, and that is a supported\n * state rather than a misconfiguration: a form with a file field still renders\n * and still submits, and the field says plainly that there is nowhere to put\n * one. Turning uploads on is naming a directory, which in a container is\n * naming a volume — and a volume is the one thing a self-hoster has to think\n * about, so it is not defaulted.\n */\nconst filesDirectory = process.env['FORMANCY_FILES_DIR']\nconst s3Endpoint = process.env['FORMANCY_S3_ENDPOINT']\n\nif (filesDirectory !== undefined && s3Endpoint !== undefined) {\n // Two stores means half the files are in one and half in the other, and\n // nothing records which -- so a later reader gets \"no such file\" for bytes\n // that exist in the store it did not ask. Refusing at startup is the only\n // point at which this is cheap to fix.\n throw new Error(\n 'Set FORMANCY_FILES_DIR or FORMANCY_S3_ENDPOINT, not both: two stores means ' +\n 'files land in one and are looked for in the other.',\n )\n}\n\n/**\n * The object store, when one is configured.\n *\n * Every field is required once the endpoint is set, and none is defaulted. A\n * bucket name guessed wrong is a deployment that accepts uploads into nothing;\n * credentials guessed wrong are a deployment where every file reads as missing.\n * Both fail here instead.\n */\nconst s3Store = ((): FileStore | undefined => {\n if (s3Endpoint === undefined) return undefined\n\n const required = (name: string): string => {\n const value = process.env[name]\n if (value === undefined || value === '') {\n throw new Error(`${name} is required when FORMANCY_S3_ENDPOINT is set.`)\n }\n return value\n }\n\n return createS3FileStore({\n endpoint: s3Endpoint,\n bucket: required('FORMANCY_S3_BUCKET'),\n // Part of the credential scope, so a wrong region is a signature the store\n // computes differently and rejects. Garage answers to any name and real S3\n // does not, which is why there is no default.\n region: required('FORMANCY_S3_REGION'),\n accessKeyId: required('FORMANCY_S3_ACCESS_KEY_ID'),\n secretAccessKey: required('FORMANCY_S3_SECRET_ACCESS_KEY'),\n })\n})()\n\nconst fileStore =\n s3Store ?? (filesDirectory === undefined ? undefined : createLocalFileStore(filesDirectory))\n\nconst maxFileBytes = Number(process.env['FORMANCY_MAX_FILE_BYTES'] ?? 10 * 1024 * 1024)\nif (!Number.isFinite(maxFileBytes) || maxFileBytes <= 0) {\n throw new Error('FORMANCY_MAX_FILE_BYTES must be a positive number of bytes.')\n}\n\n/**\n * A ClamAV daemon to ask about every upload before its bytes are kept.\n *\n * Unset is a supported state: no file is scanned, which the documentation says. Set, a\n * file is kept only once clamd has called it clean, and refused when clamd cannot be\n * reached — the point of configuring a scanner is that nothing unscanned gets in\n * ([0131](../../../docs/decisions/0131-an-upload-is-scanned-before-it-is-kept.md)).\n * Not checked at startup: clamd takes minutes to load its signatures, and a server that\n * refused to start until then would turn a slow scanner into an outage of everything.\n */\nconst clamdHost = process.env['FORMANCY_CLAMD_HOST']\nconst clamdPort = Number(process.env['FORMANCY_CLAMD_PORT'] ?? 3310)\nconst clamdMaxBytes = Number(process.env['FORMANCY_CLAMD_MAX_BYTES'] ?? CLAMD_DEFAULT_MAX_BYTES)\nif (!Number.isInteger(clamdPort) || clamdPort <= 0 || clamdPort > 65_535) {\n throw new Error('FORMANCY_CLAMD_PORT must be a port number.')\n}\nif (!Number.isFinite(clamdMaxBytes) || clamdMaxBytes <= 0) {\n throw new Error(\"FORMANCY_CLAMD_MAX_BYTES must be a positive number of bytes: clamd's StreamMaxLength.\")\n}\nconst scanner =\n clamdHost === undefined || clamdHost === ''\n ? undefined\n : createClamdScanner({ host: clamdHost, port: clamdPort, maxBytes: clamdMaxBytes })\n\n/**\n * Turns the proof-of-work challenge on for anonymous submissions.\n *\n * Unset is a supported state rather than a misconfiguration: a deployment\n * whose forms all require a session has no anonymous surface to protect, and\n * the challenge route says so with a 404 rather than failing. A deployment\n * with public forms should set it — the other layers are rate limits, an\n * origin allowlist and a body cap, all of which an attacker with a few\n * addresses walks past.\n *\n * Separate from FORMANCY_AUTH_SECRET so that rotating one does not invalidate\n * the other: rotating this one costs an unsolved puzzle, rotating that one\n * costs everybody their session.\n */\nconst challengeSecret = process.env['FORMANCY_CHALLENGE_SECRET']\nif (challengeSecret !== undefined && challengeSecret.length < 32) {\n throw new Error('FORMANCY_CHALLENGE_SECRET must be at least 32 characters, or unset.')\n}\n\nawait bootstrapSchema(sql)\nconst storage = createPostgresStorage(sql)\nconst app = await createApp(storage, {\n authSecret,\n ...(adminEmail !== undefined && adminPassword !== undefined\n ? { bootstrapAdmin: { email: adminEmail, password: adminPassword } }\n : {}),\n ...(fileStore === undefined ? {} : { fileStore }),\n ...(challengeSecret === undefined ? {} : { challengeSecret }),\n ...(scanner === undefined ? {} : { scanner }),\n maxFileBytes,\n})\n\n// Queued deliveries are useless until something sends them.\nconst outbox = startOutboxWorker(storage, {\n ...(process.env['FORMANCY_WEBHOOK_ALLOW_HTTP'] === 'true' ? { allowHttp: true } : {}),\n // Gives up the SSRF guard. For a sidecar receiver on a trusted network, and\n // for nothing else.\n ...(process.env['FORMANCY_WEBHOOK_ALLOW_PRIVATE'] === 'true'\n ? { allowPrivateAddresses: true }\n : {}),\n})\n// Somebody who attaches a file and closes the tab leaves bytes behind. A disk\n// that fills up for a reason nobody is watching is the most tedious outage\n// there is.\nconst collector =\n fileStore === undefined ? undefined : startFileCollector(storage, fileStore)\n\n// Independent of the collector: a deployment can have public forms and no\n// uploads, and that deployment still accumulates spent challenges.\nconst sweeper = challengeSecret === undefined ? undefined : startChallengeSweeper(storage)\n\nfor (const signal of ['SIGINT', 'SIGTERM'] as const) {\n process.once(signal, () => {\n outbox.stop()\n collector?.stop()\n sweeper?.stop()\n void app.close().then(() => process.exit(0))\n })\n}\n\nawait app.listen({ port, host: process.env['HOST'] ?? '0.0.0.0' })\nconsole.log(`formancy server listening on :${port}`)\n\nfor (const signal of ['SIGINT', 'SIGTERM'] as const) {\n process.on(signal, () => {\n void app\n .close()\n .then(() => sql.end())\n .then(() => process.exit(0))\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;AA4CA,SAAgB,kBACd,KACA,UAA6B,CAAC,GACV;CACpB,IAAI;CACJ,IAAI;EACF,MAAM,IAAI,IAAI,GAAG;CACnB,QAAQ;EACN,OAAO;CACT;CAEA,IAAI,IAAI,aAAa,YAAY,IAAI,aAAa,SAChD,OAAO,gDAAgD,IAAI,SAAS,QAAQ,KAAK,EAAE,EAAE;CAGvF,IAAI,IAAI,aAAa,WAAW,QAAQ,cAAc,MACpD,OAAO;CAGT,IAAI,IAAI,aAAa,MAAM,IAAI,aAAa,IAC1C,OAAO;CAMT,IACE,QAAQ,0BAA0B,QAClC,YAAY,IAAI,QAAQ,KACxB,iBAAiB,IAAI,QAAQ,GAE7B,OAAO,GAAG,IAAI,SAAS;AAI3B;;;AC/BA,MAAM,qBAAqB;AAE3B,eAAe,WAAW,UAAqC;CAE7D,QAAO,MADeA,OAAU,UAAU;EAAE,KAAK;EAAM,UAAU;CAAK,CAAC,EAAA,CACxD,KAAK,WAAW,OAAO,OAAO;AAC/C;AAEA,eAAsB,QACpB,OAQA,UAA2B,CAAC,GACH;CACzB,MAAM,UAAU,kBAAkB,MAAM,KAAK;EAC3C,WAAW,QAAQ,aAAa;EAChC,uBAAuB,QAAQ,yBAAyB;CAC1D,CAAC;CACD,IAAI,YAAY,KAAA,GAAW,OAAO;EAAE,IAAI;EAAO,OAAO;CAAQ;CAE9D,MAAM,MAAM,IAAI,IAAI,MAAM,GAAG;CAC7B,MAAM,UAAU,QAAQ,WAAW;CAEnC,IAAI;CACJ,IAAI;EACF,YAAY,MAAM,QAAQ,IAAI,QAAQ;CACxC,SAAS,OAAO;EACd,OAAO;GAAE,IAAI;GAAO,OAAO,qBAAqB,IAAI,SAAS,IAAI,OAAO,KAAK;EAAI;CACnF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Fastify routes and Postgres storage over @formancy/server-core.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -17,8 +17,8 @@
|
|
|
17
17
|
],
|
|
18
18
|
"dependencies": {
|
|
19
19
|
"@fastify/rate-limit": "^11.2.0",
|
|
20
|
-
"@formancy/server-core": "0.
|
|
21
|
-
"@formancy/spec": "0.
|
|
20
|
+
"@formancy/server-core": "0.4.0",
|
|
21
|
+
"@formancy/spec": "0.4.0",
|
|
22
22
|
"@node-rs/argon2": "^2.2.1",
|
|
23
23
|
"drizzle-orm": "^0.45.2",
|
|
24
24
|
"fastify": "^5.12.5",
|