@contentauth/c2pa-utilities

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

c2pa-utilities is a home for shared utilities and libraries used by both c2pa-web and c2pa-node. Most clients will get these transitively as a dependency of one of those two packages, but @contentauth/c2pa-utilities is also published standalone fo

原始使用文档
文档目录11 节
  1. Installation
  2. API reference documentation
  3. Utilities
  4. Context and Settings
  5. Fetch with retry
  6. Asset size validation
  7. Signing algorithm
  8. Library development
  9. Prerequisites
  10. Building
  11. Testing

c2pa-utilities

c2pa-utilities is a home for shared utilities and libraries used by both c2pa-web and c2pa-node. Most clients will get these transitively as a dependency of one of those two packages, but @contentauth/c2pa-utilities is also published standalone for cases where you want to reuse a piece of it directly.

Installation

npm install @contentauth/c2pa-utilities

API reference documentation

Complete API documentation is generated from TypeScript source using TypeDoc and published to GitHub Pages.

Utilities

Context and Settings

Settings is a plain, JSON-serializable object configuring SDK behavior around trust anchors, verification options, and Reader/Builder options.

Context is a small, immutable wrapper around Settings, and is the recommended way to configure a Reader/Builder. Context objects are passed directly to the call that creates a Reader/Builder instance, so one running SDK instance can freely create many different Reader/Builders, each with its own Context. Context changes do not propagate, since the Context is snapshotted when used to construct a Reader/Builder. Therefore, it can be safely used to construct multiple instances.

See c2pa-web's README for an example.

Creating a Context

import { Context } from '@contentauth/c2pa-utilities';

const context = new Context({
  verify: {
    verifyTrust: true
  },
  trust: {
    trustAnchors: 'https://example.com/trust-anchors.pem'
  }
});

Combining Settings

Each Context holds whatever single Settings object was passed to its constructor and does not handle any merging of settings. To combine more than one Settings source, merge them first with mergeSettings(), then construct a Context from the single, merged result:

import { Context, mergeSettings } from '@contentauth/c2pa-utilities';

const base = { verify: { verifyTrust: true } };
const override = { verify: { verifyAfterSign: true } };

const context = new Context(mergeSettings(base, override));
// context.settings is { verify: { verifyTrust: true, verifyAfterSign: true } }

Resolving a Context to JSON

Settings are passed across the WASM (c2pa-web)/native(c2pa-node) boundary as a JSON string. toJson() resolves any trust-anchor URLs embedded in the settings (fetching and validating them) and serializes the result:

const contextJson = await context.toJson();
// '{"verify":{"verify_trust":true},"trust":{"trust_anchors":"-----BEGIN CERTIFICATE-----..."}}'

This step is asynchronous, and can throw if a trust-anchor URL fails to resolve. Bindings call it once, right after building the base Context, rather than on every Reader/Builder call. Internally, toJson() is a thin wrapper over resolveSettings, below.

Building Settings directly

Context is built on a handful of lower-level Settings helpers, which remain available directly for cases that don't need a Context at all:

import {
  createTrustSettings,
  createVerifySettings,
  mergeSettings,
  resolveSettings
} from '@contentauth/c2pa-utilities';

const trustSettings = createTrustSettings({
  trustAnchors: 'https://example.com/anchors.pem'
});

const verifySettings = createVerifySettings({
  verifyTrust: true,
  verifyAfterReading: true
});

const settings = mergeSettings(trustSettings, verifySettings);

// Resolves trust-anchor URLs and serializes to the snake_case JSON string the native SDK expects.
const settingsJson = await resolveSettings(settings);

resolveSettings is the entry point most direct callers want. It resolves any trust/cawgTrust URL fields (fetching and inlining the PEM content, retrying transient failures), and returns the result as a snake_case JSON string. settings is merged on top of this package's defaults, so resolveSettings always returns a value, even when called with undefined. To combine more than one Settings object first, merge them with mergeSettings() before calling resolveSettings, as above.

Other exports:

  • createTrustSettings / createCawgTrustSettings / createVerifySettings — construct a Settings fragment for one section.
  • mergeSettings — deep-merge any number of Settings fragments, with later arguments overriding earlier ones. Nested fields are merged rather than overwritten.
  • settingsToJson — serialize a Settings object to its snake_case JSON form without resolving trust-anchor URLs.
  • snakeCaseify — the lower-level camelCase-to-snake_case object converter settingsToJson/resolveSettings use internally.
  • loadSettingsFromUrl — fetch a settings JSON document from a URL, with retry.
  • resolveTrustSettings — resolve just a TrustSettings object's URL fields in place; used internally by resolveSettings.

Fetch with retry

fetchWithRetry and fetchWithRetryRaw wrap fetch with exponential backoff, Retry-After handling, and (for fetchWithRetry) a response size cap. The retry mechanism is fixed; however, policy details such as retry count, backoff timing, which statuses/errors are retryable, and the maximum honored Retry-After delay are configurable per call via FetchWithRetryOptions.

import { fetchWithRetry, fetchWithRetryRaw } from '@contentauth/c2pa-utilities';

// GET as text, retrying on network errors, 429, and 5xx, capped at 1 MB by default.
const text = await fetchWithRetry('https://example.com/anchors.pem');

// For other methods, headers, or bodies, or to handle the response yourself, use fetchWithRetryRaw.
const response = await fetchWithRetryRaw('https://example.com/upload', {
  method: 'POST',
  body: payload
});

Both functions accept an FetchWithRetryOptions object to override the defaults:

await fetchWithRetry(url, {
  maxRetries: 5,
  initialRetryDelayMs: 500,
  maxRetryDelayMs: 5_000,
  maxRetryAfterMs: 60_000,
  maxResponseBytes: 5 * 1024 * 1024,
  isRetryableStatus: (status) => status === 429 || status >= 500,
  isRetryableError: (error) => true,
  fetch: myFetchImplementation
});

An AbortError is never retried, and a malformed URL throws immediately rather than being retried.

Asset size validation

validateAssetSize is the shared size check used by both Reader implementations before reading an asset.

import { validateAssetSize, AssetTooLargeError, DEFAULT_MAX_SIZE_IN_BYTES } from '@contentauth/c2pa-utilities';

try {
  validateAssetSize(sizeInBytes, maxSizeInBytes); // pass 0 to use DEFAULT_MAX_SIZE_IN_BYTES
} catch (e) {
  if (e instanceof AssetTooLargeError) {
    // asset exceeds the resolved limit
  }
}

Signing algorithm

SigningAlg is the lowercase signing algorithm type accepted/produced by the core native library at the signer construction boundary (e.g. Signer.newSigner(cert, key, alg)). It's derived from the PascalCase SigningAlg exported by @contentauth/c2pa-types, which describes the casing used when a manifest's SignatureInfo.alg is serialized.

Library development

Prerequisites

Ensure the repo-wide prerequisites are installed:

See the contributor prerequisites for details.

Building

To build:

nx build c2pa-utilities

Testing

This library uses Vitest, with msw to mock fetch in the settings and fetch-with-retry tests.

To run the tests:

nx test c2pa-utilities

版本与发布记录

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

版本发布日期距今
0.4.0latest2026/11/046 天前
0.3.32026/10/2714 天前
0.3.22026/10/1724 天前
0.3.12026/09/241 个月前
0.3.02026/09/161 个月前
0.2.22026/08/312 个月前

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

@contentauth/c2pa-utilities 是什么?

c2pa-utilities is a home for shared utilities and libraries used by both c2pa-web and c2pa-node. Most clients will get these transitively as a dependency of one of those two packages, but @contentauth/c2pa-utilities is also published standalone fo

如何安装 @contentauth/c2pa-utilities?

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

@contentauth/c2pa-utilities 支持 TypeScript 吗?

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

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

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

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

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

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

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

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

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