@contentauth/c2pa-node 0.12.1 → 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]
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
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: 52405720 bytes
4
- sha256: 2d95b6b5e5c989c5ae5eb4ed43c941fe12527bd9010c36150394fbe22513ce71
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.1",
8
+ "version": "0.12.2",
9
9
  "description": "Node.js bindings for C2PA",
10
10
  "main": "dist/index.js",
11
11
  "type": "module",
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 {
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
  }