@contentauth/c2pa-node 0.9.5 → 0.9.7

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.toml CHANGED
@@ -11,7 +11,7 @@ crate-type = ["cdylib"]
11
11
 
12
12
  [dependencies]
13
13
  async-trait = "0.1.77"
14
- ciborium = "0.2.2"
14
+ c2pa_cbor = "0.78.0"
15
15
  c2pa = { workspace = true, features = ["file_io", "add_thumbnails"] }
16
16
  futures = "0.3"
17
17
  image = "0.25.6"
package/README.md CHANGED
@@ -61,19 +61,20 @@ This generates HTML documentation in the `docs/` directory at the repo root. It
61
61
  The `Reader` class is used to read and validate C2PA manifests from media files. It can parse embedded manifests or fetch remote manifests. Refer to the [Rust SDK](https://github.com/contentauth/c2pa-rs) for the list of settings and their effects.
62
62
 
63
63
  ```javascript
64
- import { Reader } from '@contentauth/c2pa-node';
64
+ import { Reader, Context } from '@contentauth/c2pa-node';
65
65
 
66
66
  // Read from an asset file
67
67
  const reader = await Reader.fromAsset(inputAsset);
68
68
 
69
- // Read with custom settings
70
- const settings = {
69
+ // Read with a Context — the recommended way to configure settings
70
+ // (see "Using a Context" under "Settings and configuration" below)
71
+ const context = new Context({
71
72
  verify: {
72
- verify_after_reading: false,
73
- verify_trust: true
73
+ verifyAfterReading: false,
74
+ verifyTrust: true
74
75
  }
75
- };
76
- const reader = await Reader.fromAsset(inputAsset, settings);
76
+ });
77
+ const reader = await Reader.fromAsset(inputAsset, context);
77
78
 
78
79
  // Read from manifest data and asset
79
80
  const reader = await Reader.fromManifestDataAndAsset(manifestData, asset);
@@ -91,6 +92,9 @@ const isEmbedded = reader.isEmbedded();
91
92
  const remoteUrl = reader.remoteUrl();
92
93
  ```
93
94
 
95
+ > [!NOTE]
96
+ > `Reader.fromAsset`/`Reader.fromManifestDataAndAsset` also accept a raw settings object in place of a `Context` (e.g. `Reader.fromAsset(inputAsset, { verify: { verify_trust: true } })`), but this is deprecated — see [Per-instance settings (deprecated)](#per-instance-settings-deprecated).
97
+
94
98
  `Reader.fromAsset` and `Reader.fromManifestDataAndAsset` reject assets larger than 10 GB, throwing `AssetTooLargeError` (exported from `@contentauth/c2pa-node`). Note that for a `SourceBufferAsset`, this only rejects after the buffer is already fully allocated in memory. Pass a `FileAsset` instead for large or untrusted assets so oversized files are rejected before being read into memory.
95
99
 
96
100
  ### Builder
@@ -98,24 +102,25 @@ const remoteUrl = reader.remoteUrl();
98
102
  The `Builder` class is the main component for creating and signing C2PA manifests. It provides methods to add assertions, resources, and ingredients to manifests, and handles the signing process. Use the `Signer` class to sign the manifests. Refer to the [Rust SDK](https://github.com/contentauth/c2pa-rs) for the list of settings and their effects.
99
103
 
100
104
  ```javascript
101
- import { Builder } from '@contentauth/c2pa-node';
105
+ import { Builder, Context } from '@contentauth/c2pa-node';
102
106
 
103
107
  // Create a new builder
104
- const builder = Builder.new();
108
+ const builder = await Builder.newAsync();
105
109
 
106
- // Create with custom settings
107
- const settings = {
110
+ // Create with a Context — the recommended way to configure settings
111
+ // (see "Using a Context" under "Settings and configuration" below)
112
+ const context = new Context({
108
113
  builder: {
109
- generate_c2pa_archive: true
114
+ generateC2paArchive: true
110
115
  }
111
- };
112
- const builder = Builder.new(settings);
116
+ });
117
+ const builder = await Builder.newAsync(context);
113
118
 
114
119
  // Or create from an existing manifest definition
115
- const builder = Builder.withJson(manifestDefinition);
120
+ const builder = await Builder.withJsonAsync(manifestDefinition);
116
121
 
117
- // Or create with both manifest and settings
118
- const builder = Builder.withJson(manifestDefinition, settings);
122
+ // Or create with both a manifest definition and a Context
123
+ const builder = await Builder.withJsonAsync(manifestDefinition, context);
119
124
 
120
125
  // Add assertions to the manifest
121
126
  builder.addAssertion('c2pa.actions', actionsAssertion);
@@ -127,6 +132,9 @@ await builder.addResource('resource://example', resourceAsset);
127
132
  const manifest = builder.sign(signer, inputAsset, outputAsset);
128
133
  ```
129
134
 
135
+ > [!NOTE]
136
+ > `Builder.new`/`Builder.withJson` (synchronous, taking a raw settings object in place of a `Context`) still work but are deprecated — see [Per-instance settings (deprecated)](#per-instance-settings-deprecated).
137
+
130
138
  #### Setting builder intent
131
139
 
132
140
  The builder intent describes the type of operation being performed on the asset. This influences how the manifest is structured and what assertions are automatically added. Use one of these intents:
@@ -136,7 +144,7 @@ The builder intent describes the type of operation being performed on the asset.
136
144
  - `update`: A restricted version of `edit` for non-editorial changes. There must be only one ingredient, as a parent. No changes can be made to the hashed content of the parent. There are additional restrictions on the types of changes that can be made.
137
145
 
138
146
  ```javascript
139
- const builder = Builder.new();
147
+ const builder = await Builder.newAsync();
140
148
 
141
149
  builder.setIntent({
142
150
  create: 'http://cv.iptc.org/newscodes/digitalsourcetype/trainedAlgorithmicMedia',
@@ -168,7 +176,7 @@ import * as fs from "node:fs/promises";
168
176
  const ingredientBuffer = await fs.readFile('path/to/source-image.jpg');
169
177
 
170
178
  // Create a builder
171
- const builder = Builder.new();
179
+ const builder = await Builder.newAsync();
172
180
 
173
181
  // Add the ingredient with its asset
174
182
  await builder.addIngredient(
@@ -193,7 +201,7 @@ console.log(definition.ingredients); // Contains the ingredient with embedded da
193
201
  You can add multiple ingredients to document complex provenance chains:
194
202
 
195
203
  ```javascript
196
- const builder = Builder.new();
204
+ const builder = await Builder.newAsync();
197
205
 
198
206
  // Load ingredient assets
199
207
  const background = await fs.promises.readFile('background.jpg');
@@ -242,7 +250,7 @@ const sourceReader = await Reader.fromAsset({
242
250
  });
243
251
 
244
252
  // Create a builder
245
- const builder = Builder.new();
253
+ const builder = await Builder.newAsync();
246
254
 
247
255
  // Add ingredient from reader
248
256
  const ingredient = builder.addIngredientFromReader(sourceReader);
@@ -262,14 +270,14 @@ There are two types of archives sharing the same binary format:
262
270
  ##### Reading an archive and adding its ingredients
263
271
 
264
272
  ```javascript
265
- import { Reader, Builder } from '@contentauth/c2pa-node';
273
+ import { Reader, Builder, Context } from '@contentauth/c2pa-node';
266
274
  import * as fs from 'node:fs/promises';
267
275
 
268
276
  // Read the archive using the application/c2pa MIME type
269
277
  const archiveBuffer = await fs.readFile('ingredients.c2pa');
270
278
  const reader = await Reader.fromAsset(
271
279
  { buffer: archiveBuffer, mimeType: 'application/c2pa' },
272
- { verify: { verify_after_reading: false } }
280
+ new Context({ verify: { verifyAfterReading: false } })
273
281
  );
274
282
 
275
283
  // Get the ingredients from the active manifest
@@ -277,7 +285,7 @@ const activeManifest = reader.getActive();
277
285
  const ingredients = activeManifest.ingredients;
278
286
 
279
287
  // Create a new builder with the ingredients from the archive
280
- const builder = Builder.withJson({
288
+ const builder = await Builder.withJsonAsync({
281
289
  claim_generator_info: [{ name: 'my-app', version: '1.0.0' }],
282
290
  ingredients: ingredients,
283
291
  });
@@ -312,7 +320,7 @@ When an archive contains multiple ingredients, you can filter to include only th
312
320
  ```javascript
313
321
  const reader = await Reader.fromAsset(
314
322
  { buffer: archiveBuffer, mimeType: 'application/c2pa' },
315
- { verify: { verify_after_reading: false } }
323
+ new Context({ verify: { verifyAfterReading: false } })
316
324
  );
317
325
 
318
326
  const activeManifest = reader.getActive();
@@ -324,7 +332,7 @@ const selected = allIngredients.filter(
324
332
  );
325
333
 
326
334
  // Build with only the selected ingredients
327
- const builder = Builder.withJson({
335
+ const builder = await Builder.withJsonAsync({
328
336
  claim_generator_info: [{ name: 'my-app', version: '1.0.0' }],
329
337
  ingredients: selected,
330
338
  });
@@ -353,7 +361,7 @@ for (const ingredient of selected) {
353
361
  To create an ingredient archive, add ingredients to a `Builder` and save it as an archive:
354
362
 
355
363
  ```javascript
356
- const builder = Builder.new();
364
+ const builder = await Builder.newAsync();
357
365
 
358
366
  // Add ingredients with stable instance_id for later catalog lookups
359
367
  await builder.addIngredient(
@@ -375,7 +383,7 @@ Builder archives allow you to save a builder's state (including ingredients) and
375
383
 
376
384
  ```javascript
377
385
  // Create a builder with ingredients
378
- const builder = Builder.new();
386
+ const builder = await Builder.newAsync();
379
387
 
380
388
  const ingredientBuffer = await fs.promises.readFile('source.jpg');
381
389
  await builder.addIngredient(
@@ -521,11 +529,43 @@ const decodedData = await trustmark.decode(imageBuffer);
521
529
 
522
530
  ### Settings and configuration
523
531
 
524
- The library provides comprehensive settings management that can be configured per Reader/Builder instance or using helper functions. Refer to the [Rust SDK](https://github.com/contentauth/c2pa-rs) for the list of settings and their effects.
532
+ The library provides comprehensive settings management that can be configured per Reader/Builder instance, via a `Context`, or using helper functions. Refer to the [Rust SDK](https://github.com/contentauth/c2pa-rs) for the list of settings and their effects.
533
+
534
+ #### Using a Context
525
535
 
526
- #### Per-instance settings
536
+ A `Context` (from [`c2pa-utilities`](../c2pa-utilities/README.md#context-and-settings), re-exported directly from `@contentauth/c2pa-node` so you don't need to add that package yourself) wraps `Settings` and is the recommended way to configure a `Reader` or `Builder`:
527
537
 
528
- Settings can be passed directly to `Reader` and `Builder` constructors:
538
+ ```javascript
539
+ import { Reader, Builder, Context } from '@contentauth/c2pa-node';
540
+
541
+ const context = new Context({
542
+ verify: {
543
+ verifyAfterReading: false,
544
+ verifyAfterSign: false,
545
+ verifyTrust: true,
546
+ ocspFetch: true
547
+ },
548
+ trust: {
549
+ verifyTrustList: true,
550
+ trustAnchors: "path/to/anchors.pem"
551
+ }
552
+ });
553
+
554
+ // Pass a Context to Reader
555
+ const reader = await Reader.fromAsset(inputAsset, context);
556
+
557
+ // Builder has async, Context-aware counterparts to its synchronous factories below
558
+ const builder = await Builder.newAsync(context);
559
+ const builder2 = await Builder.withJsonAsync(manifestDefinition, context);
560
+ const builder3 = await Builder.fromArchive(archiveAsset, context);
561
+ ```
562
+
563
+ > [!NOTE]
564
+ > Unlike `c2pa-web`, `c2pa-node` doesn't fetch trust-anchor URLs embedded in a `Context`'s settings yet — a trust anchor value must be inline PEM content or a local file path, not a URL, until that support lands here too.
565
+
566
+ #### Per-instance settings (deprecated)
567
+
568
+ Passing settings directly as a JSON string, or as a raw object matching the native settings shape (snake_case keys, no defaults applied), is deprecated and will be removed in a future major version — use a `Context` instead (above). `Builder.new`/`Builder.withJson` stay synchronous for this deprecated path; prefer their `newAsync`/`withJsonAsync` counterparts with a `Context` instead.
529
569
 
530
570
  ```javascript
531
571
  import { Reader, Builder } from '@contentauth/c2pa-node';
@@ -599,14 +639,18 @@ const verifySettings = createVerifySettings({
599
639
  // Merge multiple settings
600
640
  const combinedSettings = mergeSettings(trustSettings, verifySettings);
601
641
 
602
- // Convert settings to JSON string
642
+ // combinedSettings is a plain Settings object — use it with a Context (recommended)...
643
+ const readerWithContext = await Reader.fromAsset(inputAsset, new Context(combinedSettings));
644
+
645
+ // ...or convert it to a JSON string for the deprecated per-instance settings path
603
646
  const jsonString = settingsToJson(combinedSettings);
647
+ const readerWithJson = await Reader.fromAsset(inputAsset, jsonString);
604
648
 
605
- // Load settings from file (JSON or TOML)
606
- const fileSettings = await loadSettingsFromFile('./c2pa-settings.toml');
607
- const reader = await Reader.fromAsset(inputAsset, fileSettings);
649
+ // loadSettingsFromFile/loadSettingsFromUrl return a raw JSON string, not a Settings
650
+ // object, so they pair with the deprecated per-instance settings path, not Context, for now.
651
+ const fileSettings = await loadSettingsFromFile('./c2pa-settings.json');
652
+ const reader2 = await Reader.fromAsset(inputAsset, fileSettings);
608
653
 
609
- // Load settings from URL
610
654
  const urlSettings = await loadSettingsFromUrl('https://example.com/c2pa-settings.json');
611
655
  const builder = Builder.new(urlSettings);
612
656
  ```
package/dist/Builder.js CHANGED
@@ -3,39 +3,77 @@
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 { Context } from "@contentauth/c2pa-utilities";
6
7
  import { getNeonBinary } from "./binary.js";
8
+ import { resolveSettingsForNeon } from "./Settings.js";
7
9
  import { IdentityAssertionSigner } from "./IdentityAssertion.js";
10
+ function stringifyManifestDefinition(json) {
11
+ try {
12
+ return JSON.stringify(json);
13
+ }
14
+ catch (error) {
15
+ // TODO: errors should be standardized across JS and Node
16
+ if (error instanceof Error) {
17
+ throw new Error(`Failed to stringify JSON Manifest Definition: ${error.message}`);
18
+ }
19
+ throw new Error("Failed to stringify JSON Manifest Definition: Unknown error");
20
+ }
21
+ }
8
22
  export class Builder {
9
23
  builder;
10
24
  constructor(builder) {
11
25
  this.builder = builder;
12
26
  }
27
+ /**
28
+ * @deprecated Use {@link Builder.newAsync} instead, passing a `Context`. Will be removed in a
29
+ * future major version.
30
+ * @param settings A raw `C2paSettings` string/object.
31
+ */
13
32
  static new(settings) {
14
- const settingsStr = settings
15
- ? typeof settings === "string"
16
- ? settings
17
- : JSON.stringify(settings)
18
- : undefined;
33
+ const settingsStr = resolveSettingsForNeon(settings);
34
+ const builder = getNeonBinary().builderNew(settingsStr);
35
+ return new Builder(builder);
36
+ }
37
+ /**
38
+ * Create a Builder with a minimal manifest definition, configured by a `Context`.
39
+ * Prefer this over the deprecated {@link Builder.new}.
40
+ *
41
+ * Declared async for forward compatibility. Upcoming work will allow for trust anchor
42
+ * resolution at construction time.
43
+ *
44
+ * @param context A `Context` object containing configuration settings for this Builder.
45
+ * Defaults to an empty `Context` using default settings if one is not provided.
46
+ */
47
+ static async newAsync(context = new Context()) {
48
+ const settingsStr = resolveSettingsForNeon(context);
19
49
  const builder = getNeonBinary().builderNew(settingsStr);
20
50
  return new Builder(builder);
21
51
  }
52
+ /**
53
+ * @deprecated Use {@link Builder.withJsonAsync} instead, passing a `Context`. Will be removed
54
+ * in a future version.
55
+ * @param settings A raw `C2paSettings` string/object.
56
+ */
22
57
  static withJson(json, settings) {
23
- let jsonString;
24
- try {
25
- jsonString = JSON.stringify(json);
26
- }
27
- catch (error) {
28
- // TODO: errors should be standardized across JS and Node
29
- if (error instanceof Error) {
30
- throw new Error(`Failed to stringify JSON Manifest Definition: ${error.message}`);
31
- }
32
- throw new Error("Failed to stringify JSON Manifest Definition: Unknown error");
33
- }
34
- const settingsStr = settings
35
- ? typeof settings === "string"
36
- ? settings
37
- : JSON.stringify(settings)
38
- : undefined;
58
+ const jsonString = stringifyManifestDefinition(json);
59
+ const settingsStr = resolveSettingsForNeon(settings);
60
+ const builder = getNeonBinary().builderWithJson(jsonString, settingsStr);
61
+ return new Builder(builder);
62
+ }
63
+ /**
64
+ * Create a Builder from a manifest definition, configured by a `Context`. Prefer this over
65
+ * the deprecated {@link Builder.withJson}.
66
+ *
67
+ * Declared async for forward compatibility. Upcoming work will allow c2pa-node
68
+ * to resolve trust anchors at construction time.
69
+ *
70
+ * @param json The manifest JSON.
71
+ * @param context A `Context` object containing configuration settings for this Builder.
72
+ * Defaults to an empty `Context` using default settings if one is not provided.
73
+ */
74
+ static async withJsonAsync(json, context = new Context()) {
75
+ const jsonString = stringifyManifestDefinition(json);
76
+ const settingsStr = resolveSettingsForNeon(context);
39
77
  const builder = getNeonBinary().builderWithJson(jsonString, settingsStr);
40
78
  return new Builder(builder);
41
79
  }
@@ -74,12 +112,13 @@ export class Builder {
74
112
  async toArchive(asset) {
75
113
  return getNeonBinary().builderToArchive.call(this.builder, asset);
76
114
  }
77
- static async fromArchive(asset, settings) {
78
- const settingsStr = settings
79
- ? typeof settings === "string"
80
- ? settings
81
- : JSON.stringify(settings)
82
- : undefined;
115
+ /**
116
+ * @param settingsOrContext A `Context`, or (deprecated) a raw `C2paSettings` string/object. Passing a
117
+ * raw `C2paSettings` value is deprecated and will be removed in a future version. `null` is treated
118
+ * the same as `undefined`.
119
+ */
120
+ static async fromArchive(asset, settingsOrContext) {
121
+ const settingsStr = resolveSettingsForNeon(settingsOrContext);
83
122
  return new Builder(await getNeonBinary().builderFromArchive(asset, settingsStr));
84
123
  }
85
124
  sign(signer, input, output) {
@@ -3,6 +3,7 @@
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 { Context } from "@contentauth/c2pa-utilities";
6
7
  import fs from "fs-extra";
7
8
  import path from "path";
8
9
  import * as crypto from "crypto";
@@ -811,6 +812,63 @@ describe("Builder", () => {
811
812
  expect(activeManifest?.ingredients?.length).toBe(1);
812
813
  }, 30000);
813
814
  });
815
+ describe("Context", () => {
816
+ it("newAsync() with no context behaves like new()", async () => {
817
+ const builder = await Builder.newAsync();
818
+ const definition = builder.getManifestDefinition();
819
+ expect(definition).toEqual(Builder.new().getManifestDefinition());
820
+ });
821
+ it("newAsync(context) applies the Context's settings", async () => {
822
+ const dest = { path: path.join(tempDir, "context_new_signed.jpg") };
823
+ const signer = LocalSigner.newSigner(publicKey, privateKey, "es256");
824
+ // Trust verification disabled via Context.
825
+ const context = new Context({ verify: { verifyTrust: false } });
826
+ const builder = await Builder.newAsync(context);
827
+ builder.updateManifestProperty("claim_version", 2);
828
+ await builder.addIngredient(parent_json, source);
829
+ builder.sign(signer, source, dest);
830
+ const reader = await Reader.fromAsset(dest, context);
831
+ const manifestStore = reader.json();
832
+ expect(manifestStore.validation_status ?? []).not.toContainEqual(expect.objectContaining({ code: "signingCredential.untrusted" }));
833
+ });
834
+ it("withJsonAsync(json, context) applies the Context's settings", async () => {
835
+ const dest = { path: path.join(tempDir, "context_withjson_signed.jpg") };
836
+ const signer = LocalSigner.newSigner(publicKey, privateKey, "es256");
837
+ // Trust verification disabled via Context.
838
+ const context = new Context({ verify: { verifyTrust: false } });
839
+ const builder = await Builder.withJsonAsync(manifestDefinition, context);
840
+ await builder.addIngredient(parent_json, source);
841
+ await builder.addResource("thumbnail.jpg", {
842
+ mimeType: "jpeg",
843
+ buffer: testThumbnail,
844
+ });
845
+ await builder.addResource("ingredient-thumb.jpg", {
846
+ mimeType: "jpeg",
847
+ buffer: testThumbnail,
848
+ });
849
+ builder.sign(signer, source, dest);
850
+ const reader = await Reader.fromAsset(dest, context);
851
+ const manifestStore = reader.json();
852
+ expect(manifestStore.validation_status ?? []).not.toContainEqual(expect.objectContaining({ code: "signingCredential.untrusted" }));
853
+ });
854
+ it("fromArchive(asset, context) accepts a Context in place of the deprecated raw settings", async () => {
855
+ const builder = Builder.withJson(manifestDefinition);
856
+ await builder.addIngredient(parent_json, source);
857
+ await builder.addResource("thumbnail.jpg", {
858
+ mimeType: "jpeg",
859
+ buffer: testThumbnail,
860
+ });
861
+ await builder.addResource("ingredient-thumb.jpg", {
862
+ mimeType: "jpeg",
863
+ buffer: testThumbnail,
864
+ });
865
+ const archive = { buffer: null };
866
+ await builder.toArchive(archive);
867
+ const context = new Context({ verify: { verifyTrust: false } });
868
+ const restoredBuilder = await Builder.fromArchive({ buffer: archive.buffer, mimeType: "application/c2pa" }, context);
869
+ expect(restoredBuilder.getManifestDefinition().title).toBe(manifestDefinition.title);
870
+ });
871
+ });
814
872
  describe("Filter actions and ingredients", () => {
815
873
  // A manifest carrying an inception action plus two removable actions.
816
874
  const actionsManifest = () => ({
package/dist/Reader.js CHANGED
@@ -5,6 +5,7 @@
5
5
  // at your option.
6
6
  import { getNeonBinary } from "./binary.js";
7
7
  import { validateSourceAssetSize } from "./assetSize.js";
8
+ import { resolveSettingsForNeon } from "./Settings.js";
8
9
  export class Reader {
9
10
  reader;
10
11
  constructor(reader) {
@@ -22,15 +23,25 @@ export class Reader {
22
23
  async resourceToAsset(uri, asset) {
23
24
  return getNeonBinary().readerResourceToAsset.call(this.reader, uri, asset);
24
25
  }
25
- static async fromAsset(asset, settings) {
26
+ /**
27
+ * @param settingsOrContext A `Context`, or (@deprecated) a raw `C2paSettings` string/object. Passing a
28
+ * raw `C2paSettings` value is deprecated and will be removed in a future version. `null` is treated
29
+ * the same as `undefined`.
30
+ */
31
+ static async fromAsset(asset, settingsOrContext) {
26
32
  await validateSourceAssetSize(asset);
27
- const settingsStr = settings ? (typeof settings === 'string' ? settings : JSON.stringify(settings)) : undefined;
33
+ const settingsStr = resolveSettingsForNeon(settingsOrContext);
28
34
  const reader = await getNeonBinary().readerFromAsset(asset, settingsStr);
29
35
  return reader ? new Reader(reader) : null;
30
36
  }
31
- static async fromManifestDataAndAsset(manifestData, asset, settings) {
37
+ /**
38
+ * @param settingsOrContext A `Context`, or (@deprecated) a raw `C2paSettings` string/object. Passing a
39
+ * raw `C2paSettings` value is deprecated and will be removed in a future version. `null` is treated
40
+ * the same as `undefined`.
41
+ */
42
+ static async fromManifestDataAndAsset(manifestData, asset, settingsOrContext) {
32
43
  await validateSourceAssetSize(asset);
33
- const settingsStr = settings ? (typeof settings === 'string' ? settings : JSON.stringify(settings)) : undefined;
44
+ const settingsStr = resolveSettingsForNeon(settingsOrContext);
34
45
  const reader = await getNeonBinary().readerFromManifestDataAndAsset(manifestData, asset, settingsStr);
35
46
  return new Reader(reader);
36
47
  }
@@ -5,7 +5,7 @@
5
5
  // at your option.
6
6
  import path from "path";
7
7
  import fs from "fs-extra";
8
- import { AssetTooLargeError } from "@contentauth/c2pa-utilities";
8
+ import { AssetTooLargeError, Context } from "@contentauth/c2pa-utilities";
9
9
  import { Reader } from "./Reader.js";
10
10
  import { MAX_SIZE_IN_BYTES } from "./assetSize.js";
11
11
  const tempDir = path.join(__dirname, "tmp");
@@ -175,6 +175,27 @@ describe("Reader", () => {
175
175
  expect(json.manifests).toBeDefined();
176
176
  expect(json.active_manifest).toEqual(manifestStore.active_manifest);
177
177
  });
178
+ it("should read from manifest data and file with a Context", async () => {
179
+ const manifestData = await fs.readFile("./tests/fixtures/CA/manifest_data.c2pa");
180
+ const buffer = await fs.readFile("./tests/fixtures/CA.jpg");
181
+ const context = new Context({
182
+ verify: {
183
+ verifyAfterReading: false,
184
+ verifyTrust: false,
185
+ },
186
+ });
187
+ const reader = await Reader.fromManifestDataAndAsset(manifestData, {
188
+ buffer,
189
+ mimeType: "jpeg",
190
+ }, context);
191
+ expect(reader).not.toBeNull();
192
+ const json = reader.json();
193
+ // Same effect as the raw-settings equivalent above: verifyAfterReading: false means
194
+ // validation_status should be undefined.
195
+ expect(json.validation_status).toBeUndefined();
196
+ expect(json.manifests).toBeDefined();
197
+ expect(json.active_manifest).toEqual(manifestStore.active_manifest);
198
+ });
178
199
  it("should write to a file", async () => {
179
200
  const outputPath = path.join(tempDir, "thumbnail.jpg");
180
201
  const reader = await Reader.fromAsset({
package/dist/Settings.js CHANGED
@@ -10,6 +10,7 @@
10
10
  // specific language governing permissions and limitations under
11
11
  // each license.
12
12
  import fs from "fs-extra";
13
+ import { Context, settingsToJson, withDefaultSettings } from "@contentauth/c2pa-utilities";
13
14
  /**
14
15
  * This file contains only Settings functions that are unique to the Node SDK.
15
16
  *
@@ -25,3 +26,22 @@ export async function loadSettingsFromFile(filePath) {
25
26
  const content = await fs.readFile(filePath, "utf8");
26
27
  return content;
27
28
  }
29
+ /**
30
+ * Resolves a settings argument (either the deprecated raw `C2paSettings or a `Context`) into
31
+ * a JSON string that can be passed into the native library.
32
+ *
33
+ * Unlike `c2pa-web`'s `Context.toJson()`, this does not resolve trust-anchor URLs: `c2pa-node`
34
+ * doesn't perform trust-anchor URL fetching yet, so a `Context`'s settings are only merged with
35
+ * this package's defaults and serialized here.
36
+ */
37
+ export function resolveSettingsForNeon(settingsOrContext) {
38
+ if (settingsOrContext == null) {
39
+ return undefined;
40
+ }
41
+ if (settingsOrContext instanceof Context) {
42
+ return settingsToJson(withDefaultSettings(settingsOrContext.settings));
43
+ }
44
+ return typeof settingsOrContext === "string"
45
+ ? settingsOrContext
46
+ : JSON.stringify(settingsOrContext);
47
+ }
@@ -6,7 +6,8 @@
6
6
  import fs from "fs-extra";
7
7
  import * as path from "path";
8
8
  import * as os from "os";
9
- import { loadSettingsFromFile } from "./Settings.js";
9
+ import { Context, DEFAULT_SETTINGS, mergeSettings, settingsToJson, } from "@contentauth/c2pa-utilities";
10
+ import { loadSettingsFromFile, resolveSettingsForNeon } from "./Settings.js";
10
11
  describe("Settings", () => {
11
12
  describe("loadSettingsFromFile", () => {
12
13
  let tempDir;
@@ -46,4 +47,36 @@ verify_after_sign = false`;
46
47
  await expect(loadSettingsFromFile(filePath)).rejects.toThrow();
47
48
  });
48
49
  });
50
+ describe("resolveSettingsForNeon", () => {
51
+ it("returns undefined when omitted", () => {
52
+ expect(resolveSettingsForNeon(undefined)).toBeUndefined();
53
+ });
54
+ it("returns undefined when null is passed in", () => {
55
+ // A plain-JS caller can pass `null` explicitly.
56
+ // It must not fall through to JSON.stringify(null), which would send the
57
+ // native library the literal string "null" instead of "no settings".
58
+ expect(resolveSettingsForNeon(null)).toBeUndefined();
59
+ });
60
+ it("applies defaults for an empty Context", () => {
61
+ const result = resolveSettingsForNeon(new Context());
62
+ expect(JSON.parse(result)).toEqual(JSON.parse(settingsToJson(DEFAULT_SETTINGS)));
63
+ });
64
+ it("merges a Context's settings with defaults", () => {
65
+ const settings = { verify: { verifyTrust: false } };
66
+ const result = resolveSettingsForNeon(new Context(settings));
67
+ expect(JSON.parse(result)).toEqual(JSON.parse(settingsToJson(mergeSettings(DEFAULT_SETTINGS, settings))));
68
+ });
69
+ it("passes a raw settings object through as-is, without applying defaults", () => {
70
+ // The deprecated raw-settings path preserves this package's pre-Context behavior exactly:
71
+ // no defaults are merged in, unlike the Context path above.
72
+ const result = resolveSettingsForNeon({
73
+ verify: { verify_trust: false },
74
+ });
75
+ expect(JSON.parse(result)).toEqual({ verify: { verify_trust: false } });
76
+ });
77
+ it("passes a raw settings JSON string through unchanged", () => {
78
+ const json = JSON.stringify({ verify: { verify_trust: false } });
79
+ expect(resolveSettingsForNeon(json)).toBe(json);
80
+ });
81
+ });
49
82
  });
package/dist/index.js CHANGED
@@ -9,5 +9,5 @@ export { LocalSigner, CallbackSigner } from "./Signer.js";
9
9
  export { IdentityAssertionBuilder, IdentityAssertionSigner, CallbackCredentialHolder, } from "./IdentityAssertion.js";
10
10
  export { Trustmark } from "./Trustmark.js";
11
11
  export { isActionsAssertion } from "./assertions.js";
12
- export * from "./Settings.js";
12
+ export { loadSettingsFromFile } from "./Settings.js";
13
13
  export * from '@contentauth/c2pa-utilities';
package/dist/index.node CHANGED
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/dist/index.node
3
- size: 49144704 bytes
4
- sha256: 5544def93faf8bb2a10888a015e4ec2f01d4d2bf8583b4cf871a8c48643dfdbe
3
+ size: 49170696 bytes
4
+ sha256: 6f1e7f72bb6e00aff6f77477d9f4961a022a98912016820b86f72cdcced88e8a
@@ -1,10 +1,44 @@
1
1
  import type { Action, BuilderIntent, C2paReason, Ingredient, Manifest, ManifestStore } from "@contentauth/c2pa-types";
2
+ import { Context } from "@contentauth/c2pa-utilities";
2
3
  import type { BuilderInterface, C2paSettings, CallbackSignerInterface, ClaimVersion, DestinationAsset, IdentityAssertionSignerInterface, JsCallbackSignerConfig, LocalSignerInterface, ManifestAssertionKind, ReaderInterface, SourceAsset, NeonBuilderHandle } from "./types.d.ts";
3
4
  export declare class Builder implements BuilderInterface {
4
5
  private builder;
5
6
  constructor(builder: NeonBuilderHandle);
7
+ /**
8
+ * @deprecated Use {@link Builder.newAsync} instead, passing a `Context`. Will be removed in a
9
+ * future major version.
10
+ * @param settings A raw `C2paSettings` string/object.
11
+ */
6
12
  static new(settings?: C2paSettings): Builder;
13
+ /**
14
+ * Create a Builder with a minimal manifest definition, configured by a `Context`.
15
+ * Prefer this over the deprecated {@link Builder.new}.
16
+ *
17
+ * Declared async for forward compatibility. Upcoming work will allow for trust anchor
18
+ * resolution at construction time.
19
+ *
20
+ * @param context A `Context` object containing configuration settings for this Builder.
21
+ * Defaults to an empty `Context` using default settings if one is not provided.
22
+ */
23
+ static newAsync(context?: Context): Promise<Builder>;
24
+ /**
25
+ * @deprecated Use {@link Builder.withJsonAsync} instead, passing a `Context`. Will be removed
26
+ * in a future version.
27
+ * @param settings A raw `C2paSettings` string/object.
28
+ */
7
29
  static withJson(json: Manifest, settings?: C2paSettings): Builder;
30
+ /**
31
+ * Create a Builder from a manifest definition, configured by a `Context`. Prefer this over
32
+ * the deprecated {@link Builder.withJson}.
33
+ *
34
+ * Declared async for forward compatibility. Upcoming work will allow c2pa-node
35
+ * to resolve trust anchors at construction time.
36
+ *
37
+ * @param json The manifest JSON.
38
+ * @param context A `Context` object containing configuration settings for this Builder.
39
+ * Defaults to an empty `Context` using default settings if one is not provided.
40
+ */
41
+ static withJsonAsync(json: Manifest, context?: Context): Promise<Builder>;
8
42
  setIntent(intent: BuilderIntent): void;
9
43
  setNoEmbed(noEmbed?: boolean): void;
10
44
  setRemoteUrl(remoteUrl: string): void;
@@ -14,7 +48,12 @@ export declare class Builder implements BuilderInterface {
14
48
  addIngredient(ingredientJson: string, ingredient?: SourceAsset): Promise<void>;
15
49
  addIngredientFromReader(reader: ReaderInterface): Ingredient;
16
50
  toArchive(asset: DestinationAsset): Promise<void>;
17
- static fromArchive(asset: SourceAsset, settings?: C2paSettings): Promise<Builder>;
51
+ /**
52
+ * @param settingsOrContext A `Context`, or (deprecated) a raw `C2paSettings` string/object. Passing a
53
+ * raw `C2paSettings` value is deprecated and will be removed in a future version. `null` is treated
54
+ * the same as `undefined`.
55
+ */
56
+ static fromArchive(asset: SourceAsset, settingsOrContext?: C2paSettings | Context | null): Promise<Builder>;
18
57
  sign(signer: LocalSignerInterface, input: SourceAsset, output: DestinationAsset): Buffer;
19
58
  signFile(signer: LocalSignerInterface, filePath: string, output: DestinationAsset): Buffer;
20
59
  signConfigAsync(callback: (data: Buffer) => Promise<Buffer>, signerConfig: JsCallbackSignerConfig, input: SourceAsset, output: DestinationAsset): Promise<Buffer>;
@@ -1,4 +1,5 @@
1
1
  import type { Manifest, ManifestStore } from "@contentauth/c2pa-types";
2
+ import type { Context } from "@contentauth/c2pa-utilities";
2
3
  import type { C2paSettings, DestinationAsset, ReaderInterface, ResourceAsset, SourceAsset, NeonReaderHandle } from "./types.d.ts";
3
4
  export declare class Reader implements ReaderInterface {
4
5
  private reader;
@@ -7,8 +8,18 @@ export declare class Reader implements ReaderInterface {
7
8
  remoteUrl(): string;
8
9
  isEmbedded(): boolean;
9
10
  resourceToAsset(uri: string, asset: DestinationAsset): Promise<ResourceAsset>;
10
- static fromAsset(asset: SourceAsset, settings?: C2paSettings): Promise<Reader | null>;
11
- static fromManifestDataAndAsset(manifestData: Buffer, asset: SourceAsset, settings?: C2paSettings): Promise<Reader>;
11
+ /**
12
+ * @param settingsOrContext A `Context`, or (@deprecated) a raw `C2paSettings` string/object. Passing a
13
+ * raw `C2paSettings` value is deprecated and will be removed in a future version. `null` is treated
14
+ * the same as `undefined`.
15
+ */
16
+ static fromAsset(asset: SourceAsset, settingsOrContext?: C2paSettings | Context | null): Promise<Reader | null>;
17
+ /**
18
+ * @param settingsOrContext A `Context`, or (@deprecated) a raw `C2paSettings` string/object. Passing a
19
+ * raw `C2paSettings` value is deprecated and will be removed in a future version. `null` is treated
20
+ * the same as `undefined`.
21
+ */
22
+ static fromManifestDataAndAsset(manifestData: Buffer, asset: SourceAsset, settingsOrContext?: C2paSettings | Context | null): Promise<Reader>;
12
23
  activeLabel(): string | undefined;
13
24
  getActive(): Manifest | undefined;
14
25
  getHandle(): NeonReaderHandle;
@@ -1,3 +1,5 @@
1
+ import { Context } from "@contentauth/c2pa-utilities";
2
+ import type { C2paSettings } from "./types.d.ts";
1
3
  /**
2
4
  * This file contains only Settings functions that are unique to the Node SDK.
3
5
  *
@@ -10,3 +12,12 @@
10
12
  * @returns Settings as a string (TOML or JSON depending on file extension)
11
13
  */
12
14
  export declare function loadSettingsFromFile(filePath: string): Promise<string>;
15
+ /**
16
+ * Resolves a settings argument (either the deprecated raw `C2paSettings or a `Context`) into
17
+ * a JSON string that can be passed into the native library.
18
+ *
19
+ * Unlike `c2pa-web`'s `Context.toJson()`, this does not resolve trust-anchor URLs: `c2pa-node`
20
+ * doesn't perform trust-anchor URL fetching yet, so a `Context`'s settings are only merged with
21
+ * this package's defaults and serialized here.
22
+ */
23
+ export declare function resolveSettingsForNeon(settingsOrContext: C2paSettings | Context | null | undefined): string | undefined;
@@ -5,5 +5,5 @@ export { LocalSigner, CallbackSigner } from "./Signer.js";
5
5
  export { IdentityAssertionBuilder, IdentityAssertionSigner, CallbackCredentialHolder, } from "./IdentityAssertion.js";
6
6
  export { Trustmark } from "./Trustmark.js";
7
7
  export { isActionsAssertion } from "./assertions.js";
8
- export * from "./Settings.js";
8
+ export { loadSettingsFromFile } from "./Settings.js";
9
9
  export * from '@contentauth/c2pa-utilities';
@@ -180,7 +180,7 @@ export interface HashedUri {
180
180
 
181
181
  /**
182
182
  * Optional settings that can be provided when creating a Reader or Builder.
183
- * Can be a JSON string, TOML string, or a settings object.
183
+ * Can be a JSON string or a settings object.
184
184
  */
185
185
  export type C2paSettings = string | object;
186
186
 
package/package.json CHANGED
@@ -5,7 +5,7 @@
5
5
  "url": "git+https://github.com/contentauth/c2pa-js.git",
6
6
  "directory": "packages/c2pa-node"
7
7
  },
8
- "version": "0.9.5",
8
+ "version": "0.9.7",
9
9
  "description": "Node.js bindings for C2PA",
10
10
  "main": "dist/index.js",
11
11
  "type": "module",
@@ -65,7 +65,7 @@
65
65
  "pretty-bytes": "^6.1.1",
66
66
  "unzipper": "^0.10.14",
67
67
  "@contentauth/c2pa-types": "0.7.4",
68
- "@contentauth/c2pa-utilities": "0.2.2"
68
+ "@contentauth/c2pa-utilities": "0.3.0"
69
69
  },
70
70
  "nx": {
71
71
  "tags": [
@@ -183,7 +183,7 @@ fn finalize_identity_assertion(
183
183
  };
184
184
 
185
185
  let mut assertion_cbor: Vec<u8> = vec![];
186
- ciborium::into_writer(&ia, &mut assertion_cbor)
186
+ c2pa_cbor::to_writer(&mut assertion_cbor, &ia)
187
187
  .map_err(|e| c2pa::Error::BadParam(e.to_string()))?;
188
188
  // TO DO: Think through how errors map into crate::Error.
189
189
 
@@ -195,7 +195,7 @@ fn finalize_identity_assertion(
195
195
  ia.pad1 = vec![0u8; assertion_size - assertion_cbor.len() - 15];
196
196
 
197
197
  assertion_cbor.clear();
198
- ciborium::into_writer(&ia, &mut assertion_cbor)
198
+ c2pa_cbor::to_writer(&mut assertion_cbor, &ia)
199
199
  .map_err(|e| c2pa::Error::BadParam(e.to_string()))?;
200
200
 
201
201
  ia.pad2 = Some(ByteBuf::from(vec![
@@ -204,7 +204,7 @@ fn finalize_identity_assertion(
204
204
  ]));
205
205
 
206
206
  assertion_cbor.clear();
207
- ciborium::into_writer(&ia, &mut assertion_cbor)
207
+ c2pa_cbor::to_writer(&mut assertion_cbor, &ia)
208
208
  .map_err(|e| c2pa::Error::BadParam(e.to_string()))?;
209
209
  assert_eq!(assertion_size, assertion_cbor.len());
210
210
  }