@contentauth/c2pa-node 0.4.2 → 0.5.0

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.
@@ -1,68 +1,44 @@
1
- import type { TrustConfig, VerifyConfig } from "./types.d.ts";
1
+ import type { TrustConfig, VerifyConfig, SettingsContext } from "./types.d.ts";
2
2
  /**
3
- * Load settings from a JSON string and apply them globally.
4
- * @param json The JSON string containing the settings configuration
3
+ * Create a Settings object with trust configuration.
4
+ * @param trustConfig The trust configuration
5
+ * @returns Settings object that can be passed to Reader/Builder
5
6
  */
6
- export declare function loadC2paSettings(json: string): void;
7
+ export declare function createTrustSettings(trustConfig: TrustConfig): SettingsContext;
7
8
  /**
8
- * Load settings from a TOML string and apply them globally.
9
- * @param toml The TOML string containing the settings configuration
9
+ * Create a settings object with CAWG trust configuration.
10
+ * @param trustConfig The CAWG trust configuration
11
+ * @returns Settings object that can be passed to Reader/Builder
10
12
  */
11
- export declare function loadC2paSettingsToml(toml: string): void;
13
+ export declare function createCawgTrustSettings(trustConfig: TrustConfig): SettingsContext;
12
14
  /**
13
- * Load settings from a TOML or JSON file path and apply them globally.
14
- * The file format is determined by the file extension (.toml for TOML, otherwise JSON).
15
- * @param filePath The path to the settings file
16
- */
17
- export declare function loadSettingsFromFile(filePath: string): Promise<void>;
18
- /**
19
- * Load settings from a URL and apply them globally.
20
- * The format is determined by the content-type header or file extension (.toml for TOML, otherwise JSON).
21
- * @param url The URL to fetch the settings from
22
- */
23
- export declare function loadSettingsFromUrl(url: string): Promise<void>;
24
- /**
25
- * Get the current settings as a JSON string.
26
- * @returns The JSON representation of the current settings
27
- */
28
- export declare function getSettingsJson(): string;
29
- /**
30
- * Load trust configuration into the main trust settings.
31
- * @param trustConfig The trust configuration object
15
+ * Create a settings object with verify configuration.
16
+ * @param verifyConfig The verify configuration
17
+ * @returns Settings object that can be passed to Reader/Builder
32
18
  */
33
- export declare function loadTrustConfig(trustConfig: TrustConfig): void;
19
+ export declare function createVerifySettings(verifyConfig: VerifyConfig): SettingsContext;
34
20
  /**
35
- * Load trust configuration into the CAWG trust settings.
36
- * @param trustConfig The trust configuration object
21
+ * Merge multiple settings objects into one.
22
+ * Later settings override earlier ones.
23
+ * @param settings Settings objects to merge
24
+ * @returns Merged settings object
37
25
  */
38
- export declare function loadCawgTrustConfig(trustConfig: TrustConfig): void;
26
+ export declare function mergeSettings(...settings: SettingsContext[]): SettingsContext;
39
27
  /**
40
- * Get the current trust configuration.
41
- * @returns The current trust configuration object
28
+ * Convert a settings object to a JSON string.
29
+ * @param settings The settings object
30
+ * @returns JSON string representation
42
31
  */
43
- export declare function getTrustConfig(): TrustConfig;
32
+ export declare function settingsToJson(settings: SettingsContext): string;
44
33
  /**
45
- * Get the current CAWG trust configuration.
46
- * @returns The current CAWG trust configuration object
47
- */
48
- export declare function getCawgTrustConfig(): TrustConfig;
49
- /**
50
- * Load verify configuration into the verify settings.
51
- * @param verifyConfig The verify configuration object
52
- */
53
- export declare function loadVerifyConfig(verifyConfig: VerifyConfig): void;
54
- /**
55
- * Patch the verify configuration with any subset of fields.
56
- * @param patch Partial verify config fields to update
57
- */
58
- export declare function patchVerifyConfig(patch: Partial<VerifyConfig>): void;
59
- /**
60
- * Get the current verify configuration.
61
- * @returns The current verify configuration object
34
+ * Load settings from a TOML or JSON file.
35
+ * @param filePath The path to the settings file
36
+ * @returns Settings as a string (TOML or JSON depending on file extension)
62
37
  */
63
- export declare function getVerifyConfig(): VerifyConfig;
38
+ export declare function loadSettingsFromFile(filePath: string): Promise<string>;
64
39
  /**
65
- * Reset settings to their default values.
66
- * This clears any custom settings and restores the default configuration.
40
+ * Load settings from a URL.
41
+ * @param url The URL to fetch the settings from
42
+ * @returns Settings as a string
67
43
  */
68
- export declare function resetSettings(): void;
44
+ export declare function loadSettingsFromUrl(url: string): Promise<string>;
@@ -183,6 +183,12 @@ export interface HashedUri {
183
183
  alg?: string;
184
184
  }
185
185
 
186
+ /**
187
+ * Optional settings that can be provided when creating a Reader or Builder.
188
+ * Can be a JSON string, TOML string, or a settings object.
189
+ */
190
+ export type C2paSettings = string | object;
191
+
186
192
  export interface BuilderInterface {
187
193
  /** An intent lets the API know what kind of manifest to create.
188
194
  * Intents are `Create`, `Edit`, or `Update`.
@@ -460,3 +466,44 @@ export interface VerifyConfig {
460
466
  /** Whether to use strict v1 validation */
461
467
  strictV1Validation: boolean;
462
468
  }
469
+
470
+ /**
471
+ * Settings configuration object that can be passed to Reader and Builder constructors.
472
+ * Only trust, verify, and builder settings are configurable from the Node SDK.
473
+ * Uses snake_case internally to match the c2pa-rs settings format.
474
+ */
475
+ export interface SettingsContext {
476
+ /** C2PA trust configuration */
477
+ trust?: {
478
+ verify_trust_list?: boolean;
479
+ user_anchors?: string;
480
+ trust_anchors?: string;
481
+ trust_config?: string;
482
+ allowed_list?: string;
483
+ };
484
+ /** CAWG trust configuration */
485
+ cawg_trust?: {
486
+ verify_trust_list?: boolean;
487
+ user_anchors?: string;
488
+ trust_anchors?: string;
489
+ trust_config?: string;
490
+ allowed_list?: string;
491
+ };
492
+ /** Verification configuration */
493
+ verify?: {
494
+ verify_after_reading?: boolean;
495
+ verify_after_sign?: boolean;
496
+ verify_trust?: boolean;
497
+ verify_timestamp_trust?: boolean;
498
+ ocsp_fetch?: boolean;
499
+ remote_manifest_fetch?: boolean;
500
+ skip_ingredient_conflict_resolution?: boolean;
501
+ strict_v1_validation?: boolean;
502
+ };
503
+ /** Builder configuration */
504
+ builder?: {
505
+ thumbnail?: {
506
+ enabled?: boolean;
507
+ };
508
+ };
509
+ }
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.4.2",
7
+ "version": "0.5.0",
8
8
  "description": "Node.js bindings for C2PA",
9
9
  "main": "dist/index.js",
10
10
  "type": "module",
@@ -23,7 +23,7 @@
23
23
  "license": "MIT",
24
24
  "devDependencies": {
25
25
  "@changesets/cli": "^2.29.6",
26
- "@contentauth/c2pa-types": "^0.3.1",
26
+ "@contentauth/c2pa-types": "^0.4.1",
27
27
  "@eslint/js": "^9.33.0",
28
28
  "@neon-rs/cli": "0.1.82",
29
29
  "@types/cli-progress": "^3.11.6",
package/src/lib.rs CHANGED
@@ -16,7 +16,6 @@ use neon::prelude::*;
16
16
  mod asset;
17
17
  mod error;
18
18
  mod runtime;
19
- mod settings;
20
19
  mod utils;
21
20
 
22
21
  pub mod neon_builder;
@@ -176,23 +175,5 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> {
176
175
  cx.export_function("trustmarkEncode", neon_trustmark::NeonTrustmark::encode)?;
177
176
  cx.export_function("trustmarkDecode", neon_trustmark::NeonTrustmark::decode)?;
178
177
 
179
- // Settings
180
- cx.export_function("loadSettings", settings::load_settings)?;
181
- cx.export_function("loadSettingsToml", settings::load_settings_toml)?;
182
- cx.export_function("getSettingsJson", settings::get_settings_json)?;
183
-
184
- // Trust Settings
185
- cx.export_function("loadTrustConfig", settings::load_trust_config)?;
186
- cx.export_function("loadCawgTrustConfig", settings::load_cawg_trust_config)?;
187
- cx.export_function("getTrustConfig", settings::get_trust_config)?;
188
- cx.export_function("getCawgTrustConfig", settings::get_cawg_trust_config)?;
189
-
190
- // Verify Settings
191
- cx.export_function("loadVerifyConfig", settings::load_verify_config)?;
192
- cx.export_function("getVerifyConfig", settings::get_verify_config)?;
193
-
194
- // Reset Settings
195
- cx.export_function("resetSettings", settings::reset_settings)?;
196
-
197
178
  Ok(())
198
179
  }
@@ -17,44 +17,52 @@ use crate::neon_identity_assertion_signer::NeonIdentityAssertionSigner;
17
17
  use crate::neon_reader::NeonReader;
18
18
  use crate::neon_signer::{CallbackSignerConfig, NeonCallbackSigner, NeonLocalSigner};
19
19
  use crate::runtime::runtime;
20
+ use crate::utils::parse_settings;
20
21
  use c2pa::{Builder, BuilderIntent, Ingredient};
22
+ use neon::context::Context as NeonContext;
21
23
  use neon::prelude::*;
22
24
  use neon_serde4;
23
- use serde::{Deserialize, Serialize};
24
25
  use serde_json;
25
26
  use std::ops::Deref;
26
27
  use std::sync::Arc;
27
28
  use tokio::sync::Mutex;
28
29
 
29
- #[derive(Default, Serialize, Deserialize)]
30
- #[serde(rename_all = "camelCase")]
31
- struct IngredientThumbnail {
32
- pub format: String,
33
- #[serde(with = "serde_bytes")]
34
- pub data: Vec<u8>,
35
- }
36
-
37
- #[derive(Default, Serialize, Deserialize)]
38
- #[serde(rename_all = "camelCase")]
39
- struct IngredientOptions {
40
- pub is_parent: bool,
41
- pub thumbnail: Option<IngredientThumbnail>,
42
- }
43
-
44
30
  pub struct NeonBuilder {
45
31
  builder: Arc<Mutex<Builder>>,
46
32
  }
47
33
 
48
34
  impl NeonBuilder {
49
35
  pub fn new(mut cx: FunctionContext) -> JsResult<JsBox<Self>> {
36
+ // Parse optional settings parameter (argument 0)
37
+ let context_opt =
38
+ parse_settings(&mut cx, 0, "Builder").or_else(|err| cx.throw_error(err.to_string()))?;
39
+
40
+ let builder = if let Some(context) = context_opt {
41
+ Builder::from_context(context)
42
+ } else {
43
+ Builder::default()
44
+ };
45
+
50
46
  Ok(cx.boxed(Self {
51
- builder: Arc::new(Mutex::new(Builder::default())),
47
+ builder: Arc::new(Mutex::new(builder)),
52
48
  }))
53
49
  }
54
50
 
55
51
  pub fn with_json(mut cx: FunctionContext) -> JsResult<JsBox<Self>> {
56
52
  let json = cx.argument::<JsString>(0)?.value(&mut cx);
57
- let builder = Builder::from_json(&json).or_else(|err| cx.throw_error(err.to_string()))?;
53
+
54
+ // Parse optional settings parameter (argument 1)
55
+ let context_opt =
56
+ parse_settings(&mut cx, 1, "Builder").or_else(|err| cx.throw_error(err.to_string()))?;
57
+
58
+ let builder = if let Some(context) = context_opt {
59
+ Builder::from_context(context)
60
+ .with_definition(json.as_str())
61
+ .or_else(|err| cx.throw_error(err.to_string()))?
62
+ } else {
63
+ Builder::from_json(&json).or_else(|err| cx.throw_error(err.to_string()))?
64
+ };
65
+
58
66
  Ok(cx.boxed(Self {
59
67
  builder: Arc::new(Mutex::new(builder)),
60
68
  }))
@@ -285,18 +293,24 @@ impl NeonBuilder {
285
293
  .argument::<JsObject>(0)
286
294
  .and_then(|obj| parse_asset(&mut cx, obj))?;
287
295
 
296
+ // TODO: CAI-10614 This won't work until from_archive_with_context() is ready
297
+ let _context_opt =
298
+ parse_settings(&mut cx, 1, "Builder").or_else(|err| cx.throw_error(err.to_string()))?;
299
+
288
300
  let promise = cx
289
301
  .task(move || {
290
302
  let source_stream = source.into_read_stream()?;
291
303
  let builder = Builder::from_archive(source_stream)?;
292
304
  Ok(builder)
293
305
  })
294
- .promise(move |mut cx, result: Result<Builder, Error>| match result {
295
- Ok(builder) => Ok(cx.boxed(Self {
296
- builder: Arc::new(Mutex::new(builder)),
297
- })),
298
- Err(err) => as_js_error(&mut cx, err).and_then(|err| cx.throw(err)),
299
- });
306
+ .promise(
307
+ move |mut cx, result: crate::error::Result<Builder>| match result {
308
+ Ok(builder) => Ok(cx.boxed(Self {
309
+ builder: Arc::new(Mutex::new(builder)),
310
+ })),
311
+ Err(err) => as_js_error(&mut cx, err).and_then(|err| cx.throw(err)),
312
+ },
313
+ );
300
314
  Ok(promise)
301
315
  }
302
316
 
@@ -14,7 +14,9 @@
14
14
  use crate::asset::parse_asset;
15
15
  use crate::error::{as_js_error, Error, Result};
16
16
  use crate::runtime::runtime;
17
+ use crate::utils::parse_settings;
17
18
  use c2pa::Reader;
19
+ use neon::context::Context as NeonContext;
18
20
  use neon::prelude::*;
19
21
  use neon::types::buffer::TypedArray;
20
22
  use std::sync::Arc;
@@ -46,6 +48,10 @@ impl NeonReader {
46
48
  .argument::<JsObject>(0)
47
49
  .and_then(|obj| parse_asset(&mut cx, obj))?;
48
50
 
51
+ // Parse optional settings parameter (argument 1)
52
+ let context_opt =
53
+ parse_settings(&mut cx, 1, "Reader").or_else(|err| cx.throw_error(err.to_string()))?;
54
+
49
55
  let (deferred, promise) = cx.promise();
50
56
  rt.spawn(async move {
51
57
  let result: Result<Reader> = async {
@@ -57,7 +63,16 @@ impl NeonReader {
57
63
  .to_owned();
58
64
 
59
65
  let stream = source.into_read_stream()?;
60
- let reader = Reader::from_stream_async(&format, stream).await?;
66
+
67
+ // Create reader with or without context
68
+ let reader = if let Some(context) = context_opt {
69
+ Reader::from_context(context)
70
+ .with_stream_async(&format, stream)
71
+ .await?
72
+ } else {
73
+ Reader::from_stream_async(&format, stream).await?
74
+ };
75
+
61
76
  Ok(reader)
62
77
  }
63
78
  .await;
@@ -93,6 +108,11 @@ impl NeonReader {
93
108
  .argument::<JsObject>(1)
94
109
  .and_then(|obj| parse_asset(&mut cx, obj))?;
95
110
 
111
+ // Parse optional settings parameter (argument 2) - note: settings are not currently used
112
+ // for from_manifest_data_and_asset as the c2pa-rs API doesn't support context for this method yet
113
+ let _context_opt =
114
+ parse_settings(&mut cx, 2, "Reader").or_else(|err| cx.throw_error(err.to_string()))?;
115
+
96
116
  let c2pa_data = manifest_data.as_slice(&cx).to_vec();
97
117
  let (deferred, promise) = cx.promise();
98
118
  rt.spawn(async move {
@@ -104,9 +124,13 @@ impl NeonReader {
104
124
  })?
105
125
  .to_owned();
106
126
  let stream = asset.into_read_stream()?;
127
+
128
+ // TODO: CAI-10614 c2pa-rs currently does not support passing Context to
129
+ // from_manifest_data_and_stream_async
107
130
  let reader =
108
131
  Reader::from_manifest_data_and_stream_async(&c2pa_data, &format, stream)
109
132
  .await?;
133
+
110
134
  Ok(reader)
111
135
  }
112
136
  .await;
package/src/runtime.rs CHANGED
@@ -5,47 +5,20 @@
5
5
  // accordance with the terms of the Adobe license agreement accompanying
6
6
  // it.
7
7
 
8
- use crate::settings::get_global_settings_toml;
9
- use c2pa::settings::Settings;
10
- use std::sync::{Arc, OnceLock, RwLock};
8
+ use std::sync::{Arc, OnceLock};
11
9
  use tokio::runtime::{Builder, Runtime};
12
10
 
13
- // Runtime stored in a swap-able singleton to allow reloads after settings change
14
- static RUNTIME: OnceLock<RwLock<Arc<Runtime>>> = OnceLock::new();
11
+ // Runtime singleton - no longer needs reload functionality since settings are per-instance
12
+ static RUNTIME: OnceLock<Arc<Runtime>> = OnceLock::new();
15
13
 
16
14
  fn build_runtime() -> Arc<Runtime> {
17
15
  let rt = Builder::new_multi_thread()
18
16
  .enable_all()
19
- .on_thread_start(|| {
20
- // Apply the latest global TOML snapshot when each worker starts
21
- if let Some(toml) = get_global_settings_toml() {
22
- let _ = Settings::from_toml(&toml);
23
- }
24
- })
25
17
  .build()
26
18
  .expect("Failed to build runtime");
27
19
  Arc::new(rt)
28
20
  }
29
21
 
30
22
  pub fn runtime() -> Arc<Runtime> {
31
- // Ensure settings are applied to the current thread
32
- // This is important for Neon tasks that don't run on Tokio worker threads
33
- crate::settings::apply_settings_to_current_thread();
34
-
35
- let cell = RUNTIME.get_or_init(|| RwLock::new(build_runtime()));
36
- cell.read().unwrap().clone()
37
- }
38
-
39
- /// Rebuild the runtime so new worker threads use the latest global settings snapshot.
40
- /// Existing tasks continue on the old runtime; its workers retire when idle.
41
- pub fn reload_runtime() {
42
- let cell = RUNTIME.get_or_init(|| RwLock::new(build_runtime()));
43
- let new_rt = build_runtime();
44
- let old = {
45
- let mut w = cell.write().unwrap();
46
- std::mem::replace(&mut *w, new_rt)
47
- };
48
- // Let it drain in background
49
- // Drop Arc<Runtime>; cannot call shutdown_* after move. Tasks will drain naturally.
50
- drop(old);
23
+ RUNTIME.get_or_init(build_runtime).clone()
51
24
  }
package/src/utils.rs CHANGED
@@ -11,11 +11,14 @@
11
11
  // specific language governing permissions and limitations under
12
12
  // each license.
13
13
 
14
+ use c2pa::Context;
14
15
  use neon::prelude::*;
15
16
 
17
+ use crate::error::{Error, Result};
18
+
16
19
  #[allow(dead_code)]
17
20
  // Used in debugging
18
- pub fn log_message<'a, C: Context<'a>>(cx: &mut C, message: &str) {
21
+ pub fn log_message<'a, C: neon::context::Context<'a>>(cx: &mut C, message: &str) {
19
22
  let global = cx.global_object();
20
23
  let console: Handle<JsObject> = global.get(cx, "console").unwrap();
21
24
  let log: Handle<JsFunction> = console
@@ -28,3 +31,40 @@ pub fn log_message<'a, C: Context<'a>>(cx: &mut C, message: &str) {
28
31
  let args: Vec<Handle<JsValue>> = vec![msg.upcast()];
29
32
  log.call(cx, this, args).unwrap();
30
33
  }
34
+
35
+ /// 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,
37
+ /// or Err if settings are invalid.
38
+ pub fn parse_settings(
39
+ cx: &mut FunctionContext,
40
+ arg_index: usize,
41
+ error_prefix: &str,
42
+ ) -> Result<Option<Context>> {
43
+ let settings_opt = cx.argument_opt(arg_index);
44
+
45
+ match settings_opt {
46
+ Some(js_value) => {
47
+ if js_value.is_a::<JsString, _>(cx) {
48
+ let settings_string = js_value
49
+ .downcast::<JsString, _>(cx).map_err(|_| Error::Signing(format!("{}: Expected settings string", error_prefix)))?
50
+ .value(cx);
51
+
52
+ // Create context with settings
53
+ let context = Context::new()
54
+ .with_settings(settings_string.as_str())
55
+ .map_err(|e| Error::Signing(format!("{}: Invalid settings: {}", error_prefix, e)))?;
56
+
57
+ Ok(Some(context))
58
+ } else if js_value.is_a::<JsNull, _>(cx) || js_value.is_a::<JsUndefined, _>(cx) {
59
+ Ok(None)
60
+ } else {
61
+ Err(Error::Signing(format!(
62
+ "{}: Settings must be a string, null, or undefined",
63
+ error_prefix
64
+ )))
65
+ }
66
+ }
67
+ None => Ok(None),
68
+ }
69
+ }
70
+