@seedprotocol/encryption 0.8.4-next.1935.g0be0d7b → 0.8.4-next.1983.g8eb1851

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