@contentauth/c2pa-node 0.11.0 → 0.12.1
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/Cargo.toml +1 -1
- package/README.md +63 -3
- package/dist/IdentityAssertion.spec.js +28 -2
- package/dist/Reader.spec.js +60 -1
- package/dist/Trustmark.js +14 -0
- package/dist/Trustmark.spec.js +247 -9
- package/dist/index.node +2 -2
- package/dist/types/Trustmark.d.ts +12 -0
- package/dist/types/types.d.ts +22 -0
- package/package.json +2 -2
- package/src/lib.rs +1 -0
- package/src/neon_identity_assertion_signer.rs +6 -1
- package/src/neon_trustmark.rs +128 -10
package/Cargo.toml
CHANGED
package/README.md
CHANGED
|
@@ -59,6 +59,56 @@ For documentation builds and version-list maintenance, see
|
|
|
59
59
|
|
|
60
60
|
## Components
|
|
61
61
|
|
|
62
|
+
### Trustmark
|
|
63
|
+
|
|
64
|
+
`Trustmark` uses TrustMark 0.5 to encode and decode watermarks. Watermark removal
|
|
65
|
+
is opt-in and supported for variants **P** and **Q** only. Select the variant
|
|
66
|
+
used to embed the watermark:
|
|
67
|
+
|
|
68
|
+
```javascript
|
|
69
|
+
import { Trustmark } from '@contentauth/c2pa-node';
|
|
70
|
+
|
|
71
|
+
const trustmark = await Trustmark.newTrustmark({
|
|
72
|
+
variant: 'P',
|
|
73
|
+
version: 'BCH_5',
|
|
74
|
+
modelPath: './models',
|
|
75
|
+
loadRemover: true
|
|
76
|
+
});
|
|
77
|
+
const recoveredPng = await trustmark.remove(watermarkedImageBuffer);
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
`loadRemover` defaults to `false`. Enabling it downloads and loads the separate
|
|
81
|
+
`remover_P.onnx` or `remover_Q.onnx` file in `modelPath` (default `./models`), in
|
|
82
|
+
addition to the encoder and decoder. Cached files are reused. This adds startup
|
|
83
|
+
time and memory usage; ordinary encode/decode callers do not load a remover.
|
|
84
|
+
|
|
85
|
+
`remove()` accepts an 8-bit JPEG or PNG (RGB, RGBA, or grayscale) and returns an
|
|
86
|
+
**encoded PNG**, preserving dimensions and alpha. This differs from `encode()`,
|
|
87
|
+
which returns **raw RGB8 pixels**. Unsupported formats or bit depths, malformed
|
|
88
|
+
images, missing removal support, and model/inference failures reject the promise;
|
|
89
|
+
failures are never silently treated as successful removal.
|
|
90
|
+
|
|
91
|
+
Removal rejects encoded inputs larger than **64 MiB**, dimensions larger than
|
|
92
|
+
**16,384 pixels** on either axis, and images with more than **32 million pixels**.
|
|
93
|
+
Dimensions and pixel count are checked before decoding pixels or running
|
|
94
|
+
inference. Decoding also has a **best-effort 128 MiB allocation budget**. These
|
|
95
|
+
are per-call limits, not a cap on total process memory: removal allocates additional
|
|
96
|
+
full-resolution buffers, and concurrent calls require additional memory.
|
|
97
|
+
|
|
98
|
+
The returned PNG is **pixel-only**. It does not copy image metadata, including
|
|
99
|
+
EXIF, XMP, ICC color profiles, or embedded C2PA manifests. Preserving dimensions
|
|
100
|
+
and alpha does not mean preserving metadata. Callers that need ordinary image
|
|
101
|
+
metadata must carry it forward separately using an encoder that supports it.
|
|
102
|
+
Existing C2PA credentials bind to the original asset and do not remain valid for
|
|
103
|
+
the modified pixels. Use the original asset as an ingredient and sign a new
|
|
104
|
+
manifest to attach valid Content Credentials to the output; do not simply copy
|
|
105
|
+
the original manifest.
|
|
106
|
+
|
|
107
|
+
Removal is lossy: it does not restore the original pixels or guarantee removal of
|
|
108
|
+
arbitrary watermarks. It can also change an image without a detectable watermark.
|
|
109
|
+
Remove before re-watermarking if replacing an existing identifier. Operations on
|
|
110
|
+
a shared remover are serialized internally.
|
|
111
|
+
|
|
62
112
|
### Reader
|
|
63
113
|
|
|
64
114
|
The `Reader` class is used to read and validate C2PA manifests from media files. It can parse embedded manifests or fetch remote manifests. Refer to the [Rust SDK](https://github.com/contentauth/c2pa-rs) for the list of settings and their effects.
|
|
@@ -587,6 +637,7 @@ The library provides helper functions to create and manage settings objects:
|
|
|
587
637
|
import {
|
|
588
638
|
Context,
|
|
589
639
|
createTrustSettings,
|
|
640
|
+
createTsaTrustSettings,
|
|
590
641
|
createCawgTrustSettings,
|
|
591
642
|
createVerifySettings,
|
|
592
643
|
mergeSettings
|
|
@@ -600,10 +651,16 @@ const trustSettings = createTrustSettings({
|
|
|
600
651
|
allowedList: "path/to/allowed-list.pem"
|
|
601
652
|
});
|
|
602
653
|
|
|
654
|
+
// Create timestamp trust settings.
|
|
655
|
+
const tsaTrustSettings = createTsaTrustSettings({
|
|
656
|
+
trustAnchors: "path/to/tsa-anchors.pem"
|
|
657
|
+
});
|
|
658
|
+
|
|
603
659
|
// Create CAWG trust settings
|
|
604
660
|
const cawgTrustSettings = createCawgTrustSettings({
|
|
605
661
|
verifyTrustList: true,
|
|
606
|
-
trustAnchors: "path/to/cawg-anchors.pem"
|
|
662
|
+
trustAnchors: "path/to/cawg-anchors.pem",
|
|
663
|
+
trustedIcaIssuers: ["did:web:example.com"]
|
|
607
664
|
});
|
|
608
665
|
|
|
609
666
|
// Create verify settings
|
|
@@ -633,8 +690,11 @@ Low-level serialization and loading helpers remain available, but their raw JSON
|
|
|
633
690
|
- `verifyTrustList` - Whether to verify against the trust list
|
|
634
691
|
- `userAnchors` - User-provided trust anchors (PEM format or path)
|
|
635
692
|
- `trustAnchors` - Trust anchors for validation (PEM format or path)
|
|
636
|
-
- `trustConfig` - Path to trust configuration file
|
|
637
|
-
- `allowedList` - Allowed list of certificates (PEM format or path)
|
|
693
|
+
- `trustConfig` - Path to trust configuration file. Not available in `tsaTrust`.
|
|
694
|
+
- `allowedList` - Allowed list of certificates (PEM format or path). Not available in `tsaTrust`.
|
|
695
|
+
- `trustedIcaIssuers` - DIDs of identity claims aggregation issuers to trust. Available only in `cawgTrust`.
|
|
696
|
+
|
|
697
|
+
The same fields configure three sections: `trust` for claim signers, `tsaTrust` for timestamps and `cawgTrust` for CAWG identities.
|
|
638
698
|
|
|
639
699
|
**Verify settings:**
|
|
640
700
|
- `verifyAfterReading` - Whether to verify after reading a manifest
|
|
@@ -8,6 +8,7 @@ import * as crypto from "crypto";
|
|
|
8
8
|
import { spawnSync } from "child_process";
|
|
9
9
|
import { once } from "node:events";
|
|
10
10
|
import { createServer } from "node:http";
|
|
11
|
+
import { Context } from "@contentauth/c2pa-utilities";
|
|
11
12
|
import { encodeSignerPayload } from "./index.js";
|
|
12
13
|
class TestSigner {
|
|
13
14
|
privateKey;
|
|
@@ -104,7 +105,7 @@ describe("IdentityAssertionBuilder", () => {
|
|
|
104
105
|
tsaUrl: undefined,
|
|
105
106
|
tsaHeaders: undefined,
|
|
106
107
|
tsaBody: undefined,
|
|
107
|
-
directCoseHandling:
|
|
108
|
+
directCoseHandling: false,
|
|
108
109
|
};
|
|
109
110
|
// Create signers
|
|
110
111
|
const c2paTestSigner = new TestSigner(c2paPrivateKey);
|
|
@@ -142,6 +143,31 @@ describe("IdentityAssertionBuilder", () => {
|
|
|
142
143
|
mimeType: "image/jpeg",
|
|
143
144
|
});
|
|
144
145
|
});
|
|
146
|
+
it("forwards directCoseHandling through the identity signer", async () => {
|
|
147
|
+
const { CallbackSigner } = await import("./Signer.js");
|
|
148
|
+
const { Builder } = await import("./Builder.js");
|
|
149
|
+
const { IdentityAssertionSigner } = await import("./IdentityAssertion.js");
|
|
150
|
+
let calls = 0;
|
|
151
|
+
const signer = CallbackSigner.newSigner({
|
|
152
|
+
alg: "es256",
|
|
153
|
+
certs: [],
|
|
154
|
+
reserveSize: 1000,
|
|
155
|
+
directCoseHandling: true,
|
|
156
|
+
}, async () => {
|
|
157
|
+
calls += 1;
|
|
158
|
+
return Buffer.alloc(100);
|
|
159
|
+
});
|
|
160
|
+
const builder = await Builder.withJsonAsync({
|
|
161
|
+
claim_generator_info: [{ name: "c2pa_test", version: "2.0.0" }],
|
|
162
|
+
format: "image/jpeg",
|
|
163
|
+
assertions: manifestDefinition.assertions,
|
|
164
|
+
}, new Context({ verify: { verifyAfterSign: false } }));
|
|
165
|
+
await expect(builder.signAsync(IdentityAssertionSigner.new(signer.getHandle()), {
|
|
166
|
+
buffer: await fs.readFile("./tests/fixtures/CA.jpg"),
|
|
167
|
+
mimeType: "image/jpeg",
|
|
168
|
+
}, { buffer: null })).resolves.toBeDefined();
|
|
169
|
+
expect(calls).toBe(1);
|
|
170
|
+
});
|
|
145
171
|
it("forwards timestamp requests and failures through the identity signer", async () => {
|
|
146
172
|
const { CallbackSigner } = await import("./Signer.js");
|
|
147
173
|
const { Builder } = await import("./Builder.js");
|
|
@@ -272,7 +298,7 @@ describe("handles reserveSize", () => {
|
|
|
272
298
|
tsaUrl: undefined,
|
|
273
299
|
tsaHeaders: undefined,
|
|
274
300
|
tsaBody: undefined,
|
|
275
|
-
directCoseHandling:
|
|
301
|
+
directCoseHandling: false,
|
|
276
302
|
}, c2paTestSigner.sign);
|
|
277
303
|
const cawgTestSigner = new TestCawgSigner(c2paTestSigner);
|
|
278
304
|
const cawgSigner = CallbackCredentialHolder.newCallbackCredentialHolder(reserveSize, "cawg.x509.cose", cawgTestSigner.sign);
|
package/dist/Reader.spec.js
CHANGED
|
@@ -4,9 +4,12 @@
|
|
|
4
4
|
// or the MIT license (http://opensource.org/licenses/MIT),
|
|
5
5
|
// at your option.
|
|
6
6
|
import path from "path";
|
|
7
|
+
import { createHash, X509Certificate } from "crypto";
|
|
7
8
|
import fs from "fs-extra";
|
|
8
|
-
import { AssetTooLargeError, Context } from "@contentauth/c2pa-utilities";
|
|
9
|
+
import { AssetTooLargeError, Context, } from "@contentauth/c2pa-utilities";
|
|
10
|
+
import { Builder } from "./Builder.js";
|
|
9
11
|
import { Reader } from "./Reader.js";
|
|
12
|
+
import { LocalSigner } from "./Signer.js";
|
|
10
13
|
import { MAX_SIZE_IN_BYTES } from "./assetSize.js";
|
|
11
14
|
const tempDir = path.join(__dirname, "tmp");
|
|
12
15
|
describe("Reader", () => {
|
|
@@ -271,4 +274,60 @@ describe("Reader", () => {
|
|
|
271
274
|
const reader = await Reader.fromAsset(asset);
|
|
272
275
|
expect(reader).toBeNull();
|
|
273
276
|
});
|
|
277
|
+
it("trusts a claim signer pinned from trust.allowedList when no other trust set", async () => {
|
|
278
|
+
const certs = await fs.readFile("./tests/fixtures/certs/es256.pub");
|
|
279
|
+
const privateKey = await fs.readFile("./tests/fixtures/certs/es256.pem");
|
|
280
|
+
const leafHash = createHash("sha256")
|
|
281
|
+
.update(new X509Certificate(certs).raw)
|
|
282
|
+
.digest("base64");
|
|
283
|
+
const builder = await Builder.withJsonAsync({
|
|
284
|
+
claim_generator_info: [{ name: "c2pa-js tests", version: "1.0.0" }],
|
|
285
|
+
title: "allowed-list.jpg",
|
|
286
|
+
format: "image/jpeg",
|
|
287
|
+
assertions: [
|
|
288
|
+
{
|
|
289
|
+
label: "c2pa.actions",
|
|
290
|
+
data: {
|
|
291
|
+
actions: [
|
|
292
|
+
{
|
|
293
|
+
action: "c2pa.created",
|
|
294
|
+
digitalSourceType: "http://cv.iptc.org/newscodes/digitalsourcetype/digitalCapture",
|
|
295
|
+
},
|
|
296
|
+
],
|
|
297
|
+
},
|
|
298
|
+
},
|
|
299
|
+
],
|
|
300
|
+
});
|
|
301
|
+
const dest = { buffer: null };
|
|
302
|
+
builder.sign(LocalSigner.newSigner(certs, privateKey, "es256"), {
|
|
303
|
+
buffer: await fs.readFile("./tests/fixtures/thumbnail.jpg"),
|
|
304
|
+
mimeType: "image/jpeg",
|
|
305
|
+
}, dest);
|
|
306
|
+
const successCodes = async (allowedList) => {
|
|
307
|
+
const reader = await Reader.fromAsset({ buffer: dest.buffer, mimeType: "image/jpeg" }, new Context({ trust: { allowedList } }));
|
|
308
|
+
return (reader
|
|
309
|
+
.json()
|
|
310
|
+
.validation_results?.activeManifest?.success.map((status) => status.code) ?? []);
|
|
311
|
+
};
|
|
312
|
+
const otherHash = createHash("sha256")
|
|
313
|
+
.update(new X509Certificate(await fs.readFile("./tests/fixtures/certs/ed25519.pub")).raw)
|
|
314
|
+
.digest("base64");
|
|
315
|
+
expect(await successCodes(leafHash)).toContain("signingCredential.trusted");
|
|
316
|
+
expect(await successCodes(otherHash)).not.toContain("signingCredential.trusted");
|
|
317
|
+
});
|
|
318
|
+
it("trusts an ICA issuer listed in cawgTrust trustedIcaIssuers", async () => {
|
|
319
|
+
const asset = { path: "./tests/fixtures/cawg_ica_trust.jpg" };
|
|
320
|
+
const issuer = "did:jwk:eyJhbGciOiJFZERTQSIsImt0eSI6Ik9LUCIsImNydiI6IkVkMjU1MTkiLCJ4IjoiTXA1LTBlODNuTmdRaGRoQlc4UnNoa2p5OTBzYTFBOUpJemtJdGNEcUN1SSJ9";
|
|
321
|
+
const activeManifestCodes = async (settings) => {
|
|
322
|
+
const reader = await Reader.fromAsset(asset, new Context(settings));
|
|
323
|
+
const results = reader.json().validation_results?.activeManifest;
|
|
324
|
+
return [
|
|
325
|
+
...(results?.success ?? []),
|
|
326
|
+
...(results?.informational ?? []),
|
|
327
|
+
...(results?.failure ?? []),
|
|
328
|
+
].map((status) => status.code);
|
|
329
|
+
};
|
|
330
|
+
expect(await activeManifestCodes({ cawgTrust: { trustedIcaIssuers: [issuer] } })).toContain("cawg.ica.credential_valid");
|
|
331
|
+
expect(await activeManifestCodes({})).toContain("cawg.ica.untrusted_issuer");
|
|
332
|
+
});
|
|
274
333
|
});
|
package/dist/Trustmark.js
CHANGED
|
@@ -25,4 +25,18 @@ export class Trustmark {
|
|
|
25
25
|
async decode(image) {
|
|
26
26
|
return getNeonBinary().trustmarkDecode.call(this.trustmark, image);
|
|
27
27
|
}
|
|
28
|
+
/**
|
|
29
|
+
* Remove a P/Q watermark from an 8-bit JPEG or PNG, returning an encoded PNG
|
|
30
|
+
* with the same dimensions and alpha. Requires `loadRemover: true`.
|
|
31
|
+
* Removal is lossy and does not guarantee restoration of the original pixels.
|
|
32
|
+
* Input is limited to 64 MiB, 16,384 pixels per dimension, and 32 million
|
|
33
|
+
* pixels, with a best-effort 128 MiB decoder allocation budget. Limits are
|
|
34
|
+
* per call, not a cap on total process memory.
|
|
35
|
+
* Image metadata (EXIF, XMP, ICC profiles, and C2PA manifests) is not copied.
|
|
36
|
+
* Existing credentials do not remain valid for the modified pixels; sign a
|
|
37
|
+
* new manifest to attach valid Content Credentials to the output.
|
|
38
|
+
*/
|
|
39
|
+
async remove(image) {
|
|
40
|
+
return getNeonBinary().trustmarkRemove.call(this.trustmark, image);
|
|
41
|
+
}
|
|
28
42
|
}
|
package/dist/Trustmark.spec.js
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
// specific language governing permissions and limitations under
|
|
11
11
|
// each license.
|
|
12
12
|
import path from "path";
|
|
13
|
+
import os from "os";
|
|
13
14
|
import fs from "fs-extra";
|
|
14
15
|
import sharp from "sharp";
|
|
15
16
|
import { Trustmark } from "./Trustmark.js";
|
|
@@ -24,8 +25,24 @@ async function rawRgbToJpeg(rawRgbData, width, height) {
|
|
|
24
25
|
channels: 3, // RGB
|
|
25
26
|
},
|
|
26
27
|
});
|
|
27
|
-
//
|
|
28
|
-
return await image.jpeg().toBuffer();
|
|
28
|
+
// Use a high-quality JPEG round-trip for the perceptual P model.
|
|
29
|
+
return await image.jpeg({ quality: 95 }).toBuffer();
|
|
30
|
+
}
|
|
31
|
+
// Modify only the PNG header so oversized-image tests never allocate its pixels.
|
|
32
|
+
function pngWithDimensions(png, width, height) {
|
|
33
|
+
const image = Buffer.from(png);
|
|
34
|
+
expect(image.toString("ascii", 12, 16)).toBe("IHDR");
|
|
35
|
+
image.writeUInt32BE(width, 16);
|
|
36
|
+
image.writeUInt32BE(height, 20);
|
|
37
|
+
let crc = 0xffffffff;
|
|
38
|
+
for (const byte of image.subarray(12, 29)) {
|
|
39
|
+
crc ^= byte;
|
|
40
|
+
for (let bit = 0; bit < 8; bit++) {
|
|
41
|
+
crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
image.writeUInt32BE((crc ^ 0xffffffff) >>> 0, 29);
|
|
45
|
+
return image;
|
|
29
46
|
}
|
|
30
47
|
describe("Trustmark", () => {
|
|
31
48
|
let trustmark;
|
|
@@ -33,14 +50,17 @@ describe("Trustmark", () => {
|
|
|
33
50
|
let testImageWidth;
|
|
34
51
|
let testImageHeight;
|
|
35
52
|
const trustmarkConfig = {
|
|
36
|
-
variant: "
|
|
37
|
-
version: "
|
|
53
|
+
variant: "P", // Perceptual model, cached in CI
|
|
54
|
+
version: "BCH_5", // Tolerates 5 bit flips
|
|
38
55
|
modelPath: path.join(tempDir, "trustmark_models"), // Use temporary directory for model path
|
|
39
56
|
};
|
|
40
57
|
beforeAll(async () => {
|
|
41
58
|
await fs.ensureDir(tempDir);
|
|
42
59
|
// Use an actual test image from fixtures directory
|
|
43
|
-
testImage = await
|
|
60
|
+
testImage = await sharp("./tests/fixtures/A.jpg")
|
|
61
|
+
.resize(512, 512)
|
|
62
|
+
.png()
|
|
63
|
+
.toBuffer();
|
|
44
64
|
// Get image dimensions for converting raw pixel data
|
|
45
65
|
const imageInfo = await sharp(testImage).metadata();
|
|
46
66
|
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
@@ -93,8 +113,8 @@ describe("Trustmark", () => {
|
|
|
93
113
|
});
|
|
94
114
|
describe("decode", () => {
|
|
95
115
|
it("should decode a watermark from an encoded image", async () => {
|
|
96
|
-
const strength = 0.
|
|
97
|
-
const customWatermark = "
|
|
116
|
+
const strength = 0.95;
|
|
117
|
+
const customWatermark = "1011011110011000111111000000011111011111011100000110110110111";
|
|
98
118
|
// First encode a watermark
|
|
99
119
|
const rawPixelData = await trustmark.encode(testImage, strength, customWatermark);
|
|
100
120
|
// Convert raw pixel data to JPEG format for decoding
|
|
@@ -105,10 +125,10 @@ describe("Trustmark", () => {
|
|
|
105
125
|
expect(typeof decodedWatermark).toBe("string");
|
|
106
126
|
expect(decodedWatermark.length).toBeGreaterThan(0);
|
|
107
127
|
// The decoded watermark should match the original
|
|
108
|
-
expect(decodedWatermark.
|
|
128
|
+
expect(decodedWatermark).toBe(customWatermark);
|
|
109
129
|
}, 30000);
|
|
110
130
|
it("should decode watermark from image with generated watermark", async () => {
|
|
111
|
-
const strength = 0.
|
|
131
|
+
const strength = 0.95;
|
|
112
132
|
// Encode with default watermark
|
|
113
133
|
const rawPixelData = await trustmark.encode(testImage, strength);
|
|
114
134
|
// Convert raw pixel data to JPEG format for decoding
|
|
@@ -128,4 +148,222 @@ describe("Trustmark", () => {
|
|
|
128
148
|
await expect(trustmark.decode(emptyBuffer)).rejects.toThrow("The image format could not be determined");
|
|
129
149
|
}, 30000);
|
|
130
150
|
});
|
|
151
|
+
it("rejects removal when not opted in", async () => {
|
|
152
|
+
await expect(trustmark.remove(testImage)).rejects.toThrow("Watermark remover not loaded");
|
|
153
|
+
});
|
|
154
|
+
});
|
|
155
|
+
describe("Trustmark removal configuration", () => {
|
|
156
|
+
it.each(["B", "C"])("rejects unsupported variant %s before creating the model directory", async (variant) => {
|
|
157
|
+
const root = await fs.mkdtemp(path.join(os.tmpdir(), "trustmark-config-"));
|
|
158
|
+
const modelPath = path.join(root, "models");
|
|
159
|
+
try {
|
|
160
|
+
await expect(Trustmark.newTrustmark({
|
|
161
|
+
variant,
|
|
162
|
+
version: "BCH_5",
|
|
163
|
+
loadRemover: true,
|
|
164
|
+
modelPath,
|
|
165
|
+
})).rejects.toThrow("removal supports only P/Q variants");
|
|
166
|
+
expect(await fs.pathExists(modelPath)).toBe(false);
|
|
167
|
+
}
|
|
168
|
+
finally {
|
|
169
|
+
await fs.remove(root);
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
});
|
|
173
|
+
describe("Trustmark P removal", () => {
|
|
174
|
+
const variant = "P";
|
|
175
|
+
let runner;
|
|
176
|
+
let source;
|
|
177
|
+
const modelPath = path.join(tempDir, "trustmark_models");
|
|
178
|
+
const original = "1011011110011000111111000000011111011111011100000110110110111";
|
|
179
|
+
const replacement = "0011011110011000111111000000011111011111011100000110110110111";
|
|
180
|
+
beforeAll(async () => {
|
|
181
|
+
runner = await Trustmark.newTrustmark({
|
|
182
|
+
variant,
|
|
183
|
+
version: "BCH_5",
|
|
184
|
+
loadRemover: true,
|
|
185
|
+
modelPath,
|
|
186
|
+
});
|
|
187
|
+
source = await sharp("./tests/fixtures/A.jpg")
|
|
188
|
+
.resize(512, 512)
|
|
189
|
+
.png()
|
|
190
|
+
.toBuffer();
|
|
191
|
+
}, 180000);
|
|
192
|
+
it.each(["jpeg", "png"])("removes the old watermark and allows re-watermarking a %s", async (format) => {
|
|
193
|
+
const raw = await runner.encode(source, 0.95, original);
|
|
194
|
+
const encoded = await sharp(raw, {
|
|
195
|
+
raw: { width: 512, height: 512, channels: 3 },
|
|
196
|
+
})
|
|
197
|
+
.toFormat(format, { quality: 95 })
|
|
198
|
+
.toBuffer();
|
|
199
|
+
expect(await runner.decode(encoded)).toBe(original);
|
|
200
|
+
const recovered = await runner.remove(encoded);
|
|
201
|
+
expect(await sharp(recovered).metadata()).toMatchObject({
|
|
202
|
+
format: "png",
|
|
203
|
+
width: 512,
|
|
204
|
+
height: 512,
|
|
205
|
+
channels: 3,
|
|
206
|
+
hasAlpha: false,
|
|
207
|
+
});
|
|
208
|
+
const decoded = await runner.decode(recovered).catch((error) => {
|
|
209
|
+
expect(error).toBeInstanceOf(Error);
|
|
210
|
+
if (!(error instanceof Error))
|
|
211
|
+
throw error;
|
|
212
|
+
expect(error.message).toContain("watermark is corrupt or missing");
|
|
213
|
+
});
|
|
214
|
+
expect(decoded).not.toBe(original);
|
|
215
|
+
const reencoded = await runner.encode(recovered, 0.95, replacement);
|
|
216
|
+
const png = await sharp(reencoded, {
|
|
217
|
+
raw: { width: 512, height: 512, channels: 3 },
|
|
218
|
+
})
|
|
219
|
+
.png()
|
|
220
|
+
.toBuffer();
|
|
221
|
+
expect(await runner.decode(png)).toBe(replacement);
|
|
222
|
+
}, 60000);
|
|
223
|
+
it("preserves dimensions and exact alpha on unwatermarked images concurrently", async () => {
|
|
224
|
+
await Promise.all([
|
|
225
|
+
[17, 11],
|
|
226
|
+
[11, 17],
|
|
227
|
+
].map(async ([width, height]) => {
|
|
228
|
+
const rgba = Buffer.alloc(width * height * 4);
|
|
229
|
+
for (let i = 0; i < rgba.length; i += 4) {
|
|
230
|
+
rgba.set([120, 80, 160, (i / 4) % 256], i);
|
|
231
|
+
}
|
|
232
|
+
const input = await sharp(rgba, {
|
|
233
|
+
raw: { width, height, channels: 4 },
|
|
234
|
+
})
|
|
235
|
+
.png()
|
|
236
|
+
.toBuffer();
|
|
237
|
+
const output = await runner.remove(input);
|
|
238
|
+
const { data, info } = await sharp(output)
|
|
239
|
+
.raw()
|
|
240
|
+
.toBuffer({ resolveWithObject: true });
|
|
241
|
+
expect(info).toMatchObject({ width, height, channels: 4 });
|
|
242
|
+
for (let i = 3; i < rgba.length; i += 4) {
|
|
243
|
+
expect(data[i]).toBe(rgba[i]);
|
|
244
|
+
}
|
|
245
|
+
}));
|
|
246
|
+
}, 30000);
|
|
247
|
+
it("rejects invalid and unsupported input then remains usable", async () => {
|
|
248
|
+
const gif = await sharp(source).gif().toBuffer();
|
|
249
|
+
for (const invalid of [
|
|
250
|
+
Buffer.alloc(0),
|
|
251
|
+
Buffer.from("not an image"),
|
|
252
|
+
source.subarray(0, 40),
|
|
253
|
+
gif,
|
|
254
|
+
]) {
|
|
255
|
+
await expect(runner.remove(invalid)).rejects.toThrow();
|
|
256
|
+
}
|
|
257
|
+
expect(await sharp(await runner.remove(source)).metadata()).toMatchObject({
|
|
258
|
+
width: 512,
|
|
259
|
+
height: 512,
|
|
260
|
+
});
|
|
261
|
+
}, 30000);
|
|
262
|
+
it("rejects 16-bit PNG input", async () => {
|
|
263
|
+
const input = await sharp(source).toColourspace("rgb16").png().toBuffer();
|
|
264
|
+
expect(await sharp(input).metadata()).toMatchObject({ bitsPerSample: 16 });
|
|
265
|
+
await expect(runner.remove(input)).rejects.toThrow("removal supports only 8-bit JPEG/PNG images");
|
|
266
|
+
});
|
|
267
|
+
it("rejects encoded input larger than 64 MiB before reading its contents", async () => {
|
|
268
|
+
const oversized = Buffer.alloc(64 * 1024 * 1024 + 1);
|
|
269
|
+
await expect(runner.remove(oversized)).rejects.toThrow("removal input exceeds 64 MiB");
|
|
270
|
+
});
|
|
271
|
+
it.each([
|
|
272
|
+
[16385, 1],
|
|
273
|
+
[1, 16385],
|
|
274
|
+
])("rejects dimensions %i x %i before decoding pixels", async (width, height) => {
|
|
275
|
+
const input = pngWithDimensions(source, width, height);
|
|
276
|
+
await expect(runner.remove(input)).rejects.toThrow(/limit/i);
|
|
277
|
+
});
|
|
278
|
+
it("rejects more than 32 million pixels before decoding pixels", async () => {
|
|
279
|
+
const input = pngWithDimensions(source, 8000, 4001);
|
|
280
|
+
await expect(runner.remove(input)).rejects.toThrow("removal image exceeds 32000000 pixels");
|
|
281
|
+
});
|
|
282
|
+
it("accepts the dimension boundary and remains usable after rejected input", async () => {
|
|
283
|
+
const input = await sharp({
|
|
284
|
+
create: {
|
|
285
|
+
width: 16384,
|
|
286
|
+
height: 1,
|
|
287
|
+
channels: 3,
|
|
288
|
+
background: { r: 120, g: 80, b: 160 },
|
|
289
|
+
},
|
|
290
|
+
})
|
|
291
|
+
.png()
|
|
292
|
+
.toBuffer();
|
|
293
|
+
const output = await runner.remove(input);
|
|
294
|
+
expect(await sharp(output).metadata()).toMatchObject({
|
|
295
|
+
format: "png",
|
|
296
|
+
width: 16384,
|
|
297
|
+
height: 1,
|
|
298
|
+
channels: 3,
|
|
299
|
+
});
|
|
300
|
+
}, 30000);
|
|
301
|
+
it("does not download or load a remover by default or with loadRemover false", async () => {
|
|
302
|
+
const root = await fs.mkdtemp(path.join(os.tmpdir(), "trustmark-opt-in-"));
|
|
303
|
+
try {
|
|
304
|
+
for (const name of ["encoder", "decoder"]) {
|
|
305
|
+
const filename = `${name}_${variant}.onnx`;
|
|
306
|
+
await fs.copyFile(path.join(modelPath, filename), path.join(root, filename));
|
|
307
|
+
}
|
|
308
|
+
for (const loadRemover of [undefined, false]) {
|
|
309
|
+
const disabled = await Trustmark.newTrustmark({
|
|
310
|
+
variant,
|
|
311
|
+
version: "BCH_5",
|
|
312
|
+
modelPath: root,
|
|
313
|
+
loadRemover,
|
|
314
|
+
});
|
|
315
|
+
await expect(disabled.remove(source)).rejects.toThrow("Watermark remover not loaded");
|
|
316
|
+
}
|
|
317
|
+
expect(await fs.pathExists(path.join(root, `remover_${variant}.onnx`))).toBe(false);
|
|
318
|
+
}
|
|
319
|
+
finally {
|
|
320
|
+
await fs.remove(root);
|
|
321
|
+
}
|
|
322
|
+
}, 30000);
|
|
323
|
+
it("rejects initialization with an invalid remover instead of falling back", async () => {
|
|
324
|
+
const root = await fs.mkdtemp(path.join(os.tmpdir(), "trustmark-invalid-model-"));
|
|
325
|
+
try {
|
|
326
|
+
for (const name of ["encoder", "decoder"]) {
|
|
327
|
+
const filename = `${name}_${variant}.onnx`;
|
|
328
|
+
await fs.copyFile(path.join(modelPath, filename), path.join(root, filename));
|
|
329
|
+
}
|
|
330
|
+
await fs.writeFile(path.join(root, `remover_${variant}.onnx`), "invalid ONNX");
|
|
331
|
+
await expect(Trustmark.newTrustmark({
|
|
332
|
+
variant,
|
|
333
|
+
version: "BCH_5",
|
|
334
|
+
modelPath: root,
|
|
335
|
+
loadRemover: true,
|
|
336
|
+
})).rejects.toThrow(`unable to load remover model ${path.join(root, `remover_${variant}.onnx`)}`);
|
|
337
|
+
}
|
|
338
|
+
finally {
|
|
339
|
+
await fs.remove(root);
|
|
340
|
+
}
|
|
341
|
+
}, 30000);
|
|
342
|
+
it("rejects non-finite inference output instead of returning an image", async () => {
|
|
343
|
+
const root = await fs.mkdtemp(path.join(os.tmpdir(), "trustmark-inference-"));
|
|
344
|
+
try {
|
|
345
|
+
for (const name of ["encoder", "decoder"]) {
|
|
346
|
+
const filename = `${name}_${variant}.onnx`;
|
|
347
|
+
await fs.copyFile(path.join(modelPath, filename), path.join(root, filename));
|
|
348
|
+
}
|
|
349
|
+
// ONNX opset 13 ConstantOfShape graph: declares float32 [1, 3, 256, 256]
|
|
350
|
+
// input/output, but returns NaN pixels. Loading succeeds; inference fails
|
|
351
|
+
// TrustMark's output validation, exercising the native promise error path.
|
|
352
|
+
const model = Buffer.from("CAg6wwEKOAoFc2hhcGUSBm91dHB1dCIPQ29uc3RhbnRPZlNoYXBlKhYKBXZhbHVlKgoIARABSgQAAMB/oAEEEhFub25maW5pdGVfcmVtb3ZlciotCAQQB0IFc2hhcGVKIAEAAAAAAAAAAwAAAAAAAAAAAQAAAAAAAAABAAAAAAAAWiEKBWlucHV0EhgKFggBEhIKAggBCgIIAwoDCIACCgMIgAJiIgoGb3V0cHV0EhgKFggBEhIKAggBCgIIAwoDCIACCgMIgAJCAhAN", "base64");
|
|
353
|
+
await fs.writeFile(path.join(root, `remover_${variant}.onnx`), model);
|
|
354
|
+
const invalid = await Trustmark.newTrustmark({
|
|
355
|
+
variant,
|
|
356
|
+
version: "BCH_5",
|
|
357
|
+
modelPath: root,
|
|
358
|
+
loadRemover: true,
|
|
359
|
+
});
|
|
360
|
+
// Repeated failures must reject without poisoning the shared remover.
|
|
361
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
362
|
+
await expect(invalid.remove(source)).rejects.toThrow("invalid remover model");
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
finally {
|
|
366
|
+
await fs.remove(root);
|
|
367
|
+
}
|
|
368
|
+
}, 30000);
|
|
131
369
|
});
|
package/dist/index.node
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
[diffend] Oversized file quarantined before diffing.
|
|
2
2
|
name: package/dist/index.node
|
|
3
|
-
size:
|
|
4
|
-
sha256:
|
|
3
|
+
size: 52405720 bytes
|
|
4
|
+
sha256: 2d95b6b5e5c989c5ae5eb4ed43c941fe12527bd9010c36150394fbe22513ce71
|
|
@@ -5,4 +5,16 @@ export declare class Trustmark implements TrustmarkInterface {
|
|
|
5
5
|
static newTrustmark(config: TrustmarkConfig): Promise<Trustmark>;
|
|
6
6
|
encode(image: Buffer, strength: number, watermark?: string): Promise<Buffer>;
|
|
7
7
|
decode(image: Buffer): Promise<string>;
|
|
8
|
+
/**
|
|
9
|
+
* Remove a P/Q watermark from an 8-bit JPEG or PNG, returning an encoded PNG
|
|
10
|
+
* with the same dimensions and alpha. Requires `loadRemover: true`.
|
|
11
|
+
* Removal is lossy and does not guarantee restoration of the original pixels.
|
|
12
|
+
* Input is limited to 64 MiB, 16,384 pixels per dimension, and 32 million
|
|
13
|
+
* pixels, with a best-effort 128 MiB decoder allocation budget. Limits are
|
|
14
|
+
* per call, not a cap on total process memory.
|
|
15
|
+
* Image metadata (EXIF, XMP, ICC profiles, and C2PA manifests) is not copied.
|
|
16
|
+
* Existing credentials do not remain valid for the modified pixels; sign a
|
|
17
|
+
* new manifest to attach valid Content Credentials to the output.
|
|
18
|
+
*/
|
|
19
|
+
remove(image: Buffer): Promise<Buffer>;
|
|
8
20
|
}
|
package/dist/types/types.d.ts
CHANGED
|
@@ -523,10 +523,32 @@ export interface TrustmarkInterface {
|
|
|
523
523
|
* @param image image to extract the watermark from (must be in a supported image format like JPEG, PNG, etc.)
|
|
524
524
|
*/
|
|
525
525
|
decode(image: Buffer): Promise<string>;
|
|
526
|
+
|
|
527
|
+
/**
|
|
528
|
+
* Remove a P/Q watermark using the separately loaded removal model.
|
|
529
|
+
* Requires `loadRemover: true`; rejects unsupported input and removal failures.
|
|
530
|
+
* Removal is lossy, may change unwatermarked images, and does not guarantee
|
|
531
|
+
* restoration of original pixels or removal of arbitrary watermarks.
|
|
532
|
+
* Rejects inputs exceeding 64 MiB, 16,384 pixels per dimension, or 32 million
|
|
533
|
+
* pixels. Decoding has a best-effort 128 MiB allocation budget; limits are
|
|
534
|
+
* per call, not a cap on total process memory.
|
|
535
|
+
* Image metadata (EXIF, XMP, ICC profiles, and C2PA manifests) is not copied.
|
|
536
|
+
* Existing credentials do not remain valid for the modified pixels; sign a
|
|
537
|
+
* new manifest to attach valid Content Credentials to the output.
|
|
538
|
+
* @param image An 8-bit JPEG or PNG (RGB, RGBA, or grayscale)
|
|
539
|
+
* @returns Encoded PNG preserving dimensions and alpha, not raw pixel data
|
|
540
|
+
*/
|
|
541
|
+
remove(image: Buffer): Promise<Buffer>;
|
|
526
542
|
}
|
|
527
543
|
|
|
528
544
|
export interface TrustmarkConfig {
|
|
529
545
|
variant: TrustmarkVariant;
|
|
530
546
|
version: TrustmarkVersion;
|
|
531
547
|
modelPath?: string;
|
|
548
|
+
/**
|
|
549
|
+
* Load/download the separate `remover_P.onnx` or `remover_Q.onnx` model.
|
|
550
|
+
* Only supported for P/Q. Defaults to false to avoid additional downloads,
|
|
551
|
+
* startup time, and memory usage. Uses the same `modelPath` as encode/decode.
|
|
552
|
+
*/
|
|
553
|
+
loadRemover?: boolean;
|
|
532
554
|
}
|
package/package.json
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
"url": "git+https://github.com/contentauth/c2pa-js.git",
|
|
6
6
|
"directory": "packages/c2pa-node"
|
|
7
7
|
},
|
|
8
|
-
"version": "0.
|
|
8
|
+
"version": "0.12.1",
|
|
9
9
|
"description": "Node.js bindings for C2PA",
|
|
10
10
|
"main": "dist/index.js",
|
|
11
11
|
"type": "module",
|
|
@@ -65,7 +65,7 @@
|
|
|
65
65
|
"pretty-bytes": "^6.1.1",
|
|
66
66
|
"unzipper": "^0.10.14",
|
|
67
67
|
"@contentauth/c2pa-types": "0.8.0",
|
|
68
|
-
"@contentauth/c2pa-utilities": "0.5.
|
|
68
|
+
"@contentauth/c2pa-utilities": "0.5.2"
|
|
69
69
|
},
|
|
70
70
|
"nx": {
|
|
71
71
|
"tags": [
|
package/src/lib.rs
CHANGED
|
@@ -214,6 +214,7 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> {
|
|
|
214
214
|
)?;
|
|
215
215
|
cx.export_function("trustmarkEncode", neon_trustmark::NeonTrustmark::encode)?;
|
|
216
216
|
cx.export_function("trustmarkDecode", neon_trustmark::NeonTrustmark::decode)?;
|
|
217
|
+
cx.export_function("trustmarkRemove", neon_trustmark::NeonTrustmark::remove)?;
|
|
217
218
|
|
|
218
219
|
Ok(())
|
|
219
220
|
}
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
// each license.
|
|
13
13
|
|
|
14
14
|
use std::ops::Deref;
|
|
15
|
-
use std::sync::RwLock;
|
|
15
|
+
use std::sync::{PoisonError, RwLock};
|
|
16
16
|
|
|
17
17
|
use async_trait::async_trait;
|
|
18
18
|
use c2pa::{
|
|
@@ -144,6 +144,11 @@ impl AsyncSigner for NeonIdentityAssertionSigner {
|
|
|
144
144
|
c2pa::AsyncSigner::send_timestamp_request(&signer, message, context).await
|
|
145
145
|
}
|
|
146
146
|
|
|
147
|
+
fn direct_cose_handling(&self) -> bool {
|
|
148
|
+
let signer = self.signer.read().unwrap_or_else(PoisonError::into_inner);
|
|
149
|
+
c2pa::AsyncSigner::direct_cose_handling(&*signer)
|
|
150
|
+
}
|
|
151
|
+
|
|
147
152
|
fn dynamic_assertions(&self) -> Vec<Box<dyn AsyncDynamicAssertion>> {
|
|
148
153
|
let mut identity_assertions = self.identity_assertions.write().unwrap();
|
|
149
154
|
let ia_clone = identity_assertions.split_off(0);
|
package/src/neon_trustmark.rs
CHANGED
|
@@ -13,18 +13,19 @@
|
|
|
13
13
|
|
|
14
14
|
use std::{
|
|
15
15
|
fs::OpenOptions,
|
|
16
|
-
io::Write,
|
|
16
|
+
io::{Cursor, Write},
|
|
17
17
|
path::PathBuf,
|
|
18
18
|
sync::{Arc, Mutex},
|
|
19
19
|
time::Duration,
|
|
20
20
|
};
|
|
21
21
|
|
|
22
|
+
use image::ImageDecoder as _;
|
|
22
23
|
use neon::prelude::*;
|
|
23
24
|
use neon::result::{JsResult, NeonResult};
|
|
24
25
|
use neon::types::{buffer::TypedArray, Finalize, JsObject};
|
|
25
26
|
use rand::{distributions::Standard, prelude::Distribution as _};
|
|
26
27
|
use reqwest::Client;
|
|
27
|
-
use trustmark::{Trustmark, Variant, Version};
|
|
28
|
+
use trustmark::{Trustmark, Variant, Version, WatermarkRemover};
|
|
28
29
|
|
|
29
30
|
use crate::error::{as_js_error, as_js_error_fn, Error, Result};
|
|
30
31
|
use crate::runtime::runtime;
|
|
@@ -34,12 +35,14 @@ pub struct WatermarkConfig {
|
|
|
34
35
|
variant: Variant,
|
|
35
36
|
version: Version,
|
|
36
37
|
model_path: PathBuf,
|
|
38
|
+
load_remover: bool,
|
|
37
39
|
}
|
|
38
40
|
|
|
39
41
|
pub struct NeonTrustmark {
|
|
40
42
|
// All Trustmark calls are synchronous, so the standard Mutex works.
|
|
41
43
|
trustmark: Arc<Mutex<Trustmark>>,
|
|
42
44
|
version: Version,
|
|
45
|
+
remover: Option<Arc<WatermarkRemover>>,
|
|
43
46
|
}
|
|
44
47
|
|
|
45
48
|
impl Finalize for NeonTrustmark {}
|
|
@@ -79,10 +82,19 @@ pub fn parse_watermark_config(
|
|
|
79
82
|
.map(|val| std::path::PathBuf::from(val.value(cx)))
|
|
80
83
|
.unwrap_or_else(|| PathBuf::from("./models"));
|
|
81
84
|
|
|
85
|
+
let load_remover = obj
|
|
86
|
+
.get_opt::<JsBoolean, _, _>(cx, "loadRemover")?
|
|
87
|
+
.is_some_and(|value| value.value(cx));
|
|
88
|
+
|
|
89
|
+
if load_remover && !matches!(variant, Variant::P | Variant::Q) {
|
|
90
|
+
return cx.throw_error("Watermark configuration error: removal supports only P/Q variants");
|
|
91
|
+
}
|
|
92
|
+
|
|
82
93
|
Ok(WatermarkConfig {
|
|
83
94
|
variant,
|
|
84
95
|
version,
|
|
85
96
|
model_path,
|
|
97
|
+
load_remover,
|
|
86
98
|
})
|
|
87
99
|
}
|
|
88
100
|
|
|
@@ -110,9 +122,25 @@ impl NeonTrustmark {
|
|
|
110
122
|
Err(err) => return as_js_error_fn(&mut cx, err.into()).and_then(|err| cx.throw(err)),
|
|
111
123
|
};
|
|
112
124
|
|
|
125
|
+
let remover = if config.load_remover {
|
|
126
|
+
let result = fetch_models(
|
|
127
|
+
&config.model_path,
|
|
128
|
+
&[format!("remover_{}.onnx", config.variant)],
|
|
129
|
+
)
|
|
130
|
+
.and_then(|path| WatermarkRemover::new(path, config.variant).map_err(Error::Watermark));
|
|
131
|
+
|
|
132
|
+
match result {
|
|
133
|
+
Ok(remover) => Some(Arc::new(remover)),
|
|
134
|
+
Err(err) => return as_js_error_fn(&mut cx, err).and_then(|err| cx.throw(err)),
|
|
135
|
+
}
|
|
136
|
+
} else {
|
|
137
|
+
None
|
|
138
|
+
};
|
|
139
|
+
|
|
113
140
|
Ok(cx.boxed(Self {
|
|
114
141
|
trustmark: Arc::new(Mutex::new(trustmark)),
|
|
115
142
|
version: config.version,
|
|
143
|
+
remover,
|
|
116
144
|
}))
|
|
117
145
|
}
|
|
118
146
|
|
|
@@ -137,8 +165,8 @@ impl NeonTrustmark {
|
|
|
137
165
|
|
|
138
166
|
let promise = cx
|
|
139
167
|
.task(move || {
|
|
140
|
-
let trustmark = trustmark.lock()?;
|
|
141
168
|
let image = image::load_from_memory(&image_bytes)?;
|
|
169
|
+
let trustmark = trustmark.lock()?;
|
|
142
170
|
let watermark = watermark.unwrap_or_else(|| gen_watermark(version));
|
|
143
171
|
let watermarked_image = trustmark
|
|
144
172
|
.encode(watermark, image, strength)
|
|
@@ -156,6 +184,31 @@ impl NeonTrustmark {
|
|
|
156
184
|
Ok(promise)
|
|
157
185
|
}
|
|
158
186
|
|
|
187
|
+
pub fn remove(mut cx: FunctionContext) -> JsResult<JsPromise> {
|
|
188
|
+
let this = cx.this::<JsBox<Self>>()?;
|
|
189
|
+
let Some(remover) = this.remover.clone() else {
|
|
190
|
+
return cx.throw_error(
|
|
191
|
+
"Watermark remover not loaded; initialize Trustmark with loadRemover: true",
|
|
192
|
+
);
|
|
193
|
+
};
|
|
194
|
+
let buffer = cx.argument::<JsBuffer>(0)?;
|
|
195
|
+
let image_bytes = buffer.as_slice(&cx);
|
|
196
|
+
if image_bytes.len() > MAX_REMOVAL_INPUT_BYTES {
|
|
197
|
+
let error = Error::WatermarkConfiguration("removal input exceeds 64 MiB".to_string());
|
|
198
|
+
return as_js_error_fn(&mut cx, error).and_then(|err| cx.throw(err));
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
let image_bytes = image_bytes.to_vec();
|
|
202
|
+
let promise = cx
|
|
203
|
+
.task(move || remove_image(&image_bytes, &remover))
|
|
204
|
+
.promise(move |mut cx, result: Result<Vec<u8>>| match result {
|
|
205
|
+
Ok(png) => JsBuffer::from_slice(&mut cx, &png),
|
|
206
|
+
Err(err) => as_js_error(&mut cx, err).and_then(|err| cx.throw(err)),
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
Ok(promise)
|
|
210
|
+
}
|
|
211
|
+
|
|
159
212
|
pub fn decode(mut cx: FunctionContext) -> JsResult<JsPromise> {
|
|
160
213
|
let this = cx.this::<JsBox<Self>>()?;
|
|
161
214
|
let trustmark = this.trustmark.clone();
|
|
@@ -164,8 +217,8 @@ impl NeonTrustmark {
|
|
|
164
217
|
|
|
165
218
|
let promise = cx
|
|
166
219
|
.task(move || {
|
|
167
|
-
let trustmark = trustmark.lock()?;
|
|
168
220
|
let image = image::load_from_memory(&image_bytes)?;
|
|
221
|
+
let trustmark = trustmark.lock()?;
|
|
169
222
|
let watermark = trustmark.decode(image)?;
|
|
170
223
|
Ok(watermark)
|
|
171
224
|
})
|
|
@@ -177,6 +230,65 @@ impl NeonTrustmark {
|
|
|
177
230
|
}
|
|
178
231
|
}
|
|
179
232
|
|
|
233
|
+
// Bound the input copy, decoding, and the full-resolution buffers allocated by
|
|
234
|
+
// removal. These are per-call limits, not a process-wide concurrency budget.
|
|
235
|
+
const MAX_REMOVAL_INPUT_BYTES: usize = 64 * 1024 * 1024;
|
|
236
|
+
const MAX_REMOVAL_DIMENSION: u32 = 16_384;
|
|
237
|
+
const MAX_REMOVAL_PIXELS: u64 = 32_000_000;
|
|
238
|
+
const MAX_REMOVAL_DECODE_BYTES: u64 = 128 * 1024 * 1024;
|
|
239
|
+
|
|
240
|
+
fn remove_image(bytes: &[u8], remover: &WatermarkRemover) -> Result<Vec<u8>> {
|
|
241
|
+
let format = image::guess_format(bytes)?;
|
|
242
|
+
if !matches!(format, image::ImageFormat::Jpeg | image::ImageFormat::Png) {
|
|
243
|
+
return Err(Error::WatermarkConfiguration(
|
|
244
|
+
"removal supports only 8-bit JPEG/PNG images".to_string(),
|
|
245
|
+
));
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
let mut limits = image::Limits::default();
|
|
249
|
+
limits.max_image_width = Some(MAX_REMOVAL_DIMENSION);
|
|
250
|
+
limits.max_image_height = Some(MAX_REMOVAL_DIMENSION);
|
|
251
|
+
limits.max_alloc = Some(MAX_REMOVAL_DECODE_BYTES);
|
|
252
|
+
let mut reader = image::ImageReader::with_format(Cursor::new(bytes), format);
|
|
253
|
+
reader.limits(limits.clone());
|
|
254
|
+
let mut decoder = reader.into_decoder()?;
|
|
255
|
+
let (width, height) = decoder.dimensions();
|
|
256
|
+
if u64::from(width) * u64::from(height) > MAX_REMOVAL_PIXELS {
|
|
257
|
+
return Err(Error::WatermarkConfiguration(
|
|
258
|
+
"removal image exceeds 32000000 pixels".to_string(),
|
|
259
|
+
));
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
if !matches!(
|
|
263
|
+
decoder.color_type(),
|
|
264
|
+
image::ColorType::L8
|
|
265
|
+
| image::ColorType::La8
|
|
266
|
+
| image::ColorType::Rgb8
|
|
267
|
+
| image::ColorType::Rgba8
|
|
268
|
+
) {
|
|
269
|
+
return Err(Error::WatermarkConfiguration(
|
|
270
|
+
"removal supports only 8-bit JPEG/PNG images".to_string(),
|
|
271
|
+
));
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// Include the decoded image buffer in the allocation budget, as
|
|
275
|
+
// ImageReader::decode does. from_decoder does not reserve it itself.
|
|
276
|
+
limits.reserve(decoder.total_bytes())?;
|
|
277
|
+
decoder.set_limits(limits)?;
|
|
278
|
+
let image = image::DynamicImage::from_decoder(decoder)?;
|
|
279
|
+
let has_alpha = image.color().has_alpha();
|
|
280
|
+
let recovered = remover.remove(image).map_err(Error::Watermark)?;
|
|
281
|
+
let output = if has_alpha {
|
|
282
|
+
image::DynamicImage::ImageRgba8(recovered.to_rgba8())
|
|
283
|
+
} else {
|
|
284
|
+
image::DynamicImage::ImageRgb8(recovered.to_rgb8())
|
|
285
|
+
};
|
|
286
|
+
let mut png = Cursor::new(Vec::new());
|
|
287
|
+
output.write_to(&mut png, image::ImageFormat::Png)?;
|
|
288
|
+
|
|
289
|
+
Ok(png.into_inner())
|
|
290
|
+
}
|
|
291
|
+
|
|
180
292
|
fn check_strength(strength: f32) -> Result<()> {
|
|
181
293
|
if !(0.0..=1.0).contains(&strength) {
|
|
182
294
|
return Err(Error::WatermarkConfiguration(
|
|
@@ -195,6 +307,16 @@ const MAX_RETRIES: u32 = 3;
|
|
|
195
307
|
// Taken from Trustmark xtask.
|
|
196
308
|
// Will not overwrite models if they already exist.
|
|
197
309
|
pub fn fetch_model(variant: Variant, dir_path: &std::path::Path) -> Result<PathBuf> {
|
|
310
|
+
fetch_models(
|
|
311
|
+
dir_path,
|
|
312
|
+
&[
|
|
313
|
+
format!("encoder_{variant}.onnx"),
|
|
314
|
+
format!("decoder_{variant}.onnx"),
|
|
315
|
+
],
|
|
316
|
+
)
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
fn fetch_models(dir_path: &std::path::Path, filenames: &[String]) -> Result<PathBuf> {
|
|
198
320
|
let rt = runtime();
|
|
199
321
|
let client = Client::builder()
|
|
200
322
|
.timeout(Duration::from_secs(120))
|
|
@@ -208,12 +330,8 @@ pub fn fetch_model(variant: Variant, dir_path: &std::path::Path) -> Result<PathB
|
|
|
208
330
|
|
|
209
331
|
let root = "https://cai-watermark.adobe.net/watermarking/trustmark-models";
|
|
210
332
|
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
let decoder_filename = format!("decoder_{variant}.onnx");
|
|
214
|
-
|
|
215
|
-
for filename in [encoder_filename, decoder_filename] {
|
|
216
|
-
let model_path = dir_path.join(&filename);
|
|
333
|
+
for filename in filenames {
|
|
334
|
+
let model_path = dir_path.join(filename);
|
|
217
335
|
if model_path.exists() {
|
|
218
336
|
continue;
|
|
219
337
|
}
|