@contentauth/c2pa-node 0.9.7 → 0.9.8

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 CHANGED
@@ -97,6 +97,9 @@ const remoteUrl = reader.remoteUrl();
97
97
 
98
98
  `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.
99
99
 
100
+ > [!WARNING]
101
+ > `mimeType` is optional on the input asset for `Reader.fromAsset`/`Reader.fromManifestDataAndAsset`. If it's omitted and cannot be inferred from the file extension, the native library falls back to detecting the format from the asset's bytes. **This is not a feature to lean on.** Always supply `mimeType` when it's known, as byte-based detection is slower than a direct lookup and can be unreliable, which could surface as more confusing errors later on. Only omit it when the caller has no way to determine the asset's format. `Builder` methods always require a `mimeType` to be provided.
102
+
100
103
  ### Builder
101
104
 
102
105
  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.
@@ -179,11 +179,10 @@ describe("Builder", () => {
179
179
  expect(activeManifest?.title).toBe("Test_Manifest");
180
180
  });
181
181
  it("should add a CBOR assertion, sign, and verify it in the signed manifest", async () => {
182
- // Add the c2pa.watermarked action as a CBOR assertion
183
182
  const actionsAssertion = {
184
183
  actions: [
185
184
  {
186
- action: "c2pa.watermarked",
185
+ action: "c2pa.edited",
187
186
  },
188
187
  ],
189
188
  };
@@ -200,7 +199,7 @@ describe("Builder", () => {
200
199
  expect(cborAssertion).toBeDefined();
201
200
  if (isActionsAssertion(cborAssertion)) {
202
201
  const actions = cborAssertion.data.actions.map((a) => a.action);
203
- expect(actions).toContain("c2pa.watermarked");
202
+ expect(actions).toContain("c2pa.edited");
204
203
  }
205
204
  else {
206
205
  throw new Error("CBOR assertion does not have the expected structure");
@@ -825,6 +824,12 @@ describe("Builder", () => {
825
824
  const context = new Context({ verify: { verifyTrust: false } });
826
825
  const builder = await Builder.newAsync(context);
827
826
  builder.updateManifestProperty("claim_version", 2);
827
+ // c2pa-rs requires the first action assertion to be c2pa.created/c2pa.opened,
828
+ // and c2pa.created requires a digitalSourceType.
829
+ builder.addAction(JSON.stringify({
830
+ action: "c2pa.created",
831
+ digitalSourceType: "http://cv.iptc.org/newscodes/digitalsourcetype/digitalCapture",
832
+ }));
828
833
  await builder.addIngredient(parent_json, source);
829
834
  builder.sign(signer, source, dest);
830
835
  const reader = await Reader.fromAsset(dest, context);
@@ -837,6 +842,12 @@ describe("Builder", () => {
837
842
  // Trust verification disabled via Context.
838
843
  const context = new Context({ verify: { verifyTrust: false } });
839
844
  const builder = await Builder.withJsonAsync(manifestDefinition, context);
845
+ // c2pa-rs requires the first action assertion to be c2pa.created/c2pa.opened,
846
+ // and c2pa.created requires a digitalSourceType.
847
+ builder.addAction(JSON.stringify({
848
+ action: "c2pa.created",
849
+ digitalSourceType: "http://cv.iptc.org/newscodes/digitalsourcetype/digitalCapture",
850
+ }));
840
851
  await builder.addIngredient(parent_json, source);
841
852
  await builder.addResource("thumbnail.jpg", {
842
853
  mimeType: "jpeg",
@@ -58,7 +58,7 @@ export class CallbackCredentialHolder {
58
58
  return new CallbackCredentialHolder(credentialHolder);
59
59
  }
60
60
  async sign(payload) {
61
- return getNeonBinary().callbackSignerSignPayload.call(this.callbackCredentialHolder, payload);
61
+ return getNeonBinary().callbackCredentialHolderSignPayload.call(this.callbackCredentialHolder, payload);
62
62
  }
63
63
  reserveSize() {
64
64
  return getNeonBinary().callbackCredentialHolderReserveSize.call(this.callbackCredentialHolder);
@@ -140,3 +140,104 @@ describe("IdentityAssertionBuilder", () => {
140
140
  });
141
141
  });
142
142
  });
143
+ describe("CallbackCredentialHolder accessors", () => {
144
+ it("returns reserveSize and sigType set on the constructor", async () => {
145
+ const { CallbackCredentialHolder } = await import("./IdentityAssertion");
146
+ const holder = CallbackCredentialHolder.newCallbackCredentialHolder(10000, "cawg.x509.cose", async () => Buffer.alloc(0));
147
+ expect(holder.reserveSize()).toBe(10000);
148
+ expect(holder.sigType()).toBe("cawg.x509.cose");
149
+ });
150
+ it("signs a payload through the callback set", async () => {
151
+ const { CallbackCredentialHolder } = await import("./IdentityAssertion");
152
+ const seen = [];
153
+ const holder = CallbackCredentialHolder.newCallbackCredentialHolder(10000, "cawg.x509.cose", async (payload) => {
154
+ seen.push(payload);
155
+ return Buffer.from([1, 2, 3]);
156
+ });
157
+ const signature = await holder.sign({
158
+ referencedAssertions: [
159
+ {
160
+ url: "self#jumbf=c2pa.assertions/cawg.training-mining",
161
+ hash: new Uint8Array([9, 8, 7]),
162
+ alg: "sha256",
163
+ },
164
+ ],
165
+ sigType: "cawg.x509.cose",
166
+ roles: ["cawg.creator"],
167
+ });
168
+ expect(signature).toEqual(Buffer.from([1, 2, 3]));
169
+ expect(seen).toHaveLength(1);
170
+ const payload = seen[0];
171
+ expect(payload.sigType).toBe("cawg.x509.cose");
172
+ expect(payload.roles).toEqual(["cawg.creator"]);
173
+ expect(payload.referencedAssertions).toHaveLength(1);
174
+ expect(payload.referencedAssertions[0].url).toBe("self#jumbf=c2pa.assertions/cawg.training-mining");
175
+ expect(Buffer.from(payload.referencedAssertions[0].hash)).toEqual(Buffer.from([9, 8, 7]));
176
+ });
177
+ });
178
+ describe("handles reserveSize", () => {
179
+ async function signWithReserveSize(reserveSize) {
180
+ const { CallbackSigner } = await import("./Signer");
181
+ const { Builder } = await import("./Builder");
182
+ const { IdentityAssertionBuilder, IdentityAssertionSigner, CallbackCredentialHolder, } = await import("./IdentityAssertion");
183
+ const c2paPrivateKey = await fs.readFile("./tests/fixtures/certs/es256.pem");
184
+ const c2paPublicKey = await fs.readFile("./tests/fixtures/certs/es256.pub");
185
+ const c2paTestSigner = new TestSigner(c2paPrivateKey);
186
+ const c2paSigner = CallbackSigner.newSigner({
187
+ alg: "es256",
188
+ certs: [c2paPublicKey],
189
+ reserveSize: 10000,
190
+ tsaUrl: undefined,
191
+ tsaHeaders: undefined,
192
+ tsaBody: undefined,
193
+ directCoseHandling: true,
194
+ }, c2paTestSigner.sign);
195
+ const cawgTestSigner = new TestCawgSigner(c2paTestSigner);
196
+ const cawgSigner = CallbackCredentialHolder.newCallbackCredentialHolder(reserveSize, "cawg.x509.cose", cawgTestSigner.sign);
197
+ const builder = Builder.withJson({
198
+ claim_generator_info: [{ name: "c2pa_test", version: "2.0.0" }],
199
+ title: "Test_Manifest",
200
+ format: "image/jpeg",
201
+ instance_id: "1234",
202
+ assertions: [
203
+ {
204
+ label: "c2pa.actions.v2",
205
+ data: {
206
+ actions: [
207
+ {
208
+ action: "c2pa.created",
209
+ digitalSourceType: "http://cv.iptc.org/newscodes/digitalsourcetype/digitalCapture",
210
+ },
211
+ ],
212
+ },
213
+ kind: "Json",
214
+ },
215
+ {
216
+ label: "cawg.training-mining",
217
+ data: {
218
+ metadata: {
219
+ "cawg.ai_inference": { use: "notAllowed" },
220
+ },
221
+ },
222
+ },
223
+ ],
224
+ });
225
+ const iaSigner = IdentityAssertionSigner.new(c2paSigner.getHandle());
226
+ const iab = await IdentityAssertionBuilder.identityBuilderForCredentialHolder(cawgSigner);
227
+ iab.addReferencedAssertions(["cawg.training-mining"]);
228
+ iaSigner.addIdentityAssertion(iab);
229
+ return builder.signAsync(iaSigner, {
230
+ buffer: await fs.readFile("./tests/fixtures/CA.jpg"),
231
+ mimeType: "image/jpeg",
232
+ }, { buffer: null });
233
+ }
234
+ it("rejects a reserveSize too small for the identity assertion", async () => {
235
+ await expect(signWithReserveSize(10)).rejects.toThrow(/exceeds the planned size/i);
236
+ });
237
+ it("rejects a reserveSize overflowing into padding", async () => {
238
+ await expect(signWithReserveSize(340)).rejects.toThrow(/reserveSize/i);
239
+ });
240
+ it("signs with a large reserveSize", async () => {
241
+ await expect(signWithReserveSize(10000)).resolves.toBeDefined();
242
+ });
243
+ });
@@ -113,6 +113,14 @@ describe("Reader", () => {
113
113
  expect(json.manifests).toEqual(manifestStore.manifests);
114
114
  expect(json.active_manifest).toEqual(manifestStore.active_manifest);
115
115
  });
116
+ it("should read from an ArrayBuffer with no mimeType by detecting the format from its bytes", async () => {
117
+ const buffer = await fs.readFile("./tests/fixtures/CA.jpg");
118
+ const reader = await Reader.fromAsset({ buffer });
119
+ expect(reader).not.toBeNull();
120
+ const json = reader.json();
121
+ expect(json.manifests).toEqual(manifestStore.manifests);
122
+ expect(json.active_manifest).toEqual(manifestStore.active_manifest);
123
+ });
116
124
  it("should read from a file", async () => {
117
125
  const reader = await Reader.fromAsset({
118
126
  path: "./tests/fixtures/CA.jpg",
@@ -122,6 +130,15 @@ describe("Reader", () => {
122
130
  expect(json.manifests).toEqual(manifestStore.manifests);
123
131
  expect(json.active_manifest).toEqual(manifestStore.active_manifest);
124
132
  });
133
+ it("should read from a file with an unrecognized extension by detecting the format from its bytes", async () => {
134
+ const extensionlessPath = path.join(tempDir, "no-extension");
135
+ await fs.copyFile("./tests/fixtures/CA.jpg", extensionlessPath);
136
+ const reader = await Reader.fromAsset({ path: extensionlessPath });
137
+ expect(reader).not.toBeNull();
138
+ const json = reader.json();
139
+ expect(json.manifests).toEqual(manifestStore.manifests);
140
+ expect(json.active_manifest).toEqual(manifestStore.active_manifest);
141
+ });
125
142
  it("should return null for a file without C2PA data", async () => {
126
143
  const reader = await Reader.fromAsset({
127
144
  path: "./tests/fixtures/A.jpg",
package/dist/index.node CHANGED
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/dist/index.node
3
- size: 49170696 bytes
4
- sha256: 6f1e7f72bb6e00aff6f77477d9f4961a022a98912016820b86f72cdcced88e8a
3
+ size: 49482104 bytes
4
+ sha256: 1fd4eec767e67c0888ae47f36b6ed5dfddeb93562309c39572483506b6b114a6
@@ -62,8 +62,14 @@ export type TrustmarkVariant =
62
62
  export interface SourceBufferAsset {
63
63
  // A buffer containing the asset data
64
64
  buffer: Buffer;
65
- // The MIME type of the asset, for instance `image/jpeg`
66
- mimeType: string;
65
+ // The MIME type of the asset, for instance `image/jpeg`.
66
+ //
67
+ // Always supply this when it's known. It's only optional for Reader operations, which fall
68
+ // back to detecting the format from the asset's bytes when it's omitted. Only rely on this
69
+ // when the MIME type is truly unknown.
70
+ //
71
+ // Builder operations (e.g. signing) require it and will throw if it's omitted.
72
+ mimeType?: string;
67
73
  }
68
74
 
69
75
  /**
@@ -80,8 +86,13 @@ export interface DestinationBufferAsset {
80
86
  export interface FileAsset {
81
87
  // The path to the asset
82
88
  path: string;
83
- // The optional MIME type of the asset, for instance `image/jpeg`.
84
- // If not supplied, the MIME type will be inferred from the file extension, if available.
89
+ // The MIME type of the asset, for instance `image/jpeg`.
90
+ //
91
+ // Always supply this when it's known. It's only optional for Reader operations, which fall
92
+ // back to detecting the format from the asset's bytes when it's omitted. Only rely on this
93
+ // when the MIME type is truly unknown.
94
+ //
95
+ // Builder operations (e.g. signing) require it and will throw if it's omitted.
85
96
  mimeType?: string;
86
97
  }
87
98
 
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.9.7",
8
+ "version": "0.9.8",
9
9
  "description": "Node.js bindings for C2PA",
10
10
  "main": "dist/index.js",
11
11
  "type": "module",
@@ -64,8 +64,8 @@
64
64
  "pkg-dir": "^8.0.0",
65
65
  "pretty-bytes": "^6.1.1",
66
66
  "unzipper": "^0.10.14",
67
- "@contentauth/c2pa-types": "0.7.4",
68
- "@contentauth/c2pa-utilities": "0.3.0"
67
+ "@contentauth/c2pa-types": "0.7.5",
68
+ "@contentauth/c2pa-utilities": "0.3.1"
69
69
  },
70
70
  "nx": {
71
71
  "tags": [
package/src/asset.rs CHANGED
@@ -31,19 +31,27 @@ impl NeonWriteStreamTrait for Cursor<Vec<u8>> {}
31
31
  impl NeonWriteStreamTrait for File {}
32
32
 
33
33
  pub enum Asset {
34
- SourceBuffer(Vec<u8>, String),
34
+ SourceBuffer(Vec<u8>, Option<String>),
35
35
  File(String, Option<String>),
36
36
  DestinationBuffer(Vec<u8>),
37
37
  }
38
38
 
39
39
  impl Asset {
40
+ /// The asset's MIME type, if known.
41
+ ///
42
+ /// For a `File`, an omitted MIME type falls back to a guess from the path's extension.
43
+ /// Returns `None` when the MIME type isn't supplied and can't be inferred; callers reading
44
+ /// an asset (as opposed to signing one) can fall back to an empty format string and let the
45
+ /// native library detect the format from the asset's bytes.
46
+ ///
47
+ /// Callers should supply the real MIME type whenever it's known and only omit it when there
48
+ /// is no way to determine it.
40
49
  pub fn mime_type(&self) -> Option<String> {
41
50
  match self {
42
- Asset::SourceBuffer(_, mime_type) => Some(mime_type.to_string()),
43
- Asset::File(path, mime_type) => match mime_type {
44
- Some(mime_type) => Some(mime_type.to_string()),
45
- None => format_from_path(Path::new(&path)),
46
- },
51
+ Asset::SourceBuffer(_, mime_type) => mime_type.clone(),
52
+ Asset::File(path, mime_type) => mime_type
53
+ .clone()
54
+ .or_else(|| format_from_path(Path::new(&path))),
47
55
  _ => None,
48
56
  }
49
57
  }
@@ -105,12 +113,9 @@ pub fn parse_asset(cx: &mut FunctionContext, obj: Handle<JsObject>) -> NeonResul
105
113
  None
106
114
  };
107
115
 
108
- match (buffer, mime_type.clone(), path) {
109
- (Some(buffer), Some(mime_type), _) => Ok(Asset::SourceBuffer(buffer, mime_type)),
110
- (None, _, Some(path)) => Ok(Asset::File(path, mime_type)),
111
- (None, _, None) => Ok(Asset::DestinationBuffer(Vec::new())),
112
- _ => cx.throw_error(
113
- "Invalid asset data passed. Must contain either a buffer and mimeType or a path.",
114
- ),
116
+ match (buffer, path) {
117
+ (Some(buffer), _) => Ok(Asset::SourceBuffer(buffer, mime_type)),
118
+ (None, Some(path)) => Ok(Asset::File(path, mime_type)),
119
+ (None, None) => Ok(Asset::DestinationBuffer(Vec::new())),
115
120
  }
116
121
  }
package/src/lib.rs CHANGED
@@ -186,6 +186,18 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> {
186
186
  "newCallbackCredentialHolder",
187
187
  neon_credential_holder::NeonCallbackCredentialHolder::from_js,
188
188
  )?;
189
+ cx.export_function(
190
+ "callbackCredentialHolderSignPayload",
191
+ neon_credential_holder::NeonCallbackCredentialHolder::sign_payload,
192
+ )?;
193
+ cx.export_function(
194
+ "callbackCredentialHolderReserveSize",
195
+ neon_credential_holder::NeonCallbackCredentialHolder::reserve_size_js,
196
+ )?;
197
+ cx.export_function(
198
+ "callbackCredentialHolderSigType",
199
+ neon_credential_holder::NeonCallbackCredentialHolder::sig_type_js,
200
+ )?;
189
201
 
190
202
  // Trustmark
191
203
  cx.export_function(
@@ -11,16 +11,72 @@
11
11
  // specific language governing permissions and limitations under
12
12
  // each license.
13
13
 
14
+ use std::ops::Deref;
14
15
  use std::sync::Arc;
15
16
 
16
17
  use async_trait::async_trait;
17
18
  use c2pa::identity::builder::{AsyncCredentialHolder, IdentityBuilderError};
18
19
  use c2pa::identity::SignerPayload;
20
+ use c2pa::HashedUri;
19
21
  use neon::prelude::*;
20
22
  use neon::types::buffer::TypedArray;
21
23
  use neon_serde4;
24
+ use serde::{Deserialize, Serialize};
22
25
  use tokio::sync::oneshot;
23
26
 
27
+ use crate::runtime::runtime;
28
+
29
+ #[derive(Deserialize, Serialize)]
30
+ #[serde(rename_all = "camelCase")]
31
+ struct JsSignerPayload {
32
+ referenced_assertions: Vec<JsHashedUri>,
33
+ sig_type: String,
34
+ #[serde(default)]
35
+ roles: Vec<String>,
36
+ }
37
+
38
+ #[derive(Deserialize, Serialize)]
39
+ #[serde(rename_all = "camelCase")]
40
+ struct JsHashedUri {
41
+ url: String,
42
+ #[serde(default, skip_serializing_if = "Option::is_none")]
43
+ alg: Option<String>,
44
+ #[serde(with = "serde_bytes")]
45
+ hash: Vec<u8>,
46
+ }
47
+
48
+ impl From<&SignerPayload> for JsSignerPayload {
49
+ fn from(payload: &SignerPayload) -> Self {
50
+ JsSignerPayload {
51
+ referenced_assertions: payload
52
+ .referenced_assertions
53
+ .iter()
54
+ .map(|uri| JsHashedUri {
55
+ url: uri.url(),
56
+ alg: uri.alg(),
57
+ hash: uri.hash(),
58
+ })
59
+ .collect(),
60
+ sig_type: payload.sig_type.clone(),
61
+ roles: payload.roles.clone(),
62
+ }
63
+ }
64
+ }
65
+
66
+ impl From<JsSignerPayload> for SignerPayload {
67
+ fn from(payload: JsSignerPayload) -> Self {
68
+ SignerPayload {
69
+ referenced_assertions: payload
70
+ .referenced_assertions
71
+ .into_iter()
72
+ .map(|uri| HashedUri::new(uri.url, uri.alg, &uri.hash))
73
+ .collect(),
74
+ sig_type: payload.sig_type,
75
+ roles: payload.roles,
76
+ }
77
+ }
78
+ }
79
+
24
80
  /// NeonCallbackCredentialHolder allows JS to asynchronously sign a SignerPayload.
25
81
  #[derive(Clone)]
26
82
  pub struct NeonCallbackCredentialHolder {
@@ -58,6 +114,49 @@ impl NeonCallbackCredentialHolder {
58
114
  sig_type,
59
115
  )))
60
116
  }
117
+
118
+ /// JS accessor for the reserve size of this holder instance.
119
+ pub fn reserve_size_js(mut cx: FunctionContext) -> JsResult<JsNumber> {
120
+ let this = cx.this::<JsBox<Self>>()?;
121
+ let reserve_size = this.reserve_size as f64;
122
+ Ok(cx.number(reserve_size))
123
+ }
124
+
125
+ /// JS accessor for the signature type of this holder instance.
126
+ pub fn sig_type_js(mut cx: FunctionContext) -> JsResult<JsString> {
127
+ let this = cx.this::<JsBox<Self>>()?;
128
+ let sig_type = this.sig_type.clone();
129
+ Ok(cx.string(sig_type))
130
+ }
131
+
132
+ /// Sign a `SignerPayload` supplied from JS,
133
+ /// resolving to the signature bytes.
134
+ pub fn sign_payload(mut cx: FunctionContext) -> JsResult<JsPromise> {
135
+ let payload_arg = cx.argument::<JsValue>(0)?;
136
+ let js_payload: JsSignerPayload = match neon_serde4::from_value(&mut cx, payload_arg) {
137
+ Ok(payload) => payload,
138
+ Err(err) => return cx.throw_error(err.to_string()),
139
+ };
140
+ let signer_payload: SignerPayload = js_payload.into();
141
+
142
+ let holder_handle = cx.this::<JsBox<Self>>()?;
143
+ let holder_ref: &Self = holder_handle.deref();
144
+ let holder = holder_ref.clone();
145
+ let channel = cx.channel();
146
+ let (deferred, promise) = cx.promise();
147
+ let rt = runtime();
148
+
149
+ // The credential holder's `sign` awaits a JS callback.
150
+ rt.spawn(async move {
151
+ let result = holder.sign(&signer_payload).await;
152
+ deferred.settle_with(&channel, move |mut cx| match result {
153
+ Ok(bytes) => Ok(JsBuffer::from_slice(&mut cx, &bytes)?),
154
+ Err(err) => cx.throw_error(err.to_string()),
155
+ });
156
+ });
157
+
158
+ Ok(promise)
159
+ }
61
160
  }
62
161
 
63
162
  /// # Safety
@@ -102,12 +201,10 @@ impl AsyncCredentialHolder for NeonCallbackCredentialHolder {
102
201
  let callback = self.callback.clone();
103
202
  let channel = self.channel.clone();
104
203
 
105
- // Instead of CBOR, convert SignerPayload to a JS object
106
- let payload = signer_payload.clone();
204
+ let payload = JsSignerPayload::from(signer_payload);
107
205
 
108
206
  channel
109
207
  .try_send(move |mut cx| {
110
- // Convert Rust SignerPayload to JS object
111
208
  let js_payload = match neon_serde4::to_value(&mut cx, &payload) {
112
209
  Ok(val) => val,
113
210
  Err(err) => return cx.throw_error(err.to_string()),
@@ -192,7 +192,7 @@ fn finalize_identity_assertion(
192
192
  return Err(c2pa::Error::BadParam(format!("Serialized assertion is {len} bytes, which exceeds the planned size of {assertion_size} bytes", len = assertion_cbor.len())));
193
193
  }
194
194
 
195
- ia.pad1 = vec![0u8; assertion_size - assertion_cbor.len() - 15];
195
+ ia.pad1 = vec![0u8; pad_len(assertion_size, assertion_cbor.len(), PAD1_CBOR_OVERHEAD)?];
196
196
 
197
197
  assertion_cbor.clear();
198
198
  c2pa_cbor::to_writer(&mut assertion_cbor, &ia)
@@ -200,14 +200,46 @@ fn finalize_identity_assertion(
200
200
 
201
201
  ia.pad2 = Some(ByteBuf::from(vec![
202
202
  0u8;
203
- assertion_size - assertion_cbor.len() - 6
203
+ pad_len(
204
+ assertion_size,
205
+ assertion_cbor.len(),
206
+ PAD2_CBOR_OVERHEAD
207
+ )?
204
208
  ]));
205
209
 
206
210
  assertion_cbor.clear();
207
211
  c2pa_cbor::to_writer(&mut assertion_cbor, &ia)
208
212
  .map_err(|e| c2pa::Error::BadParam(e.to_string()))?;
209
- assert_eq!(assertion_size, assertion_cbor.len());
213
+
214
+ if assertion_size != assertion_cbor.len() {
215
+ return Err(c2pa::Error::BadParam(format!(
216
+ "Padded assertion is {len} bytes, different from expected {assertion_size} bytes",
217
+ len = assertion_cbor.len()
218
+ )));
219
+ }
210
220
  }
211
221
 
212
222
  Ok(DynamicAssertionContent::Cbor(assertion_cbor))
213
223
  }
224
+
225
+ /// CBOR framing cost of writing the `pad1` byte string into the assertion.
226
+ const PAD1_CBOR_OVERHEAD: usize = 15;
227
+
228
+ /// CBOR framing cost of writing the `pad2` byte string into the assertion.
229
+ const PAD2_CBOR_OVERHEAD: usize = 6;
230
+
231
+ /// Size of a padding field that brings the encoded assertion up to
232
+ /// `assertion_size`.
233
+ /// Returns a `BadParam` error when the caller's reserved size
234
+ /// cannot fit in the CBOR framing.
235
+ fn pad_len(assertion_size: usize, encoded_len: usize, overhead: usize) -> c2pa::Result<usize> {
236
+ assertion_size
237
+ .checked_sub(encoded_len)
238
+ .and_then(|remaining| remaining.checked_sub(overhead))
239
+ .ok_or_else(|| {
240
+ c2pa::Error::BadParam(format!(
241
+ "Identity assertion reserveSize {assertion_size} bytes needs at least {min} bytes",
242
+ min = encoded_len + overhead
243
+ ))
244
+ })
245
+ }
@@ -16,11 +16,7 @@ use std::sync::RwLock;
16
16
 
17
17
  use async_trait::async_trait;
18
18
  use c2pa::{
19
- crypto::{
20
- raw_signature::{AsyncRawSigner, RawSignerError},
21
- time_stamp::AsyncTimeStampProvider,
22
- },
23
- dynamic_assertion::AsyncDynamicAssertion,
19
+ crypto::time_stamp::AsyncTimeStampProvider, dynamic_assertion::AsyncDynamicAssertion,
24
20
  AsyncSigner, SigningAlg,
25
21
  };
26
22
  use neon::prelude::FunctionContext;
@@ -87,37 +83,12 @@ impl Clone for NeonIdentityAssertionSigner {
87
83
  /// - `Sync`: Allows the type to be shared between threads
88
84
  ///
89
85
  /// The type needs these capabilities because it:
90
- /// - Implements `AsyncSigner` and `AsyncRawSigner` traits for asynchronous signing operations
86
+ /// - Implements the `AsyncSigner` trait for asynchronous signing operations
91
87
  /// - Is used in the `identity_sign_async` function which performs asynchronous operations
92
88
  /// - Is part of a Node.js binding where async operations are common
93
89
  unsafe impl Send for NeonIdentityAssertionSigner {}
94
90
  unsafe impl Sync for NeonIdentityAssertionSigner {}
95
91
 
96
- #[async_trait]
97
- impl AsyncRawSigner for NeonIdentityAssertionSigner {
98
- async fn sign(&self, data: Vec<u8>) -> Result<Vec<u8>, RawSignerError> {
99
- let signer = self.signer.read().unwrap().clone();
100
- AsyncRawSigner::sign(&signer, data).await
101
- }
102
-
103
- fn alg(&self) -> SigningAlg {
104
- AsyncRawSigner::alg(&*self.signer.read().unwrap())
105
- }
106
-
107
- fn cert_chain(&self) -> Result<Vec<Vec<u8>>, RawSignerError> {
108
- self.signer.read().unwrap().cert_chain()
109
- }
110
-
111
- fn reserve_size(&self) -> usize {
112
- AsyncRawSigner::reserve_size(&*self.signer.read().unwrap())
113
- }
114
-
115
- async fn ocsp_response(&self) -> Option<Vec<u8>> {
116
- let signer = self.signer.read().unwrap().clone();
117
- AsyncRawSigner::ocsp_response(&signer).await
118
- }
119
- }
120
-
121
92
  impl AsyncTimeStampProvider for NeonIdentityAssertionSigner {
122
93
  fn time_stamp_service_url(&self) -> Option<String> {
123
94
  self.signer.read().unwrap().time_stamp_service_url()
@@ -140,11 +111,7 @@ impl AsyncSigner for NeonIdentityAssertionSigner {
140
111
  }
141
112
 
142
113
  fn certs(&self) -> Result<Vec<Vec<u8>>, c2pa::Error> {
143
- self.signer
144
- .read()
145
- .unwrap()
146
- .cert_chain()
147
- .map_err(|e| e.into())
114
+ c2pa::AsyncSigner::certs(&*self.signer.read().unwrap())
148
115
  }
149
116
 
150
117
  fn reserve_size(&self) -> usize {
@@ -173,10 +140,6 @@ impl AsyncSigner for NeonIdentityAssertionSigner {
173
140
  c2pa::AsyncSigner::send_timestamp_request(&signer, message).await
174
141
  }
175
142
 
176
- fn async_raw_signer(&self) -> Option<Box<&dyn AsyncRawSigner>> {
177
- Some(Box::new(self))
178
- }
179
-
180
143
  fn dynamic_assertions(&self) -> Vec<Box<dyn AsyncDynamicAssertion>> {
181
144
  let mut identity_assertions = self.identity_assertions.write().unwrap();
182
145
  let ia_clone = identity_assertions.split_off(0);
@@ -57,12 +57,9 @@ impl NeonReader {
57
57
  let (deferred, promise) = cx.promise();
58
58
  rt.spawn(async move {
59
59
  let result: Result<Reader> = async {
60
- let format = source
61
- .mime_type()
62
- .ok_or_else(|| {
63
- Error::Reading("Source asset must have a mime type".to_string())
64
- })?
65
- .to_owned();
60
+ // An empty format asks the native library to detect the asset's format from its
61
+ // bytes, so a source with no known MIME type can still be read.
62
+ let format = source.mime_type().unwrap_or_default();
66
63
 
67
64
  let stream = source.into_read_stream()?;
68
65
 
@@ -119,12 +116,9 @@ impl NeonReader {
119
116
  let (deferred, promise) = cx.promise();
120
117
  rt.spawn(async move {
121
118
  let result = async {
122
- let format = asset
123
- .mime_type()
124
- .ok_or_else(|| {
125
- Error::Reading("Source asset must have a mime type".to_string())
126
- })?
127
- .to_owned();
119
+ // An empty format asks the native library to detect the asset's format from its
120
+ // bytes, so an asset with no known MIME type can still be read.
121
+ let format = asset.mime_type().unwrap_or_default();
128
122
  let stream = asset.into_read_stream()?;
129
123
 
130
124
  let reader = if let Some(context) = context_opt {
@@ -17,10 +17,7 @@ use std::{boxed::Box, str::FromStr, sync::Arc};
17
17
  use async_trait::async_trait;
18
18
  use c2pa::{
19
19
  create_signer,
20
- crypto::{
21
- raw_signature::{AsyncRawSigner, RawSigner, RawSignerError},
22
- time_stamp::{AsyncTimeStampProvider, TimeStampProvider},
23
- },
20
+ crypto::time_stamp::{AsyncTimeStampProvider, TimeStampProvider},
24
21
  AsyncSigner,
25
22
  Error::OtherError,
26
23
  Signer, SigningAlg,
@@ -233,10 +230,6 @@ impl NeonCallbackSigner {
233
230
 
234
231
  Ok(promise)
235
232
  }
236
-
237
- pub fn as_raw_signer(&self) -> &dyn AsyncRawSigner {
238
- self
239
- }
240
233
  }
241
234
 
242
235
  /// # Safety
@@ -258,7 +251,7 @@ impl NeonCallbackSigner {
258
251
  /// - `Sync`: Allows the type to be shared between threads
259
252
  ///
260
253
  /// The type needs these capabilities because it:
261
- /// - Implements `AsyncSigner` and `AsyncRawSigner` traits for asynchronous signing operations
254
+ /// - Implements the `AsyncSigner` trait for asynchronous signing operations
262
255
  /// - Is used in the `identity_sign_async` function which performs asynchronous operations
263
256
  /// - Is part of a Node.js binding where async operations are common
264
257
  unsafe impl Send for NeonCallbackSigner {}
@@ -329,10 +322,6 @@ impl AsyncSigner for NeonCallbackSigner {
329
322
  fn direct_cose_handling(&self) -> bool {
330
323
  self.config.direct_cose_handling
331
324
  }
332
-
333
- fn async_raw_signer(&self) -> Option<Box<&dyn AsyncRawSigner>> {
334
- Some(Box::new(self))
335
- }
336
325
  }
337
326
 
338
327
  impl TimeStampProvider for NeonCallbackSigner {
@@ -353,93 +342,6 @@ impl AsyncTimeStampProvider for NeonCallbackSigner {
353
342
  }
354
343
  }
355
344
 
356
- #[async_trait]
357
- impl AsyncRawSigner for NeonCallbackSigner {
358
- async fn sign(&self, data: Vec<u8>) -> Result<Vec<u8>, RawSignerError> {
359
- let (tx, rx) = oneshot::channel();
360
- let sign_fn = self.callback.clone();
361
- let data = data.to_vec();
362
-
363
- // Send the signing request to the JavaScript side
364
- self.channel
365
- .try_send(move |mut cx| {
366
- let to_be_signed = JsBuffer::from_slice(&mut cx, &data)?;
367
- let sign_fn = sign_fn.to_inner(&mut cx);
368
-
369
- let sign_fut = sign_fn
370
- .call_with(&cx)
371
- .arg(to_be_signed)
372
- .apply::<JsPromise, _>(&mut cx)?
373
- .to_future(&mut cx, |mut cx, result| match result {
374
- Ok(value) => {
375
- let buffer = value.downcast_or_throw::<JsBuffer, _>(&mut cx)?;
376
- Ok(Ok(buffer.as_slice(&cx).to_vec()))
377
- }
378
- Err(err) => {
379
- let err_string = match err.to_string(&mut cx) {
380
- Ok(js_string) => js_string.value(&mut cx),
381
- Err(e) => return Err(e),
382
- };
383
- Ok(Err(RawSignerError::CryptoLibraryError(err_string)))
384
- }
385
- })?;
386
-
387
- let _ = tx.send(sign_fut);
388
- Ok(())
389
- })
390
- .map_err(|err| RawSignerError::CryptoLibraryError(err.to_string()))?;
391
-
392
- // Wait for the JavaScript promise to resolve
393
- let sign_fut = rx
394
- .await
395
- .map_err(|err| RawSignerError::CryptoLibraryError(err.to_string()))?;
396
-
397
- // Get the result from the future
398
- sign_fut
399
- .await
400
- .map_err(|err| RawSignerError::CryptoLibraryError(err.to_string()))?
401
- }
402
-
403
- fn alg(&self) -> SigningAlg {
404
- self.config.alg
405
- }
406
-
407
- fn cert_chain(&self) -> Result<Vec<Vec<u8>>, RawSignerError> {
408
- let pems = pem::parse_many(&self.config.certs)
409
- .map_err(|e| RawSignerError::CryptoLibraryError(e.to_string()))?;
410
- Ok(pems.into_iter().map(|p| p.into_contents()).collect())
411
- }
412
-
413
- fn reserve_size(&self) -> usize {
414
- self.config.reserve_size
415
- }
416
-
417
- async fn ocsp_response(&self) -> Option<Vec<u8>> {
418
- None
419
- }
420
- }
421
-
422
- impl RawSigner for NeonCallbackSigner {
423
- fn sign(&self, _data: &[u8]) -> Result<Vec<u8>, RawSignerError> {
424
- // Synchronous signing is not supported; use AsyncRawSigner instead
425
- Err(RawSignerError::InternalError(
426
- "Synchronous signing not supported - use AsyncRawSigner instead".to_string(),
427
- ))
428
- }
429
-
430
- fn alg(&self) -> SigningAlg {
431
- AsyncRawSigner::alg(self)
432
- }
433
-
434
- fn cert_chain(&self) -> Result<Vec<Vec<u8>>, RawSignerError> {
435
- AsyncRawSigner::cert_chain(self)
436
- }
437
-
438
- fn reserve_size(&self) -> usize {
439
- AsyncRawSigner::reserve_size(self)
440
- }
441
- }
442
-
443
345
  pub struct NeonLocalSigner {
444
346
  signer: Box<dyn Signer>,
445
347
  }