TypeScript SDK (v2)
Install
Section titled “Install”# Exact pin (recommended). The "next" dist-tag tracks the newest v2 prerelease;# "latest" stays on Protocol v1 until 2.0.0.Package: @identities-ai/ratify-protocol, imported from the /v2 subpath. API documentation: the type declarations shipped with the package.
- The package root keeps the v1 API; v2 lives under
/v2. - The npm
latesttag stays on Protocol v1 until 2.0.0. Pin the exact v2 version. - The released decision is a frozen class whose constructor throws outside the release function.
Part B stores
Section titled “Part B stores”Production verifiers implement the claim store, rate reservations, receipt publisher,
independent checkpoint, and journal store durably. The in-memory implementations in
the /v2/reference subpath (every type ends in TestOnly) are for tests only. See Deployment profiles.
Quickstart
Section titled “Quickstart”Delegate, present, verify, and release: TypeScript quickstart (development only).
Examples
Section titled “Examples”Signed status
Section titled “Signed status”An issuer’s status publisher signs revocation lists and pushes under a separate status key; the verifier applies them to its journal. See Status from signed evidence.
// Ratify Protocol v2 signed status: a status publisher under a separate// status key, journal ingestion, and a revocation that turns a later// verification into deny.//// DEVELOPMENT ONLY. This program uses the in-memory reference stores from// @identities-ai/ratify-protocol/v2/reference. A production verifier supplies// durable Part B stores, an anchored journal store and an independent// checkpoint (SPEC-v2 §7).//// Run from this directory: node signed_status.tsimport { generateHybridKeypair } from "@identities-ai/ratify-protocol";import { TZDB_VERSION_V2, applyRevocationListToJournalV2, applyRevocationPushToJournalV2, configureStatusKeyEpochV2, encodeProofBundleV2, encodeRevocationListV2, encodeRevocationPushV2, issueChallengeV2, keyIDV2, loadExpectedChallengeV2, newV2ContextPolicy, newV2StatusPublisherWithKey, recordSecurityKeyRoleV2, releaseV2Decision, revocationStatusFromJournalV2, signDelegationCertV2, signProofBundleV2, v2ErrorClassOf, verifyProofBundleV2, type HybridKeyPairV2, type RevocationStatusPolicyV2, type V2StatusEvidenceObject,} from "@identities-ai/ratify-protocol/v2";import { ChallengeIssuanceStoreTestOnly, JournalStoreTestOnly, StoreTestOnly } from "@identities-ai/ratify-protocol/v2/reference";
const start = 1800000000;const namespace = "signed-status";const epoch = 1;const logID = "00000000000000000000000000000002";const certID = "status-demo-cert-1";const unsigned = { ed25519: new Uint8Array(0), ml_dsa_65: new Uint8Array(0) }; // replaced when signed
console.log("Ratify Protocol v2 signed status");console.log("development only: in-memory reference stores");
const root: HybridKeyPairV2 = await generateHybridKeypair();const agent: HybridKeyPairV2 = await generateHybridKeypair();const status: HybridKeyPairV2 = await generateHybridKeypair();const verifier: HybridKeyPairV2 = await generateHybridKeypair();const rootID = keyIDV2(root.publicKey);const agentID = keyIDV2(agent.publicKey);const verifierID = keyIDV2(verifier.publicKey);
const cert = await signDelegationCertV2({ version: 2, cert_id: certID, issuer_id: rootID, issuer_pub_key: root.publicKey, subject_id: agentID, subject_pub_key: agent.publicKey, scope: ["data:read"], constraints: [], issued_at: start, expires_at: start + 86400, signature: unsigned,}, root);console.log(`delegation: ${certID} scope=data:read`);
// The journal is the verifier's anchored record of key roles, status-key// epochs and accepted status. Roles are recorded once, when the deployment// authenticates its trust configuration.const journal = new JournalStoreTestOnly();await recordSecurityKeyRoleV2(journal, "issuer", root.publicKey);await recordSecurityKeyRoleV2(journal, "delegation", agent.publicKey);await recordSecurityKeyRoleV2(journal, "verifier", verifier.publicKey);await configureStatusKeyEpochV2(journal, rootID, 1, status.publicKey);console.log("journal: key roles recorded; status key configured for the root at epoch 1");
// Role separation: the root key can never sign status for itself.const refused = await newV2StatusPublisherWithKey(journal, root.publicKey, root, 3600).then(() => null, (err: unknown) => err);console.log(`publisher with the root key as status key: refused (${v2ErrorClassOf(refused)})`);
const publisher = await newV2StatusPublisherWithKey(journal, root.publicKey, status, 3600);const policy: RevocationStatusPolicyV2 = { maxListLifetimeSeconds: 3600, maxStatusAgeSeconds: 3600, clockSkewSeconds: 5 };
// Genesis: sequence 1, nothing revoked. The caller persists the returned// state before publishing the signed list.const genesis = await publisher.genesis(start);const genesisWire = encodeRevocationListV2(genesis.list);console.log(`publisher: genesis list sequence ${genesis.list.sequence}`);await applyRevocationListToJournalV2(journal, genesis.list, rootID, 1, status.publicKey, policy, start);let certStatus = await revocationStatusFromJournalV2(journal, rootID, certID, 1, status.publicKey, policy, start);console.log(`journal: ingested list sequence ${genesis.list.sequence}; ${certID} is ${certStatus.status}`);
const store = new StoreTestOnly(start, 30, logID, verifier);const issuance = new ChallengeIssuanceStoreTestOnly();let evidence: V2StatusEvidenceObject[] = [{ objectType: 3, wire: genesisWire }];
// verifyAndRelease runs one complete live verification at the store's// current time and prints the released decision.async function verifyAndRelease(label: string): Promise<void> { const challenge = await issueChallengeV2({ clock: store, store: issuance }, { verifierNamespace: namespace, replayEpoch: epoch, verifierID, lifetimeSeconds: 120, expectedAgentID: agentID, expectedAgentPublicKey: agent.publicKey, }); const bundle = await signProofBundleV2({ version: 2, verifier_id: verifierID, agent_id: agentID, agent_pub_key: agent.publicKey, delegations: [cert], delegation_digest: new Uint8Array(0), challenge: challenge.value, challenge_at: challenge.issuedAt, challenge_sig: unsigned, session_context: null, stream_id: null, stream_seq: null, }, agent); const expected = await loadExpectedChallengeV2(issuance, namespace, epoch, bundle.challenge); const outcome = await verifyProofBundleV2({ bundle: encodeProofBundleV2(bundle), expected, contextPolicy: newV2ContextPolicy("example.signed-status/v1", false, null, null), requiredScope: "data:read", verifierNamespace: namespace, replayEpoch: epoch, verifierID, now: store.now(), maxChallengeAgeSeconds: 300, futureSkewSeconds: 5, tzdbVersion: TZDB_VERSION_V2, statusKeys: new Map([[rootID, { epoch: 1, key: status.publicKey }]]), statusPolicy: policy, }, { claimStore: store, trust: (chain) => chain[chain.length - 1]!.issuer_id === rootID ? { outcome: "trusted", rootKey: root.publicKey } : { outcome: "untrusted" }, // The provider returns signed objects only; the verifier checks each // signature against the configured status key and applies it to the // journal before it derives a status. statusEvidence: async () => ({ objects: evidence }), statusJournal: journal, }); if (outcome.stage !== "committed" || !outcome.committed) throw new Error(`verify stopped at ${outcome.stage}: ${outcome.error}`); const receiptWire = await store.publishV2Receipt(outcome.committed.claimID(), outcome.committed.receiptBody()); const result = await releaseV2Decision(outcome.committed, receiptWire, { verifierPublicKey: verifier.publicKey, logID, claimStore: store, checkpoint: store, }); if (result.status !== "released" || !result.decision) throw new Error(`release ${result.status}: ${result.reason}`); const receipt = result.decision.receipt(); console.log(`${label}: decision=${result.decision.decision()} reason=${result.decision.reason()} ` + `status_assessment=${receipt.status_assessment} allowed=${await result.decision.allowed(store)}`);}
store.setTime(start + 5);await verifyAndRelease("verify before revocation");
// Revoke: a push with the newly revoked ID and the cumulative list, both at// sequence 2.const revoked = await publisher.revoke(genesis.state, [certID], start + 10);const pushWire = encodeRevocationPushV2(revoked.push!);const listWire = encodeRevocationListV2(revoked.list);console.log(`publisher: revoked ${certID} (push sequence ${revoked.push!.sequence}, list sequence ${revoked.list.sequence})`);await applyRevocationPushToJournalV2(journal, revoked.push!, rootID, 1, status.publicKey, policy, start + 10);certStatus = await revocationStatusFromJournalV2(journal, rootID, certID, 1, status.publicKey, policy, start + 10);console.log(`journal: ingested push sequence ${revoked.push!.sequence}; ${certID} is ${certStatus.status}`);
evidence = [{ objectType: 5, wire: pushWire }, { objectType: 3, wire: listWire }];store.setTime(start + 15);await verifyAndRelease("verify after revocation");Source: examples/v2/typescript/signed_status at commit 5ca7585c2c1d, SHA-256 checked at build time.
Custom scope and evaluator profile
Section titled “Custom scope and evaluator profile”An exact custom: required scope and a registered evaluator profile.
See Delegation and constraints.
// Ratify Protocol v2 custom scope and the standard max_count evaluator// profile (com.ratifyprotocol.max_count/v1).//// DEVELOPMENT ONLY. This program uses the in-memory reference stores from// @identities-ai/ratify-protocol/v2/reference. A production verifier supplies// durable Part B stores and an independent checkpoint (SPEC-v2 §7).//// Run from this directory: node custom_scope.tsimport { generateHybridKeypair } from "@identities-ai/ratify-protocol";import { CONSTRAINT_MAX_COUNT_V2, PROFILE_MAX_COUNT_V2, TZDB_VERSION_V2, configureStatusKeyEpochV2, constraintProfileDigestV2, encodeProofBundleV2, encodeRevocationListV2, issueChallengeV2, keyIDV2, loadExpectedChallengeV2, newConstraintEvaluatorRegistryV2, newV2ContextPolicy, newV2StatusPublisherWithKey, recordSecurityKeyRoleV2, releaseV2Decision, signDelegationCertV2, signProofBundleV2, standardMaxCountEvaluatorV2, v2ErrorClassOf, verifyProofBundleV2, type ConstraintEvaluatorRegistryV2, type DelegationCertV2, type HybridKeyPairV2,} from "@identities-ai/ratify-protocol/v2";import { ChallengeIssuanceStoreTestOnly, JournalStoreTestOnly, StoreTestOnly } from "@identities-ai/ratify-protocol/v2/reference";
const start = 1800000000;const namespace = "custom-scope";const epoch = 1;const logID = "00000000000000000000000000000003";const customScope = "custom:acme:deploy";const unsigned = { ed25519: new Uint8Array(0), ml_dsa_65: new Uint8Array(0) }; // replaced when signed
console.log("Ratify Protocol v2 custom scope and max_count profile");console.log("development only: in-memory reference stores");
const root: HybridKeyPairV2 = await generateHybridKeypair();const agent: HybridKeyPairV2 = await generateHybridKeypair();const status: HybridKeyPairV2 = await generateHybridKeypair();const verifier: HybridKeyPairV2 = await generateHybridKeypair();const rootID = keyIDV2(root.publicKey);const agentID = keyIDV2(agent.publicKey);const verifierID = keyIDV2(verifier.publicKey);
const template: DelegationCertV2 = { version: 2, cert_id: "custom-scope-cert-1", issuer_id: rootID, issuer_pub_key: root.publicKey, subject_id: agentID, subject_pub_key: agent.publicKey, scope: [], constraints: [], issued_at: start, expires_at: start + 86400, signature: unsigned,};
// A custom scope is one exact name. Wildcards are invalid.const refused = await signDelegationCertV2({ ...template, scope: ["custom:*"] }, root).then(() => null, (err: unknown) => err);console.log(`issue scope custom:*: refused (${v2ErrorClassOf(refused)})`);
// The certificate carries an extension constraint. Only a verifier that// registered the max_count/v1 profile for this type can evaluate it.const cert = await signDelegationCertV2({ ...template, scope: [customScope], constraints: [{ type: CONSTRAINT_MAX_COUNT_V2, params: { counter: "nodes", max: 5 } }],}, root);console.log(`delegation: scope=${customScope} constraint=${CONSTRAINT_MAX_COUNT_V2}(counter=nodes, max=5)`);
const maxCount = standardMaxCountEvaluatorV2();console.log(`profile: ${PROFILE_MAX_COUNT_V2} digest=${constraintProfileDigestV2(maxCount.descriptor)}`);const registry = newConstraintEvaluatorRegistryV2(1000, maxCount);
const journal = new JournalStoreTestOnly();await recordSecurityKeyRoleV2(journal, "issuer", root.publicKey);await configureStatusKeyEpochV2(journal, rootID, 1, status.publicKey);const publisher = await newV2StatusPublisherWithKey(journal, root.publicKey, status, 3600);const genesis = await publisher.genesis(start);const statusWire = encodeRevocationListV2(genesis.list);
const store = new StoreTestOnly(start, 30, logID, verifier);const issuance = new ChallengeIssuanceStoreTestOnly();
// attempt verifies one request for `nodes` nodes and releases the result.async function attempt(label: string, nodes: number, evaluators: ConstraintEvaluatorRegistryV2 | null): Promise<void> { store.setTime(store.now() + 1); const challenge = await issueChallengeV2({ clock: store, store: issuance }, { verifierNamespace: namespace, replayEpoch: epoch, verifierID, lifetimeSeconds: 120, expectedAgentID: agentID, expectedAgentPublicKey: agent.publicKey, }); const bundle = await signProofBundleV2({ version: 2, verifier_id: verifierID, agent_id: agentID, agent_pub_key: agent.publicKey, delegations: [cert], delegation_digest: new Uint8Array(0), challenge: challenge.value, challenge_at: challenge.issuedAt, challenge_sig: unsigned, session_context: null, stream_id: null, stream_seq: null, }, agent); const expected = await loadExpectedChallengeV2(issuance, namespace, epoch, bundle.challenge); const outcome = await verifyProofBundleV2({ bundle: encodeProofBundleV2(bundle), expected, contextPolicy: newV2ContextPolicy("example.custom-scope/v1", false, null, null), requiredScope: customScope, verifierNamespace: namespace, replayEpoch: epoch, verifierID, now: store.now(), maxChallengeAgeSeconds: 300, futureSkewSeconds: 5, tzdbVersion: TZDB_VERSION_V2, // The requested quantity comes from the authenticated request, never // from the proof. context: { extensionCounts: new Map([["nodes", nodes]]) }, constraintEvaluators: evaluators, statusKeys: new Map([[rootID, { epoch: 1, key: status.publicKey }]]), statusPolicy: { maxListLifetimeSeconds: 3600, maxStatusAgeSeconds: 3600, clockSkewSeconds: 5 }, }, { claimStore: store, trust: (chain) => chain[chain.length - 1]!.issuer_id === rootID ? { outcome: "trusted", rootKey: root.publicKey } : { outcome: "untrusted" }, statusEvidence: async () => ({ objects: [{ objectType: 3, wire: statusWire }] }), statusJournal: journal, }); if (outcome.stage !== "committed" || !outcome.committed) throw new Error(`verify stopped at ${outcome.stage}: ${outcome.error}`); const receiptWire = await store.publishV2Receipt(outcome.committed.claimID(), outcome.committed.receiptBody()); const result = await releaseV2Decision(outcome.committed, receiptWire, { verifierPublicKey: verifier.publicKey, logID, claimStore: store, checkpoint: store, }); if (result.status !== "released" || !result.decision) throw new Error(`release ${result.status}: ${result.reason}`); const receipt = result.decision.receipt(); console.log(`${label}: decision=${result.decision.decision()} reason=${result.decision.reason()} allowed=${await result.decision.allowed(store)}`); for (const ref of receipt.constraint_evaluators ?? []) { console.log(` receipt constraint_evaluators: ${ref.type} ${ref.profile_digest}`); }}
await attempt("request nodes=3", 3, registry);await attempt("request nodes=8", 8, registry);await attempt("request nodes=3 without the profile registered", 3, null);Source: examples/v2/typescript/custom_scope at commit 5ca7585c2c1d, SHA-256 checked at build time.
External signer
Section titled “External signer”Signing through a key held outside the SDK, with verify-before-use. See Typed signing and key IDs.
// Ratify Protocol v2 external signer: a signing provider holds the private// key; the SDK prepares each typed statement and verifies every returned// signature before using it.//// The provider here is an in-process stand-in for a remote signing service.// The interface makes no claim about any particular KMS or HSM.//// Run from this directory: node external_signer.tsimport { randomBytes } from "node:crypto";import { getPublicKeyAsync, signAsync, utils as ed25519Utils } from "@noble/ed25519";import { ml_dsa65 } from "@noble/post-quantum/ml-dsa.js";import { generateHybridKeypair } from "@identities-ai/ratify-protocol";import { SIGNER_MODE_DIRECT_V2, keyIDV2, signDelegationCertV2WithSigner, signProofBundleV2WithSigner, v2ErrorClassOf, verifyDelegationCertV2Signature, verifyProofBundleV2Signatures, type ProofBundleV2, type SignRequestV2, type SignerModeV2, type SignerV2,} from "@identities-ai/ratify-protocol/v2";
const start = 1800000000;
type HybridPublicKey = { ed25519: Uint8Array; ml_dsa_65: Uint8Array };type HybridSignature = { ed25519: Uint8Array; ml_dsa_65: Uint8Array };
const sameBytes = (a: Uint8Array, b: Uint8Array) => a.length === b.length && a.every((x, i) => x === b[i]);
// A signing service. Its private key never leaves it. It signs in direct// mode: Ed25519 over the 77-byte message M and ML-DSA-65 over M with the// SDK-chosen context string.class Provider implements SignerV2 { readonly name: string; readonly pub: HybridPublicKey; readonly log: string[] = []; readonly #ed: Uint8Array; ml: Uint8Array;
private constructor(name: string, pub: HybridPublicKey, ed: Uint8Array, ml: Uint8Array) { this.name = name; this.pub = pub; this.#ed = ed; this.ml = ml; }
static async create(name: string): Promise<Provider> { const ed = ed25519Utils.randomPrivateKey(); const ml = ml_dsa65.keygen(randomBytes(32)); return new Provider(name, { ed25519: await getPublicKeyAsync(ed), ml_dsa_65: ml.publicKey }, ed, ml.secretKey); }
publicKeyV2(): HybridPublicKey { return this.pub; }
modeV2(): SignerModeV2 { return SIGNER_MODE_DIRECT_V2; }
async signV2(req: SignRequestV2): Promise<HybridSignature> { // A provider refuses any request for a key it does not hold. if (!sameBytes(req.publicKey.ed25519, this.pub.ed25519) || !sameBytes(req.publicKey.ml_dsa_65, this.pub.ml_dsa_65)) { throw new Error(`${this.name}: request names a key this provider does not hold`); } const context = new TextDecoder().decode(req.mlDsaContext!); this.log.push(`${this.name} signed: mode=direct message=${req.message.length} bytes context=${context}`); return { ed25519: await signAsync(req.message, this.#ed), ml_dsa_65: ml_dsa65.sign(req.message, this.ml, { context: req.mlDsaContext! }), }; }}
const verified = (p: Promise<unknown>) => p.then(() => true, () => false);
console.log("Ratify Protocol v2 external signer");
const issuer = await Provider.create("issuer provider");const agent = await Provider.create("agent provider");const verifier = await generateHybridKeypair();const issuerID = keyIDV2(issuer.pub);const agentID = keyIDV2(agent.pub);const verifierID = keyIDV2(verifier.publicKey);const unsigned = { ed25519: new Uint8Array(0), ml_dsa_65: new Uint8Array(0) }; // replaced when signed
const cert = await signDelegationCertV2WithSigner({ version: 2, cert_id: "external-signer-cert-1", issuer_id: issuerID, issuer_pub_key: issuer.pub, subject_id: agentID, subject_pub_key: agent.pub, scope: ["files:read"], constraints: [], issued_at: start, expires_at: start + 86400, signature: unsigned,}, issuer);console.log(issuer.log[0]);console.log(`delegation: signature verified by the SDK (${await verified(verifyDelegationCertV2Signature(cert))})`);
const template: ProofBundleV2 = { version: 2, verifier_id: verifierID, agent_id: agentID, agent_pub_key: agent.pub, delegations: [cert], delegation_digest: new Uint8Array(0), challenge: new Uint8Array(32).fill(0x42), challenge_at: start, challenge_sig: unsigned, session_context: null, stream_id: null, stream_seq: null,};const bundle = await signProofBundleV2WithSigner(template, agent);console.log(agent.log[0]);console.log(`proof bundle: signatures verified by the SDK (${await verified(verifyProofBundleV2Signatures(bundle))})`);
// A faulty provider returns an ML-DSA-65 signature from a different key.// The SDK verifies before use, so nothing is signed.agent.ml = ml_dsa65.keygen(randomBytes(32)).secretKey;const refused = await signProofBundleV2WithSigner(template, agent).then(() => null, (err: unknown) => err);console.log(`faulty provider: refused (${v2ErrorClassOf(refused)})`);Source: examples/v2/typescript/external_signer at commit 5ca7585c2c1d, SHA-256 checked at build time.
Conformance
Section titled “Conformance”The SDK runs the shared corpus in testvectors/v2.
Which files each SDK runs, and the results at the tag, are recorded in the release notes and in
docs/V2_REFERENCE_COMPATIBILITY.md.
