// SQLite-backed Durable Object ledger (from AgentComply). 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)');
this.sql.exec('CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT)');
this.sql.exec('CREATE TABLE IF NOT EXISTS scan_cache (k TEXT PRIMARY KEY, v TEXT NOT NULL, at INTEGER NOT NULL)');
}
// InjectScan results cached by sha256(text), so the free tier (10 requests/min per IP) is respected
cacheGet(k) { const r = this.sql.exec('SELECT v FROM scan_cache WHERE k = ?', k).toArray()[0]; return r ? JSON.parse(r.v) : null; }
cachePut(k, v) { this.sql.exec('INSERT OR REPLACE INTO scan_cache (k, v, at) VALUES (?, ?, ?)', k, JSON.stringify(v), Date.now()); return true; }
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;
}
// run throttle: returns true and records the time if at least `ms` passed since the last run
claimRun(ms) {
const r = this.sql.exec("SELECT v FROM meta WHERE k = 'last_run'").toArray()[0];
const now = Date.now();
if (r && now - Number(r.v) < ms) return false;
this.sql.exec("INSERT OR REPLACE INTO meta (k, v) VALUES ('last_run', ?)", String(now));
return true;
}
}
agentgate-source: code mirror on Cloudflare Pages. All repos