# Attestation (/docs/attestation)



Attestation extends the
[audit-ledger cluster](/docs/audit-ledger#the-audit-ledger-cluster)
and sits on top of the [hash chain](/docs/hash-chain). The chain proves
a slice of the event log hasn't been mutated. Attestation wraps a signed
envelope around that slice, so a regulator, auditor or downstream replay
can verify it without read access to the writer's database.

The substrate ships as `@pleach/core/attestation`, a subpath rather than
a SKU. It has a signer, a verifier, the key-store interface, two
production adapters (AWS KMS and Vault Transit) that sign through a
client you inject, and a file-backed adapter on `attestation/testing`.
Policy, rotation cadence and framework-specific envelope shapes land in
`@pleach/compliance` or stay host-side.

> **Beta / `@experimental`.** While `@pleach/core` ships stable, the
> attestation surface (and `@pleach/compliance`) ship **beta** for the
> first release. Signing uses the key store you provide. The adapters
> throw `NotImplementedError` without an injected client. With no key
> store wired, an envelope carries `signature: ""` and
> `compliance.signed: false`, and the `modelVersions`, `promptVersions`
> and `toolVersions` maps are emitted empty.

**Subpath:** `@pleach/core/attestation`

## What attestation adds [#what-attestation-adds]

The chain detects tampering on rows you control. It proves nothing to
someone who doesn't control them. A regulator asking "show me what this
model decided at 14:00Z, signed" wants:

* canonical bytes for the slice;
* a signature by a key whose public half they can resolve out-of-band;
* a chain proof showing where the attested head sits in the broader
  event log, so the slice can't be lifted from one tenant and replayed
  under another.

`AttestationV1` carries all three. The chain supplies `eventChainHash`
and a `ChainProofV1`. The signer signs the canonical encoding of the
envelope, and the verifier checks the signature and returns a
structured `VerifyResult`. Chain replay stays with `verifyChain()` in
`@pleach/core/eventLog`.

## The core surface [#the-core-surface]

```typescript
import {
  signAttestation,
  verifyAttestation,
  canonicalizeAttestationPayload,
  computePayloadHash,
  type AttestationV1,
  type AttestationPayloadV1,
  type AttestationFieldVersions,
  type AttestationSignatureAlgorithm,
  type ChainProofV1,
  type VerificationError,
  type VerifyResult,
  type AttestationKeyStore,
  type AttestationSignResult,
  AwsKmsAttestationKeyStore,
  VaultTransitAttestationKeyStore,
  NotImplementedError,
} from "@pleach/core/attestation";
```

The `attestation/keyStores` subpath re-exports the key-store types and
adapters for hosts that only need that surface, such as a verifier
service that resolves public keys but never signs.

```typescript
import {
  AwsKmsAttestationKeyStore,
  VaultTransitAttestationKeyStore,
  type AttestationKeyStore,
} from "@pleach/core/attestation/keyStores";
```

The file-backed adapter lives on `attestation/testing`, off the
production barrel, for unit tests and local development:

```typescript
import { FileBackedAttestationKeyStore } from "@pleach/core/attestation/testing";
```

| Surface                                                 | Responsibility                                                            |
| ------------------------------------------------------- | ------------------------------------------------------------------------- |
| `signAttestation` / `verifyAttestation`                 | The sign/verify pair, over an `AttestationKeyStore`.                      |
| `canonicalizeAttestationPayload` + `computePayloadHash` | RFC 8785 JCS encoding and SHA-256, shared by signers and verifiers.       |
| `AttestationKeyStore` + production adapters             | Pluggable signing backend. KMS and Vault sign through an injected client. |
| `attestation/testing`                                   | `FileBackedAttestationKeyStore` for dev and tests.                        |

The RFC 3161 timestamp-authority client is covered under [`issuedAt` is
a claim](#issuedat-is-a-claim-externaltimestamps-is-a-proof).

## The envelope shape [#the-envelope-shape]

`AttestationV1` is the wire format. Every field is `readonly`, and the
signer freezes the returned object. The unsigned form
`AttestationPayloadV1` is `Omit<AttestationV1, "signature" |
"externalTimestamps">`. Both fields are countersignatures over the
payload, so neither sits inside what the signature covers.

```typescript
interface AttestationV1 {
  readonly version: "1";
  readonly sessionId: string;          // RFC 4122 v4
  readonly tenantId: string;
  readonly attestationId: string;      // RFC 4122 v4, generated at sign time
  readonly issuedAt: string;           // ISO 8601 UTC — SELF-ASSERTED signer clock
  readonly modelVersions: { readonly [modelId: string]: string };
  readonly promptVersions: { readonly [promptId: string]: string };
  readonly toolVersions: { readonly [toolName: string]: string };
  readonly runtimeVersion: string;     // @pleach/core package version at attest time
  readonly eventChainHash: string;
  readonly firstEventId: string;       // event handle; don't assume UUID format
  readonly lastEventId: string;        // event handle; don't assume UUID format
  readonly eventCount: number;         // >= 1
  readonly signatureAlgorithm: AttestationSignatureAlgorithm; // "ed25519"
  readonly signaturePublicKeyId: string;
  readonly signature: string;          // base64(ed25519-sig(canonical(payload)))
  readonly redactionAllowlistHash: string;
  readonly chainProof: ChainProofV1;
  readonly firstChainedSequenceNumber: number;
  readonly externalTimestamps?: readonly Rfc3161TokenReceipt[];
}
```

### `issuedAt` is a claim; `externalTimestamps` is a proof [#issuedat-is-a-claim-externaltimestamps-is-a-proof]

`issuedAt` comes from the signing process's own clock. It's worth
exactly as much as your trust in the signer. An operator holding the
signing key can backdate it and re-sign, and the signature still
verifies.

`externalTimestamps` closes that gap. Pass a `timestampAuthority` client
to `attestChainState` and it requests an
[RFC 3161](https://www.rfc-editor.org/rfc/rfc3161) token over the chain
proof's merkle root from an independent authority. The receipt shows the
attested content existed **no later than** the authority's timestamp,
which the key-holder can't rewrite.

| Surface                                    | Responsibility                                                                                                                                                                                                                                   |
| ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `createHttpTimestampAuthorityClient`       | RFC 3161 client over HTTP. Vendor-neutral: you supply the URL.                                                                                                                                                                                   |
| `buildTimeStampReq` / `parseTimeStampResp` | The DER codec, for callers that manage their own transport.                                                                                                                                                                                      |
| `Rfc3161TokenReceipt`                      | The stored receipt: base64 DER token, verified message imprint, hash algorithm, `genTimeIso`, `policyOid`, `serialNumberHex`, `accuracy`, `ordering`, `nonceHex` and any embedded `certificatesB64`. `accuracy` states how precise `genTime` is. |

What the core client checks, and what it doesn't:

1. **It checks the token covers your digest.** A mismatch in the message
   imprint or hash-algorithm OID throws rather than returning a receipt.
2. **It sends a nonce by default and checks the echo.** Pass
   `nonce: false` for an authority that rejects them.
3. **It does not verify the signature.** `@pleach/core` performs no
   CMS/PKCS #7 verification, because that is Node-only and the
   substrate runs in the browser. Verify offline (`openssl ts -verify
   -digest <imprint> -in token.der -token_in -CAfile <tsa-ca.pem>`) or
   in-process with [`verifyRfc3161Receipt`](#verifying-the-token-pleachcompliance).
4. **The token binds the chain root, not the attestation.** Two
   attestations over the same chain state have interchangeable receipts.
   To check one, confirm `messageImprintHex ===
   hex(sha256(hexDecode(eventChainHash)))`.

### The clock behind `issuedAt` [#the-clock-behind-issuedat]

A browser-side signer reading `Date.now()` inherits the device clock,
which can sit minutes off and jump backwards. `createAnchoredClock` is
the `Clock` implementation core ships for that job:

```ts
import { createAnchoredClock } from "@pleach/core/runtime";

const clock = createAnchoredClock({
  anchorMs: mintInstantMs,   // the session's trusted instant
  serverNowMs,               // server time observed at construction
});

clock.now();          // skew-corrected epoch ms, monotonic
clock.sinceMintMs();  // offset from the mint, never negative
```

It corrects device skew against the server instant and never steps
backward. It degrades to the wall clock where `performance` is
unavailable.

⛔ &#x2A;*This does not turn `issuedAt` into a proof.** A more accurate clock
reduces honest error such as drift and skew. It does nothing about
dishonest error, because an operator holding the key can still set any
value before signing. Only the authority's countersignature turns a
claim into evidence. Use the anchored clock so timestamps are *right*,
and `externalTimestamps` so they are *checkable*.

### Knowing which one you're producing [#knowing-which-one-youre-producing]

Wire a `signer` without a timestamp authority and everything succeeds.
You get a signed envelope that verifies, nothing warns, and you're
producing the weaker artifact. So the quickstart takes the authority as
an option, and both the agent and the runtime report which kind you
produce:

```ts
import { createPleachAgent } from "@pleach/core";
import { createHttpTimestampAuthorityClient } from "@pleach/core/attestation";
import { FileBackedAttestationKeyStore } from "@pleach/core/attestation/testing";
import { createSqliteDurableStore } from "@pleach/core/store";

const agent = createPleachAgent({
  db: createSqliteDurableStore("./agent.db"),
  signer: new FileBackedAttestationKeyStore({ privateKeyPath, keyId: "local" }),
  timestampAuthority: createHttpTimestampAuthorityClient({ url: TSA_URL }),
});

agent.evidence.timestamped;   // true — attestations carry an RFC 3161 receipt
agent.evidence.mintAnchorMs;  // the session's trusted mint instant, or null
agent.evidence.clockInjected; // whether timestamps come from an injected clock
```

The same shape is on the runtime as
[`runtime.evidence`](/docs/facets). It's deliberately narrow:

* It reports &#x2A;*wiring, not reachability.** An authority that is down
  still reads `timestamped: true`; the failure surfaces when a timestamp
  is requested.
* There is &#x2A;*no `clockAnchored` field.** Any object with a `now()`
  satisfies the `Clock` seam, so core can't verify that an injected
  clock is skew-corrected.

Omitting `timestampAuthority` is legitimate for internal integrity
checks, development and air-gapped deployments. Choose it rather than
defaulting into it:

```ts
if (process.env.NODE_ENV === "production" && !agent.evidence.timestamped) {
  throw new Error("refusing to start: attestations would be claim-only");
}
```

### Verifying the token (`@pleach/compliance`) [#verifying-the-token-pleachcompliance]

`@pleach/compliance` ships `verifyRfc3161Receipt` on its `./timestamp`
subpath. It performs real CMS verification against trust anchors you
pin, including certificate validity at `genTime`. SHA-1 and RSASSA-PSS
return `unsupported-algorithm`.

It needs `@sigstore/core`, an **optional** peer dependency. Without it,
the call returns `{ verified: false, reason: "verifier-unavailable" }`
rather than throwing.

Two properties to know before you cite a result:

* **Trust anchors are explicit and mandatory.** You pass PEM or DER in.
  There's no env read, OS trust store or bundled vendor list. An empty
  list is a hard `verified: false`, and a token that embeds its own
  self-signed root isn't trusted for carrying it.
* **Revocation is not checked.** No CRL or OCSP fetch happens, and the
  returned `checks` object deliberately has no `revocation` key. A
  `genTime` window reports `"skipped"` when you supply none, never
  `"pass"`.

Attachment is fail-open by design. If the authority is unreachable or
returns a non-granted status, `attestChainState` logs and returns a
valid, un-timestamped attestation. `verifyAttestation`'s `valid: true`
covers the ed25519 signature only and says nothing about any attached
token.

**`modelVersions` / `promptVersions` / `toolVersions`.** The attested
run's version surface, so a later replay can pin every model, prompt
contribution and tool version. An empty `toolVersions` is legal.

**`eventChainHash` + `firstChainedSequenceNumber`.** These anchor the
envelope to the [hash chain](/docs/hash-chain). When a chain reader
yields rows, `eventChainHash` is the `merkleRoot` of the embedded
`chainProof` and `eventCount` is the real event count. With no reader,
or zero rows, the envelope carries an all-zero placeholder root, so a
consumer can tell it from a root computed against a real log.
`firstChainedSequenceNumber` is the first row inside the slice.

**`redactionAllowlistHash`.** The hash of the active
[scrubber](/docs/scrubbers) allowlist at attest time. A verifier can
confirm the slice was redacted under a specific policy without having
the policy.

**`chainProof: ChainProofV1`.** A Merkle inclusion proof locating the
attested leaf inside the tenant's chain.
`verifyInclusionProof(proof)` from `@pleach/core/eventLog` checks only
that `leafHash` folds through `proofPath` to the proof's own
`merkleRoot`. Membership also needs that root to match one you obtained
independently, such as the `anchorChainSegments` root at the same
`headSequenceNumber` and `merkleConstruction`. That root exists only for
a chat with no restarts, because each restart starts a separately
anchored segment.

```typescript
interface ChainProofV1 {
  readonly algorithm: "sha256";
  readonly version: "pleach.c9.v1";       // the canonicalization tag
  readonly tenantId: string;
  readonly chatId: string;
  readonly headSequenceNumber: number;
  readonly leafSequenceNumber: number;
  readonly leafHash: string;              // hex
  readonly merkleRoot: string;            // hex
  readonly proofPath: ReadonlyArray<{
    readonly hash: string;                // sibling hash, hex
    readonly side: "left" | "right";      // which side the sibling sits on
  }>;
}
```

An empty `proofPath` is legal for a single-event chain, where
`merkleRoot === leafHash`.

## The CMS envelope [#the-cms-envelope]

`AttestationV1.signature` is a bare signature, with its algorithm, key
id and payload in sibling JSON fields. Only Pleach's code can verify it.
Regulatory and security teams usually work in CMS, so
`@pleach/core/attestation/cms` emits a **detached** CMS `SignedData`
over the attestation's canonical bytes, signed with Ed25519.

```typescript
import { buildAttestationDetachedCms } from "@pleach/core/attestation/cms"

const artifact = await buildAttestationDetachedCms(attestation, {
  keyStore,                    // the existing attestation signing seam
  certificateDer,              // DER of the signer's X.509 cert
  signingTime: new Date(),     // injectable, for deterministic tests
})
```

It is **additive**. `signAttestation()` and `verifyAttestation()` are
untouched, and the CMS artifact is produced alongside the `signature`
field, never instead of it.

Detached means the canonical bytes are never copied into the envelope.
Supply `certificateDer` whenever the artifact must be independently
checkable. Without it the artifact is still conformant CMS, but no
verifier can find a public key inside it.

The module is graded by `openssl cms -verify` against a written file,
not by round-tripping through the library that produced it. A mismatch
between emitted and signed attributes throws
`signed-attributes-mismatch` at emit time rather than shipping an
unverifiable artifact.

### The ASN.1 peers are optional [#the-asn1-peers-are-optional]

The encoders (`@peculiar/asn1-schema`, `@peculiar/asn1-cms`,
`@peculiar/asn1-x509`) are optional peer dependencies. A consumer who
never asks for CMS never installs them. One who does, without them,
gets `CmsAttestationError("asn1-peer-missing")` naming the package.

Detect errors with `isCmsAttestationError(err)`, never `instanceof`;
the class is brand-keyed because a dual-bundle build can duplicate it.
The `code` is one of `asn1-peer-missing`, `malformed-certificate`,
`invalid-signature-length`, `invalid-public-key` or
`signed-attributes-mismatch`.

## V2: DSSE envelopes [#v2-dsse-envelopes]

`AttestationV2` wraps the same canonical payload in a
[DSSE](https://github.com/secure-systems-lab/dsse) envelope. It's
**opt-in**: `signAttestation()` (V1) stays the default, and every V1
record verifies as before. The `envelope` field is the spec's
three-field shape, so you can hand it to a stock DSSE verifier.

```typescript
interface AttestationV2 {
  readonly version: "2";                 // envelope version
  readonly envelope: {
    readonly payloadType: string;        // ATTESTATION_V2_PAYLOAD_TYPE
    readonly payload: string;            // base64 of the JCS bytes V1 hashes
    readonly signatures: readonly { keyid: string; sig: string }[];
  };
  readonly externalTimestamps?: readonly Rfc3161TokenReceipt[]; // outside the signed bytes
}
```

`ATTESTATION_V2_PAYLOAD_TYPE` is
`application/vnd.pleach.attestation.v1+json`. The decoded payload is an
`AttestationPayloadV1` and keeps its own `version: "1"`, the
payload-schema version. It's a Pleach payload, not an in-toto Statement,
so in-toto policy engines won't interpret its fields. They can still
check the signature.

### Signing [#signing]

`signAttestationV2(payload, keyStore)` takes the same
`AttestationPayloadV1` as V1. It signs through the key store's optional
`signBytes(message)` method, pure ed25519 with no pre-hash.

```typescript
import { signAttestationV2, type AttestationV2 } from "@pleach/core/attestation";

const v2: AttestationV2 = await signAttestationV2(payload, keyStore);
```

The signer checks its own signature before returning, so a backend that
pre-hashed (Ed25519ph) or used the wrong key throws instead of minting
an envelope every DSSE verifier would reject.

There's no V1 fallback. Every failure throws `RawSigningUnsupportedError`
and emits nothing:

| `code`                        | When                                                                                     |
| ----------------------------- | ---------------------------------------------------------------------------------------- |
| `sign-bytes-absent`           | The key store has no `signBytes` method. Use `signAttestation()` or a raw-capable store. |
| `message-too-large`           | AWS KMS only: the message exceeds the 4096-byte KMS limit.                               |
| `self-verify-failed`          | The returned signature doesn't verify under the store's own public key.                  |
| `self-verify-key-unavailable` | `getPublicKey()` threw, so the signature couldn't be self-checked.                       |

Match on `err.name === "RawSigningUnsupportedError"` and `err.code`, not
`instanceof`; each `@pleach/core` subpath bundles its own copy of the
class.

| Key store                                               | `signBytes`                                                                                     |
| ------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `FileBackedAttestationKeyStore` (`attestation/testing`) | Yes. No size cap.                                                                               |
| `AwsKmsAttestationKeyStore`                             | Yes, capped at 4096 bytes.                                                                      |
| `VaultTransitAttestationKeyStore`                       | Yes, with an `ed25519` key.                                                                     |
| Your own `AttestationKeyStore`                          | Optional. Omit it, or throw `RawSigningUnsupportedError`, if your backend can't sign raw bytes. |

### Verifying [#verifying]

`verifyAttestation(attestation, publicKey)` takes V1 or V2 and
dispatches on `version`. Any other non-empty string returns
`unsupported-version`, and a missing or non-string version returns
`schema-invalid`. The V2 path passes if any one of its one to 16
signatures verifies under `publicKey`. It accepts canonical padded standard base64
only; base64url or missing padding is `schema-invalid`.

The envelope `keyid` is an **unauthenticated hint**. It sits outside the
signed bytes, and the verifier never reads it. The signer copies the key
store's `publicKeyId` into it, so an exported envelope discloses that
id. For KMS that is the full key ARN, including the account id.

Take the key id from the signed payload instead.
`decodeAttestationV2Payload` returns the inner payload without checking
anything, so resolve the key from its `signaturePublicKeyId`, then
verify under that key:

```typescript
import {
  verifyAttestation,
  decodeAttestationV2Payload,
  type AttestationV2,
} from "@pleach/core/attestation";

async function checkV2(
  v2: AttestationV2,
  resolvePublicKey: (keyId: string) => Promise<Uint8Array>, // your allowlisted resolver
) {
  const claimed = decodeAttestationV2Payload(v2);           // unauthenticated until verified
  const publicKey = await resolvePublicKey(claimed.signaturePublicKeyId);
  const result = await verifyAttestation(v2, publicKey);
  return result.valid ? claimed : null;                     // now the key id is authenticated
}
```

`decodeAttestationV2Payload` can throw on a malformed payload.
`verifyAttestation` never does.

### V2 verification errors [#v2-verification-errors]

V2 returns the same `VerifyResult`, with these `kind` values:

| `kind`                  | V2 meaning                                                                                                                                                                               |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `schema-invalid`        | The envelope or its payload is malformed.                                                                                                                                                |
| `unsupported-version`   | An unknown envelope `version`, a `payloadType` other than `ATTESTATION_V2_PAYLOAD_TYPE`, or an inner payload `version` other than `"1"`. The inner check runs after the signature check. |
| `unsupported-algorithm` | The inner `signatureAlgorithm` isn't `"ed25519"`.                                                                                                                                        |
| `key-id-unknown`        | `publicKey` isn't 32 bytes.                                                                                                                                                              |
| `signature-mismatch`    | No signature verified under `publicKey`.                                                                                                                                                 |

The verifier doesn't echo attacker-controlled text. Where a `detail`
quotes a field value, it is JSON-quoted and truncated.

## Canonicalization [#canonicalization]

`canonicalizeAttestationPayload(payload)` runs RFC 8785 JCS over the
unsigned payload. `computePayloadHash(canonical)` returns its SHA-256.

They're exported separately so a verifier can recompute the hash without
the full `verifyAttestation` path, and a custom signing backend can sign
the canonical hash without re-deriving the rules. Mismatched
canonicalization between signer and verifier surfaces as
`kind: "signature-mismatch"`.

## The `AttestationKeyStore` interface [#the-attestationkeystore-interface]

```typescript
interface AttestationSignResult {
  readonly signature: Uint8Array;   // ed25519 raw signature, 64 bytes
  readonly publicKeyId: string;     // opaque; matches AttestationV1.signaturePublicKeyId
}

interface AttestationKeyStore {
  sign(canonicalHash: Uint8Array): Promise<AttestationSignResult>;
  signBytes?(message: Uint8Array): Promise<AttestationSignResult>; // optional; V2 DSSE only
  getPublicKey(publicKeyId: string): Promise<Uint8Array>;
  identify(): string;               // the keyId this store signs with; synchronous
}
```

* **Signer path.** `sign(canonicalHash)` returns the raw signature and
  the key id the verifier needs.
* **Verifier path.** `getPublicKey(publicKeyId)` returns the 32-byte
  public key for `verifyAttestation()`.

The interface has no key-rotation surface, permission model or audit
hooks. Adapters layer those on their own infrastructure.

## Production adapters [#production-adapters]

`AwsKmsAttestationKeyStore` and `VaultTransitAttestationKeyStore` sign
through a transport you pass as `client`. `@pleach/core` takes no hard
dependency on `@aws-sdk/client-kms` or a Vault SDK. Without a `client`,
both adapters' `sign()` and `getPublicKey()` throw `NotImplementedError`.

The KMS `client` implements `KmsSigningClient`: `sign({ keyArn,
message })` returns the raw 64-byte signature, and `getPublicKey({
keyArn })` returns the raw or SPKI-DER key. The Vault `client` implements
`VaultTransitHttpClient` (`sign({ mount, keyName, inputBase64 })`,
`getPublicKey({ mount, keyName })`).

```typescript
import {
  AwsKmsAttestationKeyStore,
  VaultTransitAttestationKeyStore,
} from "@pleach/core/attestation";

const kms = new AwsKmsAttestationKeyStore({
  region: "us-east-1",
  keyArn: "arn:aws:kms:us-east-1:123456789012:key/abc-...",
  client: myKmsClient, // wraps SignCommand + GetPublicKeyCommand
});

const vault = new VaultTransitAttestationKeyStore({
  vaultAddr:    "https://vault.example.com:8200",
  transitMount: "transit",
  keyName:      "audit-attestation",
  client:       myVaultClient, // POST sign, GET keys
});
```

Both adapters are pinned to ed25519 at v1. Vault's key type must be
`ed25519`, and other curves are rejected at the type level.
`publicKeyId` is `vault://<mount>/<keyName>` for Vault and the full KMS
ARN for AWS.

## Signing is host/operator-provisioned [#signing-is-hostoperator-provisioned]

Attestation is early-stage. The sign and verify functions and the
envelope shape are stable, but the signing key store is host- or
operator-provisioned. The KMS and Vault adapters sign once you inject a
client, and the file-backed signer covers local and dev use.

## The file-backed adapter (dev + tests) [#the-file-backed-adapter-dev--tests]

`FileBackedAttestationKeyStore` signs from a local key file with no
external service. It lives on `attestation/testing` so app code can't
reach it through the production barrel.

```typescript
import { FileBackedAttestationKeyStore } from "@pleach/core/attestation/testing";

const keyStore = new FileBackedAttestationKeyStore({
  privateKeyPath: "/run/secrets/attestation-key.bin",
  keyId:          "test-key-2026-06",
});
```

The key file is 32 raw bytes, the ed25519 seed. There's no PEM or PKCS#8
support. The key is cached for the life of the instance, so construct a
fresh store to rotate.

## Worked example [#worked-example]

A host plugin signs each completed `AuditableCall`, and a verifier
service checks the envelope.

```typescript
// Signer side — runs in the host plugin's recordCall path.
import {
  signAttestation,
  type AttestationPayloadV1,
  type AttestationKeyStore,
} from "@pleach/core/attestation";

async function attestCall(
  call: AuditableCall,
  keyStore: AttestationKeyStore,
  publicKeyId: string,
): Promise<AttestationV1> {
  const payload: AttestationPayloadV1 = {
    version: "1",
    sessionId:      call.sessionId,
    tenantId:       call.tenantId,
    attestationId:  crypto.randomUUID(),
    issuedAt:       new Date().toISOString(),
    modelVersions:  call.fingerprint.modelVersions,
    promptVersions: call.fingerprint.promptVersions,
    toolVersions:   call.fingerprint.toolVersions,
    runtimeVersion: PLEACH_CORE_VERSION,
    eventChainHash: call.chainHash,
    firstEventId:   call.firstEventId,
    lastEventId:    call.lastEventId,
    eventCount:     call.eventCount,
    signatureAlgorithm:   "ed25519",
    signaturePublicKeyId: publicKeyId,
    redactionAllowlistHash: call.redactionAllowlistHash,
    chainProof:             call.chainProof,
    firstChainedSequenceNumber: call.firstSeq,
  };
  return signAttestation(payload, keyStore);
}
```

The verifier resolves the public key out-of-band (KMS `GetPublicKey`,
Vault Transit `read key`, or a local cache for the file-backed adapter)
and runs `verifyAttestation`.

```typescript
// Verifier side — runs in a service that receives signed envelopes.
import {
  verifyAttestation,
  type AttestationV1,
  type VerifyResult,
} from "@pleach/core/attestation";

async function checkEnvelope(
  attestation: AttestationV1,
  resolvePublicKey: (keyId: string) => Promise<Uint8Array>,
): Promise<VerifyResult> {
  const publicKey = await resolvePublicKey(attestation.signaturePublicKeyId);
  return verifyAttestation(attestation, publicKey);
}
```

`verifyAttestation` never throws on signature mismatch. The
`VerifyResult` is `{ valid: true }` or `{ valid: false, errors:
VerificationError[] }`, each error tagged by `kind`:

| `kind`                  | Meaning                                                                                                                   |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `signature-mismatch`    | The signature didn't verify against the resolved public key and canonical payload.                                        |
| `schema-invalid`        | The `version`, `signatureAlgorithm` or `signature` field failed the structural check.                                     |
| `key-id-unknown`        | The `publicKey` argument wasn't a 32-byte `Uint8Array`.                                                                   |
| `unsupported-algorithm` | Well-formed, but names an algorithm this build doesn't implement. Still `valid: false`.                                   |
| `unsupported-version`   | The envelope `version` isn't `"1"` or `"2"`. Still `valid: false`. See [V2 verification errors](#v2-verification-errors). |

Schema errors short-circuit before the signature check.

`unsupported-algorithm` is split from `schema-invalid` because the
distinction is evidentiary. A malformed record reads to an auditor as
corruption or tampering. An older verifier meeting a newer record is a
statement about the verifier, and over a long retention window it's
normal. One needs the record re-examined and the other needs the
verifier upgraded.

### Example: dating a disputed message [#example-dating-a-disputed-message]

**Example: dating a disputed message.** A user disputes when the app told them to seek care. The deployment requested time-stamp tokens from an authority it chose, by passing `timestampAuthority` to `attestChainState`. The reviewer asks when those rows existed, without trusting the deployment's server clock.

1. Find the attestation over the log slice that holds the message. Its `externalTimestamps` field carries the stored receipts. The `issuedAt` field is only the signer's own claim.
2. Check that the receipt's message imprint matches the SHA-256 of the envelope's `eventChainHash`. The token binds the chain root, not the attestation.
3. Run `verifyRfc3161Receipt` from `@pleach/compliance/timestamp` with the trust anchors you pin. See [Verifying the token](#verifying-the-token-pleachcompliance).
4. Read `genTime` from the result. The slice existed no later than that moment, as the authority attests.

The token dates the slice. It doesn't prove the app's answer was correct. Revocation isn't checked, and attachment is fail-open, so an attestation can exist with no token at all. The attestation surface is beta.

### Example: an outside auditor checks one month [#example-an-outside-auditor-checks-one-month]

**Example: an outside auditor checks one month.** An auditor receives signed envelopes over one month's rows and has no access to the writer's database. The question is whether the envelopes verify and whether the slice matches a chain root they trust.

1. Obtain the signer's public key out-of-band, as in the [worked example](#worked-example).
2. Call `verifyAttestation(attestation, publicKey)` from `@pleach/core/attestation` on each envelope. It returns `{ valid: true }` or a list of errors by `kind`.
3. Check `chainProof` with `verifyInclusionProof` from `@pleach/core/eventLog`. It confirms the leaf folds to the proof's `merkleRoot`.
4. Compare that root to one obtained independently, such as an anchored segment root.

`valid: true` covers the signature only. It says nothing about an attached token. This example assumes the writer wired a key store. Without one, an envelope carries `signature: ""` and there's no signature to check. There's no `pleach attest` CLI, so the auditor calls these functions from a script.

## Relationship to the audit-ledger cluster [#relationship-to-the-audit-ledger-cluster]

| Concept                                       | Where it lives                 | What it does                                                       |
| --------------------------------------------- | ------------------------------ | ------------------------------------------------------------------ |
| [AuditableCall row](/docs/auditable-call-row) | `@pleach/core/audit`           | Typed per-call record. The unit of evidence.                       |
| [Scrubbers](/docs/scrubbers)                  | `@pleach/core/scrubbers`       | Redact payload fields before the row persists.                     |
| [Hash chain](/docs/hash-chain)                | `@pleach/core/eventLog`        | Previous-row hash and row hash on every row.                       |
| **Attestation**                               | **`@pleach/core/attestation`** | **Signed envelope over a chain slice; portable to third parties.** |
| [ProviderDecisionLedger](/docs/audit-ledger)  | `@pleach/core` (write path)    | The persistence surface every row flows through.                   |

Scrubbers shape what gets written, the chain proves it wasn't mutated,
and attestation signs the proof. Each layer assumes the layer below
holds.

## What's not in scope today [#whats-not-in-scope-today]

`@pleach/core/attestation` doesn't ship:

* **A CLI.** No `pleach attest` or `pleach verify-attestation`. Hosts
  wire the functions into their own binaries.
* **Managed key rotation.** No rotation scheduler or key-lifecycle
  policy. The adapter decides what rotation means.
* **Framework-specific envelope shapes.** No FedRAMP, HIPAA or SOC2
  variants of `AttestationV1`. Compliance bundles carry their own
  metadata alongside.
* **Compliance-mode policy enforcement.** Nothing refuses to start
  because attestation isn't configured. That's a host-side or
  `@pleach/compliance` decision.

The KMS and Vault adapters sign once you inject a client (see
[Production adapters](#production-adapters)). Dev paths can use the
file-backed adapter.

## Where to go next [#where-to-go-next]

<Cards>
  <Card title="Hash chain" href="/docs/hash-chain" description="The tamper-evidence layer attestation signs over." />

  <Card title="AuditableCall row" href="/docs/auditable-call-row" description="The per-call evidence unit." />

  <Card title="Scrubbers" href="/docs/scrubbers" description="Payload redaction at write time; attestation carries the allowlist hash." />

  <Card title="Audit ledger" href="/docs/audit-ledger" description="The ProviderDecisionLedger write path and the three compliance plug-points." />

  <Card title="Compliance" href="/docs/compliance" description="The SKU that consumes attestation alongside framework-specific policy." />
</Cards>
