The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Workers: an account's picture goes to a worker as the picture alone
Adarsh77f0832d0dea
diff --git a/docs/gpu-workers.md b/docs/gpu-workers.mdindex 520ef866..db63c656 100644--- a/docs/gpu-workers.md+++ b/docs/gpu-workers.md@@ -539,10 +539,12 @@ starts a job that its ComfyUI did not have last, it clears its ComfyUI the sameThe owner's pictures for workers are made again from their pixels on the studio (no EXIF, no GPS). An account'spictures go to the worker without being decoded, and the worker makes each one again from its pixels before its-ComfyUI or a finishing job reads it (see "Pictures of an account's run"). Before they leave, the studio blanks what-they carry besides their pixels, in place: EXIF and GPS, XMP, comments and text chunks. A JPEG keeps only its-orientation. A kind of picture that the studio can't blank that way (a GIF, say) is made again from its pixels on the-studio instead. Clips and sound go to workers only when `FUOBE_POOL_MEDIA_INPUTS` allows them (`image` by default;+ComfyUI or a finishing job reads it (see "Pictures of an account's run"). Before they leave, the studio sends only the+picture itself: it blanks what a picture carries besides its pixels, in place (EXIF and GPS, XMP, comments,+thumbnails, a JPEG's other application segments before and between its scans, every PNG chunk but its pixels' and+colours', a WebP's EXIF and XMP), and cuts off anything after the picture's end (a second picture, a phone's+motion-photo clip and its sound). A JPEG keeps only its orientation. A kind of picture that the studio can't clean+that way (a GIF, an SVG, an animated WebP, say) is made again from its pixels on the studio instead. Clips and sound go to workers only when `FUOBE_POOL_MEDIA_INPUTS` allows them (`image` by default;`image,video,audio` for all); an account's run with a kind it doesn't allow is refused before it is queued. The workerthen makes each one again before its ComfyUI reads it (see "Clips and sound"). Every VideoHelperSuite save node of agraph for the workers is sent with `save_metadata` off, so no prompt rides inside a result. An account's run is shapeddiff --git a/src/server/computer/finish.ts b/src/server/computer/finish.tsindex 8ce4185c..94bbe66a 100644--- a/src/server/computer/finish.ts+++ b/src/server/computer/finish.ts@@ -98,7 +98,7 @@ export function queueFinish(o: {const was = queued();if (was) return was;const inputs = o.inputs.map((i) => {- const data = i.contentType.startsWith("image/") ? pictureWithoutMetadata(i.data, i.contentType) : i.data;+ const data = i.contentType.startsWith("image/") ? pictureWithoutMetadata(i.data) : i.data;if (!data) throw new Error("This run couldn't finish.");const name = stageInput(principal, data, i.contentType, i.name);return { slot: i.slot, name, sha256: stagedInput(principal, name)!.sha256 };@@ -424,7 +424,7 @@ export async function pathOnWorker(generationId: string, step: number, input: {* of picture (a GIF, say) made again from its pixels here, upright, as a PNG. Throws when it isn't a picture.*/async function finishPicture<T extends { data: Buffer; contentType: string; name: string }>(f: T): Promise<T> {- if (!f.contentType.startsWith("image/") || pictureWithoutMetadata(f.data, f.contentType)) return f;+ if (!f.contentType.startsWith("image/") || pictureWithoutMetadata(f.data)) return f;const sharp = (await import("sharp")).default;const png = await sharp(f.data, { failOn: "error", limitInputPixels: 64 * 2 ** 20 }).rotate().png().toBuffer();return { ...f, data: png, contentType: "image/png", name: "picture.png" };diff --git a/src/server/media-clean.ts b/src/server/media-clean.tsindex 4c926c0a..c40cae78 100644--- a/src/server/media-clean.ts+++ b/src/server/media-clean.ts@@ -588,25 +588,143 @@ function tiffOrientation(exif: Buffer): number | null {return null;}+/** The PNG chunks a picture sent on keeps: its pixels and how its colours show. Every other chunk is blanked. */+const PNG_PICTURE = new Set(["IHDR", "PLTE", "IDAT", "IEND", "tRNS", "gAMA", "cHRM", "sRGB", "iCCP", "sBIT", "pHYs", "bKGD"]);++/** A picture sent on: the patches that blank what it carries besides its pixels, and where the picture ends. */+type Picture = { patches: Patch[]; end: number };++/**+ * A PNG sent on: every chunk outside PNG_PICTURE becomes a private chunk decoders skip ("fuPd"), zeroed, with a fresh+ * CRC. It ends after IEND (anything after it is cut off). A critical chunk the list doesn't know can't be skipped by a+ * decoder, so such a PNG is unreadable here.+ */+function pngPicture(b: Buffer): Picture {+ const out: Patch[] = [];+ const NAME = Buffer.from("fuPd");+ let at = 8;+ for (;;) {+ need(at + 12 <= b.length);+ const len = b.readUInt32BE(at);+ const type = b.toString("latin1", at + 4, at + 8);+ need(/^[A-Za-z]{4}$/.test(type) && at + 12 + len <= b.length);+ if (!PNG_PICTURE.has(type)) {+ need((b[at + 4] & 0x20) !== 0);+ out.push({ at: at + 4, bytes: NAME }, zeros(at + 8, len), { at: at + 8 + len, bytes: u32be(crc32([NAME, len])) });+ }+ at += 12 + len;+ if (type === "IEND") return { patches: out, end: at };+ }+}++/** The JPEG markers of a picture's own structure: its frame, tables, scans and restart interval. */+const JPEG_STRUCTURE = new Set([0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf]);+/**- * A picture with what it carries besides its pixels blanked, as the share files are (the same patches): a JPEG's EXIF,- * XMP, comments and other application segments, a PNG's text and EXIF chunks, a WebP's EXIF and XMP, an SVG's- * metadata. Nothing is decoded, and the size and every offset stay. A JPEG keeps its EXIF orientation (alone in its EXIF- * segment), so it shows the way it did. The same bytes back when there was nothing to blank; null for any other kind of- * picture (a GIF, say: it is made again from its pixels instead), or one that can't be read where such data lives.+ * A segment a JPEG sent on keeps besides its structure: JFIF with no thumbnail of its own, an ICC profile, and Adobe's+ * colour transform. Every other application segment (EXIF, XMP, a multi-picture index, maker notes) and every comment is+ * blanked.*/-export function pictureWithoutMetadata(data: Buffer, contentType = ""): Buffer | null {+function jpegKeeps(marker: number, body: Buffer): boolean {+ if (marker === 0xe0) return body.length === 14 && body.toString("latin1", 0, 5) === "JFIF\0" && body[12] === 0 && body[13] === 0;+ if (marker === 0xe2) return body.toString("latin1", 0, 12) === "ICC_PROFILE\0";+ if (marker === 0xee) return body.length === 12 && body.toString("latin1", 0, 5) === "Adobe";+ return false;+}++/** Where a scan's coded data ends: at the next marker (an 0xFF followed by neither 0x00, a restart marker nor 0xFF). */+function scanEnd(b: Buffer, from: number): number {+ let at = from;+ for (;;) {+ at = b.indexOf(0xff, at);+ need(at >= 0 && at + 1 < b.length);+ const next = b[at + 1];+ if (next === 0x00 || (next >= 0xd0 && next <= 0xd7)) at += 2;+ else if (next === 0xff) at += 1;+ else return at;+ }+}++/**+ * A JPEG sent on: every segment outside its structure and jpegKeeps becomes a zeroed comment, before its first scan and+ * between its scans alike (a progressive JPEG has several), and it ends at its end marker (anything after it, such as a+ * second picture with its own EXIF or a phone's motion-photo clip, is cut off). A marker it doesn't know, or a picture+ * with no end, is unreadable here.+ */+function jpegPicture(b: Buffer): Picture {+ const out: Patch[] = [];+ let at = 2;+ for (;;) {+ need(at + 2 <= b.length && b[at] === 0xff);+ const m = b[at + 1];+ if (m === 0xff) {+ at += 1; // fill byte+ continue;+ }+ if (m === 0xd9) return { patches: out, end: at + 2 };+ if (m === 0x01 || (m >= 0xd0 && m <= 0xd7)) {+ at += 2;+ continue;+ }+ need(at + 4 <= b.length);+ const len = b.readUInt16BE(at + 2);+ need(len >= 2 && at + 2 + len <= b.length);+ if ((m >= 0xe0 && m <= 0xef) || m === 0xfe) {+ if (!jpegKeeps(m, b.subarray(at + 4, at + 2 + len))) out.push({ at: at + 1, bytes: Buffer.from([0xfe]) }, zeros(at + 4, len - 2));+ } else need(JPEG_STRUCTURE.has(m));+ at += 2 + len;+ if (m === 0xda) at = scanEnd(b, at);+ }+}++/** The WebP chunks a picture sent on keeps: a still's pixels, its alpha, its extended header and its colour profile. */+const WEBP_PICTURE = new Set(["VP8 ", "VP8L", "VP8X", "ALPH", "ICCP"]);++/**+ * A WebP sent on: every chunk outside WEBP_PICTURE becomes JUNK, zeroed, and VP8X stops announcing EXIF and XMP. It ends+ * where its RIFF size says (anything after it is cut off). An animated WebP is unreadable here (its frames would carry+ * chunks of their own).+ */+function webpPicture(b: Buffer): Picture {+ const out: Patch[] = [];+ need(b.length >= 20);+ const declared = b.readUInt32LE(4);+ need(declared >= 12);+ const end = Math.min(b.length, 8 + declared);+ let at = 12;+ while (at < end) {+ need(at + 8 <= end);+ const id = b.toString("latin1", at, at + 4);+ const len = b.readUInt32LE(at + 4);+ need(at + 8 + len <= end && id !== "ANIM" && id !== "ANMF");+ if (!WEBP_PICTURE.has(id)) out.push({ at, bytes: Buffer.from("JUNK") }, zeros(at + 8, len));+ if (id === "VP8X" && len >= 1 && b[at + 8] & 0x0c) out.push({ at: at + 8, bytes: Buffer.from([b[at + 8] & ~0x0c]) });+ at += 8 + len + (len & 1);+ }+ return { patches: out, end };+}++/**+ * A picture to send on to another machine (a worker), with only its image in it: a PNG, a JPEG or a still WebP, its+ * pixels' data kept as it is (nothing is decoded) and everything else blanked in place: a JPEG's EXIF and GPS, XMP,+ * comments, thumbnails and other application segments (between a progressive JPEG's scans too), a PNG's text, EXIF,+ * timestamp and provenance chunks (any chunk but its pixels' and colours'), a WebP's EXIF and XMP. Anything after the+ * picture's end (a second picture with its own EXIF, a phone's motion-photo clip and its sound) is cut off. A JPEG keeps+ * its EXIF orientation (alone in its EXIF segment), so it shows the way it did. The same bytes back when there was+ * nothing to blank or cut. Null for any other kind of picture (a GIF, an SVG, an animated WebP: it is made again from+ * its pixels instead), or one that can't be read to its end.+ */+export function pictureWithoutMetadata(data: Buffer): Buffer | null {try {- const r = new Reader(data, data.length);- const head = r.read(0, 16);- const at = (s: string, i = 0) => head.toString("latin1", i, i + s.length) === s;- let patches: Patch[] = [];- if (head.length >= 8 && head.readUInt32BE(0) === 0x89504e47) patches = png(r);- else if (head[0] === 0xff && head[1] === 0xd8) patches = [...jpeg(r), ...keepOrientation(r)];- else if (at("RIFF") && at("WEBP", 8)) patches = riff(r, true);- else if (contentType.split(";")[0].trim().toLowerCase() === "image/svg+xml") patches = svg(r);+ let pic: Picture;+ if (data.length >= 8 && data.readUInt32BE(0) === 0x89504e47 && data.readUInt32BE(4) === 0x0d0a1a0a) pic = pngPicture(data);+ else if (data.length >= 4 && data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) {+ pic = jpegPicture(data);+ pic.patches.push(...keepOrientation(new Reader(data, pic.end)));+ } else if (data.length >= 12 && data.toString("latin1", 0, 4) === "RIFF" && data.toString("latin1", 8, 12) === "WEBP") pic = webpPicture(data);else return null;- return patches.length ? overlay(data, 0, patches) : data;+ const out = pic.patches.length ? overlay(data, 0, pic.patches) : data;+ return pic.end < data.length ? out.subarray(0, pic.end) : out;} catch (e) {if (e instanceof Unreadable || e instanceof RangeError) return null;throw e;diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex e799b01d..ebfb8fe4 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -215,9 +215,10 @@ export const workersTake = (kind: "image" | "video" | "audio"): boolean => poolM/*** A file for a job on the workers: refused when they don't take its kind. A picture is made again from its pixels here* (no EXIF, no GPS), unless `o.onWorker`: then the worker makes it again itself before its ComfyUI reads it, and this- * server only checks that it is a picture it can size, and blanks what it carries besides its pixels (EXIF and GPS,- * XMP, comments, text) without decoding it: none of that ever leaves for a worker. A JPEG keeps its orientation. A- * kind of picture whose such parts this server can't blank that way (a GIF, say) is made again from its pixels here.+ * server only checks that it is a picture it can size, blanks what it carries besides its pixels (EXIF and GPS, XMP,+ * comments, thumbnails, text) without decoding it, and cuts off anything after the picture's end (a second picture, a+ * motion photo's clip): none of that ever leaves for a worker. A JPEG keeps its orientation. A kind of picture whose+ * such parts this server can't blank that way (a GIF, an SVG, an animated WebP, say) is made again from its pixels here.*/export async function forWorkers(data: Buffer, contentType: string, name: string, o: { onWorker?: boolean } = {}): Promise<{ data: Buffer; contentType: string; name: string }> {const kind = contentType.split("/")[0];@@ -226,7 +227,7 @@ export async function forWorkers(data: Buffer, contentType: string, name: stringconst refused = () => new ProviderError("The shared GPUs don't take this kind of file.");if (o.onWorker) {if (!imageSize(data)) throw refused();- const clean = pictureWithoutMetadata(data, contentType);+ const clean = pictureWithoutMetadata(data);if (clean) return { data: clean, contentType, name };}const sharp = (await import("sharp")).default;diff --git a/tests/cpu-slot.test.ts b/tests/cpu-slot.test.tsindex d13a0d34..ec9cc043 100644--- a/tests/cpu-slot.test.ts+++ b/tests/cpu-slot.test.ts@@ -645,7 +645,7 @@ describe("an account's pictures leave for a worker without what they carry besid.withMetadata({ orientation: 6 }).withExif({ IFD0: { Artist: "someone private", Copyright: "a home address" } }).toBuffer();- const clean = pictureWithoutMetadata(jpeg, "image/jpeg")!;+ const clean = pictureWithoutMetadata(jpeg)!;expect(clean.length).toBe(jpeg.length);expect(clean.includes(Buffer.from("someone private"))).toBe(false);expect(clean.includes(Buffer.from("a home address"))).toBe(false);@@ -656,20 +656,20 @@ describe("an account's pictures leave for a worker without what they carry besidexpect([meta.width, meta.height]).toEqual([40, 20]);// Upright already: nothing of its EXIF stays.const upright = await sharp({ create: { width: 40, height: 20, channels: 3, background: "#c33" } }).jpeg().withExif({ IFD0: { Artist: "someone private" } }).toBuffer();- const plain = pictureWithoutMetadata(upright, "image/jpeg")!;+ const plain = pictureWithoutMetadata(upright)!;expect(plain.includes(Buffer.from("someone private"))).toBe(false);expect((await sharp(plain).metadata()).exif).toBeUndefined();const png = await pngWithText("a private note");expect((await sharp(png).metadata()).width).toBe(8);- const cleanPng = pictureWithoutMetadata(png, "image/png")!;+ const cleanPng = pictureWithoutMetadata(png)!;expect(cleanPng.includes(Buffer.from("a private note"))).toBe(false);expect((await sharp(cleanPng).metadata()).width).toBe(8);const webp = await sharp({ create: { width: 8, height: 6, channels: 3, background: "#123" } }).webp().withExif({ IFD0: { Artist: "someone private" } }).toBuffer();- const cleanWebp = pictureWithoutMetadata(webp, "image/webp")!;+ const cleanWebp = pictureWithoutMetadata(webp)!;expect(cleanWebp.includes(Buffer.from("someone private"))).toBe(false);expect((await sharp(cleanWebp).metadata()).width).toBe(8);// Not a picture it can read where such things live: refused.- expect(pictureWithoutMetadata(Buffer.from([0xff, 0xd8, 0xff, 0xe1, 0xff, 0xff, 0x00]), "image/jpeg")).toBeNull();+ expect(pictureWithoutMetadata(Buffer.from([0xff, 0xd8, 0xff, 0xe1, 0xff, 0xff, 0x00]))).toBeNull();});it("an account's run on the workers stages its picture that way, sized as it shows; its own GPU gets it as it came, sized by its pixels", async () => {@@ -709,6 +709,17 @@ describe("an account's pictures leave for a worker without what they carry besidexpect(staged.some((b) => b.includes(Buffer.from("someone private")))).toBe(false);expect(staged[0].length).toBe(photo.length);});++ it("a camera path's photo with a second picture and a motion photo's clip after it goes as the first picture only", async () => {+ const sharp = (await import("sharp")).default;+ const photo = await sharp({ create: { width: 16, height: 12, channels: 3, background: "#36c" } }).jpeg().toBuffer();+ const second = await sharp({ create: { width: 4, height: 4, channels: 3, background: "#000" } }).jpeg().withExif({ IFD0: { Artist: "GPS 48.85837 N" } }).toBuffer();+ const clip = Buffer.from("....ftypmp42 MOTION PHOTO VIDEO AND SOUND", "latin1");+ const { id } = pathFinish(Buffer.concat([photo, second, clip]));+ const staged = tasks.inputsOf(id).map((i) => fs.readFileSync(path.join(dir, "relay", "in", i.name)));+ expect(staged[0].equals(photo)).toBe(true);+ expect(staged.some((b) => b.includes(Buffer.from("GPS 48.85837")) || b.includes(Buffer.from("MOTION PHOTO")))).toBe(false);+ });});// ---------------------------------------------------------------------------@@ -805,7 +816,7 @@ describe("pictures for a worker that this server can't blank in place", () => {const sharp = (await import("sharp")).default;const gif = await gifWithComment("a private note");expect((await sharp(gif).metadata()).width).toBe(8);- expect(pictureWithoutMetadata(gif, "image/gif")).toBeNull();+ expect(pictureWithoutMetadata(gif)).toBeNull();const route = { provider: "comfyui", endpoint: "selftest-image", op: "edit" } as never;const pooled = await hosted.runOnPool(accountId, async () => {const name = (await comfyProvider.prepareFile!(gif, "image/gif", "me.gif", route))!;diff --git a/tests/media-clean.test.ts b/tests/media-clean.test.tsindex 1e004200..48699f75 100644--- a/tests/media-clean.test.ts+++ b/tests/media-clean.test.ts@@ -3,7 +3,7 @@ import path from "node:path";import { Readable } from "node:stream";import zlib from "node:zlib";import { describe, expect, it } from "vitest";-import { metadataPatches, overlay, patchStream, type Patch } from "@/server/media-clean";+import { metadataPatches, overlay, patchStream, pictureWithoutMetadata, type Patch } from "@/server/media-clean";import { tempDir } from "./helpers/temp-dir";/**@@ -332,3 +332,119 @@ describe("media metadata", () => {expect(data.toString()).toBe("0123456789abcdefghij"); // the stored bytes aren't touched});});++// ---------------------------------------------------------------------------+// Pictures sent on to a worker: only the picture itself goes++describe("a picture sent on to a worker keeps only its image", () => {+ const GPS = "GPS 48.85837 N 2.29448 E";+ const seg = (m: number, data: Buffer) => Buffer.concat([Buffer.from([0xff, m]), u16be(data.length + 2), data]);+ const exifWith = (text: string) => seg(0xe1, Buffer.from(`Exif\0\0MM\0*\0\0\0\x08${text}`, "latin1"));+ /** A clip a phone puts after its photo (a motion photo): its own boxes, with sound. */+ const motionClip = Buffer.concat([box("ftyp", Buffer.from("mp42isom")), box("mdat", Buffer.from("MOTION PHOTO VIDEO AND SOUND"))]);+ const has = (b: Buffer, s: string) => b.includes(Buffer.from(s, "latin1"));++ async function jpeg(o: { progressive?: boolean } = {}) {+ const sharp = (await import("sharp")).default;+ return sharp({ create: { width: 24, height: 16, channels: 3, background: "#4a6" } })+ .jpeg({ progressive: !!o.progressive })+ .toBuffer();+ }+ async function decodes(b: Buffer) {+ const sharp = (await import("sharp")).default;+ const m = await sharp(b, { failOn: "error" }).metadata();+ return [m.width, m.height];+ }++ it("a JPEG followed by a second picture with its own EXIF and GPS, and a motion photo's clip: both are cut off", async () => {+ const first = await jpeg();+ const second = Buffer.concat([Buffer.from([0xff, 0xd8]), exifWith(GPS), (await jpeg()).subarray(2)]);+ const sent = Buffer.concat([first, second, motionClip]);+ const out = pictureWithoutMetadata(sent)!;+ expect(out).not.toBeNull();+ expect(has(out, GPS)).toBe(false);+ expect(has(out, "ftyp")).toBe(false);+ expect(has(out, "MOTION PHOTO")).toBe(false);+ expect(out.equals(first)).toBe(true);+ expect(await decodes(out)).toEqual([24, 16]);+ });++ it("a progressive JPEG: EXIF, GPS and comments between its scans are blanked too, and it still decodes", async () => {+ const src = await jpeg({ progressive: true });+ // Its second scan: the second start-of-scan marker (coded data never holds 0xFF 0xDA).+ const scans: number[] = [];+ for (let at = src.indexOf(Buffer.from([0xff, 0xda])); at >= 0; at = src.indexOf(Buffer.from([0xff, 0xda]), at + 2)) scans.push(at);+ expect(scans.length).toBeGreaterThan(1);+ const sent = Buffer.concat([src.subarray(0, scans[1]), exifWith(GPS), seg(0xfe, Buffer.from(SECRET)), seg(0xe2, Buffer.from(`MPF\0${SECRET}`, "latin1")), src.subarray(scans[1])]);+ const out = pictureWithoutMetadata(sent)!;+ expect(has(out, GPS)).toBe(false);+ expect(has(out, "SECRET")).toBe(false);+ expect(out.length).toBe(sent.length);+ expect(await decodes(out)).toEqual([24, 16]);+ });++ it("a JPEG's JFIF thumbnail and other application segments go; JFIF without one, an ICC profile and Adobe's stay", async () => {+ const thumb = Buffer.concat([Buffer.from("JFIF\0\x01\x02\0\0\x01\0\x01\x01\x01", "latin1"), Buffer.from(SECRET.slice(0, 3), "latin1")]);+ const src = await jpeg();+ const sent = Buffer.concat([Buffer.from([0xff, 0xd8]), seg(0xe0, thumb), seg(0xe2, Buffer.from("ICC_PROFILE\0\x01\x01profile", "latin1")), seg(0xee, Buffer.from("Adobe\0\x64\0\0\0\0\x01", "latin1")), seg(0xed, Buffer.from(`Photoshop 3.0\0${SECRET}`, "latin1")), src.subarray(2)]);+ const out = pictureWithoutMetadata(sent)!;+ expect(has(out, "SECRET")).toBe(false);+ expect(has(out, SECRET.slice(0, 3))).toBe(false);+ expect(has(out, "ICC_PROFILE")).toBe(true);+ expect(has(out, "Adobe")).toBe(true);+ expect(await decodes(out)).toEqual([24, 16]);+ });++ it("a PNG keeps only its pixels' and colours' chunks: a provenance (caBX) and a timestamp chunk go, and so does anything after its end", async () => {+ const sharp = (await import("sharp")).default;+ const src = await sharp({ create: { width: 8, height: 6, channels: 3, background: "#123" } }).png().toBuffer();+ const iend = src.length - 12;+ expect(src.toString("latin1", iend + 4, iend + 8)).toBe("IEND");+ const sent = Buffer.concat([+ src.subarray(0, iend),+ pngChunk("caBX", Buffer.from(`c2pa manifest ${SECRET}`, "latin1")),+ pngChunk("tIME", Buffer.from([0x07, 0xea, 11, 5, 9, 30, 0])),+ pngChunk("gAMA", u32be(45455)),+ src.subarray(iend),+ Buffer.from(`trailing ${GPS}`, "latin1"),+ motionClip,+ ]);+ const out = pictureWithoutMetadata(sent)!;+ expect(has(out, "SECRET")).toBe(false);+ expect(has(out, GPS)).toBe(false);+ expect(has(out, "MOTION PHOTO")).toBe(false);+ const chunks = pngChunks(out);+ expect(chunks.every((c) => c.crcOk)).toBe(true);+ expect(chunks.map((c) => c.type)).not.toContain("caBX");+ expect(chunks.map((c) => c.type)).not.toContain("tIME");+ expect(chunks.map((c) => c.type)).toContain("gAMA");+ expect(chunks.at(-1)?.type).toBe("IEND");+ expect(await decodes(out)).toEqual([8, 6]);+ });++ it("a WebP is cut where its RIFF size ends, and a chunk outside its picture becomes JUNK", async () => {+ const sharp = (await import("sharp")).default;+ const src = await sharp({ create: { width: 8, height: 6, channels: 3, background: "#123" } }).webp().withExif({ IFD0: { Artist: SECRET } }).toBuffer();+ const extra = Buffer.concat([Buffer.from("C2PA", "latin1"), Buffer.from([8, 0, 0, 0]), Buffer.from("SECRET!!")]);+ const body = Buffer.concat([src.subarray(12), extra]);+ const riff = Buffer.concat([Buffer.from("RIFF"), Buffer.from([0, 0, 0, 0]), Buffer.from("WEBP"), body]);+ riff.writeUInt32LE(4 + body.length, 4);+ const out = pictureWithoutMetadata(Buffer.concat([riff, motionClip]))!;+ expect(out.length).toBe(riff.length);+ expect(has(out, "SECRET")).toBe(false);+ expect(has(out, "MOTION PHOTO")).toBe(false);+ expect(await decodes(out)).toEqual([8, 6]);+ });++ it("is made again from its pixels instead (null) when it is another kind, has a chunk no decoder may skip, or has no end", async () => {+ expect(pictureWithoutMetadata(Buffer.from("GIF89a\x01\0\x01\0\0\0\0;", "latin1"))).toBeNull();+ expect(pictureWithoutMetadata(Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg"><metadata>${SECRET}</metadata></svg>`))).toBeNull();+ const sharp = (await import("sharp")).default;+ const png = await sharp({ create: { width: 2, height: 2, channels: 3, background: "#000" } }).png().toBuffer();+ expect(pictureWithoutMetadata(Buffer.concat([png.subarray(0, 33), pngChunk("CgBI", Buffer.from(SECRET)), png.subarray(33)]))).toBeNull();+ const cut = await jpeg();+ expect(pictureWithoutMetadata(cut.subarray(0, cut.length - 2))).toBeNull();+ const animated = Buffer.concat([Buffer.from("RIFF"), u32le(4 + 8 + 4), Buffer.from("WEBPANIM"), u32le(4), Buffer.alloc(4)]);+ expect(pictureWithoutMetadata(animated)).toBeNull();+ });+});diff --git a/tests/worker-tickets.test.ts b/tests/worker-tickets.test.tsindex 17d49910..44466084 100644--- a/tests/worker-tickets.test.ts+++ b/tests/worker-tickets.test.ts@@ -784,3 +784,62 @@ describe("setup saves the PC's ceiling", () => {expect(parseGpuGen("300, 45")).toBeNull();});});++describe("an account's picture is staged for the worker with only its image in it", () => {+ const GPS = "GPS 48.85837 N 2.29448 E";+ const u16 = (n: number) => Buffer.from([n >> 8, n & 0xff]);+ const exifWith = (text: string) => {+ const body = Buffer.from(`Exif\0\0MM\0*\0\0\0\x08${text}`, "latin1");+ return Buffer.concat([Buffer.from([0xff, 0xe1]), u16(body.length + 2), body]);+ };+ const boxOf = (type: string, body: Buffer) => {+ const head = Buffer.alloc(8);+ head.writeUInt32BE(8 + body.length);+ head.write(type, 4, "latin1");+ return Buffer.concat([head, body]);+ };+ /** What a phone puts after its photo (a motion photo): a clip with sound. */+ const motionClip = Buffer.concat([boxOf("ftyp", Buffer.from("mp42isom")), boxOf("mdat", Buffer.from("MOTION PHOTO VIDEO AND SOUND"))]);+ const pngChunk = (type: string, data: Buffer) => {+ const len = Buffer.alloc(4);+ len.writeUInt32BE(data.length);+ const crc = Buffer.alloc(4);+ crc.writeUInt32BE(zlibCrc(Buffer.concat([Buffer.from(type, "latin1"), data])));+ return Buffer.concat([len, Buffer.from(type, "latin1"), data, crc]);+ };+ let zlibCrc: (b: Buffer) => number;+ const route = { provider: "comfyui", endpoint: "selftest-image", op: "edit" } as never;+ const staged = async (data: Buffer, contentType: string, name: string) => {+ const file = await hosted.runOnPool(accountId, async () => (await comfyProvider.prepareFile!(data, contentType, name, route))!);+ return fs.readFileSync(path.join(dir, "relay", "in", file));+ };+ const has = (b: Buffer, s: string) => b.includes(Buffer.from(s, "latin1"));++ beforeAll(async () => {+ zlibCrc = (await import("node:zlib")).crc32;+ });++ it("a JPEG followed by a second picture with its own EXIF and GPS, and a motion photo's clip, stages the first picture only", async () => {+ const sharp = (await import("sharp")).default;+ const first = await sharp({ create: { width: 24, height: 16, channels: 3, background: "#4a6" } }).jpeg().toBuffer();+ const second = Buffer.concat([Buffer.from([0xff, 0xd8]), exifWith(GPS), first.subarray(2)]);+ const got = await staged(Buffer.concat([first, second, motionClip]), "image/jpeg", "phone.jpg");+ expect(has(got, GPS)).toBe(false);+ expect(has(got, "ftyp")).toBe(false);+ expect(has(got, "MOTION PHOTO")).toBe(false);+ expect(got.equals(first)).toBe(true);+ });++ it("a PNG with a provenance (caBX) chunk and data after its last chunk stages none of them", async () => {+ const sharp = (await import("sharp")).default;+ const src = await sharp({ create: { width: 8, height: 6, channels: 3, background: "#123" } }).png().toBuffer();+ const iend = src.length - 12;+ const sent = Buffer.concat([src.subarray(0, iend), pngChunk("caBX", Buffer.from("c2pa manifest: someone private", "latin1")), src.subarray(iend), Buffer.from(`trailing ${GPS}`, "latin1"), motionClip]);+ const got = await staged(sent, "image/png", "shot.png");+ expect(has(got, "someone private")).toBe(false);+ expect(has(got, "caBX")).toBe(false);+ expect(has(got, GPS)).toBe(false);+ expect(has(got, "MOTION PHOTO")).toBe(false);+ expect((await sharp(got).metadata()).width).toBe(8);+ });+});