1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554 | /**
* The room's replicated, encrypted, append-only log (OrbitDB events DB on
* Helia, PROTOCOL.md v2). This is the only module that touches @orbitdb/core.
*
* Address determinism: every member derives the same db name from the room
* secret and passes an identical access controller, so the manifest CID — and
* therefore the address — is equal for all of them with no exchange needed.
* Access control IS the encryption: write:["*"] plus decrypt-or-drop.
*
* History model: replication replaces v1's one-shot hist-req pull. Entries
* persist in the device blockstore (IndexedDB), so reopening a room offline
* replays it from disk, and any member's device serves late joiners.
*/
import { bitswap } from "@helia/block-brokers";
import { libp2pRouting } from "@helia/routers";
import { unixfs, type UnixFS } from "@helia/unixfs";
import { createHelia, type HeliaLibp2p } from "helia";
import { IDBBlockstore } from "blockstore-idb";
import { IDBDatastore } from "datastore-idb";
import * as dagPb from "@ipld/dag-pb";
import { fixedSize } from "ipfs-unixfs-importer/chunker";
import { CID } from "multiformats/cid";
import { base58btc } from "multiformats/bases/base58";
import {
createOrbitDB,
Entry,
Identities,
KeyStore,
type EventsDatabase,
type OrbitDBInstance,
type OrbitEntry,
} from "@orbitdb/core";
import { HardenedIPFSAccessController } from "./access";
import type { Libp2p } from "libp2p";
import type { AtRestCipher, Bytes, RoomCrypto } from "./crypto";
import { makeLogEncryption, type LogEncryption } from "./encryption";
import type { Identity } from "./identity";
import { registerSuetaProvider, SuetaIdentityProvider } from "./orbit-identity";
import type { LogOp } from "./protocol";
const IMG_MAX_BYTES = 2 * 1024 * 1024 + 1024; // re-encode cap + envelope slack
const DAG_PB = 0x70; // dag-pb multicodec (unixfs internal nodes; leaves are raw)
/** Outcome of feeding one mailbox-delivered entry into the log. */
export type IngestResult =
| "joined" // verified and in the log — will surface via emitUnseen()
| "duplicate" // already in the log
| "deferred" // an ancestor or identity block is not local yet — retry later
| "rejected"; // failed verification (signature/access/log id) — drop for good
export interface LogEntryMeta {
hash: string;
/**
* Verified author id: base64url Ed25519 pub for sueta identities, a stable
* per-device key for OrbitDB's default "publickey" identities, "" when the
* entry's signing key doesn't match its referenced identity (see #authorOf).
*/
from: string;
/** Lamport time, used only for folding reaction ops deterministically. */
clock: number;
op: LogOp;
}
/**
* One Helia node per session, shared across rooms; owns the IDB stores.
* Store names are app-supplied (derive them from your storage namespace —
* two apps on one origin must not share a blockstore: bitswap serves every
* local block to connected peers, and GC/quota would mix across apps).
*/
export async function openHelia(
libp2p: Libp2p,
stores: { blocks: string; data: string } = { blocks: "sueta-blocks", data: "sueta-data" },
): Promise<HeliaLibp2p> {
const blockstore = new IDBBlockstore(stores.blocks);
const datastore = new IDBDatastore(stores.data);
await blockstore.open();
await datastore.open();
// libp2p is created and owned by Net; Helia must not re-create or stop it.
// Bitswap-only, member↔member: Helia's DEFAULTS also race public HTTP
// gateways (trustless-gateway.link, 4everland.io) for every block — our
// blocks are ciphertext held only by members, so those requests would leak
// CIDs + client IPs to third parties for zero benefit. Never add them back.
return (await createHelia({
libp2p,
blockstore,
datastore,
blockBrokers: [bitswap()],
routers: [libp2pRouting(libp2p)],
start: true,
})) as HeliaLibp2p;
}
export class RoomLog {
#db: EventsDatabase;
#orbitdb: OrbitDBInstance;
#helia: HeliaLibp2p;
#fs: UnixFS;
#imgCipher: AtRestCipher;
#encryption: LogEncryption;
#authorCache = new Map<string, { id: string; publicKey: string }>(); // identity hash → record
#seen = new Set<string>();
/**
* Live + replicated entries, deduped by hash. Wired inside open() BEFORE
* replication starts — entries can arrive the moment sync.start() runs, and
* #emit marks hashes as seen, so a late-attached handler would lose them
* permanently. Pass both callbacks to RoomLog.open().
*/
onEntry: (e: LogEntryMeta) => void = () => {};
onError: (err: Error) => void = () => {};
/** Mailbox hooks (wired by room.ts when the feature is on; default no-ops). */
onAppended: (hash: string) => void = () => {};
onImageStored: (rootCid: string) => void = () => {};
/**
* When set, putImage chunks at this size so every unixfs block fits one
* mailbox frame. Only affects NEW images; the CID travels in the entry.
*/
imageChunkBytes: number | null = null;
private constructor(
db: EventsDatabase,
orbitdb: OrbitDBInstance,
helia: HeliaLibp2p,
imgCipher: AtRestCipher,
encryption: LogEncryption,
) {
this.#db = db;
this.#orbitdb = orbitdb;
this.#helia = helia;
this.#fs = unixfs(helia);
this.#imgCipher = imgCipher;
this.#encryption = encryption;
}
get address(): string {
return this.#db.address;
}
get myAuthorId(): string {
return this.#orbitdb.identity.id;
}
static async open(
helia: HeliaLibp2p,
rc: RoomCrypto,
identity: Identity | null,
hooks?: { onEntry?: (e: LogEntryMeta) => void; onError?: (err: Error) => void },
): Promise<RoomLog> {
// The directory embeds the salt-derived roomId, so it is already unique
// per app — no storage-namespace prefix needed (unlike openHelia's stores).
const directory = `sueta/${rc.roomId}`;
let identities: unknown;
let orbitIdentity: unknown;
if (identity) {
registerSuetaProvider();
const keystore = await KeyStore({ path: `${directory}/keystore` });
identities = await Identities({ ipfs: helia, keystore });
orbitIdentity = await (
identities as { createIdentity(o: Record<string, unknown>): Promise<unknown> }
).createIdentity({ provider: SuetaIdentityProvider({ identity }) });
}
const orbitdb = await createOrbitDB({
ipfs: helia,
directory,
...(identities ? { identities, identity: orbitIdentity } : {}),
});
const dbName = await rc.dbName();
const encryption = await makeLogEncryption(rc);
// sync:false → attach the error listener BEFORE any peer exchange can
// throw (a non-member's undecryptable garbage must never crash us)
// Hardened wrapper: same manifest address as the vanilla IPFS controller
// (only {type:"ipfs", write} is hashed), but forged-authorship entries —
// signed by one key while referencing another key's identity — are
// rejected at replication time. See lib/access.ts.
const db = await orbitdb.open(dbName, {
type: "events",
AccessController: HardenedIPFSAccessController({ write: ["*"] }),
encryption,
sync: false,
});
const log = new RoomLog(db, orbitdb, helia, await rc.imgCipher(), encryption);
if (hooks?.onEntry) log.onEntry = hooks.onEntry;
if (hooks?.onError) log.onError = hooks.onError;
db.events.on("error", (err) => log.onError(err));
db.events.on("update", (entry) => void log.#onUpdate(entry));
await db.sync.start();
return log;
}
#updateChain: Promise<void> = Promise.resolve();
/**
* 'update' fires once per new HEAD — a replicated branch join delivers many
* entries under one event. If the head links to entries we haven't emitted,
* sweep the log for stragglers (they're all in local storage by the time
* the event fires). Serialized so sweeps don't interleave.
*/
#onUpdate(entry: OrbitEntry): void {
this.#updateChain = this.#updateChain.then(async () => {
const missingLinks = (entry?.next ?? []).some((h) => !this.#seen.has(h));
if (missingLinks) await this.#sweepUnseen();
await this.#emit(entry);
});
}
async #sweepUnseen(): Promise<void> {
const unseen: OrbitEntry[] = [];
try {
for await (const e of this.#db.log.iterator({ amount: 500 })) {
if (!this.#seen.has(e.hash)) unseen.push(e);
}
} catch (err) {
this.onError(err as Error);
}
for (const e of unseen.reverse()) await this.#emit(e);
}
/**
* Surface entries added via ingestEntry — a direct joinEntry doesn't fire
* the 'update' event, so mailbox replay calls this once after its joins.
* Serialized on the same chain as live updates.
*/
emitUnseen(): Promise<void> {
this.#updateChain = this.#updateChain.then(() => this.#sweepUnseen());
return this.#updateChain;
}
async #emit(entry: OrbitEntry): Promise<void> {
if (!entry?.hash || this.#seen.has(entry.hash)) return;
this.#seen.add(entry.hash);
// the events DB wraps each value as {op:'ADD', key:null, value}
const wrapper = entry.payload as { op?: string; value?: unknown } | undefined;
const op = (wrapper && wrapper.op === "ADD" ? wrapper.value : wrapper) as LogOp;
if (!op || typeof op !== "object" || typeof (op as { t?: unknown }).t !== "string") return;
this.onEntry({
hash: entry.hash,
from: await this.#authorOf(entry),
clock: entry.clock?.time ?? 0,
op,
});
}
/**
* Durable author id of an entry, defense-in-depth on top of the hardened
* access controller: the binding only counts when the entry's signing key
* IS the referenced identity's key (lib/access.ts closes this at
* replication; here it also covers entries accepted by older clients).
* "sueta" identities yield the b64url Ed25519 pub (fingerprint/TOFU-able);
* OrbitDB's default "publickey" identities yield a stable per-device id so
* identity-less users still get working "mine" styling and reactions.
*/
async #authorOf(entry: OrbitEntry): Promise<string> {
const ref = entry.identity ?? "";
if (!ref || !entry.key) return "";
let rec = this.#authorCache.get(ref);
if (rec === undefined) {
try {
const ident = await this.#orbitdb.identities.getIdentity(ref);
rec =
ident && (ident.type === "sueta" || ident.type === "publickey")
? { id: ident.id, publicKey: ident.publicKey }
: { id: "", publicKey: "" };
} catch {
rec = { id: "", publicKey: "" };
}
this.#authorCache.set(ref, rec);
}
return rec.id && rec.publicKey === entry.key ? rec.id : "";
}
async append(op: LogOp): Promise<string> {
const hash = await this.#db.add(op);
try {
this.onAppended(hash);
} catch {} // mailbox enqueue must never fail an append
return hash;
}
/** Replay the newest `amount` entries from local storage (offline-capable). */
async loadTail(amount: number): Promise<number> {
const entries: OrbitEntry[] = [];
try {
for await (const e of this.#db.log.iterator({ amount })) entries.push(e);
} catch (err) {
this.onError(err as Error);
}
// iterator yields newest→oldest; emit oldest-first so the UI builds in order
for (const e of entries.reverse()) await this.#emit(e);
return entries.length;
}
// ---- images: encrypted unixfs blobs, replicated via bitswap --------------
async putImage(data: Bytes): Promise<{ cid: string; bytes: number }> {
const sealed = await this.#imgCipher.seal(data);
const cid = await this.#fs.addBytes(
sealed,
this.imageChunkBytes ? { chunker: fixedSize({ chunkSize: this.imageChunkBytes }) } : {},
);
try {
for await (const _ of this.#helia.pins.add(cid)) void _;
} catch {} // already pinned
try {
this.onImageStored(cid.toString());
} catch {}
return { cid: cid.toString(), bytes: sealed.length };
}
/** Fetch + decrypt an image blob (local blockstore or bitswap from members). */
async getImage(cidStr: string, signal?: AbortSignal): Promise<Bytes | null> {
try {
const cid = CID.parse(cidStr);
const parts: Uint8Array[] = [];
let total = 0;
for await (const chunk of this.#fs.cat(cid, { signal })) {
total += chunk.length;
if (total > IMG_MAX_BYTES) return null; // liar: bigger than protocol cap
parts.push(chunk);
}
const sealed = new Uint8Array(total);
let off = 0;
for (const p of parts) {
sealed.set(p, off);
off += p.length;
}
return await this.#imgCipher.open(sealed);
} catch {
return null;
}
}
/** Unpin images that fell out of the newest-N window; blocks GC'd next sweep. */
async pruneImages(keep: Set<string>, dropped: string[]): Promise<void> {
for (const cidStr of dropped) {
if (keep.has(cidStr)) continue;
try {
const cid = CID.parse(cidStr);
for await (const _ of this.#helia.pins.rm(cid)) void _;
} catch {} // not pinned here — fine
}
try {
await this.#helia.gc();
} catch {}
}
// ---- offline mailbox surface (PROTOCOL.md §9) -----------------------------
//
// Export: hand the orchestrator the exact stored bytes (sealed entry blocks,
// unixfs image blocks, this device's identity record). Import: verify and
// feed replayed blocks back in with the SAME guarantees as live replication
// (Entry.decode = decrypt-or-drop; joinEntry = signature + hardened access
// control), never letting a missing block reach a bitswap timeout.
/** Sealed (kEntry) block bytes of a local entry — byte-identical on every replica. */
async sealedEntryBytes(hash: string): Promise<Uint8Array | null> {
try {
return (await this.#db.log.storage.get(hash)) ?? null;
} catch {
return null;
}
}
/** This device's plaintext identity record block (sealed by the caller for transit). */
myIdentityBlock(): { cid: CID; bytes: Uint8Array } | null {
try {
const { hash, bytes } = this.#orbitdb.identity;
return { cid: CID.parse(hash, base58btc), bytes };
} catch {
return null;
}
}
/** A locally stored block, never touching bitswap; null when absent. */
async rawBlock(cid: CID): Promise<Uint8Array | null> {
try {
if (!(await this.#helia.blockstore.has(cid))) return null;
return await this.#helia.blockstore.get(cid);
} catch {
return null;
}
}
/**
* All blocks of a locally stored image DAG, children before parents (so a
* replayer that processes in order always has leaves before the root pin).
* [] when any block is missing or the DAG is deeper than unixfs produces
* at our chunk sizes (root + raw leaves).
*/
async imageDagBlocks(rootCid: string): Promise<{ cid: CID; bytes: Uint8Array }[]> {
const out: { cid: CID; bytes: Uint8Array }[] = [];
const walk = async (cid: CID, depth: number): Promise<boolean> => {
const bytes = await this.rawBlock(cid);
if (!bytes) return false;
if (cid.code === DAG_PB) {
if (depth >= 1) return false; // deeper than root+leaves — refuse, don't ship a partial DAG
let links: CID[];
try {
links = dagPb.decode(bytes).Links.map((l) => l.Hash);
} catch {
return false;
}
for (const l of links) if (!(await walk(l, depth + 1))) return false;
}
out.push({ cid, bytes });
return true;
};
try {
return (await walk(CID.parse(rootCid), 0)) ? out : [];
} catch {
return [];
}
}
/** Decode a sealed entry block; null on garbage (not a member's bytes / tampered). */
async decodeSealedEntry(bytes: Uint8Array): Promise<OrbitEntry | null> {
try {
const entry = await Entry.decode(bytes, this.#encryption.replication.decrypt, this.#encryption.data.decrypt);
return entry?.hash && Entry.isEntry(entry) ? entry : null;
} catch {
return null;
}
}
/** Store a sealed entry block (pinned via the oplog's IPFSBlockStorage). */
async putEntryBlock(hash: string, bytes: Uint8Array): Promise<void> {
await this.#db.log.storage.put(hash, bytes);
}
/** Store an image block; pinning happens per-DAG in pinImageIfLocal. */
async putRawBlock(cid: CID, bytes: Uint8Array): Promise<void> {
await this.#helia.blockstore.put(cid, bytes);
}
/** Store + pin an identity record block (tiny, link-free — the pin never leaves disk). */
async putIdentityBlock(cid: CID, bytes: Uint8Array): Promise<void> {
await this.#helia.blockstore.put(cid, bytes);
try {
for await (const _ of this.#helia.pins.add(cid)) void _;
} catch {} // already pinned
}
async hasEntry(hash: string): Promise<boolean> {
try {
return await this.#db.log.has(hash);
} catch {
return false;
}
}
/**
* Feed one decoded mailbox entry into the log. The local-only reachability
* pre-check mirrors joinEntry's traversal (next ∪ refs, stopping at entries
* already in the log) and additionally requires every hop's author identity
* block to be local — joinEntry's canAppend fetches it with a 30 s bitswap
* timeout otherwise. Anything not fully resolvable is "deferred" for retry;
* a throw past the pre-check is a verification failure ⇒ "rejected".
*/
async ingestEntry(entry: OrbitEntry): Promise<IngestResult> {
if (await this.hasEntry(entry.hash)) return "duplicate";
if (!(await this.#canJoinLocally(entry))) return "deferred";
try {
const added = await this.#db.log.joinEntry(entry);
return added ? "joined" : "duplicate";
} catch {
return "rejected";
}
}
async #canJoinLocally(entry: OrbitEntry): Promise<boolean> {
const visited = new Set<string>([entry.hash]);
const frontier: string[] = [];
const expand = async (e: OrbitEntry): Promise<boolean> => {
if (!(await this.#identityLocal(e))) return false;
for (const h of [...(e.next ?? []), ...(e.refs ?? [])]) {
if (!visited.has(h)) {
visited.add(h);
frontier.push(h);
}
}
return true;
};
if (!(await expand(entry))) return false;
while (frontier.length > 0) {
if (visited.size > 5000) return false; // runaway chain — let live replication carry it
const hash = frontier.pop()!;
if (await this.hasEntry(hash)) continue; // joined — its ancestry is in the log
let bytes: Uint8Array | null = null;
try {
bytes = await this.rawBlock(CID.parse(hash, base58btc));
} catch {}
if (!bytes) return false;
const e = await this.decodeSealedEntry(bytes);
if (!e || !(await expand(e))) return false;
}
return true;
}
/** Is the entry's identity record resolvable without the network? */
async #identityLocal(e: OrbitEntry): Promise<boolean> {
const ref = e.identity;
if (!ref) return false;
if (this.#authorCache.has(ref)) return true;
try {
return await this.#helia.blockstore.has(CID.parse(ref, base58btc));
} catch {
return false;
}
}
/**
* Display-only projection of an entry that can't be joined yet (missing
* ancestors). Same shape #emit produces; NOT marked seen, so a later real
* join still emits it (ChatStore dedups by hash).
*/
async entryMeta(entry: OrbitEntry): Promise<LogEntryMeta | null> {
const wrapper = entry.payload as { op?: string; value?: unknown } | undefined;
const op = (wrapper && wrapper.op === "ADD" ? wrapper.value : wrapper) as LogOp;
if (!op || typeof op !== "object" || typeof (op as { t?: unknown }).t !== "string") return null;
const from = (await this.#identityLocal(entry)) ? await this.#authorOf(entry) : "";
return { hash: entry.hash, from, clock: entry.clock?.time ?? 0, op };
}
/**
* Pin a mailbox-ingested image root once its whole DAG is local. Receivers
* never pin bitswap-fetched images (they can refetch from members), but a
* mailbox image may have NO online source — without the pin, pruneImages'
* gc would delete in-window blocks. The window's unpin path already covers
* these (pruneImages takes any CID).
*/
async pinImageIfLocal(rootCid: string): Promise<boolean> {
const blocks = await this.imageDagBlocks(rootCid); // [] unless fully local
if (blocks.length === 0) return false;
try {
for await (const _ of this.#helia.pins.add(CID.parse(rootCid))) void _;
} catch {} // already pinned
return true;
}
async close(): Promise<void> {
await this.#db.close().catch(() => {});
await this.#orbitdb.stop().catch(() => {});
}
/** Forget-room: drop the log's local data (entries, index, heads). */
async drop(): Promise<void> {
await this.#db.drop().catch(() => {});
await this.#orbitdb.stop().catch(() => {});
}
}
|