@contentauth/c2pa-node 0.2.1 → 0.2.3

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.
@@ -0,0 +1,487 @@
1
+ // Copyright 2025 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
+
7
+ // Unless required by applicable law or agreed to in writing,
8
+ // this software is distributed on an "AS IS" BASIS, WITHOUT
9
+ // WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
10
+ // implied. See the LICENSE-MIT and LICENSE-APACHE files for the
11
+ // specific language governing permissions and limitations under
12
+ // each license.
13
+
14
+ use c2pa::settings::Settings;
15
+ use neon::prelude::*;
16
+ use std::sync::{OnceLock, RwLock};
17
+
18
+ use crate::runtime::reload_runtime;
19
+
20
+ // Global JSON snapshot used to initialize each Tokio worker thread
21
+ static GLOBAL_SETTINGS_TOML: OnceLock<RwLock<Option<String>>> = OnceLock::new();
22
+
23
+ fn global_toml() -> &'static RwLock<Option<String>> {
24
+ GLOBAL_SETTINGS_TOML.get_or_init(|| RwLock::new(None))
25
+ }
26
+
27
+ fn set_global_settings_toml(toml: Option<String>) {
28
+ *global_toml().write().unwrap() = toml;
29
+ }
30
+
31
+ pub(crate) fn get_global_settings_toml() -> Option<String> {
32
+ global_toml().read().unwrap().clone()
33
+ }
34
+
35
+ /// Parse a JSON string (argument 0) into c2pa-rs Settings and apply them globally.
36
+ /// Returns undefined; the JSON snapshot is stored globally for new worker threads.
37
+ pub fn load_settings(mut cx: FunctionContext) -> JsResult<JsUndefined> {
38
+ let json_arg = cx.argument::<JsString>(0)?;
39
+ let json_string = json_arg.value(&mut cx);
40
+
41
+ // Apply settings globally using deprecated Settings::from_string with JSON format
42
+ #[allow(deprecated)]
43
+ match Settings::from_string(&json_string, "json") {
44
+ Ok(_) => {
45
+ // Settings are now applied globally, return the TOML representation
46
+ let toml_string = Settings::to_toml()
47
+ .or_else(|e| cx.throw_error(format!("Failed to get settings as TOML: {}", e)))?;
48
+ // Save the JSON snapshot for new worker threads
49
+ set_global_settings_toml(Some(toml_string));
50
+ reload_runtime();
51
+ Ok(cx.undefined())
52
+ }
53
+ Err(e) => cx.throw_error(format!("Failed to apply settings: {}", e)),
54
+ }
55
+ }
56
+
57
+ /// Parse a TOML string (argument 0) into c2pa-rs Settings and apply them globally.
58
+ /// Returns undefined; the TOML snapshot is stored globally for new worker threads.
59
+ pub fn load_settings_toml(mut cx: FunctionContext) -> JsResult<JsUndefined> {
60
+ let toml_arg = cx.argument::<JsString>(0)?;
61
+ let toml_string = toml_arg.value(&mut cx);
62
+
63
+ // Apply settings globally using Settings::from_toml
64
+ match Settings::from_toml(&toml_string) {
65
+ Ok(_) => {
66
+ // Settings are now applied globally, save the TOML representation
67
+ let toml_string = Settings::to_toml()
68
+ .or_else(|e| cx.throw_error(format!("Failed to get settings as TOML: {}", e)))?;
69
+ // Save the TOML snapshot for new worker threads
70
+ set_global_settings_toml(Some(toml_string));
71
+ reload_runtime();
72
+ Ok(cx.undefined())
73
+ }
74
+ Err(e) => cx.throw_error(format!("Failed to apply TOML settings: {}", e)),
75
+ }
76
+ }
77
+
78
+ /// Returns the JSON settings snapshot currently stored by the Node SDK.
79
+ /// This value represents the canonical settings source in this crate and
80
+ /// should match the thread-local SETTINGS used internally by the `c2pa`
81
+ /// crate on each worker thread (applied in `runtime.rs` using `on_thread_start`).
82
+ pub fn get_settings_json(mut cx: FunctionContext) -> JsResult<JsValue> {
83
+ match get_global_settings_toml() {
84
+ Some(toml_string) => {
85
+ // Convert TOML -> JSON string for SDK consumption
86
+ let toml_val: toml::Value = match toml::from_str(&toml_string) {
87
+ Ok(v) => v,
88
+ Err(e) => return cx.throw_error(format!("Failed to parse TOML: {}", e)),
89
+ };
90
+ let json = match serde_json::to_string(&toml_val) {
91
+ Ok(s) => s,
92
+ Err(e) => return cx.throw_error(format!("Failed to serialize JSON: {}", e)),
93
+ };
94
+ Ok(cx.string(json).upcast())
95
+ }
96
+ None => {
97
+ let obj = cx.empty_object();
98
+ Ok(obj.upcast())
99
+ }
100
+ }
101
+ }
102
+
103
+ /// Get the raw TOML snapshot of the current global settings. Used for debugging.
104
+ #[allow(dead_code)]
105
+ pub fn get_settings_toml(mut cx: FunctionContext) -> JsResult<JsValue> {
106
+ match get_global_settings_toml() {
107
+ Some(t) => Ok(cx.string(t).upcast()),
108
+ None => Ok(cx.undefined().upcast()),
109
+ }
110
+ }
111
+
112
+ /// Load trust configuration into the main trust settings.
113
+ /// Takes a JSON string representing a TrustConfig object and applies it to the trust field.
114
+ pub fn load_trust_config(mut cx: FunctionContext) -> JsResult<JsUndefined> {
115
+ let json_arg = cx.argument::<JsString>(0)?;
116
+ let json_string = json_arg.value(&mut cx);
117
+
118
+ // Parse the JSON to validate it's a valid TrustConfig
119
+ let trust_config: serde_json::Value = match serde_json::from_str(&json_string) {
120
+ Ok(v) => v,
121
+ Err(e) => return cx.throw_error(format!("Invalid trust config JSON: {}", e)),
122
+ };
123
+
124
+ // Get current settings as TOML to preserve all existing settings
125
+ let current_toml = get_global_settings_toml().unwrap_or_else(|| {
126
+ // If no current settings, start with default settings
127
+ Settings::to_toml().unwrap_or_default()
128
+ });
129
+
130
+ // Parse current settings to merge with new trust config
131
+ let mut current_settings: serde_json::Value = match toml::from_str::<toml::Value>(&current_toml)
132
+ {
133
+ Ok(toml_val) => serde_json::to_value(toml_val)
134
+ .unwrap_or_else(|_| serde_json::Value::Object(serde_json::Map::new())),
135
+ Err(_) => serde_json::Value::Object(serde_json::Map::new()),
136
+ };
137
+
138
+ // Update only the trust section
139
+ if let serde_json::Value::Object(ref mut map) = current_settings {
140
+ map.insert("trust".to_string(), trust_config);
141
+ }
142
+
143
+ // Convert back to JSON string for Settings::from_string
144
+ let settings_json = serde_json::to_string(&current_settings)
145
+ .or_else(|e| cx.throw_error(format!("Failed to serialize settings: {}", e)))?;
146
+
147
+ // Use the existing load_settings function with merged settings
148
+ #[allow(deprecated)]
149
+ match Settings::from_string(&settings_json, "json") {
150
+ Ok(_) => {
151
+ // Update global settings
152
+ let full_toml = Settings::to_toml()
153
+ .or_else(|e| cx.throw_error(format!("Failed to get settings as TOML: {}", e)))?;
154
+ set_global_settings_toml(Some(full_toml));
155
+ reload_runtime();
156
+ Ok(cx.undefined())
157
+ }
158
+ Err(e) => cx.throw_error(format!("Failed to apply trust config: {}", e)),
159
+ }
160
+ }
161
+
162
+ /// Load trust configuration into the CAWG trust settings.
163
+ /// Takes a JSON string representing a TrustConfig object and applies it to the cawg_trust field.
164
+ pub fn load_cawg_trust_config(mut cx: FunctionContext) -> JsResult<JsUndefined> {
165
+ let json_arg = cx.argument::<JsString>(0)?;
166
+ let json_string = json_arg.value(&mut cx);
167
+
168
+ // Parse the JSON to validate it's a valid TrustConfig
169
+ let trust_config: serde_json::Value = match serde_json::from_str(&json_string) {
170
+ Ok(v) => v,
171
+ Err(e) => return cx.throw_error(format!("Invalid trust config JSON: {}", e)),
172
+ };
173
+
174
+ // Get current settings as TOML to preserve all existing settings
175
+ let current_toml = get_global_settings_toml().unwrap_or_else(|| {
176
+ // If no current settings, start with default settings
177
+ Settings::to_toml().unwrap_or_default()
178
+ });
179
+
180
+ // Parse current settings to merge with new trust config
181
+ let mut current_settings: serde_json::Value = match toml::from_str::<toml::Value>(&current_toml)
182
+ {
183
+ Ok(toml_val) => serde_json::to_value(toml_val)
184
+ .unwrap_or_else(|_| serde_json::Value::Object(serde_json::Map::new())),
185
+ Err(_) => serde_json::Value::Object(serde_json::Map::new()),
186
+ };
187
+
188
+ // Update only the cawg_trust section
189
+ if let serde_json::Value::Object(ref mut map) = current_settings {
190
+ map.insert("cawg_trust".to_string(), trust_config);
191
+ }
192
+
193
+ // Convert back to JSON string for Settings::from_string
194
+ let settings_json = serde_json::to_string(&current_settings)
195
+ .or_else(|e| cx.throw_error(format!("Failed to serialize settings: {}", e)))?;
196
+
197
+ // Use the existing load_settings function with merged settings
198
+ #[allow(deprecated)]
199
+ match Settings::from_string(&settings_json, "json") {
200
+ Ok(_) => {
201
+ // Update global settings
202
+ let full_toml = Settings::to_toml()
203
+ .or_else(|e| cx.throw_error(format!("Failed to get settings as TOML: {}", e)))?;
204
+ set_global_settings_toml(Some(full_toml));
205
+ reload_runtime();
206
+ Ok(cx.undefined())
207
+ }
208
+ Err(e) => cx.throw_error(format!("Failed to apply CAWG trust config: {}", e)),
209
+ }
210
+ }
211
+
212
+ /// Get the current trust configuration as JSON.
213
+ pub fn get_trust_config(mut cx: FunctionContext) -> JsResult<JsValue> {
214
+ match get_global_settings_toml() {
215
+ Some(toml_string) => {
216
+ // Convert TOML -> JSON for processing
217
+ let toml_val: toml::Value = match toml::from_str(&toml_string) {
218
+ Ok(v) => v,
219
+ Err(e) => return cx.throw_error(format!("Failed to parse TOML: {}", e)),
220
+ };
221
+ let settings: serde_json::Value = match serde_json::to_value(&toml_val) {
222
+ Ok(v) => v,
223
+ Err(e) => return cx.throw_error(format!("Failed to convert TOML to JSON: {}", e)),
224
+ };
225
+
226
+ // Extract trust section
227
+ let default_trust_config = serde_json::json!({
228
+ "verify_trust_list": true,
229
+ "user_anchors": null,
230
+ "trust_anchors": null,
231
+ "trust_config": null,
232
+ "allowed_list": null
233
+ });
234
+ let trust_section = settings.get("trust").unwrap_or(&default_trust_config);
235
+
236
+ let json = match serde_json::to_string(trust_section) {
237
+ Ok(s) => s,
238
+ Err(e) => {
239
+ return cx.throw_error(format!("Failed to serialize trust config: {}", e))
240
+ }
241
+ };
242
+ Ok(cx.string(json).upcast())
243
+ }
244
+ None => {
245
+ // Return default trust config
246
+ let default_trust = serde_json::json!({
247
+ "verify_trust_list": true,
248
+ "user_anchors": null,
249
+ "trust_anchors": null,
250
+ "trust_config": null,
251
+ "allowed_list": null
252
+ });
253
+ Ok(cx.string(default_trust.to_string()).upcast())
254
+ }
255
+ }
256
+ }
257
+
258
+ /// Get the current CAWG trust configuration as JSON.
259
+ pub fn get_cawg_trust_config(mut cx: FunctionContext) -> JsResult<JsValue> {
260
+ match get_global_settings_toml() {
261
+ Some(toml_string) => {
262
+ // Convert TOML -> JSON for processing
263
+ let toml_val: toml::Value = match toml::from_str(&toml_string) {
264
+ Ok(v) => v,
265
+ Err(e) => return cx.throw_error(format!("Failed to parse TOML: {}", e)),
266
+ };
267
+ let settings: serde_json::Value = match serde_json::to_value(&toml_val) {
268
+ Ok(v) => v,
269
+ Err(e) => return cx.throw_error(format!("Failed to convert TOML to JSON: {}", e)),
270
+ };
271
+
272
+ // Extract cawg_trust section
273
+ let default_cawg_trust_config = serde_json::json!({
274
+ "verify_trust_list": true,
275
+ "user_anchors": null,
276
+ "trust_anchors": null,
277
+ "trust_config": null,
278
+ "allowed_list": null
279
+ });
280
+ let cawg_trust_section = settings
281
+ .get("cawg_trust")
282
+ .unwrap_or(&default_cawg_trust_config);
283
+
284
+ let json = match serde_json::to_string(cawg_trust_section) {
285
+ Ok(s) => s,
286
+ Err(e) => {
287
+ return cx.throw_error(format!("Failed to serialize CAWG trust config: {}", e))
288
+ }
289
+ };
290
+ Ok(cx.string(json).upcast())
291
+ }
292
+ None => {
293
+ // Return default trust config
294
+ let default_trust = serde_json::json!({
295
+ "verify_trust_list": true,
296
+ "user_anchors": null,
297
+ "trust_anchors": null,
298
+ "trust_config": null,
299
+ "allowed_list": null
300
+ });
301
+ Ok(cx.string(default_trust.to_string()).upcast())
302
+ }
303
+ }
304
+ }
305
+
306
+ /// Load verify configuration into the verify settings.
307
+ /// Takes a JSON string representing a VerifyConfig object and applies it to the verify field.
308
+ pub fn load_verify_config(mut cx: FunctionContext) -> JsResult<JsUndefined> {
309
+ let json_arg = cx.argument::<JsString>(0)?;
310
+ let json_string = json_arg.value(&mut cx);
311
+
312
+ // Parse the JSON to get the verify config
313
+ let verify_config: serde_json::Value = match serde_json::from_str(&json_string) {
314
+ Ok(v) => v,
315
+ Err(e) => return cx.throw_error(format!("Invalid JSON: {}", e)),
316
+ };
317
+
318
+ // Get current settings and merge with verify config
319
+ let current_toml = get_global_settings_toml().unwrap_or_else(|| {
320
+ // If no current settings, create default settings
321
+ Settings::to_toml().unwrap_or_else(|_| String::new())
322
+ });
323
+
324
+ // Parse current settings
325
+ let mut current_settings: serde_json::Value = if current_toml.is_empty() {
326
+ serde_json::json!({
327
+ "version_major": 1,
328
+ "version_minor": 0,
329
+ "trust": {
330
+ "verify_trust_list": true,
331
+ "user_anchors": null,
332
+ "trust_anchors": null,
333
+ "trust_config": null,
334
+ "allowed_list": null
335
+ },
336
+ "cawg_trust": {
337
+ "verify_trust_list": true,
338
+ "user_anchors": null,
339
+ "trust_anchors": null,
340
+ "trust_config": null,
341
+ "allowed_list": null
342
+ },
343
+ "core": {
344
+ "debug": false,
345
+ "hash_alg": "sha256",
346
+ "salt_jumbf_boxes": true,
347
+ "prefer_box_hash": false,
348
+ "merkle_tree_max_proofs": 5,
349
+ "compress_manifests": true,
350
+ "backing_store_memory_threshold_in_mb": 512
351
+ },
352
+ "verify": {
353
+ "verify_after_reading": true,
354
+ "verify_after_sign": true,
355
+ "verify_trust": false,
356
+ "verify_timestamp_trust": true,
357
+ "ocsp_fetch": false,
358
+ "remote_manifest_fetch": true,
359
+ "check_ingredient_trust": true,
360
+ "skip_ingredient_conflict_resolution": false,
361
+ "strict_v1_validation": false
362
+ },
363
+ "builder": {
364
+ "thumbnail": {
365
+ "enabled": true
366
+ }
367
+ }
368
+ })
369
+ } else {
370
+ // Parse existing TOML to JSON
371
+ let toml_val: toml::Value = match toml::from_str(&current_toml) {
372
+ Ok(v) => v,
373
+ Err(e) => return cx.throw_error(format!("Failed to parse current TOML: {}", e)),
374
+ };
375
+ match serde_json::to_value(&toml_val) {
376
+ Ok(v) => v,
377
+ Err(e) => return cx.throw_error(format!("Failed to convert TOML to JSON: {}", e)),
378
+ }
379
+ };
380
+
381
+ // Update the verify section with new values
382
+ if let Some(verify_section) = current_settings.get_mut("verify") {
383
+ if let Some(obj) = verify_section.as_object_mut() {
384
+ if let Some(val) = verify_config.get("verify_after_reading") {
385
+ obj.insert("verify_after_reading".to_string(), val.clone());
386
+ }
387
+ if let Some(val) = verify_config.get("verify_after_sign") {
388
+ obj.insert("verify_after_sign".to_string(), val.clone());
389
+ }
390
+ if let Some(val) = verify_config.get("verify_trust") {
391
+ obj.insert("verify_trust".to_string(), val.clone());
392
+ }
393
+ if let Some(val) = verify_config.get("verify_timestamp_trust") {
394
+ obj.insert("verify_timestamp_trust".to_string(), val.clone());
395
+ }
396
+ if let Some(val) = verify_config.get("ocsp_fetch") {
397
+ obj.insert("ocsp_fetch".to_string(), val.clone());
398
+ }
399
+ if let Some(val) = verify_config.get("remote_manifest_fetch") {
400
+ obj.insert("remote_manifest_fetch".to_string(), val.clone());
401
+ }
402
+ if let Some(val) = verify_config.get("check_ingredient_trust") {
403
+ obj.insert("check_ingredient_trust".to_string(), val.clone());
404
+ }
405
+ if let Some(val) = verify_config.get("skip_ingredient_conflict_resolution") {
406
+ obj.insert("skip_ingredient_conflict_resolution".to_string(), val.clone());
407
+ }
408
+ if let Some(val) = verify_config.get("strict_v1_validation") {
409
+ obj.insert("strict_v1_validation".to_string(), val.clone());
410
+ }
411
+ }
412
+ }
413
+
414
+ // Convert back to TOML and apply
415
+ let updated_toml = match toml::to_string(&current_settings) {
416
+ Ok(t) => t,
417
+ Err(e) => return cx.throw_error(format!("Failed to convert to TOML: {}", e)),
418
+ };
419
+
420
+ // Apply the updated settings
421
+ match Settings::from_toml(&updated_toml) {
422
+ Ok(_) => {
423
+ // Settings are now applied globally, save the TOML representation
424
+ let toml_string = Settings::to_toml()
425
+ .or_else(|e| cx.throw_error(format!("Failed to get settings as TOML: {}", e)))?;
426
+ // Save the TOML snapshot for new worker threads
427
+ set_global_settings_toml(Some(toml_string));
428
+ reload_runtime();
429
+ Ok(cx.undefined())
430
+ }
431
+ Err(e) => cx.throw_error(format!("Failed to apply verify settings: {}", e)),
432
+ }
433
+ }
434
+
435
+ /// Get the current verify configuration as JSON.
436
+ pub fn get_verify_config(mut cx: FunctionContext) -> JsResult<JsValue> {
437
+ match get_global_settings_toml() {
438
+ Some(toml_string) => {
439
+ // Convert TOML -> JSON for processing
440
+ let toml_val: toml::Value = match toml::from_str(&toml_string) {
441
+ Ok(v) => v,
442
+ Err(e) => return cx.throw_error(format!("Failed to parse TOML: {}", e)),
443
+ };
444
+ let settings: serde_json::Value = match serde_json::to_value(&toml_val) {
445
+ Ok(v) => v,
446
+ Err(e) => return cx.throw_error(format!("Failed to convert TOML to JSON: {}", e)),
447
+ };
448
+
449
+ // Extract verify section
450
+ let default_verify_config = serde_json::json!({
451
+ "verify_after_reading": true,
452
+ "verify_after_sign": true,
453
+ "verify_trust": false,
454
+ "verify_timestamp_trust": true,
455
+ "ocsp_fetch": false,
456
+ "remote_manifest_fetch": true,
457
+ "check_ingredient_trust": true,
458
+ "skip_ingredient_conflict_resolution": false,
459
+ "strict_v1_validation": false
460
+ });
461
+ let verify_section = settings.get("verify").unwrap_or(&default_verify_config);
462
+
463
+ let json = match serde_json::to_string(verify_section) {
464
+ Ok(s) => s,
465
+ Err(e) => {
466
+ return cx.throw_error(format!("Failed to serialize verify config: {}", e))
467
+ }
468
+ };
469
+ Ok(cx.string(json).upcast())
470
+ }
471
+ None => {
472
+ // Return default verify config
473
+ let default_verify = serde_json::json!({
474
+ "verify_after_reading": true,
475
+ "verify_after_sign": true,
476
+ "verify_trust": false,
477
+ "verify_timestamp_trust": true,
478
+ "ocsp_fetch": false,
479
+ "remote_manifest_fetch": true,
480
+ "check_ingredient_trust": true,
481
+ "skip_ingredient_conflict_resolution": false,
482
+ "strict_v1_validation": false
483
+ });
484
+ Ok(cx.string(default_verify.to_string()).upcast())
485
+ }
486
+ }
487
+ }
package/src/utils.rs ADDED
@@ -0,0 +1,30 @@
1
+ // Copyright 2025 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
+
7
+ // Unless required by applicable law or agreed to in writing,
8
+ // this software is distributed on an "AS IS" BASIS, WITHOUT
9
+ // WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
10
+ // implied. See the LICENSE-MIT and LICENSE-APACHE files for the
11
+ // specific language governing permissions and limitations under
12
+ // each license.
13
+
14
+ use neon::prelude::*;
15
+
16
+ #[allow(dead_code)]
17
+ // Used in debugging
18
+ pub fn log_message<'a, C: Context<'a>>(cx: &mut C, message: &str) {
19
+ let global = cx.global_object();
20
+ let console: Handle<JsObject> = global.get(cx, "console").unwrap();
21
+ let log: Handle<JsFunction> = console
22
+ .get::<JsFunction, _, _>(cx, "log")
23
+ .unwrap()
24
+ .downcast_or_throw(cx)
25
+ .unwrap();
26
+ let msg = cx.string(message);
27
+ let this = cx.undefined();
28
+ let args: Vec<Handle<JsValue>> = vec![msg.upcast()];
29
+ log.call(cx, this, args).unwrap();
30
+ }