Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Answer the review notes: confirmed names, older backups, reminders after a restore, parallel access codes
Claude2190d5b8c326
diff --git a/docs/backup-and-restore.md b/docs/backup-and-restore.mdindex cb6f45c..7a29b51 100644--- a/docs/backup-and-restore.md+++ b/docs/backup-and-restore.md@@ -62,7 +62,7 @@ What a restore brings back: everything in the database at the time of the backupWhat 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.+- 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. The usual wait between reminders starts over with the restore, so you can send one at once. Embedded envelopes get no reminders: the app that shows them asks for a new link through the API's [embed-link endpoint](api.md#embedded-signing).- 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).diff --git a/src/lib/access-code-guesses.dbtest.ts b/src/lib/access-code-guesses.dbtest.tsindex b0d34a5..222491e 100644--- a/src/lib/access-code-guesses.dbtest.ts+++ b/src/lib/access-code-guesses.dbtest.ts@@ -4,7 +4,7 @@ import { after, before, test } from "node:test";import type pg from "pg";-import { openTestDatabase } from "./db/test-database.ts";+import { afterStatement, openTestDatabase } from "./db/test-database.ts";import { clearRateLimitStoreForTests } from "./security/rate-limit.ts";import { issueSigningLink } from "./services/signing-links.ts";import { hashAccessCode } from "./signer-checks.ts";@@ -115,3 +115,63 @@ test("a signer's wrong access codes run out, and a new code starts over", asyncassert.deepEqual(await tryCode(token, "9876"), ["access_code"]);});++test("guesses sent at the same moment cannot pass the last try together, and right codes are not counted", async () => {+ const { token } = await createEnvelopeWithAccessCode("4321");++ // Right codes along the way take nothing from the count.+ for (let attempt = 0; attempt < 3; attempt += 1) {+ assert.deepEqual(await tryCode(token, "4321"), ["access_code"]);+ }++ for (let attempt = 0; attempt < ACCESS_CODE_MAX_FAILURES - 1; attempt += 1) {+ await assert.rejects(+ tryCode(token, String(6000 + attempt)),+ (error: unknown) =>+ error instanceof SigningMutationError && error.statusCode === 400,+ );+ }++ // One try is left. Five sent together, each held right after it first+ // asks about the count until all five have: only one is compared.+ const together = 5;+ let arrived = 0;+ let releaseAll!: () => void;+ const allArrived = new Promise<void>((resolve) => {+ releaseAll = resolve;+ });+ const pool = afterStatement(+ database,+ (text) => arrived < together && text.includes("public.rate_limits"),+ async () => {+ arrived += 1;++ if (arrived === together) {+ releaseAll();+ }++ await allArrived;+ },+ );+ const results = await Promise.allSettled(+ Array.from({ length: together }, (_, offset) =>+ verifySignerCheck(+ token,+ { code: String(7000 + offset), method: "access_code" },+ { database: pool },+ ),+ ),+ );+ const statuses = results.map((result) =>+ result.status === "rejected" &&+ result.reason instanceof SigningMutationError+ ? result.reason.statusCode+ : "passed",+ );++ assert.deepEqual(+ statuses.toSorted(),+ [400, 429, 429, 429, 429],+ JSON.stringify(statuses),+ );+});diff --git a/src/lib/backup.dbtest.ts b/src/lib/backup.dbtest.tsindex e148a08..88962a3 100644--- a/src/lib/backup.dbtest.ts+++ b/src/lib/backup.dbtest.ts@@ -2,6 +2,7 @@ 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 { gunzipSync, gzipSync } from "node:zlib";import type pg from "pg";@@ -236,10 +237,11 @@ test("a restore ends the sessions, codes and signing links the backup holds", asinsert 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+ email_code_hash, email_code_expires_at, last_notified_at,+ last_nudged_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)+ ($1, $3, 'Riley', '[email protected]', 1, 'notified', $4, $6, 'code-hash', $6, $5, $5),+ ($2, $3, 'Casey', '[email protected]', 2, 'pending', null, null, null, null, null, null)`,[waitingId, signedId, envelopeId, "b".repeat(64), now, now + 3600],);@@ -286,20 +288,89 @@ test("a restore ends the sessions, codes and signing links the backup holds", as`selectid, status, signing_token_hash as "tokenHash",- email_code_hash as "codeHash"+ email_code_hash as "codeHash", last_nudged_at as "nudgedAt",+ last_notified_at as "notifiedAt"from signers where envelope_id = $1 order by sign_order`,[envelopeId],);- // The records themselves come back; only the links are gone.+ // The records themselves come back; only the links are gone. The+ // reminder sent just before the backup no longer holds back the one that+ // brings a new link.assert.deepEqual(signers.rows, [- { codeHash: null, id: waitingId, status: "notified", tokenHash: null },- { codeHash: null, id: signedId, status: "pending", tokenHash: null },+ {+ codeHash: null,+ id: waitingId,+ notifiedAt: now,+ nudgedAt: null,+ status: "notified",+ tokenHash: null,+ },+ {+ codeHash: null,+ id: signedId,+ notifiedAt: null,+ nudgedAt: null,+ status: "pending",+ tokenHash: null,+ },]);assert.equal(restored.rows.envelopes, 1);});+test("a backup made before identity confirmations kept their name keeps its confirmations", async () => {+ const userId = await addUser("[email protected]");++ await database.query(+ `+ update "user"+ set identity_verified_at = 1700000000,+ identity_verification_note = 'Passport checked',+ identity_verified_name = null,+ identity_verified_email = null+ where id = $1+ `,+ [userId],+ );++ const target = memoryStore();+ const summary = await runBackup({+ database,+ keepDays: 30,+ source: memoryStore(),+ target,+ });++ // As an older SignuDoc would have written it: without that migration.+ const stored = target.objects.get(summary.databaseBackup)!;+ const lines = gunzipSync(stored.body).toString("utf8").split("\n");+ const header = JSON.parse(lines[0]!) as { migrations: string[] };++ header.migrations = header.migrations.filter(+ (version) => version !== "20261120100000_identity_verified_snapshot",+ );+ lines[0] = JSON.stringify(header);+ stored.body = gzipSync(Buffer.from(lines.join("\n")));++ await clearTables();+ await restoreDatabase({+ backupPath: summary.databaseBackup,+ database,+ store: target,+ });++ const restored = await database.query(+ `+ select identity_verified_name as name, identity_verified_email as email+ from "user" where id = $1+ `,+ [userId],+ );++ assert.deepEqual(restored.rows, [{ email: "[email protected]", name: "Pat" }]);+});+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 e4899ce..5b34766 100644--- a/src/lib/backup.ts+++ b/src/lib/backup.ts@@ -648,6 +648,7 @@ export async function restoreDatabase({const counts: Record<string, number> = {};let batchTable: string | null = null;let batch: unknown[] = [];+ let backupMigrations = new Set<string>();async function flush() {if (!batchTable || batch.length === 0) {@@ -684,6 +685,8 @@ export async function restoreDatabase({);}+ backupMigrations = new Set(entry.header.migrations);+// 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()) {@@ -704,6 +707,7 @@ export async function restoreDatabase({}await flush();+ await backfillRowsFromOlderBackup(client, backupMigrations);const revoked = await revokeRestoredCredentials(client);@@ -718,6 +722,39 @@ export async function restoreDatabase({}}+/**+ * Backfills a migration makes on the rows it finds. Restore applies the+ * migrations to an empty database first, so when a backup was made before+ * one of these, its rows arrive after the backfill ran and are filled here+ * instead. Each runs only when the backup lacks its migration.+ */+const BACKFILLS_FOR_OLDER_BACKUPS: { migration: string; sql: string }[] = [+ {+ // Confirmations made before the confirmed name and address were kept+ // were of the account as it was then (see that migration).+ migration: "20261120100000_identity_verified_snapshot",+ sql: `+ UPDATE "user"+ SET+ identity_verified_name = name,+ identity_verified_email = email+ WHERE identity_verified_at IS NOT NULL+ AND identity_verified_name IS NULL+ `,+ },+];++export async function backfillRowsFromOlderBackup(+ client: Pick<DbPool, "query">,+ backupMigrations: ReadonlySet<string>,+) {+ for (const backfill of BACKFILLS_FOR_OLDER_BACKUPS) {+ if (!backupMigrations.has(backfill.migration)) {+ await client.query(backfill.sql);+ }+ }+}+export type RevokedCredentials = {providerSessions: number;sessions: number;@@ -735,7 +772,9 @@ export type RevokedCredentials = {* - 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;+ * signer still to sign gets a new link from the sender's reminder (the+ * reminder's wait starts over, so one can go at once), or, on an+ * embedded envelope, from the app asking the API for a new link;* - a signature that was under way at a signing provider has to be started* again.*@@ -758,7 +797,13 @@ export async function revokeRestoredCredentials(signing_token_hash = NULL,signing_token_expires_at = NULL,email_code_hash = NULL,- email_code_expires_at = NULL+ email_code_expires_at = NULL,+ -- The sender's reminder is how the signer gets a new link, so a+ -- reminder sent just before the backup must not hold it back.+ last_nudged_at = CASE+ WHEN signing_token_hash IS NOT NULL THEN NULL+ ELSE last_nudged_at+ ENDWHERE signing_token_hash IS NOT NULL OR email_code_hash IS NOT NULL`,);diff --git a/src/lib/bulk-send.dbtest.ts b/src/lib/bulk-send.dbtest.tsindex 95f5c79..e4b3562 100644--- a/src/lib/bulk-send.dbtest.ts+++ b/src/lib/bulk-send.dbtest.ts@@ -823,6 +823,18 @@ test("a Part 11 row goes out only in the confirmed person's name, and is signedassert.deepEqual(signer.rows, [{ name: "Alice Account Holder", userId: accountId },]);++ // The send is recorded in the same name the signer row carries.+ const sent = await database.query<{ signerName: string }>(+ `+ select metadata->>'signerName' as "signerName"+ from audit_events+ where envelope_id = $1 and event = 'sent'+ `,+ [result.rows[0]?.envelopeId],+ );++ assert.deepEqual(sent.rows, [{ signerName: "Alice Account Holder" }]);} finally {if (previous.rowCount) {await database.query(diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.tsindex 5033124..4a5242c 100644--- a/src/lib/envelopes.ts+++ b/src/lib/envelopes.ts@@ -2841,8 +2841,16 @@ export async function sendDraftEnvelope(}}- // Everyone in the first step of the signing order is invited now.- const firstSigners = firstStepSigners(signers);+ // Everyone in the first step of the signing order is invited now. A+ // Part 11 signer is invited, and recorded as sent to, in the name the+ // administrator confirmed, which is the name saved on the signer below.+ const firstSigners = firstStepSigners(+ signers.map((signer) => {+ const account = part11SignerAccounts.get(signer.id);++ return account ? { ...signer, name: account.name } : signer;+ }),+ );const firstSigner = firstSigners[0];if (!firstSigner) {diff --git a/src/lib/security/rate-limit.ts b/src/lib/security/rate-limit.tsindex 8792e80..d33a6f5 100644--- a/src/lib/security/rate-limit.ts+++ b/src/lib/security/rate-limit.ts@@ -235,6 +235,45 @@ export async function peekRateLimit(};}+/**+ * Takes back one request counted by consumeRateLimit, for limits that+ * count every attempt up front (so parallel ones cannot all pass a peek)+ * but only mean to keep the ones that fail. A count that drops to nothing+ * is removed, so its window starts again with the next failure.+ */+export async function refundRateLimit(+ key: string,+ {+ database,+ now = Date.now(),+ }: ConsumeRateLimitOptions & { now?: number } = {},+): Promise<void> {+ try {+ const executor = database ?? getDb();+ const removed = await executor.query(+ "delete from public.rate_limits where key = $1 and count <= 1",+ [hashKey(key)],+ );++ if ((removed.rowCount ?? 0) === 0) {+ await executor.query(+ "update public.rate_limits set count = count - 1 where key = $1 and count > 1 and expires_at > $2",+ [hashKey(key), now],+ );+ }+ } catch (error) {+ warnAboutFallback(error);++ const entry = memoryStore.get(key);++ if (entry && entry.count <= 1) {+ memoryStore.delete(key);+ } else if (entry && entry.expiresAt > now) {+ entry.count -= 1;+ }+ }+}+/** Forgets a limit's count, as after a sign-in that worked. */export async function clearRateLimit(key: string,diff --git a/src/lib/signing.ts b/src/lib/signing.tsindex 63916f4..d5d0336 100644--- a/src/lib/signing.ts+++ b/src/lib/signing.ts@@ -103,7 +103,7 @@ import {nextSignerLinkExpiresAt,} from "./envelope-deadline.ts";import { describeEntryProblem, judgeRadioGroups } from "./field-choices.ts";-import { consumeRateLimit, peekRateLimit } from "./security/rate-limit.ts";+import { consumeRateLimit, refundRateLimit } from "./security/rate-limit.ts";import {buildDisclosureSections,CONSENT_STATEMENT,@@ -1639,13 +1639,20 @@ export async function verifySignerCheck(// An access code can be short, so wrong ones are counted per signer and// code, over every link and address: a guesser gets a few tries a week,// not a few every quarter of an hour. A new code from the sender starts- // a new count.- const failures = {- key: `signing-access-code-failures:${context.signer.id!}:${state.accessCodeHash!}`,- limit: ACCESS_CODE_MAX_FAILURES,- };+ // a new count. Each try is counted before the code is compared, so tries+ // sent at the same moment cannot all pass the check; a right one is+ // then taken back off the count.+ const failuresKey = `signing-access-code-failures:${context.signer.id!}:${state.accessCodeHash!}`;+ const attempt = await consumeRateLimit(+ {+ key: failuresKey,+ limit: ACCESS_CODE_MAX_FAILURES,+ windowMs: ACCESS_CODE_FAILURE_WINDOW_MS,+ },+ { database },+ );- if (!(await peekRateLimit(failures, { database })).allowed) {+ if (!attempt.allowed) {throw new SigningMutationError("Too many wrong access codes. Ask the sender for the code, or for a new one.",429,@@ -1654,11 +1661,8 @@ export async function verifySignerCheck(passed = checkAccessCode(parsed.code, state.accessCodeHash!);- if (!passed) {- await consumeRateLimit(- { ...failures, windowMs: ACCESS_CODE_FAILURE_WINDOW_MS },- { database },- );+ if (passed) {+ await refundRateLimit(failuresKey, { database });}} else {// Count the attempt and read the code in one statement, so parallel