Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Refuse a logo upload that is cut off or damaged
Himanshu Mahto6488ad55a4c0
diff --git a/src/lib/brand-logo.dbtest.ts b/src/lib/brand-logo.dbtest.tsindex dd8d046..25bb2a2 100644--- a/src/lib/brand-logo.dbtest.ts+++ b/src/lib/brand-logo.dbtest.ts@@ -1,5 +1,6 @@import assert from "node:assert/strict";import { after, before, test } from "node:test";+import { crc32 } from "node:zlib";import type pg from "pg";@@ -21,17 +22,26 @@ type SettingsSnapshot = Record<string, unknown> | null;let database: pg.Pool;let settingsBefore: SettingsSnapshot = null;+const ONE_PIXEL_PNG = Buffer.from(+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==",+ "base64",+);++// Adds a text chunk so each marker gives a different, still valid, PNG.function png(marker: number): Uint8Array {- return Uint8Array.from([- 0x89,- 0x50,- 0x4e,- 0x47,- 0x0d,- 0x0a,- 0x1a,- 0x0a,- marker,+ const typeAndData = Buffer.from(`tEXtmarker\0${marker}`, "latin1");+ const chunk = Buffer.alloc(typeAndData.length + 8);++ chunk.writeUInt32BE(typeAndData.length - 4, 0);+ typeAndData.copy(chunk, 4);+ chunk.writeUInt32BE(crc32(typeAndData), chunk.length - 4);++ const headerEnd = 8 + 25;++ return Buffer.concat([+ ONE_PIXEL_PNG.subarray(0, headerEnd),+ chunk,+ ONE_PIXEL_PNG.subarray(headerEnd),]);}@@ -139,6 +149,24 @@ test("what is not an image never reaches the database", async () => {assert.equal(await readBrandLogo(database), null);});+test("a cut-off image never replaces the logo there is", async () => {+ const version = await saveBrandLogo(png(6), database);+ const whole = png(7);++ for (const length of [8, 29, whole.length - 1]) {+ await assert.rejects(+ saveBrandLogo(whole.subarray(0, length), database),+ BrandLogoError,+ );+ }++ const stored = await readBrandLogo(database);++ assert.equal(stored?.version, version);+ assert.deepEqual([...stored.bytes], [...png(6)]);+ await removeBrandLogo(database);+});+test("the database itself refuses a color or a logo that is not one", async () => {await saveSettings({ organizationName: "Logo Test Org" }, database);diff --git a/src/lib/brand-logo.test.ts b/src/lib/brand-logo.test.tsindex 86a0204..07499ef 100644--- a/src/lib/brand-logo.test.ts+++ b/src/lib/brand-logo.test.ts@@ -14,6 +14,40 @@ const WEBP = [0x52, 0x49, 0x46, 0x46, 0x24, 0, 0, 0, 0x57, 0x45, 0x42, 0x50, 0x56, 0x50,];+// Real 1x1 images, checked to render in Chromium.+const WHOLE_PNG = Uint8Array.from(+ Buffer.from(+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==",+ "base64",+ ),+);+const WHOLE_JPEG = Uint8Array.from(+ Buffer.from(+ "/9j/4AAQSkZJRgABAQAASABIAAD/wAARCAABAAEDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQ" ++ "EAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEG" ++ "E1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISU" ++ "pTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKz" ++ "tLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAw" ++ "EBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEE" ++ "BSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5Ok" ++ "NERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOk" ++ "paanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9" ++ "sAQwAbGxsbGxsvGxsvQi8vL0JZQkJCQllwWVlZWVlwiHBwcHBwcIiIiIiIiIiIo6Ojo6Oj" ++ "vr6+vr7V1dXV1dXV1dXV/9sAQwEhIyM2MjZdMjJd35d8l9/f39/f39/f39/f39/f39/f39" ++ "/f39/f39/f39/f39/f39/f39/f39/f39/f39/f39/f/90ABAAB/9oADAMBAAIRAxEAPwCS" ++ "iiivQJP/2Q==",+ "base64",+ ),+);+const WHOLE_WEBP = Uint8Array.from(+ Buffer.from("UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA==", "base64"),+);+const WHOLE_IMAGES = [+ ["image/png", WHOLE_PNG],+ ["image/jpeg", WHOLE_JPEG],+ ["image/webp", WHOLE_WEBP],+] as const;+test("the kind of image is read from the bytes", () => {assert.equal(sniffLogoContentType(Uint8Array.from(PNG)), "image/png");assert.equal(sniffLogoContentType(Uint8Array.from(JPEG)), "image/jpeg");@@ -57,6 +91,36 @@ test("an empty or oversized upload is refused with a reason", () => {const largest = new Uint8Array(MAX_LOGO_BYTES);- largest.set(PNG);+ largest.set(WHOLE_PNG);assert.equal(checkLogoUpload(largest), "image/png");});++test("a whole image is taken as what it is", () => {+ for (const [contentType, bytes] of WHOLE_IMAGES) {+ assert.equal(checkLogoUpload(bytes), contentType);+ }+});++test("an image cut off anywhere is refused, though it starts right", () => {+ for (const [contentType, bytes] of WHOLE_IMAGES) {+ for (let length = 1; length < bytes.length; length += 1) {+ const cut = bytes.subarray(0, length);++ assert.throws(+ () => checkLogoUpload(cut),+ (error: unknown) =>+ error instanceof BrandLogoError && error.statusCode === 400,+ `${contentType} cut to ${length} bytes`,+ );+ }+ }+});++test("a PNG with a damaged byte is refused", () => {+ // Flip a byte inside IDAT so only the CRC can catch it.+ const damaged = Uint8Array.from(WHOLE_PNG);++ damaged[45] ^= 0xff;+ assert.equal(sniffLogoContentType(damaged), "image/png");+ assert.throws(() => checkLogoUpload(damaged), BrandLogoError);+});diff --git a/src/lib/brand-logo.ts b/src/lib/brand-logo.tsindex 835a1d6..264f210 100644--- a/src/lib/brand-logo.ts+++ b/src/lib/brand-logo.ts@@ -1,4 +1,5 @@import { createHash } from "node:crypto";+import { crc32 } from "node:zlib";import { MAX_LOGO_BYTES, type LogoContentType } from "./branding.ts";import { getDb, queryOne, type DbExecutor } from "./db/connection.ts";@@ -59,6 +60,215 @@ export function sniffLogoContentType(return null;}+function readUint32BE(bytes: Uint8Array, offset: number) {+ return (+ bytes[offset] * 0x1000000 ++ ((bytes[offset + 1] << 16) | (bytes[offset + 2] << 8) | bytes[offset + 3])+ );+}++function readUint32LE(bytes: Uint8Array, offset: number) {+ return (+ bytes[offset] |+ (bytes[offset + 1] << 8) |+ (bytes[offset + 2] << 16) |+ (bytes[offset + 3] * 0x1000000)+ );+}++function readUint16BE(bytes: Uint8Array, offset: number) {+ return (bytes[offset] << 8) | bytes[offset + 1];+}++function readUint16LE(bytes: Uint8Array, offset: number) {+ return bytes[offset] | (bytes[offset + 1] << 8);+}++function chunkType(bytes: Uint8Array, offset: number) {+ return String.fromCharCode(...bytes.subarray(offset, offset + 4));+}++function isCompletePng(bytes: Uint8Array): boolean {+ let offset = 8;+ let seenHeader = false;+ let seenData = false;++ while (offset + 12 <= bytes.length) {+ const length = readUint32BE(bytes, offset);+ const type = chunkType(bytes, offset + 4);+ const dataStart = offset + 8;+ const dataEnd = dataStart + length;++ if (dataEnd + 4 > bytes.length) {+ return false;+ }++ const expectedCrc = readUint32BE(bytes, dataEnd);++ if (crc32(bytes.subarray(offset + 4, dataEnd)) !== expectedCrc) {+ return false;+ }++ if (!seenHeader) {+ if (type !== "IHDR" || length !== 13) {+ return false;+ }++ const width = readUint32BE(bytes, dataStart);+ const height = readUint32BE(bytes, dataStart + 4);++ if (width === 0 || height === 0) {+ return false;+ }++ seenHeader = true;+ } else if (type === "IDAT") {+ seenData = true;+ } else if (type === "IEND") {+ return seenData;+ }++ offset = dataEnd + 4;+ }++ return false;+}++function isCompleteJpeg(bytes: Uint8Array): boolean {+ let offset = 2;+ let seenFrame = false;++ while (offset + 4 <= bytes.length) {+ if (bytes[offset] !== 0xff) {+ return false;+ }++ const marker = bytes[offset + 1];++ if (marker === 0xff) {+ offset += 1;+ continue;+ }++ // These markers have no length field, so just step over them.+ if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {+ offset += 2;+ continue;+ }++ if (marker === 0xd9) {+ return false;+ }++ const length = readUint16BE(bytes, offset + 2);+ const segmentEnd = offset + 2 + length;++ if (length < 2 || segmentEnd > bytes.length) {+ return false;+ }++ // Frame headers (C0-CF) hold the size; C4, C8 and CC aren't frames.+ if (+ marker >= 0xc0 &&+ marker <= 0xcf &&+ marker !== 0xc4 &&+ marker !== 0xc8 &&+ marker !== 0xcc+ ) {+ if (length < 8) {+ return false;+ }++ const height = readUint16BE(bytes, offset + 5);+ const width = readUint16BE(bytes, offset + 7);++ if (width === 0 || height === 0) {+ return false;+ }++ seenFrame = true;+ }++ // Image data starts here, so all that's left is to find the end marker.+ if (marker === 0xda) {+ if (!seenFrame) {+ return false;+ }++ for (let index = bytes.length - 2; index >= segmentEnd; index -= 1) {+ if (bytes[index] === 0xff && bytes[index + 1] === 0xd9) {+ return true;+ }+ }++ return false;+ }++ offset = segmentEnd;+ }++ return false;+}++function isCompleteWebp(bytes: Uint8Array): boolean {+ if (bytes.length < 12) {+ return false;+ }++ const riffEnd = 8 + readUint32LE(bytes, 4);++ if (riffEnd > bytes.length) {+ return false;+ }++ let offset = 12;+ let seenImage = false;++ while (offset + 8 <= riffEnd) {+ const type = chunkType(bytes, offset);+ const length = readUint32LE(bytes, offset + 4);+ const dataStart = offset + 8;+ const dataEnd = dataStart + length;++ if (dataEnd > riffEnd) {+ return false;+ }++ if (type === "VP8 ") {+ if (+ length < 10 ||+ !startsWith(bytes, [0x9d, 0x01, 0x2a], dataStart + 3) ||+ (readUint16LE(bytes, dataStart + 6) & 0x3fff) === 0 ||+ (readUint16LE(bytes, dataStart + 8) & 0x3fff) === 0+ ) {+ return false;+ }++ seenImage = true;+ } else if (type === "VP8L") {+ if (length < 5 || bytes[dataStart] !== 0x2f) {+ return false;+ }++ seenImage = true;+ } else if (type === "ANMF") {+ seenImage = true;+ }++ // Odd-sized chunks get one byte of padding.+ offset = dataEnd + (length % 2);+ }++ return seenImage && offset >= riffEnd;+}++const COMPLETE_CHECKS: Record<LogoContentType, (bytes: Uint8Array) => boolean> =+ {+ "image/jpeg": isCompleteJpeg,+ "image/png": isCompletePng,+ "image/webp": isCompleteWebp,+ };+/** Checks an upload and says what it is. Throws when it cannot be a logo. */export function checkLogoUpload(bytes: Uint8Array): LogoContentType {if (bytes.length === 0) {@@ -75,6 +285,13 @@ export function checkLogoUpload(bytes: Uint8Array): LogoContentType {throw new BrandLogoError("The logo must be a PNG, JPEG or WebP image.");}+ // A matching signature doesn't mean the rest of the file is there.+ if (!COMPLETE_CHECKS[contentType](bytes)) {+ throw new BrandLogoError(+ "This image is damaged or incomplete. Choose another file.",+ );+ }+return contentType;}