Skip to main content
Introducing packages.sweber.dev
Documentation menuLedger

Ledger

Tamper-evident storage of declarations and receipts, with evidence sheets.

If a consumer says they withdrew in time and you say they didn't, you need records that you can show were not changed afterwards. inverse-ledger writes every declaration and every receipt as an entry in a hash chain: each entry contains the SHA-256 hash of the previous one, so changing, deleting or reordering any entry breaks the chain.

import { createInverseHandler } from "@sweberdev/inverse";
import { createLedger, fileStore, withLedger } from "@weber-development/inverse-ledger";

const ledger = createLedger({ store: fileStore("./data/inverse.jsonl") });

export const POST = createInverseHandler(
  withLedger(ledger, {
    company,
    onDeclaration: (record) => db.declaration.create({ data: record }), // optional, runs after the ledger
    sendReceipt: (receipt) => mailer.send(receipt),
  }),
);

withLedger appends a declaration entry before your own onDeclaration, and a receipt entry (or receipt-failed with the error) after sendReceipt.

Stores

  • fileStore(path): one JSON line per entry. Good for a VPS or a mounted volume.
  • postgresStore({ query }): PostgreSQL, Neon, Supabase, PGlite. The right choice on serverless platforms such as Vercel, which have no persistent disk.
  • sqliteStore({ query }): SQLite through node:sqlite, better-sqlite3 or bun:sqlite.
  • memoryStore(): for tests.
  • Your own: implement { read(): Promise<LedgerEntry[]>; append(entry): Promise<void>; replace(entries): Promise<void> }, optionally last() and find(ref), for S3 or anything else.

PostgreSQL and SQLite

The SQL stores take a query(sql, params) function that returns rows, so they work with any driver and add no dependency. Two adapters cover the common drivers:

import { createLedger, pgQuery, postgresStore } from "@weber-development/inverse-ledger";
import pg from "pg";

const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
const ledger = createLedger({ store: postgresStore({ query: pgQuery(pool) }) });
import { createLedger, sqliteQuery, sqliteStore } from "@weber-development/inverse-ledger";
import { DatabaseSync } from "node:sqlite"; // or: new Database(path) from better-sqlite3

const ledger = createLedger({
  store: sqliteStore({ query: sqliteQuery(new DatabaseSync("./data/inverse.db")) }),
});

pgQuery accepts anything with query(text, values) → { rows } (pg Pool or Client, @neondatabase/serverless, PGlite); sqliteQuery anything with a synchronous prepare(sql). For other drivers write the function yourself, e.g. for postgres.js: query: (text, params) => sql.unsafe(text, params).

Option
query(sql, params) => rows (sync or async)
tabletable name, optionally with schema; default inverse_ledger
migratecreate the table and an index on ref on first use; default true. With false, run await store.migrate() or the SQL in store.schema once yourself

The table has one row per entry (seq primary key, at, type, ref, payload as JSON text, payload_hash, prev, hash):

  • Append-only. The store only ever inserts rows. replace, which the ledger uses for erasure, may only clear payloads; any other change is refused. For extra safety, give the application's database user only SELECT, INSERT and UPDATE (payload) on the table.
  • No forks. seq is the primary key. If two server instances append at the same moment, one insert fails and the declaration request returns an error the consumer can retry; the chain stays linear.
  • Fast appends. The store reads the last entry and the entries of one declaration with indexed queries instead of the whole chain.

Verification, evidence sheets, redact and retain work exactly as with the file store. The inverse-ledger CLI reads JSON Lines files; for a database, call ledger.verify(), ledger.evidence(ref) and ledger.retain() from a script or a scheduled job.

Verify

const result = await ledger.verify();
// { ok: true, entries: 1342, head: "9f2c…" }
// { ok: false, entries: 1342, brokenAt: 718, reason: "hash mismatch" }
npx inverse-ledger verify ./data/inverse.jsonl

Publish or e-mail the head hash to yourself from time to time (the CLI prints it). Anyone who rewrites the whole chain then cannot match a head you recorded earlier.

Evidence sheet

const sheet = await ledger.evidence("W-7K3QX9PD");
sheet.text; // human-readable: declaration, time of receipt, receipt sent at, hashes, chain position
sheet.json; // the same as data
npx inverse-ledger evidence ./data/inverse.jsonl W-7K3QX9PD > W-7K3QX9PD.txt
npx inverse-ledger export ./data/inverse.jsonl --from 2026-06-19 > declarations.csv

Erasure

Personal data must not be kept longer than needed. ledger.redact(id, { reason }) removes the personal data of a declaration and its receipts but keeps each entry's payload hash, so the chain still verifies and you can show that a declaration existed and when.

await ledger.redact("W-7K3QX9PD", { reason: "retention period ended" });

Retention

Set a retention period once and run it on a schedule instead of redacting by hand. retain redacts every declaration received more than days days ago, together with its receipts, and logs one redaction entry per declaration:

const { refs, entries } = await ledger.retain({ days: 3 * 365 });
await ledger.retain({ days: 3 * 365, dryRun: true }); // only list what would go
npx inverse-ledger retain ./data/inverse.jsonl --days 1095 --dry-run
npx inverse-ledger retain ./data/inverse.jsonl --days 1095

How long you keep declarations is your decision; three years (the regular limitation period, § 195 BGB) is a common choice. The chain still verifies after a retention run.

Time stamp anchors

A hash chain proves order, but whoever holds the file could rewrite all of it. Anchor the head with an RFC 3161 time stamp authority (TSA): it signs the head hash together with the time, so you can later prove the chain up to that point existed then and was not rewritten.

npx inverse-ledger anchor ./data/inverse.jsonl --tsa https://freetsa.org/tsr
npx inverse-ledger anchors ./data/inverse.jsonl
import { anchorHead, listAnchors } from "@weber-development/inverse-ledger";

await anchorHead(ledger, { tsa: "https://freetsa.org/tsr" });

The TSA answer is stored as a ledger entry (note, ref anchor, field response in base64). Chain verification covers it like any entry; anchors also checks that each anchor still matches the entry before it. To verify the TSA signature, decode the response to a .tsr file, write the request digest and run openssl ts -verify -in response.tsr -digest <head> -sha256 -CAfile tsa-ca.pem. Which TSA you use, and whether its time stamps are qualified under eIDAS, is your decision.

Evidence dossier

dossier collects what a lawyer or authority asks for in one document: chain status, head hash, every declaration in a date range (with whether personal data was already erased), the anchors, and a SHA-256 of the manifest.

npx inverse-ledger dossier ./data/inverse.jsonl --from 2026-06-19 --to 2026-12-31 --lang de --company "Example AG" --html dossier.html
npx inverse-ledger dossier ./data/inverse.jsonl --kind cancellation   # JSON manifest

buildDossier(ledger, { from, to, kind, locale, company }) returns { html, manifest, manifestHash }. The HTML is self-contained and printable; all values are escaped.

CLI on a database

The CLI reads the ledger from wherever you keep it. Pass a SQLite file or a PostgreSQL URL instead of the JSON Lines file; every command works the same.

npx inverse-ledger verify ./data/inverse.db                       # SQLite, Node 22.5 or newer
npx inverse-ledger dossier postgres://user@host/db --html d.html  # PostgreSQL, needs: pnpm add pg
npx inverse-ledger evidence ./data/inverse.db W-7K3QX9PD --table my_ledger

A target ending in .db, .sqlite or .sqlite3, or starting with sqlite:, is SQLite; postgres:// and postgresql:// are PostgreSQL; anything else is a JSON Lines file. --table sets the table name (default inverse_ledger).

Dossier as PDF

--pdf writes the dossier as an A4 PDF next to or instead of the HTML. In code: dossierPdf(await buildDossier(ledger), { locale: "de", company }) returns the bytes. The PDF is plain text in Helvetica (Latin-1 characters; others become ?) and contains the same sections as the HTML.

npx inverse-ledger dossier ./data/inverse.db --from 2026-06-19 --pdf dossier.pdf --lang de

Anchors on a schedule

Run anchor from a daily cron job with --if-due-hours. It anchors only if there are entries newer than the last anchor and the last anchor is at least that many hours old; otherwise it prints "nothing to anchor yet" and exits with 0.

npx inverse-ledger anchor ./data/inverse.db --tsa https://freetsa.org/tsr --if-due-hours 24

In code: anchorIfDue(ledger, { tsa, everyHours: 24 }) returns the new entry or null.

One ledger per client

An agency that runs Inverse for many shops keeps each shop in its own hash chain, so a client can be verified, exported or erased on its own.

import { createTenantLedgers, postgresStore, tenantTable, pgQuery } from "@weber-development/inverse-ledger";

const tenants = createTenantLedgers({
  storeFor: (tenant) => postgresStore({ query: pgQuery(pool), table: tenantTable("inverse", tenant) }),
});
await tenants.get("shop-a").append("declaration", record.id, record);
const report = await tenants.verifyAll(); // [{ tenant, ok, entries, head }]

Tenant ids may contain letters, digits, _ and -; anything else is refused before it reaches a table name.

Ending a subscription at Stripe, Paddle or Lemon Squeezy

A cancellation that your customer sent through Inverse still has to reach the payment provider. cancelSubscription ends the subscription there. It changes real subscriptions, so run it after a person has looked at the declaration, and log the result in the ledger.

import { cancelSubscription } from "@weber-development/inverse-ledger";

const result = await cancelSubscription({
  provider: "stripe", // or "paddle" or "lemonsqueezy"
  apiKey: process.env.STRIPE_SECRET_KEY,
  subscriptionId: record.data.contractRef, // the id your form collects: "sub_..."
  at: "period-end", // "now" ends it immediately; Stripe also takes endsOn: "2026-11-05"
});
await ledger.append("note", record.id, result); // never contains the key

Stripe: at period end sets cancel_at_period_end, a date sets cancel_at, "now" deletes the subscription. Paddle: effective_from is next_billing_period or immediately; sandbox: true uses the sandbox API. The calls follow the providers' documented endpoints; try them with test keys and a test subscription first, and keep to what your terms promise the customer about the end date. Lemon Squeezy: DELETE /v1/subscriptions/{id}, which ends the subscription at the end of the billing period; its API has no immediate or dated cancellation, so at: "now" and endsOn throw instead of silently doing something else. None of the three calls has been run against a live provider account by the authors: they are tested against recorded requests only. HTTP errors do not throw: check result.ok.

Cases: status, refund, history

Every declaration is a case. setCaseStatus writes each change to the ledger as a case entry, so the history is part of the evidence chain and shows up in the evidence sheet.

import { getCase, listCases, setCaseStatus } from "@weber-development/inverse-ledger";

await setCaseStatus(ledger, "W-7K3QX9PD", "processing", { note: "goods received", by: "ann@example.com" });
await setCaseStatus(ledger, "W-7K3QX9PD", "refunded", { amount: "49.90", currency: "EUR" });

const open = await listCases(ledger, { status: "open", kind: "withdrawal" });
open[0]?.refundDue; // "YYYY-MM-DD": 14 days after receipt
open[0]?.overdue; // true once the date has passed and the case is still open or processing

Statuses are open, processing, refunded, rejected and closed. Only forward moves are allowed (a refunded case can only be closed), and refunded needs an amount, so the evidence shows what was paid back. After an erasure the case counts as closed.

npx inverse-ledger cases ./data/inverse.db --status open
npx inverse-ledger case ./data/inverse.db W-7K3QX9PD --set refunded --amount 49.90 --currency EUR

The case entries record what you tell the ledger; Inverse does not move money. The refund period of 14 days follows § 357 BGB and Article 13 of the directive; pass refundDays if your counsel says otherwise for a jurisdiction.

Storage format and migrate (2.0)

From 2.0 every entry carries v: 2, and SQL tables have a format column. The field is metadata and not part of the hash, so chains written by 1.x verify unchanged and nothing is rewritten.

npx inverse-ledger migrate ./data/inverse.db

The command verifies the chain, adds the column to an old table, verifies again and fails if the head hash differs. Stores open the table with migrate: true by default and do the same on first use; if you turned it off, run the statements in store.upgrade once yourself. verify prints how many entries have each format.