Open server: the project Worker, Durable Object and Artifacts (issue 17) Version 150 of shared· speed· Oct 13 (2026-10-13 16:05 UTC) · Not checked
Version 149 · Files at version 150
25 files, 3455 lines added, 4 removed.
--- a/.absoignore
+++ b/.absoignore
@@ -6,7 +6,9 @@
6 6 # Each session's own Claude Code state 9 − # Local config and secrets
9 + # Local config and secrets (the open server's server/.dev.vars and server/.wrangler/ are named too) --- a/biome.json
+++ b/biome.json
@@ -6,6 +6,7 @@
Binary file package-lock.json changed: b10521cd9bad -> 2e1381de46c1
--- a/package.json
+++ b/package.json
@@ -9,15 +9,17 @@
12 − "test": "node --import ./client/test/setup.ts --test \"src/**/*.test.ts\" \"worker/project/**/*.test.ts\" \"client/test/**/*.test.ts\" \"scripts/**/*.test.ts\"",
12 + "test": "node --import ./client/test/setup.ts --test \"src/**/*.test.ts\" \"worker/project/**/*.test.ts\" \"client/test/**/*.test.ts\" \"scripts/**/*.test.ts\" \"server/test/**/*.test.ts\"", 13 13 "typecheck": "tsc --noEmit -p tsconfig.json", 14 − "check": "npm run typecheck && npm test",
14 + "check": "npm run typecheck && npm run typecheck:server && npm test", 15 15 "check:changed": "node scripts/check-changed.mjs", 16 16 "format": "biome check --write .", 17 − "lint": "biome ci ."
17 + "lint": "biome ci .", 18 + "typecheck:server": "tsc --noEmit -p server/tsconfig.json" 19 20 "devDependencies": { 20 21 "@biomejs/biome": "2.5.15", 22 + "@cloudflare/workers-types": "^5.20261013.1", 21 23 "@types/node": "^24.19.1", 22 24 "typescript": "^5.9.3" Binary file server/package-lock.json changed: none -> f5cebad6e233
--- /dev/null
+++ b/server/package.json
@@ -0,0 +1,22 @@
2 + "name": "abso-server", 6 + "description": "abso's open server: one Worker with a Durable Object per project, on your own Cloudflare account.", 9 + "dev": "wrangler dev --local", 10 + "deploy": "wrangler deploy", 11 + "typecheck": "tsc --noEmit -p tsconfig.json" 14 + "isomorphic-git": "^1.43.0" 17 + "@cloudflare/workers-types": "^5.20261001.1", 18 + "@types/node": "^24.19.1", 19 + "typescript": "^5.9.3", 20 + "wrangler": "^4.147.0" --- /dev/null
+++ b/server/src/blobs.ts
@@ -0,0 +1,237 @@
1 + // Binary files' bytes (#27), content-addressed by SHA-256, kept in the 2 + // project's own Durable Object SQLite: 1 MB rows, so a blob is never larger 3 + // than a row allows, and hasBlob is a synchronous lookup the engine can call. 4 + // Uploads stream in (a Durable Object RPC message stops at 32 MiB) and are 5 + // hashed as they arrive; a blob whose bytes don't match its name isn't kept. 6 + import { createHash } from "node:crypto"; 7 + import type { SqliteStorage } from "./engine-project.ts"; 9 + /** Per file. The push out to Artifacts holds a tree in memory, and a Durable Object has 128 MB. */ 10 + export const BLOB_MAX = 20 * 1024 * 1024; 11 + const PART = 1024 * 1024; 12 + const SHA = /^[0-9a-f]{64}$/; 14 + "CREATE TABLE blobs (sha TEXT NOT NULL, part INTEGER NOT NULL, data BLOB NOT NULL, PRIMARY KEY (sha, part))"; 16 + const normalizedSchema = (sql: string) => sql.replace(/\s+/g, " ").trim().toUpperCase(); 19 + | { status: 200; body: { sha256: string; size: number; stored: boolean } } 20 + | { status: 400 | 413; body: { error: string } }; 22 + export class BlobStore { 23 + private storage: SqliteStorage; 25 + constructor(storage: SqliteStorage) { 26 + this.storage = storage; 29 + /** Reads must not create storage, including when a cold object has no blobs. */ 30 + private hasSchema(): boolean { 31 + const rows = this.storage.sql.exec("SELECT type, sql FROM sqlite_master WHERE name = 'blobs'").toArray() as { 35 + if (rows.length === 0) return false; 38 + rows[0]?.type !== "table" || 39 + typeof rows[0].sql !== "string" || 40 + normalizedSchema(rows[0].sql) !== normalizedSchema(SCHEMA) 42 + throw new Error("unsupported blob storage schema"); 46 + /** Only mutation paths may initialize the exact supported table. Never repair a mismatch. */ 47 + private ensureSchema(): void { 48 + if (!this.hasSchema()) this.storage.sql.exec(SCHEMA); 51 + /** Blobs in sha order after `after`, with their sizes (temporary uploads left out). */ 52 + list(after: string, limit: number): { blobs: { sha: string; size: number }[]; next: string | null } { 53 + if (!this.hasSchema()) return { blobs: [], next: null }; 54 + const rows = this.storage.sql 56 + "SELECT sha, SUM(LENGTH(data)) AS size FROM blobs WHERE sha > ? AND sha NOT LIKE 'tmp-%' GROUP BY sha ORDER BY sha LIMIT ?", 60 + .toArray() as { sha: string; size: number }[]; 61 + const more = rows.length > limit; 62 + const blobs = rows.slice(0, limit); 63 + return { blobs, next: more ? blobs.at(-1)!.sha : null }; 66 + has(sha: string): boolean { 70 + this.storage.sql.exec("SELECT 1 FROM blobs WHERE sha = ? LIMIT 1", sha).toArray().length > 0 74 + /** Every byte, for the push out. Blobs are at most BLOB_MAX. */ 75 + read(sha: string): Uint8Array | null { 76 + if (!this.hasSchema()) return null; 77 + const rows = this.storage.sql.exec("SELECT data FROM blobs WHERE sha = ? ORDER BY part", sha).toArray() as { 80 + if (rows.length === 0) return null; 81 + const out = new Uint8Array(rows.reduce((n, r) => n + r.data.byteLength, 0)); 83 + for (const r of rows) { 84 + out.set(new Uint8Array(r.data), at); 85 + at += r.data.byteLength; 90 + /** The bytes as a stream, one row at a time, or null. */ 91 + stream(sha: string): ReadableStream<Uint8Array> | null { 92 + if (!this.has(sha)) return null; 94 + this.storage.sql.exec("SELECT part FROM blobs WHERE sha = ? ORDER BY part", sha).toArray() as { part: number }[] 95 + ).map((r) => r.part); 97 + return new ReadableStream<Uint8Array>({ 99 + if (i >= parts.length) return c.close(); 100 + const [row] = this.storage.sql 101 + .exec("SELECT data FROM blobs WHERE sha = ? AND part = ?", sha, parts[i++]!) 102 + .toArray() as { data: ArrayBuffer }[]; 103 + c.enqueue(new Uint8Array(row!.data)); 109 + * A whole file's text (#46), stored as UTF-8 under its SHA-256. Synchronous, 110 + * so the engine can call it while it records. 112 + putText(text: string): string { 113 + const bytes = new TextEncoder().encode(text); 114 + const sha = createHash("sha256").update(bytes).digest("hex"); 115 + if (!this.has(sha)) this.write(sha, bytes, 0); 119 + /** A whole file's text back, or null. */ 120 + textOf(sha: string): string | null { 121 + const bytes = this.read(sha); 122 + return bytes ? new TextDecoder().decode(bytes) : null; 125 + /** Stores bytes already in memory (plain-git intake), under their own hash. */ 126 + async putBytes(bytes: Uint8Array): Promise<string> { 127 + const sha = hex(await crypto.subtle.digest("SHA-256", bytes)); 128 + if (!this.has(sha)) this.write(sha, bytes, 0); 132 + /** Streams an upload in, checking its size and that its SHA-256 is `sha`. */ 133 + /** `max` lowers BLOB_MAX for this put (a capped project's file cap, abso issue 249). */ 134 + async put(sha: string, body: ReadableStream<Uint8Array>, max: number = BLOB_MAX): Promise<PutBlob> { 135 + if (!SHA.test(sha)) return { status: 400, body: { error: "a blob's name is its SHA-256 in lowercase hex" } }; 136 + if (this.has(sha)) { 137 + await body.cancel().catch(() => {}); 138 + return { status: 200, body: { sha256: sha, size: this.size(sha), stored: false } }; 140 + const temp = `tmp-${crypto.randomUUID()}`; 141 + const digest = new crypto.DigestStream("SHA-256"); 142 + const hashing = digest.getWriter(); 145 + let pending: Uint8Array[] = []; 146 + let pendingSize = 0; 147 + const flush = () => { 148 + if (pendingSize === 0) return; 149 + part = this.write(temp, concat(pending, pendingSize), part); 154 + for await (const chunk of body) { 155 + size += chunk.byteLength; 158 + return { status: 413, body: { error: `blobs are at most ${max / 1024 / 1024} MB` } }; 160 + await hashing.write(chunk); 161 + pending.push(chunk); 162 + pendingSize += chunk.byteLength; 163 + if (pendingSize >= PART) flush(); 166 + if (part === 0) part = this.write(temp, new Uint8Array(), 0); // an empty file is a blob too 167 + await hashing.close(); 168 + const got = hex(await digest.digest); 171 + return { status: 400, body: { error: `the bytes hash to ${got}, not ${sha}` } }; 173 + // Another upload of the same bytes may have finished meanwhile. 174 + if (this.has(sha)) this.drop(temp); 176 + this.ensureSchema(); 177 + this.storage.sql.exec("UPDATE blobs SET sha = ? WHERE sha = ?", sha, temp); 179 + return { status: 200, body: { sha256: sha, size, stored: true } }; 186 + /** Every blob's bytes together, referenced or not (a capped project's total, 249). Uploads in progress don't count. */ 188 + if (!this.hasSchema()) return 0; 189 + const [row] = this.storage.sql 190 + .exec("SELECT COALESCE(SUM(LENGTH(data)), 0) AS n FROM blobs WHERE sha NOT LIKE 'tmp-%'") 191 + .toArray() as { n: number }[]; 195 + /** A blob's size in bytes: 0 when the project doesn't hold it. */ 196 + size(sha: string): number { 197 + if (!this.hasSchema()) return 0; 198 + const [row] = this.storage.sql 199 + .exec("SELECT COALESCE(SUM(LENGTH(data)), 0) AS n FROM blobs WHERE sha = ?", sha) 200 + .toArray() as { n: number }[]; 204 + /** Writes bytes as rows of at most PART from part `first` on; answers the next part. An empty blob is one empty row. */ 205 + private write(sha: string, bytes: Uint8Array, first: number): number { 206 + this.ensureSchema(); 208 + for (let at = 0; at < bytes.byteLength || (at === 0 && part === 0); at += PART) { 209 + this.storage.sql.exec( 210 + "INSERT INTO blobs (sha, part, data) VALUES (?, ?, ?)", 213 + bytes.slice(at, at + PART), 215 + if (bytes.byteLength === 0) break; 220 + private drop(sha: string) { 221 + this.ensureSchema(); 222 + this.storage.sql.exec("DELETE FROM blobs WHERE sha = ?", sha); 226 + function concat(chunks: Uint8Array[], size: number): Uint8Array { 227 + if (chunks.length === 1) return chunks[0]!; 228 + const out = new Uint8Array(size); 230 + for (const c of chunks) { 237 + const hex = (buf: ArrayBuffer) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join(""); --- /dev/null
+++ b/server/src/engine-project.ts
@@ -0,0 +1,724 @@
1 + // The engine's Project (worker/project/project.ts) behind the server's calls, with its append-only log kept in the 2 + // Durable Object's SQLite. An entry longer than one row allows (init holds every starting file; SQLite rows stop at 3 + // 2 MB) is split across rows and joined on load. Ported from the platform's worker/src/engine-project.ts; the 4 + // writer-adoption and R2 version parts are left out. 6 + import { blame, folderBlame, why } from "../../worker/project/blame.ts"; 7 + import { feedEvents } from "../../worker/project/feed.ts"; 8 + import { type Entry, type ProjectStore as LogStore, MemoryStore, Project } from "../../worker/project/project.ts"; 9 + import type { EditBody, ProjectCalls, ProjectHistory } from "../../worker/project/project-api.ts"; 10 + import { where } from "../../worker/project/where.ts"; 12 + /** The parts of a Durable Object's storage the log and blob store use, declared structurally so tests can stand in. */ 13 + export interface SqliteStorage { 14 + sql: { exec(query: string, ...bindings: unknown[]): { toArray(): unknown[] } }; 15 + transactionSync<T>(fn: () => T): T; 18 + // Characters per row. SQLite's 2 MB cap is in bytes, and a character is at 19 + // most 3 bytes of UTF-8 (an emoji is 2 characters and 4 bytes), so 600,000 stays under it. 22 + /** An entry's JSON in rows of at most PART characters, never cutting an emoji's two halves apart. */ 23 + export function logParts(text: string): string[] { 24 + const parts: string[] = []; 27 + let end = Math.min(at + PART, text.length); 28 + const c = text.charCodeAt(end - 1); 29 + if (end < text.length && c >= 0xd800 && c <= 0xdbff) end--; 30 + parts.push(text.slice(at, end)); 32 + } while (at < text.length); 36 + /** The lines an entry's atoms write: what a loaded project's size grows with (#46, #56). */ 37 + function linesIn(entry: Entry): number { 40 + (entry as { atom?: { inserts?: { lines: unknown[] }[] } }).atom, 41 + (entry as { tie?: { inserts?: { lines: unknown[] }[] } }).tie, 43 + for (const r of a?.inserts ?? []) n += r.lines.length; 48 + /** The version of shared an entry makes, or undefined (abso issue 78: the access check reads it without loading). */ 49 + function sharedVersionOf(entry: Entry): number | undefined { 50 + if (entry.type === "init") return 0; 51 + if (entry.type === "land" || entry.type === "drop") return entry.version; 52 + if (entry.type === "publish" && (entry.space ?? "") === "") return entry.version; 56 + /** Who made that version of shared, and when. Init is not a publish (abso issue 86). */ 57 + function lastPublishOf(entry: Entry): { agent: string; time: number } | undefined { 58 + if (entry.type === "land" || entry.type === "drop") return { agent: entry.agent, time: entry.time }; 59 + if (entry.type === "publish" && (entry.space ?? "") === "") return { agent: entry.agent, time: entry.time }; 63 + /** An entry's claim keys and deletes (#46): with entries and lines, what the load guard estimates memory by. */ 64 + function keysIn(entry: Entry): number { 67 + (entry as { atom?: Partial<Record<"writes" | "reads" | "holds" | "deletes", unknown[]>> }).atom, 68 + (entry as { tie?: Partial<Record<"writes" | "reads" | "holds" | "deletes", unknown[]>> }).tie, 70 + if (a) n += (a.writes?.length ?? 0) + (a.reads?.length ?? 0) + (a.holds?.length ?? 0) + (a.deletes?.length ?? 0); 75 + export class SqliteLog implements LogStore { 76 + private storage: SqliteStorage; 77 + private next: number; 79 + constructor(storage: SqliteStorage) { 80 + this.storage = storage; 82 + "CREATE TABLE IF NOT EXISTS log (seq INTEGER, part INTEGER, text TEXT NOT NULL, PRIMARY KEY (seq, part))", 85 + "CREATE TABLE IF NOT EXISTS shapes (space TEXT NOT NULL, version INTEGER NOT NULL, value TEXT NOT NULL, PRIMARY KEY (space, version))", 87 + storage.sql.exec("CREATE TABLE IF NOT EXISTS counts (name TEXT PRIMARY KEY, value INTEGER NOT NULL)"); 88 + storage.sql.exec("CREATE TABLE IF NOT EXISTS marks (name TEXT PRIMARY KEY, value TEXT NOT NULL)"); 89 + const rows = storage.sql.exec("SELECT COALESCE(MAX(seq), -1) AS last FROM log").toArray() as { last: number }[]; 90 + this.next = (rows[0]?.last ?? -1) + 1; 93 + /** The seq the next entry would take. A copy's next page must start here. */ 98 + /** Monotonic cache invalidation epoch for every canonical log mutation. */ 99 + generation(): number { 100 + const rows = this.storage.sql.exec("SELECT value FROM marks WHERE name = ?", "generation").toArray() as { 103 + const generation = Number(rows[0]?.value ?? 0); 104 + if (!Number.isSafeInteger(generation) || generation < 0) throw new Error("canonical log generation is invalid"); 109 + * Lines ever recorded (#46, #56): what loading the project costs grows with 110 + * this, not with the log's size, so a guard can read it without loading. 111 + * Kept with each append; undefined for a log written before the count, 112 + * until it next loads. 114 + lineCount(): number | undefined { 115 + const rows = this.storage.sql.exec("SELECT value FROM counts WHERE name = 'lines'").toArray() as { 118 + return rows[0]?.value; 122 + * The newest version of shared, without loading the project (abso issue 78: the website's access check asked 123 + * every project's engine for it). Kept with each append; a log from before the count is read once by streaming. 125 + sharedVersion(): number { 126 + const rows = this.storage.sql.exec("SELECT value FROM counts WHERE name = 'shared'").toArray() as { 129 + if (rows[0] !== undefined) return rows[0].value; 131 + for (const e of this.#entries()) version = sharedVersionOf(e) ?? version; 133 + this.storage.sql.exec("INSERT OR REPLACE INTO counts (name, value) VALUES ('shared', ?)", version); 138 + * Who published shared's newest version, and when, without loading the project (abso issue 86). 139 + * Null when shared has no publish yet. A log from before the mark is read once by streaming. 141 + lastPublish(): { agent: string; time: number } | null { 142 + const rows = this.storage.sql.exec("SELECT value FROM marks WHERE name = ?", "last").toArray() as { 145 + if (rows[0] !== undefined) return JSON.parse(rows[0].value) as { agent: string; time: number }; 146 + let last: { agent: string; time: number } | null = null; 147 + for (const e of this.#entries()) { 148 + const found = lastPublishOf(e); 149 + if (found) last = found; 152 + this.storage.sql.exec("INSERT OR REPLACE INTO marks (name, value) VALUES (?, ?)", "last", JSON.stringify(last)); 157 + * How big the log is, without loading the project or scanning it twice (ask 160). 158 + * Entries are the next seq. Chars are kept like lines; a log from before the 159 + * count is summed once, then kept. GET /projects' 2-second wait needs this 160 + * to stay a storage read: SUM(LENGTH(text)) over abso's log misses it. 162 + logSize(): { chars: number; entries: number } { 163 + const entries = this.next; 164 + const rows = this.storage.sql.exec("SELECT value FROM counts WHERE name = 'chars'").toArray() as { 167 + if (rows[0] !== undefined) return { chars: rows[0].value, entries }; 168 + if (entries === 0) return { chars: 0, entries: 0 }; 169 + const summed = this.storage.sql.exec("SELECT COALESCE(SUM(LENGTH(text)), 0) AS chars FROM log").toArray()[0] as 172 + const chars = summed?.chars ?? 0; 173 + this.storage.sql.exec("INSERT OR REPLACE INTO counts (name, value) VALUES ('chars', ?)", chars); 174 + return { chars, entries }; 177 + /** Claim keys and deletes ever recorded (#46), kept like the line count; undefined before they were counted. */ 178 + keyCount(): number | undefined { 179 + const rows = this.storage.sql.exec("SELECT value FROM counts WHERE name = 'keys'").toArray() as { value: number }[]; 180 + return rows[0]?.value; 184 + * The lines and keys ever recorded, counting a log from before either count without loading the project 185 + * (#46): one entry parsed at a time, so a log the load guard would refuse can still be measured. Kept once counted. 187 + countSizes(): { lines: number; keys: number } { 188 + const lines = this.lineCount(); 189 + const keys = this.keyCount(); 190 + if (lines !== undefined && keys !== undefined) return { lines, keys }; 193 + for (const e of this.#entries()) { 197 + this.#keep(lines === undefined ? l : undefined, keys === undefined ? k : undefined); 198 + return { lines: lines ?? l, keys: keys ?? k }; 201 + /** Stores the counts given. */ 202 + #keep(lines: number | undefined, keys: number | undefined): void { 203 + if (lines !== undefined) 204 + this.storage.sql.exec("INSERT OR REPLACE INTO counts (name, value) VALUES ('lines', ?)", lines); 205 + if (keys !== undefined) 206 + this.storage.sql.exec("INSERT OR REPLACE INTO counts (name, value) VALUES ('keys', ?)", keys); 209 + /** Every stored entry, in order. Rows are read one at a time, so loading never holds the whole log's text at once (#43). */ 210 + *entries(): Iterable<Entry> { 211 + // A log from before the counts: counted as it loads, and kept. 212 + const countLines = this.lineCount() === undefined; 213 + const countKeys = this.keyCount() === undefined; 216 + for (const e of this.#entries()) { 217 + if (countLines) lines += linesIn(e); 218 + if (countKeys) keys += keysIn(e); 221 + this.#keep(countLines ? lines : undefined, countKeys ? keys : undefined); 224 + *#entries(from = 0): Iterable<Entry> { 225 + // A Workers cursor is iterable; a test's stand-in may only have toArray. 226 + const cursor = this.storage.sql.exec("SELECT seq, text FROM log WHERE seq >= ? ORDER BY seq, part", from) as { 227 + toArray(): unknown[]; 228 + } & Partial<Iterable<unknown>>; 229 + const rows = (cursor[Symbol.iterator] ? cursor : cursor.toArray()) as Iterable<{ seq: number; text: string }>; 232 + for (const r of rows) { 233 + if (r.seq !== seq && seq >= 0) yield JSON.parse(text) as Entry; 234 + if (r.seq !== seq) text = ""; 238 + if (seq >= 0) yield JSON.parse(text) as Entry; 242 + * For backups (#29): the entries from seq `from` on as their stored JSON 243 + * text (not parsed, so an export holds the project up as little as it 244 + * can), at most `limit` of them and about 8 MB (always at least one), and 245 + * the seq to ask for next, or null at the end. 247 + page(from: number, limit: number): { texts: string[]; next: number | null } { 248 + const rows = this.storage.sql 249 + .exec("SELECT seq, text FROM log WHERE seq >= ? AND seq < ? ORDER BY seq, part", from, from + limit) 250 + .toArray() as { seq: number; text: string }[]; 251 + const texts: string[] = []; 255 + let next: number | null = null; 256 + for (const r of rows) { 257 + if (r.seq < from || r.seq >= from + limit) continue; 258 + if (r.seq !== seq && seq >= 0) { 260 + size += text.length; 261 + if (size > 8_000_000) { 266 + if (r.seq !== seq) text = ""; 270 + if (next === null && seq >= 0) texts.push(text); 271 + if (next === null && from + limit < this.next) next = from + limit; 272 + return { texts, next }; 275 + /** Up to `limit` entries from position `from`, parsed (#41: the feed and replay). */ 276 + since(from: number, limit: number): Entry[] { 277 + const out: Entry[] = []; 278 + for (let at = from; out.length < limit; ) { 279 + const { texts, next } = this.page(at, limit - out.length); 280 + for (const t of texts) out.push(JSON.parse(t) as Entry); 281 + if (next === null || texts.length === 0) break; 287 + /** Removes every entry: only for a restore whose log didn't load (#29). */ 289 + const generation = this.generation() + 1; 290 + this.storage.transactionSync(() => { 291 + this.storage.sql.exec("DELETE FROM log"); 292 + this.storage.sql.exec("DELETE FROM shapes"); 293 + this.storage.sql.exec("DELETE FROM counts"); 294 + this.storage.sql.exec("DELETE FROM marks WHERE name != ?", "generation"); 295 + this.storage.sql.exec( 296 + "INSERT OR REPLACE INTO marks (name, value) VALUES (?, ?)", 305 + * Each version's changed files, kept between loads (#41, the Files pages): 306 + * worked out from the log, never part of it, so an older Worker ignores 307 + * the table and nothing about the project depends on it. 310 + get(space: string, version: number): string | undefined; 311 + put(space: string, version: number, value: string): void; 313 + const sql = this.storage.sql; 315 + get: (space, version) => 317 + sql.exec("SELECT value FROM shapes WHERE space = ? AND version = ?", space, version).toArray() as { 321 + put: (space, version, value) => 322 + void sql.exec("INSERT OR REPLACE INTO shapes (space, version, value) VALUES (?, ?, ?)", space, version, value), 326 + append(entries: readonly Entry[]): void { 327 + if (!entries.length) return; 328 + let next = this.next; 329 + this.storage.transactionSync(() => { 330 + const lines = entries.reduce((n, e) => n + linesIn(e), 0); 332 + this.storage.sql.exec( 333 + "INSERT INTO counts (name, value) VALUES ('lines', ?) ON CONFLICT(name) DO UPDATE SET value = value + ?", 337 + // The newest version of shared: appended entries are the newest, so the last one that makes a version wins. 338 + for (const e of entries) { 339 + const v = sharedVersionOf(e); 340 + if (v !== undefined) 341 + this.storage.sql.exec("INSERT OR REPLACE INTO counts (name, value) VALUES ('shared', ?)", v); 342 + const last = lastPublishOf(e); 344 + this.storage.sql.exec( 345 + "INSERT OR REPLACE INTO marks (name, value) VALUES (?, ?)", 347 + JSON.stringify(last), 350 + // Keys are only added to once counted: a log from before the key count is counted whole first (countSizes). 351 + const keys = entries.reduce((n, e) => n + keysIn(e), 0); 352 + if (keys > 0) this.storage.sql.exec("UPDATE counts SET value = value + ? WHERE name = 'keys'", keys); 354 + for (const entry of entries) { 355 + const json = JSON.stringify(entry); 356 + logParts(json).forEach((text, part) => { 357 + chars += text.length; 358 + this.storage.sql.exec("INSERT INTO log (seq, part, text) VALUES (?, ?, ?)", next, part, text); 362 + // Chars are only added to once counted: a log from before the count is summed whole first (logSize). 363 + if (chars > 0) this.storage.sql.exec("UPDATE counts SET value = value + ? WHERE name = 'chars'", chars); 364 + const generation = this.generation() + 1; 365 + this.storage.sql.exec( 366 + "INSERT OR REPLACE INTO marks (name, value) VALUES (?, ?)", 375 + /** The engine's Project as the Worker's ProjectCalls; the clock comes from here. */ 376 + export class EngineProject implements ProjectCalls, ProjectHistory { 377 + blame(file: string, from?: number, to?: number, version?: number, draft?: string, agent?: string) { 378 + return blame(this.project, file, from, to, version, { ...(draft ? { draft } : {}), ...(agent ? { agent } : {}) }); 380 + folderBlame(folder: string, version?: number, draft?: string, agent?: string) { 381 + return folderBlame(this.project, folder, version, { ...(draft ? { draft } : {}), ...(agent ? { agent } : {}) }); 383 + tree(folder: string, version?: number, draft?: string | null, agent?: string, authors?: boolean) { 384 + return this.project.tree(folder, { 385 + ...(version !== undefined ? { version } : {}), 386 + draft: draft ?? null, 387 + ...(agent !== undefined ? { agent } : {}), 388 + ...(authors ? { authors } : {}), 391 + pathLife(path: string, version?: number, draft?: string | null) { 392 + return this.project.pathLife(path, { ...(version !== undefined ? { version } : {}), draft: draft ?? null }); 394 + follow(path: string, version: number, from: number, to: number, at?: number, draft?: string | null) { 395 + return this.project.follow(path, version, from, to, { ...(at !== undefined ? { at } : {}), draft: draft ?? null }); 397 + pathsOf(agent: string) { 398 + return this.project.pathsOf(agent); 400 + draftState(name: string) { 401 + return this.project.draftState(name); 403 + collisions(file?: string, folder?: string) { 404 + return this.project.collisions({ 405 + ...(file !== undefined ? { file } : {}), 406 + ...(folder !== undefined ? { folder } : {}), 409 + why(file: string, line: number, draft?: string, agent?: string) { 410 + return why(this.project, file, line, { ...(draft ? { draft } : {}), ...(agent ? { agent } : {}) }); 413 + return where(this.project); 415 + refusals(agent?: string, limit?: number) { 416 + return this.project.refusals({ ...(agent ? { agent } : {}), ...(limit !== undefined ? { limit } : {}) }); 419 + log(draft: string | null, limit?: number, path?: string, agent?: string, before?: number, follow?: boolean) { 420 + return this.project.log({ 422 + ...(limit !== undefined ? { limit } : {}), 423 + ...(path !== undefined ? { path } : {}), 424 + ...(agent ? { agent } : {}), 425 + ...(before !== undefined ? { before } : {}), 426 + ...(follow ? { follow } : {}), 429 + fileAt(path: string, version: number, draft: string | null, agent?: string) { 430 + return this.project.fileAt(path, version, { draft, ...(agent ? { agent } : {}) }); 432 + compare(from: number, to: number, draft: string | null, agent?: string) { 433 + return this.project.compare(from, to, { draft, ...(agent ? { agent } : {}) }); 435 + show(version: number, draft: string | null, agent?: string) { 436 + return this.project.show(version, { draft, ...(agent ? { agent } : {}) }); 438 + diff(agent: string) { 439 + return this.project.diff(agent); 441 + syncFull(agent: string, label?: string) { 442 + return this.project.sync(agent, { full: true, ...(label !== undefined ? { label } : {}) }); 444 + agentPaths(agent: string) { 445 + return this.project.agentPaths(agent); 447 + pathsAt(version?: number, draft?: string | null) { 448 + return this.project.pathsAt(version, draft ?? null); 450 + syncTo(agent: string, label: string) { 451 + return this.project.sync(agent, { label }); 453 + label(agent: string, name: string, version?: number, remove?: boolean) { 454 + return this.project.label(agent, name, version, Date.now(), { remove: remove === true }); 457 + return this.project.labels(); 459 + amend(agent: string, message: string) { 460 + return this.project.amend(agent, message, Date.now()); 462 + pluck(agent: string, draft: string, versions: number[], message: string, withDependencies?: boolean) { 463 + return this.project.pluck(agent, draft, versions, message, Date.now(), { 464 + withDependencies: withDependencies === true, 467 + drop(agent: string, versions: number[], message: string, withDependents?: boolean) { 468 + return this.project.drop(agent, versions, message, Date.now(), { withDependents: withDependents === true }); 470 + announce(agent: string, text: string, to?: string[], how?: string) { 471 + return this.project.announce(agent, text, to, Date.now(), how); 474 + announcePerson(person: { id: string; name: string }, text: string, to?: string[]) { 475 + return this.project.announcePerson(person, text, to, Date.now()); 477 + starting(agent: string, text: string | null, files?: string[], options: { issue?: unknown; done?: unknown } = {}) { 478 + return this.project.starting(agent, text, files, Date.now(), options); 480 + news(agent: string) { 481 + return this.project.news(agent); 483 + restore(agent: string, files: string[] | null) { 484 + return this.project.restore(agent, files, Date.now()); 487 + private project: Project; 489 + /** Reads stored entries by log position, for the feed and replay (#41); absent, those answer 501. */ 490 + private readonly read: ((from: number, limit: number) => Entry[]) | undefined; 491 + private readonly store: SqliteLog | undefined; 493 + constructor(project: Project, read?: (from: number, limit: number) => Entry[], store?: SqliteLog) { 494 + this.project = project; 499 + /** The project's events from log position `from` (#41): reading consumes nothing. */ 500 + feed(from: number, limit = 500) { 501 + if (!this.read) throw Object.assign(new Error("the feed needs the log"), { code: "not-implemented" }); 502 + const end = this.project.logLength; 503 + const start = Math.max(0, Math.min(from, end)); 504 + const entries = start < end ? this.read(start, Math.min(limit, end - start)) : []; 505 + // A drop event names the files it took out (#41), so a timeline needs no read per drop. 506 + const events = feedEvents(entries, start).map((e) => { 507 + if (e.type !== "drop" || e.version === undefined) return e; 508 + const v = this.project.log({ limit: 1, before: e.version + 1 }).versions[0]; 509 + return v && v.version === e.version ? { ...e, dropped: v.files } : e; 511 + return { next: start + entries.length, end, events }; 514 + /** The log position for a time (ms since 1970) or a version of shared (#41). */ 515 + position(q: { time?: number; version?: number }) { 516 + return this.project.position(q); 518 + /** Whether the Worker runs the queue's check; until it does, "queue": true does nothing. */ 519 + setCheckerReady(ready: boolean): void { 520 + this.project.checkerReady = ready; 522 + /** An agent withdraws what it has queued (#39). */ 523 + unqueue(agent: string) { 524 + return this.project.unqueue(agent, Date.now()); 526 + /** The log length now: what a long-poll waits to see grow. */ 528 + return this.project.logLength; 530 + /** An agent's draft diff for a reader: never creates the agent (#41). */ 531 + diffOf(agent: string) { 532 + return this.project.diffOf(agent); 534 + /** Every agent with unpublished changes: its files and how many changes (#41). */ 535 + change(id: number) { 536 + return this.project.change(id); 539 + changes(since: number, limit: number, before?: number, issue?: number) { 540 + return this.project.changes(since, limit, before, issue); 543 + move(agent: string, from: string, to: string) { 544 + return this.project.move(agent, from, to, Date.now()); 547 + note(agent: string, body: Record<string, unknown>) { 548 + return this.project.note(agent, body, Date.now()); 551 + notePerson(person: { id: string; name: string }, body: Record<string, unknown>) { 552 + return this.project.notePerson(person, body, Date.now()); 555 + closeNotePerson(person: { id: string; name: string }, id: number, how: unknown) { 556 + return this.project.closeNotePerson(person, id, how, Date.now()); 559 + closeNote(agent: string, id: number, how: unknown) { 560 + return this.project.closeNote(agent, id, how, Date.now()); 563 + notes(options: { file?: string; change?: number; open?: boolean }) { 564 + return this.project.notes(options); 568 + return this.project.ribbon(); 572 + const s = this.project.status(); 576 + .filter((a) => a.draftChanges > 0) 577 + .map((a) => ({ agent: a.agent, draft: a.draft, base: a.base, draftChanges: a.draftChanges, files: a.files })), 580 + /** The last copy replay loaded: scrubbing forward from it applies only the entries after it. */ 581 + private replica: Project | undefined; 583 + /** The project as it stood with the first `at` log entries (#41, replay). */ 584 + private at(at: number): Project { 585 + if (!this.read) throw Object.assign(new Error("replay needs the log"), { code: "not-implemented" }); 586 + const n = Math.max(0, Math.min(at, this.project.logLength)); 587 + const r = this.replica; 588 + if (r && r.logLength === n) return r; 589 + if (r && r.logLength < n) { 590 + r.catchUp(this.read(r.logLength, n - r.logLength)); 593 + this.replica = Project.load(this.read(0, n), new MemoryStore()); 594 + return this.replica; 596 + statusAt(at: number) { 597 + const p = this.at(at); 599 + at: Math.min(at, this.project.logLength), 600 + ...(p.initialized ? p.status() : { version: -1, agents: [] }), 605 + whereAt(at: number) { 606 + const p = this.at(at); 608 + at: Math.min(at, this.project.logLength), 609 + ...(p.initialized ? where(p) : { version: -1, files: {} }), 616 + * Drop the replay copy after each read (#46): a second copy of a large 617 + * project's history doubles its memory, past a Durable Object's 128 MB. 618 + * Each scrub replays from the start instead (about 0.2 s on game). 620 + private release(): void { 621 + this.replica = undefined; 624 + /** hasBlob says whether the project holds a blob's bytes (#27); without it, every blob is refused. */ 625 + /** whole stores and reads files kept whole (#46); without it every text file is tracked by line. */ 627 + storage: SqliteStorage, 628 + hasBlob?: (sha256: string) => boolean, 629 + whole?: { keep(text: string): string; read(sha: string): string | null }, 631 + const log = new SqliteLog(storage); 632 + return new EngineProject( 633 + Project.load(log.entries(), log, { 634 + ...(hasBlob ? { hasBlob } : {}), 635 + ...(whole ? { whole } : {}), 636 + now: () => Date.now(), 637 + shapes: log.shapes(), 638 + entryAt: (at) => log.since(at, 1)[0]!, 640 + (from, limit) => log.since(from, limit), 646 + return this.project.initialized; 648 + /** Committed log epoch for host-side cache invalidation; it does not dispatch work. */ 649 + committedGeneration(): number { 650 + return this.store?.generation() ?? 0; 653 + files: Record<string, string>, 654 + modes?: Record<string, { exec?: boolean; link?: string | null }>, 655 + blobs?: Record<string, string>, 657 + return this.project.init(files, Date.now(), modes ?? {}, blobs ?? {}); 659 + edit(agent: string, body: EditBody) { 660 + return this.project.edit(agent, body as Parameters<Project["edit"]>[1], Date.now()); 664 + files: Record<string, string | null>, 665 + modes?: Record<string, { exec?: boolean; link?: string | null }>, 666 + blobs?: Record<string, string>, 667 + meta?: { session?: string; subagent?: string; client?: string }, 669 + return this.project.record(agent, files, Date.now(), modes ?? {}, blobs ?? {}, meta ?? {}); 671 + publish(agent: string, message: string, asIs?: boolean) { 672 + return this.project.publish(agent, message, Date.now(), { asIs: asIs === true }); 674 + sync(agent: string) { 675 + return this.project.sync(agent); 678 + return this.project.status(); 680 + switchTo(agent: string, name: string | null, carry = false) { 681 + return this.project.switchTo(agent, name, Date.now(), { carry }); 683 + land(agent: string, message: string) { 684 + return this.project.land(agent, message, Date.now()); 686 + ingest(input: Parameters<Project["ingest"]>[0], time: number) { 687 + return this.project.ingest(input, time); 689 + syncDraft(agent: string) { 690 + return this.project.syncDraft(agent, Date.now()); 692 + filesAt(version: number) { 693 + return this.project.viewAt(version).files(); 695 + blobsAt(version: number) { 696 + return this.project.viewAt(version).blobs(); 699 + * Shared's newest version. Its files and modes are laid out on first read: every call reads shared().version 700 + * before and after its op, and laying out the files reads each file's text from the log, about 0.5 s on abso 704 + const version = this.project.version; 705 + const by = version > 0 ? this.project.published(version) : undefined; 706 + const blobs = this.project.blobs(); 707 + const project = this.project; 708 + let files: Record<string, string> | undefined; 709 + let modes: ReturnType<Project["modes"]> | undefined; 713 + files ??= project.files(); 717 + modes ??= project.modes(); 720 + ...(Object.keys(blobs).length > 0 ? { blobs } : {}), 721 + ...(by ? { last: { agent: by.agent, message: by.message } } : {}), --- /dev/null
+++ b/server/src/env.ts
@@ -0,0 +1,36 @@
1 + // What the open server's Worker is given: wrangler.jsonc's bindings and the secrets set with `wrangler secret put`. 3 + import type { IssueProject } from "./issues-entry.ts"; 4 + import type { ProjectObject } from "./project-object.ts"; 7 + /** One Durable Object per project, named by the project's name. */ 8 + PROJECT: DurableObjectNamespace<ProjectObject>; 9 + /** Issues, asks and news: one Durable Object per project, named by the project's name. */ 10 + ISSUES_DO: DurableObjectNamespace<IssueProject>; 11 + /** Each project's shared, pushed out as a git repo abso-<project>. Unbound under local `wrangler dev`: skipped. */ 12 + ARTIFACTS?: Artifacts; 13 + /** "off" leaves Artifacts alone even where it is bound: local `wrangler dev --local` binds it but cannot reach it. */ 14 + ABSO_ARTIFACTS?: string; 15 + CF_VERSION_METADATA?: WorkerVersionMetadata; 16 + /** The shared token every agent signs in with. AVCS_TOKEN is its old name. With neither set, every call is refused. */ 19 + /** For /admin/agent-keys, sent as the x-abso-admin header beside the shared token. */ 20 + ABSO_ADMIN_TOKEN?: string; 21 + AVCS_ADMIN_TOKEN?: string; 22 + /** Per-agent keys: "on" with KEY_HMAC_SECRET set. */ 24 + KEY_HMAC_SECRET?: string; 27 + /** A secret by its abso name, or its avcs name from before the rename. Empty counts as unset. */ 28 + export function secret(env: Env, name: "TOKEN" | "ADMIN_TOKEN"): string | undefined { 29 + for (const v of [env[`ABSO_${name}`], env[`AVCS_${name}`]]) if (typeof v === "string" && v !== "") return v; 33 + /** The Artifacts binding, unless it is unbound or ABSO_ARTIFACTS is "off": then nothing is pushed out or taken in. */ 34 + export function artifactsOf(env: Env): Artifacts | undefined { 35 + return env.ABSO_ARTIFACTS === "off" ? undefined : env.ARTIFACTS; --- /dev/null
+++ b/server/src/index.ts
@@ -0,0 +1,12 @@
1 + // The Worker's entry: the router (router.ts) and the Durable Object classes wrangler.jsonc binds. 3 + import type { Env } from "./env.ts"; 4 + import { issuesFetch } from "./issues-entry.ts"; 5 + import { handle } from "./router.ts"; 7 + export { IssueProject } from "./issues-entry.ts"; 8 + export { ProjectObject } from "./project-object.ts"; 11 + fetch: (request, env, ctx) => handle(request, env, ctx, issuesFetch), 12 + } satisfies ExportedHandler<Env>; --- /dev/null
+++ b/server/src/ingest.ts
@@ -0,0 +1,174 @@
1 + // In from plain git (#8, demo moment 5): commits a person pushed to the 2 + // project's Artifacts repo, read back for project.ingest. Every commit the 3 + // Worker pushes ends "abso-version: N" ("avcs-version: N" before the rename); the commits above the newest such 4 + // commit that haven't been taken in yet are the person's, and N is their base. 5 + import git from "isomorphic-git"; 6 + import http from "isomorphic-git/http/web"; 7 + import type { FileModes } from "../../worker/project/project-api.ts"; 8 + import { MemoryFS } from "./memory-fs.ts"; 9 + import { repoName } from "./push.ts"; 11 + const EXEC = 0o100755; 12 + const LINK = 0o120000; 14 + /** How far back to look for the Worker's last commit. */ 16 + const text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: false }); 18 + export interface PushedCommits { 19 + /** main's head when read. */ 23 + /** Oldest first, each with its whole tree as text and every file's mode. Binary files are left out. */ 27 + files: Record<string, string>; 29 + blobs: Record<string, string>; 31 + /** Binary files over the blob limit, left out of the commits. */ 35 + export function absoVersion(message: string): number | undefined { 36 + const m = /^(?:abso|avcs)-version: (\d+)\s*$/m.exec(message); 37 + return m ? Number(m[1]) : undefined; 40 + async function readAccess( 41 + artifacts: Artifacts, 43 + ): Promise<{ url: string; onAuth: () => { username: string; password: string } } | null> { 44 + let repo: Awaited<ReturnType<Artifacts["get"]>>; 46 + repo = await artifacts.get(repoName(project)); 51 + const [info, token] = await Promise.all([r.info(), r.createToken("read", 600)]); 52 + const password = token.plaintext.split("?expires=")[0]!; 53 + return { url: info!.remote, onAuth: () => ({ username: "x", password }) }; 56 + /** main's head on the project's repo, or null when there's no repo or no main yet. Cheap: one ref listing. */ 57 + export async function remoteHead(artifacts: Artifacts, project: string): Promise<string | null> { 58 + const access = await readAccess(artifacts, project); 59 + if (!access) return null; 60 + const refs = await git.listServerRefs({ http, url: access.url, onAuth: access.onAuth, prefix: "refs/heads/main" }); 61 + return refs.find((r) => r.ref === "refs/heads/main")?.oid ?? null; 65 + * The commits pushed since `seen` (the last head this project handled), or 66 + * none when every commit above the Worker's last one has been seen. 68 + /** Stores a binary file's bytes and answers their SHA-256, or null when they're over the limit. */ 69 + export type StoreBlob = (bytes: Uint8Array) => Promise<string | null>; 72 + * `oldBlob` gives shared's blob for a path: a binary file over the limit 73 + * keeps it, since a path missing from a commit would mean the file was deleted. 75 + export async function pushedSince( 76 + artifacts: Artifacts, 78 + seen: string | undefined, 79 + storeBlob?: StoreBlob, 80 + oldBlob: (path: string) => string | undefined = () => undefined, 81 + ): Promise<PushedCommits | null> { 82 + const access = await readAccess(artifacts, project); 83 + if (!access) return null; 84 + const fs = new MemoryFS(); 91 + onAuth: access.onAuth, 97 + const log = await git.log({ fs, dir, ref: "main", depth: DEPTH }); 98 + if (log.length === 0) return null; 99 + const head = log[0]!.oid; 100 + const fresh: typeof log = []; 101 + let base: number | undefined; 103 + for (const c of log) { 104 + if (c.oid === seen) past = true; 105 + base = absoVersion(c.commit.message); 106 + if (base !== undefined) break; 107 + if (!past) fresh.unshift(c); 109 + if (base === undefined) throw new Error(`no abso-version commit in main's last ${DEPTH} commits`); 111 + const tooBig = new Set<string>(); 112 + for (const c of fresh) 115 + message: c.commit.message.trim(), 116 + ...(await treeText(fs, dir, c.oid, storeBlob, tooBig, oldBlob)), 118 + return { head, author: fresh.at(-1)?.commit.author.name ?? "git", base, commits, tooBig: [...tooBig] }; 122 + * A commit's whole tree as text, and every file's mode: 100755 is exec, and 123 + * a link (120000) is "" with its target in modes. Files that aren't UTF-8 126 + async function treeText( 130 + storeBlob: StoreBlob | undefined, 131 + tooBig: Set<string>, 132 + oldBlob: (path: string) => string | undefined, 133 + ): Promise<{ files: Record<string, string>; modes: FileModes; blobs: Record<string, string> }> { 134 + const files: Record<string, string> = {}; 135 + const modes: FileModes = {}; 136 + const blobs: Record<string, string> = {}; 140 + trees: [git.TREE({ ref: oid })], 141 + map: async (path, [entry]) => { 142 + if (!entry || path === ".") return true; 143 + if ((await entry.type()) !== "blob") return true; 144 + const bytes = await entry.content(); 145 + if (!bytes) return true; 148 + body = text.decode(bytes); 150 + // Binary (#27): the bytes go to the blob store, and the file is a pointer to them. 151 + const sha = storeBlob ? await storeBlob(bytes) : null; 154 + modes[path] = { exec: (await entry.mode()) === EXEC, link: null }; 155 + } else if (storeBlob) { 157 + const kept = oldBlob(path); 158 + if (kept) blobs[path] = kept; 162 + const mode = await entry.mode(); 163 + if (mode === LINK) { 165 + modes[path] = { exec: false, link: body }; 168 + modes[path] = { exec: mode === EXEC, link: null }; 173 + return { files, modes, blobs }; --- /dev/null
+++ b/server/src/issues-entry.ts
@@ -0,0 +1,27 @@
1 + // Where the router meets issues, asks and news (server/src/issues/, built alongside this file). Until that folder 2 + // lands, this is a stand-in with the same exports, so the Worker builds and its tests run. When it lands, this file 5 + // export { IssueProject, issuesFetch } from "./issues/index.ts"; 7 + // The agreed interface: issuesFetch(request, env, ctx, {project, rest, auth}), where rest is the path after 8 + // /issues/p/<project> and auth is {kind: "token"} or {kind: "key", agent, role}. The router has checked auth before it 9 + // calls. The issues code reaches the project through env.PROJECT and its RPC methods agents(project) and 10 + // news(project, items) on ProjectObject. 12 + import { DurableObject } from "cloudflare:workers"; 13 + import type { Env } from "./env.ts"; 14 + import type { KeyRole } from "./keys.ts"; 16 + export type IssuesAuth = { kind: "token" } | { kind: "key"; agent: string; role: KeyRole }; 18 + export class IssueProject extends DurableObject<Env> {} 20 + export async function issuesFetch( 23 + _ctx: ExecutionContext, 24 + _where: { project: string; rest: string; auth: IssuesAuth }, 25 + ): Promise<Response> { 26 + return Response.json({ error: "issues aren't on this server yet" }, { status: 404 }); --- /dev/null
+++ b/server/src/keys.ts
@@ -0,0 +1,253 @@
1 + // Per-agent keys, ported from the platform's worker/src/keys.ts. They run when AGENT_KEYS is "on" and 2 + // KEY_HMAC_SECRET is set. Each key belongs to one agent of one project; the project's Durable Object keeps only the 3 + // key's HMAC, never the key. Without keys, the shared token (ABSO_TOKEN) is the only way in. 5 + export const KEY_PREFIX = "abso_sk_"; 7 + const FAIL_WINDOW_MS = 10 * 60 * 1000; 9 + const DAY_MS = 24 * 60 * 60 * 1000; 11 + export interface KeyEnv { 13 + KEY_HMAC_SECRET?: string; 16 + /** What a key may do in its project: the admin's choice when it was issued. */ 17 + export type KeyRole = "owner" | "writer" | "reader"; 19 + export interface KeyRow { 25 + lastUsed: number | null; 26 + revokedAt: number | null; 27 + expiresAt?: number | null; 28 + /** Absent on a key issued before roles existed: it counts as reader, so it fails closed. */ 32 + export interface FailRow { 37 + export interface AuditRow { 39 + kind: "issue" | "revoke" | "use" | "fail"; 44 + export interface KeyState { 46 + fails: Record<string, FailRow>; 47 + seen: Record<string, string>; 51 + export function emptyKeyState(): KeyState { 52 + return { rows: [], fails: {}, seen: {}, audit: [] }; 55 + /** Keys run when the switch and the secret are both set. */ 56 + export function keysEnabled(env: KeyEnv): boolean { 57 + return env.AGENT_KEYS === "on" && !!env.KEY_HMAC_SECRET; 60 + /** 90 days when omitted. 1d to 365d otherwise. */ 61 + export function expiresAt(now: number, raw: string | null): number | { error: string } { 62 + if (raw === null || raw === "") return now + 90 * DAY_MS; 63 + const match = /^(\d+)d$/.exec(raw); 64 + if (!match) return { error: "expires is a number of days, like 7d, from 1d to 365d" }; 65 + const days = Number(match[1]); 66 + if (days < 1 || days > 365) return { error: "expires is from 1d to 365d" }; 67 + return now + days * DAY_MS; 70 + export function isAgentKey(presented: string | undefined): boolean { 71 + return typeof presented === "string" && presented.startsWith(KEY_PREFIX) && presented.length > KEY_PREFIX.length; 74 + export async function hmac(secret: string, message: string): Promise<string> { 75 + const key = await crypto.subtle.importKey( 77 + new TextEncoder().encode(secret), 78 + { name: "HMAC", hash: "SHA-256" }, 82 + const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(message))); 83 + return [...mac].map((b) => b.toString(16).padStart(2, "0")).join(""); 86 + /** Whether two strings are equal, taking the same time wherever they differ. */ 87 + export function timingSame(a: string, b: string): boolean { 88 + if (a.length !== b.length) return false; 90 + for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i); 94 + function randomHex(bytes: number): string { 95 + const b = new Uint8Array(bytes); 96 + crypto.getRandomValues(b); 97 + return [...b].map((n) => n.toString(16).padStart(2, "0")).join(""); 100 + export function newKey(): { id: string; key: string } { 101 + const raw = new Uint8Array(32); 102 + crypto.getRandomValues(raw); 103 + const body = btoa(String.fromCharCode(...raw)) 104 + .replaceAll("+", "-") 105 + .replaceAll("/", "_") 106 + .replace(/=+$/, ""); 107 + return { id: `k_${randomHex(4)}`, key: `${KEY_PREFIX}${body}` }; 110 + function note(state: KeyState, row: AuditRow): void { 111 + state.audit.push(row); 112 + if (state.audit.length > AUDIT_CAP) state.audit.splice(0, state.audit.length - AUDIT_CAP); 115 + export interface Issued { 121 + /** Issues a key. The returned value is the only copy; the state keeps the HMAC. */ 122 + export async function issueKey( 132 + const made = newKey(); 133 + const addr = await hmac(secret, address); 136 + hmac: await hmac(secret, made.key), 145 + note(state, { t: now, kind: "issue", id: made.id, addr }); 146 + return { id: made.id, key: made.key, agent }; 149 + export function revokeKey(state: KeyState, id: string, now: number, addr: string): boolean { 150 + const row = state.rows.find((r) => r.id === id); 151 + if (!row || row.revokedAt !== null) return false; 152 + row.revokedAt = now; 153 + note(state, { t: now, kind: "revoke", id, addr }); 157 + export function listKeys(state: KeyState, agent?: string) { 159 + .filter((r) => agent === undefined || r.agent === agent) 160 + .map(({ id, agent: a, issuedBy, at, lastUsed, revokedAt, expiresAt: exp, role }) => ({ 163 + role: role ?? "reader", 168 + expiresAt: exp ?? null, 172 + export type KeyDecision = 173 + | { ok: true; id: string; as: string; role: KeyRole; dirty: boolean } 174 + | { ok: false; status: number; error: string; dirty: boolean }; 177 + * Checks a presented key against one project. The URL's agent must match the key's agent: a mismatch is a 403, and 178 + * the agent is not rewritten. A missing secret is a 503 that names no key. Failures are counted per address and 179 + * slowed after a few. Nothing returned or recorded contains the key. 181 + export async function checkKey( 183 + secret: string | undefined, 185 + agent: string | undefined, 188 + ): Promise<KeyDecision> { 189 + if (!secret) return { ok: false, status: 503, error: "the key secret (KEY_HMAC_SECRET) is not set", dirty: false }; 190 + const addr = await hmac(secret, address); 191 + const fail = state.fails[addr]; 192 + if (fail && now - fail.at < FAIL_WINDOW_MS && fail.n >= FAIL_LIMIT) { 193 + return { ok: false, status: 429, error: "too many failed keys; try again shortly", dirty: false }; 195 + const mac = await hmac(secret, presented); 196 + const row = state.rows.find((r) => timingSame(r.hmac, mac)); 197 + const bump = () => { 198 + const cur = state.fails[addr]; 199 + state.fails[addr] = !cur || now - cur.at >= FAIL_WINDOW_MS ? { n: 1, at: now } : { n: cur.n + 1, at: cur.at }; 200 + note(state, { t: now, kind: "fail", id: row?.id ?? null, addr }); 202 + if (!row || row.revokedAt !== null || (row.expiresAt != null && now >= row.expiresAt)) { 205 + ? "that key is not for this project" 206 + : row.revokedAt !== null 207 + ? "that key was revoked" 208 + : "that key has expired"; 209 + return { ok: false, status: 403, error, dirty: true }; 211 + if (agent !== undefined && row.agent !== agent) { 213 + return { ok: false, status: 403, error: "that key is not for this agent", dirty: true }; 216 + if (state.fails[addr]) { 217 + delete state.fails[addr]; 220 + if (state.seen[row.id] !== addr) { 221 + state.seen[row.id] = addr; 222 + note(state, { t: now, kind: "use", id: row.id, addr }); 225 + if (row.lastUsed === null || now - row.lastUsed >= 60_000) { 229 + return { ok: true, id: row.id, as: `key ${row.id}`, role: row.role ?? "reader", dirty }; 232 + /** Project routes only an owner's key may use, whatever the method. */ 233 + const OWNER_ONLY = new Set(["git-remote", "git-sync", "export"]); 236 + * Whether a key's role allows a request. A reader only reads. A writer also writes, but only on its own agent's 237 + * routes (/a/:agent/..., where checkKey has matched the agent), and blob uploads, which a record needs. Owner-only 238 + * routes need an owner's key. 240 + export function keyAllows( 242 + request: { write: boolean; agent: string | undefined; route: string | undefined; method?: string }, 243 + ): { ok: true } | { ok: false; status: number; error: string } { 244 + if (role === "owner") return { ok: true }; 245 + if (request.route !== undefined && OWNER_ONLY.has(request.route)) 246 + return { ok: false, status: 403, error: `${request.route} needs an owner's key` }; 247 + if (!request.write) return { ok: true }; 248 + if (role === "reader") return { ok: false, status: 403, error: "this key only reads" }; 249 + if (request.method === "PUT" && /^blobs\/[0-9a-f]{64}$/.test(request.route ?? "")) return { ok: true }; 250 + if (request.agent === undefined) 251 + return { ok: false, status: 403, error: "a writer's key writes only on its own agent's routes" }; 252 + return { ok: true }; --- /dev/null
+++ b/server/src/memory-fs.ts
@@ -0,0 +1,235 @@
1 + // From Cloudflare's isomorphic-git example, with fixes isomorphic-git 1.43 2 + // needs: errors carry .code (isomorphic-git checks err.code === "ENOENT"), 3 + // stats are plain fields it can normalize in place, and the executable bit 4 + // and symbolic links are kept (#27), so a checkout of a repo with either works. 6 + function fsError(code: string, path: string): Error { 7 + return Object.assign(new Error(`${code}: ${path}`), { code }); 11 + | { kind: "dir"; children: Set<string>; mtimeMs: number } 12 + | { kind: "file"; data: Uint8Array; exec: boolean; mtimeMs: number } 13 + | { kind: "link"; target: string; mtimeMs: number }; 15 + const enc = new TextEncoder(); 17 + /** Plain fields, not getters: isomorphic-git writes to them when it normalizes stats. */ 23 + private kind: Entry["kind"]; 25 + constructor(entry: Entry) { 26 + this.kind = entry.kind; 28 + entry.kind === "file" ? entry.data.byteLength : entry.kind === "link" ? enc.encode(entry.target).byteLength : 0; 29 + this.mtimeMs = entry.mtimeMs; 30 + this.ctimeMs = entry.mtimeMs; 31 + this.mode = entry.kind === "dir" ? 0o040000 : entry.kind === "link" ? 0o120000 : entry.exec ? 0o100755 : 0o100644; 35 + return this.kind === "file"; 39 + return this.kind === "dir"; 43 + return this.kind === "link"; 47 + export class MemoryFS { 48 + encoder = new TextEncoder(); 49 + decoder = new TextDecoder(); 50 + entries = new Map<string, Entry>([["/", { kind: "dir", children: new Set(), mtimeMs: Date.now() }]]); 53 + readFile: this.readFile.bind(this), 54 + writeFile: this.writeFile.bind(this), 55 + unlink: this.unlink.bind(this), 56 + readdir: this.readdir.bind(this), 57 + mkdir: this.mkdir.bind(this), 58 + rmdir: this.rmdir.bind(this), 59 + stat: this.stat.bind(this), 60 + lstat: this.lstat.bind(this), 61 + readlink: this.readlink.bind(this), 62 + symlink: this.symlink.bind(this), 63 + chmod: this.chmod.bind(this), 66 + normalize(input: string) { 67 + const segments: string[] = []; 69 + for (const part of input.split("/")) { 70 + if (!part || part === ".") { 82 + return `/${segments.join("/")}` || "/"; 85 + parent(path: string) { 86 + const normalized = this.normalize(path); 87 + if (normalized === "/") { 91 + const parts = normalized.split("/").filter(Boolean); 93 + return parts.length ? `/${parts.join("/")}` : "/"; 96 + basename(path: string) { 97 + return this.normalize(path).split("/").filter(Boolean).pop() ?? ""; 100 + getEntry(path: string) { 101 + return this.entries.get(this.normalize(path)); 104 + requireEntry(path: string) { 105 + const entry = this.getEntry(path); 107 + throw fsError("ENOENT", path); 113 + requireDir(path: string) { 114 + const entry = this.requireEntry(path); 115 + if (entry.kind !== "dir") { 116 + throw fsError("ENOTDIR", path); 122 + async mkdir(path: string, options?: { recursive?: boolean } | number) { 123 + const target = this.normalize(path); 124 + if (target === "/") { 128 + const recursive = typeof options === "object" && options !== null && options.recursive; 129 + const parent = this.parent(target); 131 + if (!this.entries.has(parent)) { 133 + throw fsError("ENOENT", parent); 136 + await this.mkdir(parent, { recursive: true }); 139 + if (this.entries.has(target)) { 143 + this.entries.set(target, { 145 + children: new Set(), 146 + mtimeMs: Date.now(), 149 + this.requireDir(parent).children.add(this.basename(target)); 152 + /** options.mode with any execute bit (isomorphic-git passes 0o777 for 100755) makes the file executable. */ 153 + async writeFile(path: string, data: string | Uint8Array | ArrayBuffer, options?: string | { mode?: number }) { 154 + const target = this.normalize(path); 155 + await this.mkdir(this.parent(target), { recursive: true }); 158 + typeof data === "string" ? this.encoder.encode(data) : data instanceof Uint8Array ? data : new Uint8Array(data); 159 + const mode = typeof options === "object" && options !== null ? options.mode : undefined; 161 + this.entries.set(target, { 164 + exec: mode !== undefined && (mode & 0o111) !== 0, 165 + mtimeMs: Date.now(), 168 + this.requireDir(this.parent(target)).children.add(this.basename(target)); 171 + async readFile(path: string, options?: string | { encoding?: string }) { 172 + const entry = this.requireEntry(path); 173 + if (entry.kind === "dir") { 174 + throw fsError("EISDIR", path); 177 + const data = entry.kind === "link" ? this.encoder.encode(entry.target) : entry.data; 178 + const encoding = typeof options === "string" ? options : options?.encoding; 179 + return encoding ? this.decoder.decode(data) : data; 182 + async readdir(path: string) { 183 + return [...this.requireDir(path).children].sort(); 186 + async unlink(path: string) { 187 + const target = this.normalize(path); 188 + const entry = this.requireEntry(target); 189 + if (entry.kind === "dir") { 190 + throw fsError("EISDIR", path); 193 + this.entries.delete(target); 194 + this.requireDir(this.parent(target)).children.delete(this.basename(target)); 197 + async rmdir(path: string) { 198 + const target = this.normalize(path); 199 + const entry = this.requireDir(target); 200 + if (entry.children.size > 0) { 201 + throw fsError("ENOTEMPTY", path); 204 + this.entries.delete(target); 205 + this.requireDir(this.parent(target)).children.delete(this.basename(target)); 208 + async stat(path: string) { 209 + return new MemoryStats(this.requireEntry(path)); 212 + /** Links aren't followed anywhere here, so lstat and stat agree. */ 213 + async lstat(path: string) { 214 + return this.stat(path); 217 + async readlink(path: string): Promise<string> { 218 + const entry = this.requireEntry(path); 219 + if (entry.kind !== "link") throw fsError("EINVAL", path); 220 + return entry.target; 223 + async symlink(target: string, path: string): Promise<void> { 224 + const at = this.normalize(path); 225 + if (this.entries.has(at)) throw fsError("EEXIST", path); 226 + await this.mkdir(this.parent(at), { recursive: true }); 227 + this.entries.set(at, { kind: "link", target, mtimeMs: Date.now() }); 228 + this.requireDir(this.parent(at)).children.add(this.basename(at)); 231 + async chmod(path: string, mode: number): Promise<void> { 232 + const entry = this.requireEntry(path); 233 + if (entry.kind === "file") entry.exec = (mode & 0o111) !== 0; --- /dev/null
+++ b/server/src/project-object.ts
@@ -0,0 +1,534 @@
1 + // One project: its append-only log and blobs in the Durable Object's SQLite, the engine loaded from them, and the push 2 + // out to the project's Artifacts repo after each new version of shared. Ported from the platform's ProjectObject 3 + // (worker/src/index.ts), trimmed to the core path: no CI, merge queue checker, boxes, pipelines, members, visibility, 4 + // R2 copies, edge cache, probes or disk-first writer. 6 + import { DurableObject } from "cloudflare:workers"; 7 + import { type Answer, answer, type Readers } from "../../worker/project/http.ts"; 8 + import type { ProjectCalls, ProjectHistory } from "../../worker/project/project-api.ts"; 9 + import { BLOB_MAX, BlobStore } from "./blobs.ts"; 10 + import { EngineProject, SqliteLog } from "./engine-project.ts"; 11 + import { artifactsOf, type Env } from "./env.ts"; 12 + import { pushedSince, remoteHead } from "./ingest.ts"; 25 + import { type PushResult, pushShared, repoName } from "./push.ts"; 27 + /** At most one push out a minute: each one clones the repo, so publishes in a burst share one. */ 28 + export const PUSH_EVERY_MS = 60_000; 29 + /** While agents are working, how often a call looks for plain-git pushes to the repo. */ 30 + const GIT_CHECK_MS = 15_000; 33 + * The load guard (platform issue 46): an estimate of a loaded project's memory from its log entries, lines and claim 34 + * keys, all read from SQLite without loading. A Durable Object has 128 MB. Past the hard cap a project refuses to 35 + * load (export still reads it); past the soft cap, new work is held so the hard cap is never reached. 37 + const LOAD_BYTES_PER_ENTRY = 1_200; 38 + const LOAD_BYTES_PER_LINE = 20; 39 + const LOAD_BYTES_PER_KEY = 20; 40 + const LOAD_BASE_BYTES = 10_000_000; 41 + const LOAD_MAX_BYTES = 114_000_000; 42 + const LOAD_SOFT_BYTES = 94_800_000; 43 + /** Before its lines are counted, a log over this many characters refuses to load. */ 44 + const LOG_LOAD_MAX_CHARS = 12_000_000; 45 + /** The ops the soft cap holds: the ones that bring new work into the history. */ 46 + const SOFT_HELD_OPS: ReadonlySet<string> = new Set(["record", "edit", "publish", "land", "amend", "pluck", "drop"]); 48 + export function loadEstimate(entries: number, lines: number, keys: number): number { 49 + return entries * LOAD_BYTES_PER_ENTRY + lines * LOAD_BYTES_PER_LINE + keys * LOAD_BYTES_PER_KEY + LOAD_BASE_BYTES; 52 + /** A presented agent key, checked inside the call so the check and the call are one trip. */ 53 + export interface KeyForCall { 57 + route: string | undefined; 60 + /** A news item from the issues code: delivered as an announcement from its writer. */ 61 + export interface IssueNews { 63 + issue: number | null; 68 + /** What the issues Durable Object hears when a start note naming an issue begins and ends. Each is optional. */ 69 + interface IssueHooks { 70 + claim?(agent: string, issue: number, change: number): Promise<unknown>; 71 + unclaim?(agent: string, issue: number): Promise<unknown>; 72 + done?(agent: string, issue: number, version: number): Promise<unknown>; 75 + export class ProjectObject extends DurableObject<Env> { 76 + private blobs: BlobStore; 77 + private loaded: ProjectCalls | undefined; 78 + /** Why the log didn't load, if it didn't. */ 79 + private loadError: unknown; 80 + private tried = false; 81 + /** Feed long-polls waiting for the log to grow; woken after every call that wrote. */ 82 + private waiting: (() => void)[] = []; 83 + /** When this object last asked the repo for pushes made with plain git. */ 84 + private gitCheckedAt = 0; 85 + private gitSyncing: Promise<{ head: string; commits: number; answer: unknown } | null> | undefined; 87 + constructor(ctx: DurableObjectState, env: Env) { 89 + this.blobs = new BlobStore(ctx.storage); 92 + /** Where files kept whole go: the project's blob store. */ 93 + private wholeFiles() { 94 + return { keep: (text: string) => this.blobs.putText(text), read: (sha: string) => this.blobs.textOf(sha) }; 97 + /** The project, loaded from its log on first use. A log too big for memory is refused, not loaded. */ 98 + private ensure(): ProjectCalls | undefined { 99 + if (this.loaded || this.tried) return this.loaded; 102 + const why = this.tooBigToLoad(); 103 + if (why) throw new Error(`${why}, too big to load in a Durable Object's memory; GET export still reads it`); 104 + this.loaded = EngineProject.open(this.ctx.storage, (sha) => this.blobs.has(sha), this.wholeFiles()); 111 + private get project(): ProjectCalls { 112 + const p = this.ensure(); 113 + if (!p) throw this.loadError; 117 + private logChars(): { chars: number; entries: number } { 118 + const tables = this.ctx.storage.sql 119 + .exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'log'") 121 + return tables.length === 0 ? { chars: 0, entries: 0 } : new SqliteLog(this.ctx.storage).logSize(); 124 + private sizes(): { lines: number; keys: number } | undefined { 125 + if (this.logChars().entries === 0) return undefined; 127 + return new SqliteLog(this.ctx.storage).countSizes(); 133 + /** Why recording new work is held: the estimate is past the soft cap; else null. */ 134 + private softHeld(): string | null { 135 + const counted = this.sizes(); 136 + if (counted === undefined) return null; 137 + const bytes = loadEstimate(this.logChars().entries, counted.lines, counted.keys); 138 + return bytes > LOAD_SOFT_BYTES 139 + ? `this project is near the most a project can hold (an estimated ${(bytes / 1e6).toFixed(0)} MB of ${LOAD_MAX_BYTES / 1e6} MB), so recording and publishing are held; status and reads keep working` 143 + /** Why this project mustn't load: its estimated memory, or before its lines are counted, its log's size; else null. */ 144 + private tooBigToLoad(): string | null { 145 + const counted = this.sizes(); 146 + if (counted !== undefined) { 147 + const bytes = loadEstimate(this.logChars().entries, counted.lines, counted.keys); 148 + return bytes > LOAD_MAX_BYTES 149 + ? `this project holds ${counted.lines} lines and ${this.logChars().entries} entries, an estimated ${(bytes / 1e6).toFixed(0)} MB once loaded` 152 + const { chars } = this.logChars(); 153 + return chars > LOG_LOAD_MAX_CHARS ? `this project's log is ${(chars / 1e6).toFixed(1)} MB` : null; 156 + // Blobs: binary files' bytes, named by their SHA-256. 158 + async putBlob(sha: string, body: ReadableStream<Uint8Array>): Promise<Answer> { 159 + const a = await this.blobs.put(sha, body); 160 + // A push out waiting on missing blobs goes again now. 161 + if (a.status === 200 && (await this.ctx.storage.get("pushError"))) await this.ctx.storage.setAlarm(Date.now()); 165 + async getBlob(sha: string): Promise<ReadableStream<Uint8Array> | null> { 166 + return this.blobs.stream(sha); 169 + /** Shared's newest version, from storage alone, never loading the project. Null when there's no project. */ 170 + async head(): Promise<{ version: number; at: string } | null> { 171 + if (this.logChars().entries === 0) return null; 172 + return { version: new SqliteLog(this.ctx.storage).sharedVersion(), at: new Date().toISOString() }; 175 + /** Backups: one page of the log as JSON lines. It works even when the log won't load. */ 176 + async exportLog(from: number, limit: number): Promise<{ lines: string; next: number | null } | null> { 177 + if (this.logChars().entries === 0) return null; 178 + const { texts, next } = new SqliteLog(this.ctx.storage).page(from, limit); 179 + return { lines: texts.map((t) => `${t}\n`).join(""), next }; 182 + private wake(): void { 183 + const all = this.waiting; 185 + for (const w of all) w(); 189 + * GET feed?from=&wait=<seconds, up to 25>: when nothing is new, hold the call until an entry is written or the wait 190 + * ends, then answer as usual. 192 + private async feed(name: string, body: unknown): Promise<Answer> { 193 + const q = (body ?? {}) as Record<string, string | undefined>; 194 + const wait = Math.min(25, Math.max(0, Number(q.wait) || 0)); 195 + const first = await this.call(name, "feed", undefined, body, true); 196 + const from = Number(q.from) || 0; 197 + const empty = first.status === 200 && (first.body as { next: number }).next <= from; 198 + if (!empty || wait === 0) return first; 199 + await new Promise<void>((resolve) => { 200 + const timer = setTimeout(resolve, wait * 1000); 201 + this.waiting.push(() => { 202 + clearTimeout(timer); 206 + return this.call(name, "feed", undefined, body, true); 209 + /** One project call: the agent key (if any), the size caps, then answer() from worker/project/http.ts. */ 213 + agent: string | undefined, 218 + ): Promise<Answer> { 220 + const decided = await this.checkAgentKey(key.presented, agent, key.address); 221 + if (!decided.ok) return { status: decided.status, body: { error: decided.error } }; 222 + const allowed = keyAllows(decided.role, { write: key.write, agent, route: key.route }); 223 + if (!allowed.ok) return { status: allowed.status, body: { error: allowed.error } }; 226 + if (op === "feed" && !inFeed) return this.feed(name, body); 227 + if (SOFT_HELD_OPS.has(op)) { 228 + const held = this.softHeld(); 229 + if (held) return { status: 507, body: { error: held } }; 231 + const loaded = this.ensure(); 233 + const why = this.loadError instanceof Error ? this.loadError.message : String(this.loadError); 234 + return { status: 507, body: { error: `the project's log did not load: ${why}` } }; 236 + // Readers live in storage, not the log: a refused call writes nothing, so replay never needs them. 237 + const list = new Set((await this.ctx.storage.get<string[]>("readers")) ?? []); 238 + let changed = false; 239 + const readers: Readers = { 240 + has: (a) => list.has(a), 242 + if (on === list.has(a)) return; 243 + if (on) list.add(a); 244 + else list.delete(a); 247 + list: () => [...list].sort(), 249 + const before = loaded.exists() ? loaded.shared().version : -1; 250 + const logLength = () => (this.loaded as { logLength?: () => number } | undefined)?.logLength?.() ?? 0; 251 + const entriesBefore = logLength(); 252 + const a = answer(loaded, op, agent, body, readers, how); 253 + if (changed) await this.ctx.storage.put("readers", readers.list()); 254 + if (logLength() !== entriesBefore) this.wake(); 255 + if (a.status === 200 && op === "starting") a.body = await this.startingHooks(name, a.body); 256 + if (a.status === 200) a.body = this.withBlobSizes(op, a.body); 257 + const after = loaded.exists() ? loaded.shared().version : -1; 258 + if (a.status === 200 && after >= 0 && (op === "init" || after > before)) { 259 + // A new version of shared: push it out to Artifacts in the background. The alarm retries; the call never waits. 260 + await this.ctx.storage.put("name", name); 261 + if (artifactsOf(this.env)) await this.ctx.storage.setAlarm(Date.now()); 264 + artifactsOf(this.env) && 265 + Date.now() - this.gitCheckedAt > GIT_CHECK_MS && 266 + (await this.ctx.storage.get("name")) !== undefined && 267 + (await this.ctx.storage.getAlarm()) === null 269 + // While agents are working, the alarm also looks for plain-git pushes. 270 + await this.ctx.storage.setAlarm(Date.now()); 276 + * The engine's starting answer carries hooks for the issues code (a start note naming an issue began or ended). They 277 + * go to the project's IssueProject, and never to the client. A failed hook is logged and never fails the call. 279 + private async startingHooks(name: string, body: unknown): Promise<unknown> { 280 + const { hooks, ...rest } = body as { 282 + claim?: { issue: number; agent: string; change: number }; 283 + unclaim?: { issue: number; agent: string; change: number; done?: boolean; version?: number }; 286 + if (!hooks) return body; 287 + const issues = this.env.ISSUES_DO.get(this.env.ISSUES_DO.idFromName(name)) as unknown as IssueHooks; 288 + const tell = async (what: string, call: () => Promise<unknown> | undefined) => { 292 + console.log(JSON.stringify({ event: "issues-hook", what, project: name, error: String(e).slice(0, 200) })); 295 + const end = hooks.unclaim; 296 + if (end?.done && end.version !== undefined) { 297 + const version = end.version; 298 + await tell("done", () => issues.done?.(end.agent, end.issue, version)); 299 + } else if (end) await tell("unclaim", () => issues.unclaim?.(end.agent, end.issue)); 300 + const claim = hooks.claim; 301 + if (claim) await tell("claim", () => issues.claim?.(claim.agent, claim.issue, claim.change)); 305 + /** A folder's binary files count by their bytes, and a binary file says its size: the blob store knows both. */ 306 + private withBlobSizes(op: string, body: unknown): unknown { 307 + if (op === "tree" && Array.isArray((body as { entries?: unknown }).entries)) { 308 + const b = body as { entries: { bytes?: number; blobs?: string[] }[] }; 311 + entries: b.entries.map(({ blobs, ...e }) => 312 + blobs ? { ...e, bytes: (e.bytes ?? 0) + blobs.reduce((n, sha) => n + this.blobs.size(sha), 0) } : e, 316 + if (op === "file" && typeof (body as { blob?: unknown }).blob === "string") 317 + return { ...(body as object), size: this.blobs.size((body as { blob: string }).blob) }; 321 + // The push out to Artifacts, and plain-git pushes back in. 324 + * Takes in commits pushed to the project's repo with plain git: the ones above the server's last commit that 325 + * haven't been taken in yet. One run at a time; a call while a run is going gets that run's answer. 327 + gitSync(): Promise<{ head: string; commits: number; answer: unknown } | null> { 328 + this.gitSyncing ??= this.gitSyncOnce().finally(() => { 329 + this.gitSyncing = undefined; 331 + return this.gitSyncing; 334 + private async gitSyncOnce(): Promise<{ head: string; commits: number; answer: unknown } | null> { 335 + const artifacts = artifactsOf(this.env); 336 + if (!artifacts) return null; 337 + this.gitCheckedAt = Date.now(); 338 + const name = await this.ctx.storage.get<string>("name"); 339 + if (!name || !this.project.exists()) return null; 340 + const seen = await this.ctx.storage.get<string>("git:head"); 341 + const pushed = await this.ctx.storage.get<PushResult>("pushed"); 342 + const head = await remoteHead(artifacts, name); 343 + if (!head || head === seen || head === pushed?.commit) return null; 344 + const sharedBlobs = this.project.shared().blobs ?? {}; 345 + const found = await pushedSince( 349 + async (bytes) => (bytes.byteLength > BLOB_MAX ? null : this.blobs.putBytes(bytes)), 350 + (path) => sharedBlobs[path], 352 + if (!found || found.commits.length === 0) { 353 + if (found) await this.ctx.storage.put("git:head", found.head); 356 + let result: unknown; 358 + result = this.project.ingest({ author: found.author, base: found.base, commits: found.commits }, Date.now()); 360 + result = { error: e instanceof Error ? e.message : String(e) }; 363 + at: new Date().toISOString(), 365 + commits: found.commits.length, 367 + ...(found.tooBig.length ? { tooBig: found.tooBig } : {}), 369 + await this.ctx.storage.put({ "git:head": found.head, "git:last": taken }); 371 + if ((result as { landed?: boolean }).landed) await this.ctx.storage.setAlarm(Date.now()); 375 + /** Sets the alarm for `at` unless one is due sooner. */ 376 + private async soon(at: number): Promise<void> { 377 + const now = await this.ctx.storage.getAlarm(); 378 + if (now === null || now > at) await this.ctx.storage.setAlarm(at); 382 + * Plain-git pushes in first, so the push out builds on them; then shared out to the project's Artifacts repo, at 383 + * most once a minute, backing off on failure. Without an ARTIFACTS binding (local dev) it does nothing. 385 + async alarm(): Promise<void> { 386 + const artifacts = artifactsOf(this.env); 387 + if (!artifacts) return; 388 + const name = await this.ctx.storage.get<string>("name"); 389 + if (!name || !this.ensure()?.exists()) return; 390 + await this.gitSync().then( 391 + () => this.ctx.storage.delete("git:error"), 393 + this.ctx.storage.put("git:error", { 394 + at: new Date().toISOString(), 395 + error: e instanceof Error ? e.message : String(e), 398 + const shared = this.project.shared(); 399 + const done = await this.ctx.storage.get<PushResult>("pushed"); 400 + if (done && done.version >= shared.version) return; 401 + const pushedAt = (await this.ctx.storage.get<number>("pushedAt")) ?? 0; 402 + if (Date.now() - pushedAt < PUSH_EVERY_MS) { 403 + await this.soon(pushedAt + PUSH_EVERY_MS); 406 + let result: PushResult; 408 + result = await pushShared(artifacts, name, shared, (sha) => this.blobs.read(sha)); 410 + // Kept for /out, and tried again with a backoff of our own (a thrown alarm is retried only six times). 411 + const was = await this.ctx.storage.get<{ attempts?: number }>("pushError"); 412 + const attempts = (was?.attempts ?? 0) + 1; 413 + await this.ctx.storage.put("pushError", { 414 + version: shared.version, 415 + at: new Date().toISOString(), 417 + error: e instanceof Error ? e.message : String(e), 419 + await this.soon(Date.now() + Math.min(10 * 60_000, 15_000 * 2 ** Math.min(attempts - 1, 6))); 422 + await this.ctx.storage.put({ pushed: result, "git:head": result.commit, pushedAt: Date.now() }); 423 + await this.ctx.storage.delete("pushError"); 424 + // Another publish may have landed while this push ran. 425 + if (this.project.shared().version > result.version) await this.soon(Date.now() + PUSH_EVERY_MS); 428 + /** The push out: the repo, the last version pushed, and plain-git intake. */ 430 + const name = await this.ctx.storage.get<string>("name"); 431 + const p = this.ensure(); 433 + repo: name ? repoName(name) : null, 434 + artifacts: artifactsOf(this.env) ? "bound" : "unbound", 435 + version: p?.exists() ? p.shared().version : null, 436 + pushed: (await this.ctx.storage.get<PushResult>("pushed")) ?? null, 437 + error: (await this.ctx.storage.get("pushError")) ?? null, 439 + head: (await this.ctx.storage.get<string>("git:head")) ?? null, 440 + last: (await this.ctx.storage.get("git:last")) ?? null, 441 + error: (await this.ctx.storage.get("git:error")) ?? null, 446 + // Per-agent keys: the HMACs live here, one project's keys per object. 448 + private async keyState(): Promise<KeyState> { 449 + return (await this.ctx.storage.get<KeyState>("agent-keys")) ?? emptyKeyState(); 452 + async checkAgentKey(presented: string, agent: string | undefined, address: string) { 453 + const state = await this.keyState(); 454 + const decided = await checkKey(state, this.env.KEY_HMAC_SECRET, presented, agent, Date.now(), address); 455 + if (decided.dirty) await this.ctx.storage.put("agent-keys", state); 456 + if (!decided.ok) return decided; 457 + const row = state.rows.find((r) => r.id === decided.id); 458 + return { ...decided, agent: row?.agent ?? "" }; 461 + /** Issues a key. The returned key is the only copy. */ 462 + async issueAgentKey( 465 + expiresRaw: string | null, 467 + ): Promise<{ id: string; key: string; agent: string } | { error: string }> { 468 + const secret = this.env.KEY_HMAC_SECRET; 469 + if (!secret) return { error: "the key secret (KEY_HMAC_SECRET) is not set" }; 470 + const when = expiresAt(Date.now(), expiresRaw); 471 + if (typeof when !== "number") return { error: when.error }; 472 + const state = await this.keyState(); 473 + const issued = await issueKey(state, secret, agent, "admin", Date.now(), address, when, role); 474 + await this.ctx.storage.put("agent-keys", state); 478 + async revokeAgentKey(id: string, address: string): Promise<{ revoked: boolean }> { 479 + const secret = this.env.KEY_HMAC_SECRET; 480 + if (!secret) return { revoked: false }; 481 + const state = await this.keyState(); 482 + const revoked = revokeKey(state, id, Date.now(), await hmac(secret, address)); 483 + await this.ctx.storage.put("agent-keys", state); 487 + async listAgentKeys(agent?: string) { 488 + return listKeys(await this.keyState(), agent); 491 + // For the issues code (server/src/issues/). 493 + /** The project's agent names, for the ask seat check. None when there's no project. */ 494 + async agents(_project: string): Promise<string[]> { 495 + const p = this.ensure(); 496 + if (!p?.exists()) return []; 497 + return p.status().agents.map((a) => a.agent); 501 + * Issues news, delivered through the engine's announce path: each item goes to the agents whose start note names 502 + * its issue and to the known agents in `to`, never back to its writer. 504 + async news(_project: string, items: IssueNews[]): Promise<{ to: string[] }[]> { 505 + const p = this.ensure(); 506 + if (!p?.exists()) return items.map(() => ({ to: [] })); 507 + const engine = p as ProjectCalls & ProjectHistory; 508 + const out: { to: string[] }[] = []; 509 + for (const item of items) { 510 + const status = p.status() as { agents: { agent: string; starting?: { issue?: number } }[] }; 511 + const known = new Set(status.agents.map((a) => a.agent)); 512 + const to = new Set([ 513 + ...(item.issue !== null 514 + ? status.agents.filter((a) => a.starting?.issue === item.issue).map((a) => a.agent) 516 + ...(item.to ?? []).filter((t) => known.has(t)), 518 + to.delete(item.from); 519 + if (to.size === 0) { 520 + out.push({ to: [] }); 524 + engine.announce(item.from, item.text, [...to]); 525 + out.push({ to: [...to] }); 527 + console.log(JSON.stringify({ event: "issues-news", error: String(e).slice(0, 200) })); 528 + out.push({ to: [] }); --- /dev/null
+++ b/server/src/push.ts
@@ -0,0 +1,256 @@
1 + // Out to Artifacts (#8): shared's files as one git commit on main of the 2 + // project's repo, with the publish message and the agent as author. The repo 3 + // is created on first use. isomorphic-git works in an in-memory filesystem: 4 + // a depth-1 clone of main with nothing checked out, then a new tree from 5 + // shared's files that compresses and writes only what changed (abso issue 293). 6 + import git from "isomorphic-git"; 7 + import http from "isomorphic-git/http/web"; 8 + import type { FileModes } from "../../worker/project/project-api.ts"; 9 + import { MemoryFS } from "./memory-fs.ts"; 11 + export interface PushResult { 19 + /** New blob bytes per push before the push out splits into parts: Artifacts refuses a push much over 20 MB. */ 20 + const PUSH_BATCH = 16 * 1024 * 1024; 22 + /** A file as a tree entry holds it: its blob and its mode ("100644", "100755", "120000"). */ 23 + export interface TreeFile { 28 + /** Every file in a tree, and every folder's tree oid ("" is the root), read from tree objects only. */ 29 + export async function readTreeFiles( 34 + files = new Map<string, TreeFile>(), 35 + trees = new Map<string, string>(), 36 + ): Promise<{ files: Map<string, TreeFile>; trees: Map<string, string> }> { 37 + trees.set(prefix, oid); 38 + const { tree } = await git.readTree({ fs, dir, oid }); 39 + for (const e of tree) { 40 + const path = prefix === "" ? e.path : `${prefix}/${e.path}`; 41 + if (e.type === "tree") await readTreeFiles(fs, dir, e.oid, path, files, trees); 42 + else if (e.type === "blob") files.set(path, { oid: e.oid, mode: e.mode }); 44 + return { files, trees }; 48 + * A blob's git oid, with the platform's SHA-1 (abso issue 293): native and awaited, so hashing every file of a big 49 + * project neither burns the object's CPU in JavaScript nor holds its other requests back for long. 51 + export async function blobOid(bytes: Uint8Array): Promise<string> { 52 + const head = new TextEncoder().encode(`blob ${bytes.byteLength}\0`); 53 + const all = new Uint8Array(head.byteLength + bytes.byteLength); 55 + all.set(bytes, head.byteLength); 56 + const d = new Uint8Array(await crypto.subtle.digest("SHA-1", all)); 57 + return [...d].map((b) => b.toString(16).padStart(2, "0")).join(""); 60 + const parentOf = (path: string) => { 61 + const cut = path.lastIndexOf("/"); 62 + return cut < 0 ? "" : path.slice(0, cut); 66 + * The tree for `files`, written bottom up. A folder with nothing changed under it keeps its old tree oid (`before`), 67 + * so only the folders on a changed path are written again. 69 + export async function writeTrees( 72 + files: Map<string, TreeFile>, 73 + before: Map<string, string>, 74 + changed: Set<string>, 76 + const dirty = new Set<string>([""]); 77 + for (const path of changed) for (let d = parentOf(path); d !== ""; d = parentOf(d)) dirty.add(d); 78 + type Entry = { mode: string; oid: string; type: "blob" | "tree" }; 79 + const kids = new Map<string, Map<string, Entry>>([["", new Map()]]); 80 + const folder = (d: string) => { 83 + kids.set(d, (k = new Map())); 84 + if (d !== "") folder(parentOf(d)); 88 + for (const [path, f] of files) 89 + folder(parentOf(path)).set(path.slice(path.lastIndexOf("/") + 1), { ...f, type: "blob" }); 90 + // Deepest first, so a folder's subfolders have their oids before it is written. 91 + const depth = (d: string) => (d === "" ? 0 : d.split("/").length); 92 + const order = [...kids.keys()].sort((a, b) => depth(b) - depth(a)); 94 + for (const d of order) { 95 + const old = before.get(d); 97 + old !== undefined && !dirty.has(d) 99 + : await git.writeTree({ fs, dir, tree: [...kids.get(d)!].map(([path, e]) => ({ path, ...e })) }); 100 + if (d === "") root = oid; 101 + else folder(parentOf(d)).set(d.slice(d.lastIndexOf("/") + 1), { mode: "040000", oid, type: "tree" }); 107 + * A project's Artifacts repo: abso-<project>. Project names are letters, digits, ".", "_" and "-" (validName), which 108 + * repo names take as they are. 110 + export function repoName(project: string): string { 111 + return `abso-${project}`; 114 + /** The project one of our repos holds, or null for a repo that isn't ours. */ 115 + export function projectOfRepo(repo: string): string | null { 116 + return repo.startsWith("abso-") && repo.length > "abso-".length ? repo.slice("abso-".length) : null; 119 + /** The repo's remote and a write token good for `seconds`, creating the repo if it's new. */ 120 + export async function writeAccess( 121 + artifacts: Artifacts, 124 + ): Promise<{ remote: string; secret: string }> { 126 + using repo = await artifacts.get(name); 127 + const [info, token] = await Promise.all([repo.info(), repo.createToken("write", seconds)]); 128 + return { remote: info!.remote, secret: token.plaintext.split("?expires=")[0]! }; 130 + const created = await artifacts.create(name, { description: `abso project ${name}`, setDefaultBranch: "main" }); 131 + return { remote: created.remote, secret: created.token.split("?expires=")[0]! }; 135 + export interface SharedFiles { 137 + files: Record<string, string>; 139 + blobs?: Record<string, string>; 140 + last?: { agent: string; message: string }; 144 + * Shared's files as commits on top of `head` (null: a repo with no main yet), in the repo at `dir`. `part` is called 145 + * with each earlier part's commit when the new blobs are too big for one push. Answers the last commit and how many 148 + export async function commitShared( 151 + head: string | null, 152 + shared: SharedFiles, 153 + readBlob: (sha256: string) => Uint8Array | null, 154 + part: (commit: string) => Promise<void> = async () => {}, 155 + ): Promise<{ commit: string; changed: number }> { 157 + ? await readTreeFiles(fs, dir, (await git.readCommit({ fs, dir, oid: head })).commit.tree) 158 + : { files: new Map<string, TreeFile>(), trees: new Map<string, string>() }; 159 + const blobs = shared.blobs ?? {}; 160 + const now = new Map<string, TreeFile>(); 161 + const changed = new Set<string>(); 162 + for (const path of old.files.keys()) if (!(path in shared.files) && !(path in blobs)) changed.add(path); 163 + // A file whose blob and mode match the last push keeps its entry; only a new blob is compressed and written. 164 + const put = async (path: string, bytes: Uint8Array, mode: string, oid: string) => { 165 + const was = old.files.get(path); 166 + if (was?.oid !== oid) await git.writeBlob({ fs, dir, blob: bytes }); 167 + if (was?.oid !== oid || was.mode !== mode) changed.add(path); 168 + now.set(path, { oid, mode }); 170 + // Each file goes into the tree as a blob with its mode (#27): 100755 for exec, 120000 for a link, whose blob is 172 + const enc = new TextEncoder(); 173 + for (const [path, text] of Object.entries(shared.files)) { 174 + const mode = shared.modes?.[path]; 175 + const link = typeof mode?.link === "string" ? mode.link : null; 176 + const bytes = enc.encode(link ?? text); 177 + await put(path, bytes, link !== null ? "120000" : mode?.exec ? "100755" : "100644", await blobOid(bytes)); 179 + const agent = shared.last?.agent ?? "abso"; 180 + const author = { name: agent, email: `${agent}@abso.invalid` }; 181 + const committer = { name: "abso", email: "abso@abso.invalid" }; 182 + const say = (p: string) => `${shared.last?.message ?? "Start the project"}${p}\n\nabso-version: ${shared.version}\n`; 184 + // A part holds what's written so far, and the last push's entries for the binary files not reached yet. 185 + const commitNow = async (message: string) => { 186 + const files = new Map(now); 187 + for (const [path, f] of old.files) if (!files.has(path) && path in blobs) files.set(path, f); 188 + const tree = await writeTrees(fs, dir, files, old.trees, changed); 189 + parent = await git.commit({ 196 + parent: parent ? [parent] : [], 201 + // Binary files (#27) aren't in files: their bytes come from the blob store. 202 + // Artifacts refuses a push much over 20 MB, so when the new blobs add up 203 + // to more than PUSH_BATCH, the earlier ones go in commits of their own 204 + // first. Every part carries abso-version, so intake never takes them in. 207 + for (const [path, sha] of Object.entries(blobs)) { 208 + const bytes = readBlob(sha); 209 + if (!bytes) throw new Error(`${path}: blob ${sha} is missing from the project's store`); 210 + const oid = await blobOid(bytes); 211 + const fresh = old.files.get(path)?.oid !== oid; 212 + if (fresh && pending > 0 && pending + bytes.byteLength > PUSH_BATCH) { 213 + await part(await commitNow(say(` (part ${++parts})`))); 216 + if (fresh) pending += bytes.byteLength; 217 + await put(path, bytes, shared.modes?.[path]?.exec ? "100755" : "100644", oid); 219 + const commit = await commitNow(say(parts > 0 ? ` (part ${parts + 1}, last)` : "")); 220 + return { commit, changed: changed.size }; 223 + export async function pushShared( 224 + artifacts: Artifacts, 226 + shared: SharedFiles, 227 + /** A binary file's bytes by SHA-256 (#27), from the project's blob store. */ 228 + readBlob: (sha256: string) => Uint8Array | null = () => null, 229 + ): Promise<PushResult> { 230 + const t0 = Date.now(); 231 + const name = repoName(project); 232 + const { remote, secret } = await writeAccess(artifacts, name); 233 + const onAuth = () => ({ username: "x", password: secret }); 234 + let fs = new MemoryFS(); 235 + const dir = "/repo"; 236 + // A new repo has no main yet. isomorphic-git "clones" an empty repo without 237 + // an error but leaves HEAD on master, so check for main and start clean. 238 + // Nothing is checked out: the new tree is built from tree objects (293). 239 + const head = await git 240 + .clone({ fs, http, dir, url: remote, ref: "main", singleBranch: true, depth: 1, noCheckout: true, onAuth }) 241 + .then(() => git.resolveRef({ fs, dir, ref: "main" })) 243 + if (head === null) { 244 + fs = new MemoryFS(); 245 + await git.init({ fs, dir, defaultBranch: "main" }); 247 + const t1 = Date.now(); 248 + const push = () => git.push({ fs, http, dir, url: remote, ref: "main", remoteRef: "main", onAuth }); 249 + const { commit, changed } = await commitShared(fs, dir, head, shared, readBlob, async () => void (await push())); 250 + const t2 = Date.now(); 253 + `push ${project} v${shared.version}: clone ${t1 - t0} ms, files ${t2 - t1} ms (${changed} changed), push ${Date.now() - t2} ms`, 255 + return { repo: name, remote, commit, version: shared.version, ms: Date.now() - t0 }; --- /dev/null
+++ b/server/src/router.ts
@@ -0,0 +1,299 @@
1 + // The open server's router (index.ts is the Worker's entry). abso's open server: one Worker that anyone deploys to their own Cloudflare account (`cd server && npx wrangler 2 + // deploy`). Every project is a Durable Object named by the project's name; its shared is pushed out to an Artifacts 3 + // repo abso-<project>. The routes are the platform's core routes, so the stock client works against it: 5 + // GET /version the deployed version's tag; no token needed 6 + // /p/<project>/<read or init> init, status, log, show, file, blame, feed and the other reads (http.ts) 7 + // /p/<project>/a/<agent>/<op> an agent's calls: record, publish, sync, draft, land, announce, ... 8 + // GET /p/<project>/head shared's newest version, read from storage without loading the project 9 + // PUT|GET /p/<project>/blobs/<sha256> a binary file's bytes; a PUT whose bytes don't hash to the name is refused 10 + // GET /p/<project>/out the push out to Artifacts: repo, last version pushed, plain-git intake 11 + // POST /p/<project>/git-remote the repo's remote and a write token good for an hour, for plain git 12 + // POST /p/<project>/git-sync takes in commits pushed with plain git now (the alarm also does) 13 + // GET /p/<project>/export?from=&limit= the log as JSON lines, for backups 14 + // /issues/p/<project>/... issues, asks and news (issues-entry.ts) 15 + // GET|POST /admin/agent-keys?project= per-agent keys: list, or issue (?agent=&role=&expires=); POST .../revoke?id= 17 + // Every route but /version needs Authorization: Bearer <ABSO_TOKEN>, or an agent's key when AGENT_KEYS is on. With no 18 + // ABSO_TOKEN set, the server refuses every call. 20 + import { type Answer, validName } from "../../worker/project/http.ts"; 21 + import { artifactsOf, type Env, secret } from "./env.ts"; 22 + import type { IssuesAuth, issuesFetch } from "./issues-entry.ts"; 23 + import { isAgentKey, type KeyRole, keyAllows, keysEnabled, timingSame } from "./keys.ts"; 24 + import type { KeyForCall } from "./project-object.ts"; 25 + import { repoName, writeAccess } from "./push.ts"; 28 + "edit|record|publish|sync|draft|draft-sync|land|pluck|amend|diff|restore|drop|label|announce|news|note|note-close|move|starting|reader|files|status|unqueue"; 30 + "init|status|head|out|export|blobs/[^/]+|git-sync|git-remote|blame|why|tree|path|follow|collisions|draft-state|where|feed|drafts|diff|ribbon|position|changes|notes|change/[0-9]{1,12}|refusals|labels|files|announce|log|show|file|compare|visibility|ci|queue"; 32 + /** A project's routes: the project, the top-level route, and an agent's name and op under /a/. */ 33 + export const PROJECT_ROUTE = new RegExp(`^/p/([^/]+)/(${TOP_ROUTES}|a/([^/]+)/(${AGENT_OPS}))$`); 34 + /** Issues, asks and news: the project and the rest of the path, handed to the issues code. */ 35 + export const ISSUES_ROUTE = /^\/issues\/p\/([^/]+)(\/.*)?$/; 37 + /** Routes answered here or by a direct object method, not through the project call. */ 38 + const DIRECT = new Set(["head", "out", "export", "git-remote", "git-sync", "ci", "queue", "visibility"]); 39 + /** Reads whose query string is the call's body. */ 40 + const QUERY_READS = new Set([ 65 + const SHA = /^[0-9a-f]{64}$/; 67 + const json = (status: number, body: unknown) => 68 + Response.json(body, { status, headers: { "cache-control": "no-store" } }); 70 + /** Whether two secrets match, in constant time whatever their lengths: their SHA-256 digests are compared. */ 71 + export async function sameSecret(a: string, b: string): Promise<boolean> { 72 + const digest = async (s: string) => 73 + [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s)))] 74 + .map((n) => n.toString(16).padStart(2, "0")) 76 + return timingSame(await digest(a), await digest(b)); 79 + export type Caller = { kind: "token" } | { kind: "key"; presented: string }; 82 + * Who is calling: the shared token, or an agent key to be checked by its project. A Response is a refusal. With no 83 + * shared token set, everything is refused. 85 + export async function authorize(request: Request, env: Env): Promise<Caller | Response> { 86 + const shared = secret(env, "TOKEN"); 90 + "this server has no ABSO_TOKEN set, so it refuses every call; set one with npx wrangler secret put ABSO_TOKEN", 92 + const presented = (request.headers.get("authorization") ?? "").replace(/^Bearer /, ""); 93 + if (presented && isAgentKey(presented) && keysEnabled(env)) return { kind: "key", presented }; 94 + if (presented && (await sameSecret(presented, shared))) return { kind: "token" }; 95 + return json(401, { error: "missing or wrong token" }); 98 + /** The x-abso-admin header against ABSO_ADMIN_TOKEN, in constant time. */ 99 + async function isAdmin(request: Request, env: Env): Promise<boolean> { 100 + const token = secret(env, "ADMIN_TOKEN"); 101 + const sent = request.headers.get("x-abso-admin") ?? request.headers.get("x-avcs-admin"); 102 + return !!token && !!sent && (await sameSecret(sent, token)); 105 + const addressOf = (request: Request) => request.headers.get("cf-connecting-ip") ?? "unknown"; 106 + const projectObject = (env: Env, project: string) => env.PROJECT.get(env.PROJECT.idFromName(project)); 108 + /** Per-agent keys for one project: list (GET), issue (POST ?agent=&role=&expires=), revoke (POST .../revoke?id=). */ 109 + async function agentKeys(request: Request, env: Env, url: URL, caller: Caller): Promise<Response> { 110 + if (!keysEnabled(env)) 111 + return json(404, { error: "agent keys are off here: AGENT_KEYS=on and KEY_HMAC_SECRET turn them on" }); 112 + if (caller.kind !== "token") return json(401, { error: "missing or wrong token" }); 113 + if (!(await isAdmin(request, env))) return json(403, { error: "agent keys need x-abso-admin: <the admin token>" }); 114 + const project = url.searchParams.get("project") ?? ""; 115 + if (!validName(project)) return json(400, { error: "agent keys need ?project=<name>" }); 116 + const obj = projectObject(env, project); 117 + if (url.pathname === "/admin/agent-keys/revoke") { 118 + if (request.method !== "POST") return json(405, { error: "revoking a key is a POST" }); 119 + return json(200, await obj.revokeAgentKey(url.searchParams.get("id") ?? "", addressOf(request))); 121 + if (request.method === "GET") 122 + return json(200, { keys: await obj.listAgentKeys(url.searchParams.get("agent") ?? undefined) }); 123 + if (request.method !== "POST") return json(405, { error: "agent keys take GET or POST" }); 124 + const agent = url.searchParams.get("agent") ?? ""; 125 + if (!validName(agent)) return json(400, { error: "issuing a key needs ?agent=<name>" }); 126 + const role = url.searchParams.get("role") ?? "writer"; 127 + if (role !== "owner" && role !== "writer" && role !== "reader") 128 + return json(400, { error: "role is owner, writer or reader" }); 129 + const issued = await obj.issueAgentKey(agent, addressOf(request), url.searchParams.get("expires"), role); 130 + return "error" in issued ? json(400, issued) : json(200, issued); 133 + /** The engine's ci and queue reads, for a server with neither: empty, so status and log say nothing about them. */ 134 + const NO_CI = { latest: null, checked: null, running: null, red: null, behind: null }; 135 + const NO_QUEUE = { items: [], paused: null }; 137 + async function projectRoute( 142 + match: RegExpExecArray, 143 + ): Promise<Response> { 144 + const [, project, top, agent, op] = match as unknown as [ 151 + if (!validName(project)) return json(400, { error: "project names use letters, digits, '.', '_' and '-'" }); 152 + const obj = projectObject(env, project); 153 + const route = agent === undefined ? top : op; 154 + const write = request.method !== "GET" && request.method !== "HEAD"; 155 + const blob = top.startsWith("blobs/"); 156 + let keyForCall: KeyForCall | undefined; 157 + let how: string | undefined; 158 + if (caller.kind === "key") { 159 + if (DIRECT.has(top) || blob) { 160 + const decided = await obj.checkAgentKey(caller.presented, agent, addressOf(request)); 161 + if (!decided.ok) return json(decided.status, { error: decided.error }); 162 + const allowed = keyAllows(decided.role, { write, agent, route, method: request.method }); 163 + if (!allowed.ok) return json(allowed.status, { error: allowed.error }); 165 + } else keyForCall = { presented: caller.presented, address: addressOf(request), write, route }; 168 + if (top === "head") { 169 + if (request.method !== "GET") return json(405, { error: "head is a GET" }); 170 + const head = await obj.head(); 171 + return head ? json(200, head) : json(404, { error: "no such project; run init first" }); 173 + if (top === "out") return json(200, await obj.out()); 174 + if (top === "ci") return json(200, NO_CI); 175 + if (top === "queue") return json(200, NO_QUEUE); 176 + if (top === "visibility") { 177 + if (request.method !== "GET") 178 + return json(400, { error: "every project on this server is private: it answers only its token and keys" }); 179 + return json(200, { project, visibility: "private" }); 182 + const sha = top.slice("blobs/".length); 183 + if (!SHA.test(sha)) return json(400, { error: "a blob's name is its SHA-256 in lowercase hex" }); 184 + if (request.method === "PUT") { 185 + if (!request.body) return json(400, { error: "PUT the blob's bytes as the body" }); 186 + const a = (await obj.putBlob(sha, request.body)) as unknown as Answer; 187 + return json(a.status, a.body); 189 + if (request.method !== "GET") return json(405, { error: "blobs take GET or PUT" }); 190 + const bytes = await obj.getBlob(sha); 191 + if (!bytes) return json(404, { error: `no blob ${sha} in this project` }); 192 + return new Response(bytes, { 193 + headers: { "content-type": "application/octet-stream", "cache-control": "private, max-age=31536000, immutable" }, 196 + if (top === "export") { 197 + const from = Number(url.searchParams.get("from") ?? "0"); 198 + const limit = Number(url.searchParams.get("limit") ?? "500"); 199 + if (!Number.isInteger(from) || from < 0 || !Number.isInteger(limit) || limit < 1 || limit > 5000) 200 + return json(400, { error: "export takes ?from=<seq>&limit=<1-5000>" }); 201 + const page = await obj.exportLog(from, limit); 202 + if (page === null) return json(404, { error: "no such project; run init first" }); 203 + return new Response(page.lines, { 205 + "content-type": "application/x-ndjson", 206 + "x-abso-next": page.next === null ? "" : String(page.next), 207 + "cache-control": "no-store", 211 + if (top === "git-remote") { 212 + // For a person who works with plain git: clone, commit, push; the project takes the commits in. 213 + if (request.method !== "POST") return json(405, { error: "git-remote is a POST" }); 214 + const artifacts = artifactsOf(env); 215 + if (!artifacts) return json(501, { error: "this server has no Artifacts binding, so no git remote" }); 216 + if ((await obj.head()) === null) return json(404, { error: "no such project; run init first" }); 217 + const { remote, secret: token } = await writeAccess(artifacts, repoName(project), 3600); 218 + // The token goes in a header for each git call, never in the remote URL or a credential store. 219 + const header = `Authorization: Basic ${btoa(`x:${token}`)}`; 220 + const git = `git -c credential.helper= -c http.extraHeader="${header}"`; 226 + clone: `${git} clone ${remote}`, 227 + fetch: `${git} fetch`, 228 + push: `${git} push`, 231 + if (top === "git-sync") { 232 + if (request.method !== "POST") return json(405, { error: "git-sync is a POST" }); 234 + return json(200, { taken: await obj.gitSync() }); 236 + return json(502, { error: `could not read the project's repo: ${e instanceof Error ? e.message : String(e)}` }); 241 + if (request.method === "POST") { 242 + const text = await request.text(); 245 + body = JSON.parse(text); 247 + return json(400, { error: "the body must be JSON" }); 250 + } else if (request.method === "GET" && (QUERY_READS.has(route ?? "") || top.startsWith("change/"))) { 251 + body = Object.fromEntries(url.searchParams); 252 + } else return json(405, { error: `${route} is a POST` }); 253 + // Which client sent a recording goes in the log with it. 254 + if ((op === "edit" || op === "record") && body && typeof body === "object") { 255 + const client = request.headers.get("x-abso-client") ?? request.headers.get("x-avcs-client") ?? ""; 256 + const { client: _, ...rest } = body as Record<string, unknown>; 257 + body = { ...rest, ...(/^[\w.+-]{1,20}\/[\w.+-]{1,40}$/.test(client) ? { client } : {}) }; 260 + const a = (await obj.call(project, (op ?? top)!, agent, body, false, how, keyForCall)) as unknown as Answer; 261 + return json(a.status, a.body); 263 + const error = `the project object failed: ${e instanceof Error ? e.message : String(e)}`; 264 + console.error(`${project} ${op ?? top}: ${error}`); 265 + return json(500, { error }); 269 + /** One request. The issues code comes in as an argument, so this file loads without the Workers runtime (tests). */ 270 + export async function handle( 273 + ctx: ExecutionContext, 274 + issues: typeof issuesFetch, 275 + ): Promise<Response> { 276 + const url = new URL(request.url); 277 + if (url.pathname === "/version") return json(200, { commit: env.CF_VERSION_METADATA?.tag || null }); 278 + const caller = await authorize(request, env); 279 + if (caller instanceof Response) return caller; 280 + if (url.pathname === "/") 281 + return new Response("abso: agent-first version control. The API lives under /p/<project>.\n"); 282 + if (url.pathname === "/admin/agent-keys" || url.pathname === "/admin/agent-keys/revoke") 283 + return agentKeys(request, env, url, caller); 284 + const onIssues = ISSUES_ROUTE.exec(url.pathname); 286 + const project = decodeURIComponent(onIssues[1]!); 287 + if (!validName(project)) return json(400, { error: "project names use letters, digits, '.', '_' and '-'" }); 288 + let auth: IssuesAuth = { kind: "token" }; 289 + if (caller.kind === "key") { 290 + const decided = await projectObject(env, project).checkAgentKey(caller.presented, undefined, addressOf(request)); 291 + if (!decided.ok) return json(decided.status, { error: decided.error }); 292 + auth = { kind: "key", agent: decided.agent, role: decided.role as KeyRole }; 294 + return issues(request, env, ctx, { project, rest: onIssues[2] ?? "", auth }); 296 + const m = PROJECT_ROUTE.exec(url.pathname); 297 + if (!m) return json(404, { error: "no such route" }); 298 + return projectRoute(request, env, url, caller, m); --- /dev/null
+++ b/server/test/blobs.test.ts
@@ -0,0 +1,44 @@
1 + import assert from "node:assert/strict"; 2 + import { createHash } from "node:crypto"; 3 + import { before, describe, it } from "node:test"; 4 + import { BlobStore } from "../src/blobs.ts"; 5 + import { installDigestStream, memoryStorage, streamOf } from "./helpers.ts"; 7 + const sha = (text: string) => createHash("sha256").update(text).digest("hex"); 9 + describe("the blob store", () => { 10 + before(installDigestStream); 12 + it("keeps bytes whose SHA-256 is their name", async () => { 13 + const store = new BlobStore(memoryStorage()); 14 + const a = await store.put(sha("hello"), streamOf("hello")); 15 + assert.deepEqual(a, { status: 200, body: { sha256: sha("hello"), size: 5, stored: true } }); 16 + assert.equal(store.has(sha("hello")), true); 17 + assert.equal(new TextDecoder().decode(store.read(sha("hello"))!), "hello"); 18 + const again = await store.put(sha("hello"), streamOf("hello")); 19 + assert.equal((again.body as { stored: boolean }).stored, false); 22 + it("refuses bytes that hash to something else, and keeps nothing", async () => { 23 + const store = new BlobStore(memoryStorage()); 24 + const a = await store.put(sha("hello"), streamOf("goodbye")); 25 + assert.equal(a.status, 400); 26 + assert.match((a.body as { error: string }).error, new RegExp(`hash to ${sha("goodbye")}`)); 27 + assert.equal(store.has(sha("hello")), false); 28 + assert.equal(store.has(sha("goodbye")), false); 29 + assert.deepEqual(store.list("", 10), { blobs: [], next: null }); 32 + it("refuses a name that isn't a lowercase SHA-256", async () => { 33 + const store = new BlobStore(memoryStorage()); 34 + assert.equal((await store.put("abc", streamOf("x"))).status, 400); 35 + assert.equal((await store.put(sha("x").toUpperCase(), streamOf("x"))).status, 400); 38 + it("refuses a blob over the size cap", async () => { 39 + const store = new BlobStore(memoryStorage()); 40 + const a = await store.put(sha("too big"), streamOf("too big"), 3); 41 + assert.equal(a.status, 413); 42 + assert.equal(store.total(), 0); --- /dev/null
+++ b/server/test/e2e-transcript.md
@@ -0,0 +1,132 @@
1 + # End to end: the stock client against `wrangler dev --local` 3 + Server: `http://127.0.0.1:8799` (server/ in abso-core, run with `npx wrangler dev --local`, Artifacts off). 4 + Token: an invented local test token in `server/.dev.vars`, given to the client as `ABSO_TOKEN`. 5 + Project: `e2e-1791907434`. Folders are temporary, outside abso-core. Run 2026-10-13T16:03Z. 10 + (starter) $ abso init . --server http://127.0.0.1:8799 --project e2e-1791907434 --agent starter 11 + Created project e2e-1791907434 at version 0 from 3 text files in <temp>\starter. 12 + Wrote a starting .absoignore (Claude Code state and operating system files); edit it like .gitignore. 13 + No abso.json written: package.json gives no check or build to guess, so CI has nothing to run on each new version. To give it a check, push an abso.json like {"check": "npm test"} (abso ci --help says what it runs). 14 + This folder is agent starter. Settings are in .abso/config.json. 15 + Edits made by Claude Code reach the server through the abso mod, which isn't on this machine yet: node <abso-core>\client\install-mod.ts installs it, and new chats load it. Anything else: abso record. 20 + (alice) $ abso join e2e-1791907434 --agent alice --dir . --server http://127.0.0.1:8799 21 + Joined e2e-1791907434 as alice at version 0: wrote 3 files into <temp>\alice. 22 + Edits made by Claude Code reach the server through the abso mod, which isn't on this machine yet: node <abso-core>\client\install-mod.ts installs it, and new chats load it. Anything else: abso record. 27 + (bob) $ abso join e2e-1791907434 --agent bob --dir . --server http://127.0.0.1:8799 28 + Joined e2e-1791907434 as bob at version 0: wrote 3 files into <temp>\bob. 29 + Edits made by Claude Code reach the server through the abso mod, which isn't on this machine yet: node <abso-core>\client\install-mod.ts installs it, and new chats load it. Anything else: abso record. 33 + ## Both agents edit and push (different files) 36 + (alice) $ abso push -m Alice edits line two 37 + Recorded first: 1 changed (hello.txt). 43 + (bob) $ abso push -m Bob writes the notes 44 + Recorded first: 1 changed (notes.md). 45 + Pushed version 2. It went on top of version 1 (alice: "Alice edits line two"), which your folder doesn't have yet. Nothing of theirs was overwritten; run abso pull to see both. 49 + ## A collision: both change line four 53 + Pulled to version 2: 1 file updated, 0 deleted. 60 + Pulled to version 2: 1 file updated, 0 deleted. 66 + (alice) $ abso push -m Alice rewrites line four 67 + Recorded first: 1 changed (hello.txt). 73 + (bob) $ abso push -m Bob rewrites line four 74 + Recorded first: 1 changed (hello.txt). 75 + Not pushed: 1 collision with work pushed since your last pull. 78 + line four, as bob wants it 79 + theirs, by alice in version 3 ("Alice rewrites line four") (line 4): 80 + line four, as alice wants it 81 + Run abso pull: each of those files comes back holding both sides' lines, with no markers. Edit it to what it should be, then push again. 83 + alice pushed "Alice rewrites line four" (version 3), which changes hello.txt lines 4-4, where your draft also changes lines; run abso pull to see both versions. 91 + shared is at version 3. 92 + version 3 by alice, 2026-10-13 16:03 UTC: Alice rewrites line four 94 + version 2 by bob, 2026-10-13 16:03 UTC: Bob writes the notes 96 + version 1 by alice, 2026-10-13 16:03 UTC: Alice edits line two 98 + version 0 by init, 2026-10-13 16:03 UTC: Start the project 99 + 3 files: .absoignore, hello.txt, notes.md 105 + Project e2e-1791907434: shared is at version 3. This folder is bob, working in shared. Signed in with shared token. 106 + Everything in this folder is recorded. 108 + alice, base 3, 0 draft changes 109 + * bob, base 2, 1 draft change: hello.txt 110 + starter, base 0, 0 draft changes 115 + (alice) $ abso status 116 + Project e2e-1791907434: shared is at version 3. This folder is alice, working in shared. Signed in with shared token. 117 + Everything in this folder is recorded. 119 + * alice, base 3, 0 draft changes 120 + bob, base 2, 1 draft change: hello.txt 121 + starter, base 0, 0 draft changes 125 + ## Other checks against the same server, with curl 127 + - No token, or a wrong one: 401 `missing or wrong token`. `GET /version` answers without one. 128 + - Per-agent keys (`AGENT_KEYS=on`, a local `KEY_HMAC_SECRET`): `POST /admin/agent-keys` without `x-abso-admin` is 403; with it, a writer key for `carol` is issued and listed. Carol's key syncs as carol; as `dave` it is 403 `that key is not for this agent`; on another project, 403 `that key is not for this project`. 129 + - Blobs: a PUT whose bytes don't hash to the name is 400 `the bytes hash to …, not …`; the right hash is stored and read back; a name that isn't a SHA-256 is 400. 130 + - `GET head` answers `{version, at}` from storage. `GET feed?from=<end>&wait=3` holds for 3 seconds, then answers with no events. 131 + - `/issues/p/<project>/...` reaches the issues stand-in (404 `issues aren't on this server yet`) after auth. 132 + - `POST git-remote` with Artifacts off: 501 `this server has no Artifacts binding, so no git remote`. --- /dev/null
+++ b/server/test/engine-project.test.ts
@@ -0,0 +1,37 @@
1 + import assert from "node:assert/strict"; 2 + import { describe, it } from "node:test"; 3 + import { answer } from "../../worker/project/http.ts"; 4 + import { EngineProject, SqliteLog } from "../src/engine-project.ts"; 5 + import { memoryStorage } from "./helpers.ts"; 7 + describe("the engine over the object's SQLite log", () => { 8 + it("serves init, records and pushes through answer(), and holds a collision", () => { 9 + const storage = memoryStorage(); 10 + const p = EngineProject.open(storage); 11 + assert.equal(answer(p, "init", undefined, { files: { "a.txt": "one\ntwo\nthree\n" } }).status, 200); 12 + for (const agent of ["alice", "bob"]) assert.equal(answer(p, "sync", agent, {}).status, 200); 13 + answer(p, "record", "alice", { files: { "a.txt": "one\nTWO by alice\nthree\n" } }); 14 + answer(p, "record", "bob", { files: { "a.txt": "one\ntwo by bob\nthree\n" } }); 15 + const first = answer(p, "publish", "alice", { message: "Alice's two" }); 16 + assert.deepEqual(first, { status: 200, body: { ok: true, version: 1, changes: 1 } }); 17 + const second = answer(p, "publish", "bob", { message: "Bob's two" }).body as { ok: boolean; collisions: unknown[] }; 18 + assert.equal(second.ok, false); 19 + assert.equal(second.collisions.length, 1); 22 + it("loads the same project back from the log", () => { 23 + const storage = memoryStorage(); 24 + const p = EngineProject.open(storage); 25 + answer(p, "init", undefined, { files: { "a.txt": "one\n" } }); 26 + answer(p, "sync", "alice", {}); 27 + answer(p, "record", "alice", { files: { "a.txt": "one\ntwo\n" } }); 28 + answer(p, "publish", "alice", { message: "Add two" }); 29 + const again = EngineProject.open(storage); 30 + assert.equal(again.shared().version, 1); 31 + assert.equal(again.shared().files["a.txt"], "one\ntwo\n"); 32 + const log = new SqliteLog(storage); 33 + assert.equal(log.sharedVersion(), 1); 34 + assert.deepEqual(log.lastPublish()?.agent, "alice"); 35 + assert.equal(log.logSize().entries, log.seq()); --- /dev/null
+++ b/server/test/helpers.ts
@@ -0,0 +1,82 @@
1 + // Stand-ins for the Workers runtime in Node tests: a Durable Object's SQLite storage over node:sqlite, and the 2 + // DigestStream the blob store hashes uploads with. 4 + import { createHash } from "node:crypto"; 5 + import { DatabaseSync } from "node:sqlite"; 6 + import type { SqliteStorage } from "../src/engine-project.ts"; 8 + export function memoryStorage(): SqliteStorage & { db: DatabaseSync } { 9 + const db = new DatabaseSync(":memory:"); 14 + exec(query: string, ...bindings: unknown[]) { 15 + const statement = db.prepare(query); 16 + const args = bindings as never[]; 17 + const rows = statement.columns().length > 0 ? statement.all(...args) : (statement.run(...args), []); 18 + // Workers hands BLOB columns back as ArrayBuffers. 23 + Object.entries(r as Record<string, unknown>).map(([k, v]) => [ 25 + v instanceof Uint8Array ? v.buffer.slice(v.byteOffset, v.byteOffset + v.byteLength) : v, 32 + transactionSync<T>(fn: () => T): T { 33 + const name = `t${depth++}`; 34 + db.exec(`SAVEPOINT ${name}`); 37 + db.exec(`RELEASE ${name}`); 40 + db.exec(`ROLLBACK TO ${name}; RELEASE ${name}`); 49 + /** Workers' crypto.DigestStream, for the blob store's streaming hash. */ 50 + export function installDigestStream(): void { 51 + const c = (globalThis as unknown as { crypto: { DigestStream?: unknown } }).crypto; 52 + if (c.DigestStream) return; 53 + class DigestStream extends WritableStream<Uint8Array> { 54 + readonly digest: Promise<ArrayBuffer>; 55 + constructor(algorithm: string) { 56 + const hash = createHash(algorithm.replace("-", "").toLowerCase()); 57 + let done!: (b: ArrayBuffer) => void; 58 + const digest = new Promise<ArrayBuffer>((ok) => { 62 + write: (chunk) => void hash.update(chunk), 64 + const b = hash.digest(); 65 + done(b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength)); 68 + this.digest = digest; 71 + c.DigestStream = DigestStream; 74 + export function streamOf(text: string): ReadableStream<Uint8Array> { 75 + const bytes = new TextEncoder().encode(text); 76 + return new ReadableStream({ --- /dev/null
+++ b/server/test/push.test.ts
@@ -0,0 +1,68 @@
1 + import assert from "node:assert/strict"; 2 + import { describe, it } from "node:test"; 3 + import git from "isomorphic-git"; 4 + import { absoVersion } from "../src/ingest.ts"; 5 + import { MemoryFS } from "../src/memory-fs.ts"; 6 + import { commitShared, projectOfRepo, readTreeFiles, repoName } from "../src/push.ts"; 8 + describe("repo names", () => { 9 + it("names a project's Artifacts repo abso-<project>, and back", () => { 10 + assert.equal(repoName("game"), "abso-game"); 11 + assert.equal(repoName("my.site_2"), "abso-my.site_2"); 12 + assert.equal(projectOfRepo("abso-game"), "game"); 13 + assert.equal(projectOfRepo("avcs-game"), null); 14 + assert.equal(projectOfRepo("abso-"), null); 17 + it("reads the version a pushed commit carries, under either name", () => { 18 + assert.equal(absoVersion("Fix it\n\nabso-version: 12\n"), 12); 19 + assert.equal(absoVersion("Fix it\n\navcs-version: 7\n"), 7); 20 + assert.equal(absoVersion("a person's own commit"), undefined); 24 + describe("commitShared", () => { 25 + it("writes shared as a commit with its modes, then only what changed", async () => { 26 + const fs = new MemoryFS(); 28 + await git.init({ fs, dir, defaultBranch: "main" }); 29 + const noBlobs = () => null; 30 + const first = await commitShared( 36 + files: { "a.txt": "one\n", "run.sh": "echo hi\n", link: "" }, 37 + modes: { "run.sh": { exec: true }, link: { link: "a.txt" } }, 41 + assert.equal(first.changed, 3); 42 + const commit = (await git.readCommit({ fs, dir, oid: first.commit })).commit; 43 + assert.match(commit.message, /^Start the project\n\nabso-version: 0\n$/); 44 + const { files } = await readTreeFiles(fs, dir, commit.tree); 45 + assert.deepEqual(Object.fromEntries([...files].map(([p, f]) => [p, f.mode])), { 50 + const second = await commitShared( 56 + files: { "a.txt": "one\ntwo\n", "run.sh": "echo hi\n", link: "" }, 57 + modes: { "run.sh": { exec: true }, link: { link: "a.txt" } }, 58 + last: { agent: "alice", message: "Add two" }, 62 + assert.equal(second.changed, 1); 63 + const next = (await git.readCommit({ fs, dir, oid: second.commit })).commit; 64 + assert.equal(next.author.name, "alice"); 65 + assert.deepEqual(next.parent, [first.commit]); 66 + assert.equal(absoVersion(next.message), 1); --- /dev/null
+++ b/server/test/router.test.ts
@@ -0,0 +1,224 @@
1 + import assert from "node:assert/strict"; 2 + import { describe, it } from "node:test"; 3 + import type { Env } from "../src/env.ts"; 4 + import { authorize, handle, ISSUES_ROUTE, PROJECT_ROUTE, sameSecret } from "../src/router.ts"; 6 + const TOKEN = "test-token-for-the-router"; 8 + /** A project namespace whose objects record every call and answer what each test needs. */ 9 + function fakeEnv(extra: Partial<Env> = {}) { 10 + const calls: { project: string; method: string; args: unknown[] }[] = []; 11 + const object = (project: string) => 16 + (_t, method: string) => 17 + async (...args: unknown[]) => { 18 + calls.push({ project, method, args }); 19 + if (method === "call") return { status: 200, body: { op: args[1], agent: args[2], body: args[3] } }; 20 + if (method === "putBlob") return { status: 200, body: { stored: true } }; 21 + if (method === "head") return { version: 3, at: "now" }; 22 + if (method === "checkAgentKey") 23 + return { ok: true, id: "k_1", as: "key k_1", role: "writer", agent: "carol", dirty: false }; 24 + if (method === "issueAgentKey") return { id: "k_2", key: "abso_sk_new", agent: args[0] }; 30 + PROJECT: { idFromName: (n: string) => n, get: (id: string) => object(id) }, 31 + ISSUES_DO: { idFromName: (n: string) => n, get: () => ({}) }, 35 + return { env, calls }; 38 + const ctx = {} as ExecutionContext; 39 + const noIssues = async () => new Response("issues", { status: 299 }); 40 + const request = (path: string, init: RequestInit & { token?: string | null } = {}) => { 41 + const { token = TOKEN, ...rest } = init; 42 + const headers = new Headers(rest.headers); 43 + if (token) headers.set("authorization", `Bearer ${token}`); 44 + return new Request(`http://abso.test${path}`, { ...rest, headers }); 47 + describe("routes", () => { 48 + it("matches the project's top routes and an agent's ops", () => { 49 + assert.deepEqual(PROJECT_ROUTE.exec("/p/game/status")?.slice(1, 3), ["game", "status"]); 50 + assert.deepEqual(PROJECT_ROUTE.exec("/p/game/a/alice/publish")?.slice(1), [ 56 + assert.equal(PROJECT_ROUTE.exec("/p/game/change/12")?.[2], "change/12"); 57 + assert.equal(PROJECT_ROUTE.exec("/p/game/a/alice/run"), null, "boxes are not on the open server"); 58 + assert.equal(PROJECT_ROUTE.exec("/p/game/ci/log"), null, "nor CI's output"); 59 + assert.equal(PROJECT_ROUTE.exec("/p/game/members"), null); 60 + assert.deepEqual(ISSUES_ROUTE.exec("/issues/p/game/issues/4")?.slice(1), ["game", "/issues/4"]); 61 + assert.deepEqual(ISSUES_ROUTE.exec("/issues/p/game")?.slice(1), ["game", undefined]); 64 + it("sends an agent's op to the project's object, with the JSON body", async () => { 65 + const { env, calls } = fakeEnv(); 66 + const res = await handle( 67 + request("/p/game/a/alice/publish", { method: "POST", body: JSON.stringify({ message: "why" }) }), 72 + assert.equal(res.status, 200); 73 + assert.deepEqual(await res.json(), { op: "publish", agent: "alice", body: { message: "why" } }); 74 + assert.equal(calls[0]?.project, "game"); 77 + it("reads take their query as the body, and a read refuses a POST-only op as a GET", async () => { 78 + const { env } = fakeEnv(); 79 + const log = await handle(request("/p/game/log?limit=5"), env, ctx, noIssues); 80 + assert.deepEqual(await log.json(), { op: "log", body: { limit: "5" } }); 81 + const publish = await handle(request("/p/game/a/alice/publish"), env, ctx, noIssues); 82 + assert.equal(publish.status, 405); 85 + it("refuses a project name the engine wouldn't take", async () => { 86 + const { env, calls } = fakeEnv(); 87 + const res = await handle(request("/p/..bad/status"), env, ctx, noIssues); 88 + assert.equal(res.status, 400); 89 + assert.equal(calls.length, 0); 92 + it("answers head from the object, and ci and queue as empty", async () => { 93 + const { env } = fakeEnv(); 94 + assert.deepEqual(await (await handle(request("/p/game/head"), env, ctx, noIssues)).json(), { 98 + const ci = (await (await handle(request("/p/game/ci"), env, ctx, noIssues)).json()) as Record<string, unknown>; 99 + assert.equal(ci.red, null); 100 + assert.deepEqual(await (await handle(request("/p/game/queue"), env, ctx, noIssues)).json(), { 106 + it("checks a blob's name before its bytes go anywhere", async () => { 107 + const { env, calls } = fakeEnv(); 108 + const bad = await handle(request("/p/game/blobs/not-a-hash", { method: "PUT", body: "x" }), env, ctx, noIssues); 109 + assert.equal(bad.status, 400); 110 + const upper = await handle( 111 + request(`/p/game/blobs/${"A".repeat(64)}`, { method: "PUT", body: "x" }), 116 + assert.equal(upper.status, 400); 117 + assert.equal(calls.length, 0); 118 + const good = await handle( 119 + request(`/p/game/blobs/${"a".repeat(64)}`, { method: "PUT", body: "x" }), 124 + assert.equal(good.status, 200); 125 + assert.equal(calls[0]?.method, "putBlob"); 128 + it("hands /issues to the issues code with the rest of the path and who is calling", async () => { 129 + const { env } = fakeEnv(); 131 + const res = await handle(request("/issues/p/game/issues?open=1"), env, ctx, async (_r, _e, _c, where) => { 133 + return new Response("ok"); 135 + assert.equal(await res.text(), "ok"); 136 + assert.deepEqual(seen, { project: "game", rest: "/issues", auth: { kind: "token" } }); 139 + it("gives the issues code a key's agent and role", async () => { 140 + const { env } = fakeEnv({ AGENT_KEYS: "on", KEY_HMAC_SECRET: "s" }); 142 + await handle(request("/issues/p/game/issues", { token: "abso_sk_abc" }), env, ctx, async (_r, _e, _c, where) => { 144 + return new Response("ok"); 146 + assert.deepEqual(seen, { project: "game", rest: "/issues", auth: { kind: "key", agent: "carol", role: "writer" } }); 149 + it("answers /version without a token", async () => { 150 + const { env } = fakeEnv({ ABSO_TOKEN: undefined }); 151 + const res = await handle(request("/version", { token: null }), env, ctx, noIssues); 152 + assert.equal(res.status, 200); 156 + describe("auth", () => { 157 + it("refuses everything when no shared token is set", async () => { 158 + const { env, calls } = fakeEnv({ ABSO_TOKEN: undefined }); 159 + const res = await handle(request("/p/game/status", { token: "anything" }), env, ctx, noIssues); 160 + assert.equal(res.status, 503); 161 + assert.match(((await res.json()) as { error: string }).error, /no ABSO_TOKEN/); 162 + const empty = await authorize(request("/p/game/status", { token: null }), { ...env, ABSO_TOKEN: "" }); 163 + assert.ok(empty instanceof Response && empty.status === 503); 164 + assert.equal(calls.length, 0); 167 + it("refuses a missing or wrong token, and takes the right one", async () => { 168 + const { env, calls } = fakeEnv(); 169 + assert.equal((await handle(request("/p/game/status", { token: null }), env, ctx, noIssues)).status, 401); 170 + assert.equal((await handle(request("/p/game/status", { token: "wrong" }), env, ctx, noIssues)).status, 401); 171 + assert.equal((await handle(request("/p/game/status", { token: `${TOKEN}x` }), env, ctx, noIssues)).status, 401); 172 + assert.equal((await handle(request("/", { token: "wrong" }), env, ctx, noIssues)).status, 401); 173 + assert.equal(calls.length, 0); 174 + assert.equal((await handle(request("/p/game/status"), env, ctx, noIssues)).status, 200); 177 + it("takes the token under its old name, AVCS_TOKEN", async () => { 178 + const { env } = fakeEnv({ ABSO_TOKEN: undefined, AVCS_TOKEN: TOKEN }); 179 + assert.deepEqual(await authorize(request("/p/game/status"), env), { kind: "token" }); 182 + it("treats an agent key as a key only when keys are on", async () => { 183 + const off = fakeEnv(); 184 + const refused = await authorize(request("/p/game/status", { token: "abso_sk_abc" }), off.env); 185 + assert.ok(refused instanceof Response && refused.status === 401); 186 + const on = fakeEnv({ AGENT_KEYS: "on", KEY_HMAC_SECRET: "s" }); 187 + assert.deepEqual(await authorize(request("/p/game/status", { token: "abso_sk_abc" }), on.env), { 189 + presented: "abso_sk_abc", 193 + it("compares secrets whatever their lengths", async () => { 194 + assert.equal(await sameSecret("abc", "abc"), true); 195 + assert.equal(await sameSecret("abc", "abcd"), false); 196 + assert.equal(await sameSecret("", "abc"), false); 199 + it("issues agent keys only with the admin token beside the shared one", async () => { 200 + const { env, calls } = fakeEnv({ AGENT_KEYS: "on", KEY_HMAC_SECRET: "s", ABSO_ADMIN_TOKEN: "admin-secret" }); 201 + const path = "/admin/agent-keys?project=game&agent=carol"; 202 + assert.equal((await handle(request(path, { method: "POST" }), env, ctx, noIssues)).status, 403); 203 + const wrong = request(path, { method: "POST", headers: { "x-abso-admin": "nope" } }); 204 + assert.equal((await handle(wrong, env, ctx, noIssues)).status, 403); 205 + const key = request(path, { method: "POST", token: "abso_sk_abc", headers: { "x-abso-admin": "admin-secret" } }); 206 + assert.equal((await handle(key, env, ctx, noIssues)).status, 401); 207 + assert.equal(calls.length, 0); 208 + const ok = request(path, { method: "POST", headers: { "x-abso-admin": "admin-secret" } }); 209 + const res = await handle(ok, env, ctx, noIssues); 210 + assert.equal(res.status, 200); 211 + assert.deepEqual(await res.json(), { id: "k_2", key: "abso_sk_new", agent: "carol" }); 214 + it("has no agent keys routes while keys are off", async () => { 215 + const { env } = fakeEnv({ ABSO_ADMIN_TOKEN: "admin-secret" }); 216 + const res = await handle( 217 + request("/admin/agent-keys?project=game", { headers: { "x-abso-admin": "admin-secret" } }), 222 + assert.equal(res.status, 404); --- /dev/null
+++ b/server/tsconfig.json
@@ -0,0 +1,17 @@
5 + "moduleResolution": "bundler", 9 + "allowImportingTsExtensions": true, 10 + "verbatimModuleSyntax": true, 11 + "erasableSyntaxOnly": true, 12 + "noUncheckedIndexedAccess": true, 13 + "skipLibCheck": true, 14 + "types": ["@cloudflare/workers-types", "node"] 16 + "include": ["src/**/*.ts", "test/**/*.ts"] --- /dev/null
+++ b/server/wrangler.jsonc
@@ -0,0 +1,33 @@
1 + // abso's open server: deploy it to your own Cloudflare account with `npx wrangler deploy` from this folder, after 2 + // `npx wrangler secret put ABSO_TOKEN`. Without that secret the server refuses every call. Local development: 3 + // `npx wrangler dev --local` (or `npm run dev`), with ABSO_TOKEN=<anything> in .dev.vars (never recorded: .absoignore 4 + // leaves it out). Keep --local: Artifacts is a remote binding, and without it wrangler dev connects to your account. 5 + // Put ABSO_ARTIFACTS=off in .dev.vars too: --local still binds Artifacts, but nothing local can reach it. 7 + "$schema": "./node_modules/wrangler/config-schema.json", 9 + "main": "src/index.ts", 10 + "compatibility_date": "2026-10-01", 11 + "compatibility_flags": ["nodejs_compat"], 13 + "observability": { "enabled": true }, 14 + // CPU per request: 2 minutes, not the default 30 seconds, so a heavy push finishes instead of resetting the 15 + // project's object. Billed only for CPU used. 16 + "limits": { "cpu_ms": 120000 }, 17 + // GET /version answers with the deployed version's tag. 18 + "version_metadata": { "binding": "CF_VERSION_METADATA" }, 20 + // Per-agent keys: on once KEY_HMAC_SECRET is set (npx wrangler secret put KEY_HMAC_SECRET). Until then, only 21 + // the shared token signs in. 24 + // Each project's shared is pushed out to its own repo, abso-<project>, in this namespace. 25 + "artifacts": [{ "binding": "ARTIFACTS", "namespace": "abso" }], 28 + { "name": "PROJECT", "class_name": "ProjectObject" }, 29 + { "name": "ISSUES_DO", "class_name": "IssueProject" } 32 + "migrations": [{ "tag": "v1", "new_sqlite_classes": ["ProjectObject", "IssueProject"] }]