@contentauth/c2pa-node 0.8.2 → 0.9.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/README.md +34 -29
- package/dist/Builder.js +3 -0
- package/dist/Builder.spec.js +273 -0
- package/dist/Reader.js +3 -0
- package/dist/Reader.spec.js +8 -0
- package/dist/Settings.js +4 -78
- package/dist/Settings.spec.js +1 -213
- package/dist/assetSize.js +35 -0
- package/dist/index.js +1 -0
- package/dist/index.node +0 -0
- package/dist/types/Builder.d.ts +1 -0
- package/dist/types/Settings.d.ts +4 -37
- package/dist/types/assetSize.d.ts +14 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/types.d.ts +46 -71
- package/package.json +5 -4
- package/src/lib.rs +4 -0
- package/src/neon_builder.rs +95 -1
package/README.md
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
|
-
#
|
|
1
|
+
# CAI Node.js library
|
|
2
2
|
|
|
3
3
|
`@contentauth/c2pa-node` is a Node.js library in the [c2pa-js](https://github.com/contentauth/c2pa-js) monorepo that can:
|
|
4
|
+
|
|
4
5
|
- Read and validate C2PA data from media files in supported formats.
|
|
5
6
|
- Add signed manifests to media files in supported formats.
|
|
6
7
|
|
|
7
8
|
## Prerequisites
|
|
8
9
|
|
|
9
|
-
To use the
|
|
10
|
+
To use the c2pa-node library, you need Node.js 22 or later. If you need to manage multiple versions of Node on your machine, use a tool such as [nvm](https://github.com/nvm-sh/nvm).
|
|
10
11
|
|
|
11
|
-
To
|
|
12
|
+
To build from source, you also need [Rust](https://www.rust-lang.org/tools/install). This is not required when installing the package normally: precompiled binaries are downloaded automatically during installation.
|
|
12
13
|
|
|
13
14
|
## Installation
|
|
14
15
|
|
|
@@ -17,19 +18,19 @@ To **build from source** you also need [Rust](https://www.rust-lang.org/tools/in
|
|
|
17
18
|
Using npm:
|
|
18
19
|
|
|
19
20
|
```sh
|
|
20
|
-
|
|
21
|
+
npm install @contentauth/c2pa-node
|
|
21
22
|
```
|
|
22
23
|
|
|
23
24
|
Using Yarn:
|
|
24
25
|
|
|
25
26
|
```sh
|
|
26
|
-
|
|
27
|
+
yarn add @contentauth/c2pa-node
|
|
27
28
|
```
|
|
28
29
|
|
|
29
30
|
Using pnpm:
|
|
30
31
|
|
|
31
32
|
```sh
|
|
32
|
-
|
|
33
|
+
pnpm add @contentauth/c2pa-node
|
|
33
34
|
```
|
|
34
35
|
|
|
35
36
|
This command will download precompiled binaries for the following systems:
|
|
@@ -90,6 +91,8 @@ const isEmbedded = reader.isEmbedded();
|
|
|
90
91
|
const remoteUrl = reader.remoteUrl();
|
|
91
92
|
```
|
|
92
93
|
|
|
94
|
+
`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
|
+
|
|
93
96
|
### Builder
|
|
94
97
|
|
|
95
98
|
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.
|
|
@@ -124,15 +127,13 @@ await builder.addResource('resource://example', resourceAsset);
|
|
|
124
127
|
const manifest = builder.sign(signer, inputAsset, outputAsset);
|
|
125
128
|
```
|
|
126
129
|
|
|
127
|
-
#### Setting
|
|
128
|
-
|
|
129
|
-
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.
|
|
130
|
+
#### Setting builder intent
|
|
130
131
|
|
|
131
|
-
|
|
132
|
+
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:
|
|
132
133
|
|
|
133
|
-
`
|
|
134
|
-
|
|
135
|
-
`update`: A restricted version of
|
|
134
|
+
- `create`: Indicates the asset is a new digital creation, a `DigitalSourceType` is required. The manifest must not have a parent ingredient. A `c2pa.created` action will be added if not provided.
|
|
135
|
+
- `edit`: Indicates the asset is an edit of a pre-existing parent asset. The manifest must have a parent ingredient. A parent ingredient will be generated from the source stream if not otherwise provided. A `c2pa.opened` action will be tied to the parent ingredient.
|
|
136
|
+
- `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.
|
|
136
137
|
|
|
137
138
|
```javascript
|
|
138
139
|
const builder = Builder.new();
|
|
@@ -152,11 +153,11 @@ The `create` intent accepts a `DigitalSourceType` that describes the origin of t
|
|
|
152
153
|
- `'http://cv.iptc.org/newscodes/digitalsourcetype/digitalCapture'` - Digital camera capture
|
|
153
154
|
- `'http://cv.iptc.org/newscodes/digitalsourcetype/composite'` - Composite of multiple sources
|
|
154
155
|
|
|
155
|
-
For a complete list of digital source types, see the [C2PA specification](https://c2pa.org/specifications/specifications/2.
|
|
156
|
+
For a complete list of digital source types, see the [C2PA specification](https://c2pa.org/specifications/specifications/2.4/specs/C2PA_Specification.html#_digital_source_type) and [IPTC digital source type vocabulary](https://cv.iptc.org/newscodes/digitalsourcetype).
|
|
156
157
|
|
|
157
158
|
For more details on builder intents, see the [c2pa-rs Builder documentation](https://docs.rs/c2pa/latest/c2pa/struct.Builder.html).
|
|
158
159
|
|
|
159
|
-
#### Adding
|
|
160
|
+
#### Adding ingredients from assets
|
|
160
161
|
|
|
161
162
|
When you have access to the ingredient asset, use `addIngredient` with an asset to include both the metadata and the asset data:
|
|
162
163
|
|
|
@@ -187,7 +188,7 @@ const definition = builder.getManifestDefinition();
|
|
|
187
188
|
console.log(definition.ingredients); // Contains the ingredient with embedded data
|
|
188
189
|
```
|
|
189
190
|
|
|
190
|
-
#### Adding
|
|
191
|
+
#### Adding multiple ingredients
|
|
191
192
|
|
|
192
193
|
You can add multiple ingredients to document complex provenance chains:
|
|
193
194
|
|
|
@@ -230,7 +231,7 @@ const definition = builder.getManifestDefinition();
|
|
|
230
231
|
console.log(definition.ingredients.length); // 2
|
|
231
232
|
```
|
|
232
233
|
|
|
233
|
-
#### Adding
|
|
234
|
+
#### Adding ingredients from readers
|
|
234
235
|
|
|
235
236
|
You can also add ingredients directly from a `Reader` object, which automatically includes the C2PA data:
|
|
236
237
|
|
|
@@ -249,7 +250,7 @@ const ingredient = builder.addIngredientFromReader(sourceReader);
|
|
|
249
250
|
console.log(ingredient.title); // Contains ingredient metadata
|
|
250
251
|
```
|
|
251
252
|
|
|
252
|
-
#### Adding
|
|
253
|
+
#### Adding ingredients from archive files
|
|
253
254
|
|
|
254
255
|
You can add ingredients from `.c2pa` archive files. Archives are binary files that contain a manifest store with ingredients and their associated resources (thumbnails, manifest data, etc.). To work with them, read the archive with `Reader` using the `application/c2pa` MIME type, then extract the ingredients and transfer their binary resources to a new `Builder`.
|
|
255
256
|
|
|
@@ -368,7 +369,7 @@ await builder.addIngredient(
|
|
|
368
369
|
await builder.toArchive({ path: 'ingredient-catalog.c2pa' });
|
|
369
370
|
```
|
|
370
371
|
|
|
371
|
-
#### Creating and
|
|
372
|
+
#### Creating and reusing builder archives
|
|
372
373
|
|
|
373
374
|
Builder archives allow you to save a builder's state (including ingredients) and reuse it later:
|
|
374
375
|
|
|
@@ -447,7 +448,7 @@ const signer = CallbackSigner.newSigner(
|
|
|
447
448
|
);
|
|
448
449
|
```
|
|
449
450
|
|
|
450
|
-
### Identity
|
|
451
|
+
### Identity assertion components
|
|
451
452
|
|
|
452
453
|
For working with identity assertions and CAWG (Content Authenticity Working Group) identities:
|
|
453
454
|
|
|
@@ -518,11 +519,11 @@ const encodedImage = await trustmark.encode(
|
|
|
518
519
|
const decodedData = await trustmark.decode(imageBuffer);
|
|
519
520
|
```
|
|
520
521
|
|
|
521
|
-
### Settings and
|
|
522
|
+
### Settings and configuration
|
|
522
523
|
|
|
523
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.
|
|
524
525
|
|
|
525
|
-
#### Per-
|
|
526
|
+
#### Per-instance settings
|
|
526
527
|
|
|
527
528
|
Settings can be passed directly to `Reader` and `Builder` constructors:
|
|
528
529
|
|
|
@@ -554,7 +555,7 @@ const settingsJson = JSON.stringify(settings);
|
|
|
554
555
|
const builder2 = Builder.new(settingsJson);
|
|
555
556
|
```
|
|
556
557
|
|
|
557
|
-
#### Settings
|
|
558
|
+
#### Settings helper functions
|
|
558
559
|
|
|
559
560
|
The library provides helper functions to create and manage settings objects:
|
|
560
561
|
|
|
@@ -610,16 +611,16 @@ const urlSettings = await loadSettingsFromUrl('https://example.com/c2pa-settings
|
|
|
610
611
|
const builder = Builder.new(urlSettings);
|
|
611
612
|
```
|
|
612
613
|
|
|
613
|
-
#### Available
|
|
614
|
+
#### Available settings
|
|
614
615
|
|
|
615
|
-
**Trust
|
|
616
|
+
**Trust settings:**
|
|
616
617
|
- `verifyTrustList` - Whether to verify against the trust list
|
|
617
618
|
- `userAnchors` - User-provided trust anchors (PEM format or path)
|
|
618
619
|
- `trustAnchors` - Trust anchors for validation (PEM format or path)
|
|
619
620
|
- `trustConfig` - Path to trust configuration file
|
|
620
621
|
- `allowedList` - Allowed list of certificates (PEM format or path)
|
|
621
622
|
|
|
622
|
-
**Verify
|
|
623
|
+
**Verify settings:**
|
|
623
624
|
- `verifyAfterReading` - Whether to verify after reading a manifest
|
|
624
625
|
- `verifyAfterSign` - Whether to verify after signing a manifest
|
|
625
626
|
- `verifyTrust` - Whether to verify trust during validation
|
|
@@ -629,18 +630,22 @@ const builder = Builder.new(urlSettings);
|
|
|
629
630
|
- `skipIngredientConflictResolution` - Whether to skip ingredient conflict resolution
|
|
630
631
|
- `strictV1Validation` - Whether to use strict v1 validation
|
|
631
632
|
|
|
632
|
-
**Builder
|
|
633
|
+
**Builder settings:**
|
|
633
634
|
- `generate_c2pa_archive` - Whether to generate C2PA archive format
|
|
634
635
|
|
|
635
|
-
|
|
636
|
-
|
|
636
|
+
> [!NOTE]
|
|
637
|
+
> Settings are passed as per-instance configuration. There are no global settings that affect all Readers and Builders.
|
|
637
638
|
|
|
638
639
|
### Build and use custom binary
|
|
640
|
+
|
|
639
641
|
**Build Rust binary:**
|
|
642
|
+
|
|
640
643
|
```bash
|
|
641
644
|
pnpm run build:rust
|
|
642
645
|
```
|
|
646
|
+
|
|
643
647
|
**Use custom Rust binary:**
|
|
648
|
+
|
|
644
649
|
```bash
|
|
645
650
|
export C2PA_LIBRARY_PATH=<path-to-binary-folder>/index.node
|
|
646
651
|
```
|
package/dist/Builder.js
CHANGED
|
@@ -158,6 +158,9 @@ export class Builder {
|
|
|
158
158
|
filterActionsAndIngredients(keepAction, rescueIngredient) {
|
|
159
159
|
getNeonBinary().builderFilterActionsAndIngredients.call(this.builder, keepAction, rescueIngredient);
|
|
160
160
|
}
|
|
161
|
+
updateActions(transform) {
|
|
162
|
+
getNeonBinary().builderUpdateActions.call(this.builder, transform);
|
|
163
|
+
}
|
|
161
164
|
getHandle() {
|
|
162
165
|
return this.builder;
|
|
163
166
|
}
|
package/dist/Builder.spec.js
CHANGED
|
@@ -984,5 +984,278 @@ describe("Builder", () => {
|
|
|
984
984
|
throw new Error("action predicate boom");
|
|
985
985
|
}, () => false)).toThrow("action predicate boom");
|
|
986
986
|
});
|
|
987
|
+
it("updateActions patches a parameter on an existing action", () => {
|
|
988
|
+
const builder = Builder.withJson(actionsManifest());
|
|
989
|
+
builder.updateActions((actions) => actions.map((action) => action.action === "c2pa.created"
|
|
990
|
+
? {
|
|
991
|
+
...action,
|
|
992
|
+
parameters: { ...action.parameters, patchMe: "patch-test" },
|
|
993
|
+
}
|
|
994
|
+
: action));
|
|
995
|
+
const definition = builder.getManifestDefinition();
|
|
996
|
+
const actionsAssertions = definition.assertions.filter((a) => a.label.startsWith("c2pa.actions"));
|
|
997
|
+
expect(actionsAssertions).toHaveLength(1);
|
|
998
|
+
// Keep original actions label (no upgrade)
|
|
999
|
+
expect(actionsAssertions[0].label).toBe("c2pa.actions");
|
|
1000
|
+
const patched = actionsAssertions[0].data.actions;
|
|
1001
|
+
expect(patched.map((a) => a.action)).toEqual([
|
|
1002
|
+
"c2pa.created",
|
|
1003
|
+
"c2pa.edited",
|
|
1004
|
+
"c2pa.color_adjustments",
|
|
1005
|
+
]);
|
|
1006
|
+
expect(patched[0].parameters.patchMe).toBe("patch-test");
|
|
1007
|
+
});
|
|
1008
|
+
it("updateActions adds a new parameter alongside the existing ones", () => {
|
|
1009
|
+
const manifest = actionsManifest();
|
|
1010
|
+
manifest.assertions[0].data.actions[1].parameters = {
|
|
1011
|
+
existingValue: "kept",
|
|
1012
|
+
};
|
|
1013
|
+
const builder = Builder.withJson(manifest);
|
|
1014
|
+
builder.updateActions((actions) => actions.map((action) => action.action === "c2pa.edited"
|
|
1015
|
+
? {
|
|
1016
|
+
...action,
|
|
1017
|
+
parameters: {
|
|
1018
|
+
...action.parameters,
|
|
1019
|
+
addedValue: "added-value",
|
|
1020
|
+
},
|
|
1021
|
+
}
|
|
1022
|
+
: action));
|
|
1023
|
+
const definition = builder.getManifestDefinition();
|
|
1024
|
+
const actionsAssertions = definition.assertions.filter((a) => a.label.startsWith("c2pa.actions"));
|
|
1025
|
+
expect(actionsAssertions).toHaveLength(1);
|
|
1026
|
+
const updated = actionsAssertions[0].data.actions;
|
|
1027
|
+
expect(updated.map((a) => a.action)).toEqual([
|
|
1028
|
+
"c2pa.created",
|
|
1029
|
+
"c2pa.edited",
|
|
1030
|
+
"c2pa.color_adjustments",
|
|
1031
|
+
]);
|
|
1032
|
+
expect(updated[1].parameters.addedValue).toBe("added-value");
|
|
1033
|
+
expect(updated[1].parameters.existingValue).toBe("kept");
|
|
1034
|
+
// The untargeted actions gain nothing.
|
|
1035
|
+
expect(updated[0].parameters?.addedValue).toBeUndefined();
|
|
1036
|
+
expect(updated[2].parameters?.addedValue).toBeUndefined();
|
|
1037
|
+
});
|
|
1038
|
+
it("updateActions is no-op when there is no actions assertion", () => {
|
|
1039
|
+
const builder = Builder.withJson({
|
|
1040
|
+
claim_generator_info: [{ name: "c2pa_test", version: "1.0.0" }],
|
|
1041
|
+
title: "Test_NoActions",
|
|
1042
|
+
format: "image/jpeg",
|
|
1043
|
+
ingredients: [],
|
|
1044
|
+
assertions: [],
|
|
1045
|
+
resources: { resources: {} },
|
|
1046
|
+
});
|
|
1047
|
+
let calls = 0;
|
|
1048
|
+
builder.updateActions((actions) => {
|
|
1049
|
+
calls += 1;
|
|
1050
|
+
return [...actions, { action: "c2pa.created" }];
|
|
1051
|
+
});
|
|
1052
|
+
expect(calls).toBe(0);
|
|
1053
|
+
const definition = builder.getManifestDefinition();
|
|
1054
|
+
expect((definition.assertions ?? []).filter((a) => a.label.startsWith("c2pa.actions"))).toHaveLength(0);
|
|
1055
|
+
});
|
|
1056
|
+
it("updateActions drops an assertion whose transform returns an empty list", () => {
|
|
1057
|
+
// (this means there could be no actions, so in non-test code, something after such a call
|
|
1058
|
+
// should make sure the manifest is still valid and inception actions are here as needed!)
|
|
1059
|
+
const builder = Builder.withJson({
|
|
1060
|
+
claim_generator_info: [{ name: "c2pa_test", version: "1.0.0" }],
|
|
1061
|
+
title: "Test_TwoAssertions",
|
|
1062
|
+
format: "image/jpeg",
|
|
1063
|
+
ingredients: [],
|
|
1064
|
+
assertions: [
|
|
1065
|
+
{
|
|
1066
|
+
label: "c2pa.actions",
|
|
1067
|
+
data: {
|
|
1068
|
+
actions: [
|
|
1069
|
+
{
|
|
1070
|
+
action: "c2pa.created",
|
|
1071
|
+
digitalSourceType: "http://c2pa.org/digitalsourcetype/empty",
|
|
1072
|
+
},
|
|
1073
|
+
],
|
|
1074
|
+
},
|
|
1075
|
+
},
|
|
1076
|
+
{
|
|
1077
|
+
label: "c2pa.actions.v2",
|
|
1078
|
+
data: { actions: [{ action: "c2pa.edited" }] },
|
|
1079
|
+
},
|
|
1080
|
+
],
|
|
1081
|
+
resources: { resources: {} },
|
|
1082
|
+
});
|
|
1083
|
+
// Empty out the gathered assertion only.
|
|
1084
|
+
builder.updateActions((actions) => actions.some((a) => a.action === "c2pa.edited") ? [] : actions);
|
|
1085
|
+
const definition = builder.getManifestDefinition();
|
|
1086
|
+
const actionsAssertions = definition.assertions.filter((a) => a.label.startsWith("c2pa.actions"));
|
|
1087
|
+
expect(actionsAssertions).toHaveLength(1);
|
|
1088
|
+
expect(actionsAssertions[0].label).toBe("c2pa.actions");
|
|
1089
|
+
expect(actionsAssertions[0].data.actions.map((a) => a.action)).toEqual(["c2pa.created"]);
|
|
1090
|
+
});
|
|
1091
|
+
it("updateActions rewrites every actions assertion under its own label", () => {
|
|
1092
|
+
const builder = Builder.withJson({
|
|
1093
|
+
claim_generator_info: [{ name: "c2pa_test", version: "1.0.0" }],
|
|
1094
|
+
title: "Test_MultiAssertion",
|
|
1095
|
+
format: "image/jpeg",
|
|
1096
|
+
ingredients: [],
|
|
1097
|
+
assertions: [
|
|
1098
|
+
{
|
|
1099
|
+
label: "c2pa.actions",
|
|
1100
|
+
data: {
|
|
1101
|
+
actions: [
|
|
1102
|
+
{
|
|
1103
|
+
action: "c2pa.created",
|
|
1104
|
+
digitalSourceType: "http://c2pa.org/digitalsourcetype/empty",
|
|
1105
|
+
},
|
|
1106
|
+
],
|
|
1107
|
+
},
|
|
1108
|
+
},
|
|
1109
|
+
{
|
|
1110
|
+
label: "c2pa.actions.v2",
|
|
1111
|
+
data: { actions: [{ action: "c2pa.edited" }] },
|
|
1112
|
+
},
|
|
1113
|
+
],
|
|
1114
|
+
resources: { resources: {} },
|
|
1115
|
+
});
|
|
1116
|
+
const seen = [];
|
|
1117
|
+
builder.updateActions((actions) => {
|
|
1118
|
+
seen.push(actions.map((a) => a.action));
|
|
1119
|
+
return actions.map((action) => ({
|
|
1120
|
+
...action,
|
|
1121
|
+
parameters: { ...action.parameters, addedValue: "added-value" },
|
|
1122
|
+
}));
|
|
1123
|
+
});
|
|
1124
|
+
// The transform runs once per actions assertion, in positional order.
|
|
1125
|
+
expect(seen).toEqual([["c2pa.created"], ["c2pa.edited"]]);
|
|
1126
|
+
const definition = builder.getManifestDefinition();
|
|
1127
|
+
const actionsAssertions = definition.assertions.filter((a) => a.label.startsWith("c2pa.actions"));
|
|
1128
|
+
expect(actionsAssertions.map((a) => a.label)).toEqual([
|
|
1129
|
+
"c2pa.actions",
|
|
1130
|
+
"c2pa.actions.v2",
|
|
1131
|
+
]);
|
|
1132
|
+
for (const assertion of actionsAssertions) {
|
|
1133
|
+
const actions = assertion.data.actions;
|
|
1134
|
+
expect(actions).toHaveLength(1);
|
|
1135
|
+
expect(actions[0].parameters.addedValue).toBe("added-value");
|
|
1136
|
+
}
|
|
1137
|
+
});
|
|
1138
|
+
it("updateActions preserves the created flag", () => {
|
|
1139
|
+
const builder = Builder.withJson({
|
|
1140
|
+
claim_generator_info: [{ name: "c2pa_test", version: "1.0.0" }],
|
|
1141
|
+
title: "Test_CreatedFlag",
|
|
1142
|
+
format: "image/jpeg",
|
|
1143
|
+
ingredients: [],
|
|
1144
|
+
assertions: [
|
|
1145
|
+
{
|
|
1146
|
+
label: "c2pa.actions.v2",
|
|
1147
|
+
created: true,
|
|
1148
|
+
data: {
|
|
1149
|
+
actions: [
|
|
1150
|
+
{
|
|
1151
|
+
action: "c2pa.created",
|
|
1152
|
+
digitalSourceType: "http://c2pa.org/digitalsourcetype/empty",
|
|
1153
|
+
},
|
|
1154
|
+
],
|
|
1155
|
+
},
|
|
1156
|
+
},
|
|
1157
|
+
{
|
|
1158
|
+
label: "c2pa.actions.v2",
|
|
1159
|
+
data: { actions: [{ action: "c2pa.color_adjustments" }] },
|
|
1160
|
+
},
|
|
1161
|
+
],
|
|
1162
|
+
resources: { resources: {} },
|
|
1163
|
+
});
|
|
1164
|
+
builder.updateActions((actions) => actions);
|
|
1165
|
+
const definition = builder.getManifestDefinition();
|
|
1166
|
+
const actionsAssertions = definition.assertions.filter((a) => a.label.startsWith("c2pa.actions"));
|
|
1167
|
+
// The created-list assertion keeps its flag and its leading position; a
|
|
1168
|
+
// rebuild via add_assertion would reset the flag and move it to the end.
|
|
1169
|
+
expect(actionsAssertions).toHaveLength(2);
|
|
1170
|
+
expect(actionsAssertions[0].created).toBe(true);
|
|
1171
|
+
expect(actionsAssertions[1].created).toBeFalsy();
|
|
1172
|
+
expect(actionsAssertions[0].data.actions.map((a) => a.action)).toEqual(["c2pa.created"]);
|
|
1173
|
+
});
|
|
1174
|
+
it("updateActions produces a signable manifest", async () => {
|
|
1175
|
+
const builder = Builder.withJson({
|
|
1176
|
+
claim_generator_info: [{ name: "c2pa_test", version: "1.0.0" }],
|
|
1177
|
+
title: "Test_UpdateActionsSign",
|
|
1178
|
+
format: "image/jpeg",
|
|
1179
|
+
instance_id: "update-actions-sign",
|
|
1180
|
+
ingredients: [],
|
|
1181
|
+
assertions: [
|
|
1182
|
+
{
|
|
1183
|
+
label: "c2pa.actions.v2",
|
|
1184
|
+
created: true,
|
|
1185
|
+
data: {
|
|
1186
|
+
actions: [
|
|
1187
|
+
{
|
|
1188
|
+
action: "c2pa.created",
|
|
1189
|
+
digitalSourceType: "http://c2pa.org/digitalsourcetype/empty",
|
|
1190
|
+
},
|
|
1191
|
+
],
|
|
1192
|
+
},
|
|
1193
|
+
},
|
|
1194
|
+
{
|
|
1195
|
+
label: "c2pa.actions.v2",
|
|
1196
|
+
data: { actions: [{ action: "c2pa.color_adjustments" }] },
|
|
1197
|
+
},
|
|
1198
|
+
],
|
|
1199
|
+
resources: { resources: {} },
|
|
1200
|
+
});
|
|
1201
|
+
builder.updateActions((actions) => actions);
|
|
1202
|
+
const dest = { path: path.join(tempDir, "update-actions-signed.jpg") };
|
|
1203
|
+
const signer = LocalSigner.newSigner(publicKey, privateKey, "es256");
|
|
1204
|
+
const bytes = builder.sign(signer, source, dest);
|
|
1205
|
+
expect(bytes.length).toBeGreaterThan(0);
|
|
1206
|
+
const reader = await Reader.fromAsset(dest);
|
|
1207
|
+
expect(reader).not.toBeNull();
|
|
1208
|
+
const manifestStore = reader.json();
|
|
1209
|
+
const codes = (manifestStore.validation_status ?? []).map((s) => s.code);
|
|
1210
|
+
expect(codes).not.toContain("assertion.action.malformed");
|
|
1211
|
+
expect(codes).not.toContain("assertion.action.ingredientMismatch");
|
|
1212
|
+
});
|
|
1213
|
+
it("updateActions preserves action order when transform patches in place", () => {
|
|
1214
|
+
const builder = Builder.withJson(actionsManifest());
|
|
1215
|
+
// Patch the middle entry; the transform never reorders.
|
|
1216
|
+
builder.updateActions((actions) => actions.map((action) => action.action === "c2pa.edited"
|
|
1217
|
+
? { ...action, parameters: { note: "patched" } }
|
|
1218
|
+
: action));
|
|
1219
|
+
const definition = builder.getManifestDefinition();
|
|
1220
|
+
const actionsAssertion = definition.assertions.find((a) => a.label.startsWith("c2pa.actions"));
|
|
1221
|
+
const names = actionsAssertion.data.actions.map((a) => a.action);
|
|
1222
|
+
expect(names).toEqual([
|
|
1223
|
+
"c2pa.created",
|
|
1224
|
+
"c2pa.edited",
|
|
1225
|
+
"c2pa.color_adjustments",
|
|
1226
|
+
]);
|
|
1227
|
+
});
|
|
1228
|
+
it("updateActions surfaces an error thrown by transform", () => {
|
|
1229
|
+
const builder = Builder.withJson(actionsManifest());
|
|
1230
|
+
expect(() => builder.updateActions(() => {
|
|
1231
|
+
throw new Error("transform boom");
|
|
1232
|
+
})).toThrow("transform boom");
|
|
1233
|
+
});
|
|
1234
|
+
it("updateActions preserves allActionsIncluded/softwareAgents/templates/metadata not seen by transform", () => {
|
|
1235
|
+
const manifest = actionsManifest();
|
|
1236
|
+
manifest.assertions[0].data.allActionsIncluded = true;
|
|
1237
|
+
manifest.assertions[0].data.softwareAgents = [
|
|
1238
|
+
{ name: "c2pa_test", version: "1.0.0" },
|
|
1239
|
+
];
|
|
1240
|
+
manifest.assertions[0].data.templates = [
|
|
1241
|
+
{ action: "c2pa.edited" },
|
|
1242
|
+
];
|
|
1243
|
+
manifest.assertions[0].data.metadata = {
|
|
1244
|
+
dataSource: { type: "humanEdits" },
|
|
1245
|
+
};
|
|
1246
|
+
const builder = Builder.withJson(manifest);
|
|
1247
|
+
// transform only ever sees/returns the flattened actions list, never the sibling fields.
|
|
1248
|
+
builder.updateActions((actions) => actions);
|
|
1249
|
+
const definition = builder.getManifestDefinition();
|
|
1250
|
+
const actionsAssertions = definition.assertions.filter((a) => a.label.startsWith("c2pa.actions"));
|
|
1251
|
+
expect(actionsAssertions).toHaveLength(1);
|
|
1252
|
+
const data = actionsAssertions[0].data;
|
|
1253
|
+
expect(data.allActionsIncluded).toBe(true);
|
|
1254
|
+
expect(data.softwareAgents).toEqual([
|
|
1255
|
+
{ name: "c2pa_test", version: "1.0.0" },
|
|
1256
|
+
]);
|
|
1257
|
+
expect(data.templates).toEqual([{ action: "c2pa.edited" }]);
|
|
1258
|
+
expect(data.metadata).toEqual({ dataSource: { type: "humanEdits" } });
|
|
1259
|
+
});
|
|
987
1260
|
});
|
|
988
1261
|
});
|
package/dist/Reader.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// or the MIT license (http://opensource.org/licenses/MIT),
|
|
5
5
|
// at your option.
|
|
6
6
|
import { getNeonBinary } from "./binary.js";
|
|
7
|
+
import { validateSourceAssetSize } from "./assetSize.js";
|
|
7
8
|
export class Reader {
|
|
8
9
|
reader;
|
|
9
10
|
constructor(reader) {
|
|
@@ -22,11 +23,13 @@ export class Reader {
|
|
|
22
23
|
return getNeonBinary().readerResourceToAsset.call(this.reader, uri, asset);
|
|
23
24
|
}
|
|
24
25
|
static async fromAsset(asset, settings) {
|
|
26
|
+
await validateSourceAssetSize(asset);
|
|
25
27
|
const settingsStr = settings ? (typeof settings === 'string' ? settings : JSON.stringify(settings)) : undefined;
|
|
26
28
|
const reader = await getNeonBinary().readerFromAsset(asset, settingsStr);
|
|
27
29
|
return reader ? new Reader(reader) : null;
|
|
28
30
|
}
|
|
29
31
|
static async fromManifestDataAndAsset(manifestData, asset, settings) {
|
|
32
|
+
await validateSourceAssetSize(asset);
|
|
30
33
|
const settingsStr = settings ? (typeof settings === 'string' ? settings : JSON.stringify(settings)) : undefined;
|
|
31
34
|
const reader = await getNeonBinary().readerFromManifestDataAndAsset(manifestData, asset, settingsStr);
|
|
32
35
|
return new Reader(reader);
|
package/dist/Reader.spec.js
CHANGED
|
@@ -5,7 +5,9 @@
|
|
|
5
5
|
// at your option.
|
|
6
6
|
import path from "path";
|
|
7
7
|
import * as fs from "fs-extra";
|
|
8
|
+
import { AssetTooLargeError } from "@contentauth/c2pa-utilities";
|
|
8
9
|
import { Reader } from "./Reader.js";
|
|
10
|
+
import { MAX_SIZE_IN_BYTES } from "./assetSize.js";
|
|
9
11
|
const tempDir = path.join(__dirname, "tmp");
|
|
10
12
|
describe("Reader", () => {
|
|
11
13
|
const manifestStore = JSON.parse(`{
|
|
@@ -126,6 +128,12 @@ describe("Reader", () => {
|
|
|
126
128
|
});
|
|
127
129
|
expect(reader).toBeNull();
|
|
128
130
|
});
|
|
131
|
+
it("should throw AssetTooLargeError for a file asset exceeding the max size", async () => {
|
|
132
|
+
const oversizedPath = path.join(tempDir, "oversized.jpg");
|
|
133
|
+
await fs.ensureFile(oversizedPath);
|
|
134
|
+
await fs.truncate(oversizedPath, MAX_SIZE_IN_BYTES + 1);
|
|
135
|
+
await expect(Reader.fromAsset({ path: oversizedPath })).rejects.toThrow(AssetTooLargeError);
|
|
136
|
+
});
|
|
129
137
|
it("should read from manifest data and buffer", async () => {
|
|
130
138
|
const manifestData = await fs.readFile("./tests/fixtures/CA/manifest_data.c2pa");
|
|
131
139
|
const buffer = await fs.readFile("./tests/fixtures/CA.jpg");
|
package/dist/Settings.js
CHANGED
|
@@ -10,74 +10,12 @@
|
|
|
10
10
|
// specific language governing permissions and limitations under
|
|
11
11
|
// each license.
|
|
12
12
|
import * as fs from "fs-extra";
|
|
13
|
-
import fetch from "node-fetch";
|
|
14
|
-
function snakeCaseify(object) {
|
|
15
|
-
return Object.entries(object).reduce((result, [key, val]) => {
|
|
16
|
-
result[snakeCase(key)] =
|
|
17
|
-
typeof val === "object" && val !== null ? snakeCaseify(val) : val;
|
|
18
|
-
return result;
|
|
19
|
-
}, {});
|
|
20
|
-
}
|
|
21
|
-
function snakeCase(str) {
|
|
22
|
-
return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
|
|
23
|
-
}
|
|
24
|
-
/**
|
|
25
|
-
* Create a Settings object with trust configuration.
|
|
26
|
-
* @param trustConfig The trust configuration
|
|
27
|
-
* @returns Settings object that can be passed to Reader/Builder
|
|
28
|
-
*/
|
|
29
|
-
export function createTrustSettings(trustConfig) {
|
|
30
|
-
return { trust: { ...trustConfig } };
|
|
31
|
-
}
|
|
32
|
-
/**
|
|
33
|
-
* Create a settings object with CAWG trust configuration.
|
|
34
|
-
* @param trustConfig The CAWG trust configuration
|
|
35
|
-
* @returns Settings object that can be passed to Reader/Builder
|
|
36
|
-
*/
|
|
37
|
-
export function createCawgTrustSettings(trustConfig) {
|
|
38
|
-
return { cawgTrust: { ...trustConfig } };
|
|
39
|
-
}
|
|
40
|
-
/**
|
|
41
|
-
* Create a settings object with verify configuration.
|
|
42
|
-
* @param verifyConfig The verify configuration
|
|
43
|
-
* @returns Settings object that can be passed to Reader/Builder
|
|
44
|
-
*/
|
|
45
|
-
export function createVerifySettings(verifyConfig) {
|
|
46
|
-
return { verify: { ...verifyConfig } };
|
|
47
|
-
}
|
|
48
13
|
/**
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
*
|
|
14
|
+
* This file contains only Settings functions that are unique to the Node SDK.
|
|
15
|
+
*
|
|
16
|
+
* Shared Settings-related functions and types can be found in `c2pa-utilities`,
|
|
17
|
+
* and are re-exported by `c2pa-node` (see `index.ts`) for convenience.
|
|
53
18
|
*/
|
|
54
|
-
export function mergeSettings(...settings) {
|
|
55
|
-
const merged = {};
|
|
56
|
-
for (const setting of settings) {
|
|
57
|
-
if (setting.trust) {
|
|
58
|
-
merged.trust = { ...merged.trust, ...setting.trust };
|
|
59
|
-
}
|
|
60
|
-
if (setting.cawgTrust) {
|
|
61
|
-
merged.cawgTrust = { ...merged.cawgTrust, ...setting.cawgTrust };
|
|
62
|
-
}
|
|
63
|
-
if (setting.verify) {
|
|
64
|
-
merged.verify = { ...merged.verify, ...setting.verify };
|
|
65
|
-
}
|
|
66
|
-
if (setting.builder) {
|
|
67
|
-
merged.builder = { ...merged.builder, ...setting.builder };
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
return merged;
|
|
71
|
-
}
|
|
72
|
-
/**
|
|
73
|
-
* Convert a settings object to a JSON string.
|
|
74
|
-
* Converts camelCase keys to snake_case to match the c2pa-rs settings format.
|
|
75
|
-
* @param settings The settings object
|
|
76
|
-
* @returns JSON string representation with snake_case keys
|
|
77
|
-
*/
|
|
78
|
-
export function settingsToJson(settings) {
|
|
79
|
-
return JSON.stringify(snakeCaseify(settings));
|
|
80
|
-
}
|
|
81
19
|
/**
|
|
82
20
|
* Load settings from a TOML or JSON file.
|
|
83
21
|
* @param filePath The path to the settings file
|
|
@@ -87,15 +25,3 @@ export async function loadSettingsFromFile(filePath) {
|
|
|
87
25
|
const content = await fs.readFile(filePath, "utf8");
|
|
88
26
|
return content;
|
|
89
27
|
}
|
|
90
|
-
/**
|
|
91
|
-
* Load settings from a URL.
|
|
92
|
-
* @param url The URL to fetch the settings from
|
|
93
|
-
* @returns Settings as a string
|
|
94
|
-
*/
|
|
95
|
-
export async function loadSettingsFromUrl(url) {
|
|
96
|
-
const res = await fetch(url);
|
|
97
|
-
if (!res.ok) {
|
|
98
|
-
throw new Error(`Failed to fetch settings from URL: ${res.status} ${res.statusText}`);
|
|
99
|
-
}
|
|
100
|
-
return await res.text();
|
|
101
|
-
}
|
package/dist/Settings.spec.js
CHANGED
|
@@ -3,189 +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 { createTrustSettings, createCawgTrustSettings, createVerifySettings, mergeSettings, settingsToJson, loadSettingsFromFile, loadSettingsFromUrl, } from "./Settings.js";
|
|
7
6
|
import * as fs from "fs-extra";
|
|
8
7
|
import * as path from "path";
|
|
9
8
|
import * as os from "os";
|
|
10
|
-
import {
|
|
11
|
-
// Mock node-fetch
|
|
12
|
-
vi.mock("node-fetch", () => ({
|
|
13
|
-
default: vi.fn(),
|
|
14
|
-
}));
|
|
9
|
+
import { loadSettingsFromFile } from "./Settings.js";
|
|
15
10
|
describe("Settings", () => {
|
|
16
|
-
it("creates trust settings", () => {
|
|
17
|
-
const trustConfig = {
|
|
18
|
-
verifyTrustList: true,
|
|
19
|
-
userAnchors: "test",
|
|
20
|
-
allowedList: "allowed",
|
|
21
|
-
};
|
|
22
|
-
const settings = createTrustSettings(trustConfig);
|
|
23
|
-
expect(settings.trust).toBeDefined();
|
|
24
|
-
expect(settings.trust?.verifyTrustList).toBe(true);
|
|
25
|
-
expect(settings.trust?.userAnchors).toBe("test");
|
|
26
|
-
expect(settings.trust?.allowedList).toBe("allowed");
|
|
27
|
-
});
|
|
28
|
-
it("creates CAWG trust settings", () => {
|
|
29
|
-
const trustConfig = {
|
|
30
|
-
verifyTrustList: false,
|
|
31
|
-
trustAnchors: "anchors",
|
|
32
|
-
};
|
|
33
|
-
const settings = createCawgTrustSettings(trustConfig);
|
|
34
|
-
expect(settings.cawgTrust).toBeDefined();
|
|
35
|
-
expect(settings.cawgTrust?.verifyTrustList).toBe(false);
|
|
36
|
-
expect(settings.cawgTrust?.trustAnchors).toBe("anchors");
|
|
37
|
-
});
|
|
38
|
-
it("creates verify settings", () => {
|
|
39
|
-
const verifyConfig = {
|
|
40
|
-
verifyAfterReading: true,
|
|
41
|
-
verifyAfterSign: false,
|
|
42
|
-
verifyTrust: true,
|
|
43
|
-
verifyTimestampTrust: false,
|
|
44
|
-
ocspFetch: true,
|
|
45
|
-
remoteManifestFetch: false,
|
|
46
|
-
skipIngredientConflictResolution: true,
|
|
47
|
-
strictV1Validation: false,
|
|
48
|
-
};
|
|
49
|
-
const settings = createVerifySettings(verifyConfig);
|
|
50
|
-
expect(settings.verify).toBeDefined();
|
|
51
|
-
expect(settings.verify?.verifyAfterReading).toBe(true);
|
|
52
|
-
expect(settings.verify?.verifyAfterSign).toBe(false);
|
|
53
|
-
expect(settings.verify?.verifyTrust).toBe(true);
|
|
54
|
-
expect(settings.verify?.ocspFetch).toBe(true);
|
|
55
|
-
});
|
|
56
|
-
it("creates verify settings with partial config", () => {
|
|
57
|
-
const settings = createVerifySettings({
|
|
58
|
-
verifyAfterReading: false,
|
|
59
|
-
});
|
|
60
|
-
expect(settings.verify).toBeDefined();
|
|
61
|
-
expect(settings.verify?.verifyAfterReading).toBe(false);
|
|
62
|
-
expect(settings.verify?.verifyAfterSign).toBeUndefined();
|
|
63
|
-
expect(settings.verify?.verifyTrust).toBeUndefined();
|
|
64
|
-
});
|
|
65
|
-
it("merges multiple settings", () => {
|
|
66
|
-
const trustSettings = createTrustSettings({
|
|
67
|
-
verifyTrustList: true,
|
|
68
|
-
userAnchors: "test",
|
|
69
|
-
});
|
|
70
|
-
const verifySettings = createVerifySettings({
|
|
71
|
-
verifyAfterReading: false,
|
|
72
|
-
verifyAfterSign: true,
|
|
73
|
-
verifyTrust: true,
|
|
74
|
-
verifyTimestampTrust: true,
|
|
75
|
-
ocspFetch: false,
|
|
76
|
-
remoteManifestFetch: true,
|
|
77
|
-
skipIngredientConflictResolution: false,
|
|
78
|
-
strictV1Validation: false,
|
|
79
|
-
});
|
|
80
|
-
const merged = mergeSettings(trustSettings, verifySettings);
|
|
81
|
-
expect(merged.trust).toBeDefined();
|
|
82
|
-
expect(merged.verify).toBeDefined();
|
|
83
|
-
expect(merged.trust?.verifyTrustList).toBe(true);
|
|
84
|
-
expect(merged.verify?.verifyAfterReading).toBe(false);
|
|
85
|
-
});
|
|
86
|
-
it("converts settings to JSON with snake_case keys", () => {
|
|
87
|
-
const settings = createVerifySettings({
|
|
88
|
-
verifyAfterReading: true,
|
|
89
|
-
verifyAfterSign: true,
|
|
90
|
-
verifyTrust: false,
|
|
91
|
-
verifyTimestampTrust: true,
|
|
92
|
-
ocspFetch: false,
|
|
93
|
-
remoteManifestFetch: true,
|
|
94
|
-
skipIngredientConflictResolution: false,
|
|
95
|
-
strictV1Validation: false,
|
|
96
|
-
});
|
|
97
|
-
const json = settingsToJson(settings);
|
|
98
|
-
expect(json).toContain("verify");
|
|
99
|
-
expect(json).toContain("verify_after_reading");
|
|
100
|
-
// Should be parseable with snake_case keys
|
|
101
|
-
const parsed = JSON.parse(json);
|
|
102
|
-
expect(parsed.verify.verify_after_reading).toBe(true);
|
|
103
|
-
});
|
|
104
|
-
it("does not include undefined values in trust settings JSON", () => {
|
|
105
|
-
const trustConfig = {
|
|
106
|
-
verifyTrustList: true,
|
|
107
|
-
};
|
|
108
|
-
const settings = createTrustSettings(trustConfig);
|
|
109
|
-
const json = settingsToJson(settings);
|
|
110
|
-
const parsed = JSON.parse(json);
|
|
111
|
-
expect(parsed.trust.verify_trust_list).toBe(true);
|
|
112
|
-
expect("user_anchors" in parsed.trust).toBe(false);
|
|
113
|
-
expect("trust_anchors" in parsed.trust).toBe(false);
|
|
114
|
-
expect("trust_config" in parsed.trust).toBe(false);
|
|
115
|
-
expect("allowed_list" in parsed.trust).toBe(false);
|
|
116
|
-
});
|
|
117
|
-
it("does not include undefined values in CAWG trust settings JSON", () => {
|
|
118
|
-
const trustConfig = {
|
|
119
|
-
verifyTrustList: false,
|
|
120
|
-
};
|
|
121
|
-
const settings = createCawgTrustSettings(trustConfig);
|
|
122
|
-
const json = settingsToJson(settings);
|
|
123
|
-
const parsed = JSON.parse(json);
|
|
124
|
-
expect(parsed.cawg_trust.verify_trust_list).toBe(false);
|
|
125
|
-
expect("user_anchors" in parsed.cawg_trust).toBe(false);
|
|
126
|
-
expect("trust_anchors" in parsed.cawg_trust).toBe(false);
|
|
127
|
-
});
|
|
128
|
-
it("does not include undefined values in verify settings JSON", () => {
|
|
129
|
-
const verifyConfig = {
|
|
130
|
-
verifyAfterReading: true,
|
|
131
|
-
verifyAfterSign: false,
|
|
132
|
-
};
|
|
133
|
-
const settings = createVerifySettings(verifyConfig);
|
|
134
|
-
const json = settingsToJson(settings);
|
|
135
|
-
const parsed = JSON.parse(json);
|
|
136
|
-
expect(parsed.verify.verify_after_reading).toBe(true);
|
|
137
|
-
expect(parsed.verify.verify_after_sign).toBe(false);
|
|
138
|
-
expect("verify_trust" in parsed.verify).toBe(false);
|
|
139
|
-
expect("verify_timestamp_trust" in parsed.verify).toBe(false);
|
|
140
|
-
expect("ocsp_fetch" in parsed.verify).toBe(false);
|
|
141
|
-
expect("remote_manifest_fetch" in parsed.verify).toBe(false);
|
|
142
|
-
});
|
|
143
|
-
it("does not include undefined values when merging settings", () => {
|
|
144
|
-
const settings1 = {
|
|
145
|
-
trust: {
|
|
146
|
-
verifyTrustList: true,
|
|
147
|
-
userAnchors: "test",
|
|
148
|
-
},
|
|
149
|
-
};
|
|
150
|
-
const settings2 = {
|
|
151
|
-
trust: {
|
|
152
|
-
verifyTrustList: true,
|
|
153
|
-
allowedList: undefined,
|
|
154
|
-
},
|
|
155
|
-
verify: {
|
|
156
|
-
verifyAfterReading: false,
|
|
157
|
-
},
|
|
158
|
-
};
|
|
159
|
-
const merged = mergeSettings(settings1, settings2);
|
|
160
|
-
const json = settingsToJson(merged);
|
|
161
|
-
const parsed = JSON.parse(json);
|
|
162
|
-
expect(parsed.trust.verify_trust_list).toBe(true);
|
|
163
|
-
expect(parsed.trust.user_anchors).toBe("test");
|
|
164
|
-
expect("allowed_list" in parsed.trust).toBe(false);
|
|
165
|
-
expect(parsed.verify.verify_after_reading).toBe(false);
|
|
166
|
-
});
|
|
167
|
-
it("merges settings with later values overriding earlier ones", () => {
|
|
168
|
-
const settings1 = createVerifySettings({
|
|
169
|
-
verifyAfterReading: true,
|
|
170
|
-
verifyAfterSign: true,
|
|
171
|
-
verifyTrust: false,
|
|
172
|
-
verifyTimestampTrust: true,
|
|
173
|
-
ocspFetch: false,
|
|
174
|
-
remoteManifestFetch: true,
|
|
175
|
-
skipIngredientConflictResolution: false,
|
|
176
|
-
strictV1Validation: false,
|
|
177
|
-
});
|
|
178
|
-
const settings2 = {
|
|
179
|
-
verify: {
|
|
180
|
-
verifyTrust: true,
|
|
181
|
-
ocspFetch: true,
|
|
182
|
-
},
|
|
183
|
-
};
|
|
184
|
-
const merged = mergeSettings(settings1, settings2);
|
|
185
|
-
expect(merged.verify?.verifyAfterReading).toBe(true); // from settings1
|
|
186
|
-
expect(merged.verify?.verifyTrust).toBe(true); // overridden by settings2
|
|
187
|
-
expect(merged.verify?.ocspFetch).toBe(true); // overridden by settings2
|
|
188
|
-
});
|
|
189
11
|
describe("loadSettingsFromFile", () => {
|
|
190
12
|
let tempDir;
|
|
191
13
|
beforeEach(async () => {
|
|
@@ -224,38 +46,4 @@ verify_after_sign = false`;
|
|
|
224
46
|
await expect(loadSettingsFromFile(filePath)).rejects.toThrow();
|
|
225
47
|
});
|
|
226
48
|
});
|
|
227
|
-
describe("loadSettingsFromUrl", () => {
|
|
228
|
-
beforeEach(() => {
|
|
229
|
-
vi.clearAllMocks();
|
|
230
|
-
});
|
|
231
|
-
it("loads settings from a URL", async () => {
|
|
232
|
-
const mockSettings = JSON.stringify({
|
|
233
|
-
verify: {
|
|
234
|
-
verify_after_reading: true,
|
|
235
|
-
},
|
|
236
|
-
});
|
|
237
|
-
const fetch = (await import("node-fetch")).default;
|
|
238
|
-
vi.mocked(fetch).mockResolvedValue({
|
|
239
|
-
ok: true,
|
|
240
|
-
text: async () => mockSettings,
|
|
241
|
-
});
|
|
242
|
-
const loaded = await loadSettingsFromUrl("https://example.com/settings.json");
|
|
243
|
-
expect(loaded).toBe(mockSettings);
|
|
244
|
-
expect(fetch).toHaveBeenCalledWith("https://example.com/settings.json");
|
|
245
|
-
});
|
|
246
|
-
it("throws error for failed fetch", async () => {
|
|
247
|
-
const fetch = (await import("node-fetch")).default;
|
|
248
|
-
vi.mocked(fetch).mockResolvedValue({
|
|
249
|
-
ok: false,
|
|
250
|
-
status: 404,
|
|
251
|
-
statusText: "Not Found",
|
|
252
|
-
});
|
|
253
|
-
await expect(loadSettingsFromUrl("https://example.com/missing.json")).rejects.toThrow("Failed to fetch settings from URL: 404 Not Found");
|
|
254
|
-
});
|
|
255
|
-
it("throws error for network failure", async () => {
|
|
256
|
-
const fetch = (await import("node-fetch")).default;
|
|
257
|
-
vi.mocked(fetch).mockRejectedValue(new Error("Network error"));
|
|
258
|
-
await expect(loadSettingsFromUrl("https://example.com/settings.json")).rejects.toThrow("Network error");
|
|
259
|
-
});
|
|
260
|
-
});
|
|
261
49
|
});
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// Copyright 2026 Adobe. All rights reserved.
|
|
2
|
+
// This file is licensed to you under the Apache License,
|
|
3
|
+
// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
|
4
|
+
// or the MIT license (http://opensource.org/licenses/MIT),
|
|
5
|
+
// at your option.
|
|
6
|
+
// Unless required by applicable law or agreed to in writing,
|
|
7
|
+
// this software is distributed on an "AS IS" BASIS, WITHOUT
|
|
8
|
+
// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
|
|
9
|
+
// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
|
|
10
|
+
// specific language governing permissions and limitations under
|
|
11
|
+
// each license.
|
|
12
|
+
import * as fs from "fs-extra";
|
|
13
|
+
import { validateAssetSize } from "@contentauth/c2pa-utilities";
|
|
14
|
+
// c2pa-node runs server-side, so it can reasonably support larger assets than c2pa-web,
|
|
15
|
+
// and may be less resource-constrained in comparison.
|
|
16
|
+
export const MAX_SIZE_IN_BYTES = 10 * 10 ** 9; // 10 GB
|
|
17
|
+
/**
|
|
18
|
+
* Validates a {@link SourceAsset}'s size before it's handed to the native reader.
|
|
19
|
+
*
|
|
20
|
+
* For a `FileAsset`, this rejects an oversized file before it's read into memory.
|
|
21
|
+
* For a `SourceBufferAsset`, the buffer is already fully allocated by the time this runs,
|
|
22
|
+
* so the memory cost isn't prevented, only reader construction is. Prefer `path`
|
|
23
|
+
* for large or untrusted assets.
|
|
24
|
+
*
|
|
25
|
+
* @throws Error if reading the `FileAsset` fails.
|
|
26
|
+
* @throws {AssetTooLargeError} If `sizeInBytes` exceeds the resolved limit.
|
|
27
|
+
*/
|
|
28
|
+
export async function validateSourceAssetSize(asset) {
|
|
29
|
+
if ("buffer" in asset) {
|
|
30
|
+
validateAssetSize(asset.buffer.length, MAX_SIZE_IN_BYTES);
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
const { size } = await fs.stat(asset.path);
|
|
34
|
+
validateAssetSize(size, MAX_SIZE_IN_BYTES);
|
|
35
|
+
}
|
package/dist/index.js
CHANGED
package/dist/index.node
CHANGED
|
Binary file
|
package/dist/types/Builder.d.ts
CHANGED
|
@@ -25,5 +25,6 @@ export declare class Builder implements BuilderInterface {
|
|
|
25
25
|
filterActions(keep: (action: Action) => boolean): void;
|
|
26
26
|
filterIngredients(rescue: (ingredient: Ingredient, provenance: ManifestStore | null) => boolean): void;
|
|
27
27
|
filterActionsAndIngredients(keepAction: (action: Action) => boolean, rescueIngredient: (ingredient: Ingredient, provenance: ManifestStore | null) => boolean): void;
|
|
28
|
+
updateActions(transform: (actions: Action[]) => Action[]): void;
|
|
28
29
|
getHandle(): NeonBuilderHandle;
|
|
29
30
|
}
|
package/dist/types/Settings.d.ts
CHANGED
|
@@ -1,45 +1,12 @@
|
|
|
1
|
-
import type { TrustConfig, VerifyConfig, SettingsContext } from "./types.d.ts";
|
|
2
1
|
/**
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
2
|
+
* This file contains only Settings functions that are unique to the Node SDK.
|
|
3
|
+
*
|
|
4
|
+
* Shared Settings-related functions and types can be found in `c2pa-utilities`,
|
|
5
|
+
* and are re-exported by `c2pa-node` (see `index.ts`) for convenience.
|
|
6
6
|
*/
|
|
7
|
-
export declare function createTrustSettings(trustConfig: TrustConfig): SettingsContext;
|
|
8
|
-
/**
|
|
9
|
-
* Create a settings object with CAWG trust configuration.
|
|
10
|
-
* @param trustConfig The CAWG trust configuration
|
|
11
|
-
* @returns Settings object that can be passed to Reader/Builder
|
|
12
|
-
*/
|
|
13
|
-
export declare function createCawgTrustSettings(trustConfig: TrustConfig): SettingsContext;
|
|
14
|
-
/**
|
|
15
|
-
* Create a settings object with verify configuration.
|
|
16
|
-
* @param verifyConfig The verify configuration
|
|
17
|
-
* @returns Settings object that can be passed to Reader/Builder
|
|
18
|
-
*/
|
|
19
|
-
export declare function createVerifySettings(verifyConfig: VerifyConfig): SettingsContext;
|
|
20
|
-
/**
|
|
21
|
-
* Merge multiple settings objects into one.
|
|
22
|
-
* Later settings override earlier ones.
|
|
23
|
-
* @param settings Settings objects to merge
|
|
24
|
-
* @returns Merged settings object
|
|
25
|
-
*/
|
|
26
|
-
export declare function mergeSettings(...settings: SettingsContext[]): SettingsContext;
|
|
27
|
-
/**
|
|
28
|
-
* Convert a settings object to a JSON string.
|
|
29
|
-
* Converts camelCase keys to snake_case to match the c2pa-rs settings format.
|
|
30
|
-
* @param settings The settings object
|
|
31
|
-
* @returns JSON string representation with snake_case keys
|
|
32
|
-
*/
|
|
33
|
-
export declare function settingsToJson(settings: SettingsContext): string;
|
|
34
7
|
/**
|
|
35
8
|
* Load settings from a TOML or JSON file.
|
|
36
9
|
* @param filePath The path to the settings file
|
|
37
10
|
* @returns Settings as a string (TOML or JSON depending on file extension)
|
|
38
11
|
*/
|
|
39
12
|
export declare function loadSettingsFromFile(filePath: string): Promise<string>;
|
|
40
|
-
/**
|
|
41
|
-
* Load settings from a URL.
|
|
42
|
-
* @param url The URL to fetch the settings from
|
|
43
|
-
* @returns Settings as a string
|
|
44
|
-
*/
|
|
45
|
-
export declare function loadSettingsFromUrl(url: string): Promise<string>;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { SourceAsset } from "./types.d.ts";
|
|
2
|
+
export declare const MAX_SIZE_IN_BYTES: number;
|
|
3
|
+
/**
|
|
4
|
+
* Validates a {@link SourceAsset}'s size before it's handed to the native reader.
|
|
5
|
+
*
|
|
6
|
+
* For a `FileAsset`, this rejects an oversized file before it's read into memory.
|
|
7
|
+
* For a `SourceBufferAsset`, the buffer is already fully allocated by the time this runs,
|
|
8
|
+
* so the memory cost isn't prevented, only reader construction is. Prefer `path`
|
|
9
|
+
* for large or untrusted assets.
|
|
10
|
+
*
|
|
11
|
+
* @throws Error if reading the `FileAsset` fails.
|
|
12
|
+
* @throws {AssetTooLargeError} If `sizeInBytes` exceeds the resolved limit.
|
|
13
|
+
*/
|
|
14
|
+
export declare function validateSourceAssetSize(asset: SourceAsset): Promise<void>;
|
package/dist/types/index.d.ts
CHANGED
package/dist/types/types.d.ts
CHANGED
|
@@ -19,26 +19,18 @@ import type {
|
|
|
19
19
|
C2paReason,
|
|
20
20
|
Ingredient,
|
|
21
21
|
Manifest,
|
|
22
|
+
ManifestAssertionKind,
|
|
22
23
|
ManifestStore,
|
|
23
24
|
} from "@contentauth/c2pa-types";
|
|
25
|
+
import type { SigningAlg } from "@contentauth/c2pa-utilities";
|
|
24
26
|
|
|
25
|
-
export type {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
* > All digital signatures that are stored in a C2PA Manifest shall > be generated using one of the digital signature algorithms and > key types listed as described in this section
|
|
33
|
-
*/
|
|
34
|
-
export type SigningAlg =
|
|
35
|
-
| "es256"
|
|
36
|
-
| "es384"
|
|
37
|
-
| "es512"
|
|
38
|
-
| "ps256"
|
|
39
|
-
| "ps384"
|
|
40
|
-
| "ps512"
|
|
41
|
-
| "ed25519";
|
|
27
|
+
export type {
|
|
28
|
+
Action,
|
|
29
|
+
C2paReason,
|
|
30
|
+
Ingredient,
|
|
31
|
+
ManifestAssertionKind,
|
|
32
|
+
} from "@contentauth/c2pa-types";
|
|
33
|
+
export type { SigningAlg } from "@contentauth/c2pa-utilities";
|
|
42
34
|
|
|
43
35
|
export type ClaimVersion = 1 | 2;
|
|
44
36
|
|
|
@@ -64,8 +56,6 @@ export type TrustmarkVariant =
|
|
|
64
56
|
// Quality Trustmark model
|
|
65
57
|
| "Q";
|
|
66
58
|
|
|
67
|
-
export type ManifestAssertionKind = "Cbor" | "Json" | "Binary" | "Uri";
|
|
68
|
-
|
|
69
59
|
/**
|
|
70
60
|
* A buffer for the source asset
|
|
71
61
|
*/
|
|
@@ -195,7 +185,9 @@ export interface HashedUri {
|
|
|
195
185
|
export type C2paSettings = string | object;
|
|
196
186
|
|
|
197
187
|
export interface BuilderInterface {
|
|
198
|
-
/**
|
|
188
|
+
/**
|
|
189
|
+
* An intent lets the API know what kind of manifest to create.
|
|
190
|
+
*
|
|
199
191
|
* Intents are `Create`, `Edit`, or `Update`.
|
|
200
192
|
* This allows the API to check that you are doing the right thing.
|
|
201
193
|
* It can also do things for you, like add parent ingredients from the source asset
|
|
@@ -399,6 +391,25 @@ export interface BuilderInterface {
|
|
|
399
391
|
) => boolean,
|
|
400
392
|
): void;
|
|
401
393
|
|
|
394
|
+
/**
|
|
395
|
+
* Replaces the actions in the `c2pa.actions`/`c2pa.actions.v2` assertions.
|
|
396
|
+
*
|
|
397
|
+
* A manifest can carry more than one actions assertion (the created-list and
|
|
398
|
+
* gathered-list entries are distinct assertions). `transform` is therefore
|
|
399
|
+
* invoked once per actions assertion, in positional order, with that
|
|
400
|
+
* assertion's own actions.
|
|
401
|
+
*
|
|
402
|
+
* A no-op if there is no actions assertion. Use `addAction` for those.
|
|
403
|
+
*
|
|
404
|
+
* The returned list is written back as is.
|
|
405
|
+
* `transform` can therefore produce an actions array that fails
|
|
406
|
+
* validation at signing time, for example by removing the inception action
|
|
407
|
+
* (`c2pa.created`/`c2pa.opened`) or moving it out of first position.
|
|
408
|
+
*
|
|
409
|
+
* @param transform Receives one assertion's actions and returns its full replacement list.
|
|
410
|
+
*/
|
|
411
|
+
updateActions(transform: (actions: Action[]) => Action[]): void;
|
|
412
|
+
|
|
402
413
|
/**
|
|
403
414
|
* Get the internal handle for use with Neon bindings
|
|
404
415
|
*/
|
|
@@ -497,62 +508,26 @@ export interface TrustmarkConfig {
|
|
|
497
508
|
modelPath?: string;
|
|
498
509
|
}
|
|
499
510
|
|
|
511
|
+
import type {
|
|
512
|
+
Settings as _Settings,
|
|
513
|
+
TrustSettings as _TrustSettings,
|
|
514
|
+
VerifySettings as _VerifySettings
|
|
515
|
+
} from "@contentauth/c2pa-utilities";
|
|
516
|
+
|
|
500
517
|
/**
|
|
501
|
-
*
|
|
502
|
-
*
|
|
518
|
+
* @deprecated Use `TrustSettings` instead, which encapsulates both normal trust and CAWG trust settings.
|
|
519
|
+
* Kept as an alias for backwards compatibility.
|
|
503
520
|
*/
|
|
504
|
-
export
|
|
505
|
-
/** Whether to verify against the trust list */
|
|
506
|
-
verifyTrustList: boolean;
|
|
507
|
-
/** User-provided trust anchors (PEM format or base64-encoded certificate hashes) */
|
|
508
|
-
userAnchors?: string;
|
|
509
|
-
/** Trust anchors for validation (PEM format or base64-encoded certificate hashes) */
|
|
510
|
-
trustAnchors?: string;
|
|
511
|
-
/** Trust configuration file path */
|
|
512
|
-
trustConfig?: string;
|
|
513
|
-
/** Allowed list of certificates (PEM format or base64-encoded certificate hashes) */
|
|
514
|
-
allowedList?: string;
|
|
515
|
-
}
|
|
521
|
+
export type TrustConfig = _TrustSettings;
|
|
516
522
|
|
|
517
523
|
/**
|
|
518
|
-
*
|
|
519
|
-
*
|
|
524
|
+
* @deprecated Use `VerifySettings` instead.
|
|
525
|
+
* Kept as an alias for backwards compatibility.
|
|
520
526
|
*/
|
|
521
|
-
export
|
|
522
|
-
/** Whether to verify after reading a manifest */
|
|
523
|
-
verifyAfterReading?: boolean;
|
|
524
|
-
/** Whether to verify after signing a manifest */
|
|
525
|
-
verifyAfterSign?: boolean;
|
|
526
|
-
/** Whether to verify trust during validation */
|
|
527
|
-
verifyTrust?: boolean;
|
|
528
|
-
/** Whether to verify timestamp trust */
|
|
529
|
-
verifyTimestampTrust?: boolean;
|
|
530
|
-
/** Whether to fetch OCSP responses */
|
|
531
|
-
ocspFetch?: boolean;
|
|
532
|
-
/** Whether to fetch remote manifests */
|
|
533
|
-
remoteManifestFetch?: boolean;
|
|
534
|
-
/** Whether to skip ingredient conflict resolution */
|
|
535
|
-
skipIngredientConflictResolution?: boolean;
|
|
536
|
-
/** Whether to use strict v1 validation */
|
|
537
|
-
strictV1Validation?: boolean;
|
|
538
|
-
}
|
|
527
|
+
export type VerifyConfig = _VerifySettings;
|
|
539
528
|
|
|
540
529
|
/**
|
|
541
|
-
*
|
|
542
|
-
*
|
|
543
|
-
* Uses snake_case internally to match the c2pa-rs settings format.
|
|
530
|
+
* @deprecated Use `Settings` instead.
|
|
531
|
+
* Kept as an alias for backwards compatibility.
|
|
544
532
|
*/
|
|
545
|
-
export
|
|
546
|
-
/** C2PA trust configuration */
|
|
547
|
-
trust?: TrustConfig;
|
|
548
|
-
/** CAWG trust configuration */
|
|
549
|
-
cawgTrust?: TrustConfig;
|
|
550
|
-
/** Verification configuration */
|
|
551
|
-
verify?: VerifyConfig;
|
|
552
|
-
/** Builder configuration */
|
|
553
|
-
builder?: {
|
|
554
|
-
thumbnail?: {
|
|
555
|
-
enabled?: boolean;
|
|
556
|
-
};
|
|
557
|
-
};
|
|
558
|
-
}
|
|
533
|
+
export type SettingsContext = _Settings;
|
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.
|
|
8
|
+
"version": "0.9.0",
|
|
9
9
|
"description": "Node.js bindings for C2PA",
|
|
10
10
|
"main": "dist/index.js",
|
|
11
11
|
"type": "module",
|
|
@@ -45,8 +45,7 @@
|
|
|
45
45
|
"typedoc": "^0.28.19",
|
|
46
46
|
"typedoc-plugin-markdown": "^4.11.0",
|
|
47
47
|
"typescript": "^5.9.3",
|
|
48
|
-
"vitest": "^3.2.4"
|
|
49
|
-
"@contentauth/c2pa-types": "0.7.3"
|
|
48
|
+
"vitest": "^3.2.4"
|
|
50
49
|
},
|
|
51
50
|
"keywords": [
|
|
52
51
|
"c2pa"
|
|
@@ -64,7 +63,9 @@
|
|
|
64
63
|
"node-fetch": "^3.3.2",
|
|
65
64
|
"pkg-dir": "^8.0.0",
|
|
66
65
|
"pretty-bytes": "^6.1.1",
|
|
67
|
-
"unzipper": "^0.10.14"
|
|
66
|
+
"unzipper": "^0.10.14",
|
|
67
|
+
"@contentauth/c2pa-types": "0.7.3",
|
|
68
|
+
"@contentauth/c2pa-utilities": "0.2.0"
|
|
68
69
|
},
|
|
69
70
|
"nx": {
|
|
70
71
|
"tags": [
|
package/src/lib.rs
CHANGED
|
@@ -97,6 +97,10 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> {
|
|
|
97
97
|
"builderFilterActionsAndIngredients",
|
|
98
98
|
neon_builder::NeonBuilder::filter_actions_and_ingredients,
|
|
99
99
|
)?;
|
|
100
|
+
cx.export_function(
|
|
101
|
+
"builderUpdateActions",
|
|
102
|
+
neon_builder::NeonBuilder::update_actions,
|
|
103
|
+
)?;
|
|
100
104
|
|
|
101
105
|
// Reader
|
|
102
106
|
cx.export_function("readerNew", neon_reader::NeonReader::new)?;
|
package/src/neon_builder.rs
CHANGED
|
@@ -18,7 +18,7 @@ use crate::neon_reader::NeonReader;
|
|
|
18
18
|
use crate::neon_signer::{CallbackSignerConfig, NeonCallbackSigner, NeonLocalSigner};
|
|
19
19
|
use crate::runtime::runtime;
|
|
20
20
|
use crate::utils::parse_settings;
|
|
21
|
-
use c2pa::{assertions::Action, Builder, BuilderIntent, Ingredient, Reader};
|
|
21
|
+
use c2pa::{assertions::{Action, Actions}, Builder, BuilderIntent, Ingredient, Reader};
|
|
22
22
|
use neon::context::Context as NeonContext;
|
|
23
23
|
use neon::prelude::*;
|
|
24
24
|
use neon_serde4;
|
|
@@ -676,6 +676,100 @@ impl NeonBuilder {
|
|
|
676
676
|
Ok(cx.undefined())
|
|
677
677
|
}
|
|
678
678
|
|
|
679
|
+
/// Replaces the actions in the `c2pa.actions`/`c2pa.actions.v2` assertions.
|
|
680
|
+
/// `softwareAgents`/`allActionsIncluded`/`templates`/`metadata` are preserved as-is.
|
|
681
|
+
///
|
|
682
|
+
/// A manifest can carry more than one actions assertion (the created-list and gathered-list
|
|
683
|
+
/// entries are distinct assertions). `transform` is invoked once per actions assertion,
|
|
684
|
+
/// in positional order, with that assertion's own actions. It return value
|
|
685
|
+
/// replaces only that assertion's actions.
|
|
686
|
+
/// No-op if there is no actions assertion. Use `add_action` for those.
|
|
687
|
+
///
|
|
688
|
+
/// If `transform` throws or its return value doesn't deserialize into an action list, the
|
|
689
|
+
/// exception is surfaced to the caller and the builder is left unchanged. The same applies
|
|
690
|
+
/// when an existing actions assertion is present but malformed. All fallible work runs
|
|
691
|
+
/// before any mutation, so a failure never leaves a partially-rewritten builder.
|
|
692
|
+
///
|
|
693
|
+
/// An assertion whose `transform` returns an empty list is dropped rather than written as an
|
|
694
|
+
/// invalid empty actions array, matching `filter_actions`.
|
|
695
|
+
///
|
|
696
|
+
/// The returned list is written back verbatim: it is not validated or reordered, and unlike
|
|
697
|
+
/// [`Self::filter_actions`] the inception action is not force-kept. A `transform` that drops
|
|
698
|
+
/// `c2pa.created`/`c2pa.opened` or moves it out of first position can produce an actions
|
|
699
|
+
/// array that fails validation at signing time.
|
|
700
|
+
///
|
|
701
|
+
/// # Deadlock
|
|
702
|
+
/// The builder's lock is held for the whole call, so `transform` must not call back into the
|
|
703
|
+
/// same builder, for example `getManifestDefinition` or a filter: the lock is not re-entrant
|
|
704
|
+
/// and re-entry would deadlock.
|
|
705
|
+
pub fn update_actions(mut cx: FunctionContext) -> JsResult<JsUndefined> {
|
|
706
|
+
let rt = runtime();
|
|
707
|
+
let this = cx.this::<JsBox<Self>>()?;
|
|
708
|
+
let transform = cx.argument::<JsFunction>(0)?;
|
|
709
|
+
let mut builder = rt.block_on(async { this.builder.lock().await });
|
|
710
|
+
|
|
711
|
+
// Every actions assertion, in positional order.
|
|
712
|
+
let positions: Vec<usize> = builder
|
|
713
|
+
.definition
|
|
714
|
+
.assertions
|
|
715
|
+
.iter()
|
|
716
|
+
.enumerate()
|
|
717
|
+
.filter(|(_, a)| a.label.starts_with(Actions::LABEL))
|
|
718
|
+
.map(|(i, _)| i)
|
|
719
|
+
.collect();
|
|
720
|
+
|
|
721
|
+
// Decode every assertion up front.
|
|
722
|
+
// The roundtrip is so we can access what we need to without the direct type access.
|
|
723
|
+
let mut decoded: Vec<(usize, Actions)> = Vec::with_capacity(positions.len());
|
|
724
|
+
for pos in positions {
|
|
725
|
+
let value = serde_json::to_value(&builder.definition.assertions[pos].data)
|
|
726
|
+
.or_else(|err| cx.throw_error(err.to_string()))?;
|
|
727
|
+
let actions: Actions =
|
|
728
|
+
serde_json::from_value(value).or_else(|err| cx.throw_error(err.to_string()))?;
|
|
729
|
+
decoded.push((pos, actions));
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
// Run the transform for every assertion before mutating anything...
|
|
733
|
+
let mut rewritten: Vec<(usize, Option<serde_json::Value>)> =
|
|
734
|
+
Vec::with_capacity(decoded.len());
|
|
735
|
+
for (pos, mut actions) in decoded {
|
|
736
|
+
let js_actions = neon_serde4::to_value(&mut cx, &actions.actions)
|
|
737
|
+
.or_else(|err| cx.throw_error(err.to_string()))?;
|
|
738
|
+
let undefined = cx.undefined();
|
|
739
|
+
let result = transform.call(&mut cx, undefined, [js_actions])?;
|
|
740
|
+
let updated_actions: Vec<Action> = neon_serde4::from_value(&mut cx, result)
|
|
741
|
+
.or_else(|err| cx.throw_error(err.to_string()))?;
|
|
742
|
+
|
|
743
|
+
if updated_actions.is_empty() {
|
|
744
|
+
rewritten.push((pos, None));
|
|
745
|
+
continue;
|
|
746
|
+
}
|
|
747
|
+
actions.actions = updated_actions;
|
|
748
|
+
let value =
|
|
749
|
+
serde_json::to_value(&actions).or_else(|err| cx.throw_error(err.to_string()))?;
|
|
750
|
+
rewritten.push((pos, Some(value)));
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
// Mutate in place.
|
|
754
|
+
let mut emptied: Vec<usize> = Vec::new();
|
|
755
|
+
for (pos, value) in rewritten {
|
|
756
|
+
match value {
|
|
757
|
+
Some(value) => {
|
|
758
|
+
let data = serde_json::from_value(value)
|
|
759
|
+
.or_else(|err| cx.throw_error(err.to_string()))?;
|
|
760
|
+
builder.definition.assertions[pos].data = data;
|
|
761
|
+
}
|
|
762
|
+
None => emptied.push(pos),
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
// Remove emptied assertions from the back so earlier indices stay valid.
|
|
766
|
+
for pos in emptied.into_iter().rev() {
|
|
767
|
+
builder.definition.assertions.remove(pos);
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
Ok(cx.undefined())
|
|
771
|
+
}
|
|
772
|
+
|
|
679
773
|
/// Retains ingredients, rescuing an otherwise-orphaned ingredient when the JS `rescue`
|
|
680
774
|
/// predicate returns true for it. Referenced and `parentOf` ingredients are always kept,
|
|
681
775
|
/// per `Builder::filter_ingredients`.
|