@contentauth/c2pa-node 0.2.1 → 0.2.2

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 ADDED
@@ -0,0 +1,38 @@
1
+ [package]
2
+ name = "c2pa-node"
3
+ version = "0.1.0"
4
+ license = "MIT"
5
+ edition = "2021"
6
+ exclude = ["index.node"]
7
+
8
+ [lib]
9
+ crate-type = ["cdylib"]
10
+
11
+ [dependencies]
12
+ async-trait = "0.1.77"
13
+ ciborium = "0.2.2"
14
+ c2pa = { version = "0.64", default-features = false, features = ["file_io", "pdf", "fetch_remote_manifests", "add_thumbnails", "rust_native_crypto"] }
15
+ futures = "0.3"
16
+ image = "0.25.6"
17
+ neon = { version = "1.0.0", default-features = false, features = [
18
+ "futures",
19
+ "napi-6",
20
+ ] }
21
+ neon-serde4 = "1.0.0"
22
+ pem = "3.0.4"
23
+ reqwest = { version = "0.12.2", default-features = false, features = [
24
+ "blocking",
25
+ "brotli",
26
+ "deflate",
27
+ "gzip",
28
+ "rustls-tls",
29
+ ] }
30
+ serde = { version = "1.0.203", features = ["derive"] }
31
+ serde_bytes = "0.11.15"
32
+ serde_json = "1.0.117"
33
+ toml = "0.8"
34
+ thiserror = "1.0.61"
35
+ tokio = { version = "1.43.0", features = ["rt-multi-thread"] }
36
+ tokio-util = "0.7.13"
37
+ trustmark = "0.2"
38
+ rand = "0.8.5"
package/dist/index.node CHANGED
Binary file
package/package.json CHANGED
@@ -4,12 +4,16 @@
4
4
  "type": "git",
5
5
  "url": "git+https://github.com/contentauth/c2pa-node-v2.git"
6
6
  },
7
- "version": "0.2.1",
7
+ "version": "0.2.2",
8
8
  "description": "Node.js bindings for C2PA",
9
9
  "main": "dist/index.js",
10
10
  "types": "dist/types/index.d.ts",
11
11
  "files": [
12
- "dist"
12
+ "dist",
13
+ "scripts",
14
+ "src",
15
+ "Cargo.toml",
16
+ "Cargo.lock"
13
17
  ],
14
18
  "engines": {
15
19
  "node": ">=18.20.2"
@@ -31,7 +35,6 @@
31
35
  "cbor2": "^2.0.1",
32
36
  "cpy-cli": "^5.0.0",
33
37
  "eslint": "^9.33.0",
34
- "fs-extra": "^11.3.1",
35
38
  "npm-run-all": "^4.1.5",
36
39
  "rimraf": "^6.0.1",
37
40
  "sharp": "^0.34.3",
@@ -49,8 +52,15 @@
49
52
  },
50
53
  "homepage": "https://github.com/contentauth/c2pa-node-v2#readme",
51
54
  "dependencies": {
55
+ "cargo-cp-artifact": "^0.1.0",
56
+ "cli-progress": "^3.2.0",
52
57
  "debug": "^4.4.1",
53
- "node-fetch": "^3.3.2"
58
+ "fs-extra": "^11.3.1",
59
+ "mkdirp": "^3.0.0",
60
+ "node-fetch": "^3.3.2",
61
+ "pkg-dir": "^8.0.0",
62
+ "pretty-bytes": "^6.0.0",
63
+ "unzipper": "^0.10.0"
54
64
  },
55
65
  "scripts": {
56
66
  "build": "run-s build:rust build:ts",
@@ -69,6 +79,7 @@
69
79
  "lint": "cargo clippy && pnpm eslint",
70
80
  "postbuild:rust-debug": "neon dist < cargo.log",
71
81
  "postcross-build": "neon dist -m /target < cross.log",
82
+ "postinstall": "node scripts/postinstall.js",
72
83
  "release": "run-s build changeset:publish",
73
84
  "test": "pnpm build:debug && vitest run",
74
85
  "test:watch": "pnpm build:debug && vitest",
@@ -0,0 +1,212 @@
1
+ /**
2
+ * Copyright 2023 Adobe
3
+ * All Rights Reserved.
4
+ *
5
+ * NOTICE: Adobe permits you to use, modify, and distribute this file in
6
+ * accordance with the terms of the Adobe license agreement accompanying
7
+ * it.
8
+ */
9
+
10
+ const { stat, readFile } = require('node:fs/promises');
11
+ const { createWriteStream } = require('node:fs');
12
+ const { PassThrough } = require('node:stream');
13
+ const cliProgress = require('cli-progress');
14
+ const unzipper = require('unzipper');
15
+ const os = require('node:os');
16
+ const { mkdirp } = require('mkdirp');
17
+ const { resolve } = require('node:path');
18
+ const { exec } = require('node:child_process');
19
+ const { promisify } = require('node:util');
20
+
21
+ const pExec = promisify(exec);
22
+
23
+ const execCallback = (err, stdout, stderr) => {
24
+ if (err) {
25
+ console.error(`ERROR: ${err}`);
26
+ } else if (stdout) {
27
+ console.log(stdout);
28
+ } else if (stderr) {
29
+ console.error(stderr);
30
+ }
31
+ };
32
+
33
+ async function fileExists(path) {
34
+ try {
35
+ await stat(path);
36
+ return true;
37
+ } catch (err) {
38
+ if (err.code === 'ENOENT') {
39
+ return false;
40
+ }
41
+ throw err;
42
+ }
43
+ }
44
+
45
+ function getPlatform() {
46
+ const arch = os.arch();
47
+ const platform = os.platform();
48
+
49
+ console.debug('Detected', { arch, platform });
50
+
51
+ if (arch === 'arm64' && platform === 'linux') {
52
+ return 'aarch64-unknown-linux-gnu';
53
+ } else if (arch === 'x64' && platform === 'linux') {
54
+ return 'x86_64-unknown-linux-gnu';
55
+ } else if (arch === 'arm64' && platform === 'darwin') {
56
+ return 'aarch64-apple-darwin';
57
+ } else if (arch === 'x64' && platform === 'darwin') {
58
+ return 'x86_64-apple-darwin';
59
+ } else if (platform === 'win32') {
60
+ return 'x86_64-pc-windows-msvc';
61
+ }
62
+
63
+ console.log(
64
+ `Can not find binary for architecture: ${arch} and platform: ${platform}, attempting to build Rust`,
65
+ );
66
+
67
+ return null;
68
+ }
69
+
70
+ async function downloadFromUrl(appRoot, url) {
71
+ console.log(`Checking for a release at: ${url}`);
72
+ // Dynamic import for ES modules
73
+ const fetchModule = await import('node-fetch');
74
+ const fetch = fetchModule.default;
75
+ const res = await fetch(url);
76
+
77
+ if (res.ok) {
78
+ // Dynamic import for ES module
79
+ const { default: prettyBytes } = await import('pretty-bytes');
80
+
81
+ const destDir = resolve(appRoot, 'dist', 'generated');
82
+ const totalSize = parseInt(res.headers.get('Content-Length'), 10);
83
+ await mkdirp(destDir);
84
+ const destPath = resolve(destDir, 'c2pa.node');
85
+ const destStream = createWriteStream(destPath);
86
+ const progress = new PassThrough();
87
+ const bar = new cliProgress.SingleBar(
88
+ {
89
+ format:
90
+ 'Downloading | {bar} | {value_formatted} / {total_formatted} ({percentage}%) | ETA: {eta}s',
91
+ },
92
+ cliProgress.Presets.shades_classic,
93
+ );
94
+ let downloaded = 0;
95
+
96
+ bar.start(totalSize, 0, {
97
+ value_formatted: prettyBytes(0),
98
+ total_formatted: prettyBytes(totalSize),
99
+ });
100
+
101
+ progress.on('data', (chunk) => {
102
+ downloaded += chunk.length;
103
+ bar.update(downloaded, {
104
+ value_formatted: prettyBytes(downloaded),
105
+ total_formatted: prettyBytes(totalSize),
106
+ });
107
+ });
108
+
109
+ return new Promise((resolve, reject) => {
110
+ res.body
111
+ .pipe(progress)
112
+ .pipe(unzipper.ParseOne())
113
+ .pipe(destStream)
114
+ .on('finish', () => {
115
+ bar.stop();
116
+ console.log(`Downloaded to ${destPath}`);
117
+ resolve(true);
118
+ })
119
+ .on('error', reject);
120
+ });
121
+ }
122
+
123
+ return false;
124
+ }
125
+
126
+ async function downloadBinary(appRoot) {
127
+ const pkgPath = resolve(appRoot, 'package.json');
128
+ const pkg = JSON.parse(await readFile(pkgPath));
129
+ const repo = pkg.repository?.url ?? pkg.repository;
130
+ const repoBase = (repo ?? '').replace(/^git\+/, '').replace(/\.git$/i, '');
131
+ const version = pkg.version;
132
+ const platform = getPlatform();
133
+
134
+ if (repoBase && version && platform) {
135
+ const fileName = `c2pa-node_${platform}-v${version}.zip`;
136
+ const downloadUrl = [
137
+ repoBase,
138
+ 'releases',
139
+ 'download',
140
+ `v${version}`,
141
+ fileName,
142
+ ].join('/');
143
+ return downloadFromUrl(appRoot, downloadUrl);
144
+ }
145
+
146
+ return false;
147
+ }
148
+
149
+ async function rustExists() {
150
+ try {
151
+ await Promise.all([pExec('rustc --version'), pExec('cargo --version')]);
152
+ return true;
153
+ } catch {
154
+ return false;
155
+ }
156
+ }
157
+
158
+ async function buildRust(root) {
159
+ console.log('🦀 Building Rust...');
160
+ const generatedDir = resolve(root, 'generated');
161
+ const bindingsPath = resolve(generatedDir, 'c2pa.node');
162
+ const cargoPath = resolve(root, 'Cargo.toml');
163
+ await mkdirp(generatedDir);
164
+ return new Promise((resolve, reject) => {
165
+ const result = exec(
166
+ `npx cargo-cp-artifact -nc "${bindingsPath}" -- cargo build --message-format=json-render-diagnostics --release --manifest-path="${cargoPath}"`,
167
+ execCallback,
168
+ );
169
+ result.on('exit', (code) => {
170
+ code === 0 ? resolve() : reject();
171
+ });
172
+ });
173
+ }
174
+
175
+ async function main() {
176
+ // Dynamic import for ES module
177
+ const pkgDirModule = await import('pkg-dir');
178
+ const pkgDir = pkgDirModule.packageDirectory;
179
+ const appRoot = await pkgDir(__dirname);
180
+ const distRoot = resolve(appRoot, 'dist');
181
+ const cargoDistPath = resolve(distRoot, 'Cargo.toml');
182
+ const libraryOverridePath = process.env.C2PA_LIBRARY_PATH;
183
+ const cargoDistPathExists = await fileExists(cargoDistPath);
184
+ const rustToolchainExists = await rustExists();
185
+
186
+ if (libraryOverridePath) {
187
+ console.log('Skipping Rust build since C2PA_LIBRARY_PATH is set');
188
+ return;
189
+ }
190
+
191
+ if (process.env.SKIP_BINARY_DOWNLOAD) {
192
+ console.log(
193
+ 'Skipping prebuilt binary download since SKIP_BINARY_DOWNLOAD is set',
194
+ );
195
+ } else if (await downloadBinary(appRoot)) {
196
+ return;
197
+ }
198
+
199
+ if (!rustToolchainExists) {
200
+ console.warn('Skipping Rust build since Rust and/or Cargo is not found');
201
+ } else if (cargoDistPathExists) {
202
+ await buildRust(distRoot);
203
+ } else {
204
+ await buildRust(appRoot);
205
+ }
206
+ }
207
+
208
+ if (!process.env.SKIP_RUST_BUILD) {
209
+ main();
210
+ } else {
211
+ console.log('Skipping Rust build since SKIP_RUST_BUILD is set');
212
+ }
package/src/asset.rs ADDED
@@ -0,0 +1,114 @@
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::error::Error;
15
+ use c2pa::format_from_path;
16
+ use neon::prelude::*;
17
+ use neon::types::buffer::TypedArray;
18
+ use std::fs::{File, OpenOptions};
19
+ use std::io::{BufReader, Cursor, Read, Seek, Write};
20
+ use std::path::Path;
21
+
22
+ pub(crate) trait NeonReadStreamTrait: Read + Seek + Send {}
23
+ pub(crate) trait NeonWriteStreamTrait: Write + Read + Seek + Send {}
24
+
25
+ impl NeonReadStreamTrait for Cursor<Vec<u8>> {}
26
+ impl NeonReadStreamTrait for BufReader<File> {}
27
+
28
+ impl NeonWriteStreamTrait for Cursor<Vec<u8>> {}
29
+ impl NeonWriteStreamTrait for File {}
30
+
31
+ pub enum Asset {
32
+ SourceBuffer(Vec<u8>, String),
33
+ File(String, Option<String>),
34
+ DestinationBuffer(Vec<u8>),
35
+ }
36
+
37
+ impl Asset {
38
+ pub fn mime_type(&self) -> Option<String> {
39
+ match self {
40
+ Asset::SourceBuffer(_, mime_type) => Some(mime_type.to_string()),
41
+ Asset::File(path, mime_type) => match mime_type {
42
+ Some(mime_type) => Some(mime_type.to_string()),
43
+ None => format_from_path(Path::new(&path)),
44
+ },
45
+ _ => None,
46
+ }
47
+ }
48
+ pub fn into_read_stream(self) -> Result<Box<dyn NeonReadStreamTrait>, Error> {
49
+ match self {
50
+ Asset::SourceBuffer(buffer, _) => Ok(Box::new(Cursor::new(buffer))),
51
+ Asset::File(path, _) => {
52
+ let file = File::open(Path::new(&path)).map_err(Error::from)?;
53
+ Ok(Box::new(BufReader::new(file)))
54
+ }
55
+ _ => Err(Error::Asset("Cannot write to source buffer".to_string())),
56
+ }
57
+ }
58
+
59
+ pub fn write_stream(&self) -> Result<Box<dyn NeonWriteStreamTrait>, Error> {
60
+ match self {
61
+ Asset::File(path, _) => {
62
+ let file = OpenOptions::new()
63
+ .read(true)
64
+ .write(true)
65
+ .create(true)
66
+ .truncate(true)
67
+ .open(Path::new(&path))
68
+ .map_err(Error::from)?;
69
+ Ok(Box::new(file))
70
+ }
71
+ Asset::DestinationBuffer(buffer) => Ok(Box::new(Cursor::new(buffer.to_owned()))),
72
+ _ => Err(Error::Asset("Cannot write to source buffer".to_string())),
73
+ }
74
+ }
75
+
76
+ pub fn name(&self) -> &str {
77
+ match self {
78
+ Asset::File(_, _) => "file",
79
+ Asset::DestinationBuffer(_) => "destination_buffer",
80
+ Asset::SourceBuffer(_, _) => "source_buffer",
81
+ }
82
+ }
83
+ }
84
+
85
+ pub fn parse_asset(cx: &mut FunctionContext, obj: Handle<JsObject>) -> NeonResult<Asset> {
86
+ let mime_type = obj
87
+ .get_opt::<JsString, _, _>(cx, "mimeType")?
88
+ .map(|val| val.value(cx))
89
+ .or(None);
90
+ let path = obj
91
+ .get_opt::<JsString, _, _>(cx, "path")?
92
+ .map(|val| val.value(cx))
93
+ .or(None);
94
+ let buffer_value = obj.get::<JsValue, _, _>(cx, "buffer")?;
95
+ let buffer = if buffer_value.is_a::<JsBuffer, _>(cx) {
96
+ Some(
97
+ buffer_value
98
+ .downcast_or_throw::<JsBuffer, _>(cx)?
99
+ .as_slice(cx)
100
+ .to_vec(),
101
+ )
102
+ } else {
103
+ None
104
+ };
105
+
106
+ match (buffer, mime_type.clone(), path) {
107
+ (Some(buffer), Some(mime_type), _) => Ok(Asset::SourceBuffer(buffer, mime_type)),
108
+ (None, _, Some(path)) => Ok(Asset::File(path, mime_type)),
109
+ (None, _, None) => Ok(Asset::DestinationBuffer(Vec::new())),
110
+ _ => cx.throw_error(
111
+ "Invalid asset data passed. Must contain either a buffer and mimeType or a path.",
112
+ ),
113
+ }
114
+ }
package/src/error.rs ADDED
@@ -0,0 +1,104 @@
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 std::sync::PoisonError;
15
+
16
+ use neon::prelude::*;
17
+ use thiserror::Error;
18
+
19
+ #[derive(Error, Debug)]
20
+ pub enum Error {
21
+ #[error("Asset parsing failed: {0}")]
22
+ Asset(String),
23
+
24
+ #[error("Async signing failed {0}")]
25
+ AsyncSigning(String),
26
+
27
+ #[error(transparent)]
28
+ C2pa(#[from] c2pa::Error),
29
+
30
+ #[error(transparent)]
31
+ FileIO(#[from] std::io::Error),
32
+
33
+ #[error(transparent)]
34
+ Image(#[from] image::ImageError),
35
+
36
+ #[error(transparent)]
37
+ Json(#[from] serde_json::Error),
38
+
39
+ #[error("Lock acquisition failed: {0}")]
40
+ Lock(String),
41
+
42
+ #[error(transparent)]
43
+ NeonSerde(#[from] neon_serde4::errors::Error),
44
+
45
+ #[error("Trustmark model download failed")]
46
+ ModelDownload(String),
47
+
48
+ #[error(transparent)]
49
+ RemoteManifestFetch(#[from] reqwest::Error),
50
+
51
+ #[error("Settings handling failed: {0}")]
52
+ Settings(String),
53
+
54
+ #[error("Signing failed: {0}")]
55
+ Signing(String),
56
+
57
+ #[error(transparent)]
58
+ TokioJoin(#[from] tokio::task::JoinError),
59
+
60
+ #[error(transparent)]
61
+ TokioTimeout(#[from] tokio::time::error::Elapsed),
62
+
63
+ #[error(transparent)]
64
+ TokioLock(#[from] tokio::sync::TryLockError),
65
+
66
+ #[error(transparent)]
67
+ Watermark(#[from] trustmark::Error),
68
+
69
+ #[error("Watermark configuration error: {0}")]
70
+ WatermarkConfiguration(String),
71
+
72
+ #[error(transparent)]
73
+ UTF8(#[from] std::str::Utf8Error),
74
+ }
75
+
76
+ impl<T> From<PoisonError<T>> for Error {
77
+ fn from(err: PoisonError<T>) -> Self {
78
+ Error::Lock(err.to_string())
79
+ }
80
+ }
81
+
82
+ // Implement Send for Error
83
+ unsafe impl Send for Error {}
84
+ unsafe impl Sync for Error {}
85
+
86
+ #[allow(dead_code)]
87
+ pub type Result<T> = std::result::Result<T, Error>;
88
+
89
+ pub fn as_js_error<'a>(cx: &mut TaskContext<'a>, err: Error) -> JsResult<'a, JsError> {
90
+ cx.execute_scoped(|mut cx| {
91
+ let js_err = cx.error(err.to_string())?;
92
+ let js_err_name = cx.string(format!("{err:?}"));
93
+ js_err.set(&mut cx, "name", js_err_name)?;
94
+
95
+ Ok(js_err)
96
+ })
97
+ }
98
+
99
+ pub fn as_js_error_fn<'a>(cx: &mut FunctionContext<'a>, err: Error) -> JsResult<'a, JsError> {
100
+ let js_err = cx.error(err.to_string())?;
101
+ let js_err_name = cx.string(format!("{err:?}"));
102
+ js_err.set(cx, "name", js_err_name)?;
103
+ Ok(js_err)
104
+ }