@seedprotocol/encryption 0.0.0-stage → 0.8.4-next.1913.g77fa9da

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.
package/dist/index.js ADDED
@@ -0,0 +1,862 @@
1
+ import { ml_kem768_x25519 as e } from "@noble/post-quantum/hybrid.js";
2
+ import { ed25519 as t, x25519 as n } from "@noble/curves/ed25519.js";
3
+ import { generateMnemonic as r, mnemonicToEntropy as i } from "@scure/bip39";
4
+ import { wordlist as a } from "@scure/bip39/wordlists/english.js";
5
+ //#region src/base64.ts
6
+ var o = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", s = (/* @__PURE__ */ new Int16Array(128)).fill(-1);
7
+ for (let e = 0; e < 64; e++) s[o.charCodeAt(e)] = e;
8
+ function c(e) {
9
+ let t = "", n = 0;
10
+ for (; n + 2 < e.length; n += 3) {
11
+ let r = e[n] << 16 | e[n + 1] << 8 | e[n + 2];
12
+ t += o[r >> 18] + o[r >> 12 & 63] + o[r >> 6 & 63] + o[r & 63];
13
+ }
14
+ let r = e.length - n;
15
+ if (r === 1) {
16
+ let r = e[n] << 16;
17
+ t += o[r >> 18] + o[r >> 12 & 63];
18
+ } else if (r === 2) {
19
+ let r = e[n] << 16 | e[n + 1] << 8;
20
+ t += o[r >> 18] + o[r >> 12 & 63] + o[r >> 6 & 63];
21
+ }
22
+ return t;
23
+ }
24
+ function l(e) {
25
+ if (e.length % 4 == 1) return null;
26
+ let t = new Uint8Array(Math.floor(e.length * 3 / 4)), n = 0, r = 0, i = 0;
27
+ for (let a = 0; a < e.length; a++) {
28
+ let o = e.charCodeAt(a), c = o < 128 ? s[o] : -1;
29
+ if (c < 0) return null;
30
+ n = n << 6 | c, r += 6, r >= 8 && (r -= 8, t[i++] = n >> r & 255);
31
+ }
32
+ return r > 0 && n & (1 << r) - 1 ? null : t;
33
+ }
34
+ //#endregion
35
+ //#region src/envelope.ts
36
+ var u = "seed-private/v1", ee = "application/octet-stream", te = {
37
+ name: "Seed-Encryption",
38
+ value: u
39
+ }, ne = 32, d = 65536, re = 16, f = 16, p = 64, ie = 65536, m = `${u}\n`, ae = `${u}/header`, oe = `${u}/payload`, h = new TextEncoder(), g = new TextDecoder("utf-8", { fatal: !0 }), _ = class extends Error {
40
+ code;
41
+ constructor(e, t) {
42
+ super(t), this.name = "EnvelopeError", this.code = e;
43
+ }
44
+ }, se = /^[A-Za-z][A-Za-z0-9]*$/, ce = /^0x[0-9a-f]{64}$/, v = /^[\x21-\x7e]+$/;
45
+ function y(e) {
46
+ let t = new Uint8Array(e);
47
+ return crypto.getRandomValues(t), t;
48
+ }
49
+ function b() {
50
+ return y(32);
51
+ }
52
+ function x() {
53
+ return `0x${Array.from(y(32), (e) => e.toString(16).padStart(2, "0")).join("")}`;
54
+ }
55
+ function S(e) {
56
+ if (e.length < m.length) return !1;
57
+ for (let t = 0; t < m.length; t++) if (e[t] !== m.charCodeAt(t)) return !1;
58
+ return !0;
59
+ }
60
+ function C(e) {
61
+ let t = Object.keys(e).sort();
62
+ for (let n of t) {
63
+ if (!se.test(n)) throw new _("BAD_BIND", `Invalid bind key ${JSON.stringify(n)}`);
64
+ if (typeof e[n] != "string") throw new _("BAD_BIND", `Bind value for ${n} must be a string`);
65
+ }
66
+ if (!ce.test(e.envelopeId ?? "")) throw new _("BAD_BIND", "bind.envelopeId must be 0x followed by 64 lowercase hex digits");
67
+ return JSON.stringify(Object.fromEntries(t.map((t) => [t, e[t]])));
68
+ }
69
+ function w(e) {
70
+ let t = new Uint8Array(e.reduce((e, t) => e + t.length, 0)), n = 0;
71
+ for (let r of e) t.set(r, n), n += r.length;
72
+ return t;
73
+ }
74
+ function T(e) {
75
+ return new Uint8Array(e);
76
+ }
77
+ async function E(e, t, n, r) {
78
+ let i = await crypto.subtle.importKey("raw", T(e), "HKDF", !1, ["deriveBits"]), a = await crypto.subtle.deriveBits({
79
+ name: "HKDF",
80
+ hash: "SHA-256",
81
+ salt: T(t),
82
+ info: T(n)
83
+ }, i, r * 8);
84
+ return new Uint8Array(a);
85
+ }
86
+ async function le(e, t) {
87
+ let n = await E(e, /* @__PURE__ */ new Uint8Array(), h.encode(ae), 32);
88
+ return crypto.subtle.importKey("raw", n, {
89
+ name: "HMAC",
90
+ hash: "SHA-256"
91
+ }, !1, [t]);
92
+ }
93
+ async function ue(e, t, n, r) {
94
+ let i = await E(e, t, w([
95
+ h.encode(oe),
96
+ new Uint8Array([0]),
97
+ h.encode(n)
98
+ ]), 32);
99
+ return crypto.subtle.importKey("raw", i, "AES-GCM", !1, [r]);
100
+ }
101
+ function D(e, t) {
102
+ let n = /* @__PURE__ */ new Uint8Array(12), r = e;
103
+ for (let e = 10; e >= 0 && r > 0; e--) n[e] = r % 256, r = Math.floor(r / 256);
104
+ return n[11] = +!!t, n;
105
+ }
106
+ function de(e) {
107
+ if (e < 2) return e;
108
+ let t = 0;
109
+ for (; 2 ** (t + 1) <= e;) t++;
110
+ let n = 0;
111
+ for (; 2 ** (n + 1) <= t;) n++;
112
+ let r = 2 ** (t - (n + 1));
113
+ return Math.ceil(e / r) * r;
114
+ }
115
+ function fe(e, t, n) {
116
+ let r = h.encode(JSON.stringify({
117
+ bodyLength: t.length,
118
+ contentType: e
119
+ })), i = /* @__PURE__ */ new Uint8Array(4);
120
+ new DataView(i.buffer).setUint32(0, r.length);
121
+ let a = 4 + r.length + t.length, o = n === "padme" ? de(a) : a;
122
+ return w([
123
+ i,
124
+ r,
125
+ t,
126
+ new Uint8Array(o - a)
127
+ ]);
128
+ }
129
+ function pe(e) {
130
+ if (e.length < 4) throw new _("BAD_CONTENT_FRAME", "Payload is shorter than its content frame");
131
+ let t = new DataView(e.buffer, e.byteOffset, 4).getUint32(0);
132
+ if (t > ie || 4 + t > e.length) throw new _("BAD_CONTENT_FRAME", "Content metadata length is out of range");
133
+ let n;
134
+ try {
135
+ n = JSON.parse(g.decode(e.subarray(4, 4 + t)));
136
+ } catch {
137
+ throw new _("BAD_CONTENT_FRAME", "Content metadata is not UTF-8 JSON");
138
+ }
139
+ let { contentType: r, bodyLength: i } = n ?? {};
140
+ if (typeof r != "string") throw new _("BAD_CONTENT_FRAME", "Content metadata has no contentType");
141
+ let a = 4 + t;
142
+ if (typeof i != "number" || !Number.isSafeInteger(i) || i < 0 || a + i > e.length) throw new _("BAD_CONTENT_FRAME", "Content metadata bodyLength is missing or out of range");
143
+ let o = a + i;
144
+ for (let t = o; t < e.length; t++) if (e[t] !== 0) throw new _("BAD_CONTENT_FRAME", "Padding after the body is not all zero");
145
+ return {
146
+ contentType: r,
147
+ body: e.subarray(a, o)
148
+ };
149
+ }
150
+ function me(e) {
151
+ if (!v.test(e.type) || e.args.some((e) => !v.test(e))) throw new _("BAD_HEADER", "Stanza type and arguments must be non-empty printable ASCII without spaces");
152
+ let t = c(e.body), n = "";
153
+ for (let e = 0; e <= t.length; e += p) n += `${t.slice(e, e + p)}\n`;
154
+ return `-> ${[e.type, ...e.args].join(" ")}\n${n}`;
155
+ }
156
+ function he(e, t) {
157
+ if (t.length === 0) throw new _("BAD_HEADER", "An envelope needs at least one stanza");
158
+ return `${m}bind ${c(h.encode(e))}\n${t.map(me).join("")}---`;
159
+ }
160
+ async function ge(e, t) {
161
+ if (e.fileKey.length !== 32) throw new _("BAD_FILE_KEY", "File key must be 32 bytes");
162
+ if (t.length !== f) throw new _("BAD_HEADER", "Payload nonce must be 16 bytes");
163
+ let n = C(e.bind), r = h.encode(he(n, e.stanzas)), i = new Uint8Array(await crypto.subtle.sign("HMAC", await le(e.fileKey, "sign"), r)), a = await ue(e.fileKey, t, n, "encrypt"), o = fe(e.contentType, e.body, e.padding ?? "padme"), s = [], l = Math.max(1, Math.ceil(o.length / d));
164
+ for (let e = 0; e < l; e++) {
165
+ let t = o.subarray(e * d, (e + 1) * d), n = await crypto.subtle.encrypt({
166
+ name: "AES-GCM",
167
+ iv: D(e, e === l - 1)
168
+ }, a, t);
169
+ s.push(new Uint8Array(n));
170
+ }
171
+ return w([
172
+ r,
173
+ h.encode(` ${c(i)}\n`),
174
+ t,
175
+ ...s
176
+ ]);
177
+ }
178
+ function O(e) {
179
+ return ge(e, y(f));
180
+ }
181
+ function k(e, t) {
182
+ let n = e.indexOf(10, t);
183
+ if (n < 0) throw new _("BAD_HEADER", "Header ends without a newline");
184
+ let r;
185
+ try {
186
+ r = g.decode(e.subarray(t, n));
187
+ } catch {
188
+ throw new _("BAD_HEADER", "Header is not UTF-8");
189
+ }
190
+ if (!/^[\x20-\x7e]*$/.test(r)) throw new _("BAD_HEADER", "Header lines must be printable ASCII");
191
+ return {
192
+ line: r,
193
+ next: n + 1
194
+ };
195
+ }
196
+ function _e(e) {
197
+ if (!S(e)) throw new _("NOT_ENVELOPE", `Bytes do not start with ${u}`);
198
+ let t = m.length, n = k(e, t);
199
+ if (!n.line.startsWith("bind ")) throw new _("BAD_HEADER", "Missing bind line");
200
+ let r = l(n.line.slice(5));
201
+ if (!r) throw new _("BAD_HEADER", "bind line is not canonical base64");
202
+ let i, a;
203
+ try {
204
+ i = g.decode(r), a = JSON.parse(i);
205
+ } catch {
206
+ throw new _("BAD_BIND", "bind is not UTF-8 JSON");
207
+ }
208
+ if (typeof a != "object" || !a || Array.isArray(a) || C(a) !== i) throw new _("BAD_BIND", "bind is not canonical");
209
+ t = n.next;
210
+ let o = [];
211
+ for (; n = k(e, t), !n.line.startsWith("--- ");) {
212
+ if (!n.line.startsWith("-> ")) throw new _("BAD_HEADER", "Expected a stanza or the MAC line");
213
+ let [r, ...i] = n.line.slice(3).split(" ");
214
+ if (!r || !v.test(r) || i.some((e) => !v.test(e))) throw new _("BAD_HEADER", "Malformed stanza line");
215
+ t = n.next;
216
+ let a = "";
217
+ for (;;) {
218
+ if (n = k(e, t), t = n.next, n.line.length > p) throw new _("BAD_HEADER", "Stanza body line is too long");
219
+ if (a += n.line, n.line.length < p) break;
220
+ }
221
+ let s = l(a);
222
+ if (!s) throw new _("BAD_HEADER", "Stanza body is not canonical base64");
223
+ o.push({
224
+ type: r,
225
+ args: i,
226
+ body: s
227
+ });
228
+ }
229
+ if (o.length === 0) throw new _("BAD_HEADER", "Envelope has no stanzas");
230
+ let s = l(n.line.slice(4));
231
+ if (!s || s.length !== 32) throw new _("BAD_HEADER", "MAC is not 32 bytes of canonical base64");
232
+ return {
233
+ bind: a,
234
+ bindText: i,
235
+ stanzas: o,
236
+ macInput: e.subarray(0, t + 3),
237
+ mac: s,
238
+ payloadOffset: n.next
239
+ };
240
+ }
241
+ function ve(e) {
242
+ let { bind: t, stanzas: n } = _e(e);
243
+ return {
244
+ bind: t,
245
+ stanzas: n
246
+ };
247
+ }
248
+ async function A(e, t) {
249
+ let n = _e(e);
250
+ for (let [e, r] of Object.entries(t.expectBind ?? {})) if (n.bind[e] !== r) throw new _("BIND_MISMATCH", `Envelope bind ${e} does not match`);
251
+ let r = t.fileKey ?? await t.unwrap?.({
252
+ bind: n.bind,
253
+ stanzas: n.stanzas
254
+ });
255
+ if (!r) throw new _("NO_KEY", "No stanza could be unwrapped");
256
+ if (r.length !== 32) throw new _("BAD_FILE_KEY", "File key must be 32 bytes");
257
+ if (!await crypto.subtle.verify("HMAC", await le(r, "verify"), T(n.mac), T(n.macInput))) throw new _("HEADER_MAC", "Header MAC does not verify; wrong key or altered header");
258
+ let i = e.subarray(n.payloadOffset);
259
+ if (i.length < 32) throw new _("TRUNCATED", "Payload is truncated");
260
+ let a = await ue(r, i.subarray(0, f), n.bindText, "decrypt"), o = 65552, s = [], c = f;
261
+ for (let e = 0;; e++) {
262
+ let t = i.length - c;
263
+ if (t < re) throw new _("TRUNCATED", "Payload ends without a final chunk");
264
+ let n = t <= o, r = T(i.subarray(c, c + Math.min(t, o))), l;
265
+ try {
266
+ l = new Uint8Array(await crypto.subtle.decrypt({
267
+ name: "AES-GCM",
268
+ iv: D(e, n)
269
+ }, a, r));
270
+ } catch {
271
+ if (n && t === o) {
272
+ try {
273
+ await crypto.subtle.decrypt({
274
+ name: "AES-GCM",
275
+ iv: D(e, !1)
276
+ }, a, r);
277
+ } catch {
278
+ throw new _("BAD_CHUNK", `Chunk ${e} does not authenticate`);
279
+ }
280
+ throw new _("TRUNCATED", "Payload ends without a final chunk");
281
+ }
282
+ if (!n) {
283
+ try {
284
+ await crypto.subtle.decrypt({
285
+ name: "AES-GCM",
286
+ iv: D(e, !0)
287
+ }, a, r);
288
+ } catch {
289
+ throw new _("BAD_CHUNK", `Chunk ${e} does not authenticate`);
290
+ }
291
+ throw new _("TRAILING_DATA", "Bytes follow the final chunk");
292
+ }
293
+ throw new _("BAD_CHUNK", `Chunk ${e} does not authenticate`);
294
+ }
295
+ if (n && l.length === 0 && e > 0) throw new _("BAD_CHUNK", "The final chunk is empty");
296
+ if (s.push(l), c += r.length, n) break;
297
+ }
298
+ let { contentType: l, body: u } = pe(w(s));
299
+ return {
300
+ bind: n.bind,
301
+ contentType: l,
302
+ body: u
303
+ };
304
+ }
305
+ //#endregion
306
+ //#region src/hpke.ts
307
+ var ye = 25722, be = 1, xe = 2, Se = 32, Ce = 12, we = 32, j = 1216, Te = 32, Ee = 1120, M = new TextEncoder();
308
+ function N(e) {
309
+ return new Uint8Array([e >> 8, e & 255]);
310
+ }
311
+ function P(e) {
312
+ let t = new Uint8Array(e.reduce((e, t) => e + t.length, 0)), n = 0;
313
+ for (let r of e) t.set(r, n), n += r.length;
314
+ return t;
315
+ }
316
+ var De = P([
317
+ M.encode("HPKE"),
318
+ N(ye),
319
+ N(be),
320
+ N(xe)
321
+ ]), Oe = M.encode("HPKE-v1");
322
+ async function ke(e, t) {
323
+ let n = e.length === 0 ? new Uint8Array(we) : new Uint8Array(e), r = await crypto.subtle.importKey("raw", n, {
324
+ name: "HMAC",
325
+ hash: "SHA-256"
326
+ }, !1, ["sign"]);
327
+ return new Uint8Array(await crypto.subtle.sign("HMAC", r, new Uint8Array(t)));
328
+ }
329
+ function F(e, t, n) {
330
+ return ke(e, P([
331
+ Oe,
332
+ De,
333
+ M.encode(t),
334
+ n
335
+ ]));
336
+ }
337
+ async function Ae(e, t, n, r) {
338
+ return (await ke(e, P([P([
339
+ N(r),
340
+ Oe,
341
+ De,
342
+ M.encode(t),
343
+ n
344
+ ]), new Uint8Array([1])]))).slice(0, r);
345
+ }
346
+ async function je(e, t, n) {
347
+ let r = /* @__PURE__ */ new Uint8Array(), i = await F(r, "psk_id_hash", r), a = await F(r, "info_hash", t), o = P([
348
+ new Uint8Array([0]),
349
+ i,
350
+ a
351
+ ]), s = await F(e, "secret", r), c = await Ae(s, "key", o, Se), l = await Ae(s, "base_nonce", o, Ce);
352
+ return {
353
+ key: await crypto.subtle.importKey("raw", c, "AES-GCM", !1, [n]),
354
+ nonce: l
355
+ };
356
+ }
357
+ function Me(t) {
358
+ let { secretKey: n, publicKey: r } = e.keygen(t);
359
+ return {
360
+ secretKey: n,
361
+ publicKey: r
362
+ };
363
+ }
364
+ async function Ne(t, n, r, i, a) {
365
+ let { sharedSecret: o, cipherText: s } = e.encapsulate(t, a), { key: c, nonce: l } = await je(o, n, "encrypt"), u = await crypto.subtle.encrypt({
366
+ name: "AES-GCM",
367
+ iv: l,
368
+ additionalData: new Uint8Array(r)
369
+ }, c, new Uint8Array(i));
370
+ return {
371
+ enc: s,
372
+ ciphertext: new Uint8Array(u)
373
+ };
374
+ }
375
+ async function Pe(t, n, r, i, a) {
376
+ let { key: o, nonce: s } = await je(e.decapsulate(t, n), r, "decrypt");
377
+ try {
378
+ return new Uint8Array(await crypto.subtle.decrypt({
379
+ name: "AES-GCM",
380
+ iv: s,
381
+ additionalData: new Uint8Array(i)
382
+ }, o, new Uint8Array(a)));
383
+ } catch {
384
+ return null;
385
+ }
386
+ }
387
+ //#endregion
388
+ //#region src/recipient.ts
389
+ var I = "mlkem768x25519", Fe = new TextEncoder().encode("seed-private/v1/mlkem768x25519"), Ie = 48;
390
+ function L(e) {
391
+ let t = e ?? crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32));
392
+ if (t.length !== 32) throw new _("BAD_RECIPIENT_KEY", "Recipient seed must be 32 bytes");
393
+ return Me(t);
394
+ }
395
+ async function Le(e, t, n) {
396
+ if (e.length !== 32) throw new _("BAD_FILE_KEY", "File key must be 32 bytes");
397
+ if (t.length !== 1216) throw new _("BAD_RECIPIENT_KEY", `Recipient public key must be ${j} bytes`);
398
+ let { enc: r, ciphertext: i } = await Ne(t, Fe, /* @__PURE__ */ new Uint8Array(), e, n);
399
+ return {
400
+ type: I,
401
+ args: [c(r)],
402
+ body: i
403
+ };
404
+ }
405
+ function R(e, t) {
406
+ return Le(e, t);
407
+ }
408
+ async function z(e, t) {
409
+ if (e.type !== "mlkem768x25519") return null;
410
+ if (t.length !== 32) throw new _("BAD_RECIPIENT_KEY", "Recipient secret key must be 32 bytes");
411
+ let n = e.args.length === 1 ? l(e.args[0]) : null;
412
+ if (!n || n.length !== 1120) throw new _("BAD_HEADER", `${I} stanza needs one argument: ${Ee} bytes of base64`);
413
+ if (e.body.length !== Ie) throw new _("BAD_HEADER", `${I} stanza body must be ${Ie} bytes`);
414
+ return Pe(n, t, Fe, /* @__PURE__ */ new Uint8Array(), e.body);
415
+ }
416
+ function Re(e) {
417
+ return async (t) => {
418
+ for (let n of t.stanzas) for (let t of e) {
419
+ let e = await z(n, t);
420
+ if (e) return e;
421
+ }
422
+ return null;
423
+ };
424
+ }
425
+ //#endregion
426
+ //#region src/entitlement.ts
427
+ var ze = class extends Error {
428
+ kind;
429
+ constructor(e) {
430
+ super(`No entitlement adapter is registered for policy kind "${e}"`), this.name = "UnknownEntitlementKindError", this.kind = e;
431
+ }
432
+ }, B = /* @__PURE__ */ new Map();
433
+ function Be(e, t) {
434
+ if (!e) throw Error("Entitlement kind must be a non-empty string");
435
+ if (B.has(e)) throw Error(`An entitlement adapter is already registered for "${e}"`);
436
+ return B.set(e, t), () => {
437
+ B.get(e) === t && B.delete(e);
438
+ };
439
+ }
440
+ function Ve(e, t, n = "latest") {
441
+ let r = B.get(e.kind);
442
+ return r ? r.isEntitled(e, t, n) : Promise.reject(new ze(e.kind));
443
+ }
444
+ //#endregion
445
+ //#region src/identity.ts
446
+ var He = 32, V = new TextEncoder(), H = /* @__PURE__ */ new Uint8Array();
447
+ function Ue(e) {
448
+ return Array.from(e, (e) => e.toString(16).padStart(2, "0")).join("");
449
+ }
450
+ async function U(e) {
451
+ if (e.length !== 32) throw new _("BAD_KEYSTORE", "Identity secret must be 32 bytes");
452
+ let r = await E(e, H, V.encode("seed-private/v1/identity/mlkem768x25519"), 32), i = await E(e, H, V.encode("seed-private/v1/identity/x25519"), 32), a = L(r), o = await E(e, H, V.encode("seed-private/v1/identity/ed25519"), 32), s = {
453
+ secretKey: i,
454
+ publicKey: n.getPublicKey(i)
455
+ }, c = {
456
+ secretKey: o,
457
+ publicKey: t.getPublicKey(o)
458
+ };
459
+ return {
460
+ keyId: await We(a.publicKey, s.publicKey, c.publicKey),
461
+ secret: new Uint8Array(e),
462
+ recipient: a,
463
+ tagKey: s,
464
+ bindingKey: c
465
+ };
466
+ }
467
+ async function We(e, t, n) {
468
+ let r = V.encode("seed-private/v1/key-id"), i = new Uint8Array(r.length + 1 + e.length + t.length + n.length);
469
+ return i.set(r, 0), i.set(e, r.length + 1), i.set(t, r.length + 1 + e.length), i.set(n, r.length + 1 + e.length + t.length), `0x${Ue(new Uint8Array(await crypto.subtle.digest("SHA-256", i)))}`;
470
+ }
471
+ function W(e, t, n) {
472
+ let r = e.startsWith("0x") ? e.slice(2) : e;
473
+ if (!RegExp(`^[0-9a-fA-F]{${t * 2}}$`).test(r)) throw new _("BAD_KEYSTORE", `${n} must be ${t} bytes of hex`);
474
+ return Uint8Array.from({ length: t }, (e, t) => parseInt(r.slice(t * 2, t * 2 + 2), 16));
475
+ }
476
+ function G(e, { account: t, chainId: n }) {
477
+ let r = V.encode("seed-private/v1/key-binding"), i = BigInt(n);
478
+ if (i < 0n || i >= 1n << 256n) throw new _("BAD_KEYSTORE", "chainId must fit in 32 bytes");
479
+ let a = new Uint8Array(r.length + 1 + 32 + 32 + 20);
480
+ return a.set(r, 0), a.set(W(e, 32, "keyId"), r.length + 1), a.set(W(i.toString(16).padStart(64, "0"), 32, "chainId"), r.length + 33), a.set(W(t, 20, "account"), r.length + 65), a;
481
+ }
482
+ function Ge(e, n) {
483
+ return t.sign(G(e.keyId, n), e.bindingKey.secretKey);
484
+ }
485
+ function Ke({ keyId: e, bindingPublicKey: n, signature: r }, i) {
486
+ try {
487
+ return t.verify(r, G(e, i), n);
488
+ } catch {
489
+ return !1;
490
+ }
491
+ }
492
+ function qe() {
493
+ return U(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)));
494
+ }
495
+ function Je() {
496
+ return r(a, 256);
497
+ }
498
+ function Ye(e) {
499
+ return e.normalize("NFKD").trim().toLowerCase().split(/\s+/).join(" ");
500
+ }
501
+ async function Xe(e) {
502
+ let t = Ye(e), n;
503
+ try {
504
+ n = i(t, a);
505
+ } catch {
506
+ throw new _("BAD_RECOVERY_PHRASE", "Recovery phrase has an unknown word or a bad checksum");
507
+ }
508
+ if (n.length !== 32) throw new _("BAD_RECOVERY_PHRASE", "Recovery phrase must be 24 words");
509
+ return L(await E(n, H, V.encode("seed-private/v1/recovery/mlkem768x25519"), 32));
510
+ }
511
+ //#endregion
512
+ //#region src/keystore.ts
513
+ var Ze = "application/vnd.seedprotocol.identity-secret", K = "passkey-prf", Qe = "eoa-signature", q = 32, $e = 48, J = new TextEncoder(), et = /* @__PURE__ */ new Uint8Array(), tt = /* @__PURE__ */ new Uint8Array(12);
514
+ function Y(e) {
515
+ return E(e.secret, et, J.encode("seed-private/v1/keystore"), 32);
516
+ }
517
+ async function nt(e, t) {
518
+ let n = await crypto.subtle.importKey("raw", e, "AES-GCM", !1, ["encrypt"]);
519
+ return new Uint8Array(await crypto.subtle.encrypt({
520
+ name: "AES-GCM",
521
+ iv: tt
522
+ }, n, t));
523
+ }
524
+ async function rt(e, t) {
525
+ let n = await crypto.subtle.importKey("raw", e, "AES-GCM", !1, ["decrypt"]);
526
+ try {
527
+ return new Uint8Array(await crypto.subtle.decrypt({
528
+ name: "AES-GCM",
529
+ iv: tt
530
+ }, n, new Uint8Array(t)));
531
+ } catch {
532
+ return null;
533
+ }
534
+ }
535
+ function it() {
536
+ return crypto.getRandomValues(new Uint8Array(q));
537
+ }
538
+ function at(e) {
539
+ return Array.from(e, (e) => e.toString(16).padStart(2, "0")).join("");
540
+ }
541
+ function X(e, t, n) {
542
+ let r = e.args.length === t ? e.args.map((e) => l(e)) : [];
543
+ if (!(r.length === t && r.every((e, t) => e !== null && (n[t] === 0 ? e.length > 0 : e.length === n[t])) && e.body.length === $e)) throw new _("BAD_HEADER", `Malformed ${e.type} stanza`);
544
+ return r;
545
+ }
546
+ async function ot(e, t) {
547
+ return R(await Y(e), t);
548
+ }
549
+ async function st(e, t) {
550
+ return E(e, t, J.encode("seed-private/v1/passkey-prf"), 32);
551
+ }
552
+ function ct() {
553
+ return it();
554
+ }
555
+ async function lt(e, { credentialId: t, salt: n, prfOutput: r }) {
556
+ if (n.length !== q) throw new _("BAD_KEYSTORE", `Passkey salt must be ${q} bytes`);
557
+ if (t.length === 0 || r.length < 32) throw new _("BAD_KEYSTORE", "Missing passkey credential or PRF output");
558
+ let i = await nt(await st(r, n), await Y(e));
559
+ return {
560
+ type: K,
561
+ args: [c(t), c(n)],
562
+ body: i
563
+ };
564
+ }
565
+ function ut(e) {
566
+ let [t, n] = X(e, 2, [0, q]);
567
+ return {
568
+ credentialId: t,
569
+ salt: n
570
+ };
571
+ }
572
+ function dt(e) {
573
+ return [
574
+ "Unlock your Seed Protocol encryption key",
575
+ "",
576
+ "Signing this message lets this app read your private Versions. Anyone who gets this signature can read them too, so sign it only in apps you trust.",
577
+ "",
578
+ `Key: 0x${at(e)}`
579
+ ].join("\n");
580
+ }
581
+ function ft() {
582
+ return it();
583
+ }
584
+ var pt = 115792089237316195423570985008687907852837564279074904382605163141518161494337n;
585
+ function mt(e) {
586
+ let t = e.startsWith("0x") ? e.slice(2) : e;
587
+ if (!/^[0-9a-fA-F]*$/.test(t) || t.length !== 130 && t.length !== 128) throw new _("BAD_KEYSTORE", "Signature must be 64 or 65 bytes of hex");
588
+ let n = t.slice(0, 64), r = BigInt(`0x${t.slice(64, 128)}`);
589
+ t.length === 128 && (r &= (1n << 255n) - 1n), r > pt / 2n && (r = pt - r);
590
+ let i = /* @__PURE__ */ new Uint8Array(64), a = n + r.toString(16).padStart(64, "0");
591
+ for (let e = 0; e < 64; e++) i[e] = parseInt(a.slice(e * 2, e * 2 + 2), 16);
592
+ return i;
593
+ }
594
+ async function ht(e, t) {
595
+ return E(mt(e), t, J.encode("seed-private/v1/eoa-signature"), 32);
596
+ }
597
+ async function gt(e, { salt: t, signature: n, acceptWalletKeyRisk: r }) {
598
+ if (r !== !0) throw new _("BAD_KEYSTORE", "eoaSignatureStanza needs acceptWalletKeyRisk: true; prefer a passkey and the recovery phrase");
599
+ if (t.length !== q) throw new _("BAD_KEYSTORE", `Signature salt must be ${q} bytes`);
600
+ let i = await nt(await ht(n, t), await Y(e));
601
+ return {
602
+ type: Qe,
603
+ args: [c(t)],
604
+ body: i
605
+ };
606
+ }
607
+ async function _t(e, t) {
608
+ if (t.length === 0) throw new _("BAD_KEYSTORE", "A keystore manifest needs at least one stanza");
609
+ return O({
610
+ fileKey: await Y(e),
611
+ bind: {
612
+ envelopeId: x(),
613
+ keyId: e.keyId,
614
+ purpose: "keystore"
615
+ },
616
+ stanzas: t,
617
+ contentType: Ze,
618
+ body: e.secret
619
+ });
620
+ }
621
+ function vt(e) {
622
+ let t = yt(e), n = [];
623
+ for (let e of t.stanzas) e.type === "mlkem768x25519" ? n.push({ type: "recovery" }) : e.type === "passkey-prf" ? n.push({
624
+ type: "passkey",
625
+ credentialId: ut(e).credentialId
626
+ }) : e.type === "eoa-signature" && n.push({
627
+ type: "eoa-signature",
628
+ salt: X(e, 1, [q])[0]
629
+ });
630
+ return {
631
+ keyId: t.bind.keyId,
632
+ authenticators: n
633
+ };
634
+ }
635
+ function yt(e) {
636
+ let t = ve(e);
637
+ if (t.bind.purpose !== "keystore" || !/^0x[0-9a-f]{64}$/.test(t.bind.keyId ?? "")) throw new _("BAD_KEYSTORE", "Not a keystore manifest");
638
+ return t;
639
+ }
640
+ async function bt(e, t) {
641
+ if ("recoveryPhrase" in t) {
642
+ let { secretKey: n } = await Xe(t.recoveryPhrase);
643
+ for (let t of e.stanzas) {
644
+ let e = await z(t, n);
645
+ if (e) return e;
646
+ }
647
+ return null;
648
+ }
649
+ if ("passkey" in t) {
650
+ let n = e.stanzas.filter((e) => e.type === K);
651
+ if (n.length === 0) return null;
652
+ let r = n.map(ut), i = await t.passkey(r);
653
+ if (!i) return null;
654
+ for (let e = 0; e < n.length; e++) {
655
+ if (!Z(r[e].credentialId, i.credentialId)) continue;
656
+ let t = await rt(await st(i.prfOutput, r[e].salt), n[e].body);
657
+ if (t) return t;
658
+ }
659
+ return null;
660
+ }
661
+ for (let n of e.stanzas) {
662
+ if (n.type !== "eoa-signature") continue;
663
+ let [e] = X(n, 1, [q]), r = await rt(await ht(await t.signMessage(dt(e)), e), n.body);
664
+ if (r) return r;
665
+ }
666
+ return null;
667
+ }
668
+ function Z(e, t) {
669
+ return e.length === t.length && e.every((e, n) => e === t[n]);
670
+ }
671
+ async function xt(e, t, n = {}) {
672
+ let r = yt(e);
673
+ if (n.expectKeyId !== void 0 && r.bind.keyId !== n.expectKeyId) throw new _("BIND_MISMATCH", "Keystore manifest is for another key id");
674
+ let i = { fileKey: null }, a = await A(e, { unwrap: async (e) => i.fileKey = await bt(e, t) });
675
+ if (a.contentType !== "application/vnd.seedprotocol.identity-secret" || a.body.length !== 32) throw new _("BAD_KEYSTORE", "Keystore manifest body is not an identity secret");
676
+ let o = await U(a.body);
677
+ if (o.keyId !== r.bind.keyId || !Z(await Y(o), i.fileKey)) throw new _("BAD_KEYSTORE", "Keystore manifest contents do not match its key id");
678
+ return o;
679
+ }
680
+ //#endregion
681
+ //#region src/passkey.ts
682
+ function St(e) {
683
+ let t = "";
684
+ for (let n of e) t += String.fromCharCode(n);
685
+ return btoa(t).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
686
+ }
687
+ function Ct(e) {
688
+ return e instanceof ArrayBuffer ? new Uint8Array(e) : new Uint8Array(e.buffer, e.byteOffset, e.byteLength);
689
+ }
690
+ function wt() {
691
+ return crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32));
692
+ }
693
+ function Tt(e = {}) {
694
+ return async (t) => {
695
+ let n = {};
696
+ for (let e of t) n[St(e.credentialId)] = { first: new Uint8Array(e.salt) };
697
+ let r = await navigator.credentials.get({ publicKey: {
698
+ challenge: wt(),
699
+ rpId: e.rpId,
700
+ allowCredentials: t.map((e) => ({
701
+ type: "public-key",
702
+ id: new Uint8Array(e.credentialId)
703
+ })),
704
+ userVerification: "required",
705
+ extensions: { prf: { evalByCredential: n } }
706
+ } });
707
+ if (!r) return null;
708
+ let i = r.getClientExtensionResults().prf?.results?.first;
709
+ if (!i) throw new _("PASSKEY_PRF_UNSUPPORTED", "This passkey or browser does not support the PRF extension");
710
+ return {
711
+ credentialId: new Uint8Array(r.rawId),
712
+ prfOutput: Ct(i)
713
+ };
714
+ };
715
+ }
716
+ async function Et(e, t) {
717
+ let n = await navigator.credentials.create({ publicKey: {
718
+ challenge: wt(),
719
+ rp: {
720
+ name: t.rpName,
721
+ id: t.rpId
722
+ },
723
+ user: {
724
+ id: crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)),
725
+ name: t.userName,
726
+ displayName: t.userName
727
+ },
728
+ pubKeyCredParams: [{
729
+ type: "public-key",
730
+ alg: -7
731
+ }, {
732
+ type: "public-key",
733
+ alg: -257
734
+ }],
735
+ authenticatorSelection: {
736
+ residentKey: "preferred",
737
+ userVerification: "required"
738
+ },
739
+ extensions: { prf: {} }
740
+ } });
741
+ if (!n) throw new _("PASSKEY_PRF_UNSUPPORTED", "No passkey was created");
742
+ if (n.getClientExtensionResults().prf?.enabled === !1) throw new _("PASSKEY_PRF_UNSUPPORTED", "This passkey does not support the PRF extension");
743
+ let r = new Uint8Array(n.rawId), i = ct(), a = await Tt(t)([{
744
+ credentialId: r,
745
+ salt: i
746
+ }]);
747
+ if (!a) throw new _("PASSKEY_PRF_UNSUPPORTED", "The passkey was not used");
748
+ return lt(e, {
749
+ credentialId: r,
750
+ salt: i,
751
+ prfOutput: a.prfOutput
752
+ });
753
+ }
754
+ //#endregion
755
+ //#region src/deviceStore.ts
756
+ var Dt = "seed-encryption", Q = "identities";
757
+ function Ot(e) {
758
+ return new Promise((t, n) => {
759
+ e.onsuccess = () => t(e.result), e.onerror = () => n(e.error);
760
+ });
761
+ }
762
+ function kt() {
763
+ let e = indexedDB.open(Dt, 1);
764
+ return e.onupgradeneeded = () => e.result.createObjectStore(Q, { keyPath: "keyId" }), Ot(e);
765
+ }
766
+ async function $(e, t) {
767
+ let n = await kt();
768
+ try {
769
+ let r = n.transaction(Q, e), i = new Promise((e, t) => {
770
+ r.oncomplete = () => e(), r.onerror = () => t(r.error), r.onabort = () => t(r.error);
771
+ }), a = await Ot(t(r.objectStore(Q)));
772
+ return await i, a;
773
+ } finally {
774
+ n.close();
775
+ }
776
+ }
777
+ async function At(e) {
778
+ let t = await crypto.subtle.generateKey({
779
+ name: "AES-GCM",
780
+ length: 256
781
+ }, !1, ["encrypt", "decrypt"]), n = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12)), r = new TextEncoder().encode(e.keyId), i = new Uint8Array(await crypto.subtle.encrypt({
782
+ name: "AES-GCM",
783
+ iv: n,
784
+ additionalData: r
785
+ }, t, new Uint8Array(e.secret))), a = {
786
+ keyId: e.keyId,
787
+ deviceKey: t,
788
+ iv: n,
789
+ ciphertext: i,
790
+ savedAt: Date.now()
791
+ };
792
+ await $("readwrite", (e) => e.put(a));
793
+ }
794
+ async function jt(e) {
795
+ let t = await $("readonly", (t) => t.get(e));
796
+ if (!t) return null;
797
+ let n;
798
+ try {
799
+ n = new Uint8Array(await crypto.subtle.decrypt({
800
+ name: "AES-GCM",
801
+ iv: new Uint8Array(t.iv),
802
+ additionalData: new TextEncoder().encode(e)
803
+ }, t.deviceKey, new Uint8Array(t.ciphertext)));
804
+ } catch {
805
+ throw new _("BAD_KEYSTORE", `The identity saved for ${e} does not decrypt`);
806
+ }
807
+ let r = await U(n);
808
+ if (r.keyId !== e) throw new _("BAD_KEYSTORE", `The identity saved for ${e} has another key id`);
809
+ return r;
810
+ }
811
+ async function Mt() {
812
+ return await $("readonly", (e) => e.getAllKeys());
813
+ }
814
+ async function Nt(e) {
815
+ await $("readwrite", (t) => t.delete(e));
816
+ }
817
+ //#endregion
818
+ //#region src/uploadEncryptor.ts
819
+ function Pt(e) {
820
+ let t = e.recipients.map((e) => new Uint8Array(e));
821
+ if (t.length === 0) throw new _("BAD_RECIPIENT_KEY", "A private upload needs at least one recipient");
822
+ for (let e of t) if (e.length !== 1216) throw new _("BAD_RECIPIENT_KEY", `Recipient public key must be ${j} bytes`);
823
+ if (e.bind && "envelopeId" in e.bind) throw new _("BAD_BIND", "envelopeId is chosen per upload; leave it out of bind");
824
+ return async ({ blob: n, contentType: r }) => {
825
+ let i = b(), a = await O({
826
+ fileKey: i,
827
+ bind: {
828
+ ...e.bind,
829
+ envelopeId: x()
830
+ },
831
+ stanzas: await Promise.all(t.map((e) => R(i, e))),
832
+ contentType: r || "application/octet-stream",
833
+ body: new Uint8Array(await n.arrayBuffer()),
834
+ padding: e.padding
835
+ });
836
+ return {
837
+ blob: new Blob([a]),
838
+ tags: [{ ...te }]
839
+ };
840
+ };
841
+ }
842
+ //#endregion
843
+ //#region src/envelopeDecryptor.ts
844
+ function Ft(e) {
845
+ let t = Re(e.map((e) => e.recipient.secretKey));
846
+ return async (e) => {
847
+ try {
848
+ let { contentType: n, body: r } = await A(e, { unwrap: t });
849
+ return {
850
+ contentType: n,
851
+ body: r
852
+ };
853
+ } catch (e) {
854
+ if (e instanceof _ && e.code === "NO_KEY") return null;
855
+ throw e;
856
+ }
857
+ };
858
+ }
859
+ //#endregion
860
+ export { d as CHUNK_SIZE, ee as ENVELOPE_CONTENT_TYPE, u as ENVELOPE_FORMAT, te as ENVELOPE_FORMAT_TAG, Qe as EOA_SIGNATURE_STANZA_TYPE, _ as EnvelopeError, ne as FILE_KEY_LENGTH, He as IDENTITY_SECRET_LENGTH, Ze as KEYSTORE_CONTENT_TYPE, K as PASSKEY_PRF_STANZA_TYPE, ze as UnknownEntitlementKindError, j as XWING_PUBLIC_KEY_LENGTH, Te as XWING_SECRET_KEY_LENGTH, I as XWING_STANZA_TYPE, _t as buildKeystoreManifest, C as canonicalBind, qe as createEncryptionIdentity, Ft as createEnvelopeDecryptor, Pt as createPrivateUploadEncryptor, A as decryptEnvelope, vt as describeKeystoreManifest, O as encryptEnvelope, U as encryptionIdentityFromSecret, We as encryptionKeyId, Et as enrollPasskey, dt as eoaSignatureMessage, gt as eoaSignatureStanza, Nt as forgetIdentityOnDevice, x as generateEnvelopeId, ft as generateEoaSignatureSalt, b as generateFileKey, ct as generatePasskeySalt, L as generateRecipientKeyPair, Je as generateRecoveryPhrase, Ve as isEntitled, S as isEnvelope, G as keyBindingMessage, Mt as listIdentitiesOnDevice, jt as loadIdentityFromDevice, xt as openKeystoreManifest, ve as parseEnvelopeHeader, Tt as passkeyPrf, lt as passkeyStanza, Xe as recoveryKeyFromPhrase, ot as recoveryStanza, Be as registerEntitlementAdapter, At as saveIdentityOnDevice, Ge as signKeyBinding, z as unwrapFileKey, Re as unwrapWithSecretKeys, Ke as verifyKeyBinding, R as wrapFileKey };
861
+
862
+ //# sourceMappingURL=index.js.map