agentcomply / tree / src/ledger-do.js ยท raw (this view has old GitHub links rewritten for the mirror; raw is byte-exact)
// SQLite-backed Durable Object ledger (free plan). Appends are serialized by the DO; a stale prev_hash is rejected.
import { DurableObject } from 'cloudflare:workers';
export class ReceiptLedger extends DurableObject {
  constructor(ctx, env) {
    super(ctx, env);
    this.sql = ctx.storage.sql;
    this.sql.exec('CREATE TABLE IF NOT EXISTS receipts (seq INTEGER PRIMARY KEY, hash TEXT NOT NULL, prev_hash TEXT, receipt TEXT NOT NULL)');
  }
  head() {
    const r = this.sql.exec('SELECT seq, hash FROM receipts ORDER BY seq DESC LIMIT 1').toArray()[0];
    return r ? { seq: r.seq, hash: r.hash } : null;
  }
  append(receiptJson) {
    const r = JSON.parse(receiptJson);
    const h = this.head() || { seq: 0, hash: null };
    if (r.chain.seq !== h.seq + 1 || (r.chain.prev_hash ?? null) !== (h.hash ?? null)) return false;
    this.sql.exec('INSERT INTO receipts (seq, hash, prev_hash, receipt) VALUES (?, ?, ?, ?)', r.chain.seq, r.integrity.hash, r.chain.prev_hash, receiptJson);
    return true;
  }
  list(limit = 500) {
    return this.sql.exec('SELECT receipt FROM receipts ORDER BY seq DESC LIMIT ?', limit).toArray().map((x) => JSON.parse(x.receipt)).reverse();
  }
  get(seq) {
    const r = this.sql.exec('SELECT receipt FROM receipts WHERE seq = ?', seq).toArray()[0];
    return r ? JSON.parse(r.receipt) : null;
  }
}

agentgate-source: code mirror on Cloudflare Pages. All repos