Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
End restored sessions, codes and signing links after a restore
Claude1539da6aafba
diff --git a/docs/backup-and-restore.md b/docs/backup-and-restore.mdindex 654b87c..cb6f45c 100644--- a/docs/backup-and-restore.md+++ b/docs/backup-and-restore.md@@ -59,6 +59,14 @@ You need a computer with Node.js 24 and a copy of this repository at the same veWhat 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.+What a restore does not bring back: anything that lets someone in. A backup holds sign-ins and links as they were when it was made, including ones that were signed out, used or replaced since, so the restore ends them all:++- Everyone signs in again, and password reset links and emailed codes from before the restore stop working.+- Every signing link stops working. For each envelope still out for signature, send a reminder from its page: that emails the signer a new link.+- A signature that was under way at a signing provider has to be started again.++Passwords and API keys come back as they were at the time of the backup. If someone changed a password, or an administrator revoked an API key, after the backup was made, do it again. If the restore follows a break-in, also change `BETTER_AUTH_SECRET` (everyone using two-step sign-in then sets it up again, see step 4).+## In a security review- **Backup frequency:** daily, at 08:00 UTC.diff --git a/scripts/restore-backup.ts b/scripts/restore-backup.tsindex 8db1458..2171495 100644--- a/scripts/restore-backup.ts+++ b/scripts/restore-backup.ts@@ -96,7 +96,7 @@ async function main() {try {console.log(`Restoring ${backupPath}…`);- const { rows } = await restoreDatabase({+ const { revoked, rows } = await restoreDatabase({backupPath,database,store: backupStore,@@ -105,6 +105,16 @@ async function main() {for (const [table, count] of Object.entries(rows)) {console.log(` ${table}: ${String(count)} rows`);}++ console.log(+ [+ "Ended what the backup had of sign-ins and links, so none of them works again:",+ ` ${String(revoked.sessions)} sessions (everyone signs in again)`,+ ` ${String(revoked.verifications)} one-time codes and reset links`,+ ` ${String(revoked.signingLinks)} signing links (senders send a reminder for a new one)`,+ ` ${String(revoked.providerSessions)} signatures under way at a signing provider`,+ ].join("\n"),+ );} finally {await database.end();}diff --git a/src/lib/backup.dbtest.ts b/src/lib/backup.dbtest.tsindex fbcd24c..e148a08 100644--- a/src/lib/backup.dbtest.ts+++ b/src/lib/backup.dbtest.ts@@ -16,6 +16,7 @@ import {runBackup,} from "./backup.ts";import { openTestDatabase } from "./db/test-database.ts";+import { enforceSessionLimits } from "./session-controls.ts";import { recordSystemAuditEvent } from "./services/system-audit.ts";import { saveSettings } from "./settings.ts";@@ -199,6 +200,106 @@ test("a backup restores into an empty database exactly as it was", async () => {);});+test("a restore ends the sessions, codes and signing links the backup holds", async () => {+ const userId = await addUser("[email protected]");+ const envelopeId = randomUUID();+ const waitingId = randomUUID();+ const signedId = randomUUID();+ const now = Math.floor(Date.now() / 1000);+ const limits = { sessionIdleMinutes: null, sessionMaxHours: null };++ await database.query(+ `+ insert into session (id, "expiresAt", token, "userId", last_active_at)+ values ($1, now() + interval '7 days', 'kept-cookie-token', $2, $3)+ `,+ [randomUUID(), userId, now],+ );+ await database.query(+ `+ insert into verification (id, identifier, value, "expiresAt")+ values ($1, 'reset-password:abc', $2, now() + interval '1 hour')+ `,+ [randomUUID(), userId],+ );+ await database.query(+ `+ insert into envelopes (+ id, user_id, title, status, source_pdf_key, source_pdf_filename,+ source_pdf_size_bytes, page_count, source_pdf_hash, sent_at+ ) values ($1, $2, 'Lease', 'sent', 'k.pdf', 'lease.pdf', 10, 1, $3, $4)+ `,+ [envelopeId, userId, "a".repeat(64), now],+ );+ await database.query(+ `+ insert into signers (+ id, envelope_id, name, email, sign_order, status,+ signing_token_hash, signing_token_expires_at,+ email_code_hash, email_code_expires_at, last_notified_at+ ) values+ ($1, $3, 'Riley', '[email protected]', 1, 'notified', $4, $6, 'code-hash', $6, $5),+ ($2, $3, 'Casey', '[email protected]', 2, 'pending', null, null, null, null, null)+ `,+ [waitingId, signedId, envelopeId, "b".repeat(64), now, now + 3600],+ );++ // Both work when the backup is made. Whatever happened to them after it+ // (a sign-out everywhere, a spent link), the backup still has them live.+ assert.equal(+ await enforceSessionLimits("kept-cookie-token", limits, { database }),+ true,+ );++ const target = memoryStore();+ const summary = await runBackup({+ database,+ keepDays: 30,+ source: memoryStore(),+ target,+ });++ await clearTables();++ const restored = await restoreDatabase({+ backupPath: summary.databaseBackup,+ database,+ store: target,+ });++ assert.deepEqual(restored.revoked, {+ providerSessions: 0,+ sessions: 1,+ signingLinks: 1,+ verifications: 1,+ });+ assert.equal(+ await enforceSessionLimits("kept-cookie-token", limits, { database }),+ false,+ );++ const verification = await database.query(`select 1 from verification`);++ assert.equal(verification.rowCount, 0);++ const signers = await database.query(+ `+ select+ id, status, signing_token_hash as "tokenHash",+ email_code_hash as "codeHash"+ from signers where envelope_id = $1 order by sign_order+ `,+ [envelopeId],+ );++ // The records themselves come back; only the links are gone.+ assert.deepEqual(signers.rows, [+ { codeHash: null, id: waitingId, status: "notified", tokenHash: null },+ { codeHash: null, id: signedId, status: "pending", tokenHash: null },+ ]);+ assert.equal(restored.rows.envelopes, 1);+});+test("a restore refuses a database that already has accounts", async () => {await addUser("[email protected]");diff --git a/src/lib/backup.ts b/src/lib/backup.tsindex b1aa8bc..e4899ce 100644--- a/src/lib/backup.ts+++ b/src/lib/backup.ts@@ -620,7 +620,7 @@ export async function restoreDatabase({backupPath: string;database: DbPool;store: BackupStore;-}): Promise<{ rows: Record<string, number> }> {+}): Promise<{ revoked: RevokedCredentials; rows: Record<string, number> }> {const found = await store.get(backupPath);if (!found) {@@ -704,15 +704,78 @@ export async function restoreDatabase({}await flush();++ const revoked = await revokeRestoredCredentials(client);+await client.query("COMMIT");++ return { revoked, rows: counts };} catch (error) {await client.query("ROLLBACK").catch(() => undefined);throw error;} finally {client.release();}+}++export type RevokedCredentials = {+ providerSessions: number;+ sessions: number;+ signingLinks: number;+ verifications: number;+};++/**+ * Ends every credential a restore brought back from the backup, inside the+ * restore's own transaction. A backup holds them as they were when it was+ * made: a session signed out or ended by an administrator since, a signing+ * link spent or replaced since, a password reset already used. Brought back+ * as they were, they would work again. So after a restore:+ *+ * - everyone signs in again (sessions, and the one-time codes and links in+ * verification, go);+ * - every signing link and emailed signing code stops working, and a+ * signer still to sign gets a new link from the sender's reminder;+ * - a signature that was under way at a signing provider has to be started+ * again.+ *+ * The rate limit counts go too: they are kept for minutes, not as records.+ * Download links for finished documents are kept: nothing ends them early,+ * so the backup's are the same as the live ones were.+ */+export async function revokeRestoredCredentials(+ client: Pick<DbPool, "query">,+): Promise<RevokedCredentials> {+ const sessions = await client.query(`DELETE FROM session`);+ const verifications = await client.query(`DELETE FROM verification`);++ await client.query(`DELETE FROM rate_limits`);- return { rows: counts };+ const signingLinks = await client.query(+ `+ UPDATE signers+ SET+ signing_token_hash = NULL,+ signing_token_expires_at = NULL,+ email_code_hash = NULL,+ email_code_expires_at = NULL+ WHERE signing_token_hash IS NOT NULL OR email_code_hash IS NOT NULL+ `,+ );+ const providerSessions = await client.query(+ `+ UPDATE provider_signing_sessions+ SET state = 'failed', secret_data = ''+ WHERE state IN ('pending', 'signing')+ `,+ );++ return {+ providerSessions: providerSessions.rowCount ?? 0,+ sessions: sessions.rowCount ?? 0,+ signingLinks: signingLinks.rowCount ?? 0,+ verifications: verifications.rowCount ?? 0,+ };}/** Copies the backed-up files into the install's store, at their own paths. */