Skip to content

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

TypeScript

Fix review findings in the local drivers and the test setup

Claude0ff078f3cf00
diff --git a/e2e/global-setup.ts b/e2e/global-setup.ts
index 1980df7..34fa63c 100644
--- a/e2e/global-setup.ts
+++ b/e2e/global-setup.ts
@@ -1,4 +1,3 @@
-import { execFileSync } from "node:child_process";
import { rm } from "node:fs/promises";
import pg from "pg";
@@ -58,10 +57,13 @@ export default async function globalSetup() {
await client.end();
}
- execFileSync(process.execPath, ["db/migrate.mjs"], {
- env: { ...process.env, DATABASE_URL: e2eDatabaseUrl },
- stdio: "inherit",
- });
+ // Called directly with the test database, so a DATABASE_URL_UNPOOLED or
+ // similar in the developer's own environment cannot redirect it.
+ // The runner is an ES module, so it is loaded with import() rather than a
+ // static import that Playwright would compile to require().
+ const { runMigrations } = await import("../db/migrate.mjs");
+
+ await runMigrations({ connectionString: e2eDatabaseUrl });
await rm(e2eDataDir, { force: true, recursive: true });
}
diff --git a/e2e/signing-flow.spec.ts b/e2e/signing-flow.spec.ts
index 2ad56fc..913771f 100644
--- a/e2e/signing-flow.spec.ts
+++ b/e2e/signing-flow.spec.ts
@@ -4,7 +4,9 @@ import { extractLink, extractLinks, waitForEmail } from "./support/outbox";
import { writeSamplePdf } from "./support/sample-pdf";
const PASSWORD = "correct horse battery staple 42";
-const ENVELOPE_TITLE = "E2E sample agreement";
+// The accent and the em dash are on purpose: download file names are built
+// from the title, and a header value cannot carry the em dash as it is.
+const ENVELOPE_TITLE = "Façade works agreement — phase 1";
function watchForContentSecurityPolicyViolations(page: Page, sink: string[]) {
page.on("console", (message) => {
diff --git a/e2e/support/outbox.ts b/e2e/support/outbox.ts
index 567dfc0..ad0af9b 100644
--- a/e2e/support/outbox.ts
+++ b/e2e/support/outbox.ts
@@ -23,15 +23,19 @@ async function readOutbox(): Promise<CapturedEmail[]> {
fileNames
.filter((fileName) => fileName.endsWith(".json"))
.sort()
- .map(
- async (fileName) =>
- JSON.parse(
+ .map(async (fileName) => {
+ try {
+ return JSON.parse(
await readFile(path.join(e2eOutboxDir, fileName), "utf8"),
- ) as CapturedEmail,
- ),
+ ) as CapturedEmail;
+ } catch {
+ // Unreadable right now: the next poll picks it up.
+ return null;
+ }
+ }),
);
- return emails;
+ return emails.filter((email) => email !== null);
}
/** Waits for the newest captured email with this template and recipient. */
diff --git a/src/lib/services/email.ts b/src/lib/services/email.ts
index 249cac5..6edfec3 100644
--- a/src/lib/services/email.ts
+++ b/src/lib/services/email.ts
@@ -1,5 +1,5 @@
import { randomUUID } from "node:crypto";
-import { mkdir, writeFile } from "node:fs/promises";
+import { mkdir, rename, writeFile } from "node:fs/promises";
import path from "node:path";
import { Resend } from "resend";
@@ -127,8 +127,11 @@ function createCaptureEmailService(env: EnvSource): EmailService {
}
const emailEnv = getEnv(env).email;
+ // The comment stops Turbopack from tracing the whole project into the
+ // server bundle because of a path it cannot analyse.
const captureDir = path.resolve(
- env.EMAIL_CAPTURE_DIR?.trim() || DEFAULT_CAPTURE_DIR,
+ /*turbopackIgnore: true*/ env.EMAIL_CAPTURE_DIR?.trim() ||
+ DEFAULT_CAPTURE_DIR,
);
const config = {
senderAddress: emailEnv.senderAddress ?? DEFAULT_CAPTURE_SENDER_ADDRESS,
@@ -140,13 +143,17 @@ function createCaptureEmailService(env: EnvSource): EmailService {
): Promise<EmailDeliveryResult> {
const messageId = `capture-${randomUUID()}`;
const filePath = path.join(
- captureDir,
+ /*turbopackIgnore: true*/ captureDir,
`${String(Date.now())}-${messageId}.json`,
);
+ const temporaryPath = `${filePath}.tmp`;
+
+ // Written under a temporary name and renamed, so anything watching the
+ // outbox never reads a half-written file.
await mkdir(captureDir, { recursive: true });
await writeFile(
- filePath,
+ temporaryPath,
JSON.stringify(
{
...buildResendPayload(message, config),
@@ -158,6 +165,7 @@ function createCaptureEmailService(env: EnvSource): EmailService {
2,
),
);
+ await rename(temporaryPath, filePath);
console.info(
`[email:capture] ${message.template} to ${message.to} -> ${filePath}`,
);
diff --git a/src/lib/services/storage.ts b/src/lib/services/storage.ts
index 2105ee0..60e790b 100644
--- a/src/lib/services/storage.ts
+++ b/src/lib/services/storage.ts
@@ -25,8 +25,14 @@ export function buildContentDisposition(
fileName: string,
dispositionType: "attachment" | "inline" = "attachment",
): string {
- const fallbackName = fileName.replace(/["\\\r\n]+/g, "_");
- const encodedName = encodeURIComponent(fileName).replace(/\+/g, "%20");
+ // Header values must be Latin-1, and the quoted fallback is safest as plain
+ // ASCII. Browsers that understand filename* (all current ones) use the
+ // UTF-8 name instead.
+ const fallbackName = fileName.replace(/[^\x20-\x7e]+|["\\]+/g, "_");
+ const encodedName = encodeURIComponent(fileName).replace(
+ /['()*]/g,
+ (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,
+ );
return `${dispositionType}; filename="${fallbackName}"; filename*=UTF-8''${encodedName}`;
}
diff --git a/src/lib/services/storage/local.ts b/src/lib/services/storage/local.ts
index eeb8d19..587a324 100644
--- a/src/lib/services/storage/local.ts
+++ b/src/lib/services/storage/local.ts
@@ -1,5 +1,6 @@
+import { randomUUID } from "node:crypto";
import { createReadStream } from "node:fs";
-import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
+import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { Readable } from "node:stream";
@@ -35,6 +36,24 @@ function isMissingFileError(error: unknown): boolean {
);
}
+// Writes to a temporary name and renames it into place, so a reader never
+// sees a half-written file.
+async function writeFileAtomically(
+ filePath: string,
+ data: Uint8Array | string,
+) {
+ const temporaryPath = `${filePath}.${randomUUID()}.tmp`;
+
+ try {
+ await writeFile(temporaryPath, data);
+ await rename(temporaryPath, filePath);
+ } catch (error) {
+ await rm(temporaryPath, { force: true });
+
+ throw error;
+ }
+}
+
export function createLocalStorageService({
env = process.env,
rootDir,
@@ -45,13 +64,20 @@ export function createLocalStorageService({
);
}
+ // The comment stops Turbopack from tracing the whole project into the
+ // server bundle because of a path it cannot analyse.
const resolvedRootDir = path.resolve(
- rootDir ?? env.STORAGE_LOCAL_DIR?.trim() ?? DEFAULT_LOCAL_STORAGE_DIR,
+ /*turbopackIgnore: true*/ rootDir ??
+ env.STORAGE_LOCAL_DIR?.trim() ??
+ DEFAULT_LOCAL_STORAGE_DIR,
);
function resolveObjectPath(key: string) {
const normalizedKey = normalizeStorageKey(key);
- const objectPath = path.join(resolvedRootDir, ...normalizedKey.split("/"));
+ const objectPath = path.join(
+ /*turbopackIgnore: true*/ resolvedRootDir,
+ ...normalizedKey.split("/"),
+ );
return { normalizedKey, objectPath };
}
@@ -161,15 +187,15 @@ export function createLocalStorageService({
const { normalizedKey, objectPath } = resolveObjectPath(input.key);
await mkdir(path.dirname(objectPath), { recursive: true });
- await Promise.all([
- writeFile(objectPath, input.body),
- writeFile(
- `${objectPath}${METADATA_SUFFIX}`,
- JSON.stringify({
- contentType: input.contentType,
- } satisfies LocalObjectMetadata),
- ),
- ]);
+ // Metadata first: once the object itself is visible, its content type
+ // is already there to be read.
+ await writeFileAtomically(
+ `${objectPath}${METADATA_SUFFIX}`,
+ JSON.stringify({
+ contentType: input.contentType,
+ } satisfies LocalObjectMetadata),
+ );
+ await writeFileAtomically(objectPath, input.body);
return {
bucketName: LOCAL_BUCKET_NAME,