@fleetmesh/leaf 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +103 -2
  2. package/dist/constants.d.ts +27 -0
  3. package/dist/constants.js +32 -0
  4. package/dist/descriptor.d.ts +29 -0
  5. package/dist/descriptor.js +73 -0
  6. package/dist/did.d.ts +59 -0
  7. package/dist/did.js +221 -0
  8. package/dist/didcomm.d.ts +59 -0
  9. package/dist/didcomm.js +176 -0
  10. package/dist/encoding.d.ts +14 -0
  11. package/dist/encoding.js +68 -0
  12. package/dist/event.d.ts +22 -0
  13. package/dist/event.js +42 -0
  14. package/dist/giftwrap.d.ts +29 -0
  15. package/dist/giftwrap.js +100 -0
  16. package/dist/index.d.ts +17 -0
  17. package/dist/index.js +20 -0
  18. package/dist/keys.d.ts +6 -0
  19. package/dist/keys.js +31 -0
  20. package/dist/mediation/leaf.d.ts +121 -0
  21. package/dist/mediation/leaf.js +238 -0
  22. package/dist/mediation/messages.d.ts +96 -0
  23. package/dist/mediation/messages.js +79 -0
  24. package/dist/negentropy.d.ts +81 -0
  25. package/dist/negentropy.js +352 -0
  26. package/dist/nip44.d.ts +18 -0
  27. package/dist/nip44.js +119 -0
  28. package/dist/pwa/browser-leaf.d.ts +15 -0
  29. package/dist/pwa/browser-leaf.js +91 -0
  30. package/dist/pwa/hub.d.ts +51 -0
  31. package/dist/pwa/hub.js +137 -0
  32. package/dist/pwa/store.d.ts +39 -0
  33. package/dist/pwa/store.js +157 -0
  34. package/dist/relay.d.ts +67 -0
  35. package/dist/relay.js +232 -0
  36. package/dist/seal.d.ts +56 -0
  37. package/dist/seal.js +146 -0
  38. package/dist/session.d.ts +75 -0
  39. package/dist/session.js +230 -0
  40. package/package.json +45 -4
  41. package/src/constants.ts +36 -0
  42. package/src/descriptor.ts +88 -0
  43. package/src/did.ts +222 -0
  44. package/src/didcomm.ts +196 -0
  45. package/src/encoding.ts +67 -0
  46. package/src/event.ts +56 -0
  47. package/src/giftwrap.ts +108 -0
  48. package/src/index.ts +20 -0
  49. package/src/keys.ts +33 -0
  50. package/src/mediation/leaf.ts +292 -0
  51. package/src/mediation/messages.ts +124 -0
  52. package/src/negentropy.ts +357 -0
  53. package/src/nip44.ts +110 -0
  54. package/src/pwa/browser-leaf.ts +99 -0
  55. package/src/pwa/hub.ts +173 -0
  56. package/src/pwa/store.ts +173 -0
  57. package/src/relay.ts +273 -0
  58. package/src/seal.ts +154 -0
  59. package/src/session.ts +255 -0
@@ -0,0 +1,357 @@
1
+ // Negentropy V1, the set reconciliation NIP-77 standardises (core
2
+ // fleetmesh_core/storage/negentropy.py, after
3
+ // negentropy/docs/negentropy-protocol-v1.md).
4
+ //
5
+ // Two halves, and only one is normative:
6
+ //
7
+ // the wire format protocol byte 0x61, ranges of (upper bound, mode,
8
+ // payload), delta-encoded timestamps, minimal id
9
+ // prefixes. Implementations MUST agree byte for byte.
10
+ // the split how a differing range is divided and when to list ids
11
+ // instead. Any split interoperates while ranges stay
12
+ // adjacent and cover the space; ours is the reference's,
13
+ // so the two also agree on frames.
14
+ //
15
+ // Only the client learns anything. A leaf is always the client: it
16
+ // reconciles against its mediator without telling it what the phone holds.
17
+ import { sha256 } from '@noble/hashes/sha2.js';
18
+ import { concatBytes } from '@noble/curves/utils.js';
19
+ import { bytesToHex, hexToBytes, isHex } from './encoding.ts';
20
+
21
+ export const VERSION = 0x61;
22
+ export const VERSION_MIN = 0x60;
23
+ export const VERSION_MAX = 0x6f;
24
+ export const INFINITY = 2n ** 64n - 1n;
25
+ export const FINGERPRINT_BYTES = 16;
26
+ export const ID_BYTES = 32;
27
+ export const SKIP = 0, FINGERPRINT = 1, ID_LIST = 2;
28
+ export type Mode = typeof SKIP | typeof FINGERPRINT | typeof ID_LIST;
29
+
30
+ // Not normative: the reference's choices.
31
+ export const BUCKETS = 16;
32
+ export const LIST_THRESHOLD = BUCKETS * 2;
33
+
34
+ /** [timestamp, id hex]. Timestamps are unix seconds, so a number. */
35
+ export type Item = [number, string];
36
+
37
+ export class Malformed extends Error {}
38
+
39
+ /** Not an error on the wire: a server answers it with the version it speaks. */
40
+ export class UnsupportedVersion extends Error {
41
+ readonly version: number;
42
+ constructor(version: number) {
43
+ super('negentropy protocol version ' + (version - 0x60));
44
+ this.version = version;
45
+ }
46
+ }
47
+
48
+ // ------------------------------------------------------------------ varint --
49
+ /** Base-128, most significant digit first, high bit on all but the last. */
50
+ export function encodeVarint(n: bigint | number): Uint8Array {
51
+ let v = BigInt(n);
52
+ if (v < 0n) throw new RangeError('varints are unsigned');
53
+ if (v === 0n) return Uint8Array.of(0);
54
+ const out: number[] = [];
55
+ while (v) {
56
+ out.unshift(Number(v & 0x7fn));
57
+ v >>= 7n;
58
+ }
59
+ for (let i = 0; i < out.length - 1; i++) out[i]! |= 0x80;
60
+ return Uint8Array.from(out);
61
+ }
62
+
63
+ export function decodeVarint(buf: Uint8Array, i: number): [bigint, number] {
64
+ let n = 0n;
65
+ for (let k = 0; k < 10; k++) {
66
+ if (i >= buf.length) throw new Malformed('message ends inside a varint');
67
+ const b = buf[i++]!;
68
+ n = (n << 7n) | BigInt(b & 0x7f);
69
+ if (!(b & 0x80)) {
70
+ if (n > INFINITY) throw new Malformed('varint exceeds 64 bits');
71
+ return [n, i];
72
+ }
73
+ }
74
+ throw new Malformed('varint exceeds 64 bits');
75
+ }
76
+
77
+ // ------------------------------------------------------------- fingerprint --
78
+ /** SHA256(sum of ids as 32-byte little-endian uints mod 2^256 || varint(count))[:16]. */
79
+ export function fingerprintOf(ids: Iterable<Uint8Array>): Uint8Array {
80
+ const acc = new Uint8Array(32);
81
+ let count = 0;
82
+ for (const id of ids) {
83
+ if (id.length !== ID_BYTES) throw new Malformed('an id is 32 bytes');
84
+ let carry = 0;
85
+ for (let j = 0; j < 32; j++) {
86
+ const s = acc[j]! + id[j]! + carry;
87
+ acc[j] = s & 0xff;
88
+ carry = s >> 8;
89
+ }
90
+ count++;
91
+ }
92
+ return sha256(concatBytes(acc, encodeVarint(count))).slice(0, FINGERPRINT_BYTES);
93
+ }
94
+
95
+ /** The hex fingerprint of hex ids, as replication.fingerprint spells it. */
96
+ export const fingerprint = (ids: Iterable<string>): string => bytesToHex(fingerprintOf([...ids].map(hexToBytes)));
97
+
98
+ // ------------------------------------------------------------------- bound --
99
+ /** An exclusive upper bound: a timestamp and a disambiguating id prefix.
100
+ * Omitted trailing prefix bytes are zero. */
101
+ export interface Bound { timestamp: bigint; prefix: Uint8Array }
102
+
103
+ export const bound = (timestamp: bigint | number, prefix: Uint8Array = new Uint8Array(0)): Bound =>
104
+ ({ timestamp: BigInt(timestamp), prefix });
105
+
106
+ function compareBytes(a: Uint8Array, b: Uint8Array): number {
107
+ const n = Math.min(a.length, b.length);
108
+ for (let i = 0; i < n; i++) if (a[i] !== b[i]) return a[i]! - b[i]!;
109
+ return a.length - b.length;
110
+ }
111
+
112
+ /** A bound against an item key: (timestamp, prefix padded to 32 with zeros). */
113
+ function compareBoundToKey(bd: Bound, ts: bigint, id: Uint8Array): number {
114
+ if (bd.timestamp !== ts) return bd.timestamp < ts ? -1 : 1;
115
+ for (let i = 0; i < ID_BYTES; i++) {
116
+ const p = i < bd.prefix.length ? bd.prefix[i]! : 0;
117
+ if (p !== id[i]) return p - id[i]!;
118
+ }
119
+ return 0;
120
+ }
121
+
122
+ /** The shortest bound separating two adjacent items: no prefix when the
123
+ * timestamps differ, else their common prefix plus one byte. */
124
+ export function minimalBound(prev: Item | null, item: Item): Bound {
125
+ if (prev === null || prev[0] !== item[0]) return bound(item[0]);
126
+ const a = hexToBytes(prev[1]), b = hexToBytes(item[1]);
127
+ let n = 0;
128
+ while (n < 32 && a[n] === b[n]) n++;
129
+ return bound(item[0], b.slice(0, n + 1));
130
+ }
131
+
132
+ // ----------------------------------------------------------------- message --
133
+ export type Range =
134
+ | { upper: Bound; mode: typeof SKIP }
135
+ | { upper: Bound; mode: typeof FINGERPRINT; payload: Uint8Array }
136
+ | { upper: Bound; mode: typeof ID_LIST; payload: string[] };
137
+
138
+ export function encodeMessage(ranges: Range[]): Uint8Array {
139
+ const parts: Uint8Array[] = [Uint8Array.of(VERSION)];
140
+ let prevTs = 0n;
141
+ for (const r of ranges) {
142
+ const { timestamp, prefix } = r.upper;
143
+ if (timestamp === INFINITY) parts.push(encodeVarint(0));
144
+ else {
145
+ parts.push(encodeVarint(1n + timestamp - prevTs));
146
+ prevTs = timestamp;
147
+ }
148
+ parts.push(encodeVarint(prefix.length), prefix, encodeVarint(r.mode));
149
+ if (r.mode === FINGERPRINT) parts.push(r.payload);
150
+ else if (r.mode === ID_LIST) {
151
+ parts.push(encodeVarint(r.payload.length));
152
+ for (const id of r.payload) parts.push(hexToBytes(id));
153
+ }
154
+ }
155
+ return concatBytes(...parts);
156
+ }
157
+
158
+ function take(buf: Uint8Array, i: number, n: number, what: string): [Uint8Array, number] {
159
+ if (i + n > buf.length) throw new Malformed(`message ends inside ${what}: wanted ${n} bytes, ${buf.length - i} left`);
160
+ return [buf.slice(i, i + n), i + n];
161
+ }
162
+
163
+ /** Bytes to ranges, or an exception; never a partial parse. A bound after
164
+ * infinity is normalised to infinity, as the reference does. */
165
+ export function decodeMessage(buf: Uint8Array): Range[] {
166
+ if (!buf.length) throw new Malformed('empty message');
167
+ const v = buf[0]!;
168
+ if (v < VERSION_MIN || v > VERSION_MAX) throw new Malformed('not a negentropy message (first byte 0x' + v.toString(16).padStart(2, '0') + ')');
169
+ if (v !== VERSION) throw new UnsupportedVersion(v);
170
+ let i = 1, prevTs = 0n;
171
+ const out: Range[] = [];
172
+ while (i < buf.length) {
173
+ let enc: bigint, n: bigint, mode: bigint, prefix: Uint8Array;
174
+ [enc, i] = decodeVarint(buf, i);
175
+ let ts: bigint;
176
+ if (enc === 0n || prevTs === INFINITY) ts = prevTs = INFINITY;
177
+ // A delta may run past 64 bits; the reference reads that as a bound above
178
+ // every item rather than refusing it, and so does this.
179
+ else ts = prevTs = prevTs + enc - 1n;
180
+ [n, i] = decodeVarint(buf, i);
181
+ if (n > BigInt(ID_BYTES)) throw new Malformed(`bound prefix of ${n} bytes is longer than an id`);
182
+ [prefix, i] = take(buf, i, Number(n), 'a bound prefix');
183
+ [mode, i] = decodeVarint(buf, i);
184
+ const upper = { timestamp: ts, prefix };
185
+ if (mode === 0n) out.push({ upper, mode: SKIP });
186
+ else if (mode === 1n) {
187
+ let fp: Uint8Array;
188
+ [fp, i] = take(buf, i, FINGERPRINT_BYTES, 'a fingerprint');
189
+ out.push({ upper, mode: FINGERPRINT, payload: fp });
190
+ } else if (mode === 2n) {
191
+ let count: bigint;
192
+ [count, i] = decodeVarint(buf, i);
193
+ // Bounded by what is left, before anything is allocated for it.
194
+ if (count * BigInt(ID_BYTES) > BigInt(buf.length - i)) throw new Malformed('message ends inside an id list');
195
+ const ids: string[] = [];
196
+ for (let k = 0n; k < count; k++) {
197
+ let id: Uint8Array;
198
+ [id, i] = take(buf, i, ID_BYTES, 'an id list');
199
+ ids.push(bytesToHex(id));
200
+ }
201
+ out.push({ upper, mode: ID_LIST, payload: ids });
202
+ } else throw new Malformed(`unknown range mode ${mode}`);
203
+ }
204
+ return out;
205
+ }
206
+
207
+ /** Adjacent Skips are one Skip. */
208
+ function coalesceSkips(ranges: Range[]): Range[] {
209
+ const out: Range[] = [];
210
+ for (const r of ranges) {
211
+ if (r.mode === SKIP && out.length && out.at(-1)!.mode === SKIP) out[out.length - 1] = r;
212
+ else out.push(r);
213
+ }
214
+ return out;
215
+ }
216
+
217
+ const equalFp = (a: Uint8Array, b: Uint8Array) => a.length === b.length && a.every((x, i) => x === b[i]);
218
+
219
+ /** One side of a reconciliation over items sorted by (timestamp, id). */
220
+ export class Negentropy {
221
+ readonly items: Item[];
222
+ readonly isClient: boolean;
223
+ private readonly keys: [bigint, Uint8Array][];
224
+
225
+ constructor(items: Iterable<Item>, isClient = true) {
226
+ this.isClient = isClient;
227
+ const seen = new Set<string>();
228
+ const list: Item[] = [];
229
+ for (const [ts, id] of items) {
230
+ if (!Number.isSafeInteger(ts) || ts < 0) throw new RangeError('a timestamp is a non-negative integer');
231
+ if (!isHex(id, 64)) throw new RangeError('an id is 64 lowercase hex digits');
232
+ if (seen.has(id)) throw new RangeError('duplicate id ' + id.slice(0, 16));
233
+ seen.add(id);
234
+ list.push([ts, id]);
235
+ }
236
+ list.sort((a, b) => a[0] - b[0] || (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0));
237
+ this.items = list;
238
+ this.keys = list.map(([ts, id]) => [BigInt(ts), hexToBytes(id)]);
239
+ }
240
+
241
+ /** Index of the first item not below the bound. */
242
+ private bisect(bd: Bound): number {
243
+ let lo = 0, hi = this.keys.length;
244
+ while (lo < hi) {
245
+ const mid = (lo + hi) >> 1;
246
+ const [ts, id] = this.keys[mid]!;
247
+ if (compareBoundToKey(bd, ts, id) > 0) lo = mid + 1;
248
+ else hi = mid;
249
+ }
250
+ return lo;
251
+ }
252
+
253
+ private range(lower: Bound, upper: Bound): [number, number] {
254
+ return [this.bisect(lower), this.bisect(upper)];
255
+ }
256
+
257
+ private fp(lo: number, hi: number): Uint8Array {
258
+ return fingerprintOf(this.keys.slice(lo, hi).map((k) => k[1]));
259
+ }
260
+
261
+ /** Ranges covering [lower, upper): an id list when small, else sixteen
262
+ * fingerprinted buckets with the remainder spread over the first. An empty
263
+ * range is still answered. */
264
+ private split(lower: Bound, upper: Bound, out: Range[]): void {
265
+ const [lo, hi] = this.range(lower, upper);
266
+ const n = hi - lo;
267
+ if (n < LIST_THRESHOLD) {
268
+ out.push({ upper, mode: ID_LIST, payload: this.items.slice(lo, hi).map((i) => i[1]) });
269
+ return;
270
+ }
271
+ const per = Math.floor(n / BUCKETS), extra = n % BUCKETS;
272
+ let start = lo;
273
+ for (let b = 0; b < BUCKETS; b++) {
274
+ const end = start + per + (b < extra ? 1 : 0);
275
+ const upperB = end >= hi ? upper : minimalBound(this.items[end - 1]!, this.items[end]!);
276
+ out.push({ upper: upperB, mode: FINGERPRINT, payload: this.fp(start, end) });
277
+ start = end;
278
+ }
279
+ }
280
+
281
+ /** The client's opening message: the whole space, split. */
282
+ initiate(): Uint8Array {
283
+ if (!this.isClient) throw new Error('only the client initiates');
284
+ const out: Range[] = [];
285
+ this.split(bound(0), bound(INFINITY), out);
286
+ return encodeMessage(out);
287
+ }
288
+
289
+ /** Process one message: [reply or null, have, need]. have/need are only
290
+ * populated for the client; a null reply ends the protocol. */
291
+ reconcile(message: Uint8Array): [Uint8Array | null, string[], string[]] {
292
+ let ranges: Range[];
293
+ try {
294
+ ranges = decodeMessage(message);
295
+ } catch (e) {
296
+ if (e instanceof UnsupportedVersion && !this.isClient) return [Uint8Array.of(VERSION), [], []];
297
+ throw e;
298
+ }
299
+ const out: Range[] = [];
300
+ const have: string[] = [], need: string[] = [];
301
+ let lower = bound(0);
302
+ for (const r of ranges) {
303
+ const [lo, hi] = this.range(lower, r.upper);
304
+ if (r.mode === FINGERPRINT && !equalFp(this.fp(lo, hi), r.payload)) {
305
+ this.split(lower, r.upper, out);
306
+ } else if (r.mode === ID_LIST) {
307
+ const mine = this.items.slice(lo, hi).map((i) => i[1]);
308
+ if (this.isClient) {
309
+ const theirs = new Set(r.payload), ours = new Set(mine);
310
+ need.push(...[...theirs].filter((x) => !ours.has(x)).sort());
311
+ have.push(...[...ours].filter((x) => !theirs.has(x)).sort());
312
+ out.push({ upper: r.upper, mode: SKIP });
313
+ } else {
314
+ out.push({ upper: r.upper, mode: ID_LIST, payload: mine });
315
+ }
316
+ } else {
317
+ // Still said: ranges are adjacent, so a dropped one shifts the rest.
318
+ out.push({ upper: r.upper, mode: SKIP });
319
+ }
320
+ lower = r.upper;
321
+ }
322
+ const reply = coalesceSkips(out);
323
+ // A trailing Skip is implied by the reader; intermediate ones are not.
324
+ while (reply.length && reply.at(-1)!.mode === SKIP) reply.pop();
325
+ if (!reply.length) return [null, have, need];
326
+ return [encodeMessage(reply), have, need];
327
+ }
328
+ }
329
+
330
+ export interface ReconcileReport {
331
+ have: string[];
332
+ need: string[];
333
+ rounds: number;
334
+ bytesSent: number;
335
+ bytesReceived: number;
336
+ }
337
+
338
+ /** Run a whole reconciliation in process and report what it cost. */
339
+ export function reconcile(clientItems: Iterable<Item>, serverItems: Iterable<Item>, maxRounds = 32): ReconcileReport {
340
+ const client = new Negentropy(clientItems, true);
341
+ const server = new Negentropy(serverItems, false);
342
+ let msg: Uint8Array | null = client.initiate();
343
+ const have = new Set<string>(), need = new Set<string>();
344
+ let rounds = 0, sent = msg.length, received = 0;
345
+ while (msg !== null && rounds < maxRounds) {
346
+ rounds++;
347
+ const [reply] = server.reconcile(msg);
348
+ if (reply === null) break;
349
+ received += reply.length;
350
+ const [next, h, n] = client.reconcile(reply);
351
+ h.forEach((x) => have.add(x));
352
+ n.forEach((x) => need.add(x));
353
+ msg = next;
354
+ if (msg !== null) sent += msg.length;
355
+ }
356
+ return { have: [...have].sort(), need: [...need].sort(), rounds, bytesSent: sent, bytesReceived: received };
357
+ }
package/src/nip44.ts ADDED
@@ -0,0 +1,110 @@
1
+ // NIP-44 v2 (core fleetmesh_core/crypto/nip44.py): ChaCha20 with HMAC-SHA256
2
+ // in encrypt-then-MAC. The conversation key is HKDF-extract over the
3
+ // secp256k1 ECDH x-coordinate under the salt "nip44-v2"; per message,
4
+ // HKDF-expand under the 32-byte nonce yields the cipher key, the cipher nonce
5
+ // and the MAC key. Plaintext is length-prefixed and padded to a power-of-two
6
+ // schedule so message sizes leak less.
7
+ import { chacha20 } from '@noble/ciphers/chacha.js';
8
+ import { secp256k1 } from '@noble/curves/secp256k1.js';
9
+ import { expand, extract } from '@noble/hashes/hkdf.js';
10
+ import { hmac } from '@noble/hashes/hmac.js';
11
+ import { sha256 } from '@noble/hashes/sha2.js';
12
+ import { concatBytes, equalBytes, randomBytes } from '@noble/curves/utils.js';
13
+ import { base64 } from '@scure/base';
14
+ import { fromUtf8, hexToBytes, isHex, utf8 } from './encoding.ts';
15
+
16
+ export const VERSION = 2;
17
+ const SALT = utf8('nip44-v2');
18
+ export const MIN_PLAINTEXT = 1, MAX_PLAINTEXT = 65535;
19
+ export const MIN_PAYLOAD = 132, MAX_PAYLOAD = 87472;
20
+
21
+ export class Nip44Error extends Error {}
22
+
23
+ /** HKDF-extract(salt="nip44-v2", ikm=ECDH x-coordinate). Symmetric in the pair. */
24
+ export function conversationKey(secHex: string, pubHex: string): Uint8Array {
25
+ if (!isHex(secHex, 64, true)) throw new Nip44Error('a secret key is 32 bytes of hex');
26
+ const sk = hexToBytes(secHex.toLowerCase());
27
+ if (!secp256k1.utils.isValidSecretKey(sk)) throw new Nip44Error('secret key out of range');
28
+ if (!isHex(pubHex, 64, true)) throw new Nip44Error('a public key is 32 bytes of hex');
29
+ let shared: Uint8Array;
30
+ try {
31
+ shared = secp256k1.getSharedSecret(sk, hexToBytes('02' + pubHex.toLowerCase()));
32
+ } catch (e) {
33
+ throw new Nip44Error('public key is not a point on the curve: ' + (e as Error).message);
34
+ }
35
+ return extract(sha256, shared.subarray(1, 33), SALT);
36
+ }
37
+
38
+ /** [chachaKey, chachaNonce, hmacKey] = HKDF-expand(convKey, nonce, 76). */
39
+ export function messageKeys(convKey: Uint8Array, nonce: Uint8Array): [Uint8Array, Uint8Array, Uint8Array] {
40
+ if (nonce.length !== 32) throw new Nip44Error('nonce must be 32 bytes');
41
+ const k = expand(sha256, convKey, nonce, 76);
42
+ return [k.subarray(0, 32), k.subarray(32, 44), k.subarray(44, 76)];
43
+ }
44
+
45
+ /** The schedule alone; pad() enforces the 1..65535 limit. */
46
+ export function calcPaddedLen(n: number): number {
47
+ if (!Number.isSafeInteger(n) || n < 1) throw new Nip44Error('invalid plaintext length ' + n);
48
+ if (n <= 32) return 32;
49
+ const nextPower = 2 ** (Math.floor(Math.log2(n - 1)) + 1);
50
+ const chunk = nextPower <= 256 ? 32 : nextPower / 8;
51
+ return chunk * (Math.floor((n - 1) / chunk) + 1);
52
+ }
53
+
54
+ export function pad(plaintext: string | Uint8Array): Uint8Array {
55
+ const data = typeof plaintext === 'string' ? utf8(plaintext) : plaintext;
56
+ const n = data.length;
57
+ if (n < MIN_PLAINTEXT || n > MAX_PLAINTEXT) throw new Nip44Error('invalid plaintext length ' + n);
58
+ const out = new Uint8Array(2 + calcPaddedLen(n));
59
+ out[0] = n >> 8;
60
+ out[1] = n & 0xff;
61
+ out.set(data, 2);
62
+ return out;
63
+ }
64
+
65
+ export function unpad(padded: Uint8Array): Uint8Array {
66
+ if (padded.length < 2) throw new Nip44Error('invalid padding');
67
+ const n = (padded[0]! << 8) | padded[1]!;
68
+ if (n === 0 || n > MAX_PLAINTEXT || padded.length !== 2 + calcPaddedLen(n)) throw new Nip44Error('invalid padding');
69
+ return padded.slice(2, 2 + n);
70
+ }
71
+
72
+ export function encrypt(plaintext: string | Uint8Array, convKey: Uint8Array, nonce: Uint8Array = randomBytes(32)): string {
73
+ const [key, cnonce, macKey] = messageKeys(convKey, nonce);
74
+ const ciphertext = chacha20(key, cnonce, pad(plaintext));
75
+ const mac = hmac(sha256, macKey, concatBytes(nonce, ciphertext));
76
+ return base64.encode(concatBytes(Uint8Array.of(VERSION), nonce, ciphertext, mac));
77
+ }
78
+
79
+ /** [nonce, ciphertext, mac]. Every length check the NIP lists, before any crypto. */
80
+ export function decodePayload(payload: string): [Uint8Array, Uint8Array, Uint8Array] {
81
+ if (!payload) throw new Nip44Error('empty payload');
82
+ if (payload[0] === '#') throw new Nip44Error('unknown version');
83
+ if (payload.length < MIN_PAYLOAD || payload.length > MAX_PAYLOAD) throw new Nip44Error('invalid payload length ' + payload.length);
84
+ let data: Uint8Array;
85
+ try {
86
+ data = base64.decode(payload);
87
+ } catch {
88
+ throw new Nip44Error('payload is not base64');
89
+ }
90
+ if (data.length < 99 || data.length > 65603) throw new Nip44Error('invalid data length ' + data.length);
91
+ if (data[0] !== VERSION) throw new Nip44Error('unknown version ' + data[0]);
92
+ return [data.subarray(1, 33), data.subarray(33, -32), data.subarray(-32)];
93
+ }
94
+
95
+ export function decryptBytes(payload: string, convKey: Uint8Array): Uint8Array {
96
+ const [nonce, ciphertext, mac] = decodePayload(payload);
97
+ const [key, cnonce, macKey] = messageKeys(convKey, nonce);
98
+ // equalBytes is constant-time in the length it is given.
99
+ if (!equalBytes(mac, hmac(sha256, macKey, concatBytes(nonce, ciphertext)))) throw new Nip44Error('invalid MAC');
100
+ return unpad(chacha20(key, cnonce, ciphertext));
101
+ }
102
+
103
+ export function decrypt(payload: string, convKey: Uint8Array): string {
104
+ try {
105
+ return fromUtf8(decryptBytes(payload, convKey));
106
+ } catch (e) {
107
+ if (e instanceof Nip44Error) throw e;
108
+ throw new Nip44Error('plaintext is not UTF-8');
109
+ }
110
+ }
@@ -0,0 +1,99 @@
1
+ // A browser leaf in one call: the store, the session and the tab hub wired
2
+ // together the way the leaf profile wants them.
3
+ //
4
+ // - the leader tab opens the store, takes (or makes) the identity, restores
5
+ // grants and keylists, connects, asks for mediation only if it has none,
6
+ // and drains once;
7
+ // - it drains again whenever the app comes to the foreground, and when the
8
+ // service worker says a push arrived ("foreground networking, push to
9
+ // wake");
10
+ // - every drain is kept in the inbox and announced to every tab;
11
+ // - a dead socket is resumed on the next drain rather than redialled in a
12
+ // loop, because on a phone a dead socket usually means a locked screen.
13
+ import { LeafHub, type Leader } from './hub.ts';
14
+ import { type MediatorConfig, LeafStore } from './store.ts';
15
+ import { LeafSession } from '../session.ts';
16
+ import type { SocketFactory } from '../relay.ts';
17
+
18
+ export interface BrowserLeafOptions {
19
+ mediator: MediatorConfig;
20
+ name?: string;
21
+ dbName?: string;
22
+ socket?: SocketFactory;
23
+ timeoutMs?: number;
24
+ /** Drain when the page becomes visible. Default true. */
25
+ pickupOnVisible?: boolean;
26
+ }
27
+
28
+ /** The message a service worker posts to its clients when a push says there is mail. */
29
+ export const SW_PICKUP = 'fleetmesh-leaf:pickup';
30
+
31
+ export function startBrowserLeaf(opts: BrowserLeafOptions): LeafHub {
32
+ return new LeafHub({
33
+ ...(opts.name ? { name: opts.name } : {}),
34
+ lead: async (h) => {
35
+ const store = await LeafStore.open(opts.dbName);
36
+ void LeafStore.persist();
37
+ await store.saveMediator(opts.mediator);
38
+ const id = await store.identity();
39
+ const state = await store.state();
40
+ const session = new LeafSession({
41
+ nodeSk: id.nodeSk, agreementSk: id.agreementSk, mediator: opts.mediator,
42
+ ...(opts.socket ? { socket: opts.socket } : {}),
43
+ ...(opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}),
44
+ ...(state ? { state } : {}),
45
+ onState: (s) => void store.saveState(s),
46
+ });
47
+ try {
48
+ await session.start();
49
+ if (!session.client.isGranted(session.mediatorDid)) {
50
+ const r = await session.requestMediation();
51
+ if (r !== 'granted') throw new Error('the mediator denied mediation: ' + (session.client.denied.get(session.mediatorDid) ?? ''));
52
+ }
53
+ } catch (e) {
54
+ session.close();
55
+ store.close();
56
+ throw e;
57
+ }
58
+ let draining: Promise<unknown> | null = null;
59
+ // One drain at a time; a second trigger while one runs joins it.
60
+ const drain = () => {
61
+ draining ??= h.pickup().catch((e) => h.setStatus('offline', (e as Error).message)).finally(() => { draining = null; });
62
+ return draining;
63
+ };
64
+ const onVisible = () => { if (document.visibilityState === 'visible') void drain(); };
65
+ const onWorker = (e: MessageEvent) => { if (e.data === SW_PICKUP) void drain(); };
66
+ if (opts.pickupOnVisible ?? true) document.addEventListener('visibilitychange', onVisible);
67
+ navigator.serviceWorker?.addEventListener('message', onWorker);
68
+ // Drains run one after another. Two at once - the launch drain and a
69
+ // tab's request, say - would each be handed the same unacked batch.
70
+ let queue: Promise<unknown> = Promise.resolve();
71
+ const once = async () => {
72
+ if (!session.connected) {
73
+ h.setStatus('connecting');
74
+ await session.resume();
75
+ h.setStatus('connected');
76
+ }
77
+ // Only what the inbox did not already hold is news.
78
+ return store.addToInbox(await session.pickup());
79
+ };
80
+ // After the hub has the leader, not before: drain() goes through it.
81
+ const initTimer = setTimeout(() => void drain(), 0);
82
+ const leader: Leader = {
83
+ pickup: () => {
84
+ const p = queue.then(once);
85
+ queue = p.catch(() => {});
86
+ return p;
87
+ },
88
+ close: () => {
89
+ clearTimeout(initTimer);
90
+ document.removeEventListener('visibilitychange', onVisible);
91
+ navigator.serviceWorker?.removeEventListener('message', onWorker);
92
+ session.close();
93
+ store.close();
94
+ },
95
+ };
96
+ return leader;
97
+ },
98
+ });
99
+ }