@contentauth/c2pa-node

中文文档
0.10.0发布于 2026/11/05MITTypeScriptES Module构建来源已验证近 30 天下载 48.6万

Node.js bindings for C2PA

原始使用文档
文档目录12 节
  1. Prerequisites
  2. Installation
  3. Installing for use in an app
  4. Documentation
  5. Components
  6. Reader
  7. Builder
  8. Signers
  9. Identity assertion components
  10. Trustmark
  11. Settings and configuration
  12. Build and use custom binary

CAI Node.js library

@contentauth/c2pa-node is a Node.js library in the 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. If you need to manage multiple versions of Node on your machine, use a tool such as nvm.

Rust is not required when installing the package normally: precompiled binaries are downloaded automatically. For source builds, see Contributing to c2pa-node.

Installation

Installing for use in an app

Using npm:

npm install @contentauth/c2pa-node

Using Yarn:

yarn add @contentauth/c2pa-node

Using pnpm:

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 is generated with TypeDoc from the declarations in published versions of @contentauth/c2pa-node. Use the version selector to switch releases. The multi-package documentation remains available at the existing root URL.

For documentation builds and version-list maintenance, see Building API documentation.

Components

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 for the list of settings and their effects.

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();

[!NOTE] Reader.fromAsset/Reader.fromManifestDataAndAsset also accept a raw settings object in place of a Context (e.g. Reader.fromAsset(inputAsset, { verify: { verify_trust: true } })), but this is deprecated — see Per-instance settings (deprecated).

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 for the list of settings and their effects.

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);

[!NOTE] Builder.new/Builder.withJson (synchronous, taking a raw settings object in place of a Context) still work but are deprecated — see Per-instance settings (deprecated).

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.
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 and IPTC digital source type vocabulary.

For more details on builder intents, see the c2pa-rs Builder documentation.

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:

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:

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:

// 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
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:

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:

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:

// 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 package.

Signers

The library provides several types of signers for different use cases:

LocalSigner

For local signing with certificates and private keys:

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:

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:

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:

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:

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

The library provides comprehensive settings management that can be configured per Reader/Builder instance, via a Context, or using helper functions. Refer to the Rust SDK for the list of settings and their effects.

Using a Context

A Context (from c2pa-utilities, re-exported directly from @contentauth/c2pa-node so you don't need to add that package yourself) wraps Settings and is the recommended way to configure a Reader or Builder:

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 has async, Context-aware counterparts to its synchronous factories below
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. The deprecated raw-settings API does not resolve URLs; use a Context for URL-based trust anchors.

Per-instance settings (deprecated)

Passing settings directly as a JSON string, or as a raw object matching the native settings shape (snake_case keys, no defaults applied), is deprecated and will be removed in a future major version — use a Context instead (above). Builder.new/Builder.withJson stay synchronous for this deprecated path; prefer their newAsync/withJsonAsync counterparts with a Context instead.

import { Reader, Builder } from '@contentauth/c2pa-node';

// Create settings object
const settings = {
  verify: {
    verify_after_reading: false,
    verify_after_sign: false,
    verify_trust: true,
    ocsp_fetch: true
  },
  trust: {
    verify_trust_list: true,
    trust_anchors: "path/to/anchors.pem"
  }
};

// Pass settings to Reader
const reader = await Reader.fromAsset(inputAsset, settings);

// Pass settings to Builder
const builder = Builder.new(settings);

// Settings can also be JSON strings
const settingsJson = JSON.stringify(settings);
const builder2 = Builder.new(settingsJson);

Settings helper functions

The library provides helper functions to create and manage settings objects:

import {
  createTrustSettings,
  createCawgTrustSettings,
  createVerifySettings,
  mergeSettings,
  settingsToJson,
  loadSettingsFromFile,
  loadSettingsFromUrl
} 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 CAWG trust settings
const cawgTrustSettings = createCawgTrustSettings({
  verifyTrustList: true,
  trustAnchors: "path/to/cawg-anchors.pem"
});

// 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 — use it with a Context (recommended)...
const readerWithContext = await Reader.fromAsset(inputAsset, new Context(combinedSettings));

// ...or convert it to a JSON string for the deprecated per-instance settings path
const jsonString = settingsToJson(combinedSettings);
const readerWithJson = await Reader.fromAsset(inputAsset, jsonString);

// loadSettingsFromFile/loadSettingsFromUrl return a raw JSON string, not a Settings
// object, so they pair with the deprecated per-instance settings path, not Context, for now.
const fileSettings = await loadSettingsFromFile('./c2pa-settings.json');
const reader2 = await Reader.fromAsset(inputAsset, fileSettings);

const urlSettings = await loadSettingsFromUrl('https://example.com/c2pa-settings.json');
const builder = Builder.new(urlSettings);

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
  • allowedList - Allowed list of certificates (PEM format or path)

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. To use a custom binary:

export C2PA_LIBRARY_PATH=<path-to-binary-folder>/index.node

版本与发布记录

@contentauth/c2pa-node 共发布 42 个版本,首次发布于 2025/08/12;过去 12 个月发布了 33 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.10.0latest2026/11/055 天前
0.9.122026/11/046 天前
0.9.112026/10/2714 天前
0.9.102026/10/1724 天前
0.9.92026/09/301 个月前
0.9.82026/09/241 个月前

关于 @contentauth/c2pa-node 的常见问题

@contentauth/c2pa-node 是什么?

Node.js bindings for C2PA

如何安装 @contentauth/c2pa-node?

在项目目录运行 npm install @contentauth/c2pa-node,或使用 pnpm add / yarn add / bun add。

@contentauth/c2pa-node 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@contentauth/c2pa-node 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@contentauth/c2pa-node 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@contentauth/c2pa-node 可以商用吗?

@contentauth/c2pa-node 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@contentauth/c2pa-node 的下载量有多少?

根据 npm 官方下载统计,@contentauth/c2pa-node 在 2026/10/11 – 2026/11/09 这 30 天内被下载 485,807 次,日均约 16,194 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@contentauth/c2pa-node 还在维护吗?

最新版本 0.10.0 发布于 2026/11/05(5 天前);至今共发布 42 个版本,其中过去 12 个月发布了 33 个;首次发布于 2025/08/12。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。