@conveno/cli 0.2.0-rc.17 → 0.2.0-rc.18

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.
@@ -1,793 +0,0 @@
1
- import { randomBytes as randomBytes$1 } from "@noble/ciphers/utils.js";
2
- import { equalBytes } from "@noble/curves/utils.js";
3
- import { sha256 } from "@noble/hashes/sha2.js";
4
- import { bytesToHex, concatBytes, utf8ToBytes } from "@noble/hashes/utils.js";
5
- import { Ln as DeviceId, _r as discriminatedUnion, br as object, hr as array, mr as _enum, vr as literal, xr as string, yr as number } from "./dist-Dc50_P_f.js";
6
- import { ed25519, x25519 } from "@noble/curves/ed25519.js";
7
- import { chacha20poly1305 } from "@noble/ciphers/chacha.js";
8
- import { expand, extract } from "@noble/hashes/hkdf.js";
9
- // ../crypto/dist/index.js
10
- /** Cryptographically secure random bytes (`crypto.getRandomValues`). */
11
- const randomBytes = (n) => randomBytes$1(n);
12
- /** Constant-time comparison of two byte arrays. */
13
- const bytesEqual = (a, b) => equalBytes(a, b);
14
- const sha256Bytes = (data) => sha256(data);
15
- const B64_RE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
16
- /** Standard base64 with padding. */
17
- function toBase64(bytes) {
18
- let s = "";
19
- for (let i = 0; i < bytes.length; i += 32768) s += String.fromCharCode(...bytes.subarray(i, i + 32768));
20
- return btoa(s);
21
- }
22
- /** Strict base64 decode: standard alphabet, padding required. Throws on anything else. */
23
- function fromBase64(s, expectedLength) {
24
- if (!B64_RE.test(s)) throw new CryptoError("bad_encoding", "Value is not valid base64.");
25
- const bin = atob(s);
26
- const out = new Uint8Array(bin.length);
27
- for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
28
- if (expectedLength !== void 0 && out.length !== expectedLength) throw new CryptoError("bad_encoding", `Expected ${expectedLength} bytes, got ${out.length} bytes.`);
29
- return out;
30
- }
31
- /** Big-endian unsigned integer of `len` bytes (RFC 8017 I2OSP). */
32
- function i2osp(n, len) {
33
- if (!Number.isSafeInteger(n) || n < 0) throw new RangeError("i2osp: not a non-negative integer");
34
- const out = new Uint8Array(len);
35
- let v = n;
36
- for (let i = len - 1; i >= 0; i--) {
37
- out[i] = v % 256;
38
- v = Math.floor(v / 256);
39
- }
40
- if (v !== 0) throw new RangeError("i2osp: integer too large");
41
- return out;
42
- }
43
- /**
44
- * Unambiguous encoding of a list of fields for signing and hashing: each field is a 4-byte
45
- * big-endian length followed by its bytes. Strings are UTF-8. Two different field lists never
46
- * encode to the same bytes, so a signature over one cannot be replayed as a signature over another.
47
- */
48
- function encodeFields(...fields) {
49
- const parts = [];
50
- for (const f of fields) {
51
- const b = typeof f === "string" ? utf8ToBytes(f) : typeof f === "number" ? i2osp(f, 8) : f;
52
- parts.push(i2osp(b.length, 4), b);
53
- }
54
- return concatBytes(...parts);
55
- }
56
- /** Every verification failure in this package. `code` is stable; `message` is for people. */
57
- var CryptoError = class extends Error {
58
- code;
59
- constructor(code, message) {
60
- super(message);
61
- this.code = code;
62
- this.name = "CryptoError";
63
- }
64
- };
65
- const Key32 = string().regex(/^[A-Za-z0-9+/]{43}=$/, "expected 32 bytes as base64");
66
- /** What other devices know about a device: its id, a display name and its two public keys. */
67
- const DevicePublic = object({
68
- deviceId: DeviceId,
69
- name: string().min(1).max(64),
70
- /** Ed25519 public key, base64. */
71
- signingKey: Key32,
72
- /** X25519 public key, base64. */
73
- kxKey: Key32
74
- });
75
- /** On-disk form of an identity. Holds secret keys: store with mode 0600. */
76
- const IdentityFile = object({
77
- version: literal(1),
78
- deviceId: DeviceId,
79
- signingSecretKey: Key32,
80
- kxSecretKey: Key32
81
- });
82
- function generateIdentity(deviceId) {
83
- const sign = ed25519.keygen();
84
- const kx = x25519.keygen();
85
- return {
86
- deviceId,
87
- signingSecretKey: sign.secretKey,
88
- signingPublicKey: sign.publicKey,
89
- kxSecretKey: kx.secretKey,
90
- kxPublicKey: kx.publicKey
91
- };
92
- }
93
- function serializeIdentity(id) {
94
- return {
95
- version: 1,
96
- deviceId: id.deviceId,
97
- signingSecretKey: toBase64(id.signingSecretKey),
98
- kxSecretKey: toBase64(id.kxSecretKey)
99
- };
100
- }
101
- /** Rebuild an identity from its file form; public keys are recomputed from the secret keys. */
102
- function parseIdentity(input) {
103
- const f = IdentityFile.parse(input);
104
- const signingSecretKey = fromBase64(f.signingSecretKey, 32);
105
- const kxSecretKey = fromBase64(f.kxSecretKey, 32);
106
- return {
107
- deviceId: f.deviceId,
108
- signingSecretKey,
109
- signingPublicKey: ed25519.getPublicKey(signingSecretKey),
110
- kxSecretKey,
111
- kxPublicKey: x25519.getPublicKey(kxSecretKey)
112
- };
113
- }
114
- function publicRecord(id, name) {
115
- return DevicePublic.parse({
116
- deviceId: id.deviceId,
117
- name,
118
- signingKey: toBase64(id.signingPublicKey),
119
- kxKey: toBase64(id.kxPublicKey)
120
- });
121
- }
122
- /** Canonical bytes of a device record, for signatures and transcripts. */
123
- function encodeDevice(d) {
124
- return encodeFields("device", d.deviceId, d.name, d.signingKey, d.kxKey);
125
- }
126
- /**
127
- * A short, stable fingerprint of a device's keys (not its name), for display: the first 16 bytes
128
- * of SHA-256 over both public keys, as hex in groups of four.
129
- */
130
- function deviceFingerprint(d) {
131
- return bytesToHex(sha256Bytes(encodeFields("fingerprint", d.signingKey, d.kxKey))).slice(0, 32).match(/.{4}/g).join(" ");
132
- }
133
- const sign = (sk, msg) => ed25519.sign(msg, sk);
134
- /**
135
- * Ed25519 verify with the strict RFC 8032 encoding rules (`zip215: false`: non-canonical point
136
- * encodings are refused, so signatures are not malleable). Malformed input verifies as false.
137
- */
138
- function verify(pk, msg, sig) {
139
- try {
140
- return ed25519.verify(sig, msg, pk, { zip215: false });
141
- } catch {
142
- return false;
143
- }
144
- }
145
- const ChainEntry = object({
146
- seq: number().int().min(0).max(512),
147
- /** Hex SHA-256 of the previous entry; empty for the genesis entry. */
148
- prev: string().regex(/^(?:[0-9a-f]{64})?$/),
149
- op: _enum(["add", "revoke"]),
150
- /** For `add`: the device added. */
151
- device: DevicePublic.optional(),
152
- /** For `revoke`: the device removed. */
153
- target: DeviceId.optional(),
154
- /** The signing device. */
155
- by: DeviceId,
156
- /** Unix ms, informational. */
157
- ts: number().int().nonnegative(),
158
- /** Ed25519 signature by `by`, base64. */
159
- sig: string().regex(/^[A-Za-z0-9+/]{86}==$/)
160
- });
161
- const DeviceChain = array(ChainEntry).min(1).max(512);
162
- function payloadBytes(e) {
163
- const subject = e.op === "add" && e.device ? encodeDevice(e.device) : encodeFields("target", e.target ?? "");
164
- return encodeFields("conveno/1 device-chain", e.seq, e.prev, e.op, subject, e.by, e.ts);
165
- }
166
- function entryHash(e) {
167
- return bytesToHex(sha256Bytes(encodeFields(payloadBytes(e), e.sig)));
168
- }
169
- function fail(message) {
170
- throw new CryptoError("bad_chain", message);
171
- }
172
- /** Verify a whole chain from genesis and return the resulting member set. Throws on any defect. */
173
- function verifyChain(input, o = {}) {
174
- const trusted = o.trustedPrefix ?? 0;
175
- const parsed = DeviceChain.safeParse(input);
176
- if (!parsed.success) fail("The device list is malformed.");
177
- const chain = parsed.data;
178
- const members = /* @__PURE__ */ new Map();
179
- const revoked = /* @__PURE__ */ new Map();
180
- const seenKeys = /* @__PURE__ */ new Set();
181
- let adds = 0;
182
- let head = "";
183
- chain.forEach((e, i) => {
184
- if (e.seq !== i) fail(`Entry ${i} has sequence number ${e.seq}.`);
185
- if (e.prev !== head) fail(`Entry ${i} does not follow entry ${i - 1}.`);
186
- let signer;
187
- if (i === 0) {
188
- if (e.op !== "add" || !e.device || e.device.deviceId !== e.by) fail("The first entry must be a device adding itself.");
189
- signer = e.device;
190
- } else {
191
- signer = members.get(e.by);
192
- if (!signer) fail(`Entry ${i} is signed by a device that is not an active member.`);
193
- }
194
- if (i >= trusted) {
195
- if (!verify(fromBase64(signer.signingKey, 32), payloadBytes(e), fromBase64(e.sig, 64))) fail(`Entry ${i} has an invalid signature.`);
196
- }
197
- if (e.op === "add") {
198
- const d = e.device;
199
- if (!d || e.target !== void 0) fail(`Entry ${i} is an add without exactly one device.`);
200
- if (++adds > 256) fail(`Entry ${i} adds more than 256 devices.`);
201
- if (members.has(d.deviceId) || revoked.has(d.deviceId)) fail(`Entry ${i} adds device ${d.deviceId}, which was already in the list.`);
202
- if (seenKeys.has(d.signingKey) || seenKeys.has(d.kxKey)) fail(`Entry ${i} reuses a key already in the list.`);
203
- seenKeys.add(d.signingKey);
204
- seenKeys.add(d.kxKey);
205
- members.set(d.deviceId, {
206
- ...d,
207
- addedAt: e.ts,
208
- addedBy: e.by
209
- });
210
- } else {
211
- const t = e.target;
212
- if (!t || e.device !== void 0) fail(`Entry ${i} is a revoke without exactly one target.`);
213
- const m = members.get(t);
214
- if (!m) fail(`Entry ${i} revokes ${t}, which is not an active member.`);
215
- if (members.size === 1) fail(`Entry ${i} revokes the last active device.`);
216
- members.delete(t);
217
- const { addedAt: _a, addedBy: _b, ...device } = m;
218
- revoked.set(t, {
219
- device,
220
- revokedAt: e.ts,
221
- by: e.by
222
- });
223
- }
224
- head = entryHash(e);
225
- });
226
- return {
227
- members,
228
- revoked,
229
- head,
230
- length: chain.length
231
- };
232
- }
233
- function signEntry(by, e) {
234
- return {
235
- ...e,
236
- sig: toBase64(sign(by.signingSecretKey, payloadBytes(e)))
237
- };
238
- }
239
- /** Start a new device list with this device as its only member. */
240
- function createChain(self, record, ts) {
241
- if (record.deviceId !== self.deviceId) throw new Error("record is not this device");
242
- return [signEntry(self, {
243
- seq: 0,
244
- prev: "",
245
- op: "add",
246
- device: record,
247
- by: self.deviceId,
248
- ts
249
- })];
250
- }
251
- /**
252
- * Append several operations signed by `self`, which must be an active member. The chain is
253
- * verified once before and once after, so the result is always a valid chain.
254
- */
255
- function appendOps(chain, self, ops, ts) {
256
- const state = verifyChain(chain);
257
- if (!state.members.has(self.deviceId)) throw new CryptoError("bad_chain", "This device is not an active member of the device list.");
258
- const next = [...chain];
259
- let prev = state.head;
260
- for (const o of ops) {
261
- const e = signEntry(self, {
262
- seq: next.length,
263
- prev,
264
- by: self.deviceId,
265
- ts,
266
- ...o
267
- });
268
- next.push(e);
269
- prev = entryHash(e);
270
- }
271
- verifyChain(next);
272
- return next;
273
- }
274
- function appendAdd(chain, self, device, ts) {
275
- return appendOps(chain, self, [{
276
- op: "add",
277
- device
278
- }], ts);
279
- }
280
- function appendRevoke(chain, self, target, ts) {
281
- return appendOps(chain, self, [{
282
- op: "revoke",
283
- target
284
- }], ts);
285
- }
286
- /** The first entry at which two chains differ, or -1 when one is a prefix of the other. */
287
- function forkPoint(a, b) {
288
- const common = Math.min(a.length, b.length);
289
- for (let i = 0; i < common; i++) if (entryHash(a[i]) !== entryHash(b[i])) return i;
290
- return -1;
291
- }
292
- /** Hash and length of a chain's last entry, as envelopes carry it. */
293
- function chainHead(chain) {
294
- return {
295
- head: entryHash(chain[chain.length - 1]),
296
- length: chain.length
297
- };
298
- }
299
- /**
300
- * Is a list with this head and length consistent with `chain`: the same list or a prefix of it.
301
- * A list longer than `chain` cannot be checked and counts as inconsistent.
302
- */
303
- function headMatches(chain, head, length) {
304
- if (length < 1 || length > chain.length) return false;
305
- return entryHash(chain[length - 1]) === head;
306
- }
307
- /**
308
- * HPKE, RFC 9180, for exactly one cipher suite:
309
- *
310
- * KEM 0x0020 DHKEM(X25519, HKDF-SHA256)
311
- * KDF 0x0001 HKDF-SHA256
312
- * AEAD 0x0003 ChaCha20Poly1305
313
- *
314
- * Modes `base` (0x00) and `auth` (0x02). The primitives (X25519, HKDF, SHA-256, ChaCha20-Poly1305)
315
- * come from the audited @noble libraries; this file only wires them together as the RFC specifies,
316
- * and the tests check it against the RFC's own test vectors (Appendix A.2).
317
- *
318
- * https://www.rfc-editor.org/rfc/rfc9180.html
319
- */
320
- const KEM_ID = 32;
321
- const KDF_ID = 1;
322
- const AEAD_ID = 3;
323
- /** Nsecret, Nenc, Npk, Nsk for DHKEM(X25519, HKDF-SHA256); Nk, Nn for ChaCha20Poly1305. */
324
- const N_SECRET = 32;
325
- const N_K = 32;
326
- const N_N = 12;
327
- const N_H = 32;
328
- const HPKE_V1 = utf8ToBytes("HPKE-v1");
329
- const SUITE_KEM = concatBytes(utf8ToBytes("KEM"), i2osp(KEM_ID, 2));
330
- const SUITE_HPKE = concatBytes(utf8ToBytes("HPKE"), i2osp(KEM_ID, 2), i2osp(KDF_ID, 2), i2osp(AEAD_ID, 2));
331
- const EMPTY = /* @__PURE__ */ new Uint8Array(0);
332
- /** RFC 9180 section 4: LabeledExtract. */
333
- function labeledExtract(suite, salt, label, ikm) {
334
- return extract(sha256, concatBytes(HPKE_V1, suite, utf8ToBytes(label), ikm), salt);
335
- }
336
- /** RFC 9180 section 4: LabeledExpand. */
337
- function labeledExpand(suite, prk, label, info, len) {
338
- const labeledInfo = concatBytes(i2osp(len, 2), HPKE_V1, suite, utf8ToBytes(label), info);
339
- return expand(sha256, prk, labeledInfo, len);
340
- }
341
- function generateKeyPair() {
342
- return x25519.keygen();
343
- }
344
- /**
345
- * X25519 with the all-zero check RFC 9180 section 7.1.4 requires. noble already refuses
346
- * low-order points; the explicit check documents and guarantees it.
347
- */
348
- function dh(sk, pk) {
349
- let out;
350
- try {
351
- out = x25519.getSharedSecret(sk, pk);
352
- } catch {
353
- throw new CryptoError("decrypt_failed", "Invalid X25519 public key.");
354
- }
355
- if (out.every((b) => b === 0)) throw new CryptoError("decrypt_failed", "Invalid X25519 public key.");
356
- return out;
357
- }
358
- function extractAndExpand(dhBytes, kemContext) {
359
- const eaePrk = labeledExtract(SUITE_KEM, EMPTY, "eae_prk", dhBytes);
360
- return labeledExpand(SUITE_KEM, eaePrk, "shared_secret", kemContext, N_SECRET);
361
- }
362
- /** RFC 9180 section 4.1: Encap / AuthEncap (skS given). `ephemeral` is for test vectors only. */
363
- function encap(pkR, skS, ephemeral = generateKeyPair()) {
364
- const enc = ephemeral.publicKey;
365
- if (skS === void 0) return {
366
- sharedSecret: extractAndExpand(dh(ephemeral.secretKey, pkR), concatBytes(enc, pkR)),
367
- enc
368
- };
369
- const pkS = x25519.getPublicKey(skS);
370
- return {
371
- sharedSecret: extractAndExpand(concatBytes(dh(ephemeral.secretKey, pkR), dh(skS, pkR)), concatBytes(enc, pkR, pkS)),
372
- enc
373
- };
374
- }
375
- /** RFC 9180 section 4.1: Decap / AuthDecap (pkS given). */
376
- function decap(enc, skR, pkS) {
377
- const pkR = x25519.getPublicKey(skR);
378
- if (pkS === void 0) return extractAndExpand(dh(skR, enc), concatBytes(enc, pkR));
379
- return extractAndExpand(concatBytes(dh(skR, enc), dh(skR, pkS)), concatBytes(enc, pkR, pkS));
380
- }
381
- /** RFC 9180 section 5.1: KeySchedule, with the default (empty) PSK, as modes base and auth use. */
382
- function keySchedule(mode, sharedSecret, info) {
383
- const pskIdHash = labeledExtract(SUITE_HPKE, EMPTY, "psk_id_hash", EMPTY);
384
- const infoHash = labeledExtract(SUITE_HPKE, EMPTY, "info_hash", info);
385
- const context = concatBytes(Uint8Array.of(mode), pskIdHash, infoHash);
386
- const secret = labeledExtract(SUITE_HPKE, sharedSecret, "secret", EMPTY);
387
- return {
388
- key: labeledExpand(SUITE_HPKE, secret, "key", context, N_K),
389
- baseNonce: labeledExpand(SUITE_HPKE, secret, "base_nonce", context, N_N),
390
- exporterSecret: labeledExpand(SUITE_HPKE, secret, "exp", context, N_H)
391
- };
392
- }
393
- /** An HPKE encryption context (RFC 9180 section 5.2). Sequence numbers start at 0. */
394
- var HpkeContext = class {
395
- schedule;
396
- sharedSecret;
397
- seq = 0;
398
- constructor(schedule, sharedSecret) {
399
- this.schedule = schedule;
400
- this.sharedSecret = sharedSecret;
401
- }
402
- nonce() {
403
- const n = this.schedule.baseNonce.slice();
404
- const s = i2osp(this.seq, N_N);
405
- for (let i = 0; i < N_N; i++) n[i] = n[i] ^ s[i];
406
- return n;
407
- }
408
- seal(aad, plaintext) {
409
- const ct = chacha20poly1305(this.schedule.key, this.nonce(), aad).encrypt(plaintext);
410
- this.seq++;
411
- return ct;
412
- }
413
- open(aad, ciphertext) {
414
- let pt;
415
- try {
416
- pt = chacha20poly1305(this.schedule.key, this.nonce(), aad).decrypt(ciphertext);
417
- } catch {
418
- throw new CryptoError("decrypt_failed", "The envelope could not be decrypted.");
419
- }
420
- this.seq++;
421
- return pt;
422
- }
423
- };
424
- /** RFC 9180 section 5.1.1 / 5.1.3: SetupBaseS / SetupAuthS. */
425
- function setupSender(o) {
426
- if (o.mode === 2 && o.skS === void 0) throw new Error("auth mode needs skS");
427
- const skS = o.mode === 2 ? o.skS : void 0;
428
- const { sharedSecret, enc } = encap(o.pkR, skS, o.ephemeral);
429
- return {
430
- enc,
431
- ctx: new HpkeContext(keySchedule(o.mode, sharedSecret, o.info), sharedSecret)
432
- };
433
- }
434
- /** RFC 9180 section 5.1.1 / 5.1.3: SetupBaseR / SetupAuthR. */
435
- function setupRecipient(o) {
436
- if (o.mode === 2 && o.pkS === void 0) throw new Error("auth mode needs pkS");
437
- const pkS = o.mode === 2 ? o.pkS : void 0;
438
- const sharedSecret = decap(o.enc, o.skR, pkS);
439
- return new HpkeContext(keySchedule(o.mode, sharedSecret, o.info), sharedSecret);
440
- }
441
- const HPKE_INFO = utf8ToBytes("conveno/1 envelope");
442
- const SIG_DOMAIN = "conveno/1 envelope-sig";
443
- /** Envelopes older than this are refused. Matches the relay's offline-queue TTL plus slack. */
444
- const ENVELOPE_MAX_AGE_MS = 6084e5;
445
- /** Envelopes dated further in the future than this are refused (clock skew allowance). */
446
- const ENVELOPE_MAX_FUTURE_MS = 3e5;
447
- function headerBytes(h) {
448
- return encodeFields("conveno/1 envelope-header", h.v, h.id, h.fromDevice, h.toDevice, h.ts, h.head, h.len, h.enc);
449
- }
450
- function signedBytes(h, ciphertext) {
451
- return concatBytes(encodeFields(SIG_DOMAIN), headerBytes(h), encodeFields(ciphertext));
452
- }
453
- function sealEnvelope(o) {
454
- const { enc, ctx } = setupSender({
455
- mode: 2,
456
- pkR: fromBase64(o.recipient.kxKey, 32),
457
- skS: o.sender.kxSecretKey,
458
- info: HPKE_INFO
459
- });
460
- const header = {
461
- v: 1,
462
- id: o.id,
463
- fromDevice: o.sender.deviceId,
464
- toDevice: o.recipient.deviceId,
465
- ts: o.ts,
466
- head: o.list.head,
467
- len: o.list.length,
468
- enc: toBase64(enc)
469
- };
470
- const ct = ctx.seal(headerBytes(header), o.plaintext);
471
- const sig = sign(o.sender.signingSecretKey, signedBytes(header, ct));
472
- return {
473
- t: "envelope",
474
- ...header,
475
- ciphertext: toBase64(ct),
476
- sig: toBase64(sig)
477
- };
478
- }
479
- /**
480
- * Check and decrypt an envelope. Order: recipient, sender membership, time window, replay,
481
- * signature, decryption. The replay check comes before the signature so a replayed envelope costs
482
- * a lookup, not a signature verification and a key agreement; refusing an id already seen cannot
483
- * hurt, since that id was accepted once. The id is recorded as seen only after decryption
484
- * succeeds, so a forged envelope cannot burn a real id. Throws CryptoError on every failure.
485
- */
486
- function openEnvelope(env, o) {
487
- if (env.v !== 1) throw new CryptoError("bad_encoding", `Unsupported envelope version ${env.v}.`);
488
- if (env.toDevice !== o.self.deviceId) throw new CryptoError("wrong_recipient", "The envelope is addressed to another device.");
489
- const sender = o.sender(env.fromDevice);
490
- if (!sender || sender.deviceId !== env.fromDevice) throw new CryptoError("unknown_sender", "The sender is not in this device list.");
491
- if (env.ts < o.now - 6084e5 || env.ts > o.now + 3e5) throw new CryptoError("stale", "The envelope timestamp is outside the accepted window.");
492
- if (o.replay.has(env.id)) throw new CryptoError("replay", "The envelope was already received.");
493
- const ct = fromBase64(env.ciphertext);
494
- const header = {
495
- v: env.v,
496
- id: env.id,
497
- fromDevice: env.fromDevice,
498
- toDevice: env.toDevice,
499
- ts: env.ts,
500
- head: env.head,
501
- len: env.len,
502
- enc: env.enc
503
- };
504
- if (!verify(fromBase64(sender.signingKey, 32), signedBytes(header, ct), fromBase64(env.sig, 64))) throw new CryptoError("bad_signature", "The envelope signature is not valid.");
505
- const pt = setupRecipient({
506
- mode: 2,
507
- enc: fromBase64(env.enc, 32),
508
- skR: o.self.kxSecretKey,
509
- pkS: fromBase64(sender.kxKey, 32),
510
- info: HPKE_INFO
511
- }).open(headerBytes(header), ct);
512
- if (o.record !== false) o.replay.add(env.id, env.ts);
513
- return pt;
514
- }
515
- /** The bytes a device signs to answer the relay's challenge. */
516
- function helloBytes(nonce, deviceId, signingKey) {
517
- return encodeFields("conveno/1 relay-hello", nonce, deviceId, signingKey);
518
- }
519
- /** Build the `hello` frame answering a relay `challenge` nonce. */
520
- function signRelayHello(id, nonce) {
521
- const signingKey = toBase64(id.signingPublicKey);
522
- const sig = sign(id.signingSecretKey, helloBytes(nonce, id.deviceId, signingKey));
523
- return {
524
- t: "hello",
525
- v: 1,
526
- deviceId: id.deviceId,
527
- signingKey,
528
- sig: toBase64(sig)
529
- };
530
- }
531
- /**
532
- * Device pairing with a short authentication string (SAS).
533
- *
534
- * The relay carries the pairing messages, so it must be assumed to be an active attacker. The
535
- * protocol is the commit-then-reveal SAS exchange used by ZRTP (RFC 6189 section 4.4.1) and
536
- * Bluetooth numeric comparison: the joiner commits to its key record and nonce before it sees
537
- * the inviter's, so a man in the middle has to fix its own values before it can learn the other
538
- * side's, and gets one guess at an 8-digit SAS (probability 1e-8).
539
- *
540
- * Two 8-digit codes come from the one transcript hash: the inviter shows one, the joiner the
541
- * other, and the owner types each device's code into the other device, which checks it. A device
542
- * never asks for the code it shows, so the owner has to read the other screen; a "yes" typed out
543
- * of habit cannot confirm a pairing. With a man in the middle the two sides hold different
544
- * transcripts, so each side's check fails except with probability 1e-8.
545
- *
546
- * joiner -> all : commit { pairingId, commit = H(pairingId, joinerRecord, nJ) }
547
- * inviter -> J : offer { pairingId, inviterRecord, nI }
548
- * joiner -> I : reveal { pairingId, joinerRecord, nJ } both now show their code
549
- * joiner -> I : confirm { pairingId, sig_J(transcript) } after the owner confirms on J
550
- * inviter -> J : welcome { pairingId, chain + add(joiner) signed by I } after confirming on I
551
- *
552
- * Key confirmation: the joiner's confirm signature and the inviter's signed chain entry prove each
553
- * side holds the signing key the SAS covered. The X25519 keys are covered by the SAS itself.
554
- */
555
- const PairingId = string().regex(/^[0-9a-f]{32}$/);
556
- const Nonce = string().regex(/^[A-Za-z0-9+/]{43}=$/);
557
- const PairMessage = discriminatedUnion("type", [
558
- object({
559
- type: literal("commit"),
560
- pairingId: PairingId,
561
- commit: Nonce
562
- }),
563
- object({
564
- type: literal("offer"),
565
- pairingId: PairingId,
566
- device: DevicePublic,
567
- nonce: Nonce
568
- }),
569
- object({
570
- type: literal("reveal"),
571
- pairingId: PairingId,
572
- device: DevicePublic,
573
- nonce: Nonce
574
- }),
575
- object({
576
- type: literal("confirm"),
577
- pairingId: PairingId,
578
- sig: string().regex(/^[A-Za-z0-9+/]{86}==$/)
579
- }),
580
- object({
581
- type: literal("welcome"),
582
- pairingId: PairingId,
583
- chain: DeviceChain
584
- }),
585
- object({
586
- type: literal("abort"),
587
- pairingId: PairingId,
588
- reason: string().max(200)
589
- })
590
- ]);
591
- function commitment(pairingId, joiner, nonce) {
592
- return sha256Bytes(encodeFields("conveno/1 pairing-commit", pairingId, encodeDevice(joiner), nonce));
593
- }
594
- function transcript(pairingId, inviter, joiner, nI, nJ) {
595
- return encodeFields("conveno/1 pairing", pairingId, encodeDevice(inviter), encodeDevice(joiner), nI, nJ);
596
- }
597
- /**
598
- * The code a device shows: SHA-256 over the transcript; bytes 0-7 (inviter) or 8-15 (joiner) as
599
- * an unsigned integer, modulo 10^8, shown as two groups of four digits. The modulo bias over a
600
- * 64-bit value is below 2^-37.
601
- */
602
- function computeSas(t, role) {
603
- const h = sha256Bytes(encodeFields("conveno/1 pairing-sas", t));
604
- const at = role === "inviter" ? 0 : 8;
605
- let n = 0n;
606
- for (let i = at; i < at + 8; i++) n = n << 8n | BigInt(h[i]);
607
- const digits = (n % 10n ** BigInt(8)).toString().padStart(8, "0");
608
- return `${digits.slice(0, 4)} ${digits.slice(4)}`;
609
- }
610
- /** Does a code the owner typed (spaces and dashes allowed) equal `expected`. Constant time. */
611
- function sasMatches(expected, typed) {
612
- const want = expected.replace(/\D/g, "");
613
- const got = typed.replace(/[\s-]/g, "");
614
- if (!/^\d+$/.test(got) || got.length !== want.length) return false;
615
- const enc = new TextEncoder();
616
- return bytesEqual(enc.encode(want), enc.encode(got));
617
- }
618
- const confirmBytes = (t) => encodeFields("conveno/1 pairing-confirm", t);
619
- function badPairing(message) {
620
- throw new CryptoError("bad_pairing", message);
621
- }
622
- /** Encode a pairing message for a relay `pair` frame's `data`. */
623
- function encodePairMessage(m) {
624
- return toBase64(new TextEncoder().encode(JSON.stringify(m)));
625
- }
626
- /** Decode a relay `pair` frame's `data`. Throws CryptoError on anything malformed. */
627
- function decodePairMessage(data) {
628
- try {
629
- return PairMessage.parse(JSON.parse(new TextDecoder().decode(fromBase64(data))));
630
- } catch {
631
- return badPairing("The pairing message is malformed.");
632
- }
633
- }
634
- /** The new device's side. */
635
- var JoinerPairing = class {
636
- self;
637
- record;
638
- pairingId = bytesToHex(randomBytes(16));
639
- nonce = toBase64(randomBytes(32));
640
- inviter;
641
- inviterNonce;
642
- t;
643
- constructor(self, record) {
644
- this.self = self;
645
- this.record = record;
646
- if (record.deviceId !== self.deviceId) throw new Error("record is not this device");
647
- }
648
- /** First message, broadcast to the account's other devices. Safe to resend. */
649
- commit() {
650
- const c = commitment(this.pairingId, this.record, this.nonce);
651
- return {
652
- type: "commit",
653
- pairingId: this.pairingId,
654
- commit: toBase64(c)
655
- };
656
- }
657
- /** The inviter's offer; returns the reveal to send back. Only the first offer is accepted. */
658
- onOffer(m) {
659
- if (m.type !== "offer" || m.pairingId !== this.pairingId) badPairing("Unexpected message.");
660
- if (this.inviter) badPairing("An offer was already accepted for this pairing.");
661
- if (m.device.deviceId === this.record.deviceId) badPairing("The offer is from this device.");
662
- this.inviter = m.device;
663
- this.inviterNonce = m.nonce;
664
- this.t = transcript(this.pairingId, m.device, this.record, m.nonce, this.nonce);
665
- return {
666
- type: "reveal",
667
- pairingId: this.pairingId,
668
- device: this.record,
669
- nonce: this.nonce
670
- };
671
- }
672
- get peer() {
673
- return this.inviter;
674
- }
675
- /** The code this device shows, for the owner to type on the other device. */
676
- get sas() {
677
- return this.t ? computeSas(this.t, "joiner") : void 0;
678
- }
679
- /** The code the other device shows, which the owner types here. */
680
- get peerSas() {
681
- return this.t ? computeSas(this.t, "inviter") : void 0;
682
- }
683
- /** Call only after the owner typed the inviter's code here and it matched (`peerSas`). */
684
- confirm() {
685
- if (!this.t) badPairing("No SAS to confirm yet.");
686
- const sig = sign(this.self.signingSecretKey, confirmBytes(this.t));
687
- return {
688
- type: "confirm",
689
- pairingId: this.pairingId,
690
- sig: toBase64(sig)
691
- };
692
- }
693
- /**
694
- * The inviter's welcome: the device list, whose last entry must add exactly this device's
695
- * record and be signed by the inviter whose keys the SAS covered.
696
- */
697
- onWelcome(m) {
698
- if (m.type !== "welcome" || m.pairingId !== this.pairingId) badPairing("Unexpected message.");
699
- const inviter = this.inviter;
700
- if (!inviter || this.inviterNonce === void 0) badPairing("No offer accepted yet.");
701
- const state = verifyChain(m.chain);
702
- const last = m.chain[m.chain.length - 1];
703
- const added = last.device;
704
- if (last.op !== "add" || last.by !== inviter.deviceId || !added || JSON.stringify(DevicePublic.parse(added)) !== JSON.stringify(this.record)) badPairing("The device list does not add this device by the confirmed inviter.");
705
- const signer = state.members.get(inviter.deviceId);
706
- if (!signer || signer.signingKey !== inviter.signingKey || signer.kxKey !== inviter.kxKey) badPairing("The inviter's keys in the device list differ from the confirmed ones.");
707
- return {
708
- chain: m.chain,
709
- state
710
- };
711
- }
712
- };
713
- /** The existing device's side. */
714
- var InviterPairing = class {
715
- self;
716
- record;
717
- nonce = toBase64(randomBytes(32));
718
- pairingIdValue;
719
- commitValue;
720
- joiner;
721
- t;
722
- joinerConfirmed = false;
723
- constructor(self, record) {
724
- this.self = self;
725
- this.record = record;
726
- if (record.deviceId !== self.deviceId) throw new Error("record is not this device");
727
- }
728
- get pairingId() {
729
- return this.pairingIdValue;
730
- }
731
- /** A joiner's commit; returns the offer. Only the first commit is taken. */
732
- onCommit(m) {
733
- if (m.type !== "commit") badPairing("Unexpected message.");
734
- if (this.pairingIdValue !== void 0) badPairing("Already pairing with another device.");
735
- this.pairingIdValue = m.pairingId;
736
- this.commitValue = fromBase64(m.commit, 32);
737
- return {
738
- type: "offer",
739
- pairingId: m.pairingId,
740
- device: this.record,
741
- nonce: this.nonce
742
- };
743
- }
744
- /** The joiner's reveal: checks it against the commit and fixes the SAS. */
745
- onReveal(m) {
746
- if (m.type !== "reveal" || m.pairingId !== this.pairingIdValue) badPairing("Unexpected message.");
747
- if (this.joiner) badPairing("The joiner already revealed.");
748
- const c = this.commitValue;
749
- if (!bytesEqual(c, commitment(m.pairingId, m.device, m.nonce))) badPairing("The joiner's reveal does not match its commitment.");
750
- if (m.device.deviceId === this.record.deviceId) badPairing("The joiner is this device.");
751
- this.joiner = m.device;
752
- this.t = transcript(m.pairingId, this.record, m.device, this.nonce, m.nonce);
753
- }
754
- get peer() {
755
- return this.joiner;
756
- }
757
- /** The code this device shows, for the owner to type on the other device. */
758
- get sas() {
759
- return this.t ? computeSas(this.t, "inviter") : void 0;
760
- }
761
- /** The code the other device shows, which the owner types here. */
762
- get peerSas() {
763
- return this.t ? computeSas(this.t, "joiner") : void 0;
764
- }
765
- /** The joiner's confirmation, signed with the signing key the SAS covered. */
766
- onConfirm(m) {
767
- if (m.type !== "confirm" || m.pairingId !== this.pairingIdValue) badPairing("Unexpected message.");
768
- if (!this.t || !this.joiner) badPairing("No SAS yet.");
769
- if (!verify(fromBase64(this.joiner.signingKey, 32), confirmBytes(this.t), fromBase64(m.sig, 64))) badPairing("The joiner's confirmation signature is not valid.");
770
- this.joinerConfirmed = true;
771
- }
772
- get joinerHasConfirmed() {
773
- return this.joinerConfirmed;
774
- }
775
- /**
776
- * Call only after the owner confirmed the SAS on this device and the joiner confirmed too.
777
- * Appends the joiner to the device list (creating the list if this device has none yet) and
778
- * returns the new chain and the welcome message.
779
- */
780
- welcome(chain, ts) {
781
- if (!this.joiner || !this.joinerConfirmed || this.pairingIdValue === void 0) badPairing("The joiner has not confirmed yet.");
782
- const next = appendAdd(chain ?? createChain(this.self, this.record, ts), this.self, this.joiner, ts);
783
- return {
784
- chain: next,
785
- message: {
786
- type: "welcome",
787
- pairingId: this.pairingIdValue,
788
- chain: next
789
- }
790
- };
791
- }
792
- };
793
- export { sasMatches as _, JoinerPairing as a, signRelayHello as b, decodePairMessage as c, forkPoint as d, generateIdentity as f, publicRecord as g, parseIdentity as h, InviterPairing as i, deviceFingerprint as l, openEnvelope as m, ENVELOPE_MAX_AGE_MS as n, appendRevoke as o, headMatches as p, ENVELOPE_MAX_FUTURE_MS as r, chainHead as s, CryptoError as t, encodePairMessage as u, sealEnvelope as v, verifyChain as x, serializeIdentity as y };