Skip to content
pleach
Operate

Tamper-evident hash chain

The per-row hash link on the audit-ledger event log — what the chain proves, how to verify it, and where it stops.

The hash chain is one of three concepts in the audit-ledger cluster. The AuditableCall row is the per-call record, with its own call-row chain. The ProviderDecisionLedger is the write path. This page covers the layer that links each persisted event-log row to its predecessor. For read-side observability, see Observability.

The chain makes three after-the-fact tampers detectable: a backfill that inserts a row at an earlier index, a reorder, and a removal from the middle of the stream. Verification reports the first index where the chain breaks.

Writer integrity is a shared responsibility. You provide the controls around the writer: least-privilege database credentials, a signing key held outside the database (keyed chains), and an outside witness.

An outside witness is an independent party that signs the chain's merkle root. Periodic RFC 3161 anchoring provides one. Anchoring only at attestation time bounds nothing in between: a writer can rewrite freely and attest afterwards. Anchoring on a schedule turns "history could have been rewritten at any point" into "at most one interval ago." The anchor interval is the bound, so choose it deliberately.

The chain is tamper-evident, not tamper-proof. A rewrite of witnessed rows is detectable only if something re-derives the root and checks it against the witnessed one.

Subpath@pleach/core/eventLog

The two columns

Each event-log row carries two hash fields. Both are raw 32-byte digests, and the verifier exports hex only for display.

  • Previous hash: the previous row's hash, copied verbatim.
  • Row hash: SHA-256 of a canonical encoding of the row, excluding the hash field itself.

Both columns ship in the @pleach/core schema bundle (base/003_harness_event_log.sql).

Rows written before stamping existed carry neither field, and the verifier skips them.

Walk a chain by sequence number, with the row id as tie-break. The shipped readers do this, including createSupabaseVerifyChainReader in @pleach/replay. Don't walk by creation time: rows from one flush share a timestamp, and that walk reports tampering on healthy chains.

What "canonical encoding" means

Two writers that saw the same row state must compute the same hash. The canonical encoding is a deterministic serialization of the row's fields.

Don't reimplement it from a guess. Use the exported helpers (canonicalizeRowForChain, computeRowHash) so a future field addition reaches the writer and verifier together.

Lifecycle status

Today. The hash fields ship in the @pleach/core schema bundle, so a bare npx @pleach/core init install has them. Writer-side stamping is on by default. Pass c9PhaseBEnabled: false to EventLogWriter to disable it for rollback; that is safe only for chats with no chained rows. createPgEventLogWriter stamps the same chain by default (stampChain: true); see Storage → durable event-log writer.

Concurrency. Without the base bundle's sequence allocator, parallel writers can collide on an ordinal. The bundle ships no uniqueness constraint on chat plus sequence number. Walk by sequence number and id either way (see The two columns).

Verification ships in code. verifyChainForChat(...) reports the first index where a chain breaks. generateProof(...) produces a portable ChainProofV1 over a window. @pleach/replay calls verifyChainForChat to gate re-execution against an untampered log.

Diagnostic probes

EventLogWriter and the verifier emit two probes you can filter on to confirm stamping and verification run in your deployment. Both fire whether or not stamping is enabled, so a missing emission points at configuration.

Row-stamp probe

Filter on [UXParity:c9-hash-chain-row-stamp]. It fires once per chat-bearing flush row.

  • phase: "active": stamping is on, and the probe carries the first 16 hex characters of each hash.
  • phase: "disabled": stamping is off, and both prefixes are null.

Both phases carry turnId when the row has a turn. A flush can hold rows from several turns, so join each stamp to its turn by turnId. Treat it as a correlation key only, never for access decisions.

interface RowStampProbe {
  phase: "active" | "disabled";
  chatId: string;
  tenantId: string;
  prevHashPrefix: string | null;
  rowHashPrefix: string | null;
}

Verify probe

Filter on [UXParity:c9-hash-chain-verify]. It fires once per verifyChainForChat call, with no sampling.

interface VerifyProbe {
  chatId: string;
  tenantId: string;
  chainValid: boolean;
  rowCount: number;            // all rows examined
  nonLegacyRowCount: number;   // chain-participating rows
  failedIndex?: number;        // present iff chainValid: false
  warnOnly: boolean;
}

warnOnly echoes the verifier option of the same name. With warnOnly: true, a failed verification also logs a [UXParity:c9-chain-verify-warn-only] line through console.warn.

Pure hash module + verification

The hashing and verification logic ships as a pure module. It needs node:crypto and nothing else, so verifiers, tests and external auditors can use the same canonicalization as the writer.

import {
  PLEACH_C9_CANONICALIZATION_VERSION,  // "pleach.c9.v1"
  computeGenesisSeed,                  // (tenantId, chatId) → Buffer
  canonicalizeRowForChain,             // (CanonicalRowFields) → Buffer
  computeRowHash,                      // (prevHash, canonical) → Buffer
  chainStep,                           // genesis-aware single advance
  verifyChain,                         // walk + row-precise diagnostic
  isLegacyRow,                         // null-rowHash detector
} from "@pleach/core/eventLog";

verifyChain returns { ok: true } or { ok: false, failedIndex, expected, actual, reason }. isLegacyRow separates pre-stamping rows from chain breaks, so a legacy row never reads as tampering.

What gets hashed, what doesn't

The chain hashes the row as persisted. Scrubber-redacted payloads hash in their redacted form. That is deliberate: the chain protects what was written, not information lost to redaction. See Scrubbers.

The payload enters the row hash only through its payload hash. New rows carry the sha256-jcs label, computed by computeEventPayloadHash. With payload encryption on, the hash covers the stored ciphertext.

The chain covers the stored payload-hash string and doesn't recompute it. To prove a payload wasn't edited, also compare computeEventPayloadHash(payload) to the stored payload hash. Rows labelled sha256 (the legacy label) can't be re-checked from a jsonb read.

Not in the v1 or v2 hash:

  • the row id and creation time;
  • the raw payload (covered through its payload hash);
  • the session id and turn id (hashed only under v3);
  • the key-version marker, which is unhashed metadata. The verifier takes the key mode from deployment config, never from this field.

Back-compat for pre-hash rows

You don't need to backfill old rows. Verification skips any row with no row hash and resumes at the next stamped row. The first stamped row is the chain root, and earlier rows sit outside the chain. They stay queryable.

A chat that already holds rows from an unchained createPgEventLogWriter starts its chain on a segment anchor at its first chained ordinal. Pass that ordinal as verifyChainForChat({ firstChainedSequenceNumber }). Without it, the verifier can't tell the unchained prefix from deleted rows and reports the chat as intact but discontinuous.

Verifying a chain

Two entry points ship. Both walk one chat's chain and report the first row where it breaks.

ReplayRuntime.verifyChainIntegrity on @pleach/replay takes a reader and returns a verdict object:

import { createReplayRuntime } from "@pleach/replay";
import { createSupabaseVerifyChainReader } from "@pleach/replay/readers/supabase";

const replay = createReplayRuntime({ tenantId });
const verdict = await replay.verifyChainIntegrity(
  { chatId, tenantId }, // optional: firstChainedSequenceNumber, expectedHead, mode
  { reader: createSupabaseVerifyChainReader(supabase) },
);
// { chatId, tenantId, valid, totalChecked, brokenAt?, segmentCount?, notVerifiedReason? }

brokenAt carries { failedIndex, expected, actual, reason } for the first divergent row. valid: true means no row failed. It doesn't prove the tail is intact unless you pass expectedHead (see Detecting a removed tail). totalChecked: 0 means nothing was walked.

verifyChainForChat on @pleach/core/eventLog is the core verifier that verifyChainIntegrity delegates to. Call it with any HarnessEventReader whose iterateChatEvents yields rows in sequence order:

import { verifyChainForChat } from "@pleach/core/eventLog";

const result = await verifyChainForChat({
  reader,       // HarnessEventReader
  tenantId,
  chatId,
  key,          // omit for an unkeyed (v1) chat
});

There's no verify-chain CLI. A hand-written SQL walk that only compares previous-row hashes catches link breaks but not an edited row. Use one of the verifiers above for a verdict.

Example: a reply edited in the database

Example: a reply edited in the database. Someone with database write access changes the stored text of one assistant reply in a March session. Months later a reviewer asks whether the record was changed after it was written. The deployment runs a durable event store, so there are rows to check.

  1. Run verifyChainForChat from @pleach/core/eventLog over that chat. See Verifying a chain.
  2. Read brokenAt. It names the first row whose recomputed hash doesn't match the stored one, with the expected and actual values. Rows before it are intact.
  3. Test for a removed tail separately. Deleted final rows leave every remaining link valid, so pass expectedHead from the chain-head store or an off-store copy. A missing tail then fails. See Detecting a removed tail.
  4. Ask whether the chain was keyed. An unkeyed chain lets anyone with write access edit a row and recompute every hash after it. A keyed chain needs a signing key kept outside the database.
  5. Compare against the stored anchors with verifyChainAnchors. A root-mismatch verdict is the loudest signal the system produces.

The chain detects a change after the write. It doesn't prevent one, and it doesn't say who made the edit. Prevention is the job of database permissions and the opt-in WORM tier.

Verifying the anchors

Chain verification and anchor verification answer different questions. A chain that verifies proves the rows you can see form an unbroken sequence. It doesn't prove that sequence is the one an outside witness saw. For evidence, run both.

verifyChainAnchors compares each witnessed segment's root, rebuilt from the live rows, against the root stored on the anchor:

import { verifyChainAnchors } from "@pleach/core/eventLog";

const report = verifyChainAnchors({
  anchors,        // the stored anchor rows for this scope
  entries,        // the live chained rows they claim to witness
  verifyResult,   // the result of verifying the chain itself
  tenantId,
  chatId,
});

root-mismatch is the loudest verdict the system produces. chain-unverifiable is reported separately: if the chain itself doesn't verify, nothing can be concluded about its root, and folding the two together would manufacture a tamper alarm from a broken input.

An anchor nobody checks is worse than none

The interval is the bound only while anchors keep arriving. A table that stopped growing an hour ago still holds valid witnesses of past roots, and none of them bounds the present. Grade liveness on staleness, never on row count.

import { evaluateChainAnchorFreshness } from "@pleach/core/eventLog";

const liveness = evaluateChainAnchorFreshness({
  anchors,
  intervalMs,     // your anchoring cadence — core owns no schedule
});
// → { status: "fresh" | "stale" | "never-anchored",
//     anchorCount, timestampedAnchorCount, ageMs, thresholdMs, detail? }

Freshness is graded only on anchors with a readable timestamp. Read anchorCount and timestampedAnchorCount as well as status: damaged rows and a stale newest anchor are independent failures.

intervalMs is validated. A non-finite or non-positive value throws.

Severity

classifyChainAnchorAlertLevel turns a liveness report into "ok" | "info" | "warn". Two rules in it are worth copying.

Liveness never shares a channel with tampering. There is no "alarm" level here. A stale anchor means only that the bound can't currently be proven, which has mundane causes such as an authority outage or a fresh install. Routing it onto the tamper signal would train people to mute that signal.

Damage raises a verdict and never lowers one. Corrupted anchors combine with the liveness verdict by taking the louder of the two. Missing or damaged evidence may withhold an escalation, but must never cause a de-escalation.

Running it on a schedule

@pleach/recipes composes these primitives into a scheduled pass as chainAnchorScheduler. It exposes runOnce() and no loop, so the schedule stays yours.

What is not claimed

Re-deriving the root and comparing it to the stored value needs no trust anchors and always runs. It proves the chain still hashes to the value you stored. It does not verify the timestamp token; that needs pinned CA roots and lives in @pleach/compliance. A skipped token check is reported as skipped, never as a pass.

Every ChainAnchorVerdict carries tokenVerified: "not-checked", so a structural ok can't be read as "cryptographically verified".

Checking the token itself

Run verifyRfc3161Receipt from @pleach/compliance/timestamp over the anchor's stored token. It confirms a timestamp authority you pinned signed the token, and that the token covers the anchor's message imprint.

import { verifyRfc3161Receipt } from "@pleach/compliance/timestamp";

const token = await verifyRfc3161Receipt(
  { tokenB64: anchor.tokenB64, messageImprintHex: anchor.messageImprintHex },
  {
    trustAnchors: [tsaRootPem],              // required; empty → "no-trust-anchor"
    requireSigningCertificateBinding: true,  // default false
  },
);
// → { verified, reason?, genTime?, checks: { signature, imprint, genTimeWindow } }

The imprint is the SHA-256 of the merkle root. Root re-derivation ties the live rows to the stored root, and the token check ties that root to a signature you didn't produce.

requireSigningCertificateBinding governs only an absent ESS SigningCertificate(V2) attribute. A present attribute naming a different certificate always fails ("signing-cert-mismatch"). The default is false because turning it on invalidates stored tokens from an authority that omits the attribute, so turn it on for new deployments. Revocation isn't checked; see Attestation.

Keyed chains (HMAC v2)

The unkeyed v1 chain proves linkage. An actor with database write access can still mutate a row and recompute every hash after it, producing a self-consistent chain. Scheduled anchoring is what bounds that actor.

Keyed mode raises the bar at the row level. Pass a signing key as EventLogWriter's c9SigningKey, and new rows are chained with HMAC-SHA256 under that secret. An actor with write access but without the key can't forge a matching hash, so a database-level rewrite breaks verification. Omit the key and the chain stays unkeyed v1. The mode requires the key-version field migration.

You provide the rest: keep the signing key outside the database and away from the store's write path, and anchor heads off-store so a key holder's writes stay bounded by the anchors.

Chain identity (v3)

A v3 chain is keyed on tenant and chain id rather than tenant and chat id. Rows that belong to no chat, such as a session's own events, auth events and tenant-wide audit, get a chain of their own. The chat id stays an attribution field.

Off by default

v3 is behind EventLogWriter's c9ChainIdentity option, which defaults to false. With it off, writer output is unchanged. The base bundle adds the v3 fields expand-only. An existing install backfills each chained row's chain id from its chat id, with chain kind chat, in its own migration before turning the option on.

ModeRow hash
v1SHA-256
v2HMAC-SHA256 under c9SigningKey
v3SHA-256
v3 keyedHMAC-SHA256 under c9SigningKey

Chain kinds are chat, session, subject, tenant-audit and auth. The same id under two kinds is two chains.

v3 also covers time and attribution in the hash: chain identity, server-stamped recorded time, occurred time, session id, turn id and subject ref. A v1 or v2 hash covers none of these, so use v3 when timestamps and session ids must be covered.

A per-writer-instance id and an ingest counter sit outside the hash. They order a tenant's rows across chains for reading, and they aren't an integrity claim.

Only a chain born under a c9ChainIdentity writer is v3. An existing v1 or v2 chain keeps its canon. The verifier accepts a legacy chain that continues into v3 through a chained chain.version_transition row; the writer doesn't emit that row today, so existing chats stay on their canon.

Before turning v3 on

A v3 row hashes the session id. If a foreign key on the event log's session id is ON DELETE SET NULL, deleting the session rewrites the column and makes the row unverifiable. The core bundle declares no such key; check any your host added.

Session chains

Under v1 and v2, events with no bound chat quietly opened a "chat" chain addressed by a session id. With v3 on, they go to a session chain instead: kind session, the session id as chain id, and an empty chat id.

SessionRuntime routes for you through wrapWriterWithSessionChain. A writer without c9ChainIdentity receives the identical event, so the wrapper is inert there.

A session chain starts with a genesis row and records each chat it binds to:

import {
  writeSessionChainGenesis,
} from "@pleach/core/eventLog";

// Writes session.created (the genesis row) on the session chain, then
// session.bound_chat on BOTH the chat chain and the session chain.
const wrote = writeSessionChainGenesis(writer, {
  sessionId,
  chatId,
  reason: "open",
});
// false: writer has v3 off, the id isn't a UUID, or sessionId === chatId

reason is one of "open" (new session), "resume" (rebind), "fork" or "cli". The paired session.bound_chat rows are the join for rebuilding session-to-chat links.

Verifying v1, v2 and v3

verifyChainById verifies one chain by its v3 identity. v1, v2 and v3 rows can share a chain, joined by a chain.version_transition row. verifyChainForChat is a thin wrapper over it with chainKind: "chat".

import { verifyChainById } from "@pleach/core/eventLog";

const result = await verifyChainById({
  reader,               // must implement iterateChainEvents for a non-chat chain
  tenantId,
  chainKind: "session",
  chainId: sessionId,
  key,                  // legacy (v2) rows, and v3 rows unless v3Key is set
});

A chat-addressed read can return v3 rows that belong to another chain but carry this chat's id as attribution. The verifier doesn't skip them. A foreign row at or above the chain's first own ordinal refuses the walk. One below it is excluded and counted in foreignChainRowCount.

Read a non-zero foreignChainRowCount on an ok verdict as "not fully verified", and verify that chat through a chain-addressed reader.

Chain anchors are still addressed by tenant and chat id. A session chain has no anchor surface yet.

Recording clock drift

wrapWriterWithClockAttestation records how far your host's clock sits from a reference, on the chain itself. Pleach measures nothing: your attestClock callback reports the offset, for example from chrony or ntpd.

import { wrapWriterWithClockAttestation } from "@pleach/core/eventLog";

const writer = wrapWriterWithClockAttestation(eventLogWriter, {
  tenantAuditChainId,          // the tenant-audit chain id you stored
  toleranceMs: 250,
  attestClock: async () => ({ source: "chrony", offsetMs, maxErrorMs, measuredAtMs: Date.now() }),
});

Each reading is written as a chained clock.attested row, and later rows written through the wrapper name the latest attestation. With v3 chain identity on, that reference is hashed with the row. A reading outside toleranceMs also writes a clock.drift_breached row. A callback that throws, times out or returns a stale value writes a clock.attestation_failed row, and so does a reading whose error bound is too wide to decide.

Three limits. No clock row ever blocks a write. A row older than the freshness bound names no attestation, so a long outage leaves rows without one. And the record is only as good as your callback's measurement: it proves what the host reported, not the true time. Without attestClock the writer is returned unchanged.

Detecting a removed tail

Pass the chain's committed head and the verifier catches a deleted tail, not just an edited row. Without it, deleting the last rows of a chain leaves every remaining link intact, and the walk reports ok: true.

The head is the chain's last committed sequence number and row hash, held by the chain-head store. Hand it to the verifier as expectedHead, and the verdict is refused unless the walk reached a row at that ordinal with that hash:

import { createReplayRuntime } from "@pleach/replay";
import { createSupabaseVerifyChainReader } from "@pleach/replay/readers/supabase";

// 1. Read the committed head BEFORE the rows. How you read it depends
//    on your store; the head is a sequence number and a row hash.
const head = await readCommittedHead(tenantId, chatId); // your code
// Postgres returns bytes as "\x…" hex: strip that prefix from the hash.

// 2. Walk the rows against it.
const replay = createReplayRuntime({ tenantId });
const verdict = await replay.verifyChainIntegrity(
  {
    chatId,
    tenantId,
    expectedHead: {
      sequenceNumber: head.sequenceNumber,
      rowHash: head.rowHash, // hex string
    },
  },
  { reader: createSupabaseVerifyChainReader(supabase) },
);

A missing tail fails with "admitted chain does not reach the committed head". Rows above the head are fine: they were written after you read it. Read the head first for that reason.

The head is evidence from outside the rows, so its strength is the gap between who can rewrite the event log and who can rewrite the chain-head store.

ActorCaught?
Can delete event-log rows but not touch the sequence table (a scoped purge, an operator mistake)Yes
Can rewrite both tablesNo — they move the head too. An anchored copy of the head is stronger.

A v3 row with no row hash is refused, never treated as legacy. A NULL-hash row above the chain's first chained row is refused too, because the legacy shape is a prefix only.

When the reader refuses to grade

verifyChainIntegrity is chat-addressed, and its Supabase reader projects the legacy canon only. On a v3 row it throws ChainReadNotVerifiableError with code "v3-row-on-chat-read", rather than reporting an intact chain as tampered.

verifyChainIntegrity maps that to valid: false, totalChecked: 0, notVerifiedReason: "v3-row-on-chat-read" and no brokenAt. That is not a chain break, so test notVerifiedReason before reading valid: false as tamper evidence. If you call the core verifier yourself, match the error with isChainReadNotVerifiable(err) from @pleach/replay.

For v3 chains, use createSupabaseChainReader (also on @pleach/replay/readers/supabase) with verifyChainById. It needs the v3 columns and, for a chat chain, the chain-id backfill, so it's opt-in rather than a drop-in replacement.

Chain segment anchors

A chain whose earliest chained row hangs off neither its genesis seed nor a segment seed can't be walked from its beginning. The verifier fails at index 0, and only the writer can mint a boundary.

With c9SegmentRestartOnBrokenChain enabled, the writer starts such a chat's next block on a segment anchor that records the restart reason. The marker is covered by the row's hashes, so it can't be added or stripped afterwards without breaking verification.

The flag is off by default. Minting an anchor declares the history before that point not vouched for, which is an operator decision, not an upgrade surprise. Restarts are bounded to one per tenant and chat per writer instance.

computeSegmentSeed and isSegmentAnchorRow export from @pleach/core/eventLog. On a keyed chain, isSegmentAnchorRow needs the signing key to decode a restart.

Which merkle construction built the root

Two constructions ship, and a proof says which one built it. ChainProofV1 carries merkleConstruction: "legacy" | "rfc6962", and generateProof(...) takes a matching construction option that defaults to "legacy".

The default is not an endorsement. Switching a chat to "rfc6962" changes every root it produces, and existing anchors countersigned the legacy roots. The choice belongs to a per-chat rollout gate, and defaulting the other way would orphan every anchored chat.

"rfc6962" follows RFC 6962 §2.1. It fixes two defects of "legacy": no domain separation between leaves and internal nodes, and a lone node paired with itself, so a root doesn't determine its leaf set.

merkleConstruction is absent on proofs minted before the field existed. verifyInclusionProof treats absence as "legacy", so never infer the construction from anything else on the proof.

A separate axis from the key version

The key-version marker says how a row is hashed (unkeyed or HMAC). merkleConstruction says how rows are combined into a root. A chat can move on either axis independently.

The call-row chain

Everything above covers the event log. The per-call ledger has its own chain, on by default. PostgresProviderDecisionLedger, resolveDefaultProviderDecisionLedger and the quickstart route's durable ledger stamp it unless you pass hashChain: false. hashChain: { signingKey } keys it. The KV ledger createPleachAgent installs is chained by default too (auditLedgerHashChain); verify it with verifyAuditLedgerStoreChain from @pleach/core/quickstart.

A table without the chain columns still gets every row, unchained, with one onError breadcrumb. The ledger's default PII redactor runs before the hash, so the chain covers the redacted row that is stored.

Verify with verifyAuditableCallChain from @pleach/core/audit. It names the first row that doesn't match, and it catches an edit, a backfill or a deletion without stopping one. Removed tail rows need an expectedHead, and an unkeyed chain is recomputable by anyone with write access. See AuditableCall row → proving rows weren't edited.

Anchoring call rows in the event log

The opt-in decorator withAuditRecordedAnchor writes one audit.recorded event per written call row. This chain covers the event, and verifyCallAnchors reports rows that are missing, changed or orphaned. See Audit ledger → anchoring call rows.

Relationship to @pleach/replay

Replay re-serves a recorded turn from the event log and names the first event that diverges. A replay over a slice whose chain doesn't verify is re-serving inputs nobody can vouch for, so verify the chain first. See Eval and replay.

What the hash chain doesn't replace

The chain is an after-the-fact tamper detector, not access control. It doesn't replace:

  • RLS. Row-level security gates who can read or write rows. The chain covers whatever rows got written.
  • Auth. The chain says nothing about identity, only that the row sequence hasn't been mutated since it was written.
  • In-flight encryption. TLS protects bytes on the way to the database. The chain protects them after they land.
  • Database-level immutability. The chain detects an edit; it doesn't stop one. The opt-in WORM tier refuses UPDATE, DELETE and TRUNCATE on the event log at the database.

Layer the chain on top of those controls, not in place of them.

Where to go next