Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Answer a repeated thumbnail request without a read from file storage
Claude8e2b9059f2b5
diff --git a/e2e/signing-flow.spec.ts b/e2e/signing-flow.spec.tsindex dcef1fa..cd95859 100644--- a/e2e/signing-flow.spec.ts+++ b/e2e/signing-flow.spec.ts@@ -619,8 +619,8 @@ test("a new install is set up, a sender sends a PDF and a recipient signs it", a.toBeGreaterThan(0);// The picture is stored beside the PDF, as a JPEG, and only the account- // that sent the document can read it. The browser is told to keep no- // copy, as it is for the document itself.+ // that sent the document can read it. The browser may keep its copy,+ // but has to ask before showing it again.await expect.poll(async () => (await page.request.get(thumbnailPath)).status()).toBe(200);@@ -628,13 +628,32 @@ test("a new install is set up, a sender sends a PDF and a recipient signs it", aconst thumbnailHeaders = (await page.request.get(thumbnailPath)).headers();expect(thumbnailHeaders["content-type"]).toBe("image/jpeg");- expect(thumbnailHeaders["cache-control"]).toBe("private, no-store");+ expect(thumbnailHeaders["cache-control"]).toBe("private, no-cache");+ expect(thumbnailHeaders["etag"]).toBeTruthy();+ // Asking again with the picture's name is answered "still good", with+ // no picture in the answer.+ const revalidation = await page.request.get(thumbnailPath, {+ headers: { "if-none-match": thumbnailHeaders["etag"] },+ });++ expect(revalidation.status()).toBe(304);+ expect((await revalidation.body()).byteLength).toBe(0);+ expect(revalidation.headers()["cache-control"]).toBe("private, no-cache");++ // Signed out, the same question gets no answer at all.const anonymousContext = await browser.newContext();expect((await anonymousContext.request.get(thumbnailPath)).status()).toBe(401,);+ expect(+ (+ await anonymousContext.request.get(thumbnailPath, {+ headers: { "if-none-match": thumbnailHeaders["etag"] },+ })+ ).status(),+ ).toBe(401);await anonymousContext.close();});diff --git a/src/app/api/envelopes/[id]/thumbnail/route.ts b/src/app/api/envelopes/[id]/thumbnail/route.tsindex a3280ad..b78e21f 100644--- a/src/app/api/envelopes/[id]/thumbnail/route.ts+++ b/src/app/api/envelopes/[id]/thumbnail/route.ts@@ -28,6 +28,15 @@ type EnvelopeThumbnailRouteContext = {const privateNoStore = { "cache-control": "private, no-store" };+// The picture itself. The browser may keep its copy, but must ask here+// before showing it again, so every showing still takes a signed-in request+// from the account that owns the envelope. When the copy is still good the+// answer is a 304 with no picture in it, and nothing is read from file+// storage. A dashboard of twenty documents would otherwise take twenty reads+// each time it opens, out of the 10,000 a month that Vercel Blob's free+// plan allows before it stops serving files.+const privateRevalidate = { "cache-control": "private, no-cache" };+// The picture of a document's first page that the dashboard shows. Only the// account that owns the envelope can read or write it.export async function GET(@@ -46,25 +55,33 @@ export async function GET(try {const thumbnail = await getEnvelopeThumbnailForUser(session.user.id, id, {database: getDb(),+ ifNoneMatch: request.headers.get("if-none-match"),});++ if (thumbnail.isNotModified) {+ return new Response(null, {+ headers: { ...privateRevalidate, etag: thumbnail.etag },+ status: 304,+ });+ }++ const { picture } = thumbnail;const headers = new Headers({- // As private as the document it was drawn from, and served the same- // way: the browser keeps no copy, so showing it always takes a- // signed-in request from the account that owns the envelope.- ...privateNoStore,+ ...privateRevalidate,"content-disposition": "inline",// Stored as a JPEG whatever the upload claimed to be, and served as// nothing else."content-security-policy": "default-src 'none'; sandbox","content-type": THUMBNAIL_CONTENT_TYPE,+ etag: thumbnail.etag,"x-content-type-options": "nosniff",});- if (typeof thumbnail.contentLength === "number") {- headers.set("content-length", String(thumbnail.contentLength));+ if (typeof picture.contentLength === "number") {+ headers.set("content-length", String(picture.contentLength));}- return new Response(thumbnail.stream, { headers, status: 200 });+ return new Response(picture.stream, { headers, status: 200 });} catch (error) {if (error instanceof EnvelopeDocumentAccessError) {return NextResponse.json(diff --git a/src/lib/envelope-thumbnail.dbtest.ts b/src/lib/envelope-thumbnail.dbtest.tsindex d020be4..1f52de1 100644--- a/src/lib/envelope-thumbnail.dbtest.ts+++ b/src/lib/envelope-thumbnail.dbtest.ts@@ -16,6 +16,7 @@ import {} from "./envelopes.ts";import { deleteEnvelopesAndFiles } from "./retention.ts";import { buildEnvelopeThumbnailKey } from "./services/storage-keys.ts";+import { buildThumbnailEtag } from "./services/thumbnails.ts";import {createStorageService,type StorageService,@@ -120,6 +121,85 @@ test("a picture is kept for an envelope that exists", async () => {assert.equal(await thumbnailExists(draft), true);});+test("a browser that already holds the picture is answered without a read from file storage", async () => {+ const draft = await insertDraft();++ await saveEnvelopeThumbnailForUser(+ draft.userId,+ draft.envelopeId,+ THUMBNAIL,+ { database, storageService },+ );++ const first = await getEnvelopeThumbnailForUser(+ draft.userId,+ draft.envelopeId,+ { database, storageService },+ );++ assert.equal(first.isNotModified, false);++ if (!first.isNotModified) {+ await first.picture.stream.cancel();+ }++ // From here on, any read of a file fails the test.+ const noReads: StorageService = {+ ...storageService,+ getObject: () => assert.fail("read a file"),+ getObjectStream: () => assert.fail("read a file"),+ headObject: () => assert.fail("read a file"),+ };+ const again = await getEnvelopeThumbnailForUser(+ draft.userId,+ draft.envelopeId,+ { database, ifNoneMatch: first.etag, storageService: noReads },+ );++ assert.deepEqual(again, { etag: first.etag, isNotModified: true });++ // The name of another envelope's picture is not this one's.+ const other = await insertDraft();+ const otherEtag = buildThumbnailEtag(other.envelopeId);++ assert.notEqual(otherEtag, first.etag);++ const mismatched = await getEnvelopeThumbnailForUser(+ draft.userId,+ draft.envelopeId,+ { database, ifNoneMatch: otherEtag, storageService },+ );++ assert.equal(mismatched.isNotModified, false);++ if (!mismatched.isNotModified) {+ await mismatched.picture.stream.cancel();+ }+});++test("quoting a picture's name does not show it to another account", async () => {+ const draft = await insertDraft();+ const stranger = await insertDraft();++ await saveEnvelopeThumbnailForUser(+ draft.userId,+ draft.envelopeId,+ THUMBNAIL,+ { database, storageService },+ );++ // The account is checked before the name is: someone who knows the+ // envelope's id, and so its picture's name, learns nothing from asking.+ await assert.rejects(+ getEnvelopeThumbnailForUser(stranger.userId, draft.envelopeId, {+ database,+ ifNoneMatch: buildThumbnailEtag(draft.envelopeId),+ storageService,+ }),+ assertNotFound,+ );+});+test("nobody else can store a picture for the envelope", async () => {const draft = await insertDraft();const stranger = await insertDraft();@@ -217,13 +297,17 @@ test("a picture stays with an envelope that is handed to another account", async[keeper.userId, draft.envelopeId],);- const picture = await getEnvelopeThumbnailForUser(+ const thumbnail = await getEnvelopeThumbnailForUser(keeper.userId,draft.envelopeId,{ database, storageService },);- await picture.stream.cancel();+ assert.equal(thumbnail.isNotModified, false);++ if (!thumbnail.isNotModified) {+ await thumbnail.picture.stream.cancel();+ }await assert.rejects(getEnvelopeThumbnailForUser(draft.userId, draft.envelopeId, {database,diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.tsindex 53db589..b9d0226 100644--- a/src/lib/envelopes.ts+++ b/src/lib/envelopes.ts@@ -84,6 +84,8 @@ import {} from "./services/storage.ts";import {assertThumbnailImage,+ buildThumbnailEtag,+ matchesEtag,THUMBNAIL_CONTENT_TYPE,} from "./services/thumbnails.ts";import {@@ -1597,32 +1599,52 @@ export async function saveEnvelopeThumbnailForUser(}}-/** Streams the stored first-page picture, or says there is none (404). */+export type EnvelopeThumbnail =+ | { etag: string; isNotModified: true }+ | { etag: string; isNotModified: false; picture: StorageObjectStream };++/**+ * Streams the stored first-page picture, or says there is none (404).+ *+ * A browser that already holds the picture sends the name it was given+ * (`ifNoneMatch`). The account is checked first, as always, and then the+ * answer is "your copy is still good" without a read from file storage.+ */export async function getEnvelopeThumbnailForUser(userId: string,envelopeId: string,{database = getDb(),+ ifNoneMatch,storageService = createStorageService(),}: {database?: DbExecutor;+ ifNoneMatch?: string | null;storageService?: StorageService;} = {},-): Promise<StorageObjectStream> {+): Promise<EnvelopeThumbnail> {const envelope = await getEnvelopeByIdForUser(userId, envelopeId, database);if (!envelope) {throw new EnvelopeDocumentAccessError("Envelope not found.", 404);}+ const etag = buildThumbnailEtag(envelope.id);++ if (matchesEtag(ifNoneMatch, etag)) {+ return { etag, isNotModified: true };+ }+try {- return await storageService.getObjectStream(+ const picture = await storageService.getObjectStream(buildEnvelopeThumbnailKey({envelopeId: envelope.id,sourcePdfKey: envelope.sourcePdfKey,userId,}),);++ return { etag, isNotModified: false, picture };} catch (error) {if (error instanceof StorageObjectNotFoundError) {throw new EnvelopeDocumentAccessError(diff --git a/src/lib/services/thumbnails.test.ts b/src/lib/services/thumbnails.test.tsindex ae36f64..c0d32eb 100644--- a/src/lib/services/thumbnails.test.ts+++ b/src/lib/services/thumbnails.test.ts@@ -3,6 +3,8 @@ import { test } from "node:test";import {assertThumbnailImage,+ buildThumbnailEtag,+ matchesEtag,readJpegDimensions,THUMBNAIL_MAX_BYTES,THUMBNAIL_MAX_DIMENSION,@@ -178,3 +180,34 @@ test("refuses a thumbnail whose picture is too large or too small", () => {ThumbnailValidationError,);});++test("a thumbnail's name is the same every time, and its own", () => {+ const etag = buildThumbnailEtag("6f1c2d0e-0000-4000-8000-000000000001");++ assert.equal(+ etag,+ buildThumbnailEtag("6f1c2d0e-0000-4000-8000-000000000001"),+ );+ assert.notEqual(+ etag,+ buildThumbnailEtag("6f1c2d0e-0000-4000-8000-000000000002"),+ );+ // An ETag is a quoted string.+ assert.match(etag, /^"[^"]+"$/);+});++test("a name the browser quotes back is recognized", () => {+ const etag = buildThumbnailEtag("6f1c2d0e-0000-4000-8000-000000000001");+ const other = buildThumbnailEtag("6f1c2d0e-0000-4000-8000-000000000002");++ assert.equal(matchesEtag(etag, etag), true);+ assert.equal(matchesEtag(`W/${etag}`, etag), true);+ assert.equal(matchesEtag(`${other}, ${etag}`, etag), true);+ assert.equal(matchesEtag("*", etag), true);++ assert.equal(matchesEtag(other, etag), false);+ assert.equal(matchesEtag(etag.replaceAll('"', ""), etag), false);+ assert.equal(matchesEtag("", etag), false);+ assert.equal(matchesEtag(null, etag), false);+ assert.equal(matchesEtag(undefined, etag), false);+});diff --git a/src/lib/services/thumbnails.ts b/src/lib/services/thumbnails.tsindex 4e62406..dec0b00 100644--- a/src/lib/services/thumbnails.ts+++ b/src/lib/services/thumbnails.ts@@ -10,6 +10,38 @@ export const THUMBNAIL_MAX_BYTES = 256 * 1024;export const THUMBNAIL_MAX_DIMENSION = 1200;const THUMBNAIL_MIN_DIMENSION = 16;+/**+ * The name a browser quotes back to ask whether its copy of a thumbnail is+ * still good (an ETag).+ *+ * A document never changes once it is uploaded, so neither does the picture+ * of its first page, and the name is made from the envelope alone. That lets+ * "your copy is still good" be answered without reading the picture from+ * file storage, where every read counts against the store's allowance. The+ * version is here to be raised if thumbnails are ever drawn differently.+ */+export function buildThumbnailEtag(envelopeId: string): string {+ return `"thumbnail-v1-${envelopeId}"`;+}++/** Whether an If-None-Match header names this ETag. */+export function matchesEtag(+ ifNoneMatch: string | null | undefined,+ etag: string,+): boolean {+ if (!ifNoneMatch) {+ return false;+ }++ return ifNoneMatch.split(",").some((candidate) => {+ const name = candidate.trim();++ // A cache in between may have marked the name as weak. For "do I+ // already have this?" the two forms mean the same.+ return name === "*" || name.replace(/^W\//, "") === etag;+ });+}+export class ThumbnailValidationError extends Error {constructor(message: string) {super(message);