@contentauth/c2pa-node 0.2.1 → 0.2.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.
@@ -0,0 +1,197 @@
1
+ // Copyright 2025 Adobe. All rights reserved.
2
+ // This file is licensed to you under the Apache License,
3
+ // Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
4
+ // or the MIT license (http://opensource.org/licenses/MIT),
5
+ // at your option.
6
+
7
+ // Unless required by applicable law or agreed to in writing,
8
+ // this software is distributed on an "AS IS" BASIS, WITHOUT
9
+ // WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
10
+ // implied. See the LICENSE-MIT and LICENSE-APACHE files for the
11
+ // specific language governing permissions and limitations under
12
+ // each license.
13
+
14
+ use crate::asset::parse_asset;
15
+ use crate::error::{as_js_error, Error};
16
+ use crate::runtime::runtime;
17
+ use c2pa::{identity::validator::CawgValidator, Reader};
18
+ use neon::prelude::*;
19
+ use neon::types::buffer::TypedArray;
20
+ use std::sync::Arc;
21
+ use tokio::sync::Mutex;
22
+
23
+ #[derive(Debug)]
24
+ pub struct NeonReader {
25
+ reader: Arc<Mutex<Reader>>,
26
+ }
27
+
28
+ impl Finalize for NeonReader {}
29
+
30
+ impl NeonReader {
31
+ pub fn new(mut cx: FunctionContext) -> JsResult<JsBox<NeonReader>> {
32
+ Ok(cx.boxed(Self {
33
+ reader: Arc::new(Mutex::new(Reader::default())),
34
+ }))
35
+ }
36
+
37
+ pub fn from_stream(mut cx: FunctionContext) -> JsResult<JsPromise> {
38
+ let source = cx
39
+ .argument::<JsObject>(0)
40
+ .and_then(|obj| parse_asset(&mut cx, obj))?;
41
+
42
+ let promise = cx
43
+ .task(move || {
44
+ let format = source
45
+ .mime_type()
46
+ .ok_or_else(|| {
47
+ Error::Signing("Ingredient asset must have a mime type".to_string())
48
+ })?
49
+ .to_owned();
50
+ let stream = source.into_read_stream()?;
51
+ let reader = Reader::from_stream(&format, stream)?;
52
+ Ok(reader)
53
+ })
54
+ .promise(move |mut cx, result: Result<Reader, Error>| match result {
55
+ Ok(reader) => {
56
+ let boxed_reader = cx.boxed(Self {
57
+ reader: Arc::new(Mutex::new(reader)),
58
+ });
59
+ Ok(boxed_reader.upcast::<JsValue>())
60
+ }
61
+ Err(err) => as_js_error(&mut cx, err).and_then(|err| cx.throw(err)),
62
+ });
63
+ Ok(promise)
64
+ }
65
+
66
+ pub fn from_manifest_data_and_asset(mut cx: FunctionContext) -> JsResult<JsPromise> {
67
+ let manifest_data = cx.argument::<JsBuffer>(0)?;
68
+ let asset = cx
69
+ .argument::<JsObject>(1)
70
+ .and_then(|obj| parse_asset(&mut cx, obj))?;
71
+
72
+ let c2pa_data = manifest_data.as_slice(&cx).to_vec();
73
+ let promise = cx
74
+ .task(move || {
75
+ let format = asset
76
+ .mime_type()
77
+ .ok_or_else(|| {
78
+ Error::Signing("Ingredient asset must have a mime type".to_string())
79
+ })?
80
+ .to_owned();
81
+ let mut stream = asset.into_read_stream()?;
82
+ let reader =
83
+ Reader::from_manifest_data_and_stream(&c2pa_data, &format, &mut stream)?;
84
+ Ok(reader)
85
+ })
86
+ .promise(move |mut cx, result: Result<Reader, Error>| match result {
87
+ Ok(reader) => {
88
+ let boxed_reader = cx.boxed(Self {
89
+ reader: Arc::new(Mutex::new(reader)),
90
+ });
91
+ Ok(boxed_reader.upcast::<JsValue>())
92
+ }
93
+ Err(err) => as_js_error(&mut cx, err).and_then(|err| cx.throw(err)),
94
+ });
95
+
96
+ Ok(promise)
97
+ }
98
+
99
+ pub fn json(mut cx: FunctionContext) -> JsResult<JsValue> {
100
+ let rt = runtime();
101
+ let this = cx.this::<JsBox<Self>>()?;
102
+ let reader = rt.block_on(async { this.reader.lock().await });
103
+ let json = reader.json();
104
+ Ok(cx.string(json).upcast())
105
+ }
106
+
107
+ pub fn remote_url(mut cx: FunctionContext) -> JsResult<JsValue> {
108
+ let rt = runtime();
109
+ let this = cx.this::<JsBox<Self>>()?;
110
+ let reader = rt.block_on(async { this.reader.lock().await });
111
+ let remote_url = reader.remote_url().unwrap_or("");
112
+ Ok(cx.string(remote_url).upcast())
113
+ }
114
+
115
+ pub fn is_embedded(mut cx: FunctionContext) -> JsResult<JsValue> {
116
+ let rt = runtime();
117
+ let this = cx.this::<JsBox<Self>>()?;
118
+ let reader = rt.block_on(async { this.reader.lock().await });
119
+ let is_embedded = reader.is_embedded();
120
+ Ok(cx.boolean(is_embedded).upcast())
121
+ }
122
+
123
+ pub fn resource_to_asset(mut cx: FunctionContext) -> JsResult<JsPromise> {
124
+ let rt = runtime();
125
+ let channel = cx.channel();
126
+ let uri = cx.argument::<JsString>(0)?.value(&mut cx);
127
+ let output = cx
128
+ .argument::<JsObject>(1)
129
+ .and_then(|obj| parse_asset(&mut cx, obj))?;
130
+ let mut output_stream = output
131
+ .write_stream()
132
+ .or_else(|err| cx.throw_error(err.to_string()))?;
133
+ let this = cx.this::<JsBox<Self>>()?;
134
+
135
+ let reader = Arc::clone(&this.reader);
136
+
137
+ let (deferred, promise) = cx.promise();
138
+ rt.spawn(async move {
139
+ let result = reader
140
+ .lock()
141
+ .await
142
+ .resource_to_stream(&uri, &mut output_stream)
143
+ .map(|bytes_written| (bytes_written, output_stream))
144
+ .map_err(Error::from);
145
+
146
+ deferred.settle_with(&channel, move |mut cx| match result {
147
+ Ok((bytes_written, mut output_stream)) => {
148
+ let buffer = if output.name() == "destination_buffer" {
149
+ let mut buffer = Vec::new();
150
+ output_stream.rewind().unwrap();
151
+ output_stream.read_to_end(&mut buffer).unwrap();
152
+ Some(buffer)
153
+ } else {
154
+ None
155
+ };
156
+
157
+ if let Some(buffer) = buffer {
158
+ let js_buffer = JsBuffer::from_slice(&mut cx, &buffer)?;
159
+ let js_bytes_written = cx.number(bytes_written as f64);
160
+ let result = cx.empty_object();
161
+ result.set(&mut cx, "buffer", js_buffer)?;
162
+ result.set(&mut cx, "bytes_written", js_bytes_written)?;
163
+ Ok(result.upcast::<JsValue>())
164
+ } else {
165
+ Ok(cx.number(bytes_written as f64).upcast::<JsValue>())
166
+ }
167
+ }
168
+ Err(err) => as_js_error(&mut cx, err).and_then(|err| cx.throw(err)),
169
+ });
170
+ });
171
+ Ok(promise)
172
+ }
173
+
174
+ pub fn post_validate_cawg(mut cx: FunctionContext) -> JsResult<JsPromise> {
175
+ let rt = runtime();
176
+ let this = cx.this::<JsBox<Self>>()?;
177
+ let reader = Arc::clone(&this.reader);
178
+
179
+ let channel = cx.channel();
180
+ let (deferred, promise) = cx.promise();
181
+
182
+ rt.spawn(async move {
183
+ let result = reader
184
+ .lock()
185
+ .await
186
+ .post_validate_async(&CawgValidator {})
187
+ .await
188
+ .map_err(Error::from);
189
+
190
+ deferred.settle_with(&channel, move |mut cx| match result {
191
+ Ok(_) => Ok(cx.undefined()),
192
+ Err(err) => as_js_error(&mut cx, err).and_then(|err| cx.throw(err)),
193
+ });
194
+ });
195
+ Ok(promise)
196
+ }
197
+ }
@@ -0,0 +1,509 @@
1
+ // Copyright 2025 Adobe. All rights reserved.
2
+ // This file is licensed to you under the Apache License,
3
+ // Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
4
+ // or the MIT license (http://opensource.org/licenses/MIT),
5
+ // at your option.
6
+
7
+ // Unless required by applicable law or agreed to in writing,
8
+ // this software is distributed on an "AS IS" BASIS, WITHOUT
9
+ // WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
10
+ // implied. See the LICENSE-MIT and LICENSE-APACHE files for the
11
+ // specific language governing permissions and limitations under
12
+ // each license.
13
+
14
+ use crate::runtime::runtime;
15
+ use async_trait::async_trait;
16
+ use c2pa::{
17
+ create_signer,
18
+ crypto::{
19
+ raw_signature::{AsyncRawSigner, RawSigner, RawSignerError},
20
+ time_stamp::{AsyncTimeStampProvider, TimeStampProvider},
21
+ },
22
+ AsyncSigner,
23
+ Error::OtherError,
24
+ Signer, SigningAlg,
25
+ };
26
+ use neon::prelude::*;
27
+ use neon::types::buffer::TypedArray;
28
+ use std::ops::Deref;
29
+ use std::{boxed::Box, str::FromStr, sync::Arc};
30
+ use tokio::sync::oneshot;
31
+
32
+ use crate::error::Error;
33
+
34
+ #[derive(Debug, Clone)]
35
+ pub struct CallbackSignerConfig {
36
+ pub alg: SigningAlg,
37
+ pub certs: Vec<u8>,
38
+ pub reserve_size: usize,
39
+ pub tsa_url: Option<String>,
40
+ pub tsa_headers: Option<Vec<(String, String)>>,
41
+ pub tsa_body: Option<Vec<u8>>,
42
+ pub direct_cose_handling: bool,
43
+ }
44
+
45
+ impl CallbackSignerConfig {
46
+ pub fn new(
47
+ alg: SigningAlg,
48
+ certs: Vec<u8>,
49
+ reserve_size: usize,
50
+ tsa_url: Option<String>,
51
+ tsa_headers: Option<Vec<(String, String)>>,
52
+ tsa_body: Option<Vec<u8>>,
53
+ direct_cose_handling: bool,
54
+ ) -> Self {
55
+ Self {
56
+ alg,
57
+ certs,
58
+ reserve_size,
59
+ tsa_url,
60
+ tsa_headers,
61
+ tsa_body,
62
+ direct_cose_handling,
63
+ }
64
+ }
65
+
66
+ pub fn from_js_config<'a>(
67
+ cx: &mut FunctionContext<'a>,
68
+ js_config: Handle<JsObject>,
69
+ ) -> JsResult<'a, JsBox<Self>> {
70
+ let alg_str: String = js_config
71
+ .get::<JsString, _, _>(cx, "alg")?
72
+ .downcast_or_throw::<JsString, _>(cx)?
73
+ .value(cx);
74
+ let alg = SigningAlg::from_str(&alg_str)
75
+ .or_else(|_| SigningAlg::from_str(&alg_str.to_uppercase()))
76
+ .or_else(|err| cx.throw_error(err.to_string()))?;
77
+
78
+ // Handle certs as an optional array of buffers
79
+ let certs_array = js_config
80
+ .get::<JsArray, _, _>(cx, "certs")?
81
+ .downcast_or_throw::<JsArray, _>(cx)?;
82
+ let mut certs = Vec::new();
83
+ for i in 0..certs_array.len(cx) {
84
+ let cert_buffer = certs_array
85
+ .get::<JsBuffer, _, _>(cx, i)?
86
+ .downcast_or_throw::<JsBuffer, _>(cx)?;
87
+ certs.extend_from_slice(cert_buffer.as_slice(cx));
88
+ }
89
+
90
+ let reserve_size = js_config
91
+ .get::<JsNumber, _, _>(cx, "reserveSize")?
92
+ .value(cx) as usize;
93
+ let tsa_url = js_config
94
+ .get_opt::<JsString, _, _>(cx, "tsaUrl")?
95
+ .map(|js_string| js_string.value(cx));
96
+ let direct_cose_handling = js_config
97
+ .get::<JsBoolean, _, _>(cx, "directCoseHandling")?
98
+ .downcast_or_throw::<JsBoolean, _>(cx)?
99
+ .value(cx);
100
+ let tsa_headers =
101
+ if let Some(js_array) = js_config.get_opt::<JsArray, _, _>(cx, "tsaHeaders")? {
102
+ let len = js_array.len(cx);
103
+ let mut headers = Vec::new();
104
+ for i in 0..len {
105
+ let js_tuple = js_array
106
+ .get::<JsArray, _, _>(cx, i)?
107
+ .downcast_or_throw::<JsArray, _>(cx)?;
108
+ let key = js_tuple
109
+ .get::<JsString, _, _>(cx, 0)?
110
+ .downcast_or_throw::<JsString, _>(cx)?;
111
+ let value = js_tuple
112
+ .get::<JsString, _, _>(cx, 1)?
113
+ .downcast_or_throw::<JsString, _>(cx)?;
114
+ headers.push((key.value(cx), value.value(cx)));
115
+ }
116
+ Some(headers)
117
+ } else {
118
+ None
119
+ };
120
+ let tsa_body = js_config
121
+ .get_opt::<JsBuffer, _, _>(cx, "tsaBody")?
122
+ .map(|js_buffer| js_buffer.as_slice(cx).to_vec());
123
+
124
+ Ok(cx.boxed(Self::new(
125
+ alg,
126
+ certs,
127
+ reserve_size,
128
+ tsa_url,
129
+ tsa_headers,
130
+ tsa_body,
131
+ direct_cose_handling,
132
+ )))
133
+ }
134
+ }
135
+
136
+ // Add a new function to convert a JavaScript object to a JsBox<CallbackSignerConfig>
137
+ pub fn callback_signer_config_from_js(
138
+ mut cx: FunctionContext,
139
+ ) -> JsResult<JsBox<CallbackSignerConfig>> {
140
+ let js_config = cx.argument::<JsObject>(0)?;
141
+ CallbackSignerConfig::from_js_config(&mut cx, js_config)
142
+ }
143
+
144
+ #[derive(Clone)]
145
+ pub struct NeonCallbackSigner {
146
+ channel: Channel,
147
+ // JsFunction must be of the form (data: Buffer) => Promise<Buffer>
148
+ callback: Arc<Root<JsFunction>>,
149
+ config: CallbackSignerConfig,
150
+ }
151
+
152
+ impl NeonCallbackSigner {
153
+ pub fn new(
154
+ channel: Channel,
155
+ callback: Arc<Root<JsFunction>>,
156
+ config: CallbackSignerConfig,
157
+ ) -> Self {
158
+ Self {
159
+ channel,
160
+ callback,
161
+ config,
162
+ }
163
+ }
164
+
165
+ pub fn from_config(mut cx: FunctionContext) -> JsResult<JsBox<Self>> {
166
+ let config_handle = cx.argument::<JsBox<CallbackSignerConfig>>(0)?;
167
+ let config_ref: &CallbackSignerConfig = config_handle.deref();
168
+ let callback = cx.argument::<JsFunction>(1)?.root(&mut cx);
169
+ let channel = cx.channel();
170
+ Ok(cx.boxed(Self::new(channel, Arc::new(callback), config_ref.clone())))
171
+ }
172
+
173
+ pub fn alg(mut cx: FunctionContext) -> JsResult<JsString> {
174
+ let this = cx.this::<JsBox<Self>>()?;
175
+ let alg = this.config.alg.to_string();
176
+ Ok(cx.string(alg))
177
+ }
178
+
179
+ pub fn certs(mut cx: FunctionContext) -> JsResult<JsArray> {
180
+ let this = cx.this::<JsBox<Self>>()?;
181
+ let certs = this.config.certs.clone();
182
+ let js_array = JsArray::new(&mut cx, certs.len());
183
+ for (i, byte) in certs.iter().enumerate() {
184
+ let js_value = cx.number(*byte as f64);
185
+ js_array.set(&mut cx, i as u32, js_value)?;
186
+ }
187
+ Ok(js_array)
188
+ }
189
+
190
+ pub fn reserve_size(mut cx: FunctionContext) -> JsResult<JsNumber> {
191
+ let this = cx.this::<JsBox<Self>>()?;
192
+ let reserve_size = this.config.reserve_size;
193
+ Ok(cx.number(reserve_size as f64))
194
+ }
195
+
196
+ pub fn time_authority_url(mut cx: FunctionContext) -> JsResult<JsValue> {
197
+ let this = cx.this::<JsBox<Self>>()?;
198
+ match this.config.tsa_url.clone() {
199
+ Some(url) => Ok(cx.string(url).upcast()),
200
+ None => Ok(cx.undefined().upcast()),
201
+ }
202
+ }
203
+
204
+ pub fn sign(mut cx: FunctionContext) -> JsResult<JsPromise> {
205
+ let rt = runtime();
206
+ let this = cx.this::<JsBox<Self>>()?;
207
+ let data = cx.argument::<JsBuffer>(0)?.as_slice(&cx).to_vec();
208
+ let (deferred, promise) = cx.promise();
209
+ let channel = cx.channel().clone();
210
+ let callback = this.callback.clone();
211
+ let config = this.config.clone();
212
+
213
+ rt.spawn(async move {
214
+ let signer = NeonCallbackSigner::new(channel.clone(), callback, config);
215
+ let result = <Self as AsyncSigner>::sign(&signer, data)
216
+ .await
217
+ .map_err(|e| e.to_string());
218
+
219
+ deferred.settle_with(&channel, move |mut cx| match result {
220
+ Ok(signature) => {
221
+ let buffer = JsBuffer::from_slice(&mut cx, &signature)?;
222
+ Ok(buffer.upcast::<JsValue>())
223
+ }
224
+ Err(e) => cx.throw_error(e),
225
+ });
226
+ });
227
+
228
+ Ok(promise)
229
+ }
230
+
231
+ pub fn as_raw_signer(&self) -> &dyn AsyncRawSigner {
232
+ self
233
+ }
234
+ }
235
+
236
+ /// # Safety
237
+ ///
238
+ /// The implementations of `Send` and `Sync` are marked as `unsafe` because the compiler cannot automatically
239
+ /// verify that the type is safe to send or share between threads. This is because:
240
+ /// - The type contains `RwLock` fields (`signer` and `identity_assertions`)
241
+ /// - The type interacts with JavaScript through Neon bindings
242
+ /// - The type contains references to JavaScript objects and callbacks
243
+ ///
244
+ /// However, the implementation is safe because:
245
+ /// - The `RwLock` fields provide thread-safe access to the contained data
246
+ /// - The JavaScript interactions are properly synchronized through the Neon runtime
247
+ /// - The type is used in a controlled environment where the JavaScript context is properly managed
248
+ /// - The type is used in a way that ensures proper synchronization of access to its resources
249
+ ///
250
+ /// These traits are necessary because:
251
+ /// - `Send`: Allows the type to be transferred between threads
252
+ /// - `Sync`: Allows the type to be shared between threads
253
+ ///
254
+ /// The type needs these capabilities because it:
255
+ /// - Implements `AsyncSigner` and `AsyncRawSigner` traits for asynchronous signing operations
256
+ /// - Is used in the `identity_sign_async` function which performs asynchronous operations
257
+ /// - Is part of a Node.js binding where async operations are common
258
+ unsafe impl Send for NeonCallbackSigner {}
259
+ unsafe impl Sync for NeonCallbackSigner {}
260
+
261
+ #[async_trait]
262
+ impl AsyncSigner for NeonCallbackSigner {
263
+ async fn sign(&self, data: Vec<u8>) -> Result<Vec<u8>, c2pa::Error> {
264
+ let (tx, rx) = oneshot::channel();
265
+ let sign_fn = self.callback.clone();
266
+ let data = data.to_vec();
267
+
268
+ self.channel
269
+ .try_send(move |mut cx| {
270
+ let to_be_signed = JsBuffer::from_slice(&mut cx, &data)?;
271
+ let sign_fn = sign_fn.to_inner(&mut cx);
272
+
273
+ let sign_fut = sign_fn
274
+ .call_with(&cx)
275
+ .arg(to_be_signed)
276
+ .apply::<JsPromise, _>(&mut cx)?
277
+ .to_future(&mut cx, |mut cx, result| match result {
278
+ Ok(value) => Ok(Ok(value
279
+ .downcast_or_throw::<JsBuffer, _>(&mut cx)?
280
+ .as_slice(&cx)
281
+ .to_vec())),
282
+ Err(err) => {
283
+ let js_string_result = err.to_string(&mut cx);
284
+ match js_string_result {
285
+ Ok(js_string) => {
286
+ let err_string: String = js_string.value(&mut cx);
287
+ Ok(Err(OtherError(Box::new(Error::AsyncSigning(err_string)))))
288
+ }
289
+ Err(throw) => Err(throw),
290
+ }
291
+ }
292
+ })?;
293
+
294
+ let _ = tx.send(sign_fut);
295
+
296
+ Ok(())
297
+ })
298
+ .map_err(|err| OtherError(Box::new(err)))?;
299
+
300
+ let sign_fut = rx.await.map_err(|err| OtherError(Box::new(err)))?;
301
+
302
+ let sign_result = sign_fut
303
+ .await
304
+ .map_err(|err| OtherError(Box::new(err)))?
305
+ .map_err(|err| OtherError(Box::new(err)))?;
306
+
307
+ Ok(sign_result)
308
+ }
309
+
310
+ fn alg(&self) -> SigningAlg {
311
+ self.config.alg
312
+ }
313
+
314
+ fn certs(&self) -> Result<Vec<Vec<u8>>, c2pa::Error> {
315
+ let pems = pem::parse_many(&self.config.certs).map_err(|e| OtherError(Box::new(e)))?;
316
+ Ok(pems.into_iter().map(|p| p.into_contents()).collect())
317
+ }
318
+
319
+ fn reserve_size(&self) -> usize {
320
+ self.config.reserve_size
321
+ }
322
+
323
+ fn direct_cose_handling(&self) -> bool {
324
+ // TODO: The direct_cose_handling field is currently not used in the signing logic.
325
+ // The field is read from config and exposed via this getter, but the actual signing
326
+ // implementation does not differentiate between directCoseHandling: true/false.
327
+ // Both cases pass the same data to the JavaScript callback regardless of this setting.
328
+ self.config.direct_cose_handling
329
+ }
330
+ }
331
+
332
+ impl TimeStampProvider for NeonCallbackSigner {
333
+ fn time_stamp_service_url(&self) -> Option<String> {
334
+ self.config.tsa_url.clone()
335
+ }
336
+ fn time_stamp_request_headers(&self) -> Option<Vec<(String, String)>> {
337
+ self.config.tsa_headers.clone()
338
+ }
339
+ }
340
+
341
+ impl AsyncTimeStampProvider for NeonCallbackSigner {
342
+ fn time_stamp_service_url(&self) -> Option<String> {
343
+ self.config.tsa_url.clone()
344
+ }
345
+ fn time_stamp_request_headers(&self) -> Option<Vec<(String, String)>> {
346
+ self.config.tsa_headers.clone()
347
+ }
348
+ }
349
+
350
+ #[async_trait]
351
+ impl AsyncRawSigner for NeonCallbackSigner {
352
+ async fn sign(&self, data: Vec<u8>) -> Result<Vec<u8>, RawSignerError> {
353
+ let (tx, rx) = oneshot::channel();
354
+ let sign_fn = self.callback.clone();
355
+ let data = data.to_vec();
356
+
357
+ // Send the signing request to the JavaScript side
358
+ self.channel
359
+ .try_send(move |mut cx| {
360
+ let to_be_signed = JsBuffer::from_slice(&mut cx, &data)?;
361
+ let sign_fn = sign_fn.to_inner(&mut cx);
362
+
363
+ let sign_fut = sign_fn
364
+ .call_with(&cx)
365
+ .arg(to_be_signed)
366
+ .apply::<JsPromise, _>(&mut cx)?
367
+ .to_future(&mut cx, |mut cx, result| match result {
368
+ Ok(value) => {
369
+ let buffer = value.downcast_or_throw::<JsBuffer, _>(&mut cx)?;
370
+ Ok(Ok(buffer.as_slice(&cx).to_vec()))
371
+ }
372
+ Err(err) => {
373
+ let err_string = match err.to_string(&mut cx) {
374
+ Ok(js_string) => js_string.value(&mut cx),
375
+ Err(e) => return Err(e),
376
+ };
377
+ Ok(Err(RawSignerError::CryptoLibraryError(err_string)))
378
+ }
379
+ })?;
380
+
381
+ let _ = tx.send(sign_fut);
382
+ Ok(())
383
+ })
384
+ .map_err(|err| RawSignerError::CryptoLibraryError(err.to_string()))?;
385
+
386
+ // Wait for the JavaScript promise to resolve
387
+ let sign_fut = rx
388
+ .await
389
+ .map_err(|err| RawSignerError::CryptoLibraryError(err.to_string()))?;
390
+
391
+ // Get the result from the future
392
+ sign_fut
393
+ .await
394
+ .map_err(|err| RawSignerError::CryptoLibraryError(err.to_string()))?
395
+ }
396
+
397
+ fn alg(&self) -> SigningAlg {
398
+ self.config.alg
399
+ }
400
+
401
+ fn cert_chain(&self) -> Result<Vec<Vec<u8>>, RawSignerError> {
402
+ let pems = pem::parse_many(&self.config.certs)
403
+ .map_err(|e| RawSignerError::CryptoLibraryError(e.to_string()))?;
404
+ Ok(pems.into_iter().map(|p| p.into_contents()).collect())
405
+ }
406
+
407
+ fn reserve_size(&self) -> usize {
408
+ self.config.reserve_size
409
+ }
410
+
411
+ async fn ocsp_response(&self) -> Option<Vec<u8>> {
412
+ None
413
+ }
414
+ }
415
+
416
+ impl RawSigner for NeonCallbackSigner {
417
+ fn sign(&self, _data: &[u8]) -> Result<Vec<u8>, RawSignerError> {
418
+ // Synchronous signing is not supported; use AsyncRawSigner instead
419
+ Err(RawSignerError::InternalError(
420
+ "Synchronous signing not supported - use AsyncRawSigner instead".to_string(),
421
+ ))
422
+ }
423
+
424
+ fn alg(&self) -> SigningAlg {
425
+ AsyncRawSigner::alg(self)
426
+ }
427
+
428
+ fn cert_chain(&self) -> Result<Vec<Vec<u8>>, RawSignerError> {
429
+ AsyncRawSigner::cert_chain(self)
430
+ }
431
+
432
+ fn reserve_size(&self) -> usize {
433
+ AsyncRawSigner::reserve_size(self)
434
+ }
435
+ }
436
+
437
+ pub struct NeonLocalSigner {
438
+ signer: Box<dyn Signer>,
439
+ }
440
+
441
+ impl NeonLocalSigner {
442
+ pub fn new(mut cx: FunctionContext) -> JsResult<JsBox<Self>> {
443
+ let signcert = cx.argument::<JsBuffer>(0)?.as_slice(&cx).to_vec();
444
+ let pkey = cx.argument::<JsBuffer>(1)?.as_slice(&cx).to_vec();
445
+ let alg_str = cx.argument::<JsString>(2)?.value(&mut cx);
446
+ let alg = SigningAlg::from_str(&alg_str).or_else(|err| cx.throw_error(err.to_string()))?;
447
+ let tsa_url = cx.argument_opt(3).and_then(|js_value| {
448
+ js_value
449
+ .downcast::<JsString, _>(&mut cx)
450
+ .ok()
451
+ .map(|js_string| js_string.value(&mut cx))
452
+ });
453
+ let signer = create_signer::from_keys(&signcert, &pkey, alg, tsa_url)
454
+ .or_else(|err| cx.throw_error(format!("Failed to create signer from keys: {err}")))?;
455
+ Ok(cx.boxed(Self { signer }))
456
+ }
457
+
458
+ #[allow(clippy::borrowed_box)]
459
+ pub(crate) fn signer(&self) -> &Box<dyn Signer> {
460
+ &self.signer
461
+ }
462
+
463
+ pub fn sign(mut cx: FunctionContext) -> JsResult<JsBuffer> {
464
+ let this = cx.this::<JsBox<Self>>()?;
465
+ let data = cx.argument::<JsBuffer>(0)?.as_slice(&cx).to_vec();
466
+ let signature =
467
+ Signer::sign(&this.signer, &data).or_else(|err| cx.throw_error(err.to_string()))?;
468
+ let buffer = JsBuffer::from_slice(&mut cx, signature.as_slice())?;
469
+ Ok(buffer)
470
+ }
471
+
472
+ pub fn alg(mut cx: FunctionContext) -> JsResult<JsString> {
473
+ let this = cx.this::<JsBox<Self>>()?;
474
+ let alg = Signer::alg(&this.signer).to_string();
475
+ Ok(cx.string(alg))
476
+ }
477
+
478
+ pub fn certs(mut cx: FunctionContext) -> JsResult<JsArray> {
479
+ let this = cx.this::<JsBox<Self>>()?;
480
+ let certs = this
481
+ .signer
482
+ .certs()
483
+ .or_else(|err| cx.throw_error(err.to_string()))?;
484
+ let js_array = JsArray::new(&mut cx, certs.len());
485
+ for (i, cert) in certs.iter().enumerate() {
486
+ let js_buffer = JsBuffer::from_slice(&mut cx, cert.as_slice())?;
487
+ js_array.set(&mut cx, i as u32, js_buffer)?;
488
+ }
489
+ Ok(js_array)
490
+ }
491
+
492
+ pub fn reserve_size(mut cx: FunctionContext) -> JsResult<JsNumber> {
493
+ let this = cx.this::<JsBox<Self>>()?;
494
+ let reserve_size = Signer::reserve_size(&this.signer);
495
+ Ok(cx.number(reserve_size as f64))
496
+ }
497
+
498
+ pub fn time_authority_url(mut cx: FunctionContext) -> JsResult<JsValue> {
499
+ let this = cx.this::<JsBox<Self>>()?;
500
+ match this.signer.time_authority_url() {
501
+ Some(url) => Ok(cx.string(url).upcast()),
502
+ None => Ok(cx.undefined().upcast()),
503
+ }
504
+ }
505
+ }
506
+
507
+ impl Finalize for NeonLocalSigner {}
508
+ impl Finalize for CallbackSignerConfig {}
509
+ impl Finalize for NeonCallbackSigner {}