Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
fix(part11): distinguish previous-name invitations from unconfirmed accounts (#231)
Kevin Rose78fe63c6915a
diff --git a/docs/part11/procedures.md b/docs/part11/procedures.mdindex e66a80b..ba5af0d 100644--- a/docs/part11/procedures.md+++ b/docs/part11/procedures.md@@ -6,7 +6,7 @@ Short templates for the procedures Part 11 expects you to have. Put each into yo1. Only people who sign or send regulated records get an account. Each account is for one person and is never reassigned or reused, even after the person leaves.2. Before confirming an identity, the administrator checks it with `[a government photo ID in person / your HR record / …]`.-3. The administrator confirms the identity in Settings, People, Confirm identity. The note says how the check was done and gives a reference, such as "Passport seen in person, HR record 4417". The note must not contain the ID number itself. The confirmation is of the account's name and email address as they are then: if either changes, the person cannot sign until an administrator checks them and confirms them again. Envelopes are sent, and signed, in the confirmed name.+3. The administrator confirms the identity in Settings, People, Confirm identity. The note says how the check was done and gives a reference, such as "Passport seen in person, HR record 4417". The note must not contain the ID number itself. The confirmation is of the account's name and email address as they are then: if either changes, the person cannot sign until an administrator checks them and confirms them again. Envelopes are sent, and signed, in the confirmed name. An unsigned invitation already sent under a previous name cannot be signed or edited after a name change, even once the new name is confirmed; the signer notifies the sender, who voids the original envelope with a reason (SOP-3) and sends a replacement envelope in the current confirmed name.4. `[A second administrator reviews new confirmations within N days.]`5. When a person leaves or changes role, the administrator takes back their identity confirmation the same day, then closes or limits the account.6. Every `[quarter]`, an administrator reviews every confirmed account against the current staff list, and records the review.diff --git a/src/lib/part11.dbtest.ts b/src/lib/part11.dbtest.tsindex bd53819..469c9e9 100644--- a/src/lib/part11.dbtest.ts+++ b/src/lib/part11.dbtest.ts@@ -328,6 +328,13 @@ test("a confirmation stops counting once the account's name or address changes",}});+const NAME_MISMATCH = {+ attemptsLeft: MAX_SIGNING_PASSWORD_ATTEMPTS,+ locked: false,+ ok: false,+ signerNameMismatch: true,+};+test("a signature is refused in a name other than the confirmed person's", async () => {const user = await createUser();const { rows } = await database.query<{ name: string }>(@@ -345,7 +352,7 @@ test("a signature is refused in a name other than the confirmed person's", async},{ database, verifyPassword },),- NOT_CONFIRMED,+ NAME_MISMATCH,);assert.deepEqual(await checkSigningCredentials(@@ -361,9 +368,14 @@ test("a signature is refused in a name other than the confirmed person's", async);});-test("confirming someone again after a name change lets them sign in the new name", async () => {+test("confirming someone again after a name change lets them sign in the new name and flags an old-name link as a mismatch", async () => {const admin = await createUser("admin");const user = await createUser();+ const { rows: beforeRename } = await database.query<{ name: string }>(+ `select name from "user" where id = $1`,+ [user.id],+ );+ const oldName = beforeRename[0]!.name;await database.query(`update "user" set name = 'Alice Married Name' where id = $1`,@@ -385,6 +397,18 @@ test("confirming someone again after a name change lets them sign in the new nam);assert.deepEqual(rows[0], { email: user.email, name: "Alice Married Name" });+ assert.deepEqual(+ await checkSigningCredentials(+ {+ email: user.email,+ password: "right",+ signerName: oldName,+ userId: user.id,+ },+ { database, verifyPassword },+ ),+ NAME_MISMATCH,+ );assert.deepEqual(await checkSigningCredentials({diff --git a/src/lib/part11.test.ts b/src/lib/part11.test.tsindex aee20ef..59f5834 100644--- a/src/lib/part11.test.ts+++ b/src/lib/part11.test.ts@@ -2,7 +2,13 @@ import assert from "node:assert/strict";import { test } from "node:test";import { toCsv } from "./audit-export.ts";-import { describePart11SignerProblem } from "./part11.ts";+import type { DbPool } from "./db/connection.ts";+import {+ checkSigningCredentials,+ describePart11SignerProblem,+ describeSigningCredentialFailure,+ MAX_SIGNING_PASSWORD_ATTEMPTS,+} from "./part11.ts";import { computeSystemAuditRowHash } from "./services/system-audit.ts";import {buildSignatureManifestation,@@ -152,3 +158,265 @@ test("the install audit hash changes when any field or the previous hash does",hash,);});++type FakeAccountRow = {+ email: string;+ emailVerified: boolean;+ failedAttempts: number;+ hash: string | null;+ identityVerifiedAt: number | null;+ lockedAt: number | null;+ name: string;+};++function makeFakeAccountPool(row: FakeAccountRow | null): {+ database: DbPool;+ queries: string[];+} {+ const queries: string[] = [];+ const client = {+ async query(sql: string) {+ const normalized = sql.trim();++ queries.push(normalized);++ if (+ normalized === "BEGIN" ||+ normalized === "COMMIT" ||+ normalized === "ROLLBACK"+ ) {+ return { rowCount: 0, rows: [] };+ }++ if (normalized.includes('FROM "user" u')) {+ return { rowCount: row ? 1 : 0, rows: row ? [row] : [] };+ }++ return { rowCount: 1, rows: [] };+ },+ release() {},+ };++ return {+ database: {+ async connect() {+ return client;+ },+ } as unknown as DbPool,+ queries,+ };+}++test("checkSigningCredentials distinguishes a previous-name invitation from an unconfirmed account (#231)", async () => {+ const samplePassphrase = "valid-fixture-value-12345";+ let verifierCalls = 0;+ const verifyCredential = async ({+ hash,+ password: value,+ }: {+ hash: string;+ password: string;+ }) => {+ verifierCalls += 1;+ return hash === "stored-check" && value === samplePassphrase;+ };++ // 1. After renaming to Casey Rivera and before an admin confirms the new name,+ // identityVerifiedAt is null, so the refusal points to identity confirmation.+ const awaitingConfirmation = makeFakeAccountPool({+ email: "[email protected]",+ emailVerified: true,+ failedAttempts: 0,+ hash: "stored-check",+ identityVerifiedAt: null,+ lockedAt: null,+ name: "Casey Rivera",+ });+ const unconfirmedResult = await checkSigningCredentials(+ {+ email: "[email protected]",+ password: samplePassphrase,+ signerName: "Casey Morgan",+ userId: "user-casey",+ },+ {+ database: awaitingConfirmation.database,+ verifyPassword: verifyCredential,+ },+ );++ if (unconfirmedResult.ok) {+ assert.fail("expected unconfirmed account to be refused");+ }++ assert.deepEqual(unconfirmedResult, {+ attemptsLeft: MAX_SIGNING_PASSWORD_ATTEMPTS,+ identityNotConfirmed: true,+ locked: false,+ ok: false,+ });+ assert.match(+ describeSigningCredentialFailure(unconfirmedResult),+ /an administrator has to confirm your identity/,+ );++ // 2. Once an admin confirms Casey Rivera, an invitation sent under the old+ // name Casey Morgan is refused as a signerNameMismatch (not unconfirmed)+ // and does not count against failed attempts.+ const reconfirmed = makeFakeAccountPool({+ email: "[email protected]",+ emailVerified: true,+ failedAttempts: 1,+ hash: "stored-check",+ identityVerifiedAt: 1_700_000_000,+ lockedAt: null,+ name: "Casey Rivera",+ });+ const mismatchResult = await checkSigningCredentials(+ {+ email: "[email protected]",+ password: samplePassphrase,+ signerName: "Casey Morgan",+ userId: "user-casey",+ },+ {+ database: reconfirmed.database,+ verifyPassword: verifyCredential,+ },+ );++ if (mismatchResult.ok) {+ assert.fail("expected previous-name invitation to be refused");+ }++ assert.deepEqual(mismatchResult, {+ attemptsLeft: MAX_SIGNING_PASSWORD_ATTEMPTS - 1,+ locked: false,+ ok: false,+ signerNameMismatch: true,+ });+ assert.equal("identityNotConfirmed" in mismatchResult, false);+ assert.equal(verifierCalls, 0);+ assert.equal(+ reconfirmed.queries.some((sql) => sql.startsWith("UPDATE")),+ false,+ );++ const mismatchMessage = describeSigningCredentialFailure(mismatchResult);++ assert.match(+ mismatchMessage,+ /different name than your account's confirmed name/,+ );+ assert.match(mismatchMessage, /void this envelope with a reason/);+ assert.match(mismatchMessage, /send a new one in your confirmed name/);+ assert.doesNotMatch(+ mismatchMessage,+ /an administrator has to confirm your identity/,+ );+ // Does not disclose the confirmed name on an unauthenticated check.+ assert.doesNotMatch(mismatchMessage, /Casey Rivera/);++ // 3. A replacement invitation sent in the confirmed name passes.+ const replacement = makeFakeAccountPool({+ email: "[email protected]",+ emailVerified: true,+ failedAttempts: 0,+ hash: "stored-check",+ identityVerifiedAt: 1_700_000_000,+ lockedAt: null,+ name: "Casey Rivera",+ });+ const replacementResult = await checkSigningCredentials(+ {+ email: "[email protected]",+ password: samplePassphrase,+ signerName: "Casey Rivera",+ userId: "user-casey",+ },+ {+ database: replacement.database,+ verifyPassword: verifyCredential,+ },+ );++ assert.deepEqual(replacementResult, { ok: true });+ assert.equal(verifierCalls, 1);++ // 4. Unverified email and signing lock still take precedence over name mismatch.+ const unverifiedEmail = makeFakeAccountPool({+ email: "[email protected]",+ emailVerified: false,+ failedAttempts: 0,+ hash: "stored-check",+ identityVerifiedAt: 1_700_000_000,+ lockedAt: null,+ name: "Casey Rivera",+ });++ assert.deepEqual(+ await checkSigningCredentials(+ {+ email: "[email protected]",+ password: samplePassphrase,+ signerName: "Casey Morgan",+ userId: "user-casey",+ },+ {+ database: unverifiedEmail.database,+ verifyPassword: verifyCredential,+ },+ ),+ {+ attemptsLeft: MAX_SIGNING_PASSWORD_ATTEMPTS,+ identityNotConfirmed: true,+ locked: false,+ ok: false,+ },+ );++ const lockedAccount = makeFakeAccountPool({+ email: "[email protected]",+ emailVerified: true,+ failedAttempts: MAX_SIGNING_PASSWORD_ATTEMPTS,+ hash: "stored-check",+ identityVerifiedAt: 1_700_000_000,+ lockedAt: 1_700_000_100,+ name: "Casey Rivera",+ });++ assert.deepEqual(+ await checkSigningCredentials(+ {+ email: "[email protected]",+ password: samplePassphrase,+ signerName: "Casey Morgan",+ userId: "user-casey",+ },+ {+ database: lockedAccount.database,+ verifyPassword: verifyCredential,+ },+ ),+ {+ attemptsLeft: 0,+ locked: true,+ ok: false,+ },+ );+});++test("describeSigningCredentialFailure covers locked and wrong-credential messages", () => {+ assert.match(+ describeSigningCredentialFailure({ attemptsLeft: 0, locked: true }),+ /locked for signing after 5 wrong passwords/,+ );+ assert.match(+ describeSigningCredentialFailure({ attemptsLeft: 1, locked: false }),+ /1 try is left/,+ );+ assert.match(+ describeSigningCredentialFailure({ attemptsLeft: 3, locked: false }),+ /3 tries are left/,+ );+});diff --git a/src/lib/part11.ts b/src/lib/part11.tsindex 028743b..048fc82 100644--- a/src/lib/part11.ts+++ b/src/lib/part11.ts@@ -334,18 +334,46 @@ async function defaultPasswordVerifier(input: {return context.password.verify(input);}-export type SigningPasswordResult =- | { ok: true }- | {- attemptsLeft: number;- /**- * An administrator took back the identity confirmation, or the email- * address is no longer confirmed, since the envelope was sent.- */- identityNotConfirmed?: true;- locked: boolean;- ok: false;- };+export type SigningPasswordFailure = {+ attemptsLeft: number;+ /**+ * An administrator took back the identity confirmation, or the email+ * address is no longer confirmed, since the envelope was sent.+ */+ identityNotConfirmed?: true;+ locked: boolean;+ ok: false;+ /**+ * The account's identity is confirmed, but under a different name than the+ * one this envelope was sent to (for example, after a name change and+ * re-confirmation).+ */+ signerNameMismatch?: true;+};++export type SigningPasswordResult = { ok: true } | SigningPasswordFailure;++/**+ * Plain-English explanation shown on the signing page when a Part 11 account+ * check or signature re-authentication is refused.+ */+export function describeSigningCredentialFailure(+ result: Omit<SigningPasswordFailure, "ok">,+): string {+ if (result.identityNotConfirmed) {+ return "Your account cannot sign this document right now: an administrator has to confirm your identity, and your email address must be confirmed. Ask the sender or an administrator.";+ }++ if (result.signerNameMismatch) {+ return "This signing link was sent under a different name than your account's confirmed name. Part 11 signatures are made in the confirmed name, so this invitation cannot be signed. Ask the sender to void this envelope with a reason and send a new one in your confirmed name.";+ }++ if (result.locked) {+ return `This account is locked for signing after ${MAX_SIGNING_PASSWORD_ATTEMPTS} wrong passwords. Ask an administrator to unlock it.`;+ }++ return `That email address or password is not right. ${result.attemptsLeft} ${result.attemptsLeft === 1 ? "try is" : "tries are"} left before the account is locked for signing.`;+}/*** The two parts of a Part 11 signature: the account's email address (its@@ -418,20 +446,30 @@ export async function checkSigningCredentials(// Checked again at every signature: what was true at send may not be// now. Not a wrong password, so it does not count towards the lock.+ if (!account.emailVerified || account.identityVerifiedAt === null) {+ return {+ attemptsLeft: Math.max(+ 0,+ MAX_SIGNING_PASSWORD_ATTEMPTS - account.failedAttempts,+ ),+ identityNotConfirmed: true as const,+ locked: false,+ ok: false as const,+ };+ }+if (- !account.emailVerified ||- account.identityVerifiedAt === null ||- (input.signerName !== undefined &&- !namesMatch(input.signerName, account.name))+ input.signerName !== undefined &&+ !namesMatch(input.signerName, account.name)) {return {attemptsLeft: Math.max(0,MAX_SIGNING_PASSWORD_ATTEMPTS - account.failedAttempts,),- identityNotConfirmed: true as const,locked: false,ok: false as const,+ signerNameMismatch: true as const,};}@@ -510,6 +548,9 @@ export async function checkSigningCredentials(: {}),locked: outcome.locked,ok: false,+ ...("signerNameMismatch" in outcome && outcome.signerNameMismatch+ ? { signerNameMismatch: true as const }+ : {}),};}diff --git a/src/lib/signing.ts b/src/lib/signing.tsindex 5ffd749..e2b8b9a 100644--- a/src/lib/signing.ts+++ b/src/lib/signing.ts@@ -53,7 +53,7 @@ import {} from "./settings.ts";import {checkSigningCredentials,- MAX_SIGNING_PASSWORD_ATTEMPTS,+ describeSigningCredentialFailure,type PasswordVerifier,SIGNATURE_MEANING_DETAILS,} from "./part11.ts";@@ -1594,22 +1594,6 @@ export async function sendSignerEmailCode(* Checks an access code or emailed code. Returns every check this browser* has now passed, for the caller to store in the link's cookie.*/-function describeCredentialFailure(result: {- attemptsLeft: number;- identityNotConfirmed?: true;- locked: boolean;-}): string {- if (result.identityNotConfirmed) {- return "Your account cannot sign this document right now: an administrator has to confirm your identity, and your email address must be confirmed. Ask the sender or an administrator.";- }-- if (result.locked) {- return `This account is locked for signing after ${MAX_SIGNING_PASSWORD_ATTEMPTS} wrong passwords. Ask an administrator to unlock it.`;- }-- return `That email address or password is not right. ${result.attemptsLeft} ${result.attemptsLeft === 1 ? "try is" : "tries are"} left before the account is locked for signing.`;-}-export async function verifySignerCheck(token: string,input: unknown,@@ -1664,7 +1648,10 @@ export async function verifySignerCheck(database,);- throw new SigningMutationError(describeCredentialFailure(result), 400);+ throw new SigningMutationError(+ describeSigningCredentialFailure(result),+ 400,+ );}} else if (parsed.method === "access_code") {// An access code can be short, so wrong ones are counted per signer and@@ -2284,7 +2271,10 @@ async function reauthenticatePart11Signer(database,);- throw new SigningMutationError(describeCredentialFailure(result), 400);+ throw new SigningMutationError(+ describeSigningCredentialFailure(result),+ 400,+ );}return {