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 | /**
* The access-control fold: control-plane ops → {mode, member set, pending
* requests, grants}. Deterministic on every replica: ops are sorted by
* (lamport clock, entry hash) and folded causally — each op is judged against
* the state folded so far, so racing approvals/removals converge identically
* everywhere.
*
* Trust rules (creatorPub comes from the URL fragment, so policy authority is
* a pure function of the link everyone already holds — no genesis-op race):
* - `mode` and `remove` fold ONLY when the hardened authorship binding
* attributes the entry to creatorPub
* - `approve` folds when its author is the creator or (approvals:"any", the
* default) any current member
* - the creator is always implicitly a member
* - X25519 certs are Ed25519-verified (async) before a grant is ever sealed
* to them; unverified certs simply never enter the fold
*
* This class is NOT the crypto boundary — a URL holder can append any control
* op — it only decides which ops MEAN anything. Content privacy rests on the
* vault secret + epoch keys (epoch.ts) that strangers never receive.
*/
import type { Box, Wrap } from "./protocol";
import type { LogEntryMeta } from "./log";
import { verifyXCert } from "./wrapbox";
export interface JoinRequest {
idPub: string;
name: string;
msg: string;
xPub: string;
ts: number;
clock: number;
}
export interface AccessState {
mode: "link" | "strict";
approvals: "any" | "creator";
epoch: number;
/** idPub → verified X25519 pub, for sealing future wraps. */
members: Map<string, string>;
removed: Set<string>;
pending: JoinRequest[];
/** Wraps addressed to `myIdPub`, newest epoch first. */
myWraps: { epoch: number; wrap: Wrap }[];
/** newEpoch → keychain box (opens E_{newEpoch-1} with E_newEpoch). */
chains: Map<number, Box>;
/** (clock, hash) of the op that switched to the current strict mode, for the content gate. */
strictSince: { clock: number; hash: string } | null;
}
type ControlT = "mode" | "cert" | "jreq" | "approve" | "deny" | "remove";
const CONTROL: ReadonlySet<string> = new Set(["mode", "cert", "jreq", "approve", "deny", "remove"]);
export function isControlOp(t: string): t is ControlT {
return CONTROL.has(t);
}
const PUB_RE = /^[A-Za-z0-9_-]{43}$/;
export class AccessFold {
#appSalt: string;
#creatorPub: string | null;
#myIdPub: string | null;
#entries: LogEntryMeta[] = [];
#seen = new Set<string>(); // entry hashes
// async cert verification cache: "idPub|xPub|sig" → verdict (undefined = in flight)
#certOk = new Map<string, boolean>();
state: AccessState = emptyState();
onChange: () => void = () => {};
constructor(appSalt: string, creatorPub: string | null, myIdPub: string | null) {
this.#appSalt = appSalt;
this.#creatorPub = creatorPub && PUB_RE.test(creatorPub) ? creatorPub : null;
this.#myIdPub = myIdPub;
}
get creatorPub(): string | null {
return this.#creatorPub;
}
/** Suffix-less links can never leave link mode. */
get strictCapable(): boolean {
return this.#creatorPub !== null;
}
ingest(e: LogEntryMeta): void {
if (!isControlOp(e.op.t) || this.#seen.has(e.hash)) return;
this.#seen.add(e.hash);
this.#entries.push(e);
// kick async signature checks for ops that carry an xPub binding
const op = e.op as { xPub?: string; xSig?: string };
if (typeof op.xPub === "string" && typeof op.xSig === "string" && e.from) {
this.#verifyCert(e.from, op.xPub, op.xSig);
}
this.refold();
this.onChange();
}
#verifyCert(idPub: string, xPub: string, xSig: string): void {
const key = `${idPub}|${xPub}|${xSig}`;
if (this.#certOk.has(key)) return;
this.#certOk.set(key, false); // pessimistic until proven
void verifyXCert(this.#appSalt, idPub, xPub, xSig).then((ok) => {
if (ok) {
this.#certOk.set(key, true);
this.refold();
this.onChange();
}
});
}
#certVerified(idPub: string, xPub: string, xSig: string): boolean {
return this.#certOk.get(`${idPub}|${xPub}|${xSig}`) === true;
}
/** Deterministic re-fold from scratch (the control plane is tiny). */
refold(): void {
const s = emptyState();
const creator = this.#creatorPub;
if (!creator) {
this.state = s;
return;
}
const denied = new Set<string>();
const reqs = new Map<string, JoinRequest>();
const isMember = (idPub: string): boolean => idPub === creator || s.members.has(idPub);
const sorted = [...this.#entries].sort((a, b) =>
a.clock !== b.clock ? a.clock - b.clock : a.hash < b.hash ? -1 : 1,
);
for (const e of sorted) {
const op = e.op;
switch (op.t) {
case "mode": {
if (e.from !== creator) break;
if (op.mode !== "link" && op.mode !== "strict") break;
const epoch = Number.isInteger(op.epoch) && op.epoch >= 1 && op.epoch <= 1_000_000 ? op.epoch : 1;
s.mode = op.mode;
s.approvals = op.approvals === "creator" ? "creator" : "any";
if (op.mode === "strict") {
if (epoch > s.epoch) s.epoch = epoch;
s.strictSince = { clock: e.clock, hash: e.hash };
if (op.chain && epoch >= 2) s.chains.set(epoch, op.chain);
} else {
s.strictSince = null;
}
this.#collectWraps(s, op.wraps, epoch);
break;
}
case "cert": {
if (!e.from || !PUB_RE.test(op.xPub ?? "")) break;
if (!this.#certVerified(e.from, op.xPub, op.xSig)) break;
// a member's cert refreshes their sealing key; a stranger's cert
// just sits there until an approve references them
if (s.members.has(e.from)) s.members.set(e.from, op.xPub);
else if (e.from === creator) s.members.set(e.from, op.xPub);
else s.pendingCerts.set(e.from, op.xPub);
break;
}
case "jreq": {
if (!e.from || !PUB_RE.test(op.xPub ?? "")) break;
if (!this.#certVerified(e.from, op.xPub, op.xSig)) break;
reqs.set(e.from, {
idPub: e.from,
name: String(op.name ?? "?").slice(0, 40),
// eslint-disable-next-line no-control-regex
msg: String(op.msg ?? "").replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 280),
xPub: op.xPub,
ts: typeof op.ts === "number" ? op.ts : 0,
clock: e.clock,
});
break;
}
case "approve": {
if (!e.from || !PUB_RE.test(op.to ?? "") || !PUB_RE.test(op.toX ?? "")) break;
if (!(e.from === creator || (s.approvals === "any" && isMember(e.from)))) break;
// creator approvals override a standing removal; member approvals don't
if (s.removed.has(op.to) && e.from !== creator) break;
s.removed.delete(op.to);
s.members.set(op.to, op.toX);
if (op.wrap && op.to === this.#myIdPub) {
const epoch = Number.isInteger(op.epoch) && op.epoch >= 1 ? op.epoch : 1;
s.myWraps.push({ epoch, wrap: op.wrap });
}
break;
}
case "deny": {
if (!e.from || !PUB_RE.test(op.to ?? "")) break;
if (!isMember(e.from)) break;
denied.add(op.to);
break;
}
case "remove": {
if (e.from !== creator || !PUB_RE.test(op.to ?? "")) break;
s.members.delete(op.to);
s.removed.add(op.to);
const epoch = Number.isInteger(op.epoch) && op.epoch >= 2 && op.epoch <= 1_000_000 ? op.epoch : 0;
if (epoch > 0) {
if (epoch > s.epoch) s.epoch = epoch;
if (op.chain) s.chains.set(epoch, op.chain);
this.#collectWraps(s, op.wraps, epoch);
}
break;
}
}
}
// pending = verified requests from non-members, minus denied/removed
s.pending = [...reqs.values()]
.filter((r) => !s.members.has(r.idPub) && r.idPub !== creator && !denied.has(r.idPub) && !s.removed.has(r.idPub))
.sort((a, b) => b.ts - a.ts)
.slice(0, 50);
s.myWraps.sort((a, b) => b.epoch - a.epoch);
this.state = s;
}
#collectWraps(s: AccessState, wraps: Wrap[] | undefined, epoch: number): void {
if (!Array.isArray(wraps) || !this.#myIdPub) return;
for (const w of wraps.slice(0, 128)) {
if (w && w.to === this.#myIdPub && typeof w.ct === "string") s.myWraps.push({ epoch, wrap: w });
}
}
}
interface FullState extends AccessState {
/** certs from identities that aren't members yet (jreq-less knock helpers). */
pendingCerts: Map<string, string>;
}
function emptyState(): FullState {
return {
mode: "link",
approvals: "any",
epoch: 0,
members: new Map(),
removed: new Set(),
pending: [],
myWraps: [],
chains: new Map(),
strictSince: null,
pendingCerts: new Map(),
};
}
|