@contentauth/c2pa-node 0.9.10 → 0.9.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 CHANGED
@@ -7,9 +7,13 @@
7
7
 
8
8
  ## Prerequisites
9
9
 
10
- To use the c2pa-node library, you need Node.js 22 or later. If you need to manage multiple versions of Node on your machine, use a tool such as [nvm](https://github.com/nvm-sh/nvm).
10
+ To use the c2pa-node library, you need Node.js 22 or later. Use a patched release: v22.23.4+ on v22, v24.22.1+ on v24, or v26.12.1+ on v26. The binary installer and JavaScript fetch paths use Node's TLS stack independently of the Rust SDK; see [TLS trust stores](../../README.md#tls-trust-stores). If you need to manage multiple versions of Node on your machine, use a tool such as [nvm](https://github.com/nvm-sh/nvm).
11
+
12
+ Rust is not required when installing the package normally: precompiled binaries
13
+ are downloaded automatically. For source builds, see
14
+ [Contributing to c2pa-node](https://github.com/contentauth/c2pa-js/blob/main/docs/project-contributions.md#contributing-to-c2pa-node).
15
+
11
16
 
12
- To build from source, you also need [Rust](https://www.rust-lang.org/tools/install). This is not required when installing the package normally: precompiled binaries are downloaded automatically during installation.
13
17
 
14
18
  ## Installation
15
19
 
@@ -44,15 +48,14 @@ This command will download precompiled binaries for the following systems:
44
48
 
45
49
  ## Documentation
46
50
 
47
- Complete API documentation is generated from TypeScript source using [TypeDoc](https://typedoc.org/) and published to GitHub Pages at [https://contentauth.github.io/c2pa-js/](https://contentauth.github.io/c2pa-js/).
48
-
49
- To generate documentation locally, run the following from the monorepo root:
50
-
51
- ```bash
52
- pnpm ci:docs
53
- ```
51
+ The [Node.js API documentation](https://contentauth.github.io/c2pa-js/node/) is
52
+ generated with [TypeDoc](https://typedoc.org/) from the declarations in published
53
+ versions of `@contentauth/c2pa-node`. Use the version selector to switch releases.
54
+ The [multi-package documentation](https://contentauth.github.io/c2pa-js/) remains
55
+ available at the existing root URL.
54
56
 
55
- This generates HTML documentation in the `docs/` directory at the repo root. It is not checked into version control and is automatically published to GitHub Pages whenever a new release is published.
57
+ For documentation builds and version-list maintenance, see
58
+ [Building API documentation](https://github.com/contentauth/c2pa-js/blob/main/docs/project-contributions.md#building-api-documentation).
56
59
 
57
60
  ## Components
58
61
 
@@ -564,7 +567,7 @@ const builder3 = await Builder.fromArchive(archiveAsset, context);
564
567
  ```
565
568
 
566
569
  > [!NOTE]
567
- > Unlike `c2pa-web`, `c2pa-node` doesn't fetch trust-anchor URLs embedded in a `Context`'s settings yet — a trust anchor value must be inline PEM content or a local file path, not a URL, until that support lands here too.
570
+ > As in `c2pa-web`, URLs in a `Context`'s trust-anchor settings are fetched and resolved before the Reader or Builder is created. The deprecated raw-settings API does not resolve URLs; use a `Context` for URL-based trust anchors.
568
571
 
569
572
  #### Per-instance settings (deprecated)
570
573
 
@@ -685,13 +688,9 @@ const builder = Builder.new(urlSettings);
685
688
 
686
689
  ### Build and use custom binary
687
690
 
688
- **Build Rust binary:**
689
-
690
- ```bash
691
- pnpm run build:rust
692
- ```
693
-
694
- **Use custom Rust binary:**
691
+ For instructions on building a Rust binary, see
692
+ [Contributing to c2pa-node](https://github.com/contentauth/c2pa-js/blob/main/docs/project-contributions.md#contributing-to-c2pa-node).
693
+ To use a custom binary:
695
694
 
696
695
  ```bash
697
696
  export C2PA_LIBRARY_PATH=<path-to-binary-folder>/index.node
package/dist/Builder.js CHANGED
@@ -5,7 +5,7 @@
5
5
  // at your option.
6
6
  import { Context } from "@contentauth/c2pa-utilities";
7
7
  import { getNeonBinary } from "./binary.js";
8
- import { resolveSettingsForNeon } from "./Settings.js";
8
+ import { resolveRawSettingsForNeon, resolveSettingsForNeon } from "./Settings.js";
9
9
  import { IdentityAssertionSigner } from "./IdentityAssertion.js";
10
10
  function stringifyManifestDefinition(json) {
11
11
  try {
@@ -30,7 +30,7 @@ export class Builder {
30
30
  * @param settings A raw `C2paSettings` string/object.
31
31
  */
32
32
  static new(settings) {
33
- const settingsStr = resolveSettingsForNeon(settings);
33
+ const settingsStr = resolveRawSettingsForNeon(settings);
34
34
  const builder = getNeonBinary().builderNew(settingsStr);
35
35
  return new Builder(builder);
36
36
  }
@@ -38,14 +38,13 @@ export class Builder {
38
38
  * Create a Builder with a minimal manifest definition, configured by a `Context`.
39
39
  * Prefer this over the deprecated {@link Builder.new}.
40
40
  *
41
- * Declared async for forward compatibility. Upcoming work will allow for trust anchor
42
- * resolution at construction time.
41
+ * Resolves trust-anchor URLs in the Context before constructing the Builder.
43
42
  *
44
43
  * @param context A `Context` object containing configuration settings for this Builder.
45
44
  * Defaults to an empty `Context` using default settings if one is not provided.
46
45
  */
47
46
  static async newAsync(context = new Context()) {
48
- const settingsStr = resolveSettingsForNeon(context);
47
+ const settingsStr = await resolveSettingsForNeon(context);
49
48
  const builder = getNeonBinary().builderNew(settingsStr);
50
49
  return new Builder(builder);
51
50
  }
@@ -56,7 +55,7 @@ export class Builder {
56
55
  */
57
56
  static withJson(json, settings) {
58
57
  const jsonString = stringifyManifestDefinition(json);
59
- const settingsStr = resolveSettingsForNeon(settings);
58
+ const settingsStr = resolveRawSettingsForNeon(settings);
60
59
  const builder = getNeonBinary().builderWithJson(jsonString, settingsStr);
61
60
  return new Builder(builder);
62
61
  }
@@ -64,8 +63,7 @@ export class Builder {
64
63
  * Create a Builder from a manifest definition, configured by a `Context`. Prefer this over
65
64
  * the deprecated {@link Builder.withJson}.
66
65
  *
67
- * Declared async for forward compatibility. Upcoming work will allow c2pa-node
68
- * to resolve trust anchors at construction time.
66
+ * Resolves trust-anchor URLs in the Context before constructing the Builder.
69
67
  *
70
68
  * @param json The manifest JSON.
71
69
  * @param context A `Context` object containing configuration settings for this Builder.
@@ -73,7 +71,7 @@ export class Builder {
73
71
  */
74
72
  static async withJsonAsync(json, context = new Context()) {
75
73
  const jsonString = stringifyManifestDefinition(json);
76
- const settingsStr = resolveSettingsForNeon(context);
74
+ const settingsStr = await resolveSettingsForNeon(context);
77
75
  const builder = getNeonBinary().builderWithJson(jsonString, settingsStr);
78
76
  return new Builder(builder);
79
77
  }
@@ -118,7 +116,7 @@ export class Builder {
118
116
  * the same as `undefined`.
119
117
  */
120
118
  static async fromArchive(asset, settingsOrContext) {
121
- const settingsStr = resolveSettingsForNeon(settingsOrContext);
119
+ const settingsStr = await resolveSettingsForNeon(settingsOrContext);
122
120
  return new Builder(await getNeonBinary().builderFromArchive(asset, settingsStr));
123
121
  }
124
122
  sign(signer, input, output) {
@@ -7,6 +7,8 @@ import { Context } from "@contentauth/c2pa-utilities";
7
7
  import fs from "fs-extra";
8
8
  import path from "path";
9
9
  import * as crypto from "crypto";
10
+ import { vi } from "vitest";
11
+ import http from "http";
10
12
  import { isActionsAssertion } from "./assertions.js";
11
13
  import { CallbackSigner, LocalSigner } from "./Signer.js";
12
14
  import { Reader } from "./Reader.js";
@@ -356,6 +358,64 @@ describe("Builder", () => {
356
358
  expect(manifestStore.active_manifest).not.toBeUndefined();
357
359
  expect(activeManifest?.title).toBe("Test_Manifest");
358
360
  });
361
+ it("should send a time-stamp request to the callback signer's tsaUrl", async () => {
362
+ // A local TSA that records each request and refuses it.
363
+ const tsaRequests = [];
364
+ const tsa = http.createServer((req, res) => {
365
+ tsaRequests.push(req.headers);
366
+ req.resume();
367
+ req.on("end", () => {
368
+ res.writeHead(503);
369
+ res.end();
370
+ });
371
+ });
372
+ await new Promise((resolve) => tsa.listen(0, "127.0.0.1", resolve));
373
+ const { port } = tsa.address();
374
+ try {
375
+ const signerConfig = {
376
+ alg: "es256",
377
+ certs: [publicKey],
378
+ reserveSize: 20000,
379
+ tsaUrl: `http://127.0.0.1:${port}/tsa`,
380
+ tsaHeaders: [["x-c2pa-test", "tsa-header"]],
381
+ directCoseHandling: false,
382
+ };
383
+ const testSigner = new TestSigner(privateKey);
384
+ const signer = CallbackSigner.newSigner(signerConfig, testSigner.sign);
385
+ // The TSA refuses, so signing must fail instead of silently
386
+ // producing a manifest without a time-stamp.
387
+ await expect(builder.signAsync(signer, source, { buffer: null })).rejects.toThrow();
388
+ expect(tsaRequests.length).toBeGreaterThan(0);
389
+ expect(tsaRequests[0]["content-type"]).toBe("application/timestamp-query");
390
+ expect(tsaRequests[0]["x-c2pa-test"]).toBe("tsa-header");
391
+ }
392
+ finally {
393
+ tsa.closeAllConnections();
394
+ await new Promise((resolve) => tsa.close(() => resolve()));
395
+ }
396
+ });
397
+ // Needs network access to a real RFC 3161 TSA, e.g.
398
+ // C2PA_TEST_TSA_URL=http://timestamp.digicert.com
399
+ it.skipIf(!process.env.C2PA_TEST_TSA_URL)("should time-stamp a manifest signed with a callback signer", async () => {
400
+ const dest = {
401
+ buffer: null,
402
+ };
403
+ const signerConfig = {
404
+ alg: "es256",
405
+ certs: [publicKey],
406
+ reserveSize: 20000,
407
+ tsaUrl: process.env.C2PA_TEST_TSA_URL,
408
+ directCoseHandling: false,
409
+ };
410
+ const testSigner = new TestSigner(privateKey);
411
+ const signer = CallbackSigner.newSigner(signerConfig, testSigner.sign);
412
+ await builder.signAsync(signer, source, dest);
413
+ const reader = await Reader.fromAsset({
414
+ buffer: dest.buffer,
415
+ mimeType: "jpeg",
416
+ });
417
+ expect(reader.getActive()?.signature_info?.time).toBeTruthy();
418
+ }, 30000);
359
419
  it("should preserve JSON assertion characters without escaping", async () => {
360
420
  const fingerprintAssertion = JSON.stringify({
361
421
  alg: "sha256",
@@ -614,6 +674,12 @@ describe("Builder", () => {
614
674
  const definition = builder.getManifestDefinition();
615
675
  expect(definition.redactions).toEqual([uri1, uri2]);
616
676
  });
677
+ it("should set a label", () => {
678
+ const label = "urn:c2pa:00000000-0000-4000-8000-000000000000";
679
+ const builder = Builder.new();
680
+ builder.updateManifestProperty("label", label);
681
+ expect(builder.getManifestDefinition().label).toBe(label);
682
+ });
617
683
  it("should test builder remote url", async () => {
618
684
  // This test mirrors the Rust test_builder_remote_url test
619
685
  // Create a simple manifest definition similar to simple_manifest_json()
@@ -836,6 +902,43 @@ describe("Builder", () => {
836
902
  const manifestStore = reader.json();
837
903
  expect(manifestStore.validation_status ?? []).not.toContainEqual(expect.objectContaining({ code: "signingCredential.untrusted" }));
838
904
  });
905
+ it("newAsync(context) fetches trust-anchor URLs before creating the Builder", async () => {
906
+ const pem = "-----BEGIN CERTIFICATE-----\nanchor\n-----END CERTIFICATE-----";
907
+ const fetch = vi.fn(async () => new Response(pem));
908
+ vi.stubGlobal("fetch", fetch);
909
+ try {
910
+ const context = new Context({
911
+ trust: { trustAnchors: "https://example.com/anchors.pem" },
912
+ });
913
+ await Builder.newAsync(context);
914
+ expect(fetch).toHaveBeenCalledOnce();
915
+ const resolvedSettings = JSON.parse(await context.toJson());
916
+ expect(resolvedSettings.trust.anchors[0].trust_anchors).toBe(pem);
917
+ }
918
+ finally {
919
+ vi.unstubAllGlobals();
920
+ }
921
+ });
922
+ it("newAsync(context) retries failed trust-anchor fetches", async () => {
923
+ const pem = "-----BEGIN CERTIFICATE-----\nanchor\n-----END CERTIFICATE-----";
924
+ const fetch = vi
925
+ .fn()
926
+ .mockResolvedValueOnce(new Response("", { status: 503 }))
927
+ .mockResolvedValueOnce(new Response(pem));
928
+ vi.stubGlobal("fetch", fetch);
929
+ try {
930
+ const context = new Context({
931
+ trust: { trustAnchors: "https://example.com/anchors.pem" },
932
+ });
933
+ await Builder.newAsync(context);
934
+ expect(fetch).toHaveBeenCalledTimes(2);
935
+ const resolvedSettings = JSON.parse(await context.toJson());
936
+ expect(resolvedSettings.trust.anchors[0].trust_anchors).toBe(pem);
937
+ }
938
+ finally {
939
+ vi.unstubAllGlobals();
940
+ }
941
+ });
839
942
  it("withJsonAsync(json, context) applies the Context's settings", async () => {
840
943
  const dest = { path: path.join(tempDir, "context_withjson_signed.jpg") };
841
944
  const signer = LocalSigner.newSigner(publicKey, privateKey, "es256");
@@ -5,6 +5,7 @@
5
5
  // at your option.
6
6
  import fs from "fs-extra";
7
7
  import * as crypto from "crypto";
8
+ import { spawnSync } from "child_process";
8
9
  import { encode } from "cbor2";
9
10
  class TestSigner {
10
11
  privateKey;
@@ -174,6 +175,35 @@ describe("CallbackCredentialHolder accessors", () => {
174
175
  expect(payload.referencedAssertions[0].url).toBe("self#jumbf=c2pa.assertions/cawg.training-mining");
175
176
  expect(Buffer.from(payload.referencedAssertions[0].hash)).toEqual(Buffer.from([9, 8, 7]));
176
177
  });
178
+ it("releases main loop when idle", () => {
179
+ // Note: Runs in a child process, since tests a potential hang.
180
+ const scriptEntrypoint = new URL("../dist/index.js", import.meta.url).href;
181
+ // Check the run of the script releases channels, to free up main loop.
182
+ const testScript = `
183
+ import {
184
+ CallbackCredentialHolder,
185
+ CallbackSigner,
186
+ IdentityAssertionSigner,
187
+ } from ${JSON.stringify(scriptEntrypoint)};
188
+ const signer = CallbackSigner.newSigner(
189
+ { alg: "es256", certs: [Buffer.alloc(1)], reserveSize: 1000, directCoseHandling: false },
190
+ async () => Buffer.alloc(64),
191
+ );
192
+ globalThis.kept = [
193
+ signer,
194
+ IdentityAssertionSigner.new(signer.getHandle()),
195
+ CallbackCredentialHolder.newCallbackCredentialHolder(
196
+ 1000,
197
+ "cawg.x509.cose",
198
+ async () => Buffer.alloc(1),
199
+ ),
200
+ ];
201
+ `;
202
+ const runResult = spawnSync(process.execPath, ["--input-type=module", "-e", testScript], { timeout: 5_000, encoding: "utf8" });
203
+ expect(runResult.stderr).not.toMatch(/Error/);
204
+ expect(runResult.signal).toBeNull();
205
+ expect(runResult.status).toBe(0);
206
+ });
177
207
  });
178
208
  describe("handles reserveSize", () => {
179
209
  async function signWithReserveSize(reserveSize) {
package/dist/Reader.js CHANGED
@@ -5,7 +5,7 @@
5
5
  // at your option.
6
6
  import { getNeonBinary } from "./binary.js";
7
7
  import { validateSourceAssetSize } from "./assetSize.js";
8
- import { resolveSettingsForNeon } from "./Settings.js";
8
+ import { resolveSdkConfig, resolveSettingsForNeon } from "./Settings.js";
9
9
  export class Reader {
10
10
  reader;
11
11
  constructor(reader) {
@@ -29,8 +29,8 @@ export class Reader {
29
29
  * the same as `undefined`.
30
30
  */
31
31
  static async fromAsset(asset, settingsOrContext) {
32
- await validateSourceAssetSize(asset);
33
- const settingsStr = resolveSettingsForNeon(settingsOrContext);
32
+ await validateSourceAssetSize(asset, resolveSdkConfig(settingsOrContext));
33
+ const settingsStr = await resolveSettingsForNeon(settingsOrContext);
34
34
  const reader = await getNeonBinary().readerFromAsset(asset, settingsStr);
35
35
  return reader ? new Reader(reader) : null;
36
36
  }
@@ -40,8 +40,8 @@ export class Reader {
40
40
  * the same as `undefined`.
41
41
  */
42
42
  static async fromManifestDataAndAsset(manifestData, asset, settingsOrContext) {
43
- await validateSourceAssetSize(asset);
44
- const settingsStr = resolveSettingsForNeon(settingsOrContext);
43
+ await validateSourceAssetSize(asset, resolveSdkConfig(settingsOrContext));
44
+ const settingsStr = await resolveSettingsForNeon(settingsOrContext);
45
45
  const reader = await getNeonBinary().readerFromManifestDataAndAsset(manifestData, asset, settingsStr);
46
46
  return new Reader(reader);
47
47
  }
@@ -151,6 +151,10 @@ describe("Reader", () => {
151
151
  await fs.truncate(oversizedPath, MAX_SIZE_IN_BYTES + 1);
152
152
  await expect(Reader.fromAsset({ path: oversizedPath })).rejects.toThrow(AssetTooLargeError);
153
153
  });
154
+ it("should honor a lower max size from a Context", async () => {
155
+ const context = new Context(undefined, { maxSizeInBytes: 1 });
156
+ await expect(Reader.fromAsset({ path: "./tests/fixtures/A.jpg" }, context)).rejects.toThrow(AssetTooLargeError);
157
+ });
154
158
  it("should read from manifest data and buffer", async () => {
155
159
  const manifestData = await fs.readFile("./tests/fixtures/CA/manifest_data.c2pa");
156
160
  const buffer = await fs.readFile("./tests/fixtures/CA.jpg");
package/dist/Settings.js CHANGED
@@ -10,7 +10,7 @@
10
10
  // specific language governing permissions and limitations under
11
11
  // each license.
12
12
  import fs from "fs-extra";
13
- import { Context, settingsToJson, withDefaultSettings } from "@contentauth/c2pa-utilities";
13
+ import { Context } from "@contentauth/c2pa-utilities";
14
14
  /**
15
15
  * This file contains only Settings functions that are unique to the Node SDK.
16
16
  *
@@ -27,21 +27,40 @@ export async function loadSettingsFromFile(filePath) {
27
27
  return content;
28
28
  }
29
29
  /**
30
- * Resolves a settings argument (either the deprecated raw `C2paSettings or a `Context`) into
31
- * a JSON string that can be passed into the native library.
30
+ * Reads the SDK config out of a settings argument.
32
31
  *
33
- * Unlike `c2pa-web`'s `Context.toJson()`, this does not resolve trust-anchor URLs: `c2pa-node`
34
- * doesn't perform trust-anchor URL fetching yet, so a `Context`'s settings are only merged with
35
- * this package's defaults and serialized here.
32
+ * Only a `Context` carries an SDK config so the deprecated raw `C2paSettings` forms always
33
+ * resolve to `undefined`, leaving this package's defaults in place.
34
+ *
35
+ * @param settingsOrContext A `Context`, or (@deprecated) a raw `C2paSettings` string/object.
36
+ * @returns The `Context`'s SDK config, or `undefined` if there is none.
36
37
  */
37
- export function resolveSettingsForNeon(settingsOrContext) {
38
+ export function resolveSdkConfig(settingsOrContext) {
39
+ return settingsOrContext instanceof Context
40
+ ? settingsOrContext.sdkConfig
41
+ : undefined;
42
+ }
43
+ /**
44
+ * Resolves Context settings, including any trust-anchor URLs, before passing them to the native
45
+ * library. Deprecated raw settings retain their existing pass-through behavior.
46
+ */
47
+ export async function resolveSettingsForNeon(settingsOrContext) {
38
48
  if (settingsOrContext == null) {
39
49
  return undefined;
40
50
  }
41
51
  if (settingsOrContext instanceof Context) {
42
- return settingsToJson(withDefaultSettings(settingsOrContext.settings));
52
+ return settingsOrContext.toJson();
43
53
  }
44
54
  return typeof settingsOrContext === "string"
45
55
  ? settingsOrContext
46
56
  : JSON.stringify(settingsOrContext);
47
57
  }
58
+ /**
59
+ * Resolves deprecated raw settings for the synchronous Builder factories.
60
+ */
61
+ export function resolveRawSettingsForNeon(settings) {
62
+ if (settings == null) {
63
+ return undefined;
64
+ }
65
+ return typeof settings === "string" ? settings : JSON.stringify(settings);
66
+ }
@@ -7,7 +7,8 @@ import fs from "fs-extra";
7
7
  import * as path from "path";
8
8
  import * as os from "os";
9
9
  import { Context, DEFAULT_SETTINGS, mergeSettings, settingsToJson, } from "@contentauth/c2pa-utilities";
10
- import { loadSettingsFromFile, resolveSettingsForNeon } from "./Settings.js";
10
+ import { vi } from "vitest";
11
+ import { loadSettingsFromFile, resolveRawSettingsForNeon, resolveSdkConfig, resolveSettingsForNeon, } from "./Settings.js";
11
12
  describe("Settings", () => {
12
13
  describe("loadSettingsFromFile", () => {
13
14
  let tempDir;
@@ -47,36 +48,80 @@ verify_after_sign = false`;
47
48
  await expect(loadSettingsFromFile(filePath)).rejects.toThrow();
48
49
  });
49
50
  });
50
- describe("resolveSettingsForNeon", () => {
51
+ describe("resolveRawSettingsForNeon", () => {
51
52
  it("returns undefined when omitted", () => {
52
- expect(resolveSettingsForNeon(undefined)).toBeUndefined();
53
+ expect(resolveRawSettingsForNeon(undefined)).toBeUndefined();
53
54
  });
54
55
  it("returns undefined when null is passed in", () => {
55
56
  // A plain-JS caller can pass `null` explicitly.
56
57
  // It must not fall through to JSON.stringify(null), which would send the
57
58
  // native library the literal string "null" instead of "no settings".
58
- expect(resolveSettingsForNeon(null)).toBeUndefined();
59
+ expect(resolveRawSettingsForNeon(null)).toBeUndefined();
60
+ });
61
+ it("passes raw settings through unchanged", () => {
62
+ const rawSettings = { verify: { verify_trust: false } };
63
+ const result = resolveRawSettingsForNeon(rawSettings);
64
+ expect(JSON.parse(result)).toEqual(rawSettings);
65
+ });
66
+ it("passes raw settings JSON through unchanged", () => {
67
+ const json = JSON.stringify({ verify: { verify_trust: false } });
68
+ expect(resolveRawSettingsForNeon(json)).toBe(json);
69
+ });
70
+ });
71
+ describe("resolveSettingsForNeon", () => {
72
+ it("returns undefined when omitted", async () => {
73
+ expect(await resolveSettingsForNeon(undefined)).toBeUndefined();
74
+ });
75
+ it("returns undefined when null is passed in", async () => {
76
+ expect(await resolveSettingsForNeon(null)).toBeUndefined();
59
77
  });
60
- it("applies defaults for an empty Context", () => {
61
- const result = resolveSettingsForNeon(new Context());
78
+ it("applies defaults for an empty Context", async () => {
79
+ const result = await resolveSettingsForNeon(new Context());
62
80
  expect(JSON.parse(result)).toEqual(JSON.parse(settingsToJson(DEFAULT_SETTINGS)));
63
81
  });
64
- it("merges a Context's settings with defaults", () => {
82
+ it("does not serialize a Context's SDK config", async () => {
83
+ const result = await resolveSettingsForNeon(new Context(undefined, { maxSizeInBytes: 42 }));
84
+ expect(JSON.parse(result)).toEqual(JSON.parse(settingsToJson(DEFAULT_SETTINGS)));
85
+ });
86
+ it("merges a Context's settings with defaults", async () => {
65
87
  const settings = { verify: { verifyTrust: false } };
66
- const result = resolveSettingsForNeon(new Context(settings));
88
+ const result = await resolveSettingsForNeon(new Context(settings));
67
89
  expect(JSON.parse(result)).toEqual(JSON.parse(settingsToJson(mergeSettings(DEFAULT_SETTINGS, settings))));
68
90
  });
69
- it("passes a raw settings object through as-is, without applying defaults", () => {
70
- // The deprecated raw-settings path preserves this package's pre-Context behavior exactly:
71
- // no defaults are merged in, unlike the Context path above.
72
- const result = resolveSettingsForNeon({
73
- verify: { verify_trust: false },
74
- });
75
- expect(JSON.parse(result)).toEqual({ verify: { verify_trust: false } });
91
+ it("fetches trust-anchor URLs before returning Context settings", async () => {
92
+ const pem = "-----BEGIN CERTIFICATE-----\nanchor\n-----END CERTIFICATE-----";
93
+ const fetch = vi.fn(async () => new Response(pem));
94
+ vi.stubGlobal("fetch", fetch);
95
+ try {
96
+ const result = await resolveSettingsForNeon(new Context({
97
+ trust: { trustAnchors: "https://example.com/anchors.pem" },
98
+ }));
99
+ expect(fetch).toHaveBeenCalledOnce();
100
+ expect(JSON.parse(result).trust.anchors[0].trust_anchors).toBe(pem);
101
+ }
102
+ finally {
103
+ vi.unstubAllGlobals();
104
+ }
76
105
  });
77
- it("passes a raw settings JSON string through unchanged", () => {
78
- const json = JSON.stringify({ verify: { verify_trust: false } });
79
- expect(resolveSettingsForNeon(json)).toBe(json);
106
+ it("keeps deprecated raw settings unchanged", async () => {
107
+ const rawSettings = { verify: { verify_trust: false } };
108
+ const result = await resolveSettingsForNeon(rawSettings);
109
+ expect(JSON.parse(result)).toEqual(rawSettings);
110
+ });
111
+ });
112
+ describe("resolveSdkConfig", () => {
113
+ it("returns a Context's SDK config", () => {
114
+ const sdkConfig = { maxSizeInBytes: 42 };
115
+ expect(resolveSdkConfig(new Context(undefined, sdkConfig))).toEqual(sdkConfig);
116
+ });
117
+ it("returns undefined when a Context carries no SDK config", () => {
118
+ expect(resolveSdkConfig(new Context())).toBeUndefined();
119
+ });
120
+ it("returns undefined for the deprecated raw settings forms", () => {
121
+ expect(resolveSdkConfig(undefined)).toBeUndefined();
122
+ expect(resolveSdkConfig(null)).toBeUndefined();
123
+ expect(resolveSdkConfig({ verify: { verifyTrust: false } })).toBeUndefined();
124
+ expect(resolveSdkConfig('{"verify":{"verify_trust":false}}')).toBeUndefined();
80
125
  });
81
126
  });
82
127
  });
package/dist/assetSize.js CHANGED
@@ -10,7 +10,7 @@
10
10
  // specific language governing permissions and limitations under
11
11
  // each license.
12
12
  import fs from "fs-extra";
13
- import { validateAssetSize } from "@contentauth/c2pa-utilities";
13
+ import { resolveConfiguredMaxSizeInBytes, validateAssetSize, } from "@contentauth/c2pa-utilities";
14
14
  // c2pa-node runs server-side, so it can reasonably support larger assets than c2pa-web,
15
15
  // and may be less resource-constrained in comparison.
16
16
  export const MAX_SIZE_IN_BYTES = 10 * 10 ** 9; // 10 GB
@@ -22,14 +22,20 @@ export const MAX_SIZE_IN_BYTES = 10 * 10 ** 9; // 10 GB
22
22
  * so the memory cost isn't prevented, only reader construction is. Prefer `path`
23
23
  * for large or untrusted assets.
24
24
  *
25
+ * @param asset The asset to validate.
26
+ * @param sdkConfig SDK config from a `Context`. A missing `maxSizeInBytes` falls back
27
+ * to {@link MAX_SIZE_IN_BYTES}.
28
+ *
29
+ * @throws {RangeError} If `maxSizeInBytes` isn't a finite, positive number.
25
30
  * @throws Error if reading the `FileAsset` fails.
26
31
  * @throws {AssetTooLargeError} If `sizeInBytes` exceeds the resolved limit.
27
32
  */
28
- export async function validateSourceAssetSize(asset) {
33
+ export async function validateSourceAssetSize(asset, sdkConfig) {
34
+ const maxSizeInBytes = resolveConfiguredMaxSizeInBytes(sdkConfig, MAX_SIZE_IN_BYTES);
29
35
  if ("buffer" in asset) {
30
- validateAssetSize(asset.buffer.length, MAX_SIZE_IN_BYTES);
36
+ validateAssetSize(asset.buffer.length, maxSizeInBytes);
31
37
  return;
32
38
  }
33
39
  const { size } = await fs.stat(asset.path);
34
- validateAssetSize(size, MAX_SIZE_IN_BYTES);
40
+ validateAssetSize(size, maxSizeInBytes);
35
41
  }
@@ -0,0 +1,55 @@
1
+ // Copyright 2026 Adobe. All rights reserved.
2
+ // This file is licensed to you under the Apache License,
3
+ // Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
4
+ // or the MIT license (http://opensource.org/licenses/MIT),
5
+ // at your option.
6
+ // Unless required by applicable law or agreed to in writing,
7
+ // this software is distributed on an "AS IS" BASIS, WITHOUT
8
+ // WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
9
+ // implied. See the LICENSE-MIT and LICENSE-APACHE files for the
10
+ // specific language governing permissions and limitations under
11
+ // each license.
12
+ import fs from "fs-extra";
13
+ import * as os from "os";
14
+ import * as path from "path";
15
+ import { AssetTooLargeError } from "@contentauth/c2pa-utilities";
16
+ import { MAX_SIZE_IN_BYTES, validateSourceAssetSize } from "./assetSize.js";
17
+ describe("validateSourceAssetSize", () => {
18
+ let tempDir;
19
+ beforeEach(async () => {
20
+ tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "c2pa-asset-size-test-"));
21
+ });
22
+ afterEach(async () => {
23
+ await fs.remove(tempDir);
24
+ });
25
+ async function createFile(sizeInBytes) {
26
+ const filePath = path.join(tempDir, "asset.bin");
27
+ await fs.ensureFile(filePath);
28
+ await fs.truncate(filePath, sizeInBytes);
29
+ return filePath;
30
+ }
31
+ it("accepts a buffer within the default limit", async () => {
32
+ await expect(validateSourceAssetSize({ buffer: Buffer.alloc(10), mimeType: "image/jpeg" })).resolves.toBeUndefined();
33
+ });
34
+ it("accepts a file within the default limit", async () => {
35
+ const filePath = await createFile(10);
36
+ await expect(validateSourceAssetSize({ path: filePath })).resolves.toBeUndefined();
37
+ });
38
+ it("rejects a file over the default limit", async () => {
39
+ const filePath = await createFile(MAX_SIZE_IN_BYTES + 1);
40
+ await expect(validateSourceAssetSize({ path: filePath })).rejects.toThrow(AssetTooLargeError);
41
+ });
42
+ it("accepts a file over the default limit when a higher maxSizeInBytes is given", async () => {
43
+ const filePath = await createFile(MAX_SIZE_IN_BYTES + 1);
44
+ await expect(validateSourceAssetSize({ path: filePath }, { maxSizeInBytes: MAX_SIZE_IN_BYTES + 2 })).resolves.toBeUndefined();
45
+ });
46
+ it("rejects a buffer over a lower maxSizeInBytes", async () => {
47
+ await expect(validateSourceAssetSize({ buffer: Buffer.alloc(10), mimeType: "image/jpeg" }, { maxSizeInBytes: 9 })).rejects.toThrow(AssetTooLargeError);
48
+ });
49
+ it("accepts a buffer exactly at maxSizeInBytes", async () => {
50
+ await expect(validateSourceAssetSize({ buffer: Buffer.alloc(10), mimeType: "image/jpeg" }, { maxSizeInBytes: 10 })).resolves.toBeUndefined();
51
+ });
52
+ it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY])("throws a RangeError for an invalid maxSizeInBytes of %s", async (maxSizeInBytes) => {
53
+ await expect(validateSourceAssetSize({ buffer: Buffer.alloc(10), mimeType: "image/jpeg" }, { maxSizeInBytes })).rejects.toThrow(RangeError);
54
+ });
55
+ });
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: 52149592 bytes
4
- sha256: 73446c43f956ffb81440f11820c43924ddaf0c0f7359a6c1315f0a1c8cb2959c
3
+ size: 52231912 bytes
4
+ sha256: 454157566c12a23b7284bce2d66644c0db33f214351c55d28438dbe832a6203c
@@ -14,8 +14,7 @@ export declare class Builder implements BuilderInterface {
14
14
  * Create a Builder with a minimal manifest definition, configured by a `Context`.
15
15
  * Prefer this over the deprecated {@link Builder.new}.
16
16
  *
17
- * Declared async for forward compatibility. Upcoming work will allow for trust anchor
18
- * resolution at construction time.
17
+ * Resolves trust-anchor URLs in the Context before constructing the Builder.
19
18
  *
20
19
  * @param context A `Context` object containing configuration settings for this Builder.
21
20
  * Defaults to an empty `Context` using default settings if one is not provided.
@@ -31,8 +30,7 @@ export declare class Builder implements BuilderInterface {
31
30
  * Create a Builder from a manifest definition, configured by a `Context`. Prefer this over
32
31
  * the deprecated {@link Builder.withJson}.
33
32
  *
34
- * Declared async for forward compatibility. Upcoming work will allow c2pa-node
35
- * to resolve trust anchors at construction time.
33
+ * Resolves trust-anchor URLs in the Context before constructing the Builder.
36
34
  *
37
35
  * @param json The manifest JSON.
38
36
  * @param context A `Context` object containing configuration settings for this Builder.
@@ -59,7 +57,7 @@ export declare class Builder implements BuilderInterface {
59
57
  signConfigAsync(callback: (data: Buffer) => Promise<Buffer>, signerConfig: JsCallbackSignerConfig, input: SourceAsset, output: DestinationAsset): Promise<Buffer>;
60
58
  signAsync(signer: CallbackSignerInterface | IdentityAssertionSignerInterface, input: SourceAsset, output: DestinationAsset): Promise<Buffer>;
61
59
  getManifestDefinition(): Manifest;
62
- updateManifestProperty(property: string, value: ClaimVersion): void;
60
+ updateManifestProperty(property: string, value: string | ClaimVersion): void;
63
61
  addRedaction(uri: string, reason: C2paReason): void;
64
62
  filterActions(keep: (action: Action) => boolean): void;
65
63
  filterIngredients(rescue: (ingredient: Ingredient, provenance: ManifestStore | null) => boolean): void;
@@ -1,4 +1,4 @@
1
- import { Context } from "@contentauth/c2pa-utilities";
1
+ import { Context, type SdkConfig } from "@contentauth/c2pa-utilities";
2
2
  import type { C2paSettings } from "./types.d.ts";
3
3
  /**
4
4
  * This file contains only Settings functions that are unique to the Node SDK.
@@ -13,11 +13,21 @@ import type { C2paSettings } from "./types.d.ts";
13
13
  */
14
14
  export declare function loadSettingsFromFile(filePath: string): Promise<string>;
15
15
  /**
16
- * Resolves a settings argument (either the deprecated raw `C2paSettings or a `Context`) into
17
- * a JSON string that can be passed into the native library.
16
+ * Reads the SDK config out of a settings argument.
18
17
  *
19
- * Unlike `c2pa-web`'s `Context.toJson()`, this does not resolve trust-anchor URLs: `c2pa-node`
20
- * doesn't perform trust-anchor URL fetching yet, so a `Context`'s settings are only merged with
21
- * this package's defaults and serialized here.
18
+ * Only a `Context` carries an SDK config so the deprecated raw `C2paSettings` forms always
19
+ * resolve to `undefined`, leaving this package's defaults in place.
20
+ *
21
+ * @param settingsOrContext A `Context`, or (@deprecated) a raw `C2paSettings` string/object.
22
+ * @returns The `Context`'s SDK config, or `undefined` if there is none.
23
+ */
24
+ export declare function resolveSdkConfig(settingsOrContext: C2paSettings | Context | null | undefined): SdkConfig | undefined;
25
+ /**
26
+ * Resolves Context settings, including any trust-anchor URLs, before passing them to the native
27
+ * library. Deprecated raw settings retain their existing pass-through behavior.
28
+ */
29
+ export declare function resolveSettingsForNeon(settingsOrContext: C2paSettings | Context | null | undefined): Promise<string | undefined>;
30
+ /**
31
+ * Resolves deprecated raw settings for the synchronous Builder factories.
22
32
  */
23
- export declare function resolveSettingsForNeon(settingsOrContext: C2paSettings | Context | null | undefined): string | undefined;
33
+ export declare function resolveRawSettingsForNeon(settings: C2paSettings | null | undefined): string | undefined;
@@ -1,3 +1,4 @@
1
+ import { type SdkConfig } from "@contentauth/c2pa-utilities";
1
2
  import type { SourceAsset } from "./types.d.ts";
2
3
  export declare const MAX_SIZE_IN_BYTES: number;
3
4
  /**
@@ -8,7 +9,12 @@ export declare const MAX_SIZE_IN_BYTES: number;
8
9
  * so the memory cost isn't prevented, only reader construction is. Prefer `path`
9
10
  * for large or untrusted assets.
10
11
  *
12
+ * @param asset The asset to validate.
13
+ * @param sdkConfig SDK config from a `Context`. A missing `maxSizeInBytes` falls back
14
+ * to {@link MAX_SIZE_IN_BYTES}.
15
+ *
16
+ * @throws {RangeError} If `maxSizeInBytes` isn't a finite, positive number.
11
17
  * @throws Error if reading the `FileAsset` fails.
12
18
  * @throws {AssetTooLargeError} If `sizeInBytes` exceeds the resolved limit.
13
19
  */
14
- export declare function validateSourceAssetSize(asset: SourceAsset): Promise<void>;
20
+ export declare function validateSourceAssetSize(asset: SourceAsset, sdkConfig?: SdkConfig): Promise<void>;
@@ -0,0 +1 @@
1
+ export {};
@@ -332,8 +332,8 @@ export interface BuilderInterface {
332
332
  getManifestDefinition(): Manifest;
333
333
 
334
334
  /**
335
- * Update a string property of the manifest
336
- * @returns The manifest definition
335
+ * Update a property of the manifest. Throws for an unsupported property or type.
336
+ * Calling while a signAsync is pending hangs the process: it blocks the thread the signer callback needs.
337
337
  */
338
338
  updateManifestProperty(property: string, value: string | ClaimVersion): void;
339
339
 
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.9.10",
8
+ "version": "0.9.12",
9
9
  "description": "Node.js bindings for C2PA",
10
10
  "main": "dist/index.js",
11
11
  "type": "module",
@@ -64,8 +64,8 @@
64
64
  "pkg-dir": "^8.0.0",
65
65
  "pretty-bytes": "^6.1.1",
66
66
  "unzipper": "^0.10.14",
67
- "@contentauth/c2pa-types": "0.7.6",
68
- "@contentauth/c2pa-utilities": "0.3.2"
67
+ "@contentauth/c2pa-types": "0.7.8",
68
+ "@contentauth/c2pa-utilities": "0.4.0"
69
69
  },
70
70
  "nx": {
71
71
  "tags": [
@@ -106,7 +106,8 @@ impl NeonCallbackCredentialHolder {
106
106
  let reserve_size = cx.argument::<JsNumber>(0)?.value(&mut cx) as usize;
107
107
  let sig_type = cx.argument::<JsString>(1)?.value(&mut cx);
108
108
  let callback = cx.argument::<JsFunction>(2)?.root(&mut cx);
109
- let channel = cx.channel();
109
+ let mut channel = cx.channel();
110
+ channel.unref(&mut cx);
110
111
  Ok(cx.boxed(Self::new(
111
112
  channel,
112
113
  Arc::new(callback),
@@ -164,7 +164,8 @@ impl NeonCallbackSigner {
164
164
  let config_handle = cx.argument::<JsBox<CallbackSignerConfig>>(0)?;
165
165
  let config_ref: &CallbackSignerConfig = config_handle.deref();
166
166
  let callback = cx.argument::<JsFunction>(1)?.root(&mut cx);
167
- let channel = cx.channel();
167
+ let mut channel = cx.channel();
168
+ channel.unref(&mut cx);
168
169
  Ok(cx.boxed(Self::new(channel, Arc::new(callback), config_ref.clone())))
169
170
  }
170
171
 
@@ -319,6 +320,17 @@ impl AsyncSigner for NeonCallbackSigner {
319
320
  self.config.reserve_size
320
321
  }
321
322
 
323
+ // Since c2pa-rs 0.91, async signing reaches the TSA only through these
324
+ // `AsyncSigner` methods; without them the defaults return `None` and
325
+ // `tsaUrl` / `tsaHeaders` are silently ignored.
326
+ fn time_authority_url(&self) -> Option<String> {
327
+ self.config.tsa_url.clone()
328
+ }
329
+
330
+ fn timestamp_request_headers(&self) -> Option<Vec<(String, String)>> {
331
+ self.config.tsa_headers.clone()
332
+ }
333
+
322
334
  fn direct_cose_handling(&self) -> bool {
323
335
  self.config.direct_cose_handling
324
336
  }