@contentauth/c2pa-node 0.6.4 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/Builder.js CHANGED
@@ -149,6 +149,12 @@ export class Builder {
149
149
  addRedaction(uri, reason) {
150
150
  getNeonBinary().builderAddRedaction.call(this.builder, uri, reason);
151
151
  }
152
+ filterActions(keep) {
153
+ getNeonBinary().builderFilterActions.call(this.builder, keep);
154
+ }
155
+ filterIngredients(rescue) {
156
+ getNeonBinary().builderFilterIngredients.call(this.builder, rescue);
157
+ }
152
158
  getHandle() {
153
159
  return this.builder;
154
160
  }
@@ -802,4 +802,114 @@ describe("Builder", () => {
802
802
  expect(activeManifest?.ingredients?.length).toBe(1);
803
803
  }, 30000);
804
804
  });
805
+ describe("Filter actions and ingredients", () => {
806
+ // A manifest carrying an inception action plus two removable actions.
807
+ const actionsManifest = () => ({
808
+ claim_generator_info: [{ name: "c2pa_test", version: "1.0.0" }],
809
+ title: "Test_Filter",
810
+ format: "image/jpeg",
811
+ ingredients: [],
812
+ assertions: [
813
+ {
814
+ label: "c2pa.actions",
815
+ data: {
816
+ actions: [
817
+ {
818
+ action: "c2pa.created",
819
+ digitalSourceType: "http://c2pa.org/digitalsourcetype/empty",
820
+ },
821
+ { action: "c2pa.edited" },
822
+ { action: "c2pa.color_adjustments" },
823
+ ],
824
+ },
825
+ },
826
+ ],
827
+ resources: { resources: {} },
828
+ });
829
+ it("filterActions keeps the inception action and drops excluded actions", () => {
830
+ const builder = Builder.withJson(actionsManifest());
831
+ // The predicate only keeps c2pa.edited; c2pa.created must survive regardless
832
+ // because it is the inception action.
833
+ builder.filterActions((action) => action.action === "c2pa.edited");
834
+ const definition = builder.getManifestDefinition();
835
+ const actionsAssertion = definition.assertions.find((a) => a.label.startsWith("c2pa.actions"));
836
+ expect(actionsAssertion).toBeDefined();
837
+ const names = actionsAssertion.data.actions.map((a) => a.action);
838
+ expect(names).toContain("c2pa.created");
839
+ expect(names).toContain("c2pa.edited");
840
+ expect(names).not.toContain("c2pa.color_adjustments");
841
+ });
842
+ it("filterActions surfaces an error thrown by the predicate", () => {
843
+ const builder = Builder.withJson(actionsManifest());
844
+ expect(() => builder.filterActions((action) => {
845
+ if (action.action === "c2pa.color_adjustments") {
846
+ throw new Error("boom from predicate");
847
+ }
848
+ return true;
849
+ })).toThrow("boom from predicate");
850
+ });
851
+ it("filterActions surfaces a non-boolean predicate return", () => {
852
+ const builder = Builder.withJson(actionsManifest());
853
+ expect(() =>
854
+ // Returning a non-boolean is a programming error and must not be coerced.
855
+ builder.filterActions(() => "yes")).toThrow(/must return a boolean/);
856
+ });
857
+ it("filterIngredients prunes orphans and passes provenance to the predicate", () => {
858
+ const builder = Builder.withJson({
859
+ claim_generator_info: [{ name: "c2pa_test", version: "1.0.0" }],
860
+ title: "Test_FilterIngredients",
861
+ format: "image/jpeg",
862
+ ingredients: [],
863
+ assertions: [
864
+ {
865
+ label: "c2pa.actions",
866
+ data: {
867
+ actions: [
868
+ {
869
+ action: "c2pa.created",
870
+ digitalSourceType: "http://c2pa.org/digitalsourcetype/empty",
871
+ },
872
+ ],
873
+ },
874
+ },
875
+ ],
876
+ resources: { resources: {} },
877
+ });
878
+ // An orphan ingredient: not referenced by any action, so eligible for pruning.
879
+ builder.addIngredient(JSON.stringify({
880
+ title: "orphan",
881
+ format: "image/jpeg",
882
+ instance_id: "orphan-1",
883
+ relationship: "componentOf",
884
+ }));
885
+ const provenanceArgs = [];
886
+ // Rescue nothing, so the orphan should be pruned.
887
+ builder.filterIngredients((_ingredient, provenance) => {
888
+ provenanceArgs.push(provenance);
889
+ return false;
890
+ });
891
+ // The predicate saw the orphan with null provenance, meaning no embedded manifest.
892
+ expect(provenanceArgs).toEqual([null]);
893
+ const definition = builder.getManifestDefinition();
894
+ expect(definition.ingredients ?? []).toHaveLength(0);
895
+ });
896
+ it("filterIngredients surfaces an error thrown by the predicate", () => {
897
+ const builder = Builder.withJson({
898
+ claim_generator_info: [{ name: "c2pa_test", version: "1.0.0" }],
899
+ title: "Test_FilterIngredientsThrow",
900
+ format: "image/jpeg",
901
+ ingredients: [],
902
+ assertions: [],
903
+ resources: { resources: {} },
904
+ });
905
+ builder.addIngredient(JSON.stringify({
906
+ title: "orphan",
907
+ format: "image/jpeg",
908
+ relationship: "componentOf",
909
+ }));
910
+ expect(() => builder.filterIngredients(() => {
911
+ throw new Error("ingredient boom");
912
+ })).toThrow("ingredient boom");
913
+ });
914
+ });
805
915
  });
package/dist/index.node CHANGED
Binary file
@@ -1,4 +1,4 @@
1
- import type { BuilderIntent, C2paReason, Ingredient, Manifest } from "@contentauth/c2pa-types";
1
+ import type { Action, BuilderIntent, C2paReason, Ingredient, Manifest, ManifestStore } from "@contentauth/c2pa-types";
2
2
  import type { BuilderInterface, C2paSettings, CallbackSignerInterface, ClaimVersion, DestinationAsset, IdentityAssertionSignerInterface, JsCallbackSignerConfig, LocalSignerInterface, ManifestAssertionKind, ReaderInterface, SourceAsset, NeonBuilderHandle } from "./types.d.ts";
3
3
  export declare class Builder implements BuilderInterface {
4
4
  private builder;
@@ -22,5 +22,7 @@ export declare class Builder implements BuilderInterface {
22
22
  getManifestDefinition(): Manifest;
23
23
  updateManifestProperty(property: string, value: ClaimVersion): void;
24
24
  addRedaction(uri: string, reason: C2paReason): void;
25
+ filterActions(keep: (action: Action) => boolean): void;
26
+ filterIngredients(rescue: (ingredient: Ingredient, provenance: ManifestStore | null) => boolean): void;
25
27
  getHandle(): NeonBuilderHandle;
26
28
  }
@@ -14,6 +14,7 @@
14
14
  // This file contains types not included in @contentauth/c2pa-types and not directly applicable to the neon generated code (index.node.d.ts)
15
15
  import { Buffer } from "buffer";
16
16
  import type {
17
+ Action,
17
18
  BuilderIntent,
18
19
  C2paReason,
19
20
  Ingredient,
@@ -21,7 +22,7 @@ import type {
21
22
  ManifestStore,
22
23
  } from "@contentauth/c2pa-types";
23
24
 
24
- export type { C2paReason, Ingredient } from "@contentauth/c2pa-types";
25
+ export type { Action, C2paReason, Ingredient } from "@contentauth/c2pa-types";
25
26
 
26
27
  /**
27
28
  * Describes the digital signature algorithms allowed by the C2PA spec
@@ -342,6 +343,43 @@ export interface BuilderInterface {
342
343
  */
343
344
  addRedaction(uri: string, reason: C2paReason): void;
344
345
 
346
+ /**
347
+ * Experimental.
348
+ * Retains only the actions for which `keep` returns true.
349
+ *
350
+ * The inception action, `c2pa.created` or `c2pa.opened`, is always kept regardless of `keep`,
351
+ * and is moved to index 0 if needed, so the manifest stays valid per the C2PA spec. Sets
352
+ * `allActionsIncluded = false` when anything is removed. This does not touch ingredients.
353
+ * Call {@link filterIngredients}, using `filterIngredients(() => false)` to drop all orphans,
354
+ * afterwards if you also want to drop ingredients now orphaned by the removed actions.
355
+ * @param keep The action is retained when the predicate returns true.
356
+ */
357
+ filterActions(keep: (action: Action) => boolean): void;
358
+
359
+ /**
360
+ * Experimental.
361
+ * Retains ingredients, then rewrites positional ingredient references so linked actions
362
+ * stay valid.
363
+ *
364
+ * An ingredient is kept if it is referenced by a current action, is a `parentOf` ingredient,
365
+ * or `rescue` returns true for it. `rescue` therefore only ever rescues an otherwise-orphaned
366
+ * ingredient. It can never drop a referenced or lineage ingredient. Call {@link filterActions}
367
+ * first if you are also removing actions: the keep-set is computed from whatever actions
368
+ * currently remain.
369
+ *
370
+ * `rescue` receives the ingredient and its `provenance`: the ingredient's embedded
371
+ * `manifest_data` parsed into a {@link ManifestStore}, or `null` when it has no embedded
372
+ * manifest. This lets the predicate make provenance-aware decisions, e.g. "this ingredient's
373
+ * chain contains AI", without re-reading the whole builder first.
374
+ * @param rescue Can rescue an otherwise-orphaned ingredient by returning true.
375
+ */
376
+ filterIngredients(
377
+ rescue: (
378
+ ingredient: Ingredient,
379
+ provenance: ManifestStore | null,
380
+ ) => boolean,
381
+ ): void;
382
+
345
383
  /**
346
384
  * Get the internal handle for use with Neon bindings
347
385
  */
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.6.4",
8
+ "version": "0.7.0",
9
9
  "description": "Node.js bindings for C2PA",
10
10
  "main": "dist/index.js",
11
11
  "type": "module",
package/src/lib.rs CHANGED
@@ -85,6 +85,14 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> {
85
85
  "builderAddRedaction",
86
86
  neon_builder::NeonBuilder::add_redaction,
87
87
  )?;
88
+ cx.export_function(
89
+ "builderFilterActions",
90
+ neon_builder::NeonBuilder::filter_actions,
91
+ )?;
92
+ cx.export_function(
93
+ "builderFilterIngredients",
94
+ neon_builder::NeonBuilder::filter_ingredients,
95
+ )?;
88
96
 
89
97
  // Reader
90
98
  cx.export_function("readerNew", neon_reader::NeonReader::new)?;
@@ -18,11 +18,12 @@ 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};
21
+ use c2pa::{assertions::Action, Builder, BuilderIntent, Ingredient, Reader};
22
22
  use neon::context::Context as NeonContext;
23
23
  use neon::prelude::*;
24
24
  use neon_serde4;
25
25
  use serde_json;
26
+ use std::io::Cursor;
26
27
  use std::ops::Deref;
27
28
  use std::sync::Arc;
28
29
  use tokio::sync::Mutex;
@@ -613,6 +614,125 @@ impl NeonBuilder {
613
614
  Ok(cx.string(json).upcast())
614
615
  }
615
616
 
617
+ /// Retains only the actions for which the JS `keep` predicate returns true. The inception
618
+ /// action, `c2pa.created` or `c2pa.opened`, is always kept, per `Builder::filter_actions`.
619
+ ///
620
+ /// If `keep` throws or returns a non-boolean, the exception is surfaced to the caller. Because
621
+ /// the underlying filter mutates in place, the builder may be left partially filtered when the
622
+ /// predicate throws midway; callers should discard it on error.
623
+ ///
624
+ /// # Deadlock
625
+ /// The builder's lock is held for the entire call, so the `keep` predicate must not call back
626
+ /// into the same builder, for example `getManifestDefinition` or another filter: the lock is not
627
+ /// re-entrant and re-entry would deadlock. The predicate should only inspect the `action`
628
+ /// argument it is given.
629
+ pub fn filter_actions(mut cx: FunctionContext) -> JsResult<JsUndefined> {
630
+ let rt = runtime();
631
+ let this = cx.this::<JsBox<Self>>()?;
632
+ let keep = cx.argument::<JsFunction>(0)?;
633
+ let undefined = cx.undefined();
634
+ let mut builder = rt.block_on(async { this.builder.lock().await });
635
+
636
+ // The c2pa filter closure is `FnMut(&Action) -> bool` with no error channel, so capture a
637
+ // JS exception out-of-band and re-raise it after filtering. Once a throw is pending we
638
+ // stop invoking JS entirely, since calling more JS APIs with an exception pending is unsound.
639
+ // This means the predicate is not run for the remaining actions, which is intentional: we
640
+ // abort and re-raise, and the caller must discard the partially mutated builder anyway,
641
+ // so their side effects would not be observable regardless.
642
+ let mut pending: Option<neon::result::Throw> = None;
643
+ let filter_result = builder
644
+ .filter_actions(|action| {
645
+ if pending.is_some() {
646
+ return false;
647
+ }
648
+ let js_action = match neon_serde4::to_value(&mut cx, action) {
649
+ Ok(v) => v,
650
+ Err(e) => {
651
+ pending = cx.throw_error::<_, ()>(e.to_string()).err();
652
+ return false;
653
+ }
654
+ };
655
+ match callback_returns_true(&mut cx, &keep, undefined, js_action) {
656
+ Ok(keep) => keep,
657
+ Err(throw) => {
658
+ pending = Some(throw);
659
+ false
660
+ }
661
+ }
662
+ })
663
+ .map(|_| ());
664
+
665
+ // A pending JS exception is the root cause and takes precedence over any Rust-side error.
666
+ if let Some(throw) = pending {
667
+ return Err(throw);
668
+ }
669
+ filter_result.or_else(|err| cx.throw_error(err.to_string()))?;
670
+ Ok(cx.undefined())
671
+ }
672
+
673
+ /// Retains ingredients, rescuing an otherwise-orphaned ingredient when the JS `rescue`
674
+ /// predicate returns true for it. Referenced and `parentOf` ingredients are always kept,
675
+ /// per `Builder::filter_ingredients`.
676
+ ///
677
+ /// The `rescue` predicate is called with two arguments: the ingredient, and its parsed
678
+ /// provenance as a manifest store, `ManifestStore`, derived from the ingredient's embedded
679
+ /// `manifest_data`, or `null` when the ingredient has no embedded manifest. This lets the
680
+ /// predicate make provenance-aware decisions, for example "the ingredient's chain contains AI",
681
+ /// without the caller having to re-read the whole builder first.
682
+ ///
683
+ /// If `rescue` throws or returns a non-boolean, the exception is surfaced to the caller. As
684
+ /// with [`Self::filter_actions`], the builder may be left partially filtered when the
685
+ /// predicate throws midway; callers should discard it on error.
686
+ ///
687
+ /// # Deadlock
688
+ /// As with [`Self::filter_actions`], the builder's lock is held for the whole call, so `rescue`
689
+ /// must not call back into the same builder; doing so would deadlock. It should only inspect
690
+ /// the `ingredient` and `provenance` arguments it is given.
691
+ pub fn filter_ingredients(mut cx: FunctionContext) -> JsResult<JsUndefined> {
692
+ let rt = runtime();
693
+ let this = cx.this::<JsBox<Self>>()?;
694
+ let rescue = cx.argument::<JsFunction>(0)?;
695
+ let undefined = cx.undefined();
696
+ let mut builder = rt.block_on(async { this.builder.lock().await });
697
+
698
+ // See `filter_actions`: capture a JS exception out-of-band and re-raise it afterwards,
699
+ // short-circuiting once a throw is pending.
700
+ let mut pending: Option<neon::result::Throw> = None;
701
+ let filter_result = builder
702
+ .filter_ingredients(|ingredient| {
703
+ if pending.is_some() {
704
+ return false;
705
+ }
706
+ let js_ingredient = match neon_serde4::to_value(&mut cx, ingredient) {
707
+ Ok(v) => v,
708
+ Err(e) => {
709
+ pending = cx.throw_error::<_, ()>(e.to_string()).err();
710
+ return false;
711
+ }
712
+ };
713
+ let js_provenance = ingredient_provenance_value(&mut cx, ingredient);
714
+ match callback_returns_true_with(
715
+ &mut cx,
716
+ &rescue,
717
+ undefined,
718
+ &[js_ingredient, js_provenance],
719
+ ) {
720
+ Ok(rescue) => rescue,
721
+ Err(throw) => {
722
+ pending = Some(throw);
723
+ false
724
+ }
725
+ }
726
+ })
727
+ .map(|_| ());
728
+
729
+ if let Some(throw) = pending {
730
+ return Err(throw);
731
+ }
732
+ filter_result.or_else(|err| cx.throw_error(err.to_string()))?;
733
+ Ok(cx.undefined())
734
+ }
735
+
616
736
  /// Update a manifest property. Available properties are limited to strings and numbers.
617
737
  /// There are other methods for thumbnails, ingredients and assertions, etc.
618
738
  pub fn update_manifest_property(mut cx: FunctionContext) -> JsResult<JsUndefined> {
@@ -672,3 +792,51 @@ impl NeonBuilder {
672
792
  }
673
793
 
674
794
  impl Finalize for NeonBuilder {}
795
+
796
+ /// Synchronously calls a JS predicate with a single argument and returns its boolean result.
797
+ /// Propagates the pending JS exception if the predicate throws, and raises a `TypeError` if it
798
+ /// returns a non-boolean value.
799
+ fn callback_returns_true(
800
+ cx: &mut FunctionContext,
801
+ callback: &Handle<JsFunction>,
802
+ this: Handle<JsUndefined>,
803
+ arg: Handle<JsValue>,
804
+ ) -> NeonResult<bool> {
805
+ callback_returns_true_with(cx, callback, this, &[arg])
806
+ }
807
+
808
+ /// Like [`callback_returns_true`] but forwards multiple arguments to the JS predicate.
809
+ fn callback_returns_true_with(
810
+ cx: &mut FunctionContext,
811
+ callback: &Handle<JsFunction>,
812
+ this: Handle<JsUndefined>,
813
+ args: &[Handle<JsValue>],
814
+ ) -> NeonResult<bool> {
815
+ let result = callback.call(cx, this, args)?;
816
+ let boolean = result
817
+ .downcast::<JsBoolean, _>(cx)
818
+ .or_else(|_| cx.throw_error("filter predicate must return a boolean"))?;
819
+ Ok(boolean.value(cx))
820
+ }
821
+
822
+ /// Parses an ingredient's embedded `manifest_data` into a manifest-store JSON value for the JS
823
+ /// predicate. Returns `null` when the ingredient has no embedded manifest or it cannot be parsed.
824
+ fn ingredient_provenance_value<'a>(
825
+ cx: &mut FunctionContext<'a>,
826
+ ingredient: &Ingredient,
827
+ ) -> Handle<'a, JsValue> {
828
+ let null = cx.null().upcast::<JsValue>();
829
+ let Some(data) = ingredient.manifest_data() else {
830
+ return null;
831
+ };
832
+ let Ok(reader) = Reader::default().with_stream("c2pa", Cursor::new(data.as_ref())) else {
833
+ return null;
834
+ };
835
+ match serde_json::from_str::<serde_json::Value>(&reader.json())
836
+ .ok()
837
+ .and_then(|value| neon_serde4::to_value(cx, &value).ok())
838
+ {
839
+ Some(value) => value,
840
+ None => null,
841
+ }
842
+ }