@contentauth/c2pa-node 0.4.1 → 0.4.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/Cargo.lock CHANGED
@@ -4156,9 +4156,9 @@ dependencies = [
4156
4156
 
4157
4157
  [[package]]
4158
4158
  name = "trustmark"
4159
- version = "0.2.1"
4159
+ version = "0.2.2"
4160
4160
  source = "registry+https://github.com/rust-lang/crates.io-index"
4161
- checksum = "7d92242b5b0be8b39a368434685e40e7e072b3d5c9cbafdc41edaebacf75181f"
4161
+ checksum = "b8d79dbe9052a5f7887e83019fa0291f3a97974dc9f08ce4851fd52e937b9d01"
4162
4162
  dependencies = [
4163
4163
  "fast_image_resize",
4164
4164
  "image",
package/Cargo.toml CHANGED
@@ -34,5 +34,5 @@ toml = "0.8"
34
34
  thiserror = "1.0.61"
35
35
  tokio = { version = "1.43.0", features = ["rt-multi-thread"] }
36
36
  tokio-util = "0.7.13"
37
- trustmark = "0.2"
37
+ trustmark = "0.2.2"
38
38
  rand = "0.8.5"
package/dist/Builder.js CHANGED
@@ -151,4 +151,7 @@ export class Builder {
151
151
  updateManifestProperty(property, value) {
152
152
  getNeonBinary().builderUpdateManifestProperty.call(this.builder, property, value);
153
153
  }
154
+ getHandle() {
155
+ return this.builder;
156
+ }
154
157
  }
@@ -19,6 +19,7 @@ import { isActionsAssertion } from "./assertions.js";
19
19
  import { CallbackSigner, LocalSigner } from "./Signer.js";
20
20
  import { Reader } from "./Reader.js";
21
21
  import { Builder } from "./Builder.js";
22
+ import { loadC2paSettings, resetSettings } from "./Settings.js";
22
23
  const tempDir = path.join(__dirname, "tmp");
23
24
  class TestSigner {
24
25
  constructor(privateKey) {
@@ -234,6 +235,70 @@ describe("Builder", () => {
234
235
  expect(manifestStore.active_manifest).not.toBeUndefined();
235
236
  expect(activeManifest === null || activeManifest === void 0 ? void 0 : activeManifest.title).toBe("Test_Manifest");
236
237
  }));
238
+ it("should populate buffer when archiving to buffer", () => __awaiter(void 0, void 0, void 0, function* () {
239
+ const archive = {
240
+ buffer: null,
241
+ };
242
+ yield builder.toArchive(archive);
243
+ expect(archive.buffer).not.toBeNull();
244
+ expect(archive.buffer.length).toBeGreaterThan(0);
245
+ }));
246
+ it("should write archive to file", () => __awaiter(void 0, void 0, void 0, function* () {
247
+ const archivePath = path.join(tempDir, "archive_file_test.zip");
248
+ const archive = { path: archivePath };
249
+ yield builder.toArchive(archive);
250
+ // Verify file was created and has content
251
+ expect(yield fs.pathExists(archivePath)).toBe(true);
252
+ const stats = yield fs.stat(archivePath);
253
+ expect(stats.size).toBeGreaterThan(0);
254
+ }));
255
+ it("should construct reader directly from builder archive buffer", () => __awaiter(void 0, void 0, void 0, function* () {
256
+ // Enable c2pa archive format
257
+ loadC2paSettings(JSON.stringify({
258
+ builder: {
259
+ generate_c2pa_archive: true,
260
+ },
261
+ verify: {
262
+ verify_after_reading: false,
263
+ },
264
+ }));
265
+ try {
266
+ // Create a builder
267
+ const simpleManifestDefinition = {
268
+ claim_generator_info: [
269
+ {
270
+ name: "c2pa_test",
271
+ version: "1.0.0",
272
+ },
273
+ ],
274
+ title: "Test_Manifest",
275
+ format: "image/jpeg",
276
+ assertions: [],
277
+ resources: { resources: {} },
278
+ };
279
+ const testBuilder = Builder.withJson(simpleManifestDefinition);
280
+ // Add an ingredient
281
+ yield testBuilder.addIngredient(parent_json, source);
282
+ // Create an archive from the builder written to a buffer
283
+ const archive = {
284
+ buffer: null,
285
+ };
286
+ yield testBuilder.toArchive(archive);
287
+ // Verify buffer was populated
288
+ expect(archive.buffer).not.toBeNull();
289
+ expect(archive.buffer.length).toBeGreaterThan(0);
290
+ // Construct a reader from the builder archive with mime-type "application/c2pa"
291
+ const reader = yield Reader.fromAsset({
292
+ buffer: archive.buffer,
293
+ mimeType: "application/c2pa",
294
+ });
295
+ expect(reader).not.toBeNull();
296
+ }
297
+ finally {
298
+ // Reset settings to defaults
299
+ resetSettings();
300
+ }
301
+ }));
237
302
  it("should sign data with callback to file", () => __awaiter(void 0, void 0, void 0, function* () {
238
303
  const dest = {
239
304
  path: path.join(tempDir, "callback_signed.jpg"),
@@ -155,7 +155,6 @@ describe("Reader", () => {
155
155
  }));
156
156
  it("should write to a file", () => __awaiter(void 0, void 0, void 0, function* () {
157
157
  var _a;
158
- let bytesWritten = 0;
159
158
  const outputPath = path.join(tempDir, "thumbnail.jpg");
160
159
  const reader = yield Reader.fromAsset({
161
160
  path: "./tests/fixtures/CA.jpg",
@@ -163,12 +162,11 @@ describe("Reader", () => {
163
162
  expect(reader).not.toBeNull();
164
163
  const activeManifest = reader.getActive();
165
164
  const uri = (_a = activeManifest === null || activeManifest === void 0 ? void 0 : activeManifest.thumbnail) === null || _a === void 0 ? void 0 : _a.identifier;
166
- if (uri !== undefined) {
167
- bytesWritten = yield reader.resourceToAsset(uri, {
168
- path: outputPath,
169
- });
170
- }
171
- expect(bytesWritten).toBe(49690);
165
+ expect(uri).toBeDefined();
166
+ const bytesWritten = yield reader.resourceToAsset(uri, {
167
+ path: outputPath,
168
+ });
169
+ expect(bytesWritten.bytes_written).toBe(49690);
172
170
  expect(fs.existsSync(outputPath));
173
171
  }));
174
172
  it("should report manifest is embedded", () => __awaiter(void 0, void 0, void 0, function* () {
package/dist/index.node CHANGED
Binary file
@@ -1,8 +1,8 @@
1
1
  import type { BuilderIntent, Ingredient, Manifest } from "@contentauth/c2pa-types";
2
- import type { BuilderInterface, CallbackSignerInterface, ClaimVersion, DestinationAsset, IdentityAssertionSignerInterface, JsCallbackSignerConfig, LocalSignerInterface, ManifestAssertionKind, ReaderInterface, SourceAsset } from "./types.d.ts";
2
+ import type { BuilderInterface, CallbackSignerInterface, ClaimVersion, DestinationAsset, IdentityAssertionSignerInterface, JsCallbackSignerConfig, LocalSignerInterface, ManifestAssertionKind, ReaderInterface, SourceAsset, NeonBuilderHandle } from "./types.d.ts";
3
3
  export declare class Builder implements BuilderInterface {
4
4
  private builder;
5
- private constructor();
5
+ constructor(builder: NeonBuilderHandle);
6
6
  static new(): Builder;
7
7
  static withJson(json: Manifest): Builder;
8
8
  setIntent(intent: BuilderIntent): void;
@@ -21,4 +21,5 @@ export declare class Builder implements BuilderInterface {
21
21
  signAsync(signer: CallbackSignerInterface | IdentityAssertionSignerInterface, input: SourceAsset, output: DestinationAsset): Promise<Buffer>;
22
22
  getManifestDefinition(): Manifest;
23
23
  updateManifestProperty(property: string, value: ClaimVersion): void;
24
+ getHandle(): NeonBuilderHandle;
24
25
  }
@@ -1,12 +1,12 @@
1
1
  import type { Manifest, ManifestStore } from "@contentauth/c2pa-types";
2
- import type { DestinationAsset, ReaderInterface, SourceAsset, NeonReaderHandle } from "./types.d.ts";
2
+ import type { DestinationAsset, ReaderInterface, ResourceAsset, SourceAsset, NeonReaderHandle } from "./types.d.ts";
3
3
  export declare class Reader implements ReaderInterface {
4
4
  private reader;
5
5
  constructor(reader: NeonReaderHandle);
6
6
  json(): ManifestStore;
7
7
  remoteUrl(): string;
8
8
  isEmbedded(): boolean;
9
- resourceToAsset(uri: string, asset: DestinationAsset): Promise<number>;
9
+ resourceToAsset(uri: string, asset: DestinationAsset): Promise<ResourceAsset>;
10
10
  static fromAsset(asset: SourceAsset): Promise<Reader | null>;
11
11
  static fromManifestDataAndAsset(manifestData: Buffer, asset: SourceAsset): Promise<Reader>;
12
12
  activeLabel(): string | undefined;
@@ -102,6 +102,13 @@ export type SourceAsset = SourceBufferAsset | FileAsset;
102
102
  */
103
103
  export type DestinationAsset = DestinationBufferAsset | FileAsset;
104
104
 
105
+ /**
106
+ * The return type of resourceToAsset.
107
+ * When the asset is a file, returns the number of bytes written.
108
+ * When the asset is a buffer, returns an object with the buffer and bytes written.
109
+ */
110
+ export type ResourceAsset = { buffer: Buffer; bytes_written: number };
111
+
105
112
  /**
106
113
  * A signer that uses a local certificate and private key to sign data
107
114
  */
@@ -315,6 +322,11 @@ export interface BuilderInterface {
315
322
  * @returns The manifest definition
316
323
  */
317
324
  updateManifestProperty(property: string, value: string | ClaimVersion): void;
325
+
326
+ /**
327
+ * Get the internal handle for use with Neon bindings
328
+ */
329
+ getHandle(): NeonBuilderHandle;
318
330
  }
319
331
 
320
332
  export interface ReaderInterface {
@@ -336,9 +348,14 @@ export interface ReaderInterface {
336
348
  /**
337
349
  * Write a resource to a buffer or file
338
350
  * @param uri The URI of the resource
339
- * @param filePath The path to the file
351
+ * @param output The destination asset (file or buffer)
352
+ * @returns When output is a file, returns the number of bytes written.
353
+ * When output is a buffer, returns an object with the buffer and bytes written.
340
354
  */
341
- resourceToAsset(uri: string, output: DestinationAsset): Promise<number>;
355
+ resourceToAsset(
356
+ uri: string,
357
+ output: DestinationAsset,
358
+ ): Promise<ResourceAsset>;
342
359
 
343
360
  /**
344
361
  * Get the internal handle for use with Neon bindings
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.1",
7
+ "version": "0.4.2",
8
8
  "description": "Node.js bindings for C2PA",
9
9
  "main": "dist/index.js",
10
10
  "type": "module",
package/src/error.rs CHANGED
@@ -51,6 +51,9 @@ pub enum Error {
51
51
  #[error("Settings handling failed: {0}")]
52
52
  Settings(String),
53
53
 
54
+ #[error("Reading failed: {0}")]
55
+ Reading(String),
56
+
54
57
  #[error("Signing failed: {0}")]
55
58
  Signing(String),
56
59
 
@@ -235,25 +235,47 @@ impl NeonBuilder {
235
235
 
236
236
  pub fn to_archive(mut cx: FunctionContext) -> JsResult<JsPromise> {
237
237
  let this = cx.this::<JsBox<Self>>()?;
238
- let dest = cx
239
- .argument::<JsObject>(0)
240
- .and_then(|obj| parse_asset(&mut cx, obj))?;
238
+ let dest_obj = cx.argument::<JsObject>(0)?;
239
+ let dest = parse_asset(&mut cx, dest_obj)?;
240
+ let is_buffer = dest.name() == "destination_buffer";
241
241
  let builder = Arc::clone(&this.builder);
242
+ let dest_obj_root: Arc<Root<JsObject>> = Arc::new(Root::new(&mut cx, &dest_obj));
242
243
 
243
244
  let promise = cx
244
245
  .task(move || {
245
246
  // Block on acquiring the async mutex lock
247
+ // Settings are automatically applied when runtime() is called
246
248
  let rt = runtime();
247
249
  let mut builder = rt.block_on(async { builder.lock().await });
248
250
 
249
- dest.write_stream().and_then(|dest_stream| {
250
- builder.to_archive(dest_stream)?;
251
- Ok(())
251
+ dest.write_stream().and_then(|mut dest_stream| {
252
+ builder.to_archive(&mut dest_stream)?;
253
+ if is_buffer {
254
+ let mut archive_data = Vec::new();
255
+ dest_stream
256
+ .rewind()
257
+ .map_err(|e| Error::Asset(format!("Failed to rewind stream: {e}")))?;
258
+ dest_stream
259
+ .read_to_end(&mut archive_data)
260
+ .map_err(|e| Error::Asset(format!("Failed to read stream: {e}")))?;
261
+ Ok(Some(archive_data))
262
+ } else {
263
+ Ok(None)
264
+ }
252
265
  })
253
266
  })
254
- .promise(move |mut cx, result: Result<(), Error>| match result {
255
- Ok(_) => Ok(cx.undefined()),
256
- Err(err) => as_js_error(&mut cx, err).and_then(|err| cx.throw(err)),
267
+ .promise(move |mut cx, result: Result<Option<Vec<u8>>, Error>| {
268
+ match result {
269
+ Ok(Some(archive_data)) => {
270
+ // If the output is a buffer, populate it with the archive data
271
+ let buffer = JsBuffer::from_slice(&mut cx, &archive_data)?;
272
+ let dest_obj = dest_obj_root.to_inner(&mut cx);
273
+ dest_obj.set(&mut cx, "buffer", buffer)?;
274
+ Ok(cx.undefined())
275
+ }
276
+ Ok(None) => Ok(cx.undefined()),
277
+ Err(err) => as_js_error(&mut cx, err).and_then(|err| cx.throw(err)),
278
+ }
257
279
  });
258
280
  Ok(promise)
259
281
  }
@@ -52,7 +52,7 @@ impl NeonReader {
52
52
  let format = source
53
53
  .mime_type()
54
54
  .ok_or_else(|| {
55
- Error::Signing("Ingredient asset must have a mime type".to_string())
55
+ Error::Reading("Source asset must have a mime type".to_string())
56
56
  })?
57
57
  .to_owned();
58
58
 
@@ -100,7 +100,7 @@ impl NeonReader {
100
100
  let format = asset
101
101
  .mime_type()
102
102
  .ok_or_else(|| {
103
- Error::Signing("Ingredient asset must have a mime type".to_string())
103
+ Error::Reading("Source asset must have a mime type".to_string())
104
104
  })?
105
105
  .to_owned();
106
106
  let stream = asset.into_read_stream()?;
@@ -182,16 +182,17 @@ impl NeonReader {
182
182
  None
183
183
  };
184
184
 
185
+ let result = cx.empty_object();
186
+ let js_bytes_written = cx.number(bytes_written as f64);
185
187
  if let Some(buffer) = buffer {
186
188
  let js_buffer = JsBuffer::from_slice(&mut cx, &buffer)?;
187
- let js_bytes_written = cx.number(bytes_written as f64);
188
- let result = cx.empty_object();
189
189
  result.set(&mut cx, "buffer", js_buffer)?;
190
- result.set(&mut cx, "bytes_written", js_bytes_written)?;
191
- Ok(result.upcast::<JsValue>())
192
190
  } else {
193
- Ok(cx.number(bytes_written as f64).upcast::<JsValue>())
191
+ let empty_buffer = JsBuffer::from_slice(&mut cx, &[])?;
192
+ result.set(&mut cx, "buffer", empty_buffer)?;
194
193
  }
194
+ result.set(&mut cx, "bytes_written", js_bytes_written)?;
195
+ Ok(result.upcast::<JsValue>())
195
196
  }
196
197
  Err(err) => as_js_error(&mut cx, err).and_then(|err| cx.throw(err)),
197
198
  });
package/src/runtime.rs CHANGED
@@ -28,6 +28,10 @@ fn build_runtime() -> Arc<Runtime> {
28
28
  }
29
29
 
30
30
  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
+
31
35
  let cell = RUNTIME.get_or_init(|| RwLock::new(build_runtime()));
32
36
  cell.read().unwrap().clone()
33
37
  }
package/src/settings.rs CHANGED
@@ -32,6 +32,14 @@ pub(crate) fn get_global_settings_toml() -> Option<String> {
32
32
  global_toml().read().unwrap().clone()
33
33
  }
34
34
 
35
+ /// Apply settings to the current thread from the global TOML snapshot.
36
+ /// This should be called whenever settings might be needed, as settings may have changed.
37
+ pub(crate) fn apply_settings_to_current_thread() {
38
+ if let Some(toml) = get_global_settings_toml() {
39
+ let _ = Settings::from_toml(&toml);
40
+ }
41
+ }
42
+
35
43
  /// Parse a JSON string (argument 0) into c2pa-rs Settings and apply them globally.
36
44
  /// Returns undefined; the JSON snapshot is stored globally for new worker threads.
37
45
  pub fn load_settings(mut cx: FunctionContext) -> JsResult<JsUndefined> {
@@ -47,6 +55,8 @@ pub fn load_settings(mut cx: FunctionContext) -> JsResult<JsUndefined> {
47
55
  .or_else(|e| cx.throw_error(format!("Failed to get settings as TOML: {}", e)))?;
48
56
  // Save the JSON snapshot for new worker threads
49
57
  set_global_settings_toml(Some(toml_string));
58
+ // Apply settings to current thread
59
+ apply_settings_to_current_thread();
50
60
  reload_runtime();
51
61
  Ok(cx.undefined())
52
62
  }
@@ -68,6 +78,8 @@ pub fn load_settings_toml(mut cx: FunctionContext) -> JsResult<JsUndefined> {
68
78
  .or_else(|e| cx.throw_error(format!("Failed to get settings as TOML: {}", e)))?;
69
79
  // Save the TOML snapshot for new worker threads
70
80
  set_global_settings_toml(Some(toml_string));
81
+ // Apply settings to current thread
82
+ apply_settings_to_current_thread();
71
83
  reload_runtime();
72
84
  Ok(cx.undefined())
73
85
  }
@@ -152,6 +164,7 @@ pub fn load_trust_config(mut cx: FunctionContext) -> JsResult<JsUndefined> {
152
164
  let full_toml = Settings::to_toml()
153
165
  .or_else(|e| cx.throw_error(format!("Failed to get settings as TOML: {}", e)))?;
154
166
  set_global_settings_toml(Some(full_toml));
167
+ apply_settings_to_current_thread();
155
168
  reload_runtime();
156
169
  Ok(cx.undefined())
157
170
  }
@@ -202,6 +215,7 @@ pub fn load_cawg_trust_config(mut cx: FunctionContext) -> JsResult<JsUndefined>
202
215
  let full_toml = Settings::to_toml()
203
216
  .or_else(|e| cx.throw_error(format!("Failed to get settings as TOML: {}", e)))?;
204
217
  set_global_settings_toml(Some(full_toml));
218
+ apply_settings_to_current_thread();
205
219
  reload_runtime();
206
220
  Ok(cx.undefined())
207
221
  }
@@ -424,6 +438,7 @@ pub fn load_verify_config(mut cx: FunctionContext) -> JsResult<JsUndefined> {
424
438
  .or_else(|e| cx.throw_error(format!("Failed to get settings as TOML: {}", e)))?;
425
439
  // Save the TOML snapshot for new worker threads
426
440
  set_global_settings_toml(Some(toml_string));
441
+ apply_settings_to_current_thread();
427
442
  reload_runtime();
428
443
  Ok(cx.undefined())
429
444
  }
@@ -496,6 +511,7 @@ pub fn reset_settings(mut cx: FunctionContext) -> JsResult<JsUndefined> {
496
511
  Ok(_) => {
497
512
  // Store the default TOML for worker threads
498
513
  set_global_settings_toml(Some(default_toml));
514
+ apply_settings_to_current_thread();
499
515
  reload_runtime();
500
516
  Ok(cx.undefined())
501
517
  }