@contentauth/c2pa-node 0.6.4 → 0.8.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/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
@@ -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.8.0",
9
9
  "description": "Node.js bindings for C2PA",
10
10
  "main": "dist/index.js",
11
11
  "type": "module",
@@ -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
@@ -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;
@@ -323,11 +324,17 @@ impl NeonBuilder {
323
324
  let promise = cx
324
325
  .task(move || {
325
326
  let source_stream = source.into_read_stream()?;
326
- let builder = if let Some(context) = context_opt {
327
+ let mut builder = if let Some(context) = context_opt {
327
328
  Builder::from_context(context).with_archive(source_stream)?
328
329
  } else {
329
330
  Builder::default().with_archive(source_stream)?
330
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);
331
338
  Ok(builder)
332
339
  })
333
340
  .promise(
@@ -613,6 +620,125 @@ impl NeonBuilder {
613
620
  Ok(cx.string(json).upcast())
614
621
  }
615
622
 
623
+ /// Retains only the actions for which the JS `keep` predicate returns true. The inception
624
+ /// action, `c2pa.created` or `c2pa.opened`, is always kept, per `Builder::filter_actions`.
625
+ ///
626
+ /// If `keep` throws or returns a non-boolean, the exception is surfaced to the caller. Because
627
+ /// the underlying filter mutates in place, the builder may be left partially filtered when the
628
+ /// predicate throws midway; callers should discard it on error.
629
+ ///
630
+ /// # Deadlock
631
+ /// The builder's lock is held for the entire call, so the `keep` predicate must not call back
632
+ /// into the same builder, for example `getManifestDefinition` or another filter: the lock is not
633
+ /// re-entrant and re-entry would deadlock. The predicate should only inspect the `action`
634
+ /// argument it is given.
635
+ pub fn filter_actions(mut cx: FunctionContext) -> JsResult<JsUndefined> {
636
+ let rt = runtime();
637
+ let this = cx.this::<JsBox<Self>>()?;
638
+ let keep = cx.argument::<JsFunction>(0)?;
639
+ let undefined = cx.undefined();
640
+ let mut builder = rt.block_on(async { this.builder.lock().await });
641
+
642
+ // The c2pa filter closure is `FnMut(&Action) -> bool` with no error channel, so capture a
643
+ // JS exception out-of-band and re-raise it after filtering. Once a throw is pending we
644
+ // stop invoking JS entirely, since calling more JS APIs with an exception pending is unsound.
645
+ // This means the predicate is not run for the remaining actions, which is intentional: we
646
+ // abort and re-raise, and the caller must discard the partially mutated builder anyway,
647
+ // so their side effects would not be observable regardless.
648
+ let mut pending: Option<neon::result::Throw> = None;
649
+ let filter_result = builder
650
+ .filter_actions(|action| {
651
+ if pending.is_some() {
652
+ return false;
653
+ }
654
+ let js_action = match neon_serde4::to_value(&mut cx, action) {
655
+ Ok(v) => v,
656
+ Err(e) => {
657
+ pending = cx.throw_error::<_, ()>(e.to_string()).err();
658
+ return false;
659
+ }
660
+ };
661
+ match callback_returns_true(&mut cx, &keep, undefined, js_action) {
662
+ Ok(keep) => keep,
663
+ Err(throw) => {
664
+ pending = Some(throw);
665
+ false
666
+ }
667
+ }
668
+ })
669
+ .map(|_| ());
670
+
671
+ // A pending JS exception is the root cause and takes precedence over any Rust-side error.
672
+ if let Some(throw) = pending {
673
+ return Err(throw);
674
+ }
675
+ filter_result.or_else(|err| cx.throw_error(err.to_string()))?;
676
+ Ok(cx.undefined())
677
+ }
678
+
679
+ /// Retains ingredients, rescuing an otherwise-orphaned ingredient when the JS `rescue`
680
+ /// predicate returns true for it. Referenced and `parentOf` ingredients are always kept,
681
+ /// per `Builder::filter_ingredients`.
682
+ ///
683
+ /// The `rescue` predicate is called with two arguments: the ingredient, and its parsed
684
+ /// provenance as a manifest store, `ManifestStore`, derived from the ingredient's embedded
685
+ /// `manifest_data`, or `null` when the ingredient has no embedded manifest. This lets the
686
+ /// predicate make provenance-aware decisions, for example "the ingredient's chain contains AI",
687
+ /// without the caller having to re-read the whole builder first.
688
+ ///
689
+ /// If `rescue` throws or returns a non-boolean, the exception is surfaced to the caller. As
690
+ /// with [`Self::filter_actions`], the builder may be left partially filtered when the
691
+ /// predicate throws midway; callers should discard it on error.
692
+ ///
693
+ /// # Deadlock
694
+ /// As with [`Self::filter_actions`], the builder's lock is held for the whole call, so `rescue`
695
+ /// must not call back into the same builder; doing so would deadlock. It should only inspect
696
+ /// the `ingredient` and `provenance` arguments it is given.
697
+ pub fn filter_ingredients(mut cx: FunctionContext) -> JsResult<JsUndefined> {
698
+ let rt = runtime();
699
+ let this = cx.this::<JsBox<Self>>()?;
700
+ let rescue = cx.argument::<JsFunction>(0)?;
701
+ let undefined = cx.undefined();
702
+ let mut builder = rt.block_on(async { this.builder.lock().await });
703
+
704
+ // See `filter_actions`: capture a JS exception out-of-band and re-raise it afterwards,
705
+ // short-circuiting once a throw is pending.
706
+ let mut pending: Option<neon::result::Throw> = None;
707
+ let filter_result = builder
708
+ .filter_ingredients(|ingredient| {
709
+ if pending.is_some() {
710
+ return false;
711
+ }
712
+ let js_ingredient = match neon_serde4::to_value(&mut cx, ingredient) {
713
+ Ok(v) => v,
714
+ Err(e) => {
715
+ pending = cx.throw_error::<_, ()>(e.to_string()).err();
716
+ return false;
717
+ }
718
+ };
719
+ let js_provenance = ingredient_provenance_value(&mut cx, ingredient);
720
+ match callback_returns_true_with(
721
+ &mut cx,
722
+ &rescue,
723
+ undefined,
724
+ &[js_ingredient, js_provenance],
725
+ ) {
726
+ Ok(rescue) => rescue,
727
+ Err(throw) => {
728
+ pending = Some(throw);
729
+ false
730
+ }
731
+ }
732
+ })
733
+ .map(|_| ());
734
+
735
+ if let Some(throw) = pending {
736
+ return Err(throw);
737
+ }
738
+ filter_result.or_else(|err| cx.throw_error(err.to_string()))?;
739
+ Ok(cx.undefined())
740
+ }
741
+
616
742
  /// Update a manifest property. Available properties are limited to strings and numbers.
617
743
  /// There are other methods for thumbnails, ingredients and assertions, etc.
618
744
  pub fn update_manifest_property(mut cx: FunctionContext) -> JsResult<JsUndefined> {
@@ -672,3 +798,51 @@ impl NeonBuilder {
672
798
  }
673
799
 
674
800
  impl Finalize for NeonBuilder {}
801
+
802
+ /// Synchronously calls a JS predicate with a single argument and returns its boolean result.
803
+ /// Propagates the pending JS exception if the predicate throws, and raises a `TypeError` if it
804
+ /// returns a non-boolean value.
805
+ fn callback_returns_true(
806
+ cx: &mut FunctionContext,
807
+ callback: &Handle<JsFunction>,
808
+ this: Handle<JsUndefined>,
809
+ arg: Handle<JsValue>,
810
+ ) -> NeonResult<bool> {
811
+ callback_returns_true_with(cx, callback, this, &[arg])
812
+ }
813
+
814
+ /// Like [`callback_returns_true`] but forwards multiple arguments to the JS predicate.
815
+ fn callback_returns_true_with(
816
+ cx: &mut FunctionContext,
817
+ callback: &Handle<JsFunction>,
818
+ this: Handle<JsUndefined>,
819
+ args: &[Handle<JsValue>],
820
+ ) -> NeonResult<bool> {
821
+ let result = callback.call(cx, this, args)?;
822
+ let boolean = result
823
+ .downcast::<JsBoolean, _>(cx)
824
+ .or_else(|_| cx.throw_error("filter predicate must return a boolean"))?;
825
+ Ok(boolean.value(cx))
826
+ }
827
+
828
+ /// Parses an ingredient's embedded `manifest_data` into a manifest-store JSON value for the JS
829
+ /// predicate. Returns `null` when the ingredient has no embedded manifest or it cannot be parsed.
830
+ fn ingredient_provenance_value<'a>(
831
+ cx: &mut FunctionContext<'a>,
832
+ ingredient: &Ingredient,
833
+ ) -> Handle<'a, JsValue> {
834
+ let null = cx.null().upcast::<JsValue>();
835
+ let Some(data) = ingredient.manifest_data() else {
836
+ return null;
837
+ };
838
+ let Ok(reader) = Reader::default().with_stream("c2pa", Cursor::new(data.as_ref())) else {
839
+ return null;
840
+ };
841
+ match serde_json::from_str::<serde_json::Value>(&reader.json())
842
+ .ok()
843
+ .and_then(|value| neon_serde4::to_value(cx, &value).ok())
844
+ {
845
+ Some(value) => value,
846
+ None => null,
847
+ }
848
+ }