Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Add a daily backup to a second Blob store, and a restore script
Claudec509a4ee2334
diff --git a/.env.example b/.env.exampleindex 6d03fcf..6f543bf 100644--- a/.env.example+++ b/.env.example@@ -132,3 +132,9 @@ EMAIL_DRIVER=capture# Audit rows are copied to the function logs as JSON lines, for a Vercel log# drain to send on to a SIEM. off keeps them out of the logs.# AUDIT_LOG=off++# A daily backup to a second, private Vercel Blob store: its read-write+# token, and how many days of copies to keep (30 by default). See+# docs/backup-and-restore.md.+# BACKUP_BLOB_READ_WRITE_TOKEN=+# BACKUP_KEEP_DAYS=30diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 041a7e8..e353298 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -37,6 +37,11 @@ release says when it does.- Audit rows (site and document trails) and security events are written tothe function logs as JSON lines once saved, so a Vercel log drain candeliver them to a SIEM. `AUDIT_LOG=off` stops the audit lines.+- A daily backup of the database and files to a second, private Blob store,+ turned on with `BACKUP_BLOB_READ_WRITE_TOKEN`, and `npm run restore-backup`+ to restore it into a new database and store. See+ `docs/backup-and-restore.md`. `vercel.json` has a second daily cron job,+ which does nothing until the token is set.This release changes the database (`20261117090000_sign_in_security.sql`,`20261117100000_session_controls.sql`), which the production build applies.diff --git a/docs/backup-and-restore.md b/docs/backup-and-restore.mdnew file mode 100644index 0000000..ffc54b8--- /dev/null+++ b/docs/backup-and-restore.md@@ -0,0 +1,66 @@+# Backup and restore++A SignuDoc install keeps its records in two places: the Postgres database (accounts, envelopes, audit trails, settings) and the Vercel Blob store (the PDFs, sealed copies and certificates). This page covers what protects each one, how to turn on SignuDoc's own daily backup, and how to restore from it.++## What you have without doing anything++- **Neon** keeps the database's history for a restore window and can restore it to a point in time, or branch from it, from the Neon console. The window is short on the free plan and longer on paid plans; see Neon's plan page for the current numbers. It protects against a bad change, not against losing the Neon project or account.+- **Vercel Blob** has no versions or recycle bin. A deleted file is gone.++So the daily backup is worth turning on for any install whose documents matter. It is optional, and you set it up by hand.++## Turn on the daily backup++The backup copies the install, once a day, to a second Blob store that you keep apart from the first.++1. **Make the backup store.** In Vercel, go to Storage, Create, Blob, and make a **private** store. Make it in a different Vercel team from the install if you can, so that losing the install's team, or an admin there, does not take the backup with it. Do not connect it to the install's project.+2. **Copy its read-write token.** In the new store, open its settings (or `.env.local` snippet) and copy `BLOB_READ_WRITE_TOKEN`. It starts with `vercel_blob_rw_`.+3. **Give it to the install.** In the install's Vercel project, under Settings, Environment Variables, add `BACKUP_BLOB_READ_WRITE_TOKEN` with that token, for Production. Mark it Sensitive.+4. **Set `CRON_SECRET`** too, if you have not already (any long random string), so only Vercel's own cron call can start a backup.+5. Deploy again.++From then on Vercel calls `/api/internal/backup` every day at 08:00 UTC (see `vercel.json`). Each run:++- writes the whole database, read as one consistent snapshot, to `database/<time>.ndjson.gz` in the backup store, and keeps `BACKUP_KEEP_DAYS` days of them (30 unless you set it, and never fewer than the newest three);+- copies every file that is new or changed since the last run to `files/<same path>`. A run copies for up to four minutes; a first backup of a large install may take a few days to catch up, and each later run only copies what changed;+- keeps the copy of a file that was deleted from the install (by the retention rules, for example) for `BACKUP_KEEP_DAYS` more days, then removes it, so the backup does not hold a document much longer than your retention rules allow.++Each run writes a `backup_finished` line to the function logs (with the counts), or `backup_failure` if it failed. With a log drain, alert on those. The app refuses a token for its own store, because that backup would not survive what it is for.++**Cost.** The backup store holds about as much as the install's store, plus the database copies. On a Vercel Hobby account, a second store in the same account counts against the same free Blob storage, so it halves how much your install can hold for $0. A store in another team has its own allowance. Each copied file is one upload to the backup store.++**Check it works.** After the first run, open the backup store in Vercel and look for `database/` and `files/`. Every few months, do a test restore (below) into a throwaway Neon project, so you know the steps before you need them.++## Restore++A restore goes into a **new, empty** database and Blob store, never over a live install. You can then point the install at them, or deploy a new install on them.++You need a computer with Node.js 24 and a copy of this repository at the same version as the install (or newer).++1. Make a new Neon database (a new Neon project, or a new branch with no data) and copy its connection string.+2. Make a new private Blob store for the restored files and copy its read-write token. Or, if the install's store still exists and only the database was lost, use `--skip-files` and skip this.+3. In the repository folder:++ ```sh+ npm ci+ export DATABASE_URL='postgres://…' # the new, empty database+ export BLOB_READ_WRITE_TOKEN='vercel_blob_rw_…' # the new Blob store+ export BACKUP_BLOB_READ_WRITE_TOKEN='vercel_blob_rw_…'+ npm run restore-backup -- --list # see which backups there are+ npm run restore-backup # restore the newest one+ ```++ `--backup database/<name>` restores an older one instead. The script applies the migrations, loads the database in one transaction (so a failed restore leaves nothing half done), then copies the files back to their own paths. It refuses a database that already has accounts in it, and a backup made by a newer SignuDoc than the copy you are running.++4. Connect the new database and Blob store to the install's Vercel project (or a new one) in place of the old ones, keep `BETTER_AUTH_SECRET` the same as before, and deploy. Two-step sign-in keys are encrypted with that secret, and session cookies are signed with it; if it changes, everyone signs in again and sets up two-step sign-in again.+5. Sign in, open a finished document, and check its audit trail and download.++What a restore brings back: everything in the database at the time of the backup, and every file as of the last run. A document sent after the last backup is not in it. The hash chains in both audit trails come back exactly as they were, so they still verify.++## In a security review++- **Backup frequency:** daily, at 08:00 UTC.+- **Retention:** `BACKUP_KEEP_DAYS` (30 by default) for database copies and deleted files.+- **Location and access:** a private Vercel Blob store chosen by the deployer, ideally in another Vercel team. Only its read-write token can read it.+- **Encryption:** Vercel Blob encrypts stored data at rest (see Vercel's security documentation). The database copy holds the same data as the database, including password hashes and the encrypted two-step sign-in keys, so treat the backup store's token like the database password.+- **Restore testing:** the procedure above, run by the deployer on a schedule they choose.diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 4acc60c..affae25 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -141,6 +141,7 @@ A deployment made with the button needs no environment variables. These are ther| `SEAL_TIMESTAMP_URL` | An RFC 3161 timestamp server that adds a trusted time to each seal, and long-term validation. See [Long-term validation](#long-term-validation). || `EIDEASY_CLIENT_ID`, `EIDEASY_SECRET` | Let senders ask for advanced or qualified signatures in the signers' own names, through eID Easy. See [Signatures in the signers' own names](#signatures-in-the-signers-own-names-eidas-ades-and-qes). || `CSC_API_URL`, `CSC_CLIENT_ID`, `CSC_CLIENT_SECRET` | The same through a trust service provider's remote signing service (CSC API v2). See [Signatures in the signers' own names](#signatures-in-the-signers-own-names-eidas-ades-and-qes). |+| `BACKUP_BLOB_READ_WRITE_TOKEN`, `BACKUP_KEEP_DAYS` | A daily backup of the database and files to a second Blob store. See [Backup and restore](backup-and-restore.md). || `AUDIT_LOG` | `off` keeps audit rows out of the function logs. See [Send the audit trail to your SIEM](#send-the-audit-trail-to-your-siem). || `SSO_ISSUER`, `SSO_CLIENT_ID`, `SSO_CLIENT_SECRET` | Sign in through your organization's identity provider (Okta, Entra ID, Google Workspace). `PASSWORD_SIGN_IN=off` then turns passwords off. See [Single sign-on](#single-sign-on). |@@ -278,6 +279,10 @@ By default the parts of an install run in the US. To keep signers' data in the ESome data still leaves the EU: Vercel's and Resend's account metadata and logs, for example. The processors' agreements and the EU-US Data Privacy Framework cover that, but check it against your own obligations.+## Backups++Turn on the daily backup to a second Blob store, and learn the restore steps, in [Backup and restore](backup-and-restore.md).+## Daily cleanupOnce a day the app deletes drafts nobody has touched for 30 days, finishes account deletions that were requested, and clears expired download links, finished rate limit counters, and trips to a signing provider that nobody came back from, with the signer revisions nothing needs any more (a file that could not be deleted is tried again the next day). The same run sends the automatic reminders that are due and tells a sender when an envelope has passed its signing deadline. The work is done by a request to:diff --git a/package.json b/package.jsonindex db147f2..61dd4e4 100644--- a/package.json+++ b/package.json@@ -20,6 +20,7 @@"format": "prettier --write .","format:check": "prettier --check .","test": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON --test \"src/**/*.test.ts\" \"db/**/*.test.mjs\"",+ "restore-backup": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON scripts/restore-backup.ts","test:db": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON --test --test-concurrency=1 \"src/**/*.dbtest.ts\"","test:e2e": "playwright test"},diff --git a/scripts/restore-backup.ts b/scripts/restore-backup.tsnew file mode 100644index 0000000..86c868f--- /dev/null+++ b/scripts/restore-backup.ts@@ -0,0 +1,127 @@+// Restores a SignuDoc install from the daily backup (src/lib/backup.ts) into+// a new, empty database and Blob store. See docs/backup-and-restore.md.+//+// DATABASE_URL=postgres://... the new, empty database+// BLOB_READ_WRITE_TOKEN=vercel_blob_rw_ the new install's Blob store+// BACKUP_BLOB_READ_WRITE_TOKEN=... the backup store+//+// npm run restore-backup -- --list list the database backups+// npm run restore-backup restore the newest one, and the files+// npm run restore-backup -- --backup <path> restore that one+// npm run restore-backup -- --skip-files the database only+//+// It applies the migrations first, then loads the backup in one transaction,+// so a restore that fails leaves the database as it was.++import pg from "pg";++import {+ createVercelBlobStore,+ DATABASE_PREFIX,+ findLatestDatabaseBackup,+ restoreDatabase,+ restoreFiles,+} from "../src/lib/backup.ts";+import { runMigrations } from "../db/migrate.mjs";++function readArgument(name: string): string | null {+ const index = process.argv.indexOf(name);++ return index >= 0 ? (process.argv[index + 1] ?? null) : null;+}++function requireVariable(name: string): string {+ const value = process.env[name]?.trim();++ if (!value) {+ console.error(`Set ${name} first. See docs/backup-and-restore.md.`);+ process.exit(1);+ }++ return value;+}++async function main() {+ const backupStore = createVercelBlobStore(+ requireVariable("BACKUP_BLOB_READ_WRITE_TOKEN"),+ );++ if (process.argv.includes("--list")) {+ let cursor: string | undefined;++ do {+ const page = await backupStore.list({ cursor, prefix: DATABASE_PREFIX });++ for (const blob of page.blobs) {+ console.log(+ `${blob.pathname} ${String(Math.round(blob.size / 1024))} KB`,+ );+ }++ cursor = page.hasMore ? page.cursor : undefined;+ } while (cursor);++ return;+ }++ const connectionString = requireVariable("DATABASE_URL");+ const appStore = process.argv.includes("--skip-files")+ ? null+ : createVercelBlobStore(requireVariable("BLOB_READ_WRITE_TOKEN"));+ const backupPath =+ readArgument("--backup") ?? (await findLatestDatabaseBackup(backupStore));++ if (!backupPath) {+ console.error("The backup store has no database backups yet.");+ process.exit(1);+ }++ console.log("Applying migrations…");+ await runMigrations({ connectionString });++ const database = new pg.Pool({ connectionString, max: 2 });++ try {+ console.log(`Restoring ${backupPath}…`);++ const { rows } = await restoreDatabase({+ backupPath,+ database,+ store: backupStore,+ });++ for (const [table, count] of Object.entries(rows)) {+ console.log(` ${table}: ${String(count)} rows`);+ }+ } finally {+ await database.end();+ }++ if (appStore) {+ console.log("Copying files…");++ const { copied, failures } = await restoreFiles({+ source: backupStore,+ target: appStore,+ });++ console.log(` ${String(copied)} files copied.`);++ if (failures.length > 0) {+ console.error(` ${String(failures.length)} could not be copied:`);++ for (const pathname of failures) {+ console.error(` ${pathname}`);+ }++ process.exitCode = 1;+ }+ }++ console.log("Done. Deploy the new install and sign in to check it.");+}++main().catch((error: unknown) => {+ console.error(error instanceof Error ? error.message : error);+ process.exit(1);+});diff --git a/src/app/api/internal/backup/route.ts b/src/app/api/internal/backup/route.tsnew file mode 100644index 0000000..5b38d68--- /dev/null+++ b/src/app/api/internal/backup/route.ts@@ -0,0 +1,112 @@+import { NextResponse } from "next/server";++import {+ createVercelBlobStore,+ isBackupStoreTheAppStore,+ readBackupSettings,+ runBackup,+} from "@/lib/backup";+import { consumeRateLimit } from "@/lib/security/rate-limit";+import { identifyRetentionCaller } from "@/lib/retention-job";+import { logRouteError, logSecurityEvent } from "@/lib/security/logging";+import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";+import { resolveStorageDriver } from "@/lib/services/storage/driver";++// The daily backup to a second Blob store (src/lib/backup.ts), called by+// Vercel's cron job (vercel.json). It does nothing until+// BACKUP_BLOB_READ_WRITE_TOKEN is set.+//+// Callers are trusted the same way as the daily cleanup's: with CRON_SECRET+// set, only Vercel's own call gets in. Without it, anyone may call, and a+// run happens at most once in 20 hours whoever asks, which is the most an+// outside caller can make it cost.++export const maxDuration = 300;++const ANONYMOUS_RUN_INTERVAL_MS = 20 * 60 * 60 * 1000;+/** Leaves time to write the summary before the function is stopped. */+const COPY_BUDGET_MS = 240_000;++async function handle(request: Request) {+ const startedAt = Date.now();+ const caller = identifyRetentionCaller(request.headers.get("authorization"));++ if (caller === "denied") {+ return NextResponse.json({ error: "Unauthorized." }, { status: 401 });+ }++ const settings = readBackupSettings();++ if (!settings || resolveStorageDriver() !== "blob") {+ return caller === "authorized"+ ? NextResponse.json({ status: "not_configured" })+ : new NextResponse(null, { status: 204 });+ }++ if (isBackupStoreTheAppStore(settings)) {+ logSecurityEvent("error", {+ category: "backup_misconfigured",+ message:+ "BACKUP_BLOB_READ_WRITE_TOKEN is for the app's own Blob store. Make a second store for backups and use its token.",+ path: getRequestPathname(request),+ });++ return NextResponse.json(+ { error: "The backup store is the app's own store." },+ { status: 500 },+ );+ }++ if (caller === "anonymous") {+ const ration = await consumeRateLimit({+ key: "job:backup",+ limit: 1,+ windowMs: ANONYMOUS_RUN_INTERVAL_MS,+ });++ if (!ration.allowed) {+ return new NextResponse(null, { status: 204 });+ }+ }++ try {+ const summary = await runBackup({+ deadline: startedAt + COPY_BUDGET_MS,+ keepDays: settings.keepDays,+ source: createVercelBlobStore(),+ target: createVercelBlobStore(settings.token),+ });+ const failed = summary.fileFailures.length > 0;++ logSecurityEvent(failed ? "error" : "info", {+ category: "backup_finished",+ message: failed+ ? `The backup finished, but ${String(summary.fileFailures.length)} files could not be copied.`+ : "The backup finished.",+ metadata: { ...summary, fileFailures: summary.fileFailures.slice(0, 20) },+ });++ if (caller === "authorized") {+ return NextResponse.json(summary, { status: failed ? 500 : 200 });+ }++ return new NextResponse(null, { status: failed ? 500 : 204 });+ } catch (error) {+ logRouteError(error, {+ category: "backup_failure",+ ipAddress: getClientIpAddress(request.headers),+ message: "The backup failed.",+ path: getRequestPathname(request),+ });++ return new NextResponse(null, { status: 500 });+ }+}++export function GET(request: Request) {+ return handle(request);+}++export function POST(request: Request) {+ return handle(request);+}diff --git a/src/lib/backup.dbtest.ts b/src/lib/backup.dbtest.tsnew file mode 100644index 0000000..ae4559e--- /dev/null+++ b/src/lib/backup.dbtest.ts@@ -0,0 +1,318 @@+import assert from "node:assert/strict";+import { randomUUID } from "node:crypto";+import { Readable } from "node:stream";+import { after, before, beforeEach, test } from "node:test";++import type pg from "pg";++import {+ type BackupBlob,+ type BackupStore,+ DATABASE_PREFIX,+ findLatestDatabaseBackup,+ restoreDatabase,+ restoreFiles,+ RestoreError,+ runBackup,+} from "./backup.ts";+import { openTestDatabase } from "./db/test-database.ts";+import { recordSystemAuditEvent } from "./services/system-audit.ts";+import { saveSettings } from "./settings.ts";++// The daily backup and its restore, against a real Postgres and an+// in-memory stand-in for two Blob stores. Run with `npm run test:db`.++let database: pg.Pool;++type Stored = { body: Buffer; contentType: string; uploadedAt: Date };++/** A Blob store kept in memory. `clock` decides each upload's time. */+function memoryStore(clock: () => Date = () => new Date()) {+ const objects = new Map<string, Stored>();++ async function toBuffer(+ body: ReadableStream<Uint8Array> | Readable | Buffer | string,+ ): Promise<Buffer> {+ if (typeof body === "string") {+ return Buffer.from(body);+ }++ if (Buffer.isBuffer(body)) {+ return body;+ }++ const chunks: Buffer[] = [];+ const readable =+ body instanceof Readable+ ? body+ : Readable.fromWeb(body as import("node:stream/web").ReadableStream);++ for await (const chunk of readable) {+ chunks.push(Buffer.from(chunk as Uint8Array));+ }++ return Buffer.concat(chunks);+ }++ const store: BackupStore & { objects: Map<string, Stored> } = {+ async delete(pathnames) {+ for (const pathname of pathnames) {+ objects.delete(pathname);+ }+ },+ async get(pathname) {+ const found = objects.get(pathname);++ return found+ ? {+ contentType: found.contentType,+ stream: new Blob([new Uint8Array(found.body)]).stream(),+ }+ : null;+ },+ async list({ prefix }) {+ const blobs: BackupBlob[] = [...objects]+ .filter(([pathname]) => !prefix || pathname.startsWith(prefix))+ .map(([pathname, stored]) => ({+ pathname,+ size: stored.body.length,+ uploadedAt: stored.uploadedAt,+ }));++ return { blobs, hasMore: false };+ },+ objects,+ async put(pathname, body, { contentType }) {+ objects.set(pathname, {+ body: await toBuffer(body),+ contentType,+ uploadedAt: clock(),+ });+ },+ };++ return store;+}++async function addUser(email: string) {+ const id = randomUUID();++ await database.query(+ `insert into "user" (id, name, email, "emailVerified", role) values ($1, 'Pat', $2, true, 'admin')`,+ [id, email],+ );++ return id;+}++async function clearTables() {+ await database.query(`truncate public."user" cascade`);+ await database.query("delete from public.system_audit_events");+ await database.query("delete from public.app_settings");+}++before(async () => {+ database = await openTestDatabase();+});++beforeEach(clearTables);++after(async () => {+ await clearTables();+ await database.end();+});++test("a backup restores into an empty database exactly as it was", async () => {+ const userId = await addUser("[email protected]");++ await saveSettings(+ { organizationName: "Acme Corp", supportAddress: "[email protected]" },+ database,+ );+ await recordSystemAuditEvent(+ {+ actorEmail: "[email protected]",+ actorUserId: userId,+ event: "settings_changed",+ metadata: { changes: ["organization_name"] },+ },+ database,+ );++ const before = await database.query(+ "select * from system_audit_events order by sequence",+ );+ const source = memoryStore();+ const target = memoryStore();++ source.objects.set("envelopes/a/original.pdf", {+ body: Buffer.from("%PDF-1.7 original"),+ contentType: "application/pdf",+ uploadedAt: new Date(),+ });++ const summary = await runBackup({+ database,+ keepDays: 30,+ source,+ target,+ });++ assert.equal(summary.filesCopied, 1);+ assert.equal(summary.stoppedEarly, false);+ assert.ok(target.objects.has("files/envelopes/a/original.pdf"));++ // Something goes badly wrong: the rows and the file are gone.+ await clearTables();+ source.objects.clear();++ const backupPath = await findLatestDatabaseBackup(target);++ assert.equal(backupPath, summary.databaseBackup);++ const restored = await restoreDatabase({+ backupPath: backupPath ?? "",+ database,+ store: target,+ });++ assert.equal(restored.rows.user, 1);++ const after = await database.query(+ "select * from system_audit_events order by sequence",+ );++ assert.deepEqual(after.rows, before.rows);++ const settings = await database.query<{ organization_name: string }>(+ "select organization_name from app_settings",+ );++ assert.equal(settings.rows[0]?.organization_name, "Acme Corp");++ const files = await restoreFiles({ source: target, target: source });++ assert.equal(files.copied, 1);+ assert.equal(+ source.objects.get("envelopes/a/original.pdf")?.body.toString(),+ "%PDF-1.7 original",+ );+});++test("a restore refuses a database that already has accounts", async () => {+ await addUser("[email protected]");++ const target = memoryStore();+ const summary = await runBackup({+ database,+ keepDays: 30,+ source: memoryStore(),+ target,+ });++ await assert.rejects(+ restoreDatabase({+ backupPath: summary.databaseBackup,+ database,+ store: target,+ }),+ RestoreError,+ );+});++test("only new or changed files are copied, and a deleted file's copy goes after the keep days", async () => {+ let now = new Date("2026-11-01T08:00:00Z");+ const clock = () => now;+ const source = memoryStore(clock);+ const target = memoryStore(clock);++ await source.put("a.pdf", Buffer.from("a"), {+ contentType: "application/pdf",+ });+ await source.put("b.pdf", Buffer.from("b"), {+ contentType: "application/pdf",+ });++ const first = await runBackup({+ database,+ keepDays: 2,+ now,+ source,+ target,+ });++ assert.equal(first.filesCopied, 2);++ // A day later: b is written again, a is deleted.+ now = new Date("2026-11-02T08:00:00Z");+ await source.put("b.pdf", Buffer.from("b, signed"), {+ contentType: "application/pdf",+ });+ await source.delete(["a.pdf"]);++ const second = await runBackup({+ database,+ keepDays: 2,+ now,+ source,+ target,+ });++ assert.equal(second.filesCopied, 1);+ assert.equal(second.filesRemoved, 0);+ assert.equal(target.objects.get("files/b.pdf")?.body.toString(), "b, signed");+ assert.ok(target.objects.has("files/a.pdf"), "kept for now");++ now = new Date("2026-11-05T08:00:00Z");++ const third = await runBackup({+ database,+ keepDays: 2,+ now,+ source,+ target,+ });++ assert.equal(third.filesCopied, 0);+ assert.equal(third.filesUnchanged, 1);+ assert.equal(third.filesRemoved, 1);+ assert.ok(!target.objects.has("files/a.pdf"));++ // Three database copies are always kept, however old.+ const databaseCopies = [...target.objects.keys()].filter((pathname) =>+ pathname.startsWith(DATABASE_PREFIX),+ );++ assert.equal(databaseCopies.length, 3);+});++test("copying stops at the deadline and the next run carries on", async () => {+ const source = memoryStore();+ const target = memoryStore();++ for (const name of ["a", "b", "c"]) {+ await source.put(`${name}.pdf`, Buffer.from(name), {+ contentType: "application/pdf",+ });+ }++ const stopped = await runBackup({+ database,+ deadline: Date.now() - 1,+ keepDays: 30,+ source,+ target,+ });++ assert.equal(stopped.stoppedEarly, true);+ assert.equal(stopped.filesCopied, 0);++ const resumed = await runBackup({+ database,+ keepDays: 30,+ source,+ target,+ });++ assert.equal(resumed.filesCopied, 3);+});diff --git a/src/lib/backup.test.ts b/src/lib/backup.test.tsnew file mode 100644index 0000000..3949a8c--- /dev/null+++ b/src/lib/backup.test.ts@@ -0,0 +1,48 @@+import assert from "node:assert/strict";+import { test } from "node:test";++import { isBackupStoreTheAppStore, readBackupSettings } from "./backup.ts";++test("backups are off until a backup store token is set", () => {+ assert.equal(readBackupSettings({}), null);+ assert.deepEqual(+ readBackupSettings({ BACKUP_BLOB_READ_WRITE_TOKEN: "vercel_blob_rw_B_x" }),+ { keepDays: 30, token: "vercel_blob_rw_B_x" },+ );++ for (const [value, expected] of [+ ["7", 7],+ ["0", 30],+ ["many", 30],+ ["99999", 30],+ ] as const) {+ assert.equal(+ readBackupSettings({+ BACKUP_BLOB_READ_WRITE_TOKEN: "t",+ BACKUP_KEEP_DAYS: value,+ })?.keepDays,+ expected,+ );+ }+});++test("a backup token for the app's own store is caught", () => {+ const settings = { keepDays: 30, token: "vercel_blob_rw_AbC123_secret" };++ assert.equal(+ isBackupStoreTheAppStore(settings, {+ BLOB_READ_WRITE_TOKEN: "vercel_blob_rw_abc123_other",+ }),+ true,+ );+ assert.equal(+ isBackupStoreTheAppStore(settings, { BLOB_STORE_ID: "store_AbC123" }),+ true,+ );+ assert.equal(+ isBackupStoreTheAppStore(settings, {+ BLOB_READ_WRITE_TOKEN: "vercel_blob_rw_Other9_x",+ }),+ false,+ );+});diff --git a/src/lib/backup.ts b/src/lib/backup.tsnew file mode 100644index 0000000..85eb652--- /dev/null+++ b/src/lib/backup.ts@@ -0,0 +1,681 @@+import { Readable } from "node:stream";+import { createGunzip, createGzip } from "node:zlib";++import { del, get, list, put } from "@vercel/blob";++import { type DbPool, getDb } from "./db/connection.ts";+import { readEnv, type EnvSource } from "./utils/env.ts";++// A daily copy of the install to a second Vercel Blob store, kept by the+// deployer apart from the first (another Vercel team, ideally), so that a+// deleted project, store or database, or a bug that deletes rows, is not the+// end of the records.+//+// It is off unless BACKUP_BLOB_READ_WRITE_TOKEN is set: a read-write token+// for that second store, which must be a private store. Each run+//+// - writes the whole database, read in one consistent snapshot, as one+// gzipped NDJSON file under database/, and keeps BACKUP_KEEP_DAYS days of+// them (30 by default, and never fewer than the newest three);+// - copies each file in the install's store that is new or changed since the+// last run to files/<same path>. A file that is gone from the install's+// store (deleted by the retention rules, say) is kept for BACKUP_KEEP_DAYS+// more days and then removed, so a backup does not keep a document longer+// than the retention rules allow by more than that.+//+// docs/backup-and-restore.md has the restore steps (scripts/restore-backup.ts).++export const BACKUP_FORMAT = "signudoc-backup";+export const BACKUP_FORMAT_VERSION = 1;+export const DATABASE_PREFIX = "database/";+export const FILES_PREFIX = "files/";+const MANIFEST_PATH = "manifest.json";+const DEFAULT_KEEP_DAYS = 30;+const MIN_DATABASE_COPIES = 3;+const DAY_MS = 24 * 60 * 60 * 1000;++/** Rows read from Postgres at a time while the database is written out. */+const EXPORT_BATCH_ROWS = 500;++/** The table migrate.mjs keeps; restore runs the migrations itself. */+export const MIGRATIONS_TABLE = "signudoc_migrations";++export type BackupBlob = { pathname: string; size: number; uploadedAt: Date };++/** The part of a Blob store a backup uses. Replaced by a fake in tests. */+export type BackupStore = {+ delete(pathnames: string[]): Promise<void>;+ get(pathname: string): Promise<{+ contentType: string;+ stream: ReadableStream<Uint8Array>;+ } | null>;+ list(options: { cursor?: string; prefix?: string }): Promise<{+ blobs: BackupBlob[];+ cursor?: string;+ hasMore: boolean;+ }>;+ put(+ pathname: string,+ body: ReadableStream<Uint8Array> | Readable | Buffer | string,+ options: { contentType: string },+ ): Promise<void>;+};++/** A private Vercel Blob store: the app's own (no token) or the backup's. */+export function createVercelBlobStore(token?: string): BackupStore {+ const auth = token ? { token } : {};++ return {+ async delete(pathnames) {+ if (pathnames.length > 0) {+ await del(pathnames, auth);+ }+ },+ async get(pathname) {+ const result = await get(pathname, {+ ...auth,+ access: "private",+ useCache: false,+ });++ if (!result || result.statusCode !== 200) {+ return null;+ }++ return { contentType: result.blob.contentType, stream: result.stream };+ },+ async list({ cursor, prefix }) {+ const result = await list({ ...auth, cursor, limit: 1000, prefix });++ return {+ blobs: result.blobs.map((blob) => ({+ pathname: blob.pathname,+ size: blob.size,+ uploadedAt: blob.uploadedAt,+ })),+ cursor: result.cursor,+ hasMore: result.hasMore,+ };+ },+ async put(pathname, body, { contentType }) {+ await put(pathname, body, {+ ...auth,+ access: "private",+ addRandomSuffix: false,+ allowOverwrite: true,+ contentType,+ multipart: typeof body !== "string" && !Buffer.isBuffer(body),+ });+ },+ };+}++export type BackupSettings = { keepDays: number; token: string };++/** The backup settings, or null when backups are not set up. */+export function readBackupSettings(+ env: EnvSource = process.env,+): BackupSettings | null {+ const token = readEnv(env, "BACKUP_BLOB_READ_WRITE_TOKEN");++ if (!token) {+ return null;+ }++ const keepDays = Number.parseInt(readEnv(env, "BACKUP_KEEP_DAYS") ?? "", 10);++ return {+ keepDays:+ Number.isFinite(keepDays) && keepDays >= 1 && keepDays <= 3650+ ? keepDays+ : DEFAULT_KEEP_DAYS,+ token,+ };+}++/** The store id inside a Blob read-write token, when it has one. */+function storeIdFromToken(token: string | undefined): string | null {+ return /^vercel_blob_rw_([A-Za-z0-9]+)_/.exec(token ?? "")?.[1] ?? null;+}++/**+ * True when the backup token is for the app's own store. A backup there+ * would not survive what it is for, and would copy itself every night.+ */+export function isBackupStoreTheAppStore(+ settings: BackupSettings,+ env: EnvSource = process.env,+): boolean {+ const backupStore = storeIdFromToken(settings.token)?.toLowerCase();+ const appStores = [+ storeIdFromToken(readEnv(env, "BLOB_READ_WRITE_TOKEN")),+ readEnv(env, "BLOB_STORE_ID")?.replace(/^store_/, "") ?? null,+ ]+ .filter((id): id is string => Boolean(id))+ .map((id) => id.toLowerCase());++ return Boolean(backupStore && appStores.includes(backupStore));+}++async function listAll(store: BackupStore, prefix?: string) {+ const blobs: BackupBlob[] = [];+ let cursor: string | undefined;++ do {+ const page = await store.list({ cursor, prefix });++ blobs.push(...page.blobs);+ cursor = page.hasMore ? page.cursor : undefined;+ } while (cursor);++ return blobs;+}++/** The public tables, in an order that inserts parents before children. */+export async function listTablesInRestoreOrder(+ database: Pick<DbPool, "query">,+): Promise<string[]> {+ const tables = await database.query<{ name: string }>(+ `+ SELECT table_name AS name+ FROM information_schema.tables+ WHERE table_schema = 'public' AND table_type = 'BASE TABLE'+ ORDER BY table_name+ `,+ );+ const references = await database.query<{ child: string; parent: string }>(+ `+ SELECT DISTINCT child.relname AS child, parent.relname AS parent+ FROM pg_constraint c+ JOIN pg_class child ON child.oid = c.conrelid+ JOIN pg_class parent ON parent.oid = c.confrelid+ JOIN pg_namespace n ON n.oid = child.relnamespace+ WHERE c.contype = 'f' AND n.nspname = 'public'+ AND child.relname <> parent.relname+ `,+ );+ const parents = new Map<string, Set<string>>();++ for (const { name } of tables.rows) {+ parents.set(name, new Set());+ }++ for (const { child, parent } of references.rows) {+ parents.get(child)?.add(parent);+ }++ const ordered: string[] = [];+ const placed = new Set<string>();++ while (ordered.length < parents.size) {+ const ready = [...parents.keys()].filter(+ (name) =>+ !placed.has(name) &&+ [...(parents.get(name) ?? [])].every(+ (parent) => placed.has(parent) || !parents.has(parent),+ ),+ );++ // A cycle between tables: put the rest in name order and let the+ // restore report what does not fit.+ const next =+ ready.length > 0+ ? ready+ : [...parents.keys()].filter((name) => !placed.has(name));++ for (const name of next) {+ placed.add(name);+ ordered.push(name);+ }+ }++ return ordered;+}++function quoteIdentifier(name: string): string {+ return `"${name.replace(/"/g, '""')}"`;+}++/**+ * The database as NDJSON lines: a header, then one line per row, each+ * read with row_to_json so every Postgres type comes back as it went in.+ * Read in one repeatable-read snapshot, so the tables agree with each other.+ */+export async function* exportDatabaseLines(+ database: DbPool,+ createdAt: Date,+): AsyncGenerator<string> {+ const client = await database.connect();++ try {+ await client.query("BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY");++ const tables = await listTablesInRestoreOrder(client);+ const migrations = await client+ .query<{ name: string }>(+ `SELECT version AS name FROM ${MIGRATIONS_TABLE} ORDER BY version`,+ )+ .then((result) => result.rows.map((row) => row.name))+ .catch(() => [] as string[]);++ yield `${JSON.stringify({+ createdAt: createdAt.toISOString(),+ format: BACKUP_FORMAT,+ migrations,+ tables,+ version: BACKUP_FORMAT_VERSION,+ })}\n`;++ for (const table of tables) {+ if (table === MIGRATIONS_TABLE) {+ continue;+ }++ const cursorName = `backup_${String(tables.indexOf(table))}`;++ await client.query(+ `DECLARE ${cursorName} NO SCROLL CURSOR FOR SELECT row_to_json(t)::text AS row FROM ${quoteIdentifier(table)} t`,+ );++ for (;;) {+ const batch = await client.query<{ row: string }>(+ `FETCH ${String(EXPORT_BATCH_ROWS)} FROM ${cursorName}`,+ );++ for (const { row } of batch.rows) {+ yield `{"table":${JSON.stringify(table)},"row":${row}}\n`;+ }++ if (batch.rows.length < EXPORT_BATCH_ROWS) {+ break;+ }+ }++ await client.query(`CLOSE ${cursorName}`);+ }++ await client.query("COMMIT");+ } catch (error) {+ await client.query("ROLLBACK").catch(() => undefined);+ throw error;+ } finally {+ client.release();+ }+}++function databaseBackupPath(createdAt: Date): string {+ return `${DATABASE_PREFIX}${createdAt.toISOString().replace(/[:.]/g, "-")}.ndjson.gz`;+}++type Manifest = {+ /** Backed-up files whose original was found missing, and since when. */+ missingSince: Record<string, string>;+ version: 1;+};++async function readManifest(store: BackupStore): Promise<Manifest> {+ const found = await store.get(MANIFEST_PATH).catch(() => null);++ if (!found) {+ return { missingSince: {}, version: 1 };+ }++ try {+ const text = await new Response(found.stream).text();+ const parsed = JSON.parse(text) as Partial<Manifest>;++ return { missingSince: parsed.missingSince ?? {}, version: 1 };+ } catch {+ return { missingSince: {}, version: 1 };+ }+}++export type BackupSummary = {+ databaseBackup: string;+ databaseBackupsRemoved: number;+ fileFailures: string[];+ filesCopied: number;+ filesRemoved: number;+ filesUnchanged: number;+ /** True when time ran out; the next run carries on. */+ stoppedEarly: boolean;+};++/** Runs one backup. Copying files stops at `deadline`. */+export async function runBackup({+ database = getDb(),+ deadline = Date.now() + 240_000,+ keepDays,+ now = new Date(),+ source,+ target,+}: {+ database?: DbPool;+ deadline?: number;+ keepDays: number;+ now?: Date;+ source: BackupStore;+ target: BackupStore;+}): Promise<BackupSummary> {+ // 1. The database.+ const databaseBackup = databaseBackupPath(now);++ await target.put(+ databaseBackup,+ Readable.from(exportDatabaseLines(database, now)).pipe(createGzip()),+ { contentType: "application/gzip" },+ );++ const cutoff = now.getTime() - keepDays * DAY_MS;+ const databaseCopies = (await listAll(target, DATABASE_PREFIX)).sort((a, b) =>+ b.pathname.localeCompare(a.pathname),+ );+ const expiredCopies = databaseCopies+ .slice(MIN_DATABASE_COPIES)+ .filter((blob) => blob.uploadedAt.getTime() < cutoff)+ .map((blob) => blob.pathname);++ await target.delete(expiredCopies);++ // 2. The files.+ const originals = await listAll(source);+ const copies = new Map(+ (await listAll(target, FILES_PREFIX)).map((blob) => [+ blob.pathname.slice(FILES_PREFIX.length),+ blob,+ ]),+ );+ const summary: BackupSummary = {+ databaseBackup,+ databaseBackupsRemoved: expiredCopies.length,+ fileFailures: [],+ filesCopied: 0,+ filesRemoved: 0,+ filesUnchanged: 0,+ stoppedEarly: false,+ };++ for (const original of originals) {+ const copy = copies.get(original.pathname);++ if (+ copy &&+ copy.size === original.size &&+ copy.uploadedAt.getTime() >= original.uploadedAt.getTime()+ ) {+ summary.filesUnchanged += 1;+ continue;+ }++ if (Date.now() >= deadline) {+ summary.stoppedEarly = true;+ break;+ }++ try {+ const found = await source.get(original.pathname);++ if (!found) {+ continue;+ }++ await target.put(`${FILES_PREFIX}${original.pathname}`, found.stream, {+ contentType: found.contentType,+ });+ summary.filesCopied += 1;+ } catch (error) {+ summary.fileFailures.push(original.pathname);+ console.error(+ `[backup] Could not copy ${original.pathname}:`,+ error instanceof Error ? error.message : error,+ );+ }+ }++ // 3. Copies whose original is gone, kept keepDays days after it went.+ const manifest = await readManifest(target);+ const present = new Set(originals.map((blob) => blob.pathname));+ const missingSince: Record<string, string> = {};+ const toRemove: string[] = [];++ for (const pathname of copies.keys()) {+ if (present.has(pathname)) {+ continue;+ }++ const since = manifest.missingSince[pathname] ?? now.toISOString();++ if (Date.parse(since) < cutoff) {+ toRemove.push(`${FILES_PREFIX}${pathname}`);+ } else {+ missingSince[pathname] = since;+ }+ }++ await target.delete(toRemove);+ summary.filesRemoved = toRemove.length;+ await target.put(+ MANIFEST_PATH,+ JSON.stringify({ missingSince, version: 1 } satisfies Manifest),+ { contentType: "application/json" },+ );++ return summary;+}++/** Reads a database backup back as its header and rows. */+export async function* readDatabaseBackup(+ stream: ReadableStream<Uint8Array>,+): AsyncGenerator<+ | {+ header: {+ createdAt: string;+ format: string;+ migrations: string[];+ tables: string[];+ version: number;+ };+ kind: "header";+ }+ | { kind: "row"; row: unknown; table: string }+> {+ const lines = Readable.fromWeb(+ stream as import("node:stream/web").ReadableStream,+ ).pipe(createGunzip());+ let buffered = "";+ let first = true;++ for await (const chunk of lines) {+ buffered += (chunk as Buffer).toString("utf8");++ let newline = buffered.indexOf("\n");++ while (newline >= 0) {+ const line = buffered.slice(0, newline);++ buffered = buffered.slice(newline + 1);+ newline = buffered.indexOf("\n");++ if (!line.trim()) {+ continue;+ }++ const parsed = JSON.parse(line) as Record<string, unknown>;++ if (first) {+ first = false;++ if (parsed.format !== BACKUP_FORMAT) {+ throw new Error("This is not a SignuDoc database backup.");+ }++ yield {+ header: parsed as never,+ kind: "header",+ };+ continue;+ }++ yield {+ kind: "row",+ row: parsed.row,+ table: String(parsed.table),+ };+ }+ }+}++/** The newest database backup in the store, or null if it has none. */+export async function findLatestDatabaseBackup(+ store: BackupStore,+): Promise<string | null> {+ const copies = await listAll(store, DATABASE_PREFIX);++ copies.sort((a, b) => b.pathname.localeCompare(a.pathname));++ return copies[0]?.pathname ?? null;+}++export class RestoreError extends Error {}++const RESTORE_BATCH_ROWS = 500;++/**+ * Loads a database backup into an empty database that has the same or+ * newer migrations applied. All of it lands in one transaction, or none.+ */+export async function restoreDatabase({+ backupPath,+ database,+ store,+}: {+ backupPath: string;+ database: DbPool;+ store: BackupStore;+}): Promise<{ rows: Record<string, number> }> {+ const found = await store.get(backupPath);++ if (!found) {+ throw new RestoreError(`There is no backup at ${backupPath}.`);+ }++ const applied = new Set(+ (+ await database.query<{ version: string }>(+ `SELECT version FROM ${MIGRATIONS_TABLE}`,+ )+ ).rows.map((row) => row.version),+ );+ const existing = await database.query<{ count: string }>(+ `SELECT count(*)::text AS count FROM "user"`,+ );++ if (existing.rows[0]?.count !== "0") {+ throw new RestoreError(+ "The database already has accounts in it. Restore into a new, empty database.",+ );+ }++ const client = await database.connect();+ const counts: Record<string, number> = {};+ let batchTable: string | null = null;+ let batch: unknown[] = [];++ async function flush() {+ if (!batchTable || batch.length === 0) {+ return;+ }++ const columns = Object.keys(batch[0] as Record<string, unknown>)+ .map(quoteIdentifier)+ .join(", ");+ const table = quoteIdentifier(batchTable);++ // Only the columns the backup has, so a column added by a newer+ // migration gets its default.+ await client.query(+ `INSERT INTO ${table} (${columns}) SELECT ${columns} FROM json_populate_recordset(null::${table}, $1::json)`,+ [JSON.stringify(batch)],+ );+ counts[batchTable] = (counts[batchTable] ?? 0) + batch.length;+ batch = [];+ }++ try {+ await client.query("BEGIN");++ for await (const entry of readDatabaseBackup(found.stream)) {+ if (entry.kind === "header") {+ const missing = entry.header.migrations.filter(+ (version) => !applied.has(version),+ );++ if (missing.length > 0) {+ throw new RestoreError(+ `The backup is from a newer version of SignuDoc. Update this copy first; it lacks ${missing.join(", ")}.`,+ );+ }++ // A new install can already have a row or two of its own (a seal+ // key, its settings). The backup's take their place.+ for (const table of [...entry.header.tables].reverse()) {+ if (table !== MIGRATIONS_TABLE) {+ await client.query(`DELETE FROM ${quoteIdentifier(table)}`);+ }+ }++ continue;+ }++ if (entry.table !== batchTable || batch.length >= RESTORE_BATCH_ROWS) {+ await flush();+ batchTable = entry.table;+ }++ batch.push(entry.row);+ }++ await flush();+ await client.query("COMMIT");+ } catch (error) {+ await client.query("ROLLBACK").catch(() => undefined);+ throw error;+ } finally {+ client.release();+ }++ return { rows: counts };+}++/** Copies the backed-up files into the install's store, at their own paths. */+export async function restoreFiles({+ source,+ target,+}: {+ source: BackupStore;+ target: BackupStore;+}): Promise<{ copied: number; failures: string[] }> {+ const copies = await listAll(source, FILES_PREFIX);+ const failures: string[] = [];+ let copied = 0;++ for (const copy of copies) {+ try {+ const found = await source.get(copy.pathname);++ if (!found) {+ failures.push(copy.pathname);+ continue;+ }++ await target.put(copy.pathname.slice(FILES_PREFIX.length), found.stream, {+ contentType: found.contentType,+ });+ copied += 1;+ } catch {+ failures.push(copy.pathname);+ }+ }++ return { copied, failures };+}diff --git a/vercel.json b/vercel.jsonindex 96a8419..2e3caf2 100644--- a/vercel.json+++ b/vercel.json@@ -5,6 +5,10 @@{"path": "/api/internal/retention","schedule": "0 9 * * *"+ },+ {+ "path": "/api/internal/backup",+ "schedule": "0 8 * * *"}]}