@contentauth/c2pa-node 0.2.3 → 0.4.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.
package/dist/Settings.js CHANGED
@@ -166,7 +166,6 @@ export function loadVerifyConfig(verifyConfig) {
166
166
  verify_timestamp_trust: verifyConfig.verifyTimestampTrust,
167
167
  ocsp_fetch: verifyConfig.ocspFetch,
168
168
  remote_manifest_fetch: verifyConfig.remoteManifestFetch,
169
- check_ingredient_trust: verifyConfig.checkIngredientTrust,
170
169
  skip_ingredient_conflict_resolution: verifyConfig.skipIngredientConflictResolution,
171
170
  strict_v1_validation: verifyConfig.strictV1Validation,
172
171
  };
@@ -196,8 +195,14 @@ export function getVerifyConfig() {
196
195
  verifyTimestampTrust: parsed.verify_timestamp_trust,
197
196
  ocspFetch: parsed.ocsp_fetch,
198
197
  remoteManifestFetch: parsed.remote_manifest_fetch,
199
- checkIngredientTrust: parsed.check_ingredient_trust,
200
198
  skipIngredientConflictResolution: parsed.skip_ingredient_conflict_resolution,
201
199
  strictV1Validation: parsed.strict_v1_validation,
202
200
  };
203
201
  }
202
+ /**
203
+ * Reset settings to their default values.
204
+ * This clears any custom settings and restores the default configuration.
205
+ */
206
+ export function resetSettings() {
207
+ getNeonBinary().resetSettings();
208
+ }
@@ -3,8 +3,11 @@
3
3
  // Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
4
4
  // or the MIT license (http://opensource.org/licenses/MIT),
5
5
  // at your option.
6
- import { loadC2paSettings, loadTrustConfig, loadCawgTrustConfig, getSettingsJson, getTrustConfig, getCawgTrustConfig, loadVerifyConfig, getVerifyConfig, patchVerifyConfig, } from "./Settings.js";
6
+ import { getCawgTrustConfig, getSettingsJson, getTrustConfig, getVerifyConfig, loadC2paSettings, loadCawgTrustConfig, loadTrustConfig, loadVerifyConfig, patchVerifyConfig, resetSettings, } from "./Settings.js";
7
7
  describe("Settings", () => {
8
+ afterAll(() => {
9
+ resetSettings();
10
+ });
8
11
  it("loads a trustlist-shaped JSON and returns JSON via getSettingsJson", () => {
9
12
  var _a, _b;
10
13
  // Matches c2pa-rs settings structure: trust + verify
@@ -98,7 +101,7 @@ describe("Settings", () => {
98
101
  expect(() => loadTrustConfig(emptyTrustConfig)).not.toThrow();
99
102
  // Verify settings are still intact
100
103
  const currentSettings = JSON.parse(getSettingsJson());
101
- expect(currentSettings.core.hash_alg).toBe("sha256");
104
+ expect(currentSettings.core.decode_identity_assertions).toBe(true);
102
105
  expect(currentSettings.verify.verify_trust).toBe(true);
103
106
  expect(currentSettings.trust.verify_trust_list).toBe(true);
104
107
  });
@@ -178,7 +181,6 @@ describe("Settings", () => {
178
181
  verifyTimestampTrust: true,
179
182
  ocspFetch: false,
180
183
  remoteManifestFetch: true, // This should not affect trust settings
181
- checkIngredientTrust: false,
182
184
  skipIngredientConflictResolution: true,
183
185
  strictV1Validation: false,
184
186
  };
@@ -198,7 +200,6 @@ describe("Settings", () => {
198
200
  expect(finalSettings.verify.verify_timestamp_trust).toBe(true);
199
201
  expect(finalSettings.verify.ocsp_fetch).toBe(false);
200
202
  expect(finalSettings.verify.remote_manifest_fetch).toBe(true);
201
- expect(finalSettings.verify.check_ingredient_trust).toBe(false);
202
203
  expect(finalSettings.verify.skip_ingredient_conflict_resolution).toBe(true);
203
204
  expect(finalSettings.verify.strict_v1_validation).toBe(false);
204
205
  // Verify that trust settings are not affected by verify settings
@@ -217,7 +218,6 @@ describe("Settings", () => {
217
218
  verifyTimestampTrust: false,
218
219
  ocspFetch: true,
219
220
  remoteManifestFetch: false,
220
- checkIngredientTrust: true,
221
221
  skipIngredientConflictResolution: false,
222
222
  strictV1Validation: true,
223
223
  };
@@ -244,7 +244,6 @@ describe("Settings", () => {
244
244
  verifyTimestampTrust: true,
245
245
  ocspFetch: false,
246
246
  remoteManifestFetch: true,
247
- checkIngredientTrust: false,
248
247
  skipIngredientConflictResolution: true,
249
248
  strictV1Validation: false,
250
249
  };
@@ -258,7 +257,6 @@ describe("Settings", () => {
258
257
  expect(finalSettings.verify.verify_timestamp_trust).toBe(true);
259
258
  expect(finalSettings.verify.ocsp_fetch).toBe(false);
260
259
  expect(finalSettings.verify.remote_manifest_fetch).toBe(true);
261
- expect(finalSettings.verify.check_ingredient_trust).toBe(false);
262
260
  expect(finalSettings.verify.skip_ingredient_conflict_resolution).toBe(true);
263
261
  expect(finalSettings.verify.strict_v1_validation).toBe(false);
264
262
  });
@@ -271,7 +269,6 @@ describe("Settings", () => {
271
269
  verifyTimestampTrust: true,
272
270
  ocspFetch: false,
273
271
  remoteManifestFetch: true,
274
- checkIngredientTrust: true,
275
272
  skipIngredientConflictResolution: false,
276
273
  strictV1Validation: false,
277
274
  };
@@ -294,7 +291,6 @@ describe("Settings", () => {
294
291
  expect(patchedRetrievedConfig.verifyTimestampTrust).toBe(true); // unchanged
295
292
  expect(patchedRetrievedConfig.ocspFetch).toBe(true); // patched
296
293
  expect(patchedRetrievedConfig.remoteManifestFetch).toBe(true); // unchanged
297
- expect(patchedRetrievedConfig.checkIngredientTrust).toBe(true); // unchanged
298
294
  expect(patchedRetrievedConfig.skipIngredientConflictResolution).toBe(false); // unchanged
299
295
  expect(patchedRetrievedConfig.strictV1Validation).toBe(true); // patched
300
296
  // Verify the changes are reflected in getSettingsJson()
@@ -307,7 +303,6 @@ describe("Settings", () => {
307
303
  expect(settings.verify.verify_after_sign).toBe(true);
308
304
  expect(settings.verify.verify_timestamp_trust).toBe(true);
309
305
  expect(settings.verify.remote_manifest_fetch).toBe(true);
310
- expect(settings.verify.check_ingredient_trust).toBe(true);
311
306
  expect(settings.verify.skip_ingredient_conflict_resolution).toBe(false);
312
307
  });
313
308
  });
package/dist/Signer.js CHANGED
@@ -76,4 +76,7 @@ export class CallbackSigner {
76
76
  timeAuthorityUrl() {
77
77
  return getNeonBinary().callbackSignerTimeAuthorityUrl.call(this.callbackSigner);
78
78
  }
79
+ directCoseHandling() {
80
+ return getNeonBinary().callbackSignerDirectCoseHandling.call(this.callbackSigner);
81
+ }
79
82
  }
@@ -18,9 +18,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
18
18
  // implied. See the LICENSE-MIT and LICENSE-APACHE files for the
19
19
  // specific language governing permissions and limitations under
20
20
  // each license.
21
+ /* eslint-disable @typescript-eslint/no-non-null-assertion */
21
22
  import * as fs from "fs-extra";
22
23
  import * as crypto from "crypto";
23
24
  import { CallbackSigner } from "./Signer.js";
25
+ import { Builder } from "./Builder.js";
26
+ import { Reader } from "./Reader.js";
24
27
  class TestSigner {
25
28
  constructor(privateKey) {
26
29
  this.sign = (bytes) => __awaiter(this, void 0, void 0, function* () {
@@ -96,4 +99,64 @@ describe("CallbackSigner", () => {
96
99
  const signer = CallbackSigner.newSigner(config, (data) => __awaiter(void 0, void 0, void 0, function* () { return data; }));
97
100
  expect(signer.timeAuthorityUrl()).toBeUndefined();
98
101
  }));
102
+ it("should create valid COSE signature with buffer output", () => __awaiter(void 0, void 0, void 0, function* () {
103
+ const testSigner = new TestSigner(yield fs.readFile("./tests/fixtures/certs/es256.pem"));
104
+ const createRawSignatureCallback = () => {
105
+ return (data) => __awaiter(void 0, void 0, void 0, function* () {
106
+ // For directCoseHandling: false, return raw signature data
107
+ // The c2pa SDK will handle COSE wrapping internally
108
+ return yield testSigner.sign(data);
109
+ });
110
+ };
111
+ // Create a simple manifest
112
+ const manifestDefinition = {
113
+ vendor: "test",
114
+ claim_generator: "test-generator",
115
+ claim_generator_info: [
116
+ {
117
+ name: "c2pa_test",
118
+ version: "1.0.0",
119
+ },
120
+ ],
121
+ title: "Test_Manifest_Buffer",
122
+ format: "image/jpeg",
123
+ instance_id: "5678",
124
+ assertions: [
125
+ {
126
+ label: "org.test.assertion",
127
+ data: { message: "Buffer test with directCoseHandling: false" },
128
+ },
129
+ ],
130
+ resources: { resources: {} },
131
+ };
132
+ const builder = Builder.withJson(manifestDefinition);
133
+ const source = {
134
+ buffer: yield fs.readFile("./tests/fixtures/CA.jpg"),
135
+ mimeType: "image/jpeg",
136
+ };
137
+ const config = {
138
+ alg: "es256",
139
+ certs: [fs.readFileSync("./tests/fixtures/certs/es256.pub")],
140
+ reserveSize: 10000,
141
+ tsaUrl: undefined,
142
+ directCoseHandling: false,
143
+ };
144
+ const callback = createRawSignatureCallback();
145
+ const signer = CallbackSigner.newSigner(config, callback);
146
+ // Sign the manifest to buffer
147
+ const dest = { buffer: null };
148
+ yield builder.signAsync(signer, source, dest);
149
+ // Read the signed manifest back and verify signature is valid
150
+ const reader = yield Reader.fromAsset({
151
+ buffer: dest.buffer,
152
+ mimeType: "image/jpeg",
153
+ });
154
+ expect(reader).not.toBeNull();
155
+ const manifestStore = reader.json();
156
+ const activeManifest = reader.getActive();
157
+ // If validation_status is undefined, the signature is valid
158
+ expect(manifestStore.validation_status[0].code).toBe("signingCredential.untrusted");
159
+ expect(manifestStore.active_manifest).not.toBeUndefined();
160
+ expect(activeManifest === null || activeManifest === void 0 ? void 0 : activeManifest.title).toBe("Test_Manifest_Buffer");
161
+ }));
99
162
  });
package/dist/index.node CHANGED
Binary file
@@ -1,15 +1,17 @@
1
- import type { Manifest } from "@contentauth/c2pa-types";
1
+ import type { BuilderIntent, Manifest } from "@contentauth/c2pa-types";
2
2
  import type { BuilderInterface, CallbackSignerInterface, ClaimVersion, DestinationAsset, IdentityAssertionSignerInterface, JsCallbackSignerConfig, LocalSignerInterface, ManifestAssertionKind, SourceAsset } from "./types.d.ts";
3
3
  export declare class Builder implements BuilderInterface {
4
4
  private builder;
5
5
  private constructor();
6
6
  static new(): Builder;
7
7
  static withJson(json: Manifest): Builder;
8
+ setIntent(intent: BuilderIntent): void;
8
9
  setNoEmbed(noEmbed?: boolean): void;
9
10
  setRemoteUrl(remoteUrl: string): void;
11
+ addAction(actionJson: string): void;
10
12
  addAssertion(label: string, assertion: unknown, assertionKind?: ManifestAssertionKind): void;
11
13
  addResource(uri: string, resource: SourceAsset): Promise<void>;
12
- addIngredient(ingredientJson: string, ingredient: SourceAsset): Promise<void>;
14
+ addIngredient(ingredientJson: string, ingredient?: SourceAsset): Promise<void>;
13
15
  toArchive(asset: DestinationAsset): Promise<void>;
14
16
  static fromArchive(asset: SourceAsset): Promise<Builder>;
15
17
  sign(signer: LocalSignerInterface, input: SourceAsset, output: DestinationAsset): Buffer;
@@ -7,9 +7,8 @@ export declare class Reader implements ReaderInterface {
7
7
  remoteUrl(): string;
8
8
  isEmbedded(): boolean;
9
9
  resourceToAsset(uri: string, asset: DestinationAsset): Promise<number>;
10
- static fromAsset(asset: SourceAsset): Promise<Reader>;
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
- postValidateCawg(): Promise<void>;
15
14
  }
@@ -61,3 +61,8 @@ export declare function patchVerifyConfig(patch: Partial<VerifyConfig>): void;
61
61
  * @returns The current verify configuration object
62
62
  */
63
63
  export declare function getVerifyConfig(): VerifyConfig;
64
+ /**
65
+ * Reset settings to their default values.
66
+ * This clears any custom settings and restores the default configuration.
67
+ */
68
+ export declare function resetSettings(): void;
@@ -20,4 +20,5 @@ export declare class CallbackSigner implements CallbackSignerInterface {
20
20
  certs(): Array<Buffer>;
21
21
  reserveSize(): number;
22
22
  timeAuthorityUrl(): string | undefined;
23
+ directCoseHandling(): boolean;
23
24
  }
@@ -13,7 +13,11 @@
13
13
 
14
14
  // This file contains types not included in @contentauth/c2pa-types and not directly applicable to the neon generated code (index.node.d.ts)
15
15
  import { Buffer } from "buffer";
16
- import type { Manifest, ManifestStore } from "@contentauth/c2pa-types";
16
+ import type {
17
+ BuilderIntent,
18
+ Manifest,
19
+ ManifestStore,
20
+ } from "@contentauth/c2pa-types";
17
21
  /**
18
22
  * Describes the digital signature algorithms allowed by the C2PA spec
19
23
  *
@@ -118,6 +122,7 @@ export interface CallbackSignerInterface {
118
122
  certs(): Array<Buffer>;
119
123
  reserveSize(): number;
120
124
  timeAuthorityUrl(): string | undefined;
125
+ directCoseHandling(): boolean;
121
126
  signer(): NeonCallbackSignerHandle;
122
127
  }
123
128
 
@@ -153,10 +158,8 @@ export interface JsCallbackSignerConfig {
153
158
  tsaUrl?: string;
154
159
  tsaHeaders?: Array<[string, string]>;
155
160
  tsaBody?: Buffer;
156
- // TODO: directCoseHandling is currently not implemented in the signing logic.
157
- // The field is read from config but the actual signing implementation does not
158
- // differentiate between directCoseHandling: true/false - both cases pass the
159
- // same data to the JavaScript callback regardless of this setting.
161
+ // When true, the callback function should return fully-formed COSE data.
162
+ // When false, the callback function should return raw signature data and the c2pa SDK will handle COSE wrapping.
160
163
  directCoseHandling: boolean;
161
164
  }
162
165
 
@@ -173,16 +176,37 @@ export interface HashedUri {
173
176
  }
174
177
 
175
178
  export interface BuilderInterface {
179
+ /** An intent lets the API know what kind of manifest to create.
180
+ * Intents are `Create`, `Edit`, or `Update`.
181
+ * This allows the API to check that you are doing the right thing.
182
+ * It can also do things for you, like add parent ingredients from the source asset
183
+ * and automatically add required c2pa.created or c2pa.opened actions.
184
+ * Create requires a `DigitalSourceType`. It is used for assets without a parent ingredient.
185
+ * Edit requires a parent ingredient and is used for most assets that are being edited.
186
+ * Update is a special case with many restrictions but is more compact than Edit.
187
+ * @param intent The intent of the manifest
188
+ */
189
+ setIntent(intent: BuilderIntent): void;
190
+
176
191
  /**
177
192
  * Set the no embed flag of the manifest
178
193
  * @param noEmbed The no embed flag of the manifest
179
194
  */
180
195
  setNoEmbed(noEmbed: boolean): void;
196
+
181
197
  /**
182
198
  * Set the remote URL of the manifest
183
199
  * @param url The remote URL of the manifest
184
200
  */
185
201
  setRemoteUrl(url: string): void;
202
+
203
+ /**
204
+ * Add a single action to the manifest.
205
+ * This is a convenience method for adding an action to the `Actions` assertion.
206
+ * @param actionJson The JSON representation of the action
207
+ */
208
+ addAction(actionJson: string): void;
209
+
186
210
  /**
187
211
  * Add CBOR assertion to the builder
188
212
  * @param label The label of the assertion
@@ -202,11 +226,14 @@ export interface BuilderInterface {
202
226
  addResource(uri: string, resource: SourceAsset): Promise<void>;
203
227
 
204
228
  /**
205
- * Add an ingredient from a buffer or file
229
+ * Add an ingredient to the manifest
206
230
  * @param ingredientJson The JSON representation of the ingredient
207
- * @param ingredient The source and format of the ingredient
231
+ * @param ingredient Optional source asset (buffer or file) for the ingredient
208
232
  */
209
- addIngredient(ingredientJson: string, ingredient: SourceAsset): Promise<void>;
233
+ addIngredient(
234
+ ingredientJson: string,
235
+ ingredient?: SourceAsset,
236
+ ): Promise<void>;
210
237
 
211
238
  /**
212
239
  * Convert the Builder into a archive formatted buffer or file
@@ -305,11 +332,6 @@ export interface ReaderInterface {
305
332
  * @param filePath The path to the file
306
333
  */
307
334
  resourceToAsset(uri: string, output: DestinationAsset): Promise<number>;
308
-
309
- /**
310
- * Run CAWG validation
311
- */
312
- postValidateCawg(): Promise<void>;
313
335
  }
314
336
 
315
337
  export interface IdentityAssertionSignerInterface {
@@ -404,8 +426,6 @@ export interface VerifyConfig {
404
426
  ocspFetch: boolean;
405
427
  /** Whether to fetch remote manifests */
406
428
  remoteManifestFetch: boolean;
407
- /** Whether to check ingredient trust */
408
- checkIngredientTrust: boolean;
409
429
  /** Whether to skip ingredient conflict resolution */
410
430
  skipIngredientConflictResolution: boolean;
411
431
  /** Whether to use strict v1 validation */
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.2.3",
7
+ "version": "0.4.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.2.1",
26
+ "@contentauth/c2pa-types": "^0.3.1",
27
27
  "@eslint/js": "^9.33.0",
28
28
  "@neon-rs/cli": "0.1.82",
29
29
  "@types/cli-progress": "^3.11.6",
@@ -68,7 +68,7 @@
68
68
  "scripts": {
69
69
  "build": "run-s build:rust build:ts",
70
70
  "build:debug": "run-s build:rust-debug build:ts",
71
- "build:docs": "rimraf docs && typedoc --plugin typedoc-plugin-markdown --readme none --out docs js-src/index.ts",
71
+ "build:docs": "rimraf docs-typedoc && typedoc --plugin typedoc-plugin-markdown --readme README.md --out docs-typedoc js-src/index.ts && cpy \"docs-typedoc/**\" docs --parents --overwrite --ignore=\"docs-typedoc/classes/index.md\" --ignore=\"docs-typedoc/README.md\" && rimraf docs-typedoc",
72
72
  "build:rust": "pnpm run build:rust-debug --release",
73
73
  "build:rust-debug": "cargo build --message-format=json-render-diagnostics > cargo.log",
74
74
  "build:ts": "tsc -b && cpy index.node dist && cpy index.node js-src && cpy --flat js-src/types.d.ts dist/types",
package/src/lib.rs CHANGED
@@ -32,11 +32,13 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> {
32
32
  // Builder
33
33
  cx.export_function("builderNew", neon_builder::NeonBuilder::new)?;
34
34
  cx.export_function("builderWithJson", neon_builder::NeonBuilder::with_json)?;
35
+ cx.export_function("builderSetIntent", neon_builder::NeonBuilder::set_intent)?;
35
36
  cx.export_function("builderSetNoEmbed", neon_builder::NeonBuilder::set_no_embed)?;
36
37
  cx.export_function(
37
- "builderSetRemote_url",
38
+ "builderSetRemoteUrl",
38
39
  neon_builder::NeonBuilder::set_remote_url,
39
40
  )?;
41
+ cx.export_function("builderAddAction", neon_builder::NeonBuilder::add_action)?;
40
42
  cx.export_function(
41
43
  "builderAddAssertion",
42
44
  neon_builder::NeonBuilder::add_assertion,
@@ -49,6 +51,10 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> {
49
51
  "builderAddIngredient",
50
52
  neon_builder::NeonBuilder::add_ingredient,
51
53
  )?;
54
+ cx.export_function(
55
+ "builderAddIngredientFromAsset",
56
+ neon_builder::NeonBuilder::add_ingredient_from_asset,
57
+ )?;
52
58
  cx.export_function("builderToArchive", neon_builder::NeonBuilder::to_archive)?;
53
59
  cx.export_function(
54
60
  "builderFromArchive",
@@ -91,10 +97,6 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> {
91
97
  "readerResourceToAsset",
92
98
  neon_reader::NeonReader::resource_to_asset,
93
99
  )?;
94
- cx.export_function(
95
- "readerPostValidateCawg",
96
- neon_reader::NeonReader::post_validate_cawg,
97
- )?;
98
100
 
99
101
  // Signers
100
102
  cx.export_function("localSignerNew", neon_signer::NeonLocalSigner::new)?;
@@ -131,6 +133,10 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> {
131
133
  "callbackSignerTimeAuthorityUrl",
132
134
  neon_signer::NeonCallbackSigner::time_authority_url,
133
135
  )?;
136
+ cx.export_function(
137
+ "callbackSignerDirectCoseHandling",
138
+ neon_signer::NeonCallbackSigner::direct_cose_handling,
139
+ )?;
134
140
 
135
141
  // Identity Assertions
136
142
  cx.export_function(
@@ -181,5 +187,8 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> {
181
187
  cx.export_function("loadVerifyConfig", settings::load_verify_config)?;
182
188
  cx.export_function("getVerifyConfig", settings::get_verify_config)?;
183
189
 
190
+ // Reset Settings
191
+ cx.export_function("resetSettings", settings::reset_settings)?;
192
+
184
193
  Ok(())
185
194
  }
@@ -16,7 +16,7 @@ use crate::error::{as_js_error, Error};
16
16
  use crate::neon_identity_assertion_signer::NeonIdentityAssertionSigner;
17
17
  use crate::neon_signer::{CallbackSignerConfig, NeonCallbackSigner, NeonLocalSigner};
18
18
  use crate::runtime::runtime;
19
- use c2pa::Builder;
19
+ use c2pa::{Builder, BuilderIntent, Ingredient};
20
20
  use neon::prelude::*;
21
21
  use neon_serde4;
22
22
  use serde::{Deserialize, Serialize};
@@ -59,6 +59,17 @@ impl NeonBuilder {
59
59
  }))
60
60
  }
61
61
 
62
+ pub fn set_intent(mut cx: FunctionContext) -> JsResult<JsUndefined> {
63
+ let rt = runtime();
64
+ let this = cx.this::<JsBox<Self>>()?;
65
+ let intent_str = cx.argument::<JsString>(0)?.value(&mut cx);
66
+ let intent: BuilderIntent = serde_json::from_str(&intent_str)
67
+ .or_else(|_| cx.throw_error(format!("Invalid intent: {}", intent_str)))?;
68
+ let mut builder = rt.block_on(async { this.builder.lock().await });
69
+ builder.set_intent(intent);
70
+ Ok(cx.undefined())
71
+ }
72
+
62
73
  pub fn set_no_embed(mut cx: FunctionContext) -> JsResult<JsUndefined> {
63
74
  let rt = runtime();
64
75
  let this = cx.this::<JsBox<Self>>()?;
@@ -77,6 +88,19 @@ impl NeonBuilder {
77
88
  Ok(cx.undefined())
78
89
  }
79
90
 
91
+ pub fn add_action(mut cx: FunctionContext) -> JsResult<JsUndefined> {
92
+ let rt = runtime();
93
+ let this = cx.this::<JsBox<Self>>()?;
94
+ 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()))?;
97
+ let mut builder = rt.block_on(async { this.builder.lock().await });
98
+ builder
99
+ .add_action(action)
100
+ .or_else(|err| cx.throw_error(err.to_string()))?;
101
+ Ok(cx.undefined())
102
+ }
103
+
80
104
  pub fn add_assertion(mut cx: FunctionContext) -> JsResult<JsUndefined> {
81
105
  let rt = runtime();
82
106
  let this = cx.this::<JsBox<Self>>()?;
@@ -112,7 +136,6 @@ impl NeonBuilder {
112
136
  }
113
137
 
114
138
  pub fn add_resource(mut cx: FunctionContext) -> JsResult<JsPromise> {
115
- let rt = runtime();
116
139
  let this = cx.this::<JsBox<Self>>()?;
117
140
  let uri = cx.argument::<JsString>(0)?.value(&mut cx);
118
141
  let resource = cx
@@ -120,27 +143,37 @@ impl NeonBuilder {
120
143
  .and_then(|obj| parse_asset(&mut cx, obj))?;
121
144
  let builder = Arc::clone(&this.builder);
122
145
 
123
- let channel = cx.channel();
124
- let (deferred, promise) = cx.promise();
125
-
126
- rt.spawn(async move {
127
- let mut builder = builder.lock().await;
128
-
129
- let result = resource.into_read_stream().and_then(|mut resource_stream| {
130
- builder.add_resource(&uri, &mut resource_stream)?;
131
- Ok(())
132
- });
146
+ let promise = cx
147
+ .task(move || {
148
+ // Block on acquiring the async mutex lock
149
+ let rt = runtime();
150
+ let mut builder = rt.block_on(async { builder.lock().await });
133
151
 
134
- deferred.settle_with(&channel, |mut cx| match result {
152
+ resource.into_read_stream().and_then(|mut resource_stream| {
153
+ builder.add_resource(&uri, &mut resource_stream)?;
154
+ Ok(())
155
+ })
156
+ })
157
+ .promise(move |mut cx, result: Result<(), Error>| match result {
135
158
  Ok(_) => Ok(cx.undefined()),
136
159
  Err(err) => as_js_error(&mut cx, err).and_then(|err| cx.throw(err)),
137
160
  });
138
- });
139
161
 
140
162
  Ok(promise)
141
163
  }
164
+ pub fn add_ingredient(mut cx: FunctionContext) -> JsResult<JsUndefined> {
165
+ let rt = runtime();
166
+ let this = cx.this::<JsBox<Self>>()?;
167
+ let ingredient_json = cx.argument::<JsString>(0)?.value(&mut cx);
168
+ let ingredient = Ingredient::from_json(&ingredient_json)
169
+ .or_else(|err| cx.throw_error(err.to_string()))?;
170
+
171
+ let mut builder = rt.block_on(async { this.builder.lock().await });
172
+ builder.add_ingredient(ingredient);
173
+ Ok(cx.undefined())
174
+ }
142
175
 
143
- pub fn add_ingredient(mut cx: FunctionContext) -> JsResult<JsPromise> {
176
+ pub fn add_ingredient_from_asset(mut cx: FunctionContext) -> JsResult<JsPromise> {
144
177
  let rt = runtime();
145
178
  let this = cx.this::<JsBox<Self>>()?;
146
179
  let ingredient_json = cx.argument::<JsString>(0)?.value(&mut cx);
@@ -156,18 +189,24 @@ impl NeonBuilder {
156
189
  rt.spawn(async move {
157
190
  let mut builder = builder.lock().await;
158
191
 
159
- let result = ingredient
160
- .mime_type()
161
- .ok_or_else(|| Error::Signing("Ingredient asset must have a mime type".to_string()))
162
- .and_then(|format| {
163
- let mut ingredient_stream = ingredient.into_read_stream()?;
164
- builder.add_ingredient_from_stream(
192
+ let result = async {
193
+ let format = ingredient
194
+ .mime_type()
195
+ .ok_or_else(|| {
196
+ Error::Signing("Ingredient asset must have a mime type".to_string())
197
+ })?
198
+ .to_owned();
199
+ let mut ingredient_stream = ingredient.into_read_stream()?;
200
+ builder
201
+ .add_ingredient_from_stream_async(
165
202
  &ingredient_json,
166
203
  &format,
167
204
  &mut ingredient_stream,
168
- )?;
169
- Ok(())
170
- });
205
+ )
206
+ .await?;
207
+ Ok(())
208
+ }
209
+ .await;
171
210
 
172
211
  deferred.settle_with(&channel, move |mut cx| match result {
173
212
  Ok(_) => Ok(cx.undefined()),
@@ -179,53 +218,47 @@ impl NeonBuilder {
179
218
  }
180
219
 
181
220
  pub fn to_archive(mut cx: FunctionContext) -> JsResult<JsPromise> {
182
- let rt = runtime();
183
221
  let this = cx.this::<JsBox<Self>>()?;
184
222
  let dest = cx
185
223
  .argument::<JsObject>(0)
186
224
  .and_then(|obj| parse_asset(&mut cx, obj))?;
187
225
  let builder = Arc::clone(&this.builder);
188
226
 
189
- let channel = cx.channel();
190
- let (deferred, promise) = cx.promise();
191
-
192
- rt.spawn(async move {
193
- let mut builder = builder.lock().await;
194
- let result = dest.write_stream().and_then(|dest_stream| {
195
- builder.to_archive(dest_stream)?;
196
- Ok(())
197
- });
227
+ let promise = cx
228
+ .task(move || {
229
+ // Block on acquiring the async mutex lock
230
+ let rt = runtime();
231
+ let mut builder = rt.block_on(async { builder.lock().await });
198
232
 
199
- deferred.settle_with(&channel, move |mut cx| match result {
233
+ dest.write_stream().and_then(|dest_stream| {
234
+ builder.to_archive(dest_stream)?;
235
+ Ok(())
236
+ })
237
+ })
238
+ .promise(move |mut cx, result: Result<(), Error>| match result {
200
239
  Ok(_) => Ok(cx.undefined()),
201
240
  Err(err) => as_js_error(&mut cx, err).and_then(|err| cx.throw(err)),
202
241
  });
203
- });
204
242
  Ok(promise)
205
243
  }
206
244
 
207
245
  pub fn from_archive(mut cx: FunctionContext) -> JsResult<JsPromise> {
208
- let rt = runtime();
209
246
  let source = cx
210
247
  .argument::<JsObject>(0)
211
248
  .and_then(|obj| parse_asset(&mut cx, obj))?;
212
249
 
213
- let channel = cx.channel();
214
- let (deferred, promise) = cx.promise();
215
-
216
- rt.spawn(async move {
217
- let result = source.into_read_stream().and_then(|source_stream| {
250
+ let promise = cx
251
+ .task(move || {
252
+ let source_stream = source.into_read_stream()?;
218
253
  let builder = Builder::from_archive(source_stream)?;
219
254
  Ok(builder)
220
- });
221
-
222
- deferred.settle_with(&channel, move |mut cx| match result {
255
+ })
256
+ .promise(move |mut cx, result: Result<Builder, Error>| match result {
223
257
  Ok(builder) => Ok(cx.boxed(Self {
224
258
  builder: Arc::new(Mutex::new(builder)),
225
259
  })),
226
260
  Err(err) => as_js_error(&mut cx, err).and_then(|err| cx.throw(err)),
227
261
  });
228
- });
229
262
  Ok(promise)
230
263
  }
231
264