惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
B
Blog
博客园 - 三生石上(FineUI控件)
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
T
The Blog of Author Tim Ferriss
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园_首页
Vercel News
Vercel News
量子位
A
About on SuperTechFans
博客园 - 聂微东
WordPress大学
WordPress大学
D
DataBreaches.Net
The Cloudflare Blog
M
MIT News - Artificial intelligence
Last Week in AI
Last Week in AI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
D
Docker
雷峰网
雷峰网
C
Check Point Blog
S
SegmentFault 最新的问题
U
Unit 42
月光博客
月光博客
Apple Machine Learning Research
Apple Machine Learning Research

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
The Audit Trail Is a Data Structure, Not a Log Message
Kingsley Ono · 2026-05-11 · via DEV Community

Logs can explain what a service thought happened.

They do not prove what happened.

Klevar Docs needed an audit trail for rendered documents, invoice events, credit note applications, signatures, voids, and attachments. The usual answer is an events table. Insert a row whenever something happens. Add timestamps. Keep it forever. That is useful, but it is still just a table unless the table can detect tampering.

The hash chain is the difference.

Each entity gets its own ordered chain. A row stores the event payload, a SHA-256 hash of the canonical payload, the previous row hash, the chain index, and a link hash that binds those values together. If someone changes a payload, deletes a prior row, swaps entity rows, or reorders entries, verification fails.

The append path is transactional with the document change. That detail matters more than the hashing. If the document row commits and the chain row rolls back, the proof is incomplete. If the chain row commits and the document row rolls back, the proof references a thing that does not exist. insertChainEntry() is designed to run inside the caller's transaction.

The core logic is direct:

const allocRes = await tx.execute(
  sql`SELECT fn_allocate_chain_index(${entityId}::uuid)::text AS idx`,
);
const chainIndex = BigInt(allocRes.rows[0]!.idx);

let previousHash: string | null = null;
if (chainIndex > 1n) {
  const priorRes = await tx.execute(
    sql`SELECT payload_hash FROM document_hash_chain
         WHERE entity_id = ${entityId}::uuid
           AND chain_index = ${(chainIndex - 1n).toString()}::bigint`,
  );
  previousHash = priorRes.rows[0]!.payload_hash;
}

const chainLinkHash = computeChainLinkHash({
  content_hash: contentHash,
  previous_hash: previousHash,
  chain_index: chainIndex,
  entity_id: entityId,
});

Enter fullscreen mode Exit fullscreen mode

There are two design choices hidden in that snippet.

The index comes from fn_allocate_chain_index(entity_id), not a PostgreSQL sequence. The same rollback problem that makes sequences wrong for legal document numbers also applies to chain indices. A verifier expects the chain to be contiguous. If index 19 is missing because a transaction rolled back after a sequence increment, the verifier cannot know whether that is harmless or tampering.

The link hash includes entity_id. That prevents a row from one entity being copied into another entity's chain without detection. Klevar has one group boundary, but the legal proof is per entity. FZE, LLC, and Ltd cannot share a chain just because the service is single-tenant.

The verifier is a walker, not a database query. It receives rows sorted by chain_index, checks ordering, checks the genesis row, checks each previous_hash, recomputes each link hash, and returns the first mismatch. It also reports intentionally broken indices. That last category is important because some retention or force-purge action may be documented rather than hidden. A broken chain can be honest if the break is recorded and visible.

What surprised me was the dependency on canonical JSON. Hashing JavaScript objects directly is a trap because key order and serialization details can drift. The service pins canonicalize@2.0.0 and runs an RFC 8785 boot assertion before Fastify binds a port. If canonicalization changes, the server refuses to start. That is not paranoia. It is the cost of using hashes as legal proof.

The hash chain also changed how I think about events. events_emitted is the integration outbox for Hub and Webhook Engine fanout. It is operational. document_hash_chain is proof. Those two surfaces overlap, but they are not the same thing. A notification can be retried, delayed, or dropped without changing the legal document. A chain append cannot be treated that way.

The biggest tradeoff is operational weight. A chain gives you another invariant to maintain, another verifier to run, another repair story to document, and another failure mode to alert on. The alternative is worse: a document archive that can produce files but cannot prove nobody altered the history.

For this system, the archive without the chain would be storage. The chain turns it into evidence.