@fungi.computer/darkroom 0.11.10 → 0.11.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -0
- package/examples/standalone/README.md +52 -0
- package/examples/standalone/worker.ts +87 -0
- package/examples/standalone/wrangler.jsonc +26 -0
- package/package.json +8 -2
- package/src/app-media-contracts.ts +142 -0
- package/src/audio-providers/elevenlabs.ts +108 -0
- package/src/audio-reference-types.ts +47 -0
- package/src/audio-references.ts +107 -0
- package/src/browser-failure.ts +73 -0
- package/src/browser.ts +7 -0
- package/src/cloudflare/provider-reason.ts +89 -0
- package/src/cloudflare/provider.ts +405 -0
- package/src/cloudflare/r2-destination.ts +130 -0
- package/src/cloudflare/reference-images.ts +193 -0
- package/src/cloudflare.ts +38 -0
- package/src/cost-estimate.ts +129 -0
- package/src/daily-media-meter.ts +163 -0
- package/src/effect.ts +2 -0
- package/src/execution-error.ts +98 -0
- package/src/failure.ts +13 -0
- package/src/gateway-models.ts +304 -0
- package/src/gateway-wire.ts +36 -0
- package/src/index.ts +1454 -0
- package/src/media-binding.ts +260 -0
- package/src/media-content-type.ts +60 -0
- package/src/media-generation.ts +171 -0
- package/src/media-operation-contract.ts +173 -0
- package/src/media-operation-do.ts +257 -0
- package/src/media-operation-owner.ts +1786 -0
- package/src/media-operation-storage.ts +110 -0
- package/src/media-operation.ts +454 -0
- package/src/media-path.ts +8 -0
- package/src/media-quote.ts +34 -0
- package/src/media-run-lifetime.ts +5 -0
- package/src/media-written.ts +38 -0
- package/src/model-catalog.ts +1574 -0
- package/src/neurons.ts +6 -0
- package/src/node-webpmux.d.ts +12 -0
- package/src/provenance-bytes.ts +22 -0
- package/src/provenance-export.ts +126 -0
- package/src/provenance-jpeg.ts +83 -0
- package/src/provenance-png.ts +26 -0
- package/src/provenance-signed.ts +7 -0
- package/src/provenance-xmp.ts +57 -0
- package/src/provenance.ts +87 -0
- package/src/reference-image-size.ts +67 -0
- package/src/reference-read.ts +50 -0
- package/src/server.ts +711 -0
- package/src/video-providers/index.ts +18 -0
- package/src/video-providers/minimax.ts +96 -0
- package/src/video-providers/reference-encoding.ts +32 -0
- package/src/video-providers/types.ts +47 -0
- package/src/video-providers/unified.ts +68 -0
- package/test/audio-models.test.ts +428 -0
- package/test/audio-references.test.ts +428 -0
- package/test/custom-catalogue.test.ts +257 -0
- package/test/daily-media-meter.test.ts +287 -0
- package/test/failure.test.ts +190 -0
- package/test/fixtures/cloudflare-workers.fixture.ts +10 -0
- package/test/fixtures/media-operation.fixture.ts +134 -0
- package/test/fixtures/media-team-prompts.ts +7 -0
- package/test/fixtures/native-sqlite.fixture.ts +40 -0
- package/test/gateway-models.test.ts +712 -0
- package/test/media-operation-do.test.ts +1565 -0
- package/test/media-quote.test.ts +81 -0
- package/test/media-retention.test.ts +597 -0
- package/test/media-service.test.ts +549 -0
- package/test/media-team-prompts.test.ts +92 -0
- package/test/model-facts.test.ts +126 -0
- package/test/prompt-limit.test.ts +53 -0
- package/test/provenance-export.test.ts +144 -0
- package/test/provenance-images.fixture.mjs +17 -0
- package/test/provenance.test.ts +179 -0
- package/test/provider-gateway.test.ts +114 -0
- package/test/provider-reasons.test.ts +133 -0
- package/test/r2-destination.test.ts +166 -0
- package/test/reference-image-size.test.ts +73 -0
- package/test/reference-images-billing.test.ts +40 -0
- package/test/reference-images.test.ts +399 -0
- package/test/standalone.cloudflare.test.mjs +298 -0
- package/test/standalone.worker.mjs +70 -0
- package/test/transform-models.test.ts +400 -0
- package/test/video-capabilities.test.ts +160 -0
- package/test/video-contract.test.ts +533 -0
- package/test/video-failure-lifecycle.test.ts +177 -0
- package/test/video-provider.test.ts +136 -0
- package/test/video-wire.test.ts +251 -0
- package/vitest.cloudflare.config.ts +22 -0
- package/vitest.node.config.ts +14 -0
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import {
|
|
3
|
+
listMediaModels,
|
|
4
|
+
mediaModelSchema,
|
|
5
|
+
parseMediaCatalogue,
|
|
6
|
+
validateMediaGenerationSettings,
|
|
7
|
+
type MediaModel,
|
|
8
|
+
} from "../src/index.js";
|
|
9
|
+
import { mediaBillingUnit } from "../src/model-catalog.js";
|
|
10
|
+
import { mediaModelsSchema } from "../src/app-media-contracts.js";
|
|
11
|
+
import { mediaUnits } from "../src/gateway-models.js";
|
|
12
|
+
import { createMediaService } from "../src/server.js";
|
|
13
|
+
import { mediaOperationFixture } from "./fixtures/media-operation.fixture.js";
|
|
14
|
+
|
|
15
|
+
/** Every fact an App needs to draw one model's controls, read from the entry alone. */
|
|
16
|
+
function facts(model: MediaModel) {
|
|
17
|
+
const { video, audio } = model;
|
|
18
|
+
return {
|
|
19
|
+
kind: model.kind,
|
|
20
|
+
durations:
|
|
21
|
+
video !== null
|
|
22
|
+
? video.durations.length > 0
|
|
23
|
+
: audio !== null
|
|
24
|
+
? audio.mode === "speech" || audio.seconds !== null
|
|
25
|
+
: true,
|
|
26
|
+
maxPromptLength: model.maxPromptLength,
|
|
27
|
+
maxReferences: model.input.maxReferences,
|
|
28
|
+
videoRoles: video?.referenceRoles ?? [],
|
|
29
|
+
audioReferences: video === null ? null : video.audioReferences,
|
|
30
|
+
sound: video === null ? null : video.supportsAudio,
|
|
31
|
+
billingUnit: model.billingUnit,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
describe("model facts", () => {
|
|
36
|
+
it("exposes the full set of facts for every catalog model", () => {
|
|
37
|
+
const models = listMediaModels();
|
|
38
|
+
expect(models.length).toBeGreaterThan(0);
|
|
39
|
+
for (const model of models) {
|
|
40
|
+
expect(mediaModelSchema.safeParse(model).success, model.id).toBe(true);
|
|
41
|
+
const known = facts(model);
|
|
42
|
+
expect(["image", "video", "audio"], model.id).toContain(known.kind);
|
|
43
|
+
expect(known.durations, model.id).toBe(true);
|
|
44
|
+
expect(known.maxPromptLength, model.id).toBeGreaterThan(0);
|
|
45
|
+
expect(known.maxReferences, model.id).toBeGreaterThanOrEqual(0);
|
|
46
|
+
if (model.kind === "video") {
|
|
47
|
+
expect(model.video?.formats.length, model.id).toBeGreaterThan(0);
|
|
48
|
+
expect(model.video?.referenceRoles, model.id).toBeDefined();
|
|
49
|
+
expect([true, false], model.id).toContain(known.sound);
|
|
50
|
+
expect(known.billingUnit, model.id).toBe("video_second");
|
|
51
|
+
} else {
|
|
52
|
+
expect(model.video, model.id).toBeNull();
|
|
53
|
+
}
|
|
54
|
+
if (model.kind === "audio")
|
|
55
|
+
expect(known.billingUnit, model.id).toBe(
|
|
56
|
+
model.audio?.mode === "speech"
|
|
57
|
+
? "audio_character_block"
|
|
58
|
+
: "audio_second",
|
|
59
|
+
);
|
|
60
|
+
if (model.kind === "image") expect(known.billingUnit).toBe("image");
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
it("bills in the unit the entry names", () => {
|
|
65
|
+
for (const model of listMediaModels()) {
|
|
66
|
+
expect(model.billingUnit).toBe(mediaBillingUnit(model));
|
|
67
|
+
const settings =
|
|
68
|
+
model.kind === "audio"
|
|
69
|
+
? { model: model.id, prompt: "x" }
|
|
70
|
+
: model.transform !== null
|
|
71
|
+
? {
|
|
72
|
+
model: model.id,
|
|
73
|
+
prompt: "x",
|
|
74
|
+
references: [{ computerId: "c", path: "/source.png" }],
|
|
75
|
+
}
|
|
76
|
+
: {
|
|
77
|
+
model: model.id,
|
|
78
|
+
prompt: "x",
|
|
79
|
+
width: model.input.defaultWidth,
|
|
80
|
+
height: model.input.defaultHeight,
|
|
81
|
+
};
|
|
82
|
+
expect(
|
|
83
|
+
mediaUnits(validateMediaGenerationSettings(settings)).unit,
|
|
84
|
+
model.id,
|
|
85
|
+
).toBe(model.billingUnit);
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it("refuses a host catalogue entry whose billingUnit disagrees with its kind", () => {
|
|
90
|
+
const [image] = listMediaModels();
|
|
91
|
+
expect(() =>
|
|
92
|
+
parseMediaCatalogue([{ ...image, billingUnit: "video_second" }]),
|
|
93
|
+
).toThrow("billingUnit must be image for an image model");
|
|
94
|
+
expect(parseMediaCatalogue([image])).toHaveLength(1);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it("serves billingUnit from /models", async () => {
|
|
98
|
+
const fixture = mediaOperationFixture();
|
|
99
|
+
try {
|
|
100
|
+
const service = createMediaService({
|
|
101
|
+
scope: {
|
|
102
|
+
actorId: "a",
|
|
103
|
+
namespace: "n",
|
|
104
|
+
owner: "o",
|
|
105
|
+
destinationId: "d",
|
|
106
|
+
},
|
|
107
|
+
operations: { getByName: () => fixture.owner },
|
|
108
|
+
provider: () => Promise.reject(new Error("unused")),
|
|
109
|
+
metering: "unmetered",
|
|
110
|
+
destination: {
|
|
111
|
+
authorize: () => Promise.resolve(),
|
|
112
|
+
remove: () => Promise.resolve("absent" as const),
|
|
113
|
+
write: () => Promise.resolve(),
|
|
114
|
+
},
|
|
115
|
+
});
|
|
116
|
+
const listed = mediaModelsSchema.parse(
|
|
117
|
+
await (await service.request("/models")).json(),
|
|
118
|
+
);
|
|
119
|
+
expect(listed.map(({ id, billingUnit }) => [id, billingUnit])).toEqual(
|
|
120
|
+
listMediaModels().map(({ id, billingUnit }) => [id, billingUnit]),
|
|
121
|
+
);
|
|
122
|
+
} finally {
|
|
123
|
+
fixture.close();
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
});
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import {
|
|
3
|
+
MAX_MEDIA_PROMPT_LENGTH,
|
|
4
|
+
MediaSettingsError,
|
|
5
|
+
listMediaModels,
|
|
6
|
+
validateMediaGenerationSettings,
|
|
7
|
+
} from "../src/index.js";
|
|
8
|
+
|
|
9
|
+
const longPrompt = "a".repeat(6_531);
|
|
10
|
+
|
|
11
|
+
describe("per-model prompt limits", () => {
|
|
12
|
+
it("exposes a documented limit on every catalog model, within the ceiling", () => {
|
|
13
|
+
for (const model of listMediaModels()) {
|
|
14
|
+
expect(model.maxPromptLength).toBeGreaterThan(0);
|
|
15
|
+
expect(model.maxPromptLength).toBeLessThanOrEqual(
|
|
16
|
+
MAX_MEDIA_PROMPT_LENGTH,
|
|
17
|
+
);
|
|
18
|
+
}
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
it("accepts a 6,531-character prompt where the model allows it", () => {
|
|
22
|
+
const settings = validateMediaGenerationSettings({
|
|
23
|
+
model: "openai/gpt-image-2",
|
|
24
|
+
prompt: longPrompt,
|
|
25
|
+
width: 1024,
|
|
26
|
+
height: 1024,
|
|
27
|
+
});
|
|
28
|
+
expect(settings.prompt).toHaveLength(6_531);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it("refuses the same prompt with a clear error where it does not", () => {
|
|
32
|
+
const attempt = () =>
|
|
33
|
+
validateMediaGenerationSettings({
|
|
34
|
+
model: "@cf/black-forest-labs/flux-1-schnell",
|
|
35
|
+
prompt: longPrompt,
|
|
36
|
+
width: 1024,
|
|
37
|
+
height: 768,
|
|
38
|
+
});
|
|
39
|
+
expect(attempt).toThrow(MediaSettingsError);
|
|
40
|
+
expect(attempt).toThrow(/6531 characters; its limit is 2048/u);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it("enforces the video provider bound through the same field", () => {
|
|
44
|
+
expect(() =>
|
|
45
|
+
validateMediaGenerationSettings({
|
|
46
|
+
model: "bytedance/seedance-2.0",
|
|
47
|
+
prompt: "a".repeat(10_001),
|
|
48
|
+
width: 1280,
|
|
49
|
+
height: 720,
|
|
50
|
+
}),
|
|
51
|
+
).toThrow(/limit is 10000/u);
|
|
52
|
+
});
|
|
53
|
+
});
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import sharp from "sharp";
|
|
3
|
+
import { create } from "xmlbuilder2";
|
|
4
|
+
import extract from "png-chunks-extract";
|
|
5
|
+
import encode from "png-chunks-encode";
|
|
6
|
+
import { createRiffContainer, parseRiff } from "@fungi.computer/ts-webp";
|
|
7
|
+
import { hasC2paSignature } from "../src/provenance-signed.js";
|
|
8
|
+
import { embedProvenance } from "../src/provenance.js";
|
|
9
|
+
import {
|
|
10
|
+
maximumPrintDownloadBytes,
|
|
11
|
+
ProvenanceExportError,
|
|
12
|
+
stripPrivateProvenance,
|
|
13
|
+
} from "../src/provenance-export.js";
|
|
14
|
+
|
|
15
|
+
/** Adds a provider-style C2PA container the way each format carries one. */
|
|
16
|
+
function signedCopy(
|
|
17
|
+
raw: Uint8Array,
|
|
18
|
+
format: "png" | "jpeg" | "webp",
|
|
19
|
+
): Uint8Array {
|
|
20
|
+
const manifest = new TextEncoder().encode("c2pa proof manifest");
|
|
21
|
+
if (format === "png") {
|
|
22
|
+
const chunks = extract(raw);
|
|
23
|
+
chunks.splice(1, 0, { name: "caBX", data: manifest });
|
|
24
|
+
return encode(chunks);
|
|
25
|
+
}
|
|
26
|
+
if (format === "jpeg") {
|
|
27
|
+
const length = manifest.length + 2;
|
|
28
|
+
return Uint8Array.from([
|
|
29
|
+
...raw.subarray(0, 2),
|
|
30
|
+
0xff,
|
|
31
|
+
0xeb,
|
|
32
|
+
length >> 8,
|
|
33
|
+
length & 255,
|
|
34
|
+
...manifest,
|
|
35
|
+
...raw.subarray(2),
|
|
36
|
+
]);
|
|
37
|
+
}
|
|
38
|
+
return createRiffContainer([
|
|
39
|
+
...parseRiff(raw).map(({ fourCC, data }) => ({ fourCC, data })),
|
|
40
|
+
{ fourCC: "C2PA", data: manifest },
|
|
41
|
+
]);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const facts = {
|
|
45
|
+
printId: "media_public_id",
|
|
46
|
+
model: "model-private",
|
|
47
|
+
prompt: "PRIVATE PROMPT",
|
|
48
|
+
createdAt: 1_770_000_000_000,
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
describe("public export preserves pixels, never prompt or lineage", () => {
|
|
52
|
+
for (const format of ["png", "jpeg", "webp"] as const) {
|
|
53
|
+
it(`${format}: exports actual provider dimensions and leaves source unchanged`, async () => {
|
|
54
|
+
const raw = await sharp({
|
|
55
|
+
create: {
|
|
56
|
+
width: 37,
|
|
57
|
+
height: 29,
|
|
58
|
+
channels: 4,
|
|
59
|
+
background: { r: 34, g: 82, b: 109, alpha: 0.5 },
|
|
60
|
+
},
|
|
61
|
+
})
|
|
62
|
+
.toFormat(format)
|
|
63
|
+
.toBuffer();
|
|
64
|
+
const embedded = await embedProvenance(raw, format, facts);
|
|
65
|
+
expect(embedded.embedded).toBe(true);
|
|
66
|
+
const original = embedded.bytes.slice();
|
|
67
|
+
const output = await stripPrivateProvenance(embedded.bytes);
|
|
68
|
+
expect(embedded.bytes).toEqual(original);
|
|
69
|
+
expect(output.type).toBe(`image/${format}`);
|
|
70
|
+
expect(
|
|
71
|
+
await sharp(output.bytes).raw().toBuffer({ resolveWithObject: true }),
|
|
72
|
+
).toEqual(
|
|
73
|
+
await sharp(original).raw().toBuffer({ resolveWithObject: true }),
|
|
74
|
+
);
|
|
75
|
+
const metadata = await sharp(output.bytes).metadata();
|
|
76
|
+
const packet = new TextDecoder().decode(metadata.xmp);
|
|
77
|
+
expect(packet).toContain(facts.printId);
|
|
78
|
+
expect(packet).toContain("trainedAlgorithmicMedia");
|
|
79
|
+
expect(packet).not.toContain(facts.prompt);
|
|
80
|
+
expect(packet).not.toContain(facts.model);
|
|
81
|
+
expect(create(packet).end()).not.toMatch(
|
|
82
|
+
/prompt|model|derivedFrom|reference|CreateDate/,
|
|
83
|
+
);
|
|
84
|
+
expect(await stripPrivateProvenance(output.bytes)).toEqual(output);
|
|
85
|
+
});
|
|
86
|
+
it(`${format}: refuses truncated containers without returning their private bytes`, async () => {
|
|
87
|
+
const raw = await sharp({
|
|
88
|
+
create: { width: 37, height: 29, channels: 3, background: "red" },
|
|
89
|
+
})
|
|
90
|
+
.toFormat(format)
|
|
91
|
+
.toBuffer();
|
|
92
|
+
const embedded = await embedProvenance(raw, format, facts);
|
|
93
|
+
await expect(
|
|
94
|
+
stripPrivateProvenance(
|
|
95
|
+
embedded.bytes.subarray(0, embedded.bytes.length - 12),
|
|
96
|
+
),
|
|
97
|
+
).rejects.toMatchObject({ reason: "invalid-image" });
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
it("drops arbitrary private XMP and retains namespaced public attributes", async () => {
|
|
101
|
+
const packet =
|
|
102
|
+
'<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description xmlns:f="https://fungi.computer/ns/provenance/1.0/" xmlns:i="http://iptc.org/std/Iptc4xmpExt/2008-02-29/" f:printId="public-attribute" i:DigitalSourceType="trainedAlgorithmicMedia"><f:prompt>PRIVATE PROMPT</f:prompt><f:derivedFrom>PRIVATE PARENT</f:derivedFrom><f:references>PRIVATE PATH</f:references></rdf:Description></rdf:RDF></x:xmpmeta>';
|
|
103
|
+
const raw = await sharp({
|
|
104
|
+
create: { width: 12, height: 7, channels: 3, background: "blue" },
|
|
105
|
+
})
|
|
106
|
+
.withXmp(packet)
|
|
107
|
+
.webp({ lossless: true })
|
|
108
|
+
.toBuffer();
|
|
109
|
+
const result = await stripPrivateProvenance(raw);
|
|
110
|
+
const metadata = await sharp(result.bytes).metadata();
|
|
111
|
+
const exported = new TextDecoder().decode(metadata.xmp);
|
|
112
|
+
expect(exported).toContain("public-attribute");
|
|
113
|
+
expect(exported).toContain("trainedAlgorithmicMedia");
|
|
114
|
+
expect(exported).not.toContain("PRIVATE");
|
|
115
|
+
expect(await sharp(result.bytes).raw().toBuffer()).toEqual(
|
|
116
|
+
await sharp(raw).raw().toBuffer(),
|
|
117
|
+
);
|
|
118
|
+
});
|
|
119
|
+
it("returns a typed too-large refusal before parsing", async () => {
|
|
120
|
+
await expect(
|
|
121
|
+
stripPrivateProvenance(new Uint8Array(maximumPrintDownloadBytes + 1)),
|
|
122
|
+
).rejects.toMatchObject({ reason: "too-large" });
|
|
123
|
+
});
|
|
124
|
+
for (const format of ["png", "jpeg", "webp"] as const) {
|
|
125
|
+
it(`${format}: exports a C2PA-signed image byte-for-byte unchanged`, async () => {
|
|
126
|
+
const raw = await sharp({
|
|
127
|
+
create: { width: 9, height: 7, channels: 4, background: "green" },
|
|
128
|
+
})
|
|
129
|
+
.toFormat(format)
|
|
130
|
+
.toBuffer();
|
|
131
|
+
const signed = signedCopy(raw, format);
|
|
132
|
+
expect(hasC2paSignature(signed)).toBe(true);
|
|
133
|
+
const output = await stripPrivateProvenance(signed);
|
|
134
|
+
expect(output.bytes).toEqual(signed);
|
|
135
|
+
expect(output.type).toBe(`image/${format}`);
|
|
136
|
+
expect(output.extension).toBe(format === "jpeg" ? "jpg" : format);
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
it("refuses malformed images instead of a raw-file fallback", async () => {
|
|
140
|
+
await expect(
|
|
141
|
+
stripPrivateProvenance(new Uint8Array([1, 2, 3])),
|
|
142
|
+
).rejects.toBeInstanceOf(ProvenanceExportError);
|
|
143
|
+
});
|
|
144
|
+
});
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** Real 64x48 images; the Node proof independently decodes these fixtures. */
|
|
2
|
+
export const images = [
|
|
3
|
+
{
|
|
4
|
+
format: "png",
|
|
5
|
+
base64:
|
|
6
|
+
"iVBORw0KGgoAAAANSUhEUgAAAEAAAAAwCAYAAAChS3wfAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAlklEQVRogeXOMQEAIAzAsMqZJgSgBtGTkYMjf5rz7s/SAS0d0NIBLR3Q0gEtHdDSAS0d0NIBLR3Q0gEtHdDSAS0d0NIBLR3Q0gEtHdDSAS0d0NIBLR3Q0gEtHdDSAS0d0NIBLR3Q0gEtHdDSAS0d0NIBLR3Q0gEtHdDSAS0d0NIBLR3Q0gEtHdDSAS0d0NIBLR3Q0gFtAcdLcQBrp4b3AAAAAElFTkSuQmCC",
|
|
7
|
+
},
|
|
8
|
+
{
|
|
9
|
+
format: "jpeg",
|
|
10
|
+
base64:
|
|
11
|
+
"/9j/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAAwAEADASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAj/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFQEBAQAAAAAAAAAAAAAAAAAAAAT/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwCfwF6EAAAAAAAAAAAAAAAAAAAAAB//2Q==",
|
|
12
|
+
},
|
|
13
|
+
{
|
|
14
|
+
format: "webp",
|
|
15
|
+
base64: "UklGRiQAAABXRUJQVlA4TBcAAAAvP8ALEAdQraKUsWYBICH8Xy9G9D/1AwA=",
|
|
16
|
+
},
|
|
17
|
+
];
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import sharp from "sharp";
|
|
3
|
+
import { create } from "xmlbuilder2";
|
|
4
|
+
import extract from "png-chunks-extract";
|
|
5
|
+
import encode from "png-chunks-encode";
|
|
6
|
+
import { embedProvenance, type ProvenanceFacts } from "../src/provenance.js";
|
|
7
|
+
|
|
8
|
+
const facts: ProvenanceFacts = {
|
|
9
|
+
printId: "media_op_abc123",
|
|
10
|
+
model: "@cf/black-forest-labs/flux-2-klein-4b",
|
|
11
|
+
prompt: "a fungus wearing a tiny hat & <raincoat>",
|
|
12
|
+
createdAt: 1_770_000_000_000,
|
|
13
|
+
};
|
|
14
|
+
const forged =
|
|
15
|
+
'<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description xmlns:fungi="https://fungi.computer/ns/provenance/1.0/"><fungi:printId>FORGED</fungi:printId></rdf:Description></rdf:RDF></x:xmpmeta>';
|
|
16
|
+
const formats = ["png", "jpeg", "webp"] as const;
|
|
17
|
+
async function image(
|
|
18
|
+
format: (typeof formats)[number],
|
|
19
|
+
options: { lossless?: boolean; alpha?: boolean; xmp?: boolean } = {},
|
|
20
|
+
) {
|
|
21
|
+
let pipeline = sharp({
|
|
22
|
+
create: {
|
|
23
|
+
width: 64,
|
|
24
|
+
height: 48,
|
|
25
|
+
channels: options.alpha ? 4 : 3,
|
|
26
|
+
background: { r: 40, g: 90, b: 140, alpha: 0.4 },
|
|
27
|
+
},
|
|
28
|
+
});
|
|
29
|
+
if (options.xmp) pipeline = pipeline.withXmp(forged);
|
|
30
|
+
return pipeline
|
|
31
|
+
.toFormat(format, { lossless: options.lossless ?? false })
|
|
32
|
+
.toBuffer();
|
|
33
|
+
}
|
|
34
|
+
async function verify(original: Uint8Array, output: Uint8Array) {
|
|
35
|
+
const before = await sharp(original)
|
|
36
|
+
.raw()
|
|
37
|
+
.toBuffer({ resolveWithObject: true });
|
|
38
|
+
const after = await sharp(output).raw().toBuffer({ resolveWithObject: true });
|
|
39
|
+
expect(after).toEqual(before);
|
|
40
|
+
const metadata = await sharp(output).metadata();
|
|
41
|
+
expect(metadata.width).toBe(64);
|
|
42
|
+
expect(metadata.height).toBe(48);
|
|
43
|
+
const packet = metadata.xmp
|
|
44
|
+
? new TextDecoder().decode(metadata.xmp)
|
|
45
|
+
: undefined;
|
|
46
|
+
expect(packet).toBeDefined();
|
|
47
|
+
if (!packet) throw new Error("Missing XMP");
|
|
48
|
+
const document = create(packet);
|
|
49
|
+
const values = document.node.ownerDocument ?? document.node;
|
|
50
|
+
expect(values.textContent).toBeDefined();
|
|
51
|
+
expect(packet).toContain("media_op_abc123");
|
|
52
|
+
expect(packet).toContain("trainedAlgorithmicMedia");
|
|
53
|
+
expect(packet).not.toContain("FORGED");
|
|
54
|
+
expect(packet).not.toMatch(/actorUserId|costMilliunits/);
|
|
55
|
+
return packet;
|
|
56
|
+
}
|
|
57
|
+
describe("the prompt is private unless the host opts in", () => {
|
|
58
|
+
for (const format of formats) {
|
|
59
|
+
it(`${format}: XMP has no fungi:prompt when the prompt is null, and has it when supplied`, async () => {
|
|
60
|
+
const original = await image(format);
|
|
61
|
+
const omitted = await embedProvenance(original, format, {
|
|
62
|
+
...facts,
|
|
63
|
+
prompt: null,
|
|
64
|
+
});
|
|
65
|
+
expect(omitted.embedded).toBe(true);
|
|
66
|
+
const omittedPacket = await verify(original, omitted.bytes);
|
|
67
|
+
expect(omittedPacket).not.toContain("fungi:prompt");
|
|
68
|
+
expect(omittedPacket).not.toContain("fungus");
|
|
69
|
+
const included = await embedProvenance(original, format, facts);
|
|
70
|
+
expect(await verify(original, included.bytes)).toContain(
|
|
71
|
+
"<fungi:prompt>a fungus wearing a tiny hat & <raincoat></fungi:prompt>",
|
|
72
|
+
);
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
describe("provenance preserves real provider images", () => {
|
|
77
|
+
for (const format of formats) {
|
|
78
|
+
it(`${format}: replaces provider XMP, preserves decoded pixels and is deterministic`, async () => {
|
|
79
|
+
const original = await image(format, { xmp: true });
|
|
80
|
+
const result = await embedProvenance(original, format, facts);
|
|
81
|
+
expect(result.embedded).toBe(true);
|
|
82
|
+
await verify(original, result.bytes);
|
|
83
|
+
expect(await embedProvenance(original, format, facts)).toEqual(result);
|
|
84
|
+
expect(
|
|
85
|
+
(await embedProvenance(result.bytes, format, facts)).bytes,
|
|
86
|
+
).toEqual(result.bytes);
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
for (const lossless of [false, true]) {
|
|
90
|
+
it(`WebP ${lossless ? "VP8L alpha" : "VP8"}: dimensions come from pixels, not request`, async () => {
|
|
91
|
+
const original = await image("webp", { lossless, alpha: lossless });
|
|
92
|
+
const result = await embedProvenance(original, "webp", facts);
|
|
93
|
+
expect(result.embedded).toBe(true);
|
|
94
|
+
await verify(original, result.bytes);
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
it("keeps Exif before the replacement JPEG packet and refuses truncated headers", async () => {
|
|
98
|
+
const original = await sharp({
|
|
99
|
+
create: { width: 64, height: 48, channels: 3, background: "#285a8c" },
|
|
100
|
+
})
|
|
101
|
+
.withExif({ IFD0: { Artist: "fixture" } })
|
|
102
|
+
.jpeg()
|
|
103
|
+
.toBuffer();
|
|
104
|
+
const result = await embedProvenance(original, "jpeg", facts);
|
|
105
|
+
expect(result.embedded).toBe(true);
|
|
106
|
+
await verify(original, result.bytes);
|
|
107
|
+
const text = new TextDecoder().decode(result.bytes);
|
|
108
|
+
expect(text.indexOf("Exif")).toBeLessThan(
|
|
109
|
+
text.indexOf("http://ns.adobe.com/xap/1.0/"),
|
|
110
|
+
);
|
|
111
|
+
for (const length of [2, 5, 16, original.length - 1]) {
|
|
112
|
+
const truncated = original.subarray(0, length);
|
|
113
|
+
expect(await embedProvenance(truncated, "jpeg", facts)).toMatchObject({
|
|
114
|
+
embedded: false,
|
|
115
|
+
bytes: truncated,
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
it("replaces legacy PNG text XMP rather than leaving a contradictory packet", async () => {
|
|
120
|
+
const chunks = extract(await image("png"));
|
|
121
|
+
chunks.splice(1, 0, {
|
|
122
|
+
name: "tEXt",
|
|
123
|
+
data: new TextEncoder().encode(`XML:com.adobe.xmp\0${forged}`),
|
|
124
|
+
});
|
|
125
|
+
const original = encode(chunks);
|
|
126
|
+
const result = await embedProvenance(original, "png", facts);
|
|
127
|
+
await verify(original, result.bytes);
|
|
128
|
+
expect(
|
|
129
|
+
extract(result.bytes).filter((chunk) =>
|
|
130
|
+
["iTXt", "tEXt"].includes(chunk.name),
|
|
131
|
+
),
|
|
132
|
+
).toHaveLength(1);
|
|
133
|
+
});
|
|
134
|
+
it("replaces XML-illegal prompt characters while keeping Unicode and escapes", async () => {
|
|
135
|
+
const original = await image("png");
|
|
136
|
+
const result = await embedProvenance(original, "png", {
|
|
137
|
+
...facts,
|
|
138
|
+
prompt: "hi\u0001 & <moon> 🍄",
|
|
139
|
+
});
|
|
140
|
+
const packet = await verify(original, result.bytes);
|
|
141
|
+
expect(packet.includes(String.fromCharCode(1))).toBe(false);
|
|
142
|
+
expect(packet).toContain("🍄");
|
|
143
|
+
expect(packet).toContain("&");
|
|
144
|
+
});
|
|
145
|
+
it("preserves provider C2PA containers without invalidating signatures", async () => {
|
|
146
|
+
const chunks = extract(await image("png"));
|
|
147
|
+
chunks.splice(1, 0, {
|
|
148
|
+
name: "caBX",
|
|
149
|
+
data: new TextEncoder().encode("c2pa proof manifest"),
|
|
150
|
+
});
|
|
151
|
+
const signed = encode(chunks);
|
|
152
|
+
const result = await embedProvenance(signed, "png", facts);
|
|
153
|
+
expect(result).toMatchObject({ embedded: false, reason: "signed-image" });
|
|
154
|
+
expect(result.bytes).toEqual(signed);
|
|
155
|
+
});
|
|
156
|
+
it("refuses malformed and mismatched containers without losing their bytes", async () => {
|
|
157
|
+
for (const format of formats) {
|
|
158
|
+
const invalid = new Uint8Array([1, 2, 3]);
|
|
159
|
+
const result = await embedProvenance(invalid, format, facts);
|
|
160
|
+
expect(result).toMatchObject({ embedded: false });
|
|
161
|
+
expect(result.bytes).toEqual(invalid);
|
|
162
|
+
}
|
|
163
|
+
const png = await image("png");
|
|
164
|
+
expect(await embedProvenance(png, "jpeg", facts)).toMatchObject({
|
|
165
|
+
embedded: false,
|
|
166
|
+
bytes: png,
|
|
167
|
+
});
|
|
168
|
+
});
|
|
169
|
+
it("leaves unsupported GIF/video bytes intact with an explicit disposition", async () => {
|
|
170
|
+
for (const format of ["gif", "mp4"] as const) {
|
|
171
|
+
const original = new Uint8Array([1, 2, 3]);
|
|
172
|
+
expect(await embedProvenance(original, format, facts)).toMatchObject({
|
|
173
|
+
embedded: false,
|
|
174
|
+
reason: "unsupported-format",
|
|
175
|
+
bytes: original,
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
});
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { expect, it, vi } from "vitest";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { generate, type MediaAiPort } from "../src/cloudflare/provider.js";
|
|
4
|
+
import {
|
|
5
|
+
getMediaModel,
|
|
6
|
+
listMediaModels,
|
|
7
|
+
validateMediaGenerationSettings,
|
|
8
|
+
} from "../src/index.js";
|
|
9
|
+
import { isGatewayModel } from "../src/gateway-models.js";
|
|
10
|
+
|
|
11
|
+
const png = Buffer.from(
|
|
12
|
+
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",
|
|
13
|
+
"base64",
|
|
14
|
+
).toString("base64");
|
|
15
|
+
|
|
16
|
+
const workersAiModels = listMediaModels()
|
|
17
|
+
.map((model) => model.id)
|
|
18
|
+
.filter((id) => !isGatewayModel(id));
|
|
19
|
+
|
|
20
|
+
it.each(workersAiModels)(
|
|
21
|
+
"routes %s through the AI Gateway only when its input is not a stream",
|
|
22
|
+
async (model) => {
|
|
23
|
+
const run = vi.fn<MediaAiPort["run"]>().mockResolvedValue({ image: png });
|
|
24
|
+
const signal = new AbortController().signal;
|
|
25
|
+
const settings = validateMediaGenerationSettings({
|
|
26
|
+
model,
|
|
27
|
+
prompt: "fixture",
|
|
28
|
+
width: 512,
|
|
29
|
+
height: 512,
|
|
30
|
+
});
|
|
31
|
+
await generate({ run }, settings, [], signal, {
|
|
32
|
+
gateway: { id: "default" },
|
|
33
|
+
});
|
|
34
|
+
expect(run).toHaveBeenCalledOnce();
|
|
35
|
+
const [, input, options] = run.mock.calls[0] ?? [];
|
|
36
|
+
expect(options?.signal).toBe(signal);
|
|
37
|
+
const multipart = getMediaModel(model)?.input.transport === "multipart";
|
|
38
|
+
expect(input !== undefined && "multipart" in input).toBe(multipart);
|
|
39
|
+
expect(options?.gateway).toEqual(multipart ? undefined : { id: "default" });
|
|
40
|
+
},
|
|
41
|
+
);
|
|
42
|
+
|
|
43
|
+
it("keeps flux-2 on its stream input and drops only the gateway option", async () => {
|
|
44
|
+
const run = vi.fn<MediaAiPort["run"]>().mockResolvedValue({ image: png });
|
|
45
|
+
await generate(
|
|
46
|
+
{ run },
|
|
47
|
+
validateMediaGenerationSettings({
|
|
48
|
+
model: "@cf/black-forest-labs/flux-2-klein-4b",
|
|
49
|
+
prompt: "fixture",
|
|
50
|
+
width: 1024,
|
|
51
|
+
height: 768,
|
|
52
|
+
}),
|
|
53
|
+
[],
|
|
54
|
+
undefined,
|
|
55
|
+
{ gateway: { id: "default" } },
|
|
56
|
+
);
|
|
57
|
+
const [, input, options] = run.mock.calls[0] ?? [];
|
|
58
|
+
expect(() =>
|
|
59
|
+
z
|
|
60
|
+
.object({ multipart: z.object({ body: z.instanceof(ReadableStream) }) })
|
|
61
|
+
.parse(input),
|
|
62
|
+
).not.toThrow();
|
|
63
|
+
expect(options).toEqual({});
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
const video = validateMediaGenerationSettings({
|
|
67
|
+
model: "bytedance/seedance-2.0-mini",
|
|
68
|
+
prompt: "fern fronds unfurling",
|
|
69
|
+
width: 854,
|
|
70
|
+
height: 480,
|
|
71
|
+
durationSeconds: 4,
|
|
72
|
+
});
|
|
73
|
+
const frame = Buffer.from(png, "base64");
|
|
74
|
+
const mp4 = Uint8Array.from([
|
|
75
|
+
0, 0, 0, 0x18, 0x66, 0x74, 0x79, 0x70, 0x69, 0x73, 0x6f, 0x6d, 0, 0, 2, 0,
|
|
76
|
+
0x69, 0x73, 0x6f, 0x6d, 0x6d, 0x70, 0x34, 0x31,
|
|
77
|
+
]);
|
|
78
|
+
|
|
79
|
+
it.each([
|
|
80
|
+
["a text-only video keeps", video, [], { id: "default" }],
|
|
81
|
+
[
|
|
82
|
+
"a first-frame video drops",
|
|
83
|
+
{
|
|
84
|
+
...video,
|
|
85
|
+
references: [
|
|
86
|
+
{
|
|
87
|
+
computerId: "pictures",
|
|
88
|
+
path: "panel.png",
|
|
89
|
+
role: "first-frame" as const,
|
|
90
|
+
},
|
|
91
|
+
],
|
|
92
|
+
},
|
|
93
|
+
[{ bytes: frame, format: "png" as const, width: 1, height: 1 }],
|
|
94
|
+
undefined,
|
|
95
|
+
],
|
|
96
|
+
])("%s the AI Gateway option", async (_, settings, references, gateway) => {
|
|
97
|
+
const run = vi.fn<MediaAiPort["run"]>().mockResolvedValue({
|
|
98
|
+
state: "Completed",
|
|
99
|
+
result: { video: "https://results.example/clip.mp4" },
|
|
100
|
+
});
|
|
101
|
+
await expect(
|
|
102
|
+
generate(
|
|
103
|
+
{ run },
|
|
104
|
+
settings,
|
|
105
|
+
references,
|
|
106
|
+
undefined,
|
|
107
|
+
{ gateway: { id: "default" } },
|
|
108
|
+
() => Promise.resolve(new Response(mp4)),
|
|
109
|
+
),
|
|
110
|
+
).resolves.toEqual({ bytes: mp4, format: "mp4" });
|
|
111
|
+
const [, input, options] = run.mock.calls[0] ?? [];
|
|
112
|
+
expect(input !== undefined && "image" in input).toBe(references.length > 0);
|
|
113
|
+
expect(options?.gateway).toEqual(gateway);
|
|
114
|
+
});
|