@contentauth/c2pa-node 0.5.3 → 0.5.5

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.
@@ -31,9 +31,9 @@ describe("Settings", () => {
31
31
  };
32
32
  const settings = createTrustSettings(trustConfig);
33
33
  expect(settings.trust).toBeDefined();
34
- expect((_a = settings.trust) === null || _a === void 0 ? void 0 : _a.verify_trust_list).toBe(true);
35
- expect((_b = settings.trust) === null || _b === void 0 ? void 0 : _b.user_anchors).toBe("test");
36
- expect((_c = settings.trust) === null || _c === void 0 ? void 0 : _c.allowed_list).toBe("allowed");
34
+ expect((_a = settings.trust) === null || _a === void 0 ? void 0 : _a.verifyTrustList).toBe(true);
35
+ expect((_b = settings.trust) === null || _b === void 0 ? void 0 : _b.userAnchors).toBe("test");
36
+ expect((_c = settings.trust) === null || _c === void 0 ? void 0 : _c.allowedList).toBe("allowed");
37
37
  });
38
38
  it("creates CAWG trust settings", () => {
39
39
  var _a, _b;
@@ -42,9 +42,9 @@ describe("Settings", () => {
42
42
  trustAnchors: "anchors",
43
43
  };
44
44
  const settings = createCawgTrustSettings(trustConfig);
45
- expect(settings.cawg_trust).toBeDefined();
46
- expect((_a = settings.cawg_trust) === null || _a === void 0 ? void 0 : _a.verify_trust_list).toBe(false);
47
- expect((_b = settings.cawg_trust) === null || _b === void 0 ? void 0 : _b.trust_anchors).toBe("anchors");
45
+ expect(settings.cawgTrust).toBeDefined();
46
+ expect((_a = settings.cawgTrust) === null || _a === void 0 ? void 0 : _a.verifyTrustList).toBe(false);
47
+ expect((_b = settings.cawgTrust) === null || _b === void 0 ? void 0 : _b.trustAnchors).toBe("anchors");
48
48
  });
49
49
  it("creates verify settings", () => {
50
50
  var _a, _b, _c, _d;
@@ -60,10 +60,20 @@ describe("Settings", () => {
60
60
  };
61
61
  const settings = createVerifySettings(verifyConfig);
62
62
  expect(settings.verify).toBeDefined();
63
- expect((_a = settings.verify) === null || _a === void 0 ? void 0 : _a.verify_after_reading).toBe(true);
64
- expect((_b = settings.verify) === null || _b === void 0 ? void 0 : _b.verify_after_sign).toBe(false);
65
- expect((_c = settings.verify) === null || _c === void 0 ? void 0 : _c.verify_trust).toBe(true);
66
- expect((_d = settings.verify) === null || _d === void 0 ? void 0 : _d.ocsp_fetch).toBe(true);
63
+ expect((_a = settings.verify) === null || _a === void 0 ? void 0 : _a.verifyAfterReading).toBe(true);
64
+ expect((_b = settings.verify) === null || _b === void 0 ? void 0 : _b.verifyAfterSign).toBe(false);
65
+ expect((_c = settings.verify) === null || _c === void 0 ? void 0 : _c.verifyTrust).toBe(true);
66
+ expect((_d = settings.verify) === null || _d === void 0 ? void 0 : _d.ocspFetch).toBe(true);
67
+ });
68
+ it("creates verify settings with partial config", () => {
69
+ var _a, _b, _c;
70
+ const settings = createVerifySettings({
71
+ verifyAfterReading: false,
72
+ });
73
+ expect(settings.verify).toBeDefined();
74
+ expect((_a = settings.verify) === null || _a === void 0 ? void 0 : _a.verifyAfterReading).toBe(false);
75
+ expect((_b = settings.verify) === null || _b === void 0 ? void 0 : _b.verifyAfterSign).toBeUndefined();
76
+ expect((_c = settings.verify) === null || _c === void 0 ? void 0 : _c.verifyTrust).toBeUndefined();
67
77
  });
68
78
  it("merges multiple settings", () => {
69
79
  var _a, _b;
@@ -84,10 +94,10 @@ describe("Settings", () => {
84
94
  const merged = mergeSettings(trustSettings, verifySettings);
85
95
  expect(merged.trust).toBeDefined();
86
96
  expect(merged.verify).toBeDefined();
87
- expect((_a = merged.trust) === null || _a === void 0 ? void 0 : _a.verify_trust_list).toBe(true);
88
- expect((_b = merged.verify) === null || _b === void 0 ? void 0 : _b.verify_after_reading).toBe(false);
97
+ expect((_a = merged.trust) === null || _a === void 0 ? void 0 : _a.verifyTrustList).toBe(true);
98
+ expect((_b = merged.verify) === null || _b === void 0 ? void 0 : _b.verifyAfterReading).toBe(false);
89
99
  });
90
- it("converts settings to JSON", () => {
100
+ it("converts settings to JSON with snake_case keys", () => {
91
101
  const settings = createVerifySettings({
92
102
  verifyAfterReading: true,
93
103
  verifyAfterSign: true,
@@ -101,22 +111,17 @@ describe("Settings", () => {
101
111
  const json = settingsToJson(settings);
102
112
  expect(json).toContain("verify");
103
113
  expect(json).toContain("verify_after_reading");
104
- // Should be parseable
114
+ // Should be parseable with snake_case keys
105
115
  const parsed = JSON.parse(json);
106
116
  expect(parsed.verify.verify_after_reading).toBe(true);
107
117
  });
108
118
  it("does not include undefined values in trust settings JSON", () => {
109
119
  const trustConfig = {
110
120
  verifyTrustList: true,
111
- // userAnchors is undefined
112
- // trustAnchors is undefined
113
- // trustConfig is undefined
114
- // allowedList is undefined
115
121
  };
116
122
  const settings = createTrustSettings(trustConfig);
117
123
  const json = settingsToJson(settings);
118
124
  const parsed = JSON.parse(json);
119
- // JSON.stringify automatically excludes undefined values
120
125
  expect(parsed.trust.verify_trust_list).toBe(true);
121
126
  expect("user_anchors" in parsed.trust).toBe(false);
122
127
  expect("trust_anchors" in parsed.trust).toBe(false);
@@ -126,12 +131,10 @@ describe("Settings", () => {
126
131
  it("does not include undefined values in CAWG trust settings JSON", () => {
127
132
  const trustConfig = {
128
133
  verifyTrustList: false,
129
- // Only verifyTrustList is defined
130
134
  };
131
135
  const settings = createCawgTrustSettings(trustConfig);
132
136
  const json = settingsToJson(settings);
133
137
  const parsed = JSON.parse(json);
134
- // JSON.stringify automatically excludes undefined values
135
138
  expect(parsed.cawg_trust.verify_trust_list).toBe(false);
136
139
  expect("user_anchors" in parsed.cawg_trust).toBe(false);
137
140
  expect("trust_anchors" in parsed.cawg_trust).toBe(false);
@@ -140,18 +143,10 @@ describe("Settings", () => {
140
143
  const verifyConfig = {
141
144
  verifyAfterReading: true,
142
145
  verifyAfterSign: false,
143
- // Only first two are defined, rest are undefined
144
- verifyTrust: undefined,
145
- verifyTimestampTrust: undefined,
146
- ocspFetch: undefined,
147
- remoteManifestFetch: undefined,
148
- skipIngredientConflictResolution: undefined,
149
- strictV1Validation: undefined,
150
146
  };
151
147
  const settings = createVerifySettings(verifyConfig);
152
148
  const json = settingsToJson(settings);
153
149
  const parsed = JSON.parse(json);
154
- // JSON.stringify automatically excludes undefined values
155
150
  expect(parsed.verify.verify_after_reading).toBe(true);
156
151
  expect(parsed.verify.verify_after_sign).toBe(false);
157
152
  expect("verify_trust" in parsed.verify).toBe(false);
@@ -162,22 +157,22 @@ describe("Settings", () => {
162
157
  it("does not include undefined values when merging settings", () => {
163
158
  const settings1 = {
164
159
  trust: {
165
- verify_trust_list: true,
166
- user_anchors: "test",
160
+ verifyTrustList: true,
161
+ userAnchors: "test",
167
162
  },
168
163
  };
169
164
  const settings2 = {
170
165
  trust: {
171
- allowed_list: undefined, // Explicitly undefined
166
+ verifyTrustList: true,
167
+ allowedList: undefined,
172
168
  },
173
169
  verify: {
174
- verify_after_reading: false,
170
+ verifyAfterReading: false,
175
171
  },
176
172
  };
177
173
  const merged = mergeSettings(settings1, settings2);
178
174
  const json = settingsToJson(merged);
179
175
  const parsed = JSON.parse(json);
180
- // JSON.stringify automatically excludes undefined values
181
176
  expect(parsed.trust.verify_trust_list).toBe(true);
182
177
  expect(parsed.trust.user_anchors).toBe("test");
183
178
  expect("allowed_list" in parsed.trust).toBe(false);
@@ -197,14 +192,14 @@ describe("Settings", () => {
197
192
  });
198
193
  const settings2 = {
199
194
  verify: {
200
- verify_trust: true, // Override this value
201
- ocsp_fetch: true, // Override this value
195
+ verifyTrust: true,
196
+ ocspFetch: true,
202
197
  },
203
198
  };
204
199
  const merged = mergeSettings(settings1, settings2);
205
- expect((_a = merged.verify) === null || _a === void 0 ? void 0 : _a.verify_after_reading).toBe(true); // from settings1
206
- expect((_b = merged.verify) === null || _b === void 0 ? void 0 : _b.verify_trust).toBe(true); // overridden by settings2
207
- expect((_c = merged.verify) === null || _c === void 0 ? void 0 : _c.ocsp_fetch).toBe(true); // overridden by settings2
200
+ expect((_a = merged.verify) === null || _a === void 0 ? void 0 : _a.verifyAfterReading).toBe(true); // from settings1
201
+ expect((_b = merged.verify) === null || _b === void 0 ? void 0 : _b.verifyTrust).toBe(true); // overridden by settings2
202
+ expect((_c = merged.verify) === null || _c === void 0 ? void 0 : _c.ocspFetch).toBe(true); // overridden by settings2
208
203
  });
209
204
  describe("loadSettingsFromFile", () => {
210
205
  let tempDir;
@@ -58,10 +58,6 @@ describe("Trustmark", () => {
58
58
  testImageWidth = imageInfo.width;
59
59
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
60
60
  testImageHeight = imageInfo.height;
61
- }));
62
- beforeEach(() => __awaiter(void 0, void 0, void 0, function* () {
63
- // Note: In a real test environment, you would need a valid model file
64
- // For now, we'll mock the trustmark creation or handle the case where model doesn't exist
65
61
  trustmark = yield Trustmark.newTrustmark(trustmarkConfig);
66
62
  }));
67
63
  describe("newTrustmark", () => {
package/dist/binary.js CHANGED
@@ -18,7 +18,8 @@ let neon = null;
18
18
  // Get the binary module (loads synchronously on first access)
19
19
  export function getNeonBinary() {
20
20
  if (neon === null) {
21
- neon = require("./index.node");
21
+ const C2PA_LIBRARY_PATH = process.env.C2PA_LIBRARY_PATH;
22
+ neon = require(C2PA_LIBRARY_PATH !== null && C2PA_LIBRARY_PATH !== void 0 ? C2PA_LIBRARY_PATH : "./index.node");
22
23
  }
23
24
  return neon;
24
25
  }
package/dist/index.node CHANGED
Binary file
@@ -1,4 +1,4 @@
1
- import type { BuilderIntent, Ingredient, Manifest } from "@contentauth/c2pa-types";
1
+ import type { BuilderIntent, C2paReason, Ingredient, Manifest } from "@contentauth/c2pa-types";
2
2
  import type { BuilderInterface, C2paSettings, CallbackSignerInterface, ClaimVersion, DestinationAsset, IdentityAssertionSignerInterface, JsCallbackSignerConfig, LocalSignerInterface, ManifestAssertionKind, ReaderInterface, SourceAsset, NeonBuilderHandle } from "./types.d.ts";
3
3
  export declare class Builder implements BuilderInterface {
4
4
  private builder;
@@ -21,5 +21,6 @@ export declare class Builder implements BuilderInterface {
21
21
  signAsync(signer: CallbackSignerInterface | IdentityAssertionSignerInterface, input: SourceAsset, output: DestinationAsset): Promise<Buffer>;
22
22
  getManifestDefinition(): Manifest;
23
23
  updateManifestProperty(property: string, value: ClaimVersion): void;
24
+ addRedaction(uri: string, reason: C2paReason): void;
24
25
  getHandle(): NeonBuilderHandle;
25
26
  }
@@ -26,8 +26,9 @@ export declare function createVerifySettings(verifyConfig: VerifyConfig): Settin
26
26
  export declare function mergeSettings(...settings: SettingsContext[]): SettingsContext;
27
27
  /**
28
28
  * Convert a settings object to a JSON string.
29
+ * Converts camelCase keys to snake_case to match the c2pa-rs settings format.
29
30
  * @param settings The settings object
30
- * @returns JSON string representation
31
+ * @returns JSON string representation with snake_case keys
31
32
  */
32
33
  export declare function settingsToJson(settings: SettingsContext): string;
33
34
  /**
@@ -15,12 +15,13 @@
15
15
  import { Buffer } from "buffer";
16
16
  import type {
17
17
  BuilderIntent,
18
+ C2paReason,
18
19
  Ingredient,
19
20
  Manifest,
20
21
  ManifestStore,
21
22
  } from "@contentauth/c2pa-types";
22
23
 
23
- export type { Ingredient } from "@contentauth/c2pa-types";
24
+ export type { C2paReason, Ingredient } from "@contentauth/c2pa-types";
24
25
 
25
26
  /**
26
27
  * Describes the digital signature algorithms allowed by the C2PA spec
@@ -332,6 +333,15 @@ export interface BuilderInterface {
332
333
  */
333
334
  updateManifestProperty(property: string, value: string | ClaimVersion): void;
334
335
 
336
+ /**
337
+ * Redact an assertion from an ingredient manifest and record the reason.
338
+ * Adds the URI to `definition.redactions` and appends a `c2pa.redacted` action
339
+ * with `parameters.redacted` pointing to the same URI.
340
+ * @param uri JUMBF URI of the assertion to redact (e.g. `self#jumbf=/c2pa/{label}/c2pa.assertions/{name}`)
341
+ * @param reason Why the assertion is being redacted. Use `"c2pa.PII.present"` for PII removal.
342
+ */
343
+ addRedaction(uri: string, reason: C2paReason): void;
344
+
335
345
  /**
336
346
  * Get the internal handle for use with Neon bindings
337
347
  */
@@ -453,21 +463,21 @@ export interface TrustConfig {
453
463
  */
454
464
  export interface VerifyConfig {
455
465
  /** Whether to verify after reading a manifest */
456
- verifyAfterReading: boolean;
466
+ verifyAfterReading?: boolean;
457
467
  /** Whether to verify after signing a manifest */
458
- verifyAfterSign: boolean;
468
+ verifyAfterSign?: boolean;
459
469
  /** Whether to verify trust during validation */
460
- verifyTrust: boolean;
470
+ verifyTrust?: boolean;
461
471
  /** Whether to verify timestamp trust */
462
- verifyTimestampTrust: boolean;
472
+ verifyTimestampTrust?: boolean;
463
473
  /** Whether to fetch OCSP responses */
464
- ocspFetch: boolean;
474
+ ocspFetch?: boolean;
465
475
  /** Whether to fetch remote manifests */
466
- remoteManifestFetch: boolean;
476
+ remoteManifestFetch?: boolean;
467
477
  /** Whether to skip ingredient conflict resolution */
468
- skipIngredientConflictResolution: boolean;
478
+ skipIngredientConflictResolution?: boolean;
469
479
  /** Whether to use strict v1 validation */
470
- strictV1Validation: boolean;
480
+ strictV1Validation?: boolean;
471
481
  }
472
482
 
473
483
  /**
@@ -477,32 +487,11 @@ export interface VerifyConfig {
477
487
  */
478
488
  export interface SettingsContext {
479
489
  /** C2PA trust configuration */
480
- trust?: {
481
- verify_trust_list?: boolean;
482
- user_anchors?: string;
483
- trust_anchors?: string;
484
- trust_config?: string;
485
- allowed_list?: string;
486
- };
490
+ trust?: TrustConfig;
487
491
  /** CAWG trust configuration */
488
- cawg_trust?: {
489
- verify_trust_list?: boolean;
490
- user_anchors?: string;
491
- trust_anchors?: string;
492
- trust_config?: string;
493
- allowed_list?: string;
494
- };
492
+ cawgTrust?: TrustConfig;
495
493
  /** Verification configuration */
496
- verify?: {
497
- verify_after_reading?: boolean;
498
- verify_after_sign?: boolean;
499
- verify_trust?: boolean;
500
- verify_timestamp_trust?: boolean;
501
- ocsp_fetch?: boolean;
502
- remote_manifest_fetch?: boolean;
503
- skip_ingredient_conflict_resolution?: boolean;
504
- strict_v1_validation?: boolean;
505
- };
494
+ verify?: VerifyConfig;
506
495
  /** Builder configuration */
507
496
  builder?: {
508
497
  thumbnail?: {
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "type": "git",
5
5
  "url": "git+https://github.com/contentauth/c2pa-node-v2.git"
6
6
  },
7
- "version": "0.5.3",
7
+ "version": "0.5.5",
8
8
  "description": "Node.js bindings for C2PA",
9
9
  "main": "dist/index.js",
10
10
  "type": "module",
@@ -22,29 +22,29 @@
22
22
  "author": "Colin Murphy <colmurph@adobe.com>",
23
23
  "license": "MIT",
24
24
  "devDependencies": {
25
- "@changesets/cli": "^2.29.6",
26
- "@contentauth/c2pa-types": "^0.4.1",
27
- "@eslint/js": "^9.33.0",
25
+ "@changesets/cli": "^2.31.0",
26
+ "@contentauth/c2pa-types": "^0.4.4",
27
+ "@eslint/js": "^9.39.4",
28
28
  "@neon-rs/cli": "0.1.82",
29
29
  "@types/cli-progress": "^3.11.6",
30
- "@types/debug": "^4.1.12",
30
+ "@types/debug": "^4.1.13",
31
31
  "@types/fs-extra": "^11.0.4",
32
32
  "@types/jest": "^29.5.14",
33
- "@types/node": "^22.17.1",
33
+ "@types/node": "^22.19.17",
34
34
  "@types/unzipper": "^0.10.11",
35
- "@typescript-eslint/eslint-plugin": "^8.39.1",
36
- "@typescript-eslint/parser": "^8.39.1",
35
+ "@typescript-eslint/eslint-plugin": "^8.59.1",
36
+ "@typescript-eslint/parser": "^8.59.1",
37
37
  "@vitest/ui": "^3.2.4",
38
- "cbor2": "^2.0.1",
38
+ "cbor2": "^2.3.0",
39
39
  "cpy-cli": "^5.0.0",
40
- "eslint": "^9.33.0",
40
+ "eslint": "^9.39.4",
41
41
  "npm-run-all": "^4.1.5",
42
- "rimraf": "^6.0.1",
43
- "sharp": "^0.34.3",
44
- "ts-jest": "^29.4.1",
45
- "typedoc": "^0.28.10",
46
- "typedoc-plugin-markdown": "^4.8.1",
47
- "typescript": "^5.9.2",
42
+ "rimraf": "^6.1.3",
43
+ "sharp": "^0.34.5",
44
+ "ts-jest": "^29.4.9",
45
+ "typedoc": "^0.28.19",
46
+ "typedoc-plugin-markdown": "^4.11.0",
47
+ "typescript": "^5.9.3",
48
48
  "vitest": "^3.2.4"
49
49
  },
50
50
  "keywords": [
@@ -55,20 +55,20 @@
55
55
  },
56
56
  "homepage": "https://github.com/contentauth/c2pa-node-v2#readme",
57
57
  "dependencies": {
58
- "cargo-cp-artifact": "^0.1.0",
59
- "cli-progress": "^3.2.0",
60
- "debug": "^4.4.1",
61
- "fs-extra": "^11.3.1",
62
- "mkdirp": "^3.0.0",
58
+ "cargo-cp-artifact": "^0.1.9",
59
+ "cli-progress": "^3.12.0",
60
+ "debug": "^4.4.3",
61
+ "fs-extra": "^11.3.4",
62
+ "mkdirp": "^3.0.1",
63
63
  "node-fetch": "^3.3.2",
64
64
  "pkg-dir": "^8.0.0",
65
- "pretty-bytes": "^6.0.0",
66
- "unzipper": "^0.10.0"
65
+ "pretty-bytes": "^6.1.1",
66
+ "unzipper": "^0.10.14"
67
67
  },
68
68
  "scripts": {
69
69
  "build": "run-s build:rust build:ts",
70
70
  "build:debug": "run-s build:rust-debug build:ts",
71
- "build:docs": "rimraf docs-typedoc && typedoc --plugin typedoc-plugin-markdown --readme README.md --out docs-typedoc js-src/index.ts && cpy \"docs-typedoc/**\" docs --parents --overwrite --ignore=\"docs-typedoc/classes/index.md\" --ignore=\"docs-typedoc/README.md\" && rimraf docs-typedoc",
71
+ "build:docs": "typedoc",
72
72
  "build:rust": "pnpm run build:rust-debug --release",
73
73
  "build:rust-debug": "cargo build --message-format=json-render-diagnostics > cargo.log",
74
74
  "build:ts": "tsc -b && cpy index.node dist && cpy index.node js-src && cpy --flat js-src/types.d.ts dist/types",
package/src/lib.rs CHANGED
@@ -81,6 +81,10 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> {
81
81
  "builderUpdateManifestProperty",
82
82
  neon_builder::NeonBuilder::update_manifest_property,
83
83
  )?;
84
+ cx.export_function(
85
+ "builderAddRedaction",
86
+ neon_builder::NeonBuilder::add_redaction,
87
+ )?;
84
88
 
85
89
  // Reader
86
90
  cx.export_function("readerNew", neon_reader::NeonReader::new)?;
@@ -18,7 +18,7 @@ use crate::neon_reader::NeonReader;
18
18
  use crate::neon_signer::{CallbackSignerConfig, NeonCallbackSigner, NeonLocalSigner};
19
19
  use crate::runtime::runtime;
20
20
  use crate::utils::parse_settings;
21
- use c2pa::{Builder, BuilderIntent, Ingredient};
21
+ use c2pa::{assertions::Action, Builder, BuilderIntent, Ingredient};
22
22
  use neon::context::Context as NeonContext;
23
23
  use neon::prelude::*;
24
24
  use neon_serde4;
@@ -60,7 +60,9 @@ impl NeonBuilder {
60
60
  .with_definition(json.as_str())
61
61
  .or_else(|err| cx.throw_error(err.to_string()))?
62
62
  } else {
63
- Builder::from_json(&json).or_else(|err| cx.throw_error(err.to_string()))?
63
+ Builder::default()
64
+ .with_definition(&json)
65
+ .or_else(|err| cx.throw_error(err.to_string()))?
64
66
  };
65
67
 
66
68
  Ok(cx.boxed(Self {
@@ -73,7 +75,7 @@ impl NeonBuilder {
73
75
  let this = cx.this::<JsBox<Self>>()?;
74
76
  let intent_str = cx.argument::<JsString>(0)?.value(&mut cx);
75
77
  let intent: BuilderIntent = serde_json::from_str(&intent_str)
76
- .or_else(|_| cx.throw_error(format!("Invalid intent: {}", intent_str)))?;
78
+ .or_else(|_| cx.throw_error(format!("Invalid intent: {intent_str}")))?;
77
79
  let mut builder = rt.block_on(async { this.builder.lock().await });
78
80
  builder.set_intent(intent);
79
81
  Ok(cx.undefined())
@@ -127,7 +129,7 @@ impl NeonBuilder {
127
129
  // For Json, expect the assertion as a string (JSON) and parse it
128
130
  let assertion_str = cx.argument::<JsString>(1)?.value(&mut cx);
129
131
  let assertion: serde_json::Value = serde_json::from_str(&assertion_str)
130
- .or_else(|err| cx.throw_error(format!("Invalid JSON: {}", err)))?;
132
+ .or_else(|err| cx.throw_error(format!("Invalid JSON: {err}")))?;
131
133
  builder
132
134
  .add_assertion(&label, &assertion)
133
135
  .or_else(|err| cx.throw_error(err.to_string()))?;
@@ -170,6 +172,28 @@ impl NeonBuilder {
170
172
 
171
173
  Ok(promise)
172
174
  }
175
+
176
+ pub fn add_redaction(mut cx: FunctionContext) -> JsResult<JsUndefined> {
177
+ let rt = runtime();
178
+ let this = cx.this::<JsBox<Self>>()?;
179
+ let uri = cx.argument::<JsString>(0)?.value(&mut cx);
180
+ let reason = cx.argument::<JsString>(1)?.value(&mut cx);
181
+ let mut builder = rt.block_on(async { this.builder.lock().await });
182
+ builder
183
+ .definition
184
+ .redactions
185
+ .get_or_insert_with(Vec::new)
186
+ .push(uri.clone());
187
+ let action = Action::new("c2pa.redacted")
188
+ .set_reason(reason)
189
+ .set_parameter("redacted".to_owned(), uri)
190
+ .or_else(|err| cx.throw_error(err.to_string()))?;
191
+ builder
192
+ .add_action(action)
193
+ .or_else(|err| cx.throw_error(err.to_string()))?;
194
+ Ok(cx.undefined())
195
+ }
196
+
173
197
  pub fn add_ingredient(mut cx: FunctionContext) -> JsResult<JsUndefined> {
174
198
  let rt = runtime();
175
199
  let this = cx.this::<JsBox<Self>>()?;
@@ -254,7 +278,7 @@ impl NeonBuilder {
254
278
  // Block on acquiring the async mutex lock
255
279
  // Settings are automatically applied when runtime() is called
256
280
  let rt = runtime();
257
- let mut builder = rt.block_on(async { builder.lock().await });
281
+ let builder = rt.block_on(async { builder.lock().await });
258
282
 
259
283
  dest.write_stream().and_then(|mut dest_stream| {
260
284
  builder.to_archive(&mut dest_stream)?;
@@ -302,7 +326,7 @@ impl NeonBuilder {
302
326
  let builder = if let Some(context) = context_opt {
303
327
  Builder::from_context(context).with_archive(source_stream)?
304
328
  } else {
305
- Builder::from_archive(source_stream)?
329
+ Builder::default().with_archive(source_stream)?
306
330
  };
307
331
  Ok(builder)
308
332
  })
@@ -70,7 +70,7 @@ impl NeonReader {
70
70
  .with_stream_async(&format, stream)
71
71
  .await?
72
72
  } else {
73
- Reader::from_stream_async(&format, stream).await?
73
+ Reader::default().with_stream_async(&format, stream).await?
74
74
  };
75
75
 
76
76
  Ok(reader)
@@ -130,7 +130,9 @@ impl NeonReader {
130
130
  .with_manifest_data_and_stream_async(&c2pa_data, &format, stream)
131
131
  .await?
132
132
  } else {
133
- Reader::from_manifest_data_and_stream_async(&c2pa_data, &format, stream).await?
133
+ Reader::default()
134
+ .with_manifest_data_and_stream_async(&c2pa_data, &format, stream)
135
+ .await?
134
136
  };
135
137
 
136
138
  Ok(reader)
@@ -184,21 +184,27 @@ fn check_strength(strength: f32) -> Result<()> {
184
184
  Ok(())
185
185
  }
186
186
 
187
+ /// Minimum expected size for a valid ONNX model file (10 MB).
188
+ const MIN_MODEL_SIZE: usize = 10 * 1024 * 1024;
189
+
190
+ /// Maximum number of download attempts per model file.
191
+ const MAX_RETRIES: u32 = 3;
192
+
187
193
  // Taken from Trustmark xtask.
188
194
  // Will not overwrite models if they already exist.
189
195
  pub fn fetch_model(variant: Variant, dir_path: &std::path::Path) -> Result<PathBuf> {
190
196
  let rt = runtime();
191
197
  let client = Client::builder()
192
- .timeout(Duration::from_secs(10))
193
- .connect_timeout(Duration::from_secs(5))
194
- .read_timeout(Duration::from_secs(5))
198
+ .timeout(Duration::from_secs(120))
199
+ .connect_timeout(Duration::from_secs(10))
200
+ .read_timeout(Duration::from_secs(60))
195
201
  .build()
196
202
  .map_err(|e| Error::ModelDownload(format!("Failed to build HTTP client: {e}")))?;
197
203
 
198
204
  // Ensure directory exists
199
205
  std::fs::create_dir_all(dir_path)?;
200
206
 
201
- let root = "https://cc-assets.netlify.app/watermarking/trustmark-models";
207
+ let root = "https://cai-watermark.adobe.net/watermarking/trustmark-models";
202
208
 
203
209
  // Construct filenames manually since encoder_filename/decoder_filename are private
204
210
  let encoder_filename = format!("encoder_{variant}.onnx");
@@ -210,32 +216,70 @@ pub fn fetch_model(variant: Variant, dir_path: &std::path::Path) -> Result<PathB
210
216
  continue;
211
217
  }
212
218
  let model_url = format!("{root}/{filename}");
213
- let model_bytes = rt.block_on(async {
214
- let response = client
215
- .get(&model_url)
216
- .send()
217
- .await
218
- .map_err(|e| Error::ModelDownload(format!("Failed to GET model: {e}")))?;
219
- response
220
- .bytes()
221
- .await
222
- .map_err(|e| Error::ModelDownload(format!("Failed to read model bytes: {e}")))
223
- .map(|b| b.to_vec())
224
- })?;
225
- let mut file = OpenOptions::new()
226
- .write(true)
227
- .create_new(true)
228
- .open(&model_path)
229
- .map_err(|e| {
230
- Error::ModelDownload(format!(
231
- "Created {dir_path:?} but failed to open model directory{model_path:?}: {e}"
232
- ))
233
- })?;
234
- file.write_all(&model_bytes).map_err(|e| {
235
- Error::ModelDownload(format!(
236
- "Failed to write model to model directory {model_path:?}: {e}"
237
- ))
238
- })?;
219
+
220
+ let mut last_err = None;
221
+ for attempt in 1..=MAX_RETRIES {
222
+ match download_model(&rt, &client, &model_url) {
223
+ Ok(model_bytes) => {
224
+ if model_bytes.len() < MIN_MODEL_SIZE {
225
+ last_err = Some(Error::ModelDownload(format!(
226
+ "Downloaded model {filename} is too small ({} bytes), expected at least {MIN_MODEL_SIZE} bytes",
227
+ model_bytes.len()
228
+ )));
229
+ continue;
230
+ }
231
+
232
+ // Write to a temporary file first, then rename for atomicity.
233
+ let tmp_path = dir_path.join(format!("{filename}.tmp"));
234
+ let mut file = OpenOptions::new()
235
+ .write(true)
236
+ .create(true)
237
+ .truncate(true)
238
+ .open(&tmp_path)
239
+ .map_err(|e| {
240
+ Error::ModelDownload(format!(
241
+ "Failed to create temp file {tmp_path:?}: {e}"
242
+ ))
243
+ })?;
244
+ file.write_all(&model_bytes).map_err(|e| {
245
+ Error::ModelDownload(format!("Failed to write model to {tmp_path:?}: {e}"))
246
+ })?;
247
+ std::fs::rename(&tmp_path, &model_path).map_err(|e| {
248
+ Error::ModelDownload(format!(
249
+ "Failed to rename {tmp_path:?} to {model_path:?}: {e}"
250
+ ))
251
+ })?;
252
+
253
+ last_err = None;
254
+ break;
255
+ }
256
+ Err(e) => {
257
+ last_err = Some(e);
258
+ if attempt < MAX_RETRIES {
259
+ std::thread::sleep(Duration::from_secs(u64::from(attempt)));
260
+ }
261
+ }
262
+ }
263
+ }
264
+
265
+ if let Some(err) = last_err {
266
+ return Err(err);
267
+ }
239
268
  }
240
269
  Ok(dir_path.to_path_buf())
241
270
  }
271
+
272
+ fn download_model(rt: &tokio::runtime::Runtime, client: &Client, url: &str) -> Result<Vec<u8>> {
273
+ rt.block_on(async {
274
+ let response = client
275
+ .get(url)
276
+ .send()
277
+ .await
278
+ .map_err(|e| Error::ModelDownload(format!("Failed to GET model: {e}")))?;
279
+ response
280
+ .bytes()
281
+ .await
282
+ .map_err(|e| Error::ModelDownload(format!("Failed to read model bytes: {e}")))
283
+ .map(|b| b.to_vec())
284
+ })
285
+ }