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 | /**
* Epoch keyring for strict (allow-list) boards.
*
* Strict content is double-sealed: an app-layer epoch AEAD (kBoard(n), derived
* from the 32-byte epoch secret E_n) inside the vault log's ordinary at-rest
* layers. Every removal / re-strict mints E_{n+1}; a keychain box (E_n sealed
* under kChain(n+1)) rides the control op, so a grant only ever delivers
* {secretV, E_current} and history unlocks by cascading backward.
*
* A removed member keeps the epochs it held (removal is not retraction) but
* can never open content sealed under later epochs.
*/
import { AtRestCipher, fromB64, randomBytes, toB64, toB64url, fromB64url, type Bytes } from "./crypto";
import type { Box, LogOp } from "./protocol";
const te = new TextEncoder();
const td = new TextDecoder();
const utf8 = (s: string): Bytes => te.encode(s) as Bytes;
/** {v: secretV, e: E_n, n: epoch} — the payload inside a Wrap. */
export interface Grant {
v: string; // vault secret, base64url 43ch
e: string; // epoch secret for epoch n
n: number;
}
export function encodeGrant(g: Grant): Bytes {
return utf8(JSON.stringify(g));
}
export function decodeGrant(b: Bytes): Grant | null {
try {
const g = JSON.parse(td.decode(b as Uint8Array)) as Grant;
if (typeof g?.v !== "string" || typeof g.e !== "string" || typeof g.n !== "number") return null;
if (!/^[A-Za-z0-9_-]{43}$/.test(g.v) || !/^[A-Za-z0-9_-]{43}$/.test(g.e)) return null;
return g;
} catch {
return null;
}
}
async function deriveGcm(ikmBytes: Bytes, appSalt: string, info: string): Promise<CryptoKey> {
const ikm = await crypto.subtle.importKey("raw", ikmBytes as BufferSource, "HKDF", false, ["deriveKey"]);
return crypto.subtle.deriveKey(
{ name: "HKDF", hash: "SHA-256", salt: utf8(appSalt) as BufferSource, info: utf8(info) as BufferSource },
ikm,
{ name: "AES-GCM", length: 256 },
false,
["encrypt", "decrypt"],
);
}
export class EpochKeyring {
#appSalt: string;
#roomId: string; // base room id — binds all access-layer AADs to the board
#secrets = new Map<number, Bytes>(); // epoch → E_n
#ops = new Map<number, AtRestCipher>(); // epoch → kBoard(n) cipher
#live = new Map<number, AtRestCipher>(); // epoch → kLive(n) cipher
current = 0;
constructor(appSalt: string, roomId: string) {
this.#appSalt = appSalt;
this.#roomId = roomId;
}
static newEpochSecret(): string {
return toB64url(randomBytes(32));
}
has(n: number): boolean {
return this.#secrets.has(n);
}
/** Install an epoch secret (from a grant or a keychain cascade). */
addEpoch(n: number, secretB64url: string): void {
if (this.#secrets.has(n)) return;
this.#secrets.set(n, fromB64url(secretB64url));
if (n > this.current) this.current = n;
}
epochSecret(n: number): string | null {
const s = this.#secrets.get(n);
return s ? toB64url(s) : null;
}
async #opCipher(n: number): Promise<AtRestCipher | null> {
const hit = this.#ops.get(n);
if (hit) return hit;
const s = this.#secrets.get(n);
if (!s) return null;
const c = new AtRestCipher(await deriveGcm(s, this.#appSalt, "board-op|v1"), utf8(`v1|${this.#roomId}|board|${n}`));
this.#ops.set(n, c);
return c;
}
async #liveCipher(n: number): Promise<AtRestCipher | null> {
const hit = this.#live.get(n);
if (hit) return hit;
const s = this.#secrets.get(n);
if (!s) return null;
const c = new AtRestCipher(await deriveGcm(s, this.#appSalt, "board-live|v1"), utf8(`v1|${this.#roomId}|blive|${n}`));
this.#live.set(n, c);
return c;
}
/** Seal an inner board op for the vault log under the current epoch. */
async sealOp(inner: LogOp): Promise<Extract<LogOp, { t: "sealed" }>> {
const c = await this.#opCipher(this.current);
if (!c) throw new Error("no epoch key");
const sealed = await c.seal(utf8(JSON.stringify(inner)));
// AtRestCipher envelope is [0x02|iv|ct]; store iv/ct split for JSON ops
return { t: "sealed", e: this.current, iv: toB64(sealed.slice(1, 13) as Bytes), ct: toB64(sealed.slice(13) as Bytes) };
}
/** Open a sealed vault op; null when we don't hold that epoch or on tamper. */
async openOp(op: { e: number; iv: string; ct: string }): Promise<LogOp | null> {
if (typeof op.e !== "number" || !Number.isInteger(op.e) || op.e < 1 || op.e > 1_000_000) return null;
const c = await this.#opCipher(op.e);
if (!c) return null;
const env = new Uint8Array(1 + 12 + fromB64(op.ct).length) as Bytes;
env[0] = 0x02;
env.set(fromB64(op.iv), 1);
env.set(fromB64(op.ct), 13);
const pt = await c.open(env);
if (!pt) return null;
try {
return JSON.parse(td.decode(pt as Uint8Array)) as LogOp;
} catch {
return null;
}
}
/** Seal a live payload (cursor/draw/drag) under the current epoch. */
async sealLive(payload: unknown): Promise<{ e: number; iv: string; ct: string } | null> {
const c = await this.#liveCipher(this.current);
if (!c) return null;
const sealed = await c.seal(utf8(JSON.stringify(payload)));
return { e: this.current, iv: toB64(sealed.slice(1, 13) as Bytes), ct: toB64(sealed.slice(13) as Bytes) };
}
async openLive(p: { e: number; iv: string; ct: string }): Promise<unknown | null> {
if (typeof p.e !== "number" || !Number.isInteger(p.e) || p.e < 1) return null;
const c = await this.#liveCipher(p.e);
if (!c) return null;
try {
const env = new Uint8Array(1 + 12 + fromB64(p.ct).length) as Bytes;
env[0] = 0x02;
env.set(fromB64(p.iv), 1);
env.set(fromB64(p.ct), 13);
const pt = await c.open(env);
return pt ? JSON.parse(td.decode(pt as Uint8Array)) : null;
} catch {
return null;
}
}
// ---- keychain: E_{n-1} sealed under kChain(n) ------------------------------
async #chainCipher(n: number): Promise<AtRestCipher | null> {
const s = this.#secrets.get(n);
if (!s) return null;
return new AtRestCipher(await deriveGcm(s, this.#appSalt, "keychain|v1"), utf8(`v1|${this.#roomId}|keychain|${n}`));
}
/** Build the keychain box for a NEW epoch n: seals E_{n-1} under kChain(n). */
async sealChain(newEpoch: number): Promise<Box> {
const prev = this.#secrets.get(newEpoch - 1);
const c = await this.#chainCipher(newEpoch);
if (!prev || !c) throw new Error("keychain needs both epochs");
const sealed = await c.seal(prev.slice() as Bytes);
return { iv: toB64(sealed.slice(1, 13) as Bytes), ct: toB64(sealed.slice(13) as Bytes) };
}
/**
* Cascade backward through keychain boxes: given chains[n] (opens E_{n-1}
* with E_n), unlock every reachable older epoch from what we hold.
*/
async cascade(chains: Map<number, Box>): Promise<void> {
for (let n = this.current; n > 1; n--) {
if (this.#secrets.has(n - 1)) continue;
const box = chains.get(n);
const c = await this.#chainCipher(n);
if (!box || !c) break;
try {
const env = new Uint8Array(1 + 12 + fromB64(box.ct).length) as Bytes;
env[0] = 0x02;
env.set(fromB64(box.iv), 1);
env.set(fromB64(box.ct), 13);
const prev = await c.open(env);
if (!prev || prev.length !== 32) break;
this.#secrets.set(n - 1, prev as Bytes);
} catch {
break;
}
}
}
}
|