@contentauth/c2pa-node 0.8.1 → 0.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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
  }
@@ -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/index.node CHANGED
Binary file
@@ -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
  }
@@ -399,6 +399,25 @@ export interface BuilderInterface {
399
399
  ) => boolean,
400
400
  ): void;
401
401
 
402
+ /**
403
+ * Replaces the actions in the `c2pa.actions`/`c2pa.actions.v2` assertions.
404
+ *
405
+ * A manifest can carry more than one actions assertion (the created-list and
406
+ * gathered-list entries are distinct assertions). `transform` is therefore
407
+ * invoked once per actions assertion, in positional order, with that
408
+ * assertion's own actions.
409
+ *
410
+ * A no-op if there is no actions assertion. Use `addAction` for those.
411
+ *
412
+ * The returned list is written back as is.
413
+ * `transform` can therefore produce an actions array that fails
414
+ * validation at signing time, for example by removing the inception action
415
+ * (`c2pa.created`/`c2pa.opened`) or moving it out of first position.
416
+ *
417
+ * @param transform Receives one assertion's actions and returns its full replacement list.
418
+ */
419
+ updateActions(transform: (actions: Action[]) => Action[]): void;
420
+
402
421
  /**
403
422
  * Get the internal handle for use with Neon bindings
404
423
  */
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.1",
8
+ "version": "0.8.3",
9
9
  "description": "Node.js bindings for C2PA",
10
10
  "main": "dist/index.js",
11
11
  "type": "module",
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)?;
@@ -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`.