Skip to main content

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 the only supported 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 Reader/Builder instances.

This package owns the single Context class definition. The Node, web and web /inline packages re-export it without bundling another copy. Importing or extending Context from any of these entry points preserves constructor identity, instanceof behavior and TypeScript assignability when they resolve the same utilities version. Downstream SDKs should re-export or subclass this class, not copy it; keep it external when bundling libraries and ensure consumers resolve one compatible version.

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 resolve the settings before constructing the native/WASM Reader or Builder. Within a Context, concurrent calls share the same resolution promise and successful results are memoized; failed resolutions can be retried on a later call.

Trust-resource fetching​

Concurrent trust-resource fetches using the global fetch, the same URL, and the same effective fetch policy share one pending request across settings resolutions. Entries are removed after success or failure; completed responses are not cached. Reusing a successfully resolved Context still reuses its memoized settings.

Custom fetch implementations are not deduplicated because a wrapper can change its request context (such as authentication headers) without changing its function identity.

Each trust-resource fetch has a fixed 30-second deadline covering network requests, retry delays, and response-body consumption. A timeout rejects with a TimeoutError, aborts the request and any pending retry delay, and rejects all waiting resolutions without substituting trust data. A later resolution can attempt a new fetch even if a custom implementation ignores cancellation.

Set ContextOptions.trustFetch using the third Context constructor argument to configure trust fetching. context.toJson(options) overrides those defaults for that resolution; resolveSettings(settings, options) accepts the same options directly. In addition to the fetch policy options described below:

  • deduplicateInFlight defaults to true; set it to false to make independent global-fetch requests.
  • requireHttps defaults to false for compatibility; set it to true to reject non-HTTPS trust-resource URLs and all redirects. Fetch's redirect: 'error' mode prevents contacting an HTTP redirect target. HTTPS redirects are also rejected, since browser Fetch does not expose cross-origin manual redirect destinations for validation. Custom fetch implementations must honor this redirect mode.

In-flight request keys use the original URL, effective fetch policy (including HTTPS enforcement), and global fetch identity. Omitted numeric defaults and explicitly supplied default values produce the same policy key, so separate Contexts and newly created options objects can share a pending request. Custom retry predicates are keyed by function identity; creating a new predicate function produces a separate policy.

const context = new Context(settings, undefined, {
trustFetch: { requireHttps: true, maxRetries: 1 }
});
await context.toJson();

In per-call options, an explicit undefined resets that option to its SDK default, while an omitted property retains the Context's configured value. For example, context.toJson({ maxRetries: undefined }) restores the SDK's default retry count for the first resolution. This does not erase core settings or clear an already memoized successful resolution.

Custom fetch implementations still honor HTTPS enforcement, numeric option validation, and the deadline, but never participate in in-flight sharing. The trust-resource deadline applies only to trust fetching, not to direct calls to fetchWithRetry, fetchWithRetryRaw, or loadSettingsFromUrl.

Building Settings directly​

Context is built on a handful of lower-level Settings helpers, which remain available for preparing configuration or working directly with native/WASM serialization. Reader/Builder creation at the JavaScript SDK API layer still requires a Context, not a settings object or serialized string:

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

const controller = new AbortController();
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,
signal: controller.signal
});

Aborting signal cancels the active request and any pending retry delay; the signal's reason is propagated and no further retry is attempted. A malformed URL throws immediately rather than being retried.

Numeric fetch options must be finite and non-negative. NaN, Infinity, -Infinity, and negative values throw before fetching; infinity does not mean retry forever. maxRetries must also be a safe integer. Omitted options retain their defaults.

OptionMeaning of 0
maxRetriesOne initial attempt, no retries
maxResponseBytesOnly an empty text response is allowed; not enforced by fetchWithRetryRaw
initialRetryDelayMsNo exponential-delay component; jitter still applies
maxRetryDelayMsNo backoff delay, including jitter
maxRetryAfterMsReject positive Retry-After delays; allow zero or past dates

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