@contentauth/c2pa-node 0.12.0 → 0.12.2

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
@@ -145,6 +145,10 @@ const isEmbedded = reader.isEmbedded();
145
145
  const remoteUrl = reader.remoteUrl();
146
146
  ```
147
147
 
148
+ Node keeps the latest resolved settings JSON and native context handle for each JavaScript `Context` in a `WeakMap`. Repeated `Reader` and `Builder` construction with the same effective settings reuses that handle without retransferring or reparsing the JSON. Successful settings resolution stays memoized within the `Context`; create a new `Context` to resolve updated trust resources. Existing Readers and Builders retain their construction-time settings.
149
+
150
+ The shared native context also owns cancellation/progress state, although Node does not expose those native APIs today. Future per-instance controls must revisit this ownership: cancellation would affect all users of that native context, and progress callbacks would receive events from multiple operations.
151
+
148
152
  `Reader.fromAsset` and `Reader.fromManifestDataAndAsset` reject assets larger than 10 GB, throwing `AssetTooLargeError` (exported from `@contentauth/c2pa-node`). Note that for a `SourceBufferAsset`, this only rejects after the buffer is already fully allocated in memory. Pass a `FileAsset` instead for large or untrusted assets so oversized files are rejected before being read into memory.
149
153
 
150
154
  > [!WARNING]
@@ -637,6 +641,7 @@ The library provides helper functions to create and manage settings objects:
637
641
  import {
638
642
  Context,
639
643
  createTrustSettings,
644
+ createTsaTrustSettings,
640
645
  createCawgTrustSettings,
641
646
  createVerifySettings,
642
647
  mergeSettings
@@ -650,10 +655,16 @@ const trustSettings = createTrustSettings({
650
655
  allowedList: "path/to/allowed-list.pem"
651
656
  });
652
657
 
658
+ // Create timestamp trust settings.
659
+ const tsaTrustSettings = createTsaTrustSettings({
660
+ trustAnchors: "path/to/tsa-anchors.pem"
661
+ });
662
+
653
663
  // Create CAWG trust settings
654
664
  const cawgTrustSettings = createCawgTrustSettings({
655
665
  verifyTrustList: true,
656
- trustAnchors: "path/to/cawg-anchors.pem"
666
+ trustAnchors: "path/to/cawg-anchors.pem",
667
+ trustedIcaIssuers: ["did:web:example.com"]
657
668
  });
658
669
 
659
670
  // Create verify settings
@@ -683,8 +694,11 @@ Low-level serialization and loading helpers remain available, but their raw JSON
683
694
  - `verifyTrustList` - Whether to verify against the trust list
684
695
  - `userAnchors` - User-provided trust anchors (PEM format or path)
685
696
  - `trustAnchors` - Trust anchors for validation (PEM format or path)
686
- - `trustConfig` - Path to trust configuration file
687
- - `allowedList` - Allowed list of certificates (PEM format or path)
697
+ - `trustConfig` - Path to trust configuration file. Not available in `tsaTrust`.
698
+ - `allowedList` - Allowed list of certificates (PEM format or path). Not available in `tsaTrust`.
699
+ - `trustedIcaIssuers` - DIDs of identity claims aggregation issuers to trust. Available only in `cawgTrust`.
700
+
701
+ The same fields configure three sections: `trust` for claim signers, `tsaTrust` for timestamps and `cawgTrust` for CAWG identities.
688
702
 
689
703
  **Verify settings:**
690
704
  - `verifyAfterReading` - Whether to verify after reading a manifest
package/dist/Builder.js CHANGED
@@ -5,6 +5,7 @@
5
5
  // at your option.
6
6
  import { Context } from "@contentauth/c2pa-utilities";
7
7
  import { getNeonBinary } from "./binary.js";
8
+ import { resolveNativeContextForNeon } from "./Settings.js";
8
9
  import { IdentityAssertionSigner } from "./IdentityAssertion.js";
9
10
  function stringifyManifestDefinition(json) {
10
11
  try {
@@ -32,8 +33,8 @@ export class Builder {
32
33
  * Defaults to an empty `Context` using default settings if one is not provided.
33
34
  */
34
35
  static async newAsync(context = new Context()) {
35
- const settingsStr = await context.toJson();
36
- const builder = getNeonBinary().builderNew(settingsStr);
36
+ const settings = await resolveNativeContextForNeon(context, "Builder");
37
+ const builder = getNeonBinary().builderNew(settings);
37
38
  return new Builder(builder);
38
39
  }
39
40
  /**
@@ -47,8 +48,8 @@ export class Builder {
47
48
  */
48
49
  static async withJsonAsync(json, context = new Context()) {
49
50
  const jsonString = stringifyManifestDefinition(json);
50
- const settingsStr = await context.toJson();
51
- const builder = getNeonBinary().builderWithJson(jsonString, settingsStr);
51
+ const settings = await resolveNativeContextForNeon(context, "Builder");
52
+ const builder = getNeonBinary().builderWithJson(jsonString, settings);
52
53
  return new Builder(builder);
53
54
  }
54
55
  setIntent(intent) {
@@ -90,8 +91,8 @@ export class Builder {
90
91
  * @param context A `Context` configuring this Builder. Defaults to an empty `Context`.
91
92
  */
92
93
  static async fromArchive(asset, context = new Context()) {
93
- const settingsStr = await context.toJson();
94
- return new Builder(await getNeonBinary().builderFromArchive(asset, settingsStr));
94
+ const settings = await resolveNativeContextForNeon(context, "Builder");
95
+ return new Builder(await getNeonBinary().builderFromArchive(asset, settings));
95
96
  }
96
97
  sign(signer, input, output) {
97
98
  return getNeonBinary().builderSign.call(this.builder, signer.getHandle(), input, output);
@@ -9,6 +9,7 @@ import path from "path";
9
9
  import * as crypto from "crypto";
10
10
  import { vi } from "vitest";
11
11
  import http from "http";
12
+ import { getNeonBinary } from "./binary.js";
12
13
  import { isActionsAssertion } from "./assertions.js";
13
14
  import { CallbackSigner, LocalSigner } from "./Signer.js";
14
15
  import { Reader } from "./Reader.js";
@@ -905,6 +906,43 @@ describe("Builder", () => {
905
906
  const manifestStore = reader.json();
906
907
  expect(manifestStore.validation_status ?? []).not.toContainEqual(expect.objectContaining({ code: "signingCredential.untrusted" }));
907
908
  });
909
+ it("shares a Context across concurrent readers and builders without changing validation", async () => {
910
+ const manifestData = await fs.readFile("./tests/fixtures/CA/manifest_data.c2pa");
911
+ const buffer = await fs.readFile("./tests/fixtures/CA.jpg");
912
+ const asset = { buffer, mimeType: "jpeg" };
913
+ const context = new Context({
914
+ verify: {
915
+ verifyAfterReading: false,
916
+ },
917
+ });
918
+ const strictContext = new Context({
919
+ verify: {
920
+ verifyAfterReading: true,
921
+ },
922
+ });
923
+ const contextFactory = vi.spyOn(getNeonBinary(), "contextFromSettings");
924
+ try {
925
+ const [reader1, reader2, builder1, builder2, strictReader, defaultReader,] = await Promise.all([
926
+ Reader.fromManifestDataAndAsset(manifestData, asset, context),
927
+ Reader.fromManifestDataAndAsset(manifestData, asset, context),
928
+ Builder.newAsync(context),
929
+ Builder.withJsonAsync(manifestDefinition, context),
930
+ Reader.fromManifestDataAndAsset(manifestData, asset, strictContext),
931
+ Reader.fromManifestDataAndAsset(manifestData, asset),
932
+ ]);
933
+ expect(reader1.json().validation_status).toBeUndefined();
934
+ expect(reader2.json().validation_status).toBeUndefined();
935
+ const strictValidation = strictReader.json().validation_status;
936
+ expect(strictValidation).toEqual(defaultReader.json().validation_status);
937
+ expect(strictValidation).toContainEqual(expect.objectContaining({ code: "signingCredential.untrusted" }));
938
+ expect(builder1.getManifestDefinition()).toBeDefined();
939
+ expect(builder2.getManifestDefinition()).toBeDefined();
940
+ expect(contextFactory).toHaveBeenCalledTimes(3);
941
+ }
942
+ finally {
943
+ contextFactory.mockRestore();
944
+ }
945
+ });
908
946
  it("newAsync(context) fetches trust-anchor URLs before creating the Builder", async () => {
909
947
  const pem = "-----BEGIN CERTIFICATE-----\nanchor\n-----END CERTIFICATE-----";
910
948
  const fetch = vi.fn(async () => new Response(pem));
@@ -922,6 +960,81 @@ describe("Builder", () => {
922
960
  vi.unstubAllGlobals();
923
961
  }
924
962
  });
963
+ it("resolves updated trust settings with a fresh Context while preserving existing instances", async () => {
964
+ const pem1 = "-----BEGIN CERTIFICATE-----\nanchor one\n-----END CERTIFICATE-----";
965
+ const pem2 = "-----BEGIN CERTIFICATE-----\nanchor two\n-----END CERTIFICATE-----";
966
+ const pems = [pem1, pem2];
967
+ let fetchCount = 0;
968
+ const fetch = vi.fn(async () => new Response(pems[fetchCount++] ?? ""));
969
+ const contextFactory = vi.spyOn(getNeonBinary(), "contextFromSettings");
970
+ vi.stubGlobal("fetch", fetch);
971
+ try {
972
+ const settings = {
973
+ trust: {
974
+ trustAnchors: "https://example.com/anchors-node-context-fresh.pem",
975
+ },
976
+ };
977
+ const context = new Context(settings);
978
+ const firstBuilder = await Builder.newAsync(context);
979
+ const firstSettings = JSON.parse(await context.toJson());
980
+ await Builder.withJsonAsync(manifestDefinition, context);
981
+ expect(fetch).toHaveBeenCalledOnce();
982
+ const freshContext = new Context(settings);
983
+ const refreshedBuilder = await Builder.newAsync(freshContext);
984
+ const refreshedSettings = JSON.parse(await freshContext.toJson());
985
+ await Builder.newAsync(context);
986
+ expect(fetch).toHaveBeenCalledTimes(2);
987
+ expect(firstSettings.trust.anchors[0].trust_anchors).toBe(pem1);
988
+ expect(refreshedSettings.trust.anchors[0].trust_anchors).toBe(pem2);
989
+ expect(JSON.parse(await context.toJson())).toEqual(firstSettings);
990
+ expect(firstBuilder.getManifestDefinition()).toBeDefined();
991
+ expect(refreshedBuilder.getManifestDefinition()).toBeDefined();
992
+ expect(contextFactory).toHaveBeenCalledTimes(2);
993
+ expect(contextFactory.mock.results[0]?.value).not.toBe(contextFactory.mock.results[1]?.value);
994
+ }
995
+ finally {
996
+ contextFactory.mockRestore();
997
+ vi.unstubAllGlobals();
998
+ }
999
+ });
1000
+ it("does not reuse another Context's native settings when fresh resolution fails", async () => {
1001
+ const pem1 = "-----BEGIN CERTIFICATE-----\nanchor one\n-----END CERTIFICATE-----";
1002
+ const pem2 = "-----BEGIN CERTIFICATE-----\nanchor two\n-----END CERTIFICATE-----";
1003
+ const fetch = vi
1004
+ .fn()
1005
+ .mockResolvedValueOnce(new Response(pem1))
1006
+ .mockResolvedValueOnce(new Response("", { status: 503 }))
1007
+ .mockResolvedValueOnce(new Response(pem2));
1008
+ const contextFactory = vi.spyOn(getNeonBinary(), "contextFromSettings");
1009
+ vi.stubGlobal("fetch", fetch);
1010
+ try {
1011
+ const settings = {
1012
+ trust: {
1013
+ trustAnchors: "https://example.com/anchors-node-context-fresh-failure.pem",
1014
+ },
1015
+ };
1016
+ const options = { trustFetch: { maxRetries: 0 } };
1017
+ const context = new Context(settings, undefined, options);
1018
+ await Builder.newAsync(context);
1019
+ const freshContext = new Context(settings, undefined, options);
1020
+ await expect(Builder.newAsync(freshContext)).rejects.toThrow();
1021
+ expect(contextFactory).toHaveBeenCalledOnce();
1022
+ await Builder.newAsync(context);
1023
+ expect(fetch).toHaveBeenCalledTimes(2);
1024
+ expect(contextFactory).toHaveBeenCalledOnce();
1025
+ const refreshedBuilder = await Builder.newAsync(freshContext);
1026
+ const refreshedSettings = JSON.parse(await freshContext.toJson());
1027
+ expect(fetch).toHaveBeenCalledTimes(3);
1028
+ expect(contextFactory).toHaveBeenCalledTimes(2);
1029
+ expect(refreshedSettings.trust.anchors[0].trust_anchors).toBe(pem2);
1030
+ expect(JSON.parse(await context.toJson()).trust.anchors[0].trust_anchors).toBe(pem1);
1031
+ expect(refreshedBuilder.getManifestDefinition()).toBeDefined();
1032
+ }
1033
+ finally {
1034
+ contextFactory.mockRestore();
1035
+ vi.unstubAllGlobals();
1036
+ }
1037
+ });
925
1038
  it("newAsync(context) retries failed trust-anchor fetches", async () => {
926
1039
  const pem = "-----BEGIN CERTIFICATE-----\nanchor\n-----END CERTIFICATE-----";
927
1040
  const fetch = vi
package/dist/Reader.js CHANGED
@@ -6,6 +6,7 @@
6
6
  import { Context } from "@contentauth/c2pa-utilities";
7
7
  import { getNeonBinary } from "./binary.js";
8
8
  import { validateSourceAssetSize } from "./assetSize.js";
9
+ import { resolveNativeContextForNeon } from "./Settings.js";
9
10
  export class Reader {
10
11
  reader;
11
12
  constructor(reader) {
@@ -28,8 +29,8 @@ export class Reader {
28
29
  */
29
30
  static async fromAsset(asset, context = new Context()) {
30
31
  await validateSourceAssetSize(asset, context.sdkConfig);
31
- const settingsStr = await context.toJson();
32
- const reader = await getNeonBinary().readerFromAsset(asset, settingsStr);
32
+ const settings = await resolveNativeContextForNeon(context, "Reader");
33
+ const reader = await getNeonBinary().readerFromAsset(asset, settings);
33
34
  return reader ? new Reader(reader) : null;
34
35
  }
35
36
  /**
@@ -37,8 +38,8 @@ export class Reader {
37
38
  */
38
39
  static async fromManifestDataAndAsset(manifestData, asset, context = new Context()) {
39
40
  await validateSourceAssetSize(asset, context.sdkConfig);
40
- const settingsStr = await context.toJson();
41
- const reader = await getNeonBinary().readerFromManifestDataAndAsset(manifestData, asset, settingsStr);
41
+ const settings = await resolveNativeContextForNeon(context, "Reader");
42
+ const reader = await getNeonBinary().readerFromManifestDataAndAsset(manifestData, asset, settings);
42
43
  return new Reader(reader);
43
44
  }
44
45
  // Non-neon methods, copied from c2pa-js
@@ -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/Settings.js CHANGED
@@ -10,6 +10,8 @@
10
10
  // specific language governing permissions and limitations under
11
11
  // each license.
12
12
  import fs from "fs-extra";
13
+ import { getNeonBinary } from "./binary.js";
14
+ const nativeContexts = new WeakMap();
13
15
  /**
14
16
  * This file contains only Settings functions that are unique to the Node SDK.
15
17
  *
@@ -25,3 +27,20 @@ export async function loadSettingsFromFile(filePath) {
25
27
  const content = await fs.readFile(filePath, "utf8");
26
28
  return content;
27
29
  }
30
+ /**
31
+ * Resolves a Context to its latest native handle. The settings JSON is transferred and parsed
32
+ * only when a Context produces a new effective JSON value.
33
+ */
34
+ export async function resolveNativeContextForNeon(context, errorPrefix) {
35
+ const settingsJson = await context.toJson();
36
+ const cachedContext = nativeContexts.get(context);
37
+ if (cachedContext?.settingsJson === settingsJson) {
38
+ return cachedContext.handle;
39
+ }
40
+ const nativeContext = getNeonBinary().contextFromSettings(settingsJson, errorPrefix);
41
+ nativeContexts.set(context, {
42
+ settingsJson,
43
+ handle: nativeContext,
44
+ });
45
+ return nativeContext;
46
+ }
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: 52409088 bytes
4
- sha256: dd151f6f6f5b4ccca5b9d5e754770ad977dca5f8dcef4bed3c3e0e78d6e8c118
3
+ size: 52372208 bytes
4
+ sha256: a368e5ca858a367c92f34903c4284a5b4a839a893d3930b612197f61fc3065cf
@@ -1,3 +1,5 @@
1
+ import type { Context } from "@contentauth/c2pa-utilities";
2
+ import type { NeonContextHandle } from "./types.d.ts";
1
3
  /**
2
4
  * This file contains only Settings functions that are unique to the Node SDK.
3
5
  *
@@ -10,3 +12,8 @@
10
12
  * @returns Settings as a string (TOML or JSON depending on file extension)
11
13
  */
12
14
  export declare function loadSettingsFromFile(filePath: string): Promise<string>;
15
+ /**
16
+ * Resolves a Context to its latest native handle. The settings JSON is transferred and parsed
17
+ * only when a Context produces a new effective JSON value.
18
+ */
19
+ export declare function resolveNativeContextForNeon(context: Context, errorPrefix: string): Promise<NeonContextHandle>;
@@ -155,6 +155,7 @@ export type CallbackSignerConfig = unknown;
155
155
  export type NeonCallbackSignerHandle = unknown;
156
156
  export type NeonCallbackCredentialHolderHandle = unknown;
157
157
  export type NeonLocalSignerHandle = unknown;
158
+ export type NeonContextHandle = unknown;
158
159
  export type NeonBuilderHandle = unknown;
159
160
  export type NeonReaderHandle = unknown;
160
161
  export type NeonIdentityAssertionSignerHandle = unknown;
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.12.0",
8
+ "version": "0.12.2",
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.1"
68
+ "@contentauth/c2pa-utilities": "0.5.2"
69
69
  },
70
70
  "nx": {
71
71
  "tags": [
package/src/lib.rs CHANGED
@@ -28,6 +28,8 @@ pub mod neon_trustmark;
28
28
 
29
29
  #[neon::main]
30
30
  fn main(mut cx: ModuleContext) -> NeonResult<()> {
31
+ cx.export_function("contextFromSettings", utils::from_settings)?;
32
+
31
33
  // Builder
32
34
  cx.export_function("builderNew", neon_builder::NeonBuilder::new)?;
33
35
  cx.export_function("builderWithJson", neon_builder::NeonBuilder::with_json)?;
@@ -44,7 +44,7 @@ impl NeonBuilder {
44
44
  parse_settings(&mut cx, 0, "Builder").or_else(|err| cx.throw_error(err.to_string()))?;
45
45
 
46
46
  let builder = if let Some(context) = context_opt {
47
- Builder::from_context(context)
47
+ Builder::from_shared_context(&context)
48
48
  } else {
49
49
  Builder::default()
50
50
  };
@@ -62,7 +62,7 @@ impl NeonBuilder {
62
62
  parse_settings(&mut cx, 1, "Builder").or_else(|err| cx.throw_error(err.to_string()))?;
63
63
 
64
64
  let builder = if let Some(context) = context_opt {
65
- Builder::from_context(context)
65
+ Builder::from_shared_context(&context)
66
66
  .with_definition(json.as_str())
67
67
  .or_else(|err| cx.throw_error(err.to_string()))?
68
68
  } else {
@@ -330,7 +330,7 @@ impl NeonBuilder {
330
330
  .task(move || {
331
331
  let source_stream = source.into_read_stream()?;
332
332
  let builder = if let Some(context) = context_opt {
333
- Builder::from_context(context).with_archive(source_stream)?
333
+ Builder::from_shared_context(&context).with_archive(source_stream)?
334
334
  } else {
335
335
  Builder::default().with_archive(source_stream)?
336
336
  };
@@ -65,7 +65,7 @@ impl NeonReader {
65
65
 
66
66
  // Create reader with or without context
67
67
  let reader = if let Some(context) = context_opt {
68
- Reader::from_context(context)
68
+ Reader::from_shared_context(&context)
69
69
  .with_stream_async(&format, stream)
70
70
  .await?
71
71
  } else {
@@ -107,8 +107,7 @@ impl NeonReader {
107
107
  .argument::<JsObject>(1)
108
108
  .and_then(|obj| parse_asset(&mut cx, obj))?;
109
109
 
110
- // Parse optional settings parameter (argument 2) - note: settings are not currently used
111
- // for from_manifest_data_and_asset as the c2pa-rs API doesn't support context for this method yet
110
+ // Parse optional settings parameter (argument 2)
112
111
  let context_opt =
113
112
  parse_settings(&mut cx, 2, "Reader").or_else(|err| cx.throw_error(err.to_string()))?;
114
113
 
@@ -122,7 +121,7 @@ impl NeonReader {
122
121
  let stream = asset.into_read_stream()?;
123
122
 
124
123
  let reader = if let Some(context) = context_opt {
125
- Reader::from_context(context)
124
+ Reader::from_shared_context(&context)
126
125
  .with_manifest_data_and_stream_async(&c2pa_data, &format, stream)
127
126
  .await?
128
127
  } else {
@@ -165,8 +165,8 @@ impl NeonTrustmark {
165
165
 
166
166
  let promise = cx
167
167
  .task(move || {
168
- let trustmark = trustmark.lock()?;
169
168
  let image = image::load_from_memory(&image_bytes)?;
169
+ let trustmark = trustmark.lock()?;
170
170
  let watermark = watermark.unwrap_or_else(|| gen_watermark(version));
171
171
  let watermarked_image = trustmark
172
172
  .encode(watermark, image, strength)
@@ -217,8 +217,8 @@ impl NeonTrustmark {
217
217
 
218
218
  let promise = cx
219
219
  .task(move || {
220
- let trustmark = trustmark.lock()?;
221
220
  let image = image::load_from_memory(&image_bytes)?;
221
+ let trustmark = trustmark.lock()?;
222
222
  let watermark = trustmark.decode(image)?;
223
223
  Ok(watermark)
224
224
  })
package/src/utils.rs CHANGED
@@ -11,11 +11,43 @@
11
11
  // specific language governing permissions and limitations under
12
12
  // each license.
13
13
 
14
+ use std::sync::Arc;
15
+
14
16
  use c2pa::Context;
17
+ use neon::context::Context as NeonContext;
15
18
  use neon::prelude::*;
16
19
 
17
20
  use crate::error::{Error, Result};
18
21
 
22
+ /// Native Context shared by Readers/Builders for the same resolved JS Context.
23
+ /// Sharing includes c2pa-rs's one-way cancellation flag and progress callback,
24
+ /// not just settings. Node does not expose these operation-control APIs today.
25
+ /// Before adding per-instance controls, revisit this ownership: cancellation
26
+ /// would affect all current and future users of the cached Context, and
27
+ /// concurrent operations would report progress through the same callback.
28
+ pub struct NeonContextHandle {
29
+ context: Arc<Context>,
30
+ }
31
+
32
+ impl Finalize for NeonContextHandle {}
33
+
34
+ fn parse_context(settings: &str, error_prefix: &str) -> Result<Arc<Context>> {
35
+ let context = Context::new()
36
+ .with_settings(settings)
37
+ .map_err(|e| Error::Signing(format!("{error_prefix}: Invalid settings: {e}")))?
38
+ .into_shared();
39
+ Ok(context)
40
+ }
41
+
42
+ pub fn from_settings(mut cx: FunctionContext) -> JsResult<JsBox<NeonContextHandle>> {
43
+ let settings = cx.argument::<JsString>(0)?.value(&mut cx);
44
+ let error_prefix = cx.argument::<JsString>(1)?.value(&mut cx);
45
+ match parse_context(&settings, &error_prefix) {
46
+ Ok(context) => Ok(cx.boxed(NeonContextHandle { context })),
47
+ Err(error) => cx.throw_error(error.to_string()),
48
+ }
49
+ }
50
+
19
51
  #[allow(dead_code)]
20
52
  // Used in debugging
21
53
  pub fn log_message<'a, C: neon::context::Context<'a>>(cx: &mut C, message: &str) {
@@ -33,18 +65,25 @@ pub fn log_message<'a, C: neon::context::Context<'a>>(cx: &mut C, message: &str)
33
65
  }
34
66
 
35
67
  /// Parse optional settings string from JS argument and create a Context.
36
- /// Returns Ok(Some(Context)) if settings are provided, Ok(None) if not provided,
68
+ /// Returns Ok(Some(Arc<Context>)) if settings are provided, Ok(None) if not provided,
37
69
  /// or Err if settings are invalid.
38
70
  pub fn parse_settings(
39
71
  cx: &mut FunctionContext,
40
72
  arg_index: usize,
41
73
  error_prefix: &str,
42
- ) -> Result<Option<Context>> {
74
+ ) -> Result<Option<Arc<Context>>> {
43
75
  let settings_opt = cx.argument_opt(arg_index);
44
76
 
45
77
  match settings_opt {
46
78
  Some(js_value) => {
47
- if js_value.is_a::<JsString, _>(cx) {
79
+ if js_value.is_a::<JsBox<NeonContextHandle>, _>(cx) {
80
+ let context_handle = js_value
81
+ .downcast::<JsBox<NeonContextHandle>, _>(cx)
82
+ .map_err(|_| {
83
+ Error::Signing(format!("{error_prefix}: Invalid native Context handle"))
84
+ })?;
85
+ Ok(Some(Arc::clone(&context_handle.context)))
86
+ } else if js_value.is_a::<JsString, _>(cx) {
48
87
  let settings_string = js_value
49
88
  .downcast::<JsString, _>(cx)
50
89
  .map_err(|_| {
@@ -52,12 +91,7 @@ pub fn parse_settings(
52
91
  })?
53
92
  .value(cx);
54
93
 
55
- // Create context with settings
56
- let context = Context::new()
57
- .with_settings(settings_string.as_str())
58
- .map_err(|e| {
59
- Error::Signing(format!("{error_prefix}: Invalid settings: {e}"))
60
- })?;
94
+ let context = parse_context(settings_string.as_str(), error_prefix)?;
61
95
  Ok(Some(context))
62
96
  } else if js_value.is_a::<JsNull, _>(cx) || js_value.is_a::<JsUndefined, _>(cx) {
63
97
  Ok(None)
@@ -67,6 +101,7 @@ pub fn parse_settings(
67
101
  )))
68
102
  }
69
103
  }
104
+
70
105
  None => Ok(None),
71
106
  }
72
107
  }