Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Let the last signer finish when email is not set up (#96)
Claude8a76ad07627b
diff --git a/src/lib/envelope-deadline.dbtest.ts b/src/lib/envelope-deadline.dbtest.tsindex 79f2661..2922797 100644--- a/src/lib/envelope-deadline.dbtest.ts+++ b/src/lib/envelope-deadline.dbtest.ts@@ -849,3 +849,113 @@ test("a reminder with no email provider is refused before the signer's link is r);assert.deepEqual(await auditEvents(envelopeId), []);});++/** Runs `run` with no email provider set, as an install whose email setup was removed. */+async function withoutEmailProvider<T>(+ run: () => Promise<T>,+ extra: Record<string, string> = {},+) {+ const names = ["EMAIL_DRIVER", "RESEND_API_KEY", ...Object.keys(extra)];+ const settingsBefore = names.map(+ (name) => [name, process.env[name]] as const,+ );++ delete process.env.EMAIL_DRIVER;+ delete process.env.RESEND_API_KEY;+ Object.assign(process.env, extra);++ try {+ return await run();+ } finally {+ for (const [name, value] of settingsBefore) {+ if (value === undefined) {+ delete process.env[name];+ } else {+ process.env[name] = value;+ }+ }+ }+}++test("the last signer completes the envelope when no email provider is set (issue #96)", async () => {+ const envelope = await createSignableEnvelope();++ try {+ await withoutEmailProvider(() =>+ submitSigningForToken(+ envelope.token,+ {+ clientTimezoneOffsetMinutes: 0,+ fields: [+ {+ fieldId: envelope.fieldId,+ imageDataUrl: DRAWN_SIGNATURE,+ inputMethod: "drawn",+ type: "signature",+ },+ ],+ },+ { database, storageService: envelope.storageService },+ ),+ );++ const state = await database.query<{+ signed_pdf_key: string | null;+ signer_status: string;+ status: string;+ values: string;+ }>(+ `+ select e.status, e.signed_pdf_key, s.status as signer_status,+ (select count(*) from fields f+ where f.id = $2 and f.submitted_at is not null)::text as values+ from envelopes e join signers s on s.envelope_id = e.id+ where e.id = $1+ `,+ [envelope.envelopeId, envelope.fieldId],+ );++ assert.equal(state.rows[0]?.status, "completed");+ assert.equal(state.rows[0]?.signer_status, "signed");+ assert.ok(state.rows[0]?.signed_pdf_key);+ assert.equal(state.rows[0]?.values, "1");++ const events = await auditEvents(envelope.envelopeId);++ assert.equal(events.filter((event) => event === "signed").length, 1);+ assert.equal(events.filter((event) => event === "completed").length, 1);+ assert.equal(+ (await verifyAuditChain(envelope.envelopeId, database)).ok,+ true,+ );+ } finally {+ await rm(envelope.storageDir, { force: true, recursive: true });+ }+});++test("a signer can decline when no email provider is set (issue #96)", async () => {+ const envelope = await createSignableEnvelope();++ try {+ const declined = await withoutEmailProvider(+ () =>+ declineSigningForToken(+ envelope.token,+ { reason: "Not what we agreed." },+ { database },+ ),+ { STORAGE_DRIVER: "local", STORAGE_LOCAL_DIR: envelope.storageDir },+ );++ assert.equal(declined.state, "declined");++ const envelopeRow = await database.query<{ status: string }>(+ `select status from envelopes where id = $1`,+ [envelope.envelopeId],+ );++ assert.equal(envelopeRow.rows[0]?.status, "declined");+ } finally {+ await rm(envelope.storageDir, { force: true, recursive: true });+ }+});diff --git a/src/lib/services/email.test.ts b/src/lib/services/email.test.tsindex 180726c..39cfcc1 100644--- a/src/lib/services/email.test.ts+++ b/src/lib/services/email.test.ts@@ -3,7 +3,11 @@ import { test } from "node:test";import type { Resend } from "resend";-import { createEmailService } from "./email.ts";+import {+ createEmailService,+ createLazyEmailService,+ type EmailService,+} from "./email.ts";// What the Resend client is asked to do when the service turns a request// away for rate. Nothing here talks to Resend.@@ -130,3 +134,30 @@ test("a batch turned away for rate is sent again too", async () => {assert.equal(deliveries[0]?.messageId, "email_1");assert.equal(requests(), 2);});++test("a lazy email service is only built when it first sends, and only once", async () => {+ let built = 0;+ const service = createLazyEmailService(() => {+ built += 1;++ return {+ async send(message) {+ return { accepted: [message.to], messageId: "m-1", rejected: [] };+ },+ async sendBatch() {+ return [];+ },+ } satisfies EmailService;+ });++ assert.equal(built, 0);+ await service.send(MESSAGE);+ await service.sendBatch([MESSAGE]);+ assert.equal(built, 1);+});++test("a lazy email service with no provider fails the send, not its creation (issue #96)", async () => {+ const service = createLazyEmailService(() => createEmailService({ env: {} }));++ await assert.rejects(service.send(MESSAGE), /RESEND_API_KEY/);+});diff --git a/src/lib/services/email.ts b/src/lib/services/email.tsindex c9ac4c5..3e84932 100644--- a/src/lib/services/email.ts+++ b/src/lib/services/email.ts@@ -314,6 +314,26 @@ export function isEmailNotConnectedError(error: unknown): boolean {);}+/**+ * An email service that is only built when a message is first sent. A flow+ * that sends email as a side effect after saving its own work (a signer+ * finishing or declining) uses it, so a missing provider key fails the+ * send, which that flow already logs and survives, instead of the whole+ * request (issue #96).+ */+export function createLazyEmailService(+ create: () => EmailService = () => createEmailService(),+): EmailService {+ let service: EmailService | undefined;+ const resolve = () => (service ??= create());++ return {+ send: async (message, options) => resolve().send(message, options),+ sendBatch: async (messages, options) =>+ resolve().sendBatch(messages, options),+ };+}+export function createEmailService({env = process.env,resolveAddresses = () => resolveEmailAddresses(env),diff --git a/src/lib/signing.ts b/src/lib/signing.tsindex a70a14d..fbdb666 100644--- a/src/lib/signing.ts+++ b/src/lib/signing.ts@@ -58,6 +58,7 @@ import {} from "./services/audit.ts";import {createEmailService,+ createLazyEmailService,fitsAsAttachments,type EmailAttachment,type EmailService,@@ -2361,7 +2362,7 @@ export async function submitSigningForToken();}- const emailService = givenEmailService ?? createEmailService();+ const emailService = givenEmailService ?? createLazyEmailService();const part11Signature = await reauthenticatePart11Signer(context,signerChecks.state,@@ -3040,7 +3041,7 @@ export async function declineSigningForToken(const context = await resolveSigningContext(token, { database });await assertSignerChecksPassed(context, verifiedMethods, database);- const emailService = createEmailService();+ const emailService = createLazyEmailService();const storageService = createStorageService();const currentSignerId = context.signer.id;const presentedTokenHash = hashOpaqueToken(token);