Skip to content

Open-source document signature platform. Not affiliated with DocuSign.

TypeScript

Say when a resent signing code was not sent

Claude164c448b5103
diff --git a/src/components/signing/signer-verification-screen.tsx b/src/components/signing/signer-verification-screen.tsx
index 8164f8e..880329e 100644
--- a/src/components/signing/signer-verification-screen.tsx
+++ b/src/components/signing/signer-verification-screen.tsx
@@ -1,7 +1,7 @@
"use client";
import { ShieldCheckIcon } from "lucide-react";
-import { useState, type FormEvent } from "react";
+import { useEffect, useState, type FormEvent } from "react";
import { Brand } from "@/components/layout/brand";
import { PublicLegalFooter } from "@/components/layout/public-legal-links";
@@ -44,6 +44,9 @@ export function SignerVerificationScreen({
);
const [isChecking, setIsChecking] = useState(false);
const [isSending, setIsSending] = useState(false);
+ // Seconds left before the server will send another code, counted down
+ // after it says the last one is still in its resend cooldown.
+ const [resendWait, setResendWait] = useState(0);
const base = `/api/signing/${encodeURIComponent(token)}`;
async function sendCode() {
@@ -57,6 +60,8 @@ export function SignerVerificationScreen({
const payload = (await response.json().catch(() => null)) as {
error?: string;
maskedEmail?: string;
+ retryAfterSeconds?: number;
+ sent?: boolean;
} | null;
if (!response.ok) {
@@ -64,8 +69,20 @@ export function SignerVerificationScreen({
return;
}
+ const maskedEmail = payload?.maskedEmail ?? state.maskedEmail;
+
+ if (payload?.sent === false) {
+ setNotice(
+ `A code was already sent to ${maskedEmail} less than a minute ago, so no new email went out. Use that code, or send a new one when the countdown on the button ends.`,
+ );
+ setResendWait(Math.max(1, Math.ceil(payload.retryAfterSeconds ?? 60)));
+ return;
+ }
+
setNotice(
- `A code was sent to ${payload?.maskedEmail ?? state.maskedEmail}.`,
+ notice
+ ? `A new code was sent to ${maskedEmail}.`
+ : `A code was sent to ${maskedEmail}.`,
);
} catch {
setError("The code could not be sent right now.");
@@ -108,6 +125,18 @@ export function SignerVerificationScreen({
}
}
+ useEffect(() => {
+ if (resendWait <= 0) {
+ return;
+ }
+
+ const timer = window.setTimeout(() => {
+ setResendWait((seconds) => Math.max(0, seconds - 1));
+ }, 1000);
+
+ return () => window.clearTimeout(timer);
+ }, [resendWait]);
+
const copy = METHOD_COPY[method];
const step = state.required.indexOf(method) + 1;
@@ -187,11 +216,16 @@ export function SignerVerificationScreen({
</ShellButton>
{method === "email_code" ? (
<ShellButton
+ disabled={resendWait > 0}
loading={isSending}
onClick={sendCode}
variant="secondary"
>
- {notice ? "Send a new code" : "Email me a code"}
+ {!notice
+ ? "Email me a code"
+ : resendWait > 0
+ ? `Send a new code in ${String(resendWait)}s`
+ : "Send a new code"}
</ShellButton>
) : null}
</div>
diff --git a/src/lib/signer-email-code.dbtest.ts b/src/lib/signer-email-code.dbtest.ts
new file mode 100644
index 0000000..09e1191
--- /dev/null
+++ b/src/lib/signer-email-code.dbtest.ts
@@ -0,0 +1,186 @@
+import assert from "node:assert/strict";
+import { createHash, randomUUID } from "node:crypto";
+import { mkdtemp, readdir, readFile, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { after, before, test } from "node:test";
+
+import { PDFDocument } from "pdf-lib";
+import type pg from "pg";
+
+import { openTestDatabase } from "./db/test-database.ts";
+import { EMAIL_CODE_RESEND_SECONDS } from "./signer-checks.ts";
+import { issueSigningLink } from "./services/signing-links.ts";
+import {
+ createStorageService,
+ type StorageService,
+} from "./services/storage.ts";
+import { sendSignerEmailCode } from "./signing.ts";
+
+// Asking for a new one-time code during the resend cooldown, against a real
+// Postgres. Run with `npm run test:db`.
+
+process.env.APP_URL ??= "https://sign.example.test";
+
+const DAY = 24 * 60 * 60;
+
+let database: pg.Pool;
+let storageDir: string;
+let outboxDir: string;
+let storageService: StorageService;
+const createdUsers: string[] = [];
+
+before(async () => {
+ database = await openTestDatabase();
+ globalThis.__signudocPgPool = database;
+ storageDir = await mkdtemp(path.join(tmpdir(), "signudoc-email-code-"));
+ outboxDir = path.join(storageDir, "outbox");
+ Object.assign(process.env, {
+ EMAIL_CAPTURE_DIR: outboxDir,
+ EMAIL_DRIVER: "capture",
+ STORAGE_DRIVER: "local",
+ STORAGE_LOCAL_DIR: storageDir,
+ });
+ storageService = createStorageService();
+});
+
+after(async () => {
+ await database.query(`delete from public."user" where id = any($1)`, [
+ createdUsers,
+ ]);
+ await database.end();
+ await rm(storageDir, { force: true, recursive: true });
+});
+
+/** A sent envelope whose one signer must confirm an emailed code. */
+async function createEnvelopeWithEmailCode() {
+ const userId = randomUUID();
+ const envelopeId = randomUUID();
+ const signerId = randomUUID();
+ const email = `${signerId}@example.test`;
+ const now = Math.floor(Date.now() / 1000);
+ const sourcePdf = await PDFDocument.create();
+
+ sourcePdf.addPage([612, 792]);
+
+ const sourcePdfBytes = await sourcePdf.save();
+ const sourcePdfKey = `test/${envelopeId}.pdf`;
+
+ await storageService.putObject({
+ body: sourcePdfBytes,
+ contentType: "application/pdf",
+ key: sourcePdfKey,
+ });
+
+ createdUsers.push(userId);
+ await database.query(
+ `insert into public."user" (id, name, email, role) values ($1, 'Sam Sender', $2, 'user')`,
+ [userId, `${userId}@example.test`],
+ );
+ 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, expires_at
+ ) values ($1, $2, 'Lease', 'sent', $3, 'lease.pdf', $4, 1, $5, $6, $7)
+ `,
+ [
+ envelopeId,
+ userId,
+ sourcePdfKey,
+ sourcePdfBytes.length,
+ createHash("sha256").update(sourcePdfBytes).digest("hex"),
+ now,
+ now + DAY,
+ ],
+ );
+ await database.query(
+ `
+ insert into envelope_pages (id, envelope_id, page_number, width_pt, height_pt)
+ values ($1, $2, 1, 612, 792)
+ `,
+ [randomUUID(), envelopeId],
+ );
+
+ const link = await issueSigningLink({ expiresInSeconds: DAY, issuedAt: now });
+
+ await database.query(
+ `
+ insert into signers (
+ id, envelope_id, name, email, sign_order, status,
+ signing_token_hash, signing_token_expires_at, last_notified_at,
+ require_email_code
+ ) values ($1, $2, 'Riley Signer', $3, 1, 'notified', $4, $5, $6, true)
+ `,
+ [signerId, envelopeId, email, link.tokenHash, link.exp, now],
+ );
+ await database.query(
+ `
+ insert into fields (
+ id, envelope_id, signer_id, type, page, x, y, width, height
+ ) values ($1, $2, $3, 'signature', 1, 0.1, 0.1, 0.2, 0.1)
+ `,
+ [randomUUID(), envelopeId, signerId],
+ );
+
+ return { email, signerId, token: link.token };
+}
+
+async function codeEmailsTo(email: string) {
+ const files = await readdir(outboxDir).catch(() => [] as string[]);
+ const messages = await Promise.all(
+ files
+ .filter((file) => file.endsWith(".json"))
+ .map(
+ async (file) =>
+ JSON.parse(await readFile(path.join(outboxDir, file), "utf8")) as {
+ template: string;
+ to: string | string[];
+ },
+ ),
+ );
+
+ return messages.filter(
+ (message) =>
+ message.template === "signing_code" &&
+ (Array.isArray(message.to) ? message.to : [message.to]).includes(email),
+ );
+}
+
+test("a resend during the cooldown says no new code was sent", async () => {
+ const signer = await createEnvelopeWithEmailCode();
+
+ const first = await sendSignerEmailCode(signer.token, { database });
+
+ assert.equal(first.sent, true);
+ assert.equal(first.retryAfterSeconds, 0);
+ assert.equal((await codeEmailsTo(signer.email)).length, 1);
+
+ const again = await sendSignerEmailCode(signer.token, { database });
+
+ assert.equal(again.sent, false, "no second email went out");
+ assert.equal(again.emailCodeSentAt, first.emailCodeSentAt);
+ assert.ok(
+ again.retryAfterSeconds > 0 &&
+ again.retryAfterSeconds <= EMAIL_CODE_RESEND_SECONDS,
+ `retryAfterSeconds is within the cooldown, got ${String(again.retryAfterSeconds)}`,
+ );
+ assert.equal((await codeEmailsTo(signer.email)).length, 1);
+});
+
+test("a resend after the cooldown sends a new code and says so", async () => {
+ const signer = await createEnvelopeWithEmailCode();
+
+ await sendSignerEmailCode(signer.token, { database });
+ // Move the first send back past the cooldown.
+ await database.query(
+ `update signers set email_code_sent_at = email_code_sent_at - $2 where id = $1`,
+ [signer.signerId, EMAIL_CODE_RESEND_SECONDS + 1],
+ );
+
+ const again = await sendSignerEmailCode(signer.token, { database });
+
+ assert.equal(again.sent, true);
+ assert.equal(again.retryAfterSeconds, 0);
+ assert.equal((await codeEmailsTo(signer.email)).length, 2);
+});
diff --git a/src/lib/signing.ts b/src/lib/signing.ts
index f950d5e..e2060b3 100644
--- a/src/lib/signing.ts
+++ b/src/lib/signing.ts
@@ -1328,6 +1328,34 @@ function signerAuditMetadata(context: ResolvedSigningContext) {
};
}
+export type SignerEmailCodeResult = {
+ emailCodeSentAt: number;
+ maskedEmail: string;
+ /** Seconds until a new code can be sent; 0 when this call sent one. */
+ retryAfterSeconds: number;
+ /**
+ * Whether this call emailed a new code. False during the resend cooldown,
+ * when the code sent a moment ago is still the one to use.
+ */
+ sent: boolean;
+};
+
+function cooldownResult(
+ emailCodeSentAt: number,
+ now: number,
+ maskedEmail: string,
+): SignerEmailCodeResult {
+ return {
+ emailCodeSentAt,
+ maskedEmail,
+ retryAfterSeconds: Math.max(
+ 1,
+ emailCodeSentAt + EMAIL_CODE_RESEND_SECONDS - now,
+ ),
+ sent: false,
+ };
+}
+
/** Emails the signer a one-time code, when the sender asked for one. */
export async function sendSignerEmailCode(
token: string,
@@ -1335,7 +1363,7 @@ export async function sendSignerEmailCode(
database = getDb(),
emailService = createEmailService(),
}: { database?: DbPool; emailService?: EmailService } = {},
-): Promise<{ emailCodeSentAt: number; maskedEmail: string }> {
+): Promise<SignerEmailCodeResult> {
const context = await resolveSigningContext(token, { database });
const state = await getSignerCheckState(context.signer.id!, database);
const now = Math.floor(Date.now() / 1000);
@@ -1349,10 +1377,11 @@ export async function sendSignerEmailCode(
now - state.emailCodeSentAt < EMAIL_CODE_RESEND_SECONDS &&
state.emailCodeHash
) {
- return {
- emailCodeSentAt: state.emailCodeSentAt,
- maskedEmail: maskEmailAddress(context.signer.email),
- };
+ return cooldownResult(
+ state.emailCodeSentAt,
+ now,
+ maskEmailAddress(context.signer.email),
+ );
}
const issued = issueEmailCode();
@@ -1404,12 +1433,14 @@ export async function sendSignerEmailCode(
);
}
+ // Another request claimed the window first and sent the code.
const current = await getSignerCheckState(context.signer.id!, database);
- return {
- emailCodeSentAt: current.emailCodeSentAt ?? now,
- maskedEmail: maskEmailAddress(context.signer.email),
- };
+ return cooldownResult(
+ current.emailCodeSentAt ?? now,
+ now,
+ maskEmailAddress(context.signer.email),
+ );
}
const minutes = Math.round(EMAIL_CODE_TTL_SECONDS / 60);
@@ -1470,6 +1501,8 @@ export async function sendSignerEmailCode(
return {
emailCodeSentAt: now,
maskedEmail: maskEmailAddress(context.signer.email),
+ retryAfterSeconds: 0,
+ sent: true,
};
}