@contentauth/c2pa-node 0.7.0 → 0.8.1

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
@@ -30,7 +30,7 @@ reqwest = { version = "0.12.2", default-features = false, features = [
30
30
  ] }
31
31
  serde = { version = "1.0.203", features = ["derive"] }
32
32
  serde_bytes = "0.11.15"
33
- serde_json = "1.0.145"
33
+ serde_json = "1.0.150"
34
34
  toml = "0.8"
35
35
  thiserror = "1.0.61"
36
36
  tokio = { version = "1.43.0", features = ["rt-multi-thread"] }
package/dist/Builder.js CHANGED
@@ -155,6 +155,9 @@ export class Builder {
155
155
  filterIngredients(rescue) {
156
156
  getNeonBinary().builderFilterIngredients.call(this.builder, rescue);
157
157
  }
158
+ filterActionsAndIngredients(keepAction, rescueIngredient) {
159
+ getNeonBinary().builderFilterActionsAndIngredients.call(this.builder, keepAction, rescueIngredient);
160
+ }
158
161
  getHandle() {
159
162
  return this.builder;
160
163
  }
@@ -142,6 +142,7 @@ describe("Builder", () => {
142
142
  beforeEach(() => {
143
143
  builder = Builder.withJson(manifestDefinition);
144
144
  builder.updateManifestProperty("claim_version", 2);
145
+ builder.setIntent("edit");
145
146
  });
146
147
  beforeEach(async () => {
147
148
  // Add ingredients and resources after builder is initialized
@@ -485,6 +486,9 @@ describe("Builder", () => {
485
486
  instance_id: "thumb-step1-1234",
486
487
  thumbnail: { format: "image/jpeg", identifier: "thumbnail.jpg" },
487
488
  });
489
+ step1Builder.setIntent({
490
+ create: "http://c2pa.org/digitalsourcetype/empty",
491
+ });
488
492
  await step1Builder.addResource("thumbnail.jpg", {
489
493
  mimeType: "image/jpeg",
490
494
  buffer: testThumbnail,
@@ -558,6 +562,9 @@ describe("Builder", () => {
558
562
  },
559
563
  ],
560
564
  });
565
+ step1Builder.setIntent({
566
+ create: "http://c2pa.org/digitalsourcetype/empty",
567
+ });
561
568
  const step1Dest = { buffer: null };
562
569
  await step1Builder.signAsync(signer, source, step1Dest);
563
570
  const step1Asset = {
@@ -688,6 +695,7 @@ describe("Builder", () => {
688
695
  resources: { resources: {} },
689
696
  };
690
697
  const builder = Builder.withJson(simpleManifestDefinition);
698
+ builder.setIntent({ create: "http://c2pa.org/digitalsourcetype/empty" });
691
699
  // Add an action using addAction method
692
700
  // The action needs to be a structured object matching the c2pa Action type
693
701
  const actionJson = JSON.stringify({
@@ -780,6 +788,7 @@ describe("Builder", () => {
780
788
  expect(reader).not.toBeNull();
781
789
  // Create a new builder and add ingredient from the reader
782
790
  const builder2 = Builder.new();
791
+ builder2.setIntent("edit");
783
792
  const ingredient = builder2.addIngredientFromReader(reader);
784
793
  expect(ingredient).toBeDefined();
785
794
  // Verify the ingredient was added to the builder
@@ -911,5 +920,69 @@ describe("Builder", () => {
911
920
  throw new Error("ingredient boom");
912
921
  })).toThrow("ingredient boom");
913
922
  });
923
+ it("filterActionsAndIngredients rescues an edited action for a kept ingredient", () => {
924
+ const builder = Builder.withJson({
925
+ claim_generator_info: [{ name: "c2pa_test", version: "1.0.0" }],
926
+ title: "Test_FilterActionsAndIngredients",
927
+ format: "image/jpeg",
928
+ ingredients: [],
929
+ assertions: [
930
+ {
931
+ label: "c2pa.actions",
932
+ data: {
933
+ actions: [
934
+ {
935
+ action: "c2pa.created",
936
+ digitalSourceType: "http://c2pa.org/digitalsourcetype/empty",
937
+ },
938
+ {
939
+ action: "c2pa.edited",
940
+ parameters: { ingredientIds: ["my-1"] },
941
+ },
942
+ ],
943
+ },
944
+ },
945
+ ],
946
+ resources: { resources: {} },
947
+ });
948
+ builder.addIngredient(JSON.stringify({
949
+ title: "my-ingredient",
950
+ format: "image/jpeg",
951
+ instance_id: "my-1",
952
+ relationship: "inputTo",
953
+ }));
954
+ // The action predicate alone would drop c2pa.edited; the ingredient predicate alone
955
+ // would rescue the ingredient. filterActionsAndIngredients keeps both together.
956
+ builder.filterActionsAndIngredients((action) => action.action !== "c2pa.edited", (ingredient) => ingredient.instance_id === "my-1");
957
+ const definition = builder.getManifestDefinition();
958
+ const actionsAssertion = definition.assertions.find((a) => a.label.startsWith("c2pa.actions"));
959
+ const names = actionsAssertion.data.actions.map((a) => a.action);
960
+ expect(names).toContain("c2pa.created");
961
+ expect(names).toContain("c2pa.edited");
962
+ expect(definition.ingredients ?? []).toHaveLength(1);
963
+ });
964
+ it("filterActionsAndIngredients drops unreferenced and unrescued", () => {
965
+ const builder = Builder.withJson(actionsManifest());
966
+ builder.addIngredient(JSON.stringify({
967
+ title: "orphan",
968
+ format: "image/jpeg",
969
+ instance_id: "orphan-1",
970
+ relationship: "componentOf",
971
+ }));
972
+ builder.filterActionsAndIngredients((action) => action.action === "c2pa.edited", () => false);
973
+ const definition = builder.getManifestDefinition();
974
+ const actionsAssertion = definition.assertions.find((a) => a.label.startsWith("c2pa.actions"));
975
+ const names = actionsAssertion.data.actions.map((a) => a.action);
976
+ expect(names).toContain("c2pa.created");
977
+ expect(names).toContain("c2pa.edited");
978
+ expect(names).not.toContain("c2pa.color_adjustments");
979
+ expect(definition.ingredients ?? []).toHaveLength(0);
980
+ });
981
+ it("filterActionsAndIngredients surfaces an error thrown by either predicate", () => {
982
+ const builder = Builder.withJson(actionsManifest());
983
+ expect(() => builder.filterActionsAndIngredients(() => {
984
+ throw new Error("action predicate boom");
985
+ }, () => false)).toThrow("action predicate boom");
986
+ });
914
987
  });
915
988
  });
@@ -63,9 +63,7 @@ describe("IdentityAssertionBuilder", () => {
63
63
  actions: [
64
64
  {
65
65
  action: "c2pa.created",
66
- parameters: {
67
- digitalSourceType: "http://cv.iptc.org/newscodes/digitalsourcetype/digitalCapture",
68
- },
66
+ digitalSourceType: "http://cv.iptc.org/newscodes/digitalsourcetype/digitalCapture",
69
67
  },
70
68
  ],
71
69
  },
@@ -122,6 +122,7 @@ describe("CallbackSigner", () => {
122
122
  resources: { resources: {} },
123
123
  };
124
124
  const builder = Builder.withJson(manifestDefinition);
125
+ builder.setIntent({ create: "http://c2pa.org/digitalsourcetype/empty" });
125
126
  const source = {
126
127
  buffer: await fs.readFile("./tests/fixtures/CA.jpg"),
127
128
  mimeType: "image/jpeg",
package/dist/index.node CHANGED
Binary file
@@ -24,5 +24,6 @@ export declare class Builder implements BuilderInterface {
24
24
  addRedaction(uri: string, reason: C2paReason): void;
25
25
  filterActions(keep: (action: Action) => boolean): void;
26
26
  filterIngredients(rescue: (ingredient: Ingredient, provenance: ManifestStore | null) => boolean): void;
27
+ filterActionsAndIngredients(keepAction: (action: Action) => boolean, rescueIngredient: (ingredient: Ingredient, provenance: ManifestStore | null) => boolean): void;
27
28
  getHandle(): NeonBuilderHandle;
28
29
  }
@@ -380,6 +380,25 @@ export interface BuilderInterface {
380
380
  ) => boolean,
381
381
  ): void;
382
382
 
383
+ /**
384
+ * Experimental.
385
+ * Retains actions and ingredients together.
386
+ *
387
+ * `rescueIngredient` is evaluated for every ingredient first; any action referencing an
388
+ * ingredient it would rescue is force-kept regardless of `keepAction`.
389
+ *
390
+ * @param keepAction The action is retained when the predicate returns true.
391
+ * @param rescueIngredient Can rescue an otherwise-orphaned ingredient and the action
392
+ * referencing it by returning true.
393
+ */
394
+ filterActionsAndIngredients(
395
+ keepAction: (action: Action) => boolean,
396
+ rescueIngredient: (
397
+ ingredient: Ingredient,
398
+ provenance: ManifestStore | null,
399
+ ) => boolean,
400
+ ): void;
401
+
383
402
  /**
384
403
  * Get the internal handle for use with Neon bindings
385
404
  */
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.7.0",
8
+ "version": "0.8.1",
9
9
  "description": "Node.js bindings for C2PA",
10
10
  "main": "dist/index.js",
11
11
  "type": "module",
@@ -46,7 +46,7 @@
46
46
  "typedoc-plugin-markdown": "^4.11.0",
47
47
  "typescript": "^5.9.3",
48
48
  "vitest": "^3.2.4",
49
- "@contentauth/c2pa-types": "0.7.2"
49
+ "@contentauth/c2pa-types": "0.7.3"
50
50
  },
51
51
  "keywords": [
52
52
  "c2pa"
@@ -25,6 +25,10 @@ const { promisify } = require('node:util');
25
25
  const pExec = promisify(exec);
26
26
 
27
27
  async function isInPnpmWorkspace(startDir) {
28
+ if (startDir.split(path.sep).includes('node_modules')) {
29
+ return false;
30
+ }
31
+
28
32
  let dir = path.dirname(startDir);
29
33
  while (true) {
30
34
  const parent = path.dirname(dir);
package/src/lib.rs CHANGED
@@ -93,6 +93,10 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> {
93
93
  "builderFilterIngredients",
94
94
  neon_builder::NeonBuilder::filter_ingredients,
95
95
  )?;
96
+ cx.export_function(
97
+ "builderFilterActionsAndIngredients",
98
+ neon_builder::NeonBuilder::filter_actions_and_ingredients,
99
+ )?;
96
100
 
97
101
  // Reader
98
102
  cx.export_function("readerNew", neon_reader::NeonReader::new)?;
@@ -324,11 +324,17 @@ impl NeonBuilder {
324
324
  let promise = cx
325
325
  .task(move || {
326
326
  let source_stream = source.into_read_stream()?;
327
- let builder = if let Some(context) = context_opt {
327
+ let mut builder = if let Some(context) = context_opt {
328
328
  Builder::from_context(context).with_archive(source_stream)?
329
329
  } else {
330
330
  Builder::default().with_archive(source_stream)?
331
331
  };
332
+ // The ARCHIVE_METADATA assertion is merely working-store bookkeeping
333
+ // used to reconstruct a builder from an archive.
334
+ builder
335
+ .definition
336
+ .assertions
337
+ .retain(|a| a.label != c2pa::assertions::labels::ARCHIVE_METADATA);
332
338
  Ok(builder)
333
339
  })
334
340
  .promise(
@@ -733,6 +739,100 @@ impl NeonBuilder {
733
739
  Ok(cx.undefined())
734
740
  }
735
741
 
742
+ /// Retains actions and ingredients together in one step, per
743
+ /// `Builder::filter_actions_and_ingredients`.
744
+ ///
745
+ /// `rescue_ingredient` is evaluated for every ingredient first; any action referencing an
746
+ /// ingredient it would rescue is force-kept regardless of `keep_action`.
747
+ ///
748
+ /// If either predicate throws or returns a non-boolean, the exception is surfaced to the
749
+ /// caller. As with [`Self::filter_actions`], the builder may be left partially filtered when a
750
+ /// predicate throws midway; callers should discard it on error.
751
+ ///
752
+ /// # Deadlock
753
+ /// As with [`Self::filter_actions`], the builder's lock is held for the whole call, so neither
754
+ /// predicate must call back into the same builder; doing so would deadlock.
755
+ pub fn filter_actions_and_ingredients(cx: FunctionContext) -> JsResult<JsUndefined> {
756
+ let rt = runtime();
757
+ // `cx` and `pending` are each borrowed mutably from one closure at a time, never by both
758
+ // closures simultaneously (calls into `filter_actions_and_ingredients` are synchronous and
759
+ // sequential), so `RefCell` lets both `FnMut` closures below share access without a
760
+ // conflicting double mutable borrow of `cx`/`pending` themselves.
761
+ let cx_cell = std::cell::RefCell::new(cx);
762
+ let pending: std::cell::RefCell<Option<neon::result::Throw>> =
763
+ std::cell::RefCell::new(None);
764
+
765
+ let (this, keep_action, rescue_ingredient, undefined) = {
766
+ let mut cx = cx_cell.borrow_mut();
767
+ let this = cx.this::<JsBox<Self>>()?;
768
+ let keep_action = cx.argument::<JsFunction>(0)?;
769
+ let rescue_ingredient = cx.argument::<JsFunction>(1)?;
770
+ let undefined = cx.undefined();
771
+ (this, keep_action, rescue_ingredient, undefined)
772
+ };
773
+ let mut builder = rt.block_on(async { this.builder.lock().await });
774
+
775
+ // See `filter_actions`/`filter_ingredients`: capture a JS exception out-of-band and
776
+ // re-raise it afterwards, short-circuiting once a throw is pending.
777
+ let filter_result = builder
778
+ .filter_actions_and_ingredients(
779
+ |action| {
780
+ if pending.borrow().is_some() {
781
+ return false;
782
+ }
783
+ let mut cx = cx_cell.borrow_mut();
784
+ let js_action = match neon_serde4::to_value(&mut *cx, action) {
785
+ Ok(v) => v,
786
+ Err(e) => {
787
+ *pending.borrow_mut() = cx.throw_error::<_, ()>(e.to_string()).err();
788
+ return false;
789
+ }
790
+ };
791
+ match callback_returns_true(&mut cx, &keep_action, undefined, js_action) {
792
+ Ok(keep) => keep,
793
+ Err(throw) => {
794
+ *pending.borrow_mut() = Some(throw);
795
+ false
796
+ }
797
+ }
798
+ },
799
+ |ingredient| {
800
+ if pending.borrow().is_some() {
801
+ return false;
802
+ }
803
+ let mut cx = cx_cell.borrow_mut();
804
+ let js_ingredient = match neon_serde4::to_value(&mut *cx, ingredient) {
805
+ Ok(v) => v,
806
+ Err(e) => {
807
+ *pending.borrow_mut() = cx.throw_error::<_, ()>(e.to_string()).err();
808
+ return false;
809
+ }
810
+ };
811
+ let js_provenance = ingredient_provenance_value(&mut cx, ingredient);
812
+ match callback_returns_true_with(
813
+ &mut cx,
814
+ &rescue_ingredient,
815
+ undefined,
816
+ &[js_ingredient, js_provenance],
817
+ ) {
818
+ Ok(rescue) => rescue,
819
+ Err(throw) => {
820
+ *pending.borrow_mut() = Some(throw);
821
+ false
822
+ }
823
+ }
824
+ },
825
+ )
826
+ .map(|_| ());
827
+
828
+ let mut cx = cx_cell.into_inner();
829
+ if let Some(throw) = pending.into_inner() {
830
+ return Err(throw);
831
+ }
832
+ filter_result.or_else(|err| cx.throw_error(err.to_string()))?;
833
+ Ok(cx.undefined())
834
+ }
835
+
736
836
  /// Update a manifest property. Available properties are limited to strings and numbers.
737
837
  /// There are other methods for thumbnails, ingredients and assertions, etc.
738
838
  pub fn update_manifest_property(mut cx: FunctionContext) -> JsResult<JsUndefined> {