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 | /**
* The home log ("selfroom"): one private E2E room shared by all devices that
* hold the same identity seed. Room secret: selfSecret = HKDF(idSeed,
* salt=APP_SALT, info="cp-self-room|v1") — docs/PROTOCOL.md §2.
*
* Since M3 the selfroom is just the PINNED room of the shared RoomHub
* (core/hub.ts): the hub owns the one shared libp2p node + Helia and the
* mailbox wiring; this class keeps its M1 public API (state fold, sync
* status, append helpers) on top of the hub's RoomHandle. Mailbox is the
* load-bearing transport; the hub's lazy live mesh (M3b) adds live OrbitDB
* replication on top whenever it happens to be up.
*/
import { APP_SALT } from "../config";
import { fromB64url, toB64url, type Bytes } from "../lib/crypto";
import type { Identity } from "../lib/identity";
import type { RoomLog } from "../lib/log";
import type { MailboxSync } from "../lib/mailbox";
import type { RelayConfig } from "../lib/descriptor";
import type { LogOp } from "../lib/protocol";
import { RoomHub, type RoomHandle, type RoomSyncState } from "./hub";
import {
HomeFold,
type ChatRegOp,
type ContactOp,
type GKeyOp,
type GMemberOp,
type GroupOp,
type HomeLang,
type HomeState,
type MCardOp,
type MLikeOp,
type ModSrcOp,
type ProfileSrcOp,
type RGrantOp,
type SettingsOp,
} from "./home-log";
const utf8 = (s: string): Bytes => new TextEncoder().encode(s) as Bytes;
/** selfSecret = HKDF-SHA256(ikm=idSeed, salt=APP_SALT, info="cp-self-room|v1"). */
export async function deriveSelfSecret(seedB64url: string): Promise<string> {
const seed = fromB64url(seedB64url);
if (seed.length !== 32) throw new Error("bad identity seed");
const ikm = await crypto.subtle.importKey("raw", seed as BufferSource, "HKDF", false, ["deriveBits"]);
const bits = await crypto.subtle.deriveBits(
{
name: "HKDF",
hash: "SHA-256",
salt: utf8(APP_SALT) as BufferSource,
info: utf8("cp-self-room|v1") as BufferSource,
},
ikm,
256,
);
return toB64url(new Uint8Array(bits));
}
/** M1 shape kept verbatim (profile tab reads it); now backed by RoomSyncState. */
export interface SyncStatus extends RoomSyncState {}
export class SelfRoom {
readonly log: RoomLog;
readonly mbx: MailboxSync | null;
readonly roomId: string;
/** The shared hub — pair/group rooms (ChatService) open through this. */
readonly hub: RoomHub;
#handle: RoomHandle;
#fold = new HomeFold();
#myPub: string;
#stopped = false;
/** Fired after any entry batch changed the folded state. */
onState: (s: HomeState) => void = () => {};
#stateListeners = new Set<(s: HomeState) => void>();
/** Fired whenever sync status might have changed (replay done, etc.). */
onSync: (s: SyncStatus) => void = () => {};
private constructor(hub: RoomHub, handle: RoomHandle, myPub: string) {
this.hub = hub;
this.#handle = handle;
this.log = handle.log;
this.mbx = handle.mbx;
this.roomId = handle.roomId;
this.#myPub = myPub;
}
get state(): HomeState {
return this.#fold.state;
}
get syncStatus(): SyncStatus {
return this.#handle.sync;
}
/**
* Boot the shared hub and open the pinned self room through it. Never
* blocks on the network: replay/flush run in the background after this
* resolves.
*/
static async start(identity: Identity, seed: string, relay: RelayConfig | null): Promise<SelfRoom> {
const selfSecret = await deriveSelfSecret(seed);
const hub = await RoomHub.start(identity, relay);
// callbacks fire before the room object exists — late-bound via holder
const holder: { room: SelfRoom | null } = { room: null };
const handle = await hub.openRoom(
"self",
selfSecret,
{
onEntry: (e) => {
if (holder.room) holder.room.#applyEntry(e, true);
},
onError: () => {}, // undecryptable garbage — expected noise, never fatal
onSync: (s) => {
if (holder.room) holder.room.#emitSync(s);
},
},
{ pinned: true },
);
const room = new SelfRoom(hub, handle, identity.publicKeyB64);
holder.room = room;
// Replay this device's own copy first (fully offline-capable). The home
// log is a STATE log: LWW keys older than any tail-N cutoff would vanish
// from the fold, so it must iterate the WHOLE log (OrbitDB's iterator
// treats `amount` as an upper bound, so Infinity yields every entry).
await handle.loadLocal(Infinity);
room.#emitState();
// … then catch up via the mailbox in the background (never blocks boot)
handle.startSync();
return room;
}
#applyEntry(e: { from: string; hash: string; op: LogOp }, notify: boolean): boolean {
// The selfroom is seed-holders-only, so every entry SHOULD be ours;
// defense-in-depth: fold only entries verifiably signed by my identity.
if (e.from !== this.#myPub) return false;
const changed = this.#fold.apply({ op: e.op, hash: e.hash });
if (changed && notify) this.#emitState();
return changed;
}
/**
* Additional folded-state listeners (views subscribe/unsubscribe as they
* mount/unmount); `onState` stays the boot wiring's single slot.
*/
onStateChanged(fn: (s: HomeState) => void): () => void {
this.#stateListeners.add(fn);
return () => this.#stateListeners.delete(fn);
}
#emitState(): void {
if (this.#stopped) return;
try {
this.onState(this.#fold.state);
} catch {}
for (const fn of this.#stateListeners) {
try {
fn(this.#fold.state);
} catch {}
}
}
#emitSync(s: SyncStatus): void {
if (this.#stopped) return;
try {
this.onSync(s);
} catch {}
}
/**
* Append a settings change (LWW singleton): merge the patch OVER the
* winning op's raw retained fields (HomeFold keeps unknown fields) so a
* client that only knows about lang round-trips future fields instead of
* clobbering them.
*
* `ts` defaults to now but callers that buffered the change (pendingLang)
* pass the click-time ts. Either way it is clamped monotonic above the
* current winning settings op — a device with a skew-ahead clock could
* otherwise pin settings forever (every honest write would lose the LWW).
*/
async setSettings(patch: { lang?: HomeLang; name?: string }, ts?: number): Promise<void> {
const stamped = Math.max(ts ?? Date.now(), this.#fold.settingsTs + 1);
const op: SettingsOp = { t: "settings", ...this.#fold.state.settings, ...patch, ts: stamped };
const hash = await this.#handle.append(op);
this.#fold.apply({ op, hash });
this.#emitState();
}
/**
* Append a contact/group/gmember/chatreg op. Callers own the LWW stamping
* discipline (services stamp strictly above the key's winner); settings go
* through setSettings, which owns the singleton's merge rules.
*/
async appendHomeOp(
op: ContactOp | GroupOp | GMemberOp | GKeyOp | RGrantOp | ChatRegOp | ProfileSrcOp | ModSrcOp | MCardOp | MLikeOp,
): Promise<void> {
const hash = await this.#handle.append(op);
this.#fold.apply({ op, hash });
this.#emitState();
}
/** Session teardown — stops the WHOLE hub (all rooms + the libp2p node). */
stop(): void {
this.#stopped = true;
this.hub.stop();
}
}
|