# CAI Node.js library `@contentauth/c2pa-node` is a Node.js library in the [c2pa-js](https://github.com/contentauth/c2pa-js) monorepo that can: - Read and validate C2PA data from media files in supported formats. - Add signed manifests to media files in supported formats. ## Prerequisites To use the c2pa-node library, you need Node.js 22 or later. Use a patched release: v22.23.4+ on v22, v24.22.1+ on v24, or v26.12.1+ on v26. The binary installer and JavaScript fetch paths use Node's TLS stack independently of the Rust SDK; see [TLS trust stores](../../README.md#tls-trust-stores). If you need to manage multiple versions of Node on your machine, use a tool such as [nvm](https://github.com/nvm-sh/nvm). Rust is not required when installing the package normally: precompiled binaries are downloaded automatically. For source builds, see [Contributing to c2pa-node](https://github.com/contentauth/c2pa-js/blob/main/docs/project-contributions.md#contributing-to-c2pa-node). ## Installation ### Installing for use in an app Using npm: ```sh npm install @contentauth/c2pa-node ``` Using Yarn: ```sh yarn add @contentauth/c2pa-node ``` Using pnpm: ```sh pnpm add @contentauth/c2pa-node ``` This command will download precompiled binaries for the following systems: - Linux x86_64 - Linux aarch64 (ARM) - macOS aarch64 (Apple Silicon) - macOS x86_64 (Intel Mac) - Windows x86 - Windows ARM ## Documentation The [Node.js API documentation](https://contentauth.github.io/c2pa-js/node/) is generated with [TypeDoc](https://typedoc.org/) from the declarations in published versions of `@contentauth/c2pa-node`. Use the version selector to switch releases. The [multi-package documentation](https://contentauth.github.io/c2pa-js/) remains available at the existing root URL. For documentation builds and version-list maintenance, see [Building API documentation](https://github.com/contentauth/c2pa-js/blob/main/docs/project-contributions.md#building-api-documentation). ## Components ### Trustmark `Trustmark` uses TrustMark 0.5 to encode and decode watermarks. Watermark removal is opt-in and supported for variants **P** and **Q** only. Select the variant used to embed the watermark: ```javascript import { Trustmark } from '@contentauth/c2pa-node'; const trustmark = await Trustmark.newTrustmark({ variant: 'P', version: 'BCH_5', modelPath: './models', loadRemover: true }); const recoveredPng = await trustmark.remove(watermarkedImageBuffer); ``` `loadRemover` defaults to `false`. Enabling it downloads and loads the separate `remover_P.onnx` or `remover_Q.onnx` file in `modelPath` (default `./models`), in addition to the encoder and decoder. Cached files are reused. This adds startup time and memory usage; ordinary encode/decode callers do not load a remover. `remove()` accepts an 8-bit JPEG or PNG (RGB, RGBA, or grayscale) and returns an **encoded PNG**, preserving dimensions and alpha. This differs from `encode()`, which returns **raw RGB8 pixels**. Unsupported formats or bit depths, malformed images, missing removal support, and model/inference failures reject the promise; failures are never silently treated as successful removal. Removal rejects encoded inputs larger than **64 MiB**, dimensions larger than **16,384 pixels** on either axis, and images with more than **32 million pixels**. Dimensions and pixel count are checked before decoding pixels or running inference. Decoding also has a **best-effort 128 MiB allocation budget**. These are per-call limits, not a cap on total process memory: removal allocates additional full-resolution buffers, and concurrent calls require additional memory. The returned PNG is **pixel-only**. It does not copy image metadata, including EXIF, XMP, ICC color profiles, or embedded C2PA manifests. Preserving dimensions and alpha does not mean preserving metadata. Callers that need ordinary image metadata must carry it forward separately using an encoder that supports it. Existing C2PA credentials bind to the original asset and do not remain valid for the modified pixels. Use the original asset as an ingredient and sign a new manifest to attach valid Content Credentials to the output; do not simply copy the original manifest. Removal is lossy: it does not restore the original pixels or guarantee removal of arbitrary watermarks. It can also change an image without a detectable watermark. Remove before re-watermarking if replacing an existing identifier. Operations on a shared remover are serialized internally. ### Reader The `Reader` class is used to read and validate C2PA manifests from media files. It can parse embedded manifests or fetch remote manifests. Refer to the [Rust SDK](https://github.com/contentauth/c2pa-rs) for the list of settings and their effects. ```javascript import { Reader, Context } from '@contentauth/c2pa-node'; // Read from an asset file const reader = await Reader.fromAsset(inputAsset); // Read with a Context — the recommended way to configure settings // (see "Using a Context" under "Settings and configuration" below) const context = new Context({ verify: { verifyAfterReading: false, verifyTrust: true } }); const reader = await Reader.fromAsset(inputAsset, context); // Read from manifest data and asset const reader = await Reader.fromManifestDataAndAsset(manifestData, asset); // Get the manifest store as JSON const manifestStore = reader.json(); // Get the active manifest const activeManifest = reader.getActive(); // Check if manifest is embedded const isEmbedded = reader.isEmbedded(); // Get remote URL if applicable const remoteUrl = reader.remoteUrl(); ``` Node keeps the latest resolved settings JSON and native context handle for each JavaScript `Context` in a `WeakMap`. Repeated `Reader` and `Builder` construction with the same effective settings reuses that handle without retransferring or reparsing the JSON. Successful settings resolution stays memoized within the `Context`; create a new `Context` to resolve updated trust resources. Existing Readers and Builders retain their construction-time settings. The shared native context also owns cancellation/progress state, although Node does not expose those native APIs today. Future per-instance controls must revisit this ownership: cancellation would affect all users of that native context, and progress callbacks would receive events from multiple operations. `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. > [!WARNING] > `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. ### Builder 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. ```javascript import { Builder, Context } from '@contentauth/c2pa-node'; // Create a new builder const builder = await Builder.newAsync(); // Create with a Context — the recommended way to configure settings // (see "Using a Context" under "Settings and configuration" below) const context = new Context({ builder: { generateC2paArchive: true } }); const builder = await Builder.newAsync(context); // Or create from an existing manifest definition const builder = await Builder.withJsonAsync(manifestDefinition); // Or create with both a manifest definition and a Context const builder = await Builder.withJsonAsync(manifestDefinition, context); // Add assertions to the manifest builder.addAssertion('c2pa.actions', actionsAssertion); // Add resources await builder.addResource('resource://example', resourceAsset); // Sign the manifest const manifest = builder.sign(signer, inputAsset, outputAsset); ``` #### Setting builder intent The builder intent describes the type of operation being performed on the asset. This influences how the manifest is structured and what assertions are automatically added. Use one of these intents: - `create`: Indicates the asset is a new digital creation, a `DigitalSourceType` is required. The manifest must not have a parent ingredient. A `c2pa.created` action will be added if not provided. - `edit`: Indicates the asset is an edit of a pre-existing parent asset. The manifest must have a parent ingredient. A parent ingredient will be generated from the source stream if not otherwise provided. A `c2pa.opened` action will be tied to the parent ingredient. - `update`: A restricted version of `edit` for non-editorial changes. There must be only one ingredient, as a parent. No changes can be made to the hashed content of the parent. There are additional restrictions on the types of changes that can be made. ```javascript const builder = await Builder.newAsync(); builder.setIntent({ create: 'http://cv.iptc.org/newscodes/digitalsourcetype/trainedAlgorithmicMedia', }); builder.setIntent('edit'); builder.setIntent('update'); ``` The `create` intent accepts a `DigitalSourceType` that describes the origin of the asset. Common values include: - `'http://cv.iptc.org/newscodes/digitalsourcetype/trainedAlgorithmicMedia'` - AI-generated content - `'http://cv.iptc.org/newscodes/digitalsourcetype/digitalCapture'` - Digital camera capture - `'http://cv.iptc.org/newscodes/digitalsourcetype/composite'` - Composite of multiple sources For a complete list of digital source types, see the [C2PA specification](https://c2pa.org/specifications/specifications/2.4/specs/C2PA_Specification.html#_digital_source_type) and [IPTC digital source type vocabulary](https://cv.iptc.org/newscodes/digitalsourcetype). For more details on builder intents, see the [c2pa-rs Builder documentation](https://docs.rs/c2pa/latest/c2pa/struct.Builder.html). #### Adding ingredients from assets When you have access to the ingredient asset, use `addIngredient` with an asset to include both the metadata and the asset data: ```javascript import * as fs from "node:fs/promises"; // Load the ingredient asset const ingredientBuffer = await fs.readFile('path/to/source-image.jpg'); // Create a builder const builder = await Builder.newAsync(); // Add the ingredient with its asset await builder.addIngredient( JSON.stringify({ title: 'source-image.jpg', format: 'image/jpeg', instance_id: 'ingredient-123', relationship: 'parentOf', }), { buffer: ingredientBuffer, mimeType: 'image/jpeg', } ); const definition = builder.getManifestDefinition(); console.log(definition.ingredients); // Contains the ingredient with embedded data ``` #### Adding multiple ingredients You can add multiple ingredients to document complex provenance chains: ```javascript const builder = await Builder.newAsync(); // Load ingredient assets const background = await fs.promises.readFile('background.jpg'); const overlay = await fs.promises.readFile('overlay.png'); // Add first ingredient await builder.addIngredient( JSON.stringify({ title: 'background.jpg', format: 'image/jpeg', instance_id: 'background-001', relationship: 'componentOf', }), { buffer: background, mimeType: 'image/jpeg', } ); // Add second ingredient await builder.addIngredient( JSON.stringify({ title: 'overlay.png', format: 'image/png', instance_id: 'overlay-002', relationship: 'componentOf', }), { buffer: overlay, mimeType: 'image/png', } ); const definition = builder.getManifestDefinition(); console.log(definition.ingredients.length); // 2 ``` #### Adding ingredients from readers You can also add ingredients directly from a `Reader` object, which automatically includes the C2PA data: ```javascript // Read an existing C2PA asset const sourceReader = await Reader.fromAsset({ path: 'source-image.jpg', }); // Create a builder const builder = await Builder.newAsync(); // Add ingredient from reader const ingredient = builder.addIngredientFromReader(sourceReader); console.log(ingredient.title); // Contains ingredient metadata ``` #### Adding ingredients from archive files You can add ingredients from `.c2pa` archive files. Archives are binary files that contain a manifest store with ingredients and their associated resources (thumbnails, manifest data, etc.). To work with them, read the archive with `Reader` using the `application/c2pa` MIME type, then extract the ingredients and transfer their binary resources to a new `Builder`. There are two types of archives sharing the same binary format: - **Builder archives** (working store archives): Serialized snapshots of a `Builder`, created by `builder.toArchive()`. They can contain multiple ingredients. - **Ingredient archives**: Contain exactly one ingredient from a source asset. They carry the provenance history for reuse in other manifests. ##### Reading an archive and adding its ingredients ```javascript import { Reader, Builder, Context } from '@contentauth/c2pa-node'; import * as fs from 'node:fs/promises'; // Read the archive using the application/c2pa MIME type const archiveBuffer = await fs.readFile('ingredients.c2pa'); const reader = await Reader.fromAsset( { buffer: archiveBuffer, mimeType: 'application/c2pa' }, new Context({ verify: { verifyAfterReading: false } }) ); // Get the ingredients from the active manifest const activeManifest = reader.getActive(); const ingredients = activeManifest.ingredients; // Create a new builder with the ingredients from the archive const builder = await Builder.withJsonAsync({ claim_generator_info: [{ name: 'my-app', version: '1.0.0' }], ingredients: ingredients, }); // Transfer binary resources (thumbnails, manifest_data) for each ingredient for (const ingredient of ingredients) { if (ingredient.thumbnail) { const resource = await reader.resourceToAsset(ingredient.thumbnail.identifier, { buffer: null }); await builder.addResource(ingredient.thumbnail.identifier, { buffer: resource.buffer, mimeType: ingredient.thumbnail.format, }); } if (ingredient.manifest_data) { const resource = await reader.resourceToAsset(ingredient.manifest_data.identifier, { buffer: null }); await builder.addResource(ingredient.manifest_data.identifier, { buffer: resource.buffer, mimeType: 'application/c2pa', }); } } // Sign the manifest const signer = LocalSigner.newSigner(cert, key, 'es256'); builder.sign(signer, inputAsset, outputAsset); ``` ##### Selecting specific ingredients from an archive When an archive contains multiple ingredients, you can filter to include only the ones you need: ```javascript const reader = await Reader.fromAsset( { buffer: archiveBuffer, mimeType: 'application/c2pa' }, new Context({ verify: { verifyAfterReading: false } }) ); const activeManifest = reader.getActive(); const allIngredients = activeManifest.ingredients; // Select only the ingredients you want (e.g., by title or instance_id) const selected = allIngredients.filter( (ing) => ing.title === 'photo_1.jpg' || ing.instance_id === 'catalog:logo' ); // Build with only the selected ingredients const builder = await Builder.withJsonAsync({ claim_generator_info: [{ name: 'my-app', version: '1.0.0' }], ingredients: selected, }); // Transfer resources only for selected ingredients for (const ingredient of selected) { if (ingredient.thumbnail) { const resource = await reader.resourceToAsset(ingredient.thumbnail.identifier, { buffer: null }); await builder.addResource(ingredient.thumbnail.identifier, { buffer: resource.buffer, mimeType: ingredient.thumbnail.format, }); } if (ingredient.manifest_data) { const resource = await reader.resourceToAsset(ingredient.manifest_data.identifier, { buffer: null }); await builder.addResource(ingredient.manifest_data.identifier, { buffer: resource.buffer, mimeType: 'application/c2pa', }); } } ``` ##### Building an ingredient archive To create an ingredient archive, add ingredients to a `Builder` and save it as an archive: ```javascript const builder = await Builder.newAsync(); // Add ingredients with stable instance_id for later catalog lookups await builder.addIngredient( JSON.stringify({ title: 'photo-A.jpg', relationship: 'componentOf', instance_id: 'catalog:photo-A', }), { path: 'photo-A.jpg' } ); // Save as a .c2pa archive await builder.toArchive({ path: 'ingredient-catalog.c2pa' }); ``` #### Creating and reusing builder archives Builder archives allow you to save a builder's state (including ingredients) and reuse it later: ```javascript // Create a builder with ingredients const builder = await Builder.newAsync(); const ingredientBuffer = await fs.promises.readFile('source.jpg'); await builder.addIngredient( JSON.stringify({ title: 'source.jpg', format: 'image/jpeg', instance_id: 'source-123', }), { buffer: ingredientBuffer, mimeType: 'image/jpeg', } ); // Save as an archive await builder.toArchive({ path: 'builder-archive.zip' }); // Later, recreate the builder from the archive const restoredBuilder = await Builder.fromArchive({ path: 'builder-archive.zip' }); // The ingredients are preserved const definition = restoredBuilder.getManifestDefinition(); console.log(definition.ingredients); // Contains the ingredient ``` For complete type definitions, see the [@contentauth/c2pa-types](https://www.npmjs.com/package/@contentauth/c2pa-types) package. ### Signers The library provides several types of signers for different use cases: #### LocalSigner For local signing with certificates and private keys: ```javascript import { LocalSigner } from '@contentauth/c2pa-node'; // Create a local signer with certificate and private key const signer = LocalSigner.newSigner( certificateBuffer, privateKeyBuffer, 'es256', // signing algorithm 'https://timestamp.example.com' // optional TSA URL ); // Sign data const signature = signer.sign(dataBuffer); ``` #### CallbackSigner For custom signing implementations using callbacks: ```javascript import { CallbackSigner } from '@contentauth/c2pa-node'; // Create a callback signer const signer = CallbackSigner.newSigner( { alg: 'es256', certs: [certificateBuffer], reserveSize: 1024, // Reserved size in bytes for the C2PA Claim Signature box. tsaUrl: 'https://timestamp.example.com' }, async (data) => { // Custom signing logic return await customSigningFunction(data); } ); ``` ### Identity assertion components For working with identity assertions and CAWG (Content Authenticity Working Group) identities: #### IdentityAssertionBuilder Builds identity assertions with roles and referenced assertions: ```javascript import { IdentityAssertionBuilder, CallbackCredentialHolder } from '@contentauth/c2pa-node'; // Create a credential holder const credentialHolder = CallbackCredentialHolder.newCallbackCredentialHolder( 1024, // reserveSize 'es256', // sigType async (payload) => { // Custom signing logic for identity assertions return await signIdentityPayload(payload); } ); // Create an identity assertion builder const identityBuilder = await IdentityAssertionBuilder.identityBuilderForCredentialHolder( credentialHolder ); // Add roles and referenced assertions identityBuilder.addRoles(['photographer', 'editor']); identityBuilder.addReferencedAssertions(['c2pa.actions']); ``` #### IdentityAssertionSigner Signs manifests with identity assertions: ```javascript import { IdentityAssertionSigner } from '@contentauth/c2pa-node'; // Create an identity assertion signer const identitySigner = IdentityAssertionSigner.new(callbackSigner); // Add identity assertion identitySigner.addIdentityAssertion(identityBuilder); // Use with Builder for signing const manifest = await builder.signAsync(identitySigner, inputAsset, outputAsset); ``` ### Trustmark The `Trustmark` class provides functionality for encoding and decoding trustmarks in images: ```javascript import { Trustmark } from '@contentauth/c2pa-node'; // Create a trustmark instance const trustmark = await Trustmark.newTrustmark({ // trustmark configuration }); // Encode a trustmark into an image const encodedImage = await trustmark.encode( imageBuffer, 0.5, // strength 'watermark-text' // optional watermark ); // Decode a trustmark from an image const decodedData = await trustmark.decode(imageBuffer); ``` ### Settings and configuration Configure each Reader/Builder instance with a `Context`. Settings helper functions remain available to prepare the settings object passed to its constructor. Refer to the [Rust SDK](https://github.com/contentauth/c2pa-rs) for the list of settings and their effects. #### Using a Context A `Context` (from [`c2pa-utilities`](../c2pa-utilities/README.md#context-and-settings), re-exported directly from `@contentauth/c2pa-node` so you don't need to add that package yourself) wraps `Settings` and is the only supported way to configure a `Reader` or `Builder`. Node, web and web's `/inline` entry point re-export the same class, so contexts and subclasses can be shared across packages: ```javascript import { Reader, Builder, Context } from '@contentauth/c2pa-node'; const context = new Context({ verify: { verifyAfterReading: false, verifyAfterSign: false, verifyTrust: true, ocspFetch: true }, trust: { verifyTrustList: true, trustAnchors: "path/to/anchors.pem" } }); // Pass a Context to Reader const reader = await Reader.fromAsset(inputAsset, context); // Builder creation resolves the Context asynchronously const builder = await Builder.newAsync(context); const builder2 = await Builder.withJsonAsync(manifestDefinition, context); const builder3 = await Builder.fromArchive(archiveAsset, context); ``` > [!NOTE] > As in `c2pa-web`, URLs in a `Context`'s trust-anchor settings are fetched and resolved before the Reader or Builder is created. Successful resolution is memoized when a Context is reused. #### Migrating from deprecated settings APIs Raw settings objects, JSON/TOML strings and `null` are no longer accepted by Reader/Builder factories. Convert configuration to the camelCase `Settings` shape and wrap it in `new Context(settings)`. Omit the context argument, or pass `new Context()`, to use defaults. | Removed API | Replacement | | --- | --- | | `Builder.new(settings)` | `await Builder.newAsync(context)` | | `Builder.withJson(definition, settings)` | `await Builder.withJsonAsync(definition, context)` | | `Reader.fromAsset(asset, settings)` | `await Reader.fromAsset(asset, context)` | | `Reader.fromManifestDataAndAsset(data, asset, settings)` | `await Reader.fromManifestDataAndAsset(data, asset, context)` | | `Builder.fromArchive(asset, settings)` | `await Builder.fromArchive(asset, context)` | | `C2paSettings`, `SettingsContext` | `Settings` for configuration objects; `Context` for factory arguments | | `TrustConfig`, `VerifyConfig` | `TrustSettings`, `VerifySettings` | `Context` applies SDK defaults and resolves trust-anchor URLs; unlike the removed raw settings path, it does not pass native settings through unchanged. #### Settings helper functions The library provides helper functions to create and manage settings objects: ```javascript import { Context, createTrustSettings, createTsaTrustSettings, createCawgTrustSettings, createVerifySettings, mergeSettings } from '@contentauth/c2pa-node'; // Create trust settings const trustSettings = createTrustSettings({ verifyTrustList: true, userAnchors: "path/to/user-anchors.pem", trustAnchors: "path/to/trust-anchors.pem", allowedList: "path/to/allowed-list.pem" }); // Create timestamp trust settings. const tsaTrustSettings = createTsaTrustSettings({ trustAnchors: "path/to/tsa-anchors.pem" }); // Create CAWG trust settings const cawgTrustSettings = createCawgTrustSettings({ verifyTrustList: true, trustAnchors: "path/to/cawg-anchors.pem", trustedIcaIssuers: ["did:web:example.com"] }); // Create verify settings const verifySettings = createVerifySettings({ verifyAfterReading: false, verifyAfterSign: false, verifyTrust: true, verifyTimestampTrust: true, ocspFetch: true, remoteManifestFetch: true, skipIngredientConflictResolution: false, strictV1Validation: false }); // Merge multiple settings const combinedSettings = mergeSettings(trustSettings, verifySettings); // combinedSettings is a plain Settings object — wrap it in a Context const readerWithContext = await Reader.fromAsset(inputAsset, new Context(combinedSettings)); ``` Low-level serialization and loading helpers remain available, but their raw JSON/TOML strings are not valid Reader/Builder factory arguments. #### Available settings **Trust settings:** - `verifyTrustList` - Whether to verify against the trust list - `userAnchors` - User-provided trust anchors (PEM format or path) - `trustAnchors` - Trust anchors for validation (PEM format or path) - `trustConfig` - Path to trust configuration file. Not available in `tsaTrust`. - `allowedList` - Allowed list of certificates (PEM format or path). Not available in `tsaTrust`. - `trustedIcaIssuers` - DIDs of identity claims aggregation issuers to trust. Available only in `cawgTrust`. The same fields configure three sections: `trust` for claim signers, `tsaTrust` for timestamps and `cawgTrust` for CAWG identities. **Verify settings:** - `verifyAfterReading` - Whether to verify after reading a manifest - `verifyAfterSign` - Whether to verify after signing a manifest - `verifyTrust` - Whether to verify trust during validation - `verifyTimestampTrust` - Whether to verify timestamp trust - `ocspFetch` - Whether to fetch OCSP responses - `remoteManifestFetch` - Whether to fetch remote manifests - `skipIngredientConflictResolution` - Whether to skip ingredient conflict resolution - `strictV1Validation` - Whether to use strict v1 validation **Builder settings:** - `generate_c2pa_archive` - Whether to generate C2PA archive format > [!NOTE] > Settings are passed as per-instance configuration. There are no global settings that affect all Readers and Builders. ### Build and use custom binary For instructions on building a Rust binary, see [Contributing to c2pa-node](https://github.com/contentauth/c2pa-js/blob/main/docs/project-contributions.md#contributing-to-c2pa-node). To use a custom binary: ```bash export C2PA_LIBRARY_PATH=/index.node ```