@contentauth/c2pa-node 0.4.0 → 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
@@ -68,6 +68,11 @@ export class Builder {
68
68
  }
69
69
  });
70
70
  }
71
+ addIngredientFromReader(reader) {
72
+ const readerHandle = reader.getHandle();
73
+ const result = getNeonBinary().builderAddIngredientFromReader.call(this.builder, readerHandle);
74
+ return JSON.parse(result);
75
+ }
71
76
  toArchive(asset) {
72
77
  return __awaiter(this, void 0, void 0, function* () {
73
78
  return getNeonBinary().builderToArchive.call(this.builder, asset);
@@ -79,11 +84,11 @@ export class Builder {
79
84
  });
80
85
  }
81
86
  sign(signer, input, output) {
82
- return getNeonBinary().builderSign.call(this.builder, signer.signer(), input, output);
87
+ return getNeonBinary().builderSign.call(this.builder, signer.getHandle(), input, output);
83
88
  }
84
89
  signFile(signer, filePath, output) {
85
90
  const input = { path: filePath };
86
- return getNeonBinary().builderSign.call(this.builder, signer.signer(), input, output);
91
+ return getNeonBinary().builderSign.call(this.builder, signer.getHandle(), input, output);
87
92
  }
88
93
  signConfigAsync(callback, signerConfig, input, output) {
89
94
  return __awaiter(this, void 0, void 0, function* () {
@@ -112,7 +117,7 @@ export class Builder {
112
117
  }
113
118
  signAsync(signer, input, output) {
114
119
  return __awaiter(this, void 0, void 0, function* () {
115
- const neonHandle = signer.signer();
120
+ const neonHandle = signer.getHandle();
116
121
  const isIdentity = signer instanceof IdentityAssertionSigner;
117
122
  const neonFn = isIdentity
118
123
  ? getNeonBinary().builderIdentitySignAsync
@@ -146,4 +151,7 @@ export class Builder {
146
151
  updateManifestProperty(property, value) {
147
152
  getNeonBinary().builderUpdateManifestProperty.call(this.builder, property, value);
148
153
  }
154
+ getHandle() {
155
+ return this.builder;
156
+ }
149
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"),
@@ -634,5 +699,43 @@ describe("Builder", () => {
634
699
  expect(addedIngredient === null || addedIngredient === void 0 ? void 0 : addedIngredient.instance_id).toBe("ingredient-12345");
635
700
  expect(addedIngredient === null || addedIngredient === void 0 ? void 0 : addedIngredient.relationship).toBe("componentOf");
636
701
  }));
702
+ it("should add ingredient from reader", () => __awaiter(void 0, void 0, void 0, function* () {
703
+ var _a;
704
+ const builder1 = Builder.new();
705
+ builder1.setIntent("edit");
706
+ const signer = LocalSigner.newSigner(publicKey, privateKey, "es256");
707
+ const dest1 = {
708
+ buffer: null,
709
+ };
710
+ builder1.sign(signer, source, dest1);
711
+ // Read the signed file back with Reader
712
+ const reader = yield Reader.fromAsset({
713
+ buffer: dest1.buffer,
714
+ mimeType: "image/jpeg",
715
+ });
716
+ expect(reader).not.toBeNull();
717
+ // Create a new builder and add ingredient from the reader
718
+ const builder2 = Builder.new();
719
+ const ingredient = builder2.addIngredientFromReader(reader);
720
+ expect(ingredient).toBeDefined();
721
+ // Verify the ingredient was added to the builder
722
+ const definition = builder2.getManifestDefinition();
723
+ expect(definition.ingredients).toBeDefined();
724
+ expect(definition.ingredients.length).toBeGreaterThan(0);
725
+ // Sign again with the new builder
726
+ const dest2 = {
727
+ buffer: null,
728
+ };
729
+ builder2.sign(signer, source, dest2);
730
+ // Verify the ingredient is in the signed manifest
731
+ const reader2 = yield Reader.fromAsset({
732
+ buffer: dest2.buffer,
733
+ mimeType: "image/jpeg",
734
+ });
735
+ expect(reader2).not.toBeNull();
736
+ const activeManifest = reader2.getActive();
737
+ expect(activeManifest === null || activeManifest === void 0 ? void 0 : activeManifest.ingredients).toBeDefined();
738
+ expect((_a = activeManifest === null || activeManifest === void 0 ? void 0 : activeManifest.ingredients) === null || _a === void 0 ? void 0 : _a.length).toBe(1);
739
+ }));
637
740
  });
638
741
  });
@@ -25,7 +25,7 @@ export class IdentityAssertionBuilder {
25
25
  }
26
26
  static identityBuilderForCredentialHolder(credentialHolder) {
27
27
  return __awaiter(this, void 0, void 0, function* () {
28
- const builder = getNeonBinary().identityBuilderForCredentialHolder(credentialHolder.signer());
28
+ const builder = getNeonBinary().identityBuilderForCredentialHolder(credentialHolder.getHandle());
29
29
  return new IdentityAssertionBuilder(builder);
30
30
  });
31
31
  }
@@ -50,7 +50,7 @@ export class IdentityAssertionSigner {
50
50
  addIdentityAssertion(identityAssertionBuilder) {
51
51
  getNeonBinary().identitySignerAddIdentityAssertion.call(this._signer, identityAssertionBuilder.builder());
52
52
  }
53
- signer() {
53
+ getHandle() {
54
54
  return this._signer;
55
55
  }
56
56
  }
@@ -58,7 +58,7 @@ export class CallbackCredentialHolder {
58
58
  constructor(callbackCredentialHolder) {
59
59
  this.callbackCredentialHolder = callbackCredentialHolder;
60
60
  }
61
- signer() {
61
+ getHandle() {
62
62
  return this.callbackCredentialHolder;
63
63
  }
64
64
  static newCallbackCredentialHolder(reserveSize, sigType, callback) {
@@ -136,7 +136,7 @@ describe("IdentityAssertionBuilder", () => {
136
136
  buffer: yield fs.readFile("./tests/fixtures/thumbnail.jpg"),
137
137
  });
138
138
  // Create and configure the identity assertion
139
- const iaSigner = IdentityAssertionSigner.new(c2paSigner.signer());
139
+ const iaSigner = IdentityAssertionSigner.new(c2paSigner.getHandle());
140
140
  const iab = yield IdentityAssertionBuilder.identityBuilderForCredentialHolder(cawgSigner);
141
141
  iab.addReferencedAssertions(["cawg.training-mining"]);
142
142
  iaSigner.addIdentityAssertion(iab);
package/dist/Reader.js CHANGED
@@ -57,4 +57,7 @@ export class Reader {
57
57
  }
58
58
  return manifestStore.manifests[activeManifest];
59
59
  }
60
+ getHandle() {
61
+ return this.reader;
62
+ }
60
63
  }
@@ -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/Signer.js CHANGED
@@ -42,7 +42,7 @@ export class LocalSigner {
42
42
  timeAuthorityUrl() {
43
43
  return getNeonBinary().localSignerTimeAuthorityUrl.call(this.localSigner);
44
44
  }
45
- signer() {
45
+ getHandle() {
46
46
  return this.localSigner;
47
47
  }
48
48
  }
@@ -50,7 +50,7 @@ export class CallbackSigner {
50
50
  constructor(callbackSigner) {
51
51
  this.callbackSigner = callbackSigner;
52
52
  }
53
- signer() {
53
+ getHandle() {
54
54
  return this.callbackSigner;
55
55
  }
56
56
  static newSigner(config, callback) {
package/dist/index.node CHANGED
Binary file
@@ -1,8 +1,8 @@
1
- import type { BuilderIntent, Manifest } from "@contentauth/c2pa-types";
2
- import type { BuilderInterface, CallbackSignerInterface, ClaimVersion, DestinationAsset, IdentityAssertionSignerInterface, JsCallbackSignerConfig, LocalSignerInterface, ManifestAssertionKind, SourceAsset } from "./types.d.ts";
1
+ import type { BuilderIntent, Ingredient, Manifest } from "@contentauth/c2pa-types";
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;
@@ -12,6 +12,7 @@ export declare class Builder implements BuilderInterface {
12
12
  addAssertion(label: string, assertion: unknown, assertionKind?: ManifestAssertionKind): void;
13
13
  addResource(uri: string, resource: SourceAsset): Promise<void>;
14
14
  addIngredient(ingredientJson: string, ingredient?: SourceAsset): Promise<void>;
15
+ addIngredientFromReader(reader: ReaderInterface): Ingredient;
15
16
  toArchive(asset: DestinationAsset): Promise<void>;
16
17
  static fromArchive(asset: SourceAsset): Promise<Builder>;
17
18
  sign(signer: LocalSignerInterface, input: SourceAsset, output: DestinationAsset): Buffer;
@@ -20,4 +21,5 @@ export declare class Builder implements BuilderInterface {
20
21
  signAsync(signer: CallbackSignerInterface | IdentityAssertionSignerInterface, input: SourceAsset, output: DestinationAsset): Promise<Buffer>;
21
22
  getManifestDefinition(): Manifest;
22
23
  updateManifestProperty(property: string, value: ClaimVersion): void;
24
+ getHandle(): NeonBuilderHandle;
23
25
  }
@@ -12,12 +12,12 @@ export declare class IdentityAssertionSigner implements IdentityAssertionSignerI
12
12
  constructor(_signer: NeonIdentityAssertionSignerHandle);
13
13
  static new(signer: NeonCallbackSignerHandle): IdentityAssertionSigner;
14
14
  addIdentityAssertion(identityAssertionBuilder: IdentityAssertionBuilder): void;
15
- signer(): NeonIdentityAssertionSignerHandle;
15
+ getHandle(): NeonIdentityAssertionSignerHandle;
16
16
  }
17
17
  export declare class CallbackCredentialHolder implements CallbackCredentialHolderInterface {
18
18
  private callbackCredentialHolder;
19
19
  constructor(callbackCredentialHolder: NeonCallbackCredentialHolderHandle);
20
- signer(): NeonCallbackCredentialHolderHandle;
20
+ getHandle(): NeonCallbackCredentialHolderHandle;
21
21
  static newCallbackCredentialHolder(reserveSize: number, sigType: string, callback: (signerPayload: SignerPayload) => Promise<Buffer>): CallbackCredentialHolder;
22
22
  sign(payload: SignerPayload): Promise<Buffer>;
23
23
  reserveSize(): number;
@@ -1,14 +1,15 @@
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;
13
13
  getActive(): Manifest | undefined;
14
+ getHandle(): NeonReaderHandle;
14
15
  }
@@ -8,12 +8,12 @@ export declare class LocalSigner implements LocalSignerInterface {
8
8
  certs(): Array<Buffer>;
9
9
  reserveSize(): number;
10
10
  timeAuthorityUrl(): string | undefined;
11
- signer(): NeonLocalSignerHandle;
11
+ getHandle(): NeonLocalSignerHandle;
12
12
  }
13
13
  export declare class CallbackSigner implements CallbackSignerInterface {
14
14
  private callbackSigner;
15
15
  constructor(callbackSigner: NeonCallbackSignerHandle);
16
- signer(): NeonCallbackSignerHandle;
16
+ getHandle(): NeonCallbackSignerHandle;
17
17
  static newSigner(config: JsCallbackSignerConfig, callback: (data: Buffer) => Promise<Buffer>): CallbackSigner;
18
18
  sign(data: Buffer): Promise<Buffer>;
19
19
  alg(): SigningAlg;
@@ -15,6 +15,7 @@
15
15
  import { Buffer } from "buffer";
16
16
  import type {
17
17
  BuilderIntent,
18
+ Ingredient,
18
19
  Manifest,
19
20
  ManifestStore,
20
21
  } from "@contentauth/c2pa-types";
@@ -101,6 +102,13 @@ export type SourceAsset = SourceBufferAsset | FileAsset;
101
102
  */
102
103
  export type DestinationAsset = DestinationBufferAsset | FileAsset;
103
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
+
104
112
  /**
105
113
  * A signer that uses a local certificate and private key to sign data
106
114
  */
@@ -110,7 +118,7 @@ export interface LocalSignerInterface {
110
118
  certs(): Array<Buffer>;
111
119
  reserveSize(): number;
112
120
  timeAuthorityUrl(): string | undefined;
113
- signer(): NeonLocalSignerHandle;
121
+ getHandle(): NeonLocalSignerHandle;
114
122
  }
115
123
 
116
124
  /**
@@ -123,14 +131,14 @@ export interface CallbackSignerInterface {
123
131
  reserveSize(): number;
124
132
  timeAuthorityUrl(): string | undefined;
125
133
  directCoseHandling(): boolean;
126
- signer(): NeonCallbackSignerHandle;
134
+ getHandle(): NeonCallbackSignerHandle;
127
135
  }
128
136
 
129
137
  export interface CallbackCredentialHolderInterface {
130
138
  sigType(): string;
131
139
  reserveSize(): number;
132
140
  sign(payload: SignerPayload): Promise<Buffer>;
133
- signer(): NeonCallbackCredentialHolderHandle;
141
+ getHandle(): NeonCallbackCredentialHolderHandle;
134
142
  }
135
143
 
136
144
  /**
@@ -235,6 +243,12 @@ export interface BuilderInterface {
235
243
  ingredient?: SourceAsset,
236
244
  ): Promise<void>;
237
245
 
246
+ /**
247
+ * Add an ingredient to the manifest from a Reader
248
+ * @param reader The Reader object of the ingredient
249
+ */
250
+ addIngredientFromReader(reader: ReaderInterface): Ingredient;
251
+
238
252
  /**
239
253
  * Convert the Builder into a archive formatted buffer or file
240
254
  * @param asset The file or buffer for the archive
@@ -308,6 +322,11 @@ export interface BuilderInterface {
308
322
  * @returns The manifest definition
309
323
  */
310
324
  updateManifestProperty(property: string, value: string | ClaimVersion): void;
325
+
326
+ /**
327
+ * Get the internal handle for use with Neon bindings
328
+ */
329
+ getHandle(): NeonBuilderHandle;
311
330
  }
312
331
 
313
332
  export interface ReaderInterface {
@@ -329,9 +348,19 @@ export interface ReaderInterface {
329
348
  /**
330
349
  * Write a resource to a buffer or file
331
350
  * @param uri The URI of the resource
332
- * @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.
354
+ */
355
+ resourceToAsset(
356
+ uri: string,
357
+ output: DestinationAsset,
358
+ ): Promise<ResourceAsset>;
359
+
360
+ /**
361
+ * Get the internal handle for use with Neon bindings
333
362
  */
334
- resourceToAsset(uri: string, output: DestinationAsset): Promise<number>;
363
+ getHandle(): NeonReaderHandle;
335
364
  }
336
365
 
337
366
  export interface IdentityAssertionSignerInterface {
@@ -345,7 +374,7 @@ export interface IdentityAssertionSignerInterface {
345
374
  identityAssertionBuilder: IdentityAssertionBuilderInterface,
346
375
  ): void;
347
376
 
348
- signer(): NeonIdentityAssertionSignerHandle;
377
+ getHandle(): NeonIdentityAssertionSignerHandle;
349
378
  }
350
379
 
351
380
  export interface IdentityAssertionBuilderInterface {
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.0",
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
 
package/src/lib.rs CHANGED
@@ -55,6 +55,10 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> {
55
55
  "builderAddIngredientFromAsset",
56
56
  neon_builder::NeonBuilder::add_ingredient_from_asset,
57
57
  )?;
58
+ cx.export_function(
59
+ "builderAddIngredientFromReader",
60
+ neon_builder::NeonBuilder::add_ingredient_from_reader,
61
+ )?;
58
62
  cx.export_function("builderToArchive", neon_builder::NeonBuilder::to_archive)?;
59
63
  cx.export_function(
60
64
  "builderFromArchive",
@@ -14,6 +14,7 @@
14
14
  use crate::asset::parse_asset;
15
15
  use crate::error::{as_js_error, Error};
16
16
  use crate::neon_identity_assertion_signer::NeonIdentityAssertionSigner;
17
+ use crate::neon_reader::NeonReader;
17
18
  use crate::neon_signer::{CallbackSignerConfig, NeonCallbackSigner, NeonLocalSigner};
18
19
  use crate::runtime::runtime;
19
20
  use c2pa::{Builder, BuilderIntent, Ingredient};
@@ -92,8 +93,8 @@ impl NeonBuilder {
92
93
  let rt = runtime();
93
94
  let this = cx.this::<JsBox<Self>>()?;
94
95
  let action_json = cx.argument::<JsString>(0)?.value(&mut cx);
95
- let action: c2pa::assertions::Action = serde_json::from_str(&action_json)
96
- .or_else(|err| cx.throw_error(err.to_string()))?;
96
+ let action: c2pa::assertions::Action =
97
+ serde_json::from_str(&action_json).or_else(|err| cx.throw_error(err.to_string()))?;
97
98
  let mut builder = rt.block_on(async { this.builder.lock().await });
98
99
  builder
99
100
  .add_action(action)
@@ -217,27 +218,64 @@ impl NeonBuilder {
217
218
  Ok(promise)
218
219
  }
219
220
 
221
+ pub fn add_ingredient_from_reader(mut cx: FunctionContext) -> JsResult<JsString> {
222
+ let rt = runtime();
223
+ let this = cx.this::<JsBox<Self>>()?;
224
+ let reader = cx.argument::<JsBox<NeonReader>>(0)?.reader();
225
+
226
+ let mut builder = rt.block_on(async { this.builder.lock().await });
227
+ let reader = rt.block_on(async { reader.lock().await });
228
+ let ingredient = builder
229
+ .add_ingredient_from_reader(&reader)
230
+ .or_else(|err| cx.throw_error(err.to_string()))?;
231
+ let json =
232
+ serde_json::to_string(&ingredient).or_else(|err| cx.throw_error(err.to_string()))?;
233
+ Ok(cx.string(json))
234
+ }
235
+
220
236
  pub fn to_archive(mut cx: FunctionContext) -> JsResult<JsPromise> {
221
237
  let this = cx.this::<JsBox<Self>>()?;
222
- let dest = cx
223
- .argument::<JsObject>(0)
224
- .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";
225
241
  let builder = Arc::clone(&this.builder);
242
+ let dest_obj_root: Arc<Root<JsObject>> = Arc::new(Root::new(&mut cx, &dest_obj));
226
243
 
227
244
  let promise = cx
228
245
  .task(move || {
229
246
  // Block on acquiring the async mutex lock
247
+ // Settings are automatically applied when runtime() is called
230
248
  let rt = runtime();
231
249
  let mut builder = rt.block_on(async { builder.lock().await });
232
250
 
233
- dest.write_stream().and_then(|dest_stream| {
234
- builder.to_archive(dest_stream)?;
235
- 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
+ }
236
265
  })
237
266
  })
238
- .promise(move |mut cx, result: Result<(), Error>| match result {
239
- Ok(_) => Ok(cx.undefined()),
240
- 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
+ }
241
279
  });
242
280
  Ok(promise)
243
281
  }
@@ -34,6 +34,11 @@ impl NeonReader {
34
34
  }))
35
35
  }
36
36
 
37
+ #[allow(clippy::borrowed_box)]
38
+ pub(crate) fn reader(&self) -> Arc<Mutex<Reader>> {
39
+ Arc::clone(&self.reader)
40
+ }
41
+
37
42
  pub fn from_stream(mut cx: FunctionContext) -> JsResult<JsPromise> {
38
43
  let rt = runtime();
39
44
  let channel = cx.channel();
@@ -47,7 +52,7 @@ impl NeonReader {
47
52
  let format = source
48
53
  .mime_type()
49
54
  .ok_or_else(|| {
50
- Error::Signing("Ingredient asset must have a mime type".to_string())
55
+ Error::Reading("Source asset must have a mime type".to_string())
51
56
  })?
52
57
  .to_owned();
53
58
 
@@ -69,9 +74,7 @@ impl NeonReader {
69
74
  // Return null instead of throwing for these specific cases
70
75
  match &err {
71
76
  Error::C2pa(c2pa_err) => match c2pa_err {
72
- c2pa::Error::JumbfNotFound => {
73
- Ok(cx.null().upcast::<JsValue>())
74
- }
77
+ c2pa::Error::JumbfNotFound => Ok(cx.null().upcast::<JsValue>()),
75
78
  _ => as_js_error(&mut cx, err).and_then(|err| cx.throw(err)),
76
79
  },
77
80
  _ => as_js_error(&mut cx, err).and_then(|err| cx.throw(err)),
@@ -97,7 +100,7 @@ impl NeonReader {
97
100
  let format = asset
98
101
  .mime_type()
99
102
  .ok_or_else(|| {
100
- Error::Signing("Ingredient asset must have a mime type".to_string())
103
+ Error::Reading("Source asset must have a mime type".to_string())
101
104
  })?
102
105
  .to_owned();
103
106
  let stream = asset.into_read_stream()?;
@@ -179,16 +182,17 @@ impl NeonReader {
179
182
  None
180
183
  };
181
184
 
185
+ let result = cx.empty_object();
186
+ let js_bytes_written = cx.number(bytes_written as f64);
182
187
  if let Some(buffer) = buffer {
183
188
  let js_buffer = JsBuffer::from_slice(&mut cx, &buffer)?;
184
- let js_bytes_written = cx.number(bytes_written as f64);
185
- let result = cx.empty_object();
186
189
  result.set(&mut cx, "buffer", js_buffer)?;
187
- result.set(&mut cx, "bytes_written", js_bytes_written)?;
188
- Ok(result.upcast::<JsValue>())
189
190
  } else {
190
- 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)?;
191
193
  }
194
+ result.set(&mut cx, "bytes_written", js_bytes_written)?;
195
+ Ok(result.upcast::<JsValue>())
192
196
  }
193
197
  Err(err) => as_js_error(&mut cx, err).and_then(|err| cx.throw(err)),
194
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
  }