@poolse/crypto 0.0.0-stage → 3.10.0
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/CHANGELOG.md +60 -0
- package/LICENSE +206 -0
- package/README.md +529 -2
- package/dist/index.cjs +2574 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1088 -0
- package/dist/index.d.ts +1088 -0
- package/dist/index.js +2487 -0
- package/dist/index.js.map +1 -0
- package/package.json +59 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,2487 @@
|
|
|
1
|
+
// src/errors.ts
|
|
2
|
+
var PoolseCryptoError = class extends Error {
|
|
3
|
+
constructor(code, message) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.code = code;
|
|
6
|
+
}
|
|
7
|
+
code;
|
|
8
|
+
name = "PoolseCryptoError";
|
|
9
|
+
};
|
|
10
|
+
var BlobConflictError = class extends Error {
|
|
11
|
+
constructor(key, currentVersion = null) {
|
|
12
|
+
super(`Blob "${key}" was changed by another device`);
|
|
13
|
+
this.key = key;
|
|
14
|
+
this.currentVersion = currentVersion;
|
|
15
|
+
}
|
|
16
|
+
key;
|
|
17
|
+
currentVersion;
|
|
18
|
+
name = "BlobConflictError";
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
// src/bytes.ts
|
|
22
|
+
function toBytes(input) {
|
|
23
|
+
return new Uint8Array(input);
|
|
24
|
+
}
|
|
25
|
+
function concat(...parts) {
|
|
26
|
+
let length = 0;
|
|
27
|
+
for (const part of parts) length += part.length;
|
|
28
|
+
const out = new Uint8Array(length);
|
|
29
|
+
let offset = 0;
|
|
30
|
+
for (const part of parts) {
|
|
31
|
+
out.set(part, offset);
|
|
32
|
+
offset += part.length;
|
|
33
|
+
}
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
var encoder;
|
|
37
|
+
var decoder;
|
|
38
|
+
function utf8(text) {
|
|
39
|
+
if (encoder === void 0) encoder = typeof TextEncoder === "function" ? new TextEncoder() : null;
|
|
40
|
+
if (encoder) return new Uint8Array(encoder.encode(text));
|
|
41
|
+
const out = [];
|
|
42
|
+
for (const ch of text) {
|
|
43
|
+
let cp = ch.codePointAt(0);
|
|
44
|
+
if (cp >= 55296 && cp <= 57343) cp = 65533;
|
|
45
|
+
if (cp < 128) out.push(cp);
|
|
46
|
+
else if (cp < 2048) out.push(192 | cp >> 6, 128 | cp & 63);
|
|
47
|
+
else if (cp < 65536) out.push(224 | cp >> 12, 128 | cp >> 6 & 63, 128 | cp & 63);
|
|
48
|
+
else {
|
|
49
|
+
out.push(
|
|
50
|
+
240 | cp >> 18,
|
|
51
|
+
128 | cp >> 12 & 63,
|
|
52
|
+
128 | cp >> 6 & 63,
|
|
53
|
+
128 | cp & 63
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return Uint8Array.from(out);
|
|
58
|
+
}
|
|
59
|
+
function fromUtf8(bytes) {
|
|
60
|
+
if (decoder === void 0) {
|
|
61
|
+
try {
|
|
62
|
+
decoder = typeof TextDecoder === "function" ? new TextDecoder("utf-8", { fatal: true }) : null;
|
|
63
|
+
} catch {
|
|
64
|
+
decoder = null;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if (decoder) {
|
|
68
|
+
try {
|
|
69
|
+
return decoder.decode(bytes);
|
|
70
|
+
} catch {
|
|
71
|
+
throw new PoolseCryptoError("malformed", "Decrypted data is not valid UTF-8");
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return decodeUtf8Strict(bytes);
|
|
75
|
+
}
|
|
76
|
+
function decodeUtf8Strict(bytes) {
|
|
77
|
+
const invalid = () => new PoolseCryptoError("malformed", "Decrypted data is not valid UTF-8");
|
|
78
|
+
let out = "";
|
|
79
|
+
for (let i = 0; i < bytes.length; ) {
|
|
80
|
+
const b0 = bytes[i];
|
|
81
|
+
let cp;
|
|
82
|
+
let need;
|
|
83
|
+
let min;
|
|
84
|
+
if (b0 < 128) {
|
|
85
|
+
out += String.fromCharCode(b0);
|
|
86
|
+
i++;
|
|
87
|
+
continue;
|
|
88
|
+
} else if (b0 >= 194 && b0 <= 223) {
|
|
89
|
+
cp = b0 & 31;
|
|
90
|
+
need = 1;
|
|
91
|
+
min = 128;
|
|
92
|
+
} else if (b0 >= 224 && b0 <= 239) {
|
|
93
|
+
cp = b0 & 15;
|
|
94
|
+
need = 2;
|
|
95
|
+
min = 2048;
|
|
96
|
+
} else if (b0 >= 240 && b0 <= 244) {
|
|
97
|
+
cp = b0 & 7;
|
|
98
|
+
need = 3;
|
|
99
|
+
min = 65536;
|
|
100
|
+
} else {
|
|
101
|
+
throw invalid();
|
|
102
|
+
}
|
|
103
|
+
for (let k = 1; k <= need; k++) {
|
|
104
|
+
const b = bytes[i + k];
|
|
105
|
+
if (b === void 0 || (b & 192) !== 128) throw invalid();
|
|
106
|
+
cp = cp << 6 | b & 63;
|
|
107
|
+
}
|
|
108
|
+
if (cp < min || cp > 1114111 || cp >= 55296 && cp <= 57343) throw invalid();
|
|
109
|
+
out += String.fromCodePoint(cp);
|
|
110
|
+
i += need + 1;
|
|
111
|
+
}
|
|
112
|
+
return out;
|
|
113
|
+
}
|
|
114
|
+
function constantTimeEqual(a, b) {
|
|
115
|
+
if (a.length !== b.length) return false;
|
|
116
|
+
let diff = 0;
|
|
117
|
+
for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
|
|
118
|
+
return diff === 0;
|
|
119
|
+
}
|
|
120
|
+
var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
121
|
+
var B64_LOOKUP = new Int16Array(128).fill(-1);
|
|
122
|
+
for (let i = 0; i < B64.length; i++) B64_LOOKUP[B64.charCodeAt(i)] = i;
|
|
123
|
+
function toBase64Url(bytes) {
|
|
124
|
+
let out = "";
|
|
125
|
+
let i = 0;
|
|
126
|
+
for (; i + 2 < bytes.length; i += 3) {
|
|
127
|
+
const n = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2];
|
|
128
|
+
out += B64[n >> 18 & 63] + B64[n >> 12 & 63] + B64[n >> 6 & 63] + B64[n & 63];
|
|
129
|
+
}
|
|
130
|
+
const rest = bytes.length - i;
|
|
131
|
+
if (rest === 1) {
|
|
132
|
+
const n = bytes[i] << 16;
|
|
133
|
+
out += B64[n >> 18 & 63] + B64[n >> 12 & 63];
|
|
134
|
+
} else if (rest === 2) {
|
|
135
|
+
const n = bytes[i] << 16 | bytes[i + 1] << 8;
|
|
136
|
+
out += B64[n >> 18 & 63] + B64[n >> 12 & 63] + B64[n >> 6 & 63];
|
|
137
|
+
}
|
|
138
|
+
return out;
|
|
139
|
+
}
|
|
140
|
+
function fromBase64Url(text) {
|
|
141
|
+
const clean = text.replace(/=+$/, "");
|
|
142
|
+
if (clean.length % 4 === 1) throw new PoolseCryptoError("malformed", "Invalid base64url length");
|
|
143
|
+
const out = new Uint8Array(Math.floor(clean.length * 3 / 4));
|
|
144
|
+
let buffer = 0;
|
|
145
|
+
let bits = 0;
|
|
146
|
+
let o = 0;
|
|
147
|
+
for (let i = 0; i < clean.length; i++) {
|
|
148
|
+
let code = clean.charCodeAt(i);
|
|
149
|
+
if (code === 43) code = 45;
|
|
150
|
+
if (code === 47) code = 95;
|
|
151
|
+
const value = code < 128 ? B64_LOOKUP[code] : -1;
|
|
152
|
+
if (value < 0) throw new PoolseCryptoError("malformed", "Invalid base64url character");
|
|
153
|
+
buffer = (buffer << 6 | value) & 65535;
|
|
154
|
+
bits += 6;
|
|
155
|
+
if (bits >= 8) {
|
|
156
|
+
bits -= 8;
|
|
157
|
+
out[o++] = buffer >> bits & 255;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
if ((buffer & (1 << bits) - 1) !== 0) {
|
|
161
|
+
throw new PoolseCryptoError("malformed", "Invalid base64url padding bits");
|
|
162
|
+
}
|
|
163
|
+
return out;
|
|
164
|
+
}
|
|
165
|
+
var B32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
166
|
+
function toBase32(bytes) {
|
|
167
|
+
let out = "";
|
|
168
|
+
let buffer = 0;
|
|
169
|
+
let bits = 0;
|
|
170
|
+
for (const byte of bytes) {
|
|
171
|
+
buffer = (buffer << 8 | byte) & 65535;
|
|
172
|
+
bits += 8;
|
|
173
|
+
while (bits >= 5) {
|
|
174
|
+
bits -= 5;
|
|
175
|
+
out += B32[buffer >> bits & 31];
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
if (bits > 0) out += B32[buffer << 5 - bits & 31];
|
|
179
|
+
return out;
|
|
180
|
+
}
|
|
181
|
+
function fromBase32(text) {
|
|
182
|
+
const clean = text.toUpperCase().replace(/[\s-]/g, "");
|
|
183
|
+
const out = new Uint8Array(Math.floor(clean.length * 5 / 8));
|
|
184
|
+
let buffer = 0;
|
|
185
|
+
let bits = 0;
|
|
186
|
+
let o = 0;
|
|
187
|
+
for (const raw of clean) {
|
|
188
|
+
const ch = raw === "O" ? "0" : raw === "I" || raw === "L" ? "1" : raw;
|
|
189
|
+
const value = B32.indexOf(ch);
|
|
190
|
+
if (value < 0) throw new PoolseCryptoError("malformed", "Invalid base32 character");
|
|
191
|
+
buffer = (buffer << 5 | value) & 65535;
|
|
192
|
+
bits += 5;
|
|
193
|
+
if (bits >= 8) {
|
|
194
|
+
bits -= 8;
|
|
195
|
+
out[o++] = buffer >> bits & 255;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
if ((buffer & (1 << bits) - 1) !== 0) {
|
|
199
|
+
throw new PoolseCryptoError("malformed", "Invalid base32 padding bits");
|
|
200
|
+
}
|
|
201
|
+
return out;
|
|
202
|
+
}
|
|
203
|
+
function toHex(bytes) {
|
|
204
|
+
let out = "";
|
|
205
|
+
for (const byte of bytes) out += byte.toString(16).padStart(2, "0");
|
|
206
|
+
return out;
|
|
207
|
+
}
|
|
208
|
+
function fromHex(hex) {
|
|
209
|
+
if (hex.length % 2 !== 0 || /[^0-9a-f]/i.test(hex)) {
|
|
210
|
+
throw new PoolseCryptoError("malformed", "Invalid hex");
|
|
211
|
+
}
|
|
212
|
+
const out = new Uint8Array(hex.length / 2);
|
|
213
|
+
for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
214
|
+
return out;
|
|
215
|
+
}
|
|
216
|
+
var ByteWriter = class {
|
|
217
|
+
parts = [];
|
|
218
|
+
u8(value) {
|
|
219
|
+
this.parts.push(Uint8Array.of(value & 255));
|
|
220
|
+
return this;
|
|
221
|
+
}
|
|
222
|
+
u16(value) {
|
|
223
|
+
if (!Number.isInteger(value) || value < 0 || value > 65535) {
|
|
224
|
+
throw new PoolseCryptoError("malformed", "Value does not fit in 16 bits");
|
|
225
|
+
}
|
|
226
|
+
this.parts.push(Uint8Array.of(value >>> 8, value & 255));
|
|
227
|
+
return this;
|
|
228
|
+
}
|
|
229
|
+
u32(value) {
|
|
230
|
+
if (!Number.isInteger(value) || value < 0 || value > 4294967295) {
|
|
231
|
+
throw new PoolseCryptoError("malformed", "Value does not fit in 32 bits");
|
|
232
|
+
}
|
|
233
|
+
const b = new Uint8Array(4);
|
|
234
|
+
new DataView(b.buffer).setUint32(0, value);
|
|
235
|
+
this.parts.push(b);
|
|
236
|
+
return this;
|
|
237
|
+
}
|
|
238
|
+
/** A non-negative safe integer as 8 bytes. */
|
|
239
|
+
u64(value) {
|
|
240
|
+
if (!Number.isSafeInteger(value) || value < 0) {
|
|
241
|
+
throw new PoolseCryptoError("malformed", "Value is not a non-negative safe integer");
|
|
242
|
+
}
|
|
243
|
+
const b = new Uint8Array(8);
|
|
244
|
+
new DataView(b.buffer).setBigUint64(0, BigInt(value));
|
|
245
|
+
this.parts.push(b);
|
|
246
|
+
return this;
|
|
247
|
+
}
|
|
248
|
+
bytes(value) {
|
|
249
|
+
this.parts.push(value);
|
|
250
|
+
return this;
|
|
251
|
+
}
|
|
252
|
+
/** Bytes with a 16-bit length prefix. */
|
|
253
|
+
bytes16(value) {
|
|
254
|
+
return this.u16(value.length).bytes(value);
|
|
255
|
+
}
|
|
256
|
+
/** Bytes with a 32-bit length prefix. */
|
|
257
|
+
bytes32(value) {
|
|
258
|
+
return this.u32(value.length).bytes(value);
|
|
259
|
+
}
|
|
260
|
+
finish() {
|
|
261
|
+
return concat(...this.parts);
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
var ByteReader = class {
|
|
265
|
+
constructor(data) {
|
|
266
|
+
this.data = data;
|
|
267
|
+
}
|
|
268
|
+
data;
|
|
269
|
+
offset = 0;
|
|
270
|
+
take(length) {
|
|
271
|
+
if (this.offset + length > this.data.length) {
|
|
272
|
+
throw new PoolseCryptoError("malformed", "Data is truncated");
|
|
273
|
+
}
|
|
274
|
+
const out = new Uint8Array(this.data.subarray(this.offset, this.offset + length));
|
|
275
|
+
this.offset += length;
|
|
276
|
+
return out;
|
|
277
|
+
}
|
|
278
|
+
u8() {
|
|
279
|
+
return this.take(1)[0];
|
|
280
|
+
}
|
|
281
|
+
u16() {
|
|
282
|
+
const b = this.take(2);
|
|
283
|
+
return b[0] << 8 | b[1];
|
|
284
|
+
}
|
|
285
|
+
u32() {
|
|
286
|
+
return new DataView(this.take(4).buffer).getUint32(0);
|
|
287
|
+
}
|
|
288
|
+
u64() {
|
|
289
|
+
const value = new DataView(this.take(8).buffer).getBigUint64(0);
|
|
290
|
+
if (value > BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
291
|
+
throw new PoolseCryptoError("malformed", "Integer is out of range");
|
|
292
|
+
}
|
|
293
|
+
return Number(value);
|
|
294
|
+
}
|
|
295
|
+
bytes(length) {
|
|
296
|
+
return this.take(length);
|
|
297
|
+
}
|
|
298
|
+
bytes16() {
|
|
299
|
+
return this.take(this.u16());
|
|
300
|
+
}
|
|
301
|
+
bytes32() {
|
|
302
|
+
return this.take(this.u32());
|
|
303
|
+
}
|
|
304
|
+
/** Everything from the start up to the current position. */
|
|
305
|
+
consumed() {
|
|
306
|
+
return new Uint8Array(this.data.subarray(0, this.offset));
|
|
307
|
+
}
|
|
308
|
+
rest() {
|
|
309
|
+
return this.take(this.data.length - this.offset);
|
|
310
|
+
}
|
|
311
|
+
remaining() {
|
|
312
|
+
return this.data.length - this.offset;
|
|
313
|
+
}
|
|
314
|
+
/** Refuse trailing bytes: every envelope has exactly one valid length. */
|
|
315
|
+
end() {
|
|
316
|
+
if (this.offset !== this.data.length) {
|
|
317
|
+
throw new PoolseCryptoError("malformed", "Unexpected trailing data");
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
};
|
|
321
|
+
|
|
322
|
+
// src/subtle.ts
|
|
323
|
+
function cryptoObject() {
|
|
324
|
+
const c = globalThis.crypto;
|
|
325
|
+
if (!c || !c.subtle || typeof c.getRandomValues !== "function") {
|
|
326
|
+
throw new PoolseCryptoError(
|
|
327
|
+
"unavailable",
|
|
328
|
+
"WebCrypto is not available: globalThis.crypto.subtle is missing. On React Native install a polyfill such as react-native-quick-crypto first."
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
return c;
|
|
332
|
+
}
|
|
333
|
+
function subtle() {
|
|
334
|
+
return cryptoObject().subtle;
|
|
335
|
+
}
|
|
336
|
+
function randomBytes(length) {
|
|
337
|
+
const out = new Uint8Array(length);
|
|
338
|
+
for (let offset = 0; offset < length; offset += 65536) {
|
|
339
|
+
cryptoObject().getRandomValues(out.subarray(offset, Math.min(length, offset + 65536)));
|
|
340
|
+
}
|
|
341
|
+
return out;
|
|
342
|
+
}
|
|
343
|
+
async function sha256(data) {
|
|
344
|
+
return new Uint8Array(await subtle().digest("SHA-256", toBytes(data)));
|
|
345
|
+
}
|
|
346
|
+
async function hkdf(ikm, salt, info, length = 32) {
|
|
347
|
+
const base = await subtle().importKey("raw", toBytes(ikm), "HKDF", false, ["deriveBits"]);
|
|
348
|
+
const bits = await subtle().deriveBits(
|
|
349
|
+
{ name: "HKDF", hash: "SHA-256", salt: toBytes(salt), info: toBytes(info) },
|
|
350
|
+
base,
|
|
351
|
+
length * 8
|
|
352
|
+
);
|
|
353
|
+
return new Uint8Array(bits);
|
|
354
|
+
}
|
|
355
|
+
var IV_LENGTH = 12;
|
|
356
|
+
var TAG_LENGTH = 16;
|
|
357
|
+
async function aesKey(raw) {
|
|
358
|
+
if (raw.length !== 32) throw new PoolseCryptoError("malformed", "AES keys are 32 bytes");
|
|
359
|
+
return subtle().importKey("raw", toBytes(raw), { name: "AES-GCM" }, false, [
|
|
360
|
+
"encrypt",
|
|
361
|
+
"decrypt"
|
|
362
|
+
]);
|
|
363
|
+
}
|
|
364
|
+
async function aesEncrypt(key, iv, plaintext, aad) {
|
|
365
|
+
const out = await subtle().encrypt(
|
|
366
|
+
{ name: "AES-GCM", iv: toBytes(iv), additionalData: toBytes(aad), tagLength: 128 },
|
|
367
|
+
key,
|
|
368
|
+
toBytes(plaintext)
|
|
369
|
+
);
|
|
370
|
+
return new Uint8Array(out);
|
|
371
|
+
}
|
|
372
|
+
async function aesDecrypt(key, iv, ciphertext, aad) {
|
|
373
|
+
if (ciphertext.length < TAG_LENGTH)
|
|
374
|
+
throw new PoolseCryptoError("malformed", "Ciphertext is too short");
|
|
375
|
+
try {
|
|
376
|
+
const out = await subtle().decrypt(
|
|
377
|
+
{ name: "AES-GCM", iv: toBytes(iv), additionalData: toBytes(aad), tagLength: 128 },
|
|
378
|
+
key,
|
|
379
|
+
toBytes(ciphertext)
|
|
380
|
+
);
|
|
381
|
+
return new Uint8Array(out);
|
|
382
|
+
} catch {
|
|
383
|
+
throw new PoolseCryptoError(
|
|
384
|
+
"tampered",
|
|
385
|
+
"Decryption failed: the data or its associated data was changed"
|
|
386
|
+
);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
async function hmacKey(raw, usage) {
|
|
390
|
+
return subtle().importKey("raw", toBytes(raw), { name: "HMAC", hash: "SHA-256" }, false, [usage]);
|
|
391
|
+
}
|
|
392
|
+
async function hmac(key, data) {
|
|
393
|
+
return new Uint8Array(await subtle().sign("HMAC", await hmacKey(key, "sign"), toBytes(data)));
|
|
394
|
+
}
|
|
395
|
+
async function hmacVerify(key, data, mac) {
|
|
396
|
+
return subtle().verify("HMAC", await hmacKey(key, "verify"), toBytes(mac), toBytes(data));
|
|
397
|
+
}
|
|
398
|
+
var P256_PUBLIC_LENGTH = 65;
|
|
399
|
+
var P256_SCALAR_LENGTH = 32;
|
|
400
|
+
var ECDSA_SIGNATURE_LENGTH = 64;
|
|
401
|
+
var ECDH = { name: "ECDH", namedCurve: "P-256" };
|
|
402
|
+
var ECDSA = { name: "ECDSA", namedCurve: "P-256" };
|
|
403
|
+
var ECDSA_SIGN = { name: "ECDSA", hash: "SHA-256" };
|
|
404
|
+
async function generateP256(use) {
|
|
405
|
+
return use === "ecdh" ? subtle().generateKey(ECDH, true, ["deriveBits"]) : subtle().generateKey(ECDSA, true, ["sign", "verify"]);
|
|
406
|
+
}
|
|
407
|
+
async function importP256Public(use, raw) {
|
|
408
|
+
if (raw.length !== P256_PUBLIC_LENGTH || raw[0] !== 4) {
|
|
409
|
+
throw new PoolseCryptoError("malformed", "Expected an uncompressed P-256 public key");
|
|
410
|
+
}
|
|
411
|
+
try {
|
|
412
|
+
return use === "ecdh" ? await subtle().importKey("raw", toBytes(raw), ECDH, true, []) : await subtle().importKey("raw", toBytes(raw), ECDSA, true, ["verify"]);
|
|
413
|
+
} catch {
|
|
414
|
+
throw new PoolseCryptoError("malformed", "Invalid P-256 public key");
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
async function exportP256Public(key) {
|
|
418
|
+
return new Uint8Array(await subtle().exportKey("raw", key));
|
|
419
|
+
}
|
|
420
|
+
async function exportP256Private(key) {
|
|
421
|
+
const jwk = await subtle().exportKey("jwk", key);
|
|
422
|
+
if (!jwk.d) throw new PoolseCryptoError("malformed", "Not a private key");
|
|
423
|
+
const d = fromBase64Url(jwk.d);
|
|
424
|
+
if (d.length !== P256_SCALAR_LENGTH)
|
|
425
|
+
throw new PoolseCryptoError("malformed", "Invalid P-256 scalar");
|
|
426
|
+
return d;
|
|
427
|
+
}
|
|
428
|
+
async function importP256Private(use, scalar, publicRaw, extractable) {
|
|
429
|
+
if (scalar.length !== P256_SCALAR_LENGTH || publicRaw.length !== P256_PUBLIC_LENGTH) {
|
|
430
|
+
throw new PoolseCryptoError("malformed", "Invalid P-256 private key");
|
|
431
|
+
}
|
|
432
|
+
const jwk = {
|
|
433
|
+
kty: "EC",
|
|
434
|
+
crv: "P-256",
|
|
435
|
+
d: toBase64Url(scalar),
|
|
436
|
+
x: toBase64Url(publicRaw.subarray(1, 33)),
|
|
437
|
+
y: toBase64Url(publicRaw.subarray(33, 65)),
|
|
438
|
+
ext: extractable
|
|
439
|
+
};
|
|
440
|
+
try {
|
|
441
|
+
return use === "ecdh" ? await subtle().importKey("jwk", jwk, ECDH, extractable, ["deriveBits"]) : await subtle().importKey("jwk", jwk, ECDSA, extractable, ["sign"]);
|
|
442
|
+
} catch {
|
|
443
|
+
throw new PoolseCryptoError("malformed", "Invalid P-256 private key");
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
async function ecdh(privateKey, publicKey) {
|
|
447
|
+
return new Uint8Array(
|
|
448
|
+
await subtle().deriveBits({ name: "ECDH", public: publicKey }, privateKey, 256)
|
|
449
|
+
);
|
|
450
|
+
}
|
|
451
|
+
async function ecdsaSign(privateKey, data) {
|
|
452
|
+
return new Uint8Array(await subtle().sign(ECDSA_SIGN, privateKey, toBytes(data)));
|
|
453
|
+
}
|
|
454
|
+
async function ecdsaVerify(publicKey, signature, data) {
|
|
455
|
+
if (signature.length !== ECDSA_SIGNATURE_LENGTH) return false;
|
|
456
|
+
return subtle().verify(ECDSA_SIGN, publicKey, toBytes(signature), toBytes(data));
|
|
457
|
+
}
|
|
458
|
+
function label(...parts) {
|
|
459
|
+
return concat(...parts.map((p) => typeof p === "string" ? utf8(p) : p));
|
|
460
|
+
}
|
|
461
|
+
async function checkCryptoSupport() {
|
|
462
|
+
const missing = [];
|
|
463
|
+
const attempt = async (name, fn) => {
|
|
464
|
+
try {
|
|
465
|
+
await fn();
|
|
466
|
+
} catch {
|
|
467
|
+
missing.push(name);
|
|
468
|
+
}
|
|
469
|
+
};
|
|
470
|
+
try {
|
|
471
|
+
cryptoObject();
|
|
472
|
+
} catch {
|
|
473
|
+
return { ok: false, missing: ["crypto.subtle"] };
|
|
474
|
+
}
|
|
475
|
+
await attempt("getRandomValues", async () => randomBytes(16));
|
|
476
|
+
await attempt("SHA-256", () => sha256(new Uint8Array(1)));
|
|
477
|
+
await attempt("HKDF", () => hkdf(new Uint8Array(32), new Uint8Array(0), new Uint8Array(0)));
|
|
478
|
+
await attempt("HMAC", () => hmac(new Uint8Array(32), new Uint8Array(1)));
|
|
479
|
+
await attempt("AES-GCM", async () => {
|
|
480
|
+
const key = await aesKey(new Uint8Array(32));
|
|
481
|
+
const iv = new Uint8Array(IV_LENGTH);
|
|
482
|
+
const ct = await aesEncrypt(key, iv, new Uint8Array(1), new Uint8Array(1));
|
|
483
|
+
await aesDecrypt(key, iv, ct, new Uint8Array(1));
|
|
484
|
+
});
|
|
485
|
+
await attempt("ECDH P-256", async () => {
|
|
486
|
+
const a = await generateP256("ecdh");
|
|
487
|
+
const raw = await exportP256Public(a.publicKey);
|
|
488
|
+
const d = await exportP256Private(a.privateKey);
|
|
489
|
+
const priv = await importP256Private("ecdh", d, raw, false);
|
|
490
|
+
await ecdh(priv, await importP256Public("ecdh", raw));
|
|
491
|
+
});
|
|
492
|
+
await attempt("ECDSA P-256", async () => {
|
|
493
|
+
const a = await generateP256("ecdsa");
|
|
494
|
+
const raw = await exportP256Public(a.publicKey);
|
|
495
|
+
const sig = await ecdsaSign(a.privateKey, new Uint8Array(1));
|
|
496
|
+
if (!await ecdsaVerify(await importP256Public("ecdsa", raw), sig, new Uint8Array(1))) {
|
|
497
|
+
throw new Error("verify");
|
|
498
|
+
}
|
|
499
|
+
});
|
|
500
|
+
return { ok: missing.length === 0, missing };
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
// src/format.ts
|
|
504
|
+
var MAGIC = 112;
|
|
505
|
+
var FORMAT_VERSION = 1;
|
|
506
|
+
var Kind = {
|
|
507
|
+
Item: 1,
|
|
508
|
+
KeyWrap: 2,
|
|
509
|
+
PublicKeyWrap: 3,
|
|
510
|
+
Attachment: 4,
|
|
511
|
+
DeviceRequest: 5,
|
|
512
|
+
DeviceGrant: 6,
|
|
513
|
+
DevicePublicKeys: 7,
|
|
514
|
+
SyncRecord: 8,
|
|
515
|
+
DeviceSecret: 9
|
|
516
|
+
};
|
|
517
|
+
var Alg = {
|
|
518
|
+
/** No encryption (only for the device-key export when no wrapping key is given). */
|
|
519
|
+
None: 0,
|
|
520
|
+
/** AES-256-GCM, keys derived with HKDF-SHA-256. */
|
|
521
|
+
Aes256GcmHkdfSha256: 1,
|
|
522
|
+
/** P-256: ECDH + HKDF-SHA-256 + AES-256-GCM for wrapping, ECDSA/SHA-256 for signatures. */
|
|
523
|
+
P256: 2,
|
|
524
|
+
/** HMAC-SHA-256 over a P-256 payload (device grants). */
|
|
525
|
+
HmacSha256: 3
|
|
526
|
+
};
|
|
527
|
+
var KIND_NAMES = {
|
|
528
|
+
[Kind.Item]: "item",
|
|
529
|
+
[Kind.KeyWrap]: "key wrap",
|
|
530
|
+
[Kind.PublicKeyWrap]: "public key wrap",
|
|
531
|
+
[Kind.Attachment]: "attachment",
|
|
532
|
+
[Kind.DeviceRequest]: "device request",
|
|
533
|
+
[Kind.DeviceGrant]: "device grant",
|
|
534
|
+
[Kind.DevicePublicKeys]: "device public keys",
|
|
535
|
+
[Kind.SyncRecord]: "sync record",
|
|
536
|
+
[Kind.DeviceSecret]: "device secret"
|
|
537
|
+
};
|
|
538
|
+
var DOMAIN = "poolse-crypto/v1/";
|
|
539
|
+
var HEADER_LENGTH = 4;
|
|
540
|
+
function writeHeader(writer, kind, alg) {
|
|
541
|
+
return writer.u8(MAGIC).u8(FORMAT_VERSION).u8(kind).u8(alg);
|
|
542
|
+
}
|
|
543
|
+
function readHeader(reader, kind, algs) {
|
|
544
|
+
if (reader.remaining() < HEADER_LENGTH)
|
|
545
|
+
throw new PoolseCryptoError("malformed", "Data is truncated");
|
|
546
|
+
if (reader.u8() !== MAGIC) throw new PoolseCryptoError("malformed", "Not poolse-crypto data");
|
|
547
|
+
const version = reader.u8();
|
|
548
|
+
if (version > FORMAT_VERSION) {
|
|
549
|
+
throw new PoolseCryptoError(
|
|
550
|
+
"unsupported",
|
|
551
|
+
`Format version ${version} is newer than this library supports (${FORMAT_VERSION})`
|
|
552
|
+
);
|
|
553
|
+
}
|
|
554
|
+
if (version !== FORMAT_VERSION)
|
|
555
|
+
throw new PoolseCryptoError("malformed", `Unknown format version ${version}`);
|
|
556
|
+
const got = reader.u8();
|
|
557
|
+
if (got !== kind) {
|
|
558
|
+
throw new PoolseCryptoError(
|
|
559
|
+
"malformed",
|
|
560
|
+
`Expected ${KIND_NAMES[kind]} data, got ${KIND_NAMES[got] ?? `kind ${got}`}`
|
|
561
|
+
);
|
|
562
|
+
}
|
|
563
|
+
const alg = reader.u8();
|
|
564
|
+
if (!algs.includes(alg)) {
|
|
565
|
+
throw new PoolseCryptoError(
|
|
566
|
+
"unsupported",
|
|
567
|
+
`Unsupported algorithm ${alg} for ${KIND_NAMES[kind]}`
|
|
568
|
+
);
|
|
569
|
+
}
|
|
570
|
+
return alg;
|
|
571
|
+
}
|
|
572
|
+
function encodeAssociatedData(domain, data, internal = {}) {
|
|
573
|
+
for (const key of Object.keys(data)) {
|
|
574
|
+
if (key.startsWith("@")) {
|
|
575
|
+
throw new PoolseCryptoError("malformed", `Associated-data key "${key}" is reserved`);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
const merged = { ...data, ...internal };
|
|
579
|
+
const keys = Object.keys(merged).sort();
|
|
580
|
+
const w = new ByteWriter().bytes16(utf8(`${DOMAIN}ad/${domain}`)).u16(keys.length);
|
|
581
|
+
for (const key of keys) {
|
|
582
|
+
if (key.length === 0) throw new PoolseCryptoError("malformed", "Empty associated-data key");
|
|
583
|
+
const value = merged[key];
|
|
584
|
+
w.bytes16(utf8(key));
|
|
585
|
+
if (typeof value === "number") {
|
|
586
|
+
if (!Number.isFinite(value)) {
|
|
587
|
+
throw new PoolseCryptoError(
|
|
588
|
+
"malformed",
|
|
589
|
+
`Associated-data value for "${key}" is not finite`
|
|
590
|
+
);
|
|
591
|
+
}
|
|
592
|
+
w.u8(1).bytes32(utf8(String(value)));
|
|
593
|
+
} else if (typeof value === "string") {
|
|
594
|
+
w.u8(0).bytes32(utf8(value));
|
|
595
|
+
} else {
|
|
596
|
+
throw new PoolseCryptoError(
|
|
597
|
+
"malformed",
|
|
598
|
+
`Associated-data value for "${key}" must be a string or number`
|
|
599
|
+
);
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
return w.finish();
|
|
603
|
+
}
|
|
604
|
+
async function deriveAesKey(raw, purpose, salt = new Uint8Array(0)) {
|
|
605
|
+
return aesKey(await hkdf(raw, salt, label(DOMAIN, "key/", purpose)));
|
|
606
|
+
}
|
|
607
|
+
var CHECK_LENGTH = 16;
|
|
608
|
+
async function keyCheck(raw, purpose) {
|
|
609
|
+
return hkdf(raw, new Uint8Array(0), label(DOMAIN, "check/", purpose), CHECK_LENGTH);
|
|
610
|
+
}
|
|
611
|
+
async function verifyKeyCheck(raw, purpose, stored) {
|
|
612
|
+
if (!constantTimeEqual(await keyCheck(raw, purpose), stored)) {
|
|
613
|
+
throw new PoolseCryptoError("wrong-key", "This was encrypted with a different key");
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
async function keyId(raw, purpose) {
|
|
617
|
+
return hkdf(raw, new Uint8Array(0), label(DOMAIN, "id/", purpose), 16);
|
|
618
|
+
}
|
|
619
|
+
function padmeLength(length) {
|
|
620
|
+
if (length < 2) return length;
|
|
621
|
+
const e = Math.floor(Math.log2(length));
|
|
622
|
+
const s = Math.floor(Math.log2(e)) + 1;
|
|
623
|
+
const lastBits = e - s;
|
|
624
|
+
const mask = 2 ** lastBits - 1;
|
|
625
|
+
return Math.ceil(length / (mask + 1)) * (mask + 1);
|
|
626
|
+
}
|
|
627
|
+
function pad(data) {
|
|
628
|
+
const unpadded = 4 + data.length;
|
|
629
|
+
const out = new Uint8Array(Math.max(padmeLength(unpadded), 32));
|
|
630
|
+
new DataView(out.buffer).setUint32(0, data.length);
|
|
631
|
+
out.set(data, 4);
|
|
632
|
+
return out;
|
|
633
|
+
}
|
|
634
|
+
function unpad(padded) {
|
|
635
|
+
if (padded.length < 4) throw new PoolseCryptoError("malformed", "Padding is invalid");
|
|
636
|
+
const length = new DataView(padded.buffer, padded.byteOffset, padded.byteLength).getUint32(0);
|
|
637
|
+
if (4 + length > padded.length) throw new PoolseCryptoError("malformed", "Padding is invalid");
|
|
638
|
+
for (let i = 4 + length; i < padded.length; i++) {
|
|
639
|
+
if (padded[i] !== 0) throw new PoolseCryptoError("malformed", "Padding is invalid");
|
|
640
|
+
}
|
|
641
|
+
return new Uint8Array(padded.subarray(4, 4 + length));
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
// src/inspect.ts
|
|
645
|
+
var NAMES = {
|
|
646
|
+
[Kind.Item]: "item",
|
|
647
|
+
[Kind.KeyWrap]: "key-wrap",
|
|
648
|
+
[Kind.PublicKeyWrap]: "public-key-wrap",
|
|
649
|
+
[Kind.Attachment]: "attachment",
|
|
650
|
+
[Kind.DeviceRequest]: "device-request",
|
|
651
|
+
[Kind.DeviceGrant]: "device-grant",
|
|
652
|
+
[Kind.DevicePublicKeys]: "device-public-keys",
|
|
653
|
+
[Kind.SyncRecord]: "sync-record",
|
|
654
|
+
[Kind.DeviceSecret]: "device-secret"
|
|
655
|
+
};
|
|
656
|
+
function inspectEnvelope(data) {
|
|
657
|
+
const r = new ByteReader(data);
|
|
658
|
+
if (r.remaining() < 4 || r.u8() !== MAGIC) {
|
|
659
|
+
throw new PoolseCryptoError("malformed", "Not poolse-crypto data");
|
|
660
|
+
}
|
|
661
|
+
const formatVersion = r.u8();
|
|
662
|
+
if (formatVersion > FORMAT_VERSION) {
|
|
663
|
+
throw new PoolseCryptoError(
|
|
664
|
+
"unsupported",
|
|
665
|
+
`Format version ${formatVersion} is newer than this library`
|
|
666
|
+
);
|
|
667
|
+
}
|
|
668
|
+
const kindByte = r.u8();
|
|
669
|
+
const kind = NAMES[kindByte];
|
|
670
|
+
if (!kind) throw new PoolseCryptoError("malformed", `Unknown kind ${kindByte}`);
|
|
671
|
+
const info = { formatVersion, kind, alg: r.u8() };
|
|
672
|
+
switch (kindByte) {
|
|
673
|
+
case Kind.Item:
|
|
674
|
+
case Kind.Attachment:
|
|
675
|
+
info.keyVersion = r.u32();
|
|
676
|
+
break;
|
|
677
|
+
case Kind.KeyWrap:
|
|
678
|
+
r.u8();
|
|
679
|
+
info.keyVersion = r.u32();
|
|
680
|
+
break;
|
|
681
|
+
case Kind.PublicKeyWrap:
|
|
682
|
+
r.u8();
|
|
683
|
+
r.u8();
|
|
684
|
+
info.keyVersion = r.u32();
|
|
685
|
+
info.recipientId = toBase64Url(r.bytes(16));
|
|
686
|
+
break;
|
|
687
|
+
case Kind.SyncRecord:
|
|
688
|
+
info.revision = r.u64();
|
|
689
|
+
break;
|
|
690
|
+
}
|
|
691
|
+
return info;
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
// src/keys.ts
|
|
695
|
+
var secrets = /* @__PURE__ */ new WeakMap();
|
|
696
|
+
function secretOf(key) {
|
|
697
|
+
const raw = secrets.get(key);
|
|
698
|
+
if (!raw) throw new PoolseCryptoError("malformed", "Not a key created by @poolse/crypto");
|
|
699
|
+
return raw;
|
|
700
|
+
}
|
|
701
|
+
function setSecret(key, raw) {
|
|
702
|
+
secrets.set(key, raw);
|
|
703
|
+
}
|
|
704
|
+
var SYMMETRIC_LENGTH = 32;
|
|
705
|
+
function checkLength(bytes) {
|
|
706
|
+
if (bytes.length !== SYMMETRIC_LENGTH) {
|
|
707
|
+
throw new PoolseCryptoError("malformed", `Expected a ${SYMMETRIC_LENGTH}-byte key`);
|
|
708
|
+
}
|
|
709
|
+
return toBytes(bytes);
|
|
710
|
+
}
|
|
711
|
+
var AccountKey = class _AccountKey {
|
|
712
|
+
/** Public identifier (base64url) — safe to store next to wraps of this key. */
|
|
713
|
+
id;
|
|
714
|
+
constructor(raw, id) {
|
|
715
|
+
this.id = id;
|
|
716
|
+
setSecret(this, raw);
|
|
717
|
+
}
|
|
718
|
+
static async generate() {
|
|
719
|
+
return _AccountKey.fromBytes(randomBytes(SYMMETRIC_LENGTH));
|
|
720
|
+
}
|
|
721
|
+
/**
|
|
722
|
+
* From raw bytes, e.g. a copy the app cached in the keychain. Prefer
|
|
723
|
+
* keeping only the device-wrapped copy and unwrapping it at start.
|
|
724
|
+
*/
|
|
725
|
+
static async fromBytes(bytes) {
|
|
726
|
+
const raw = checkLength(bytes);
|
|
727
|
+
return new _AccountKey(raw, toBase64Url(await keyId(raw, "account")));
|
|
728
|
+
}
|
|
729
|
+
/** A copy of the 32 secret bytes. Handle with care. */
|
|
730
|
+
toBytes() {
|
|
731
|
+
return toBytes(secretOf(this));
|
|
732
|
+
}
|
|
733
|
+
toJSON() {
|
|
734
|
+
return { id: this.id };
|
|
735
|
+
}
|
|
736
|
+
};
|
|
737
|
+
var ItemKey = class _ItemKey {
|
|
738
|
+
/** Starts at 1 and goes up by one on every `rotateItemKey`. */
|
|
739
|
+
version;
|
|
740
|
+
constructor(raw, version) {
|
|
741
|
+
this.version = version;
|
|
742
|
+
setSecret(this, raw);
|
|
743
|
+
}
|
|
744
|
+
static generate(version = 1) {
|
|
745
|
+
return _ItemKey.fromBytes(randomBytes(SYMMETRIC_LENGTH), version);
|
|
746
|
+
}
|
|
747
|
+
static fromBytes(bytes, version) {
|
|
748
|
+
if (!Number.isInteger(version) || version < 1 || version > 4294967295) {
|
|
749
|
+
throw new PoolseCryptoError("malformed", "Item key version must be an integer from 1");
|
|
750
|
+
}
|
|
751
|
+
return new _ItemKey(checkLength(bytes), version);
|
|
752
|
+
}
|
|
753
|
+
/** A copy of the 32 secret bytes. Handle with care. */
|
|
754
|
+
toBytes() {
|
|
755
|
+
return toBytes(secretOf(this));
|
|
756
|
+
}
|
|
757
|
+
toJSON() {
|
|
758
|
+
return { version: this.version };
|
|
759
|
+
}
|
|
760
|
+
};
|
|
761
|
+
function rotateItemKey(previous) {
|
|
762
|
+
return ItemKey.generate(previous.version + 1);
|
|
763
|
+
}
|
|
764
|
+
async function deviceIdBytes(encryption, signing) {
|
|
765
|
+
return (await sha256(label(DOMAIN, "device-id", encryption, signing))).slice(0, 16);
|
|
766
|
+
}
|
|
767
|
+
async function devicePublicKeys(encryption, signing) {
|
|
768
|
+
await importP256Public("ecdh", encryption);
|
|
769
|
+
await importP256Public("ecdsa", signing);
|
|
770
|
+
return {
|
|
771
|
+
id: toBase64Url(await deviceIdBytes(encryption, signing)),
|
|
772
|
+
encryption: toBytes(encryption),
|
|
773
|
+
signing: toBytes(signing)
|
|
774
|
+
};
|
|
775
|
+
}
|
|
776
|
+
function encodeDevicePublicKeys(keys) {
|
|
777
|
+
const w = writeHeader(new ByteWriter(), Kind.DevicePublicKeys, Alg.P256);
|
|
778
|
+
return toBase64Url(w.bytes(keys.encryption).bytes(keys.signing).finish());
|
|
779
|
+
}
|
|
780
|
+
async function decodeDevicePublicKeys(text) {
|
|
781
|
+
const r = new ByteReader(fromBase64Url(text));
|
|
782
|
+
readHeader(r, Kind.DevicePublicKeys, [Alg.P256]);
|
|
783
|
+
const encryption = r.bytes(P256_PUBLIC_LENGTH);
|
|
784
|
+
const signing = r.bytes(P256_PUBLIC_LENGTH);
|
|
785
|
+
r.end();
|
|
786
|
+
return devicePublicKeys(encryption, signing);
|
|
787
|
+
}
|
|
788
|
+
function sameDevice(a, b) {
|
|
789
|
+
return constantTimeEqual(a.encryption, b.encryption) && constantTimeEqual(a.signing, b.signing);
|
|
790
|
+
}
|
|
791
|
+
async function deviceFingerprint(keys) {
|
|
792
|
+
const digest = await sha256(label(DOMAIN, "fingerprint", keys.encryption, keys.signing));
|
|
793
|
+
return (toBase32(digest.slice(0, 20)).match(/.{4}/g) ?? []).join(" ");
|
|
794
|
+
}
|
|
795
|
+
var privateParts = /* @__PURE__ */ new WeakMap();
|
|
796
|
+
function devicePrivate(device) {
|
|
797
|
+
const parts = privateParts.get(device);
|
|
798
|
+
if (!parts) throw new PoolseCryptoError("malformed", "Not device keys created by @poolse/crypto");
|
|
799
|
+
return parts;
|
|
800
|
+
}
|
|
801
|
+
var DeviceKeys = class _DeviceKeys {
|
|
802
|
+
publicKeys;
|
|
803
|
+
constructor(publicKeys, encryption, signing, extractable) {
|
|
804
|
+
this.publicKeys = publicKeys;
|
|
805
|
+
privateParts.set(this, { encryption, signing, extractable });
|
|
806
|
+
}
|
|
807
|
+
get id() {
|
|
808
|
+
return this.publicKeys.id;
|
|
809
|
+
}
|
|
810
|
+
/**
|
|
811
|
+
* New key pairs for this device. They are extractable so the app can
|
|
812
|
+
* `export()` them once into the keychain; later loads with `import()` are
|
|
813
|
+
* non-extractable by default.
|
|
814
|
+
*/
|
|
815
|
+
static async generate() {
|
|
816
|
+
const enc = await generateP256("ecdh");
|
|
817
|
+
const sig = await generateP256("ecdsa");
|
|
818
|
+
const publicKeys = await devicePublicKeys(
|
|
819
|
+
await exportP256Public(enc.publicKey),
|
|
820
|
+
await exportP256Public(sig.publicKey)
|
|
821
|
+
);
|
|
822
|
+
return new _DeviceKeys(publicKeys, enc.privateKey, sig.privateKey, true);
|
|
823
|
+
}
|
|
824
|
+
/** Bytes for the OS keychain. Only works on keys from `generate()` or an extractable import. */
|
|
825
|
+
async export(options = {}) {
|
|
826
|
+
const parts = privateParts.get(this);
|
|
827
|
+
if (!parts.extractable) {
|
|
828
|
+
throw new PoolseCryptoError(
|
|
829
|
+
"malformed",
|
|
830
|
+
"These device keys were imported as non-extractable"
|
|
831
|
+
);
|
|
832
|
+
}
|
|
833
|
+
const body = new ByteWriter().bytes(this.publicKeys.encryption).bytes(await exportP256Private(parts.encryption)).bytes(this.publicKeys.signing).bytes(await exportP256Private(parts.signing)).finish();
|
|
834
|
+
if (!options.wrappingKey) {
|
|
835
|
+
const w = writeHeader(new ByteWriter(), Kind.DeviceSecret, Alg.None);
|
|
836
|
+
return w.bytes(body).bytes((await sha256(body)).slice(0, 16)).finish();
|
|
837
|
+
}
|
|
838
|
+
const wrappingKey = checkLength(options.wrappingKey);
|
|
839
|
+
const iv = randomBytes(IV_LENGTH);
|
|
840
|
+
const prefix = writeHeader(new ByteWriter(), Kind.DeviceSecret, Alg.Aes256GcmHkdfSha256).bytes(await keyCheck(wrappingKey, "device-secret")).bytes(iv).finish();
|
|
841
|
+
const key = await deriveAesKey(wrappingKey, "device-secret");
|
|
842
|
+
return new ByteWriter().bytes(prefix).bytes(await aesEncrypt(key, iv, body, prefix)).finish();
|
|
843
|
+
}
|
|
844
|
+
static async import(bytes, options = {}) {
|
|
845
|
+
const r = new ByteReader(bytes);
|
|
846
|
+
const alg = readHeader(r, Kind.DeviceSecret, [Alg.None, Alg.Aes256GcmHkdfSha256]);
|
|
847
|
+
const bodyLength = 2 * (P256_PUBLIC_LENGTH + P256_SCALAR_LENGTH);
|
|
848
|
+
let body;
|
|
849
|
+
if (alg === Alg.None) {
|
|
850
|
+
if (options.wrappingKey) {
|
|
851
|
+
throw new PoolseCryptoError(
|
|
852
|
+
"malformed",
|
|
853
|
+
"These device keys were exported without a wrapping key"
|
|
854
|
+
);
|
|
855
|
+
}
|
|
856
|
+
body = r.bytes(bodyLength);
|
|
857
|
+
const checksum2 = r.bytes(16);
|
|
858
|
+
r.end();
|
|
859
|
+
if (!constantTimeEqual((await sha256(body)).slice(0, 16), checksum2)) {
|
|
860
|
+
throw new PoolseCryptoError("tampered", "Device key export is corrupted");
|
|
861
|
+
}
|
|
862
|
+
} else {
|
|
863
|
+
if (!options.wrappingKey) {
|
|
864
|
+
throw new PoolseCryptoError("wrong-key", "These device keys need their wrapping key");
|
|
865
|
+
}
|
|
866
|
+
const wrappingKey = checkLength(options.wrappingKey);
|
|
867
|
+
await verifyKeyCheck(wrappingKey, "device-secret", r.bytes(CHECK_LENGTH));
|
|
868
|
+
const iv = r.bytes(IV_LENGTH);
|
|
869
|
+
const prefix = r.consumed();
|
|
870
|
+
const ct = r.rest();
|
|
871
|
+
body = await aesDecrypt(await deriveAesKey(wrappingKey, "device-secret"), iv, ct, prefix);
|
|
872
|
+
if (body.length !== bodyLength)
|
|
873
|
+
throw new PoolseCryptoError("malformed", "Device key export is invalid");
|
|
874
|
+
}
|
|
875
|
+
const b = new ByteReader(body);
|
|
876
|
+
const encPublic = b.bytes(P256_PUBLIC_LENGTH);
|
|
877
|
+
const encPrivate = b.bytes(P256_SCALAR_LENGTH);
|
|
878
|
+
const sigPublic = b.bytes(P256_PUBLIC_LENGTH);
|
|
879
|
+
const sigPrivate = b.bytes(P256_SCALAR_LENGTH);
|
|
880
|
+
const extractable = options.extractable ?? false;
|
|
881
|
+
return new _DeviceKeys(
|
|
882
|
+
await devicePublicKeys(encPublic, sigPublic),
|
|
883
|
+
await importP256Private("ecdh", encPrivate, encPublic, extractable),
|
|
884
|
+
await importP256Private("ecdsa", sigPrivate, sigPublic, extractable),
|
|
885
|
+
extractable
|
|
886
|
+
);
|
|
887
|
+
}
|
|
888
|
+
toJSON() {
|
|
889
|
+
return { id: this.id };
|
|
890
|
+
}
|
|
891
|
+
};
|
|
892
|
+
function deviceIdRaw(keys) {
|
|
893
|
+
return fromBase64Url(keys.id);
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
// src/wrap.ts
|
|
897
|
+
var WrapPurpose = {
|
|
898
|
+
/** The account key, under a recovery key. */
|
|
899
|
+
AccountKeyRecovery: 1,
|
|
900
|
+
/** An item key, under the account key. */
|
|
901
|
+
ItemKey: 2,
|
|
902
|
+
/** An older item key, under its successor (so history stays readable). */
|
|
903
|
+
PreviousItemKey: 3,
|
|
904
|
+
/** The account key, to one of the user's devices. */
|
|
905
|
+
AccountKeyDevice: 4,
|
|
906
|
+
/** An item key, to a recipient's device (sharing). */
|
|
907
|
+
ItemKeyShare: 5
|
|
908
|
+
};
|
|
909
|
+
var PURPOSE_NAMES = {
|
|
910
|
+
1: "account-key-recovery",
|
|
911
|
+
2: "item-key",
|
|
912
|
+
3: "previous-item-key",
|
|
913
|
+
4: "account-key-device",
|
|
914
|
+
5: "item-key-share"
|
|
915
|
+
};
|
|
916
|
+
var FLAG_SIGNED = 1;
|
|
917
|
+
function purposeName(purpose) {
|
|
918
|
+
const name = PURPOSE_NAMES[purpose];
|
|
919
|
+
if (!name) throw new PoolseCryptoError("unsupported", `Unknown key-wrap purpose ${purpose}`);
|
|
920
|
+
return name;
|
|
921
|
+
}
|
|
922
|
+
async function wrapSymmetric(kek, purpose, key, keyVersion, ad2) {
|
|
923
|
+
const name = purposeName(purpose);
|
|
924
|
+
const iv = randomBytes(IV_LENGTH);
|
|
925
|
+
const prefix = writeHeader(new ByteWriter(), Kind.KeyWrap, Alg.Aes256GcmHkdfSha256).u8(purpose).u32(keyVersion).bytes(await keyCheck(kek, `kek/${name}`)).bytes(iv).finish();
|
|
926
|
+
const aad = concat(
|
|
927
|
+
prefix,
|
|
928
|
+
encodeAssociatedData(`wrap/${name}`, ad2, { "@keyVersion": keyVersion })
|
|
929
|
+
);
|
|
930
|
+
const ct = await aesEncrypt(await deriveAesKey(kek, `kek/${name}`), iv, key, aad);
|
|
931
|
+
return new ByteWriter().bytes(prefix).bytes16(ct).finish();
|
|
932
|
+
}
|
|
933
|
+
async function unwrapSymmetric(kek, purpose, wrap, ad2) {
|
|
934
|
+
const r = new ByteReader(wrap);
|
|
935
|
+
readHeader(r, Kind.KeyWrap, [Alg.Aes256GcmHkdfSha256]);
|
|
936
|
+
const got = r.u8();
|
|
937
|
+
const name = purposeName(got);
|
|
938
|
+
if (got !== purpose) {
|
|
939
|
+
throw new PoolseCryptoError(
|
|
940
|
+
"malformed",
|
|
941
|
+
`Expected a ${purposeName(purpose)} wrap, got ${name}`
|
|
942
|
+
);
|
|
943
|
+
}
|
|
944
|
+
const keyVersion = r.u32();
|
|
945
|
+
const check = r.bytes(CHECK_LENGTH);
|
|
946
|
+
const iv = r.bytes(IV_LENGTH);
|
|
947
|
+
const prefix = r.consumed();
|
|
948
|
+
const ct = r.bytes16();
|
|
949
|
+
r.end();
|
|
950
|
+
await verifyKeyCheck(kek, `kek/${name}`, check);
|
|
951
|
+
const aad = concat(
|
|
952
|
+
prefix,
|
|
953
|
+
encodeAssociatedData(`wrap/${name}`, ad2, { "@keyVersion": keyVersion })
|
|
954
|
+
);
|
|
955
|
+
const key = await aesDecrypt(await deriveAesKey(kek, `kek/${name}`), iv, ct, aad);
|
|
956
|
+
return { key, keyVersion };
|
|
957
|
+
}
|
|
958
|
+
async function kekFromShared(shared, ephemeral, recipient, name) {
|
|
959
|
+
return aesKey(await hkdf(shared, concat(ephemeral, recipient), label(DOMAIN, "pubwrap/", name)));
|
|
960
|
+
}
|
|
961
|
+
function signatureInput(body, ad2) {
|
|
962
|
+
return concat(label(DOMAIN, "sig/pubwrap"), body, ad2);
|
|
963
|
+
}
|
|
964
|
+
async function wrapToDevice(recipient, purpose, key, keyVersion, ad2, signer) {
|
|
965
|
+
const name = purposeName(purpose);
|
|
966
|
+
const recipientKey = await importP256Public("ecdh", recipient.encryption);
|
|
967
|
+
const ephemeral = await generateP256("ecdh");
|
|
968
|
+
const ephemeralPublic = await exportP256Public(ephemeral.publicKey);
|
|
969
|
+
const shared = await ecdh(ephemeral.privateKey, recipientKey);
|
|
970
|
+
const iv = randomBytes(IV_LENGTH);
|
|
971
|
+
const w = writeHeader(new ByteWriter(), Kind.PublicKeyWrap, Alg.P256).u8(purpose).u8(signer ? FLAG_SIGNED : 0).u32(keyVersion).bytes(deviceIdRaw(recipient)).bytes(ephemeralPublic);
|
|
972
|
+
if (signer) w.bytes(signer.publicKeys.signing);
|
|
973
|
+
const prefix = w.bytes(iv).finish();
|
|
974
|
+
const adBytes = encodeAssociatedData(`wrap/${name}`, ad2, { "@keyVersion": keyVersion });
|
|
975
|
+
const kek = await kekFromShared(shared, ephemeralPublic, recipient.encryption, name);
|
|
976
|
+
const ct = await aesEncrypt(kek, iv, key, concat(prefix, adBytes));
|
|
977
|
+
const body = new ByteWriter().bytes(prefix).bytes16(ct).finish();
|
|
978
|
+
if (!signer) return body;
|
|
979
|
+
const signature = await ecdsaSign(devicePrivate(signer).signing, signatureInput(body, adBytes));
|
|
980
|
+
return concat(body, signature);
|
|
981
|
+
}
|
|
982
|
+
function asList(value) {
|
|
983
|
+
return Array.isArray(value) ? value : [value];
|
|
984
|
+
}
|
|
985
|
+
async function unwrapFromDevice(device, purpose, wrap, ad2, requireSignatureFrom) {
|
|
986
|
+
const r = new ByteReader(wrap);
|
|
987
|
+
readHeader(r, Kind.PublicKeyWrap, [Alg.P256]);
|
|
988
|
+
const got = r.u8();
|
|
989
|
+
const name = purposeName(got);
|
|
990
|
+
if (got !== purpose) {
|
|
991
|
+
throw new PoolseCryptoError(
|
|
992
|
+
"malformed",
|
|
993
|
+
`Expected a ${purposeName(purpose)} wrap, got ${name}`
|
|
994
|
+
);
|
|
995
|
+
}
|
|
996
|
+
const flags = r.u8();
|
|
997
|
+
if ((flags & ~FLAG_SIGNED) !== 0)
|
|
998
|
+
throw new PoolseCryptoError("unsupported", "Unknown key-wrap flags");
|
|
999
|
+
const signed = (flags & FLAG_SIGNED) !== 0;
|
|
1000
|
+
const keyVersion = r.u32();
|
|
1001
|
+
const recipientId = r.bytes(16);
|
|
1002
|
+
const ephemeralPublic = r.bytes(P256_PUBLIC_LENGTH);
|
|
1003
|
+
const signingKey = signed ? r.bytes(P256_PUBLIC_LENGTH) : null;
|
|
1004
|
+
const iv = r.bytes(IV_LENGTH);
|
|
1005
|
+
const prefix = r.consumed();
|
|
1006
|
+
const ct = r.bytes16();
|
|
1007
|
+
const body = r.consumed();
|
|
1008
|
+
const signature = signed ? r.bytes(ECDSA_SIGNATURE_LENGTH) : null;
|
|
1009
|
+
r.end();
|
|
1010
|
+
if (!constantTimeEqual(recipientId, deviceIdRaw(device.publicKeys))) {
|
|
1011
|
+
throw new PoolseCryptoError("wrong-key", "This key was wrapped for a different device");
|
|
1012
|
+
}
|
|
1013
|
+
const adBytes = encodeAssociatedData(`wrap/${name}`, ad2, { "@keyVersion": keyVersion });
|
|
1014
|
+
let signer = null;
|
|
1015
|
+
if (signingKey && signature) {
|
|
1016
|
+
const verifier = await importP256Public("ecdsa", signingKey);
|
|
1017
|
+
if (!await ecdsaVerify(verifier, signature, signatureInput(body, adBytes))) {
|
|
1018
|
+
throw new PoolseCryptoError("bad-signature", "The key wrap signature is invalid");
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
if (requireSignatureFrom !== void 0) {
|
|
1022
|
+
const trusted = asList(requireSignatureFrom);
|
|
1023
|
+
signer = signingKey && trusted.find((t) => constantTimeEqual(t.signing, signingKey)) || null;
|
|
1024
|
+
if (!signer) {
|
|
1025
|
+
throw new PoolseCryptoError(
|
|
1026
|
+
"bad-signature",
|
|
1027
|
+
signingKey ? "The key wrap is signed by an untrusted device" : "The key wrap is not signed"
|
|
1028
|
+
);
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
const ephemeralKey = await importP256Public("ecdh", ephemeralPublic);
|
|
1032
|
+
const shared = await ecdh(devicePrivate(device).encryption, ephemeralKey);
|
|
1033
|
+
const kek = await kekFromShared(shared, ephemeralPublic, device.publicKeys.encryption, name);
|
|
1034
|
+
const key = await aesDecrypt(kek, iv, ct, concat(prefix, adBytes));
|
|
1035
|
+
return { key, keyVersion, signer, signingKey };
|
|
1036
|
+
}
|
|
1037
|
+
async function wrapAccountKeyForDevice(accountKey, recipient, options) {
|
|
1038
|
+
return wrapToDevice(
|
|
1039
|
+
recipient,
|
|
1040
|
+
WrapPurpose.AccountKeyDevice,
|
|
1041
|
+
secretOf(accountKey),
|
|
1042
|
+
0,
|
|
1043
|
+
{ accountId: options.accountId },
|
|
1044
|
+
options.signer
|
|
1045
|
+
);
|
|
1046
|
+
}
|
|
1047
|
+
async function unwrapAccountKeyForDevice(wrap, device, options) {
|
|
1048
|
+
const result = await unwrapFromDevice(
|
|
1049
|
+
device,
|
|
1050
|
+
WrapPurpose.AccountKeyDevice,
|
|
1051
|
+
wrap,
|
|
1052
|
+
{ accountId: options.accountId },
|
|
1053
|
+
options.requireSignatureFrom
|
|
1054
|
+
);
|
|
1055
|
+
return {
|
|
1056
|
+
key: await AccountKey.fromBytes(result.key),
|
|
1057
|
+
signer: result.signer,
|
|
1058
|
+
signingKey: result.signingKey
|
|
1059
|
+
};
|
|
1060
|
+
}
|
|
1061
|
+
async function wrapItemKey(itemKey, accountKey, options) {
|
|
1062
|
+
return wrapSymmetric(
|
|
1063
|
+
secretOf(accountKey),
|
|
1064
|
+
WrapPurpose.ItemKey,
|
|
1065
|
+
secretOf(itemKey),
|
|
1066
|
+
itemKey.version,
|
|
1067
|
+
{
|
|
1068
|
+
itemId: options.itemId
|
|
1069
|
+
}
|
|
1070
|
+
);
|
|
1071
|
+
}
|
|
1072
|
+
async function unwrapItemKey(wrap, accountKey, options) {
|
|
1073
|
+
const { key, keyVersion } = await unwrapSymmetric(
|
|
1074
|
+
secretOf(accountKey),
|
|
1075
|
+
WrapPurpose.ItemKey,
|
|
1076
|
+
wrap,
|
|
1077
|
+
{
|
|
1078
|
+
itemId: options.itemId
|
|
1079
|
+
}
|
|
1080
|
+
);
|
|
1081
|
+
return ItemKey.fromBytes(key, keyVersion);
|
|
1082
|
+
}
|
|
1083
|
+
async function shareItemKey(itemKey, recipient, options) {
|
|
1084
|
+
return wrapToDevice(
|
|
1085
|
+
recipient,
|
|
1086
|
+
WrapPurpose.ItemKeyShare,
|
|
1087
|
+
secretOf(itemKey),
|
|
1088
|
+
itemKey.version,
|
|
1089
|
+
{ itemId: options.itemId },
|
|
1090
|
+
options.signer
|
|
1091
|
+
);
|
|
1092
|
+
}
|
|
1093
|
+
async function shareItemKeyWithDevices(itemKey, recipients, options) {
|
|
1094
|
+
const out = [];
|
|
1095
|
+
for (const recipient of recipients) {
|
|
1096
|
+
out.push({ deviceId: recipient.id, wrap: await shareItemKey(itemKey, recipient, options) });
|
|
1097
|
+
}
|
|
1098
|
+
return out;
|
|
1099
|
+
}
|
|
1100
|
+
async function openSharedItemKey(wrap, device, options) {
|
|
1101
|
+
const result = await unwrapFromDevice(
|
|
1102
|
+
device,
|
|
1103
|
+
WrapPurpose.ItemKeyShare,
|
|
1104
|
+
wrap,
|
|
1105
|
+
{ itemId: options.itemId },
|
|
1106
|
+
options.requireSignatureFrom
|
|
1107
|
+
);
|
|
1108
|
+
return {
|
|
1109
|
+
key: ItemKey.fromBytes(result.key, result.keyVersion),
|
|
1110
|
+
signer: result.signer,
|
|
1111
|
+
signingKey: result.signingKey
|
|
1112
|
+
};
|
|
1113
|
+
}
|
|
1114
|
+
async function wrapPreviousItemKey(previous, current, options) {
|
|
1115
|
+
if (previous.version >= current.version) {
|
|
1116
|
+
throw new PoolseCryptoError("malformed", "The previous key must have a lower version");
|
|
1117
|
+
}
|
|
1118
|
+
return wrapSymmetric(
|
|
1119
|
+
secretOf(current),
|
|
1120
|
+
WrapPurpose.PreviousItemKey,
|
|
1121
|
+
secretOf(previous),
|
|
1122
|
+
previous.version,
|
|
1123
|
+
{
|
|
1124
|
+
itemId: options.itemId,
|
|
1125
|
+
currentVersion: current.version
|
|
1126
|
+
}
|
|
1127
|
+
);
|
|
1128
|
+
}
|
|
1129
|
+
async function unwrapPreviousItemKey(wrap, current, options) {
|
|
1130
|
+
const { key, keyVersion } = await unwrapSymmetric(
|
|
1131
|
+
secretOf(current),
|
|
1132
|
+
WrapPurpose.PreviousItemKey,
|
|
1133
|
+
wrap,
|
|
1134
|
+
{
|
|
1135
|
+
itemId: options.itemId,
|
|
1136
|
+
currentVersion: current.version
|
|
1137
|
+
}
|
|
1138
|
+
);
|
|
1139
|
+
if (keyVersion >= current.version)
|
|
1140
|
+
throw new PoolseCryptoError("malformed", "Invalid previous key version");
|
|
1141
|
+
return ItemKey.fromBytes(key, keyVersion);
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
// src/item.ts
|
|
1145
|
+
async function seal(key, type, plaintext, ad2) {
|
|
1146
|
+
requireItemId(ad2);
|
|
1147
|
+
const raw = secretOf(key);
|
|
1148
|
+
const iv = randomBytes(IV_LENGTH);
|
|
1149
|
+
const prefix = writeHeader(new ByteWriter(), Kind.Item, Alg.Aes256GcmHkdfSha256).u32(key.version).bytes(await keyCheck(raw, "item")).bytes(iv).finish();
|
|
1150
|
+
const aad = concat(prefix, encodeAssociatedData("item", ad2, { "@type": type }));
|
|
1151
|
+
const ct = await aesEncrypt(await deriveAesKey(raw, "item-content"), iv, pad(plaintext), aad);
|
|
1152
|
+
return concat(prefix, ct);
|
|
1153
|
+
}
|
|
1154
|
+
async function open(key, type, envelope, ad2) {
|
|
1155
|
+
requireItemId(ad2);
|
|
1156
|
+
const r = new ByteReader(envelope);
|
|
1157
|
+
readHeader(r, Kind.Item, [Alg.Aes256GcmHkdfSha256]);
|
|
1158
|
+
const keyVersion = r.u32();
|
|
1159
|
+
const check = r.bytes(CHECK_LENGTH);
|
|
1160
|
+
const iv = r.bytes(IV_LENGTH);
|
|
1161
|
+
const prefix = r.consumed();
|
|
1162
|
+
const ct = r.rest();
|
|
1163
|
+
if (keyVersion !== key.version) {
|
|
1164
|
+
throw new PoolseCryptoError(
|
|
1165
|
+
"wrong-key",
|
|
1166
|
+
`This was encrypted with key version ${keyVersion}, not ${key.version}`
|
|
1167
|
+
);
|
|
1168
|
+
}
|
|
1169
|
+
const raw = secretOf(key);
|
|
1170
|
+
await verifyKeyCheck(raw, "item", check);
|
|
1171
|
+
const aad = concat(prefix, encodeAssociatedData("item", ad2, { "@type": type }));
|
|
1172
|
+
return unpad(await aesDecrypt(await deriveAesKey(raw, "item-content"), iv, ct, aad));
|
|
1173
|
+
}
|
|
1174
|
+
function requireItemId(ad2) {
|
|
1175
|
+
if (typeof ad2.itemId !== "string" || ad2.itemId.length === 0) {
|
|
1176
|
+
throw new PoolseCryptoError("malformed", "Associated data needs an itemId");
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
async function encryptItem(key, content, ad2) {
|
|
1180
|
+
if (typeof content.title !== "string")
|
|
1181
|
+
throw new PoolseCryptoError("malformed", "title must be a string");
|
|
1182
|
+
return seal(key, "item", utf8(JSON.stringify(content)), ad2);
|
|
1183
|
+
}
|
|
1184
|
+
async function decryptItem(key, envelope, ad2) {
|
|
1185
|
+
const text = fromUtf8(await open(key, "item", envelope, ad2));
|
|
1186
|
+
let value;
|
|
1187
|
+
try {
|
|
1188
|
+
value = JSON.parse(text);
|
|
1189
|
+
} catch {
|
|
1190
|
+
throw new PoolseCryptoError("malformed", "Decrypted item is not JSON");
|
|
1191
|
+
}
|
|
1192
|
+
if (!value || typeof value !== "object" || typeof value.title !== "string") {
|
|
1193
|
+
throw new PoolseCryptoError("malformed", "Decrypted item has no title");
|
|
1194
|
+
}
|
|
1195
|
+
return value;
|
|
1196
|
+
}
|
|
1197
|
+
async function encryptBytes(key, plaintext, ad2) {
|
|
1198
|
+
return seal(key, "bytes", plaintext, ad2);
|
|
1199
|
+
}
|
|
1200
|
+
async function decryptBytes(key, envelope, ad2) {
|
|
1201
|
+
return open(key, "bytes", envelope, ad2);
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
// src/attachment.ts
|
|
1205
|
+
var DEFAULT_CHUNK_SIZE = 64 * 1024;
|
|
1206
|
+
var MIN_CHUNK_SIZE = 16;
|
|
1207
|
+
var MAX_CHUNK_SIZE = 16 * 1024 * 1024;
|
|
1208
|
+
var SALT_LENGTH = 32;
|
|
1209
|
+
var ATTACHMENT_HEADER_LENGTH = HEADER_LENGTH + 4 + CHECK_LENGTH + SALT_LENGTH + 4;
|
|
1210
|
+
function nonce(index, final) {
|
|
1211
|
+
const n = new Uint8Array(12);
|
|
1212
|
+
new DataView(n.buffer).setBigUint64(3, BigInt(index));
|
|
1213
|
+
n[11] = final ? 1 : 0;
|
|
1214
|
+
return n;
|
|
1215
|
+
}
|
|
1216
|
+
async function* iterate(source) {
|
|
1217
|
+
if (source instanceof Uint8Array) {
|
|
1218
|
+
yield source;
|
|
1219
|
+
return;
|
|
1220
|
+
}
|
|
1221
|
+
if (typeof Blob !== "undefined" && source instanceof Blob) {
|
|
1222
|
+
if (typeof source.stream === "function") {
|
|
1223
|
+
yield* iterate(source.stream());
|
|
1224
|
+
} else {
|
|
1225
|
+
yield new Uint8Array(await source.arrayBuffer());
|
|
1226
|
+
}
|
|
1227
|
+
return;
|
|
1228
|
+
}
|
|
1229
|
+
if (typeof source.getReader === "function") {
|
|
1230
|
+
const reader = source.getReader();
|
|
1231
|
+
try {
|
|
1232
|
+
for (; ; ) {
|
|
1233
|
+
const { done, value } = await reader.read();
|
|
1234
|
+
if (done) return;
|
|
1235
|
+
yield value;
|
|
1236
|
+
}
|
|
1237
|
+
} finally {
|
|
1238
|
+
reader.releaseLock();
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
yield* source;
|
|
1242
|
+
}
|
|
1243
|
+
var Chunker = class {
|
|
1244
|
+
parts = [];
|
|
1245
|
+
length = 0;
|
|
1246
|
+
push(part) {
|
|
1247
|
+
if (part.length === 0) return;
|
|
1248
|
+
this.parts.push(part);
|
|
1249
|
+
this.length += part.length;
|
|
1250
|
+
}
|
|
1251
|
+
get buffered() {
|
|
1252
|
+
return this.length;
|
|
1253
|
+
}
|
|
1254
|
+
take(n) {
|
|
1255
|
+
const out = new Uint8Array(n);
|
|
1256
|
+
let offset = 0;
|
|
1257
|
+
while (offset < n) {
|
|
1258
|
+
const head = this.parts[0];
|
|
1259
|
+
const need = n - offset;
|
|
1260
|
+
if (head.length <= need) {
|
|
1261
|
+
out.set(head, offset);
|
|
1262
|
+
offset += head.length;
|
|
1263
|
+
this.parts.shift();
|
|
1264
|
+
} else {
|
|
1265
|
+
out.set(head.subarray(0, need), offset);
|
|
1266
|
+
this.parts[0] = head.subarray(need);
|
|
1267
|
+
offset += need;
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
this.length -= n;
|
|
1271
|
+
return out;
|
|
1272
|
+
}
|
|
1273
|
+
takeAll() {
|
|
1274
|
+
return this.take(this.length);
|
|
1275
|
+
}
|
|
1276
|
+
};
|
|
1277
|
+
function checkChunkSize(size) {
|
|
1278
|
+
if (!Number.isInteger(size) || size < MIN_CHUNK_SIZE || size > MAX_CHUNK_SIZE) {
|
|
1279
|
+
throw new PoolseCryptoError(
|
|
1280
|
+
"malformed",
|
|
1281
|
+
`Chunk size must be ${MIN_CHUNK_SIZE}\u2026${MAX_CHUNK_SIZE} bytes`
|
|
1282
|
+
);
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
function requireIds(ad2) {
|
|
1286
|
+
if (!ad2.itemId || !ad2.attachmentId) {
|
|
1287
|
+
throw new PoolseCryptoError("malformed", "Associated data needs itemId and attachmentId");
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
async function* encryptAttachment(key, source, ad2, options = {}) {
|
|
1291
|
+
requireIds(ad2);
|
|
1292
|
+
const chunkSize = options.chunkSize ?? DEFAULT_CHUNK_SIZE;
|
|
1293
|
+
checkChunkSize(chunkSize);
|
|
1294
|
+
const raw = secretOf(key);
|
|
1295
|
+
const salt = randomBytes(SALT_LENGTH);
|
|
1296
|
+
const header = writeHeader(new ByteWriter(), Kind.Attachment, Alg.Aes256GcmHkdfSha256).u32(key.version).bytes(await keyCheck(raw, "attachment")).bytes(salt).u32(chunkSize).finish();
|
|
1297
|
+
const fileKey = await deriveAesKey(raw, "attachment", salt);
|
|
1298
|
+
const aad = concat(header, encodeAssociatedData("attachment", ad2));
|
|
1299
|
+
yield header;
|
|
1300
|
+
const chunker = new Chunker();
|
|
1301
|
+
let index = 0;
|
|
1302
|
+
for await (const part of iterate(source)) {
|
|
1303
|
+
chunker.push(part);
|
|
1304
|
+
while (chunker.buffered > chunkSize) {
|
|
1305
|
+
yield await aesEncrypt(fileKey, nonce(index++, false), chunker.take(chunkSize), aad);
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
yield await aesEncrypt(fileKey, nonce(index, true), chunker.takeAll(), aad);
|
|
1309
|
+
}
|
|
1310
|
+
async function* decryptAttachment(key, source, ad2) {
|
|
1311
|
+
requireIds(ad2);
|
|
1312
|
+
const input = new Chunker();
|
|
1313
|
+
const it = iterate(source)[Symbol.asyncIterator]();
|
|
1314
|
+
let ended = false;
|
|
1315
|
+
const fill = async (n) => {
|
|
1316
|
+
while (!ended && input.buffered < n) {
|
|
1317
|
+
const next = await it.next();
|
|
1318
|
+
if (next.done) ended = true;
|
|
1319
|
+
else input.push(next.value);
|
|
1320
|
+
}
|
|
1321
|
+
};
|
|
1322
|
+
await fill(ATTACHMENT_HEADER_LENGTH);
|
|
1323
|
+
if (input.buffered < ATTACHMENT_HEADER_LENGTH) {
|
|
1324
|
+
throw new PoolseCryptoError("malformed", "Attachment is truncated");
|
|
1325
|
+
}
|
|
1326
|
+
const header = input.take(ATTACHMENT_HEADER_LENGTH);
|
|
1327
|
+
const r = new ByteReader(header);
|
|
1328
|
+
readHeader(r, Kind.Attachment, [Alg.Aes256GcmHkdfSha256]);
|
|
1329
|
+
const keyVersion = r.u32();
|
|
1330
|
+
const check = r.bytes(CHECK_LENGTH);
|
|
1331
|
+
const salt = r.bytes(SALT_LENGTH);
|
|
1332
|
+
const chunkSize = r.u32();
|
|
1333
|
+
checkChunkSize(chunkSize);
|
|
1334
|
+
if (keyVersion !== key.version) {
|
|
1335
|
+
throw new PoolseCryptoError(
|
|
1336
|
+
"wrong-key",
|
|
1337
|
+
`This was encrypted with key version ${keyVersion}, not ${key.version}`
|
|
1338
|
+
);
|
|
1339
|
+
}
|
|
1340
|
+
const raw = secretOf(key);
|
|
1341
|
+
await verifyKeyCheck(raw, "attachment", check);
|
|
1342
|
+
const fileKey = await deriveAesKey(raw, "attachment", salt);
|
|
1343
|
+
const aad = concat(header, encodeAssociatedData("attachment", ad2));
|
|
1344
|
+
const sealed = chunkSize + TAG_LENGTH;
|
|
1345
|
+
let index = 0;
|
|
1346
|
+
for (; ; ) {
|
|
1347
|
+
await fill(sealed + 1);
|
|
1348
|
+
if (input.buffered > sealed) {
|
|
1349
|
+
yield await aesDecrypt(fileKey, nonce(index++, false), input.take(sealed), aad);
|
|
1350
|
+
continue;
|
|
1351
|
+
}
|
|
1352
|
+
if (input.buffered < TAG_LENGTH)
|
|
1353
|
+
throw new PoolseCryptoError("malformed", "Attachment is truncated");
|
|
1354
|
+
yield await aesDecrypt(fileKey, nonce(index, true), input.takeAll(), aad);
|
|
1355
|
+
return;
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
async function collect(stream) {
|
|
1359
|
+
const parts = [];
|
|
1360
|
+
for await (const part of stream) parts.push(part);
|
|
1361
|
+
return concat(...parts);
|
|
1362
|
+
}
|
|
1363
|
+
async function encryptAttachmentBytes(key, source, ad2, options = {}) {
|
|
1364
|
+
return collect(encryptAttachment(key, source, ad2, options));
|
|
1365
|
+
}
|
|
1366
|
+
async function decryptAttachmentBytes(key, source, ad2) {
|
|
1367
|
+
return collect(decryptAttachment(key, source, ad2));
|
|
1368
|
+
}
|
|
1369
|
+
function encryptedAttachmentSize(plainSize, chunkSize = DEFAULT_CHUNK_SIZE) {
|
|
1370
|
+
checkChunkSize(chunkSize);
|
|
1371
|
+
const chunks = Math.max(1, Math.ceil(plainSize / chunkSize));
|
|
1372
|
+
return ATTACHMENT_HEADER_LENGTH + plainSize + chunks * TAG_LENGTH;
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
// src/recovery.ts
|
|
1376
|
+
var SECRET_LENGTH = 16;
|
|
1377
|
+
var CHECKSUM_LENGTH = 4;
|
|
1378
|
+
var DISPLAY_LENGTH = 32;
|
|
1379
|
+
async function checksum(secret) {
|
|
1380
|
+
return (await sha256(label(DOMAIN, "recovery-checksum", secret))).slice(0, CHECKSUM_LENGTH);
|
|
1381
|
+
}
|
|
1382
|
+
var RecoveryKey = class _RecoveryKey {
|
|
1383
|
+
/** Public identifier (base64url): which recovery key a wrap belongs to. */
|
|
1384
|
+
id;
|
|
1385
|
+
#display;
|
|
1386
|
+
constructor(raw, id, display) {
|
|
1387
|
+
this.id = id;
|
|
1388
|
+
this.#display = display;
|
|
1389
|
+
setSecret(this, raw);
|
|
1390
|
+
}
|
|
1391
|
+
/** @internal */
|
|
1392
|
+
static async create(raw) {
|
|
1393
|
+
const encoded = toBase32(concat(raw, await checksum(raw)));
|
|
1394
|
+
const display = (encoded.match(/.{4}/g) ?? []).join("-");
|
|
1395
|
+
return new _RecoveryKey(raw, toBase64Url(await keyId(raw, "recovery")), display);
|
|
1396
|
+
}
|
|
1397
|
+
/** The key as the user writes it down. Show it once; never log it. */
|
|
1398
|
+
toDisplayString() {
|
|
1399
|
+
return this.#display;
|
|
1400
|
+
}
|
|
1401
|
+
/** Deliberately not the secret, so string interpolation can't leak it. */
|
|
1402
|
+
toString() {
|
|
1403
|
+
return `RecoveryKey(${this.id})`;
|
|
1404
|
+
}
|
|
1405
|
+
toJSON() {
|
|
1406
|
+
return { id: this.id };
|
|
1407
|
+
}
|
|
1408
|
+
};
|
|
1409
|
+
async function generateRecoveryKey() {
|
|
1410
|
+
return RecoveryKey.create(randomBytes(SECRET_LENGTH));
|
|
1411
|
+
}
|
|
1412
|
+
async function parseRecoveryKey(text) {
|
|
1413
|
+
const clean = text.toUpperCase().replace(/[\s-]/g, "");
|
|
1414
|
+
if (clean.length !== DISPLAY_LENGTH) {
|
|
1415
|
+
throw new PoolseCryptoError("malformed", `A recovery key has ${DISPLAY_LENGTH} characters`);
|
|
1416
|
+
}
|
|
1417
|
+
const bytes = fromBase32(clean);
|
|
1418
|
+
const raw = toBytes(bytes.subarray(0, SECRET_LENGTH));
|
|
1419
|
+
if (!constantTimeEqual(await checksum(raw), bytes.subarray(SECRET_LENGTH))) {
|
|
1420
|
+
throw new PoolseCryptoError("checksum", "This recovery key has a typo");
|
|
1421
|
+
}
|
|
1422
|
+
return RecoveryKey.create(raw);
|
|
1423
|
+
}
|
|
1424
|
+
async function wrapAccountKeyWithRecoveryKey(accountKey, recoveryKey, options) {
|
|
1425
|
+
return wrapSymmetric(
|
|
1426
|
+
secretOf(recoveryKey),
|
|
1427
|
+
WrapPurpose.AccountKeyRecovery,
|
|
1428
|
+
secretOf(accountKey),
|
|
1429
|
+
0,
|
|
1430
|
+
{ accountId: options.accountId }
|
|
1431
|
+
);
|
|
1432
|
+
}
|
|
1433
|
+
async function unwrapAccountKeyWithRecoveryKey(wrap, recoveryKey, options) {
|
|
1434
|
+
const { key } = await unwrapSymmetric(
|
|
1435
|
+
secretOf(recoveryKey),
|
|
1436
|
+
WrapPurpose.AccountKeyRecovery,
|
|
1437
|
+
wrap,
|
|
1438
|
+
{ accountId: options.accountId }
|
|
1439
|
+
);
|
|
1440
|
+
return AccountKey.fromBytes(key);
|
|
1441
|
+
}
|
|
1442
|
+
|
|
1443
|
+
// src/approval.ts
|
|
1444
|
+
var SECRET_LENGTH2 = 16;
|
|
1445
|
+
var HASH_LENGTH = 32;
|
|
1446
|
+
var MAC_LENGTH = 32;
|
|
1447
|
+
var DEFAULT_REQUEST_MAX_AGE_MS = 10 * 60 * 1e3;
|
|
1448
|
+
var CLOCK_SKEW_MS = 2 * 60 * 1e3;
|
|
1449
|
+
var requestSecrets = /* @__PURE__ */ new WeakMap();
|
|
1450
|
+
function signatureInput2(body) {
|
|
1451
|
+
return concat(label(DOMAIN, "sig/device-request"), body);
|
|
1452
|
+
}
|
|
1453
|
+
async function grantMacKey(secret, requestHash) {
|
|
1454
|
+
return hkdf(secret, requestHash, label(DOMAIN, "key/device-grant"));
|
|
1455
|
+
}
|
|
1456
|
+
function checkAge(createdAtMs, now, maxAgeMs) {
|
|
1457
|
+
if (createdAtMs > now + CLOCK_SKEW_MS || now - createdAtMs > maxAgeMs) {
|
|
1458
|
+
throw new PoolseCryptoError("expired", "This device request has expired; make a new QR code");
|
|
1459
|
+
}
|
|
1460
|
+
}
|
|
1461
|
+
async function createDeviceRequest(device, options = {}) {
|
|
1462
|
+
const createdAt = Math.floor((options.now ?? Date.now()) / 1e3);
|
|
1463
|
+
const secret = randomBytes(SECRET_LENGTH2);
|
|
1464
|
+
const body = writeHeader(new ByteWriter(), Kind.DeviceRequest, Alg.P256).u32(createdAt).bytes(secret).bytes(device.publicKeys.encryption).bytes(device.publicKeys.signing).finish();
|
|
1465
|
+
const signature = await ecdsaSign(devicePrivate(device).signing, signatureInput2(body));
|
|
1466
|
+
const request = concat(body, signature);
|
|
1467
|
+
const pending = {
|
|
1468
|
+
device: device.publicKeys,
|
|
1469
|
+
createdAt: new Date(createdAt * 1e3)
|
|
1470
|
+
};
|
|
1471
|
+
requestSecrets.set(pending, { secret, hash: await sha256(request) });
|
|
1472
|
+
return { qr: toBase32(request), pending };
|
|
1473
|
+
}
|
|
1474
|
+
async function readDeviceRequest(qr, options = {}) {
|
|
1475
|
+
const bytes = fromBase32(qr.trim());
|
|
1476
|
+
const r = new ByteReader(bytes);
|
|
1477
|
+
readHeader(r, Kind.DeviceRequest, [Alg.P256]);
|
|
1478
|
+
const createdAt = r.u32();
|
|
1479
|
+
const secret = r.bytes(SECRET_LENGTH2);
|
|
1480
|
+
const encryption = r.bytes(P256_PUBLIC_LENGTH);
|
|
1481
|
+
const signing = r.bytes(P256_PUBLIC_LENGTH);
|
|
1482
|
+
const body = r.consumed();
|
|
1483
|
+
const signature = r.bytes(ECDSA_SIGNATURE_LENGTH);
|
|
1484
|
+
r.end();
|
|
1485
|
+
const verifier = await importP256Public("ecdsa", signing);
|
|
1486
|
+
if (!await ecdsaVerify(verifier, signature, signatureInput2(body))) {
|
|
1487
|
+
throw new PoolseCryptoError("bad-signature", "The device request signature is invalid");
|
|
1488
|
+
}
|
|
1489
|
+
checkAge(
|
|
1490
|
+
createdAt * 1e3,
|
|
1491
|
+
options.now ?? Date.now(),
|
|
1492
|
+
options.maxAgeMs ?? DEFAULT_REQUEST_MAX_AGE_MS
|
|
1493
|
+
);
|
|
1494
|
+
const request = {
|
|
1495
|
+
device: await devicePublicKeys(encryption, signing),
|
|
1496
|
+
createdAt: new Date(createdAt * 1e3)
|
|
1497
|
+
};
|
|
1498
|
+
requestSecrets.set(request, { secret, hash: await sha256(bytes) });
|
|
1499
|
+
return request;
|
|
1500
|
+
}
|
|
1501
|
+
async function approveDeviceRequest(request, approver, accountKey, options) {
|
|
1502
|
+
const state = requestSecrets.get(request);
|
|
1503
|
+
if (!state)
|
|
1504
|
+
throw new PoolseCryptoError("malformed", "Pass the request returned by readDeviceRequest");
|
|
1505
|
+
if (sameDevice(request.device, approver.publicKeys)) {
|
|
1506
|
+
throw new PoolseCryptoError("malformed", "A device cannot approve itself");
|
|
1507
|
+
}
|
|
1508
|
+
const wrap = await wrapAccountKeyForDevice(accountKey, request.device, {
|
|
1509
|
+
accountId: options.accountId,
|
|
1510
|
+
signer: approver
|
|
1511
|
+
});
|
|
1512
|
+
const body = writeHeader(new ByteWriter(), Kind.DeviceGrant, Alg.HmacSha256).bytes(state.hash).bytes(approver.publicKeys.encryption).bytes(approver.publicKeys.signing).bytes16(wrap).finish();
|
|
1513
|
+
const mac = await hmac(
|
|
1514
|
+
await grantMacKey(state.secret, state.hash),
|
|
1515
|
+
macInput(body, options.accountId)
|
|
1516
|
+
);
|
|
1517
|
+
return concat(body, mac);
|
|
1518
|
+
}
|
|
1519
|
+
function macInput(body, accountId) {
|
|
1520
|
+
return concat(
|
|
1521
|
+
label(DOMAIN, "mac/device-grant"),
|
|
1522
|
+
body,
|
|
1523
|
+
encodeAssociatedData("device-grant", { accountId })
|
|
1524
|
+
);
|
|
1525
|
+
}
|
|
1526
|
+
async function acceptDeviceGrant(grant, pending, device, options) {
|
|
1527
|
+
const state = requestSecrets.get(pending);
|
|
1528
|
+
if (!state)
|
|
1529
|
+
throw new PoolseCryptoError("malformed", "Pass the pending request from createDeviceRequest");
|
|
1530
|
+
if (!sameDevice(pending.device, device.publicKeys)) {
|
|
1531
|
+
throw new PoolseCryptoError("wrong-key", "This request was made by a different device");
|
|
1532
|
+
}
|
|
1533
|
+
checkAge(
|
|
1534
|
+
pending.createdAt.getTime(),
|
|
1535
|
+
options.now ?? Date.now(),
|
|
1536
|
+
options.maxAgeMs ?? DEFAULT_REQUEST_MAX_AGE_MS
|
|
1537
|
+
);
|
|
1538
|
+
const r = new ByteReader(grant);
|
|
1539
|
+
readHeader(r, Kind.DeviceGrant, [Alg.HmacSha256]);
|
|
1540
|
+
const requestHash = r.bytes(HASH_LENGTH);
|
|
1541
|
+
const approverEncryption = r.bytes(P256_PUBLIC_LENGTH);
|
|
1542
|
+
const approverSigning = r.bytes(P256_PUBLIC_LENGTH);
|
|
1543
|
+
const wrap = r.bytes16();
|
|
1544
|
+
const body = r.consumed();
|
|
1545
|
+
const mac = r.bytes(MAC_LENGTH);
|
|
1546
|
+
r.end();
|
|
1547
|
+
if (!constantTimeEqual(requestHash, state.hash)) {
|
|
1548
|
+
throw new PoolseCryptoError("tampered", "This grant answers a different request");
|
|
1549
|
+
}
|
|
1550
|
+
const macKey = await grantMacKey(state.secret, state.hash);
|
|
1551
|
+
if (!await hmacVerify(macKey, macInput(body, options.accountId), mac)) {
|
|
1552
|
+
throw new PoolseCryptoError("tampered", "The device grant is not authentic");
|
|
1553
|
+
}
|
|
1554
|
+
const approver = await devicePublicKeys(approverEncryption, approverSigning);
|
|
1555
|
+
const { key } = await unwrapAccountKeyForDevice(wrap, device, {
|
|
1556
|
+
accountId: options.accountId,
|
|
1557
|
+
requireSignatureFrom: approver
|
|
1558
|
+
});
|
|
1559
|
+
return { accountKey: key, approver, accountKeyWrap: wrap };
|
|
1560
|
+
}
|
|
1561
|
+
|
|
1562
|
+
// src/sync.ts
|
|
1563
|
+
var MemoryBlobTransport = class {
|
|
1564
|
+
blobs = /* @__PURE__ */ new Map();
|
|
1565
|
+
counter = 0;
|
|
1566
|
+
log = [];
|
|
1567
|
+
check(key, precondition) {
|
|
1568
|
+
const current = this.blobs.get(key);
|
|
1569
|
+
if (precondition.ifNoneMatch === "*" && current)
|
|
1570
|
+
throw new BlobConflictError(key, current.version);
|
|
1571
|
+
if (precondition.ifMatch !== void 0 && current?.version !== precondition.ifMatch) {
|
|
1572
|
+
throw new BlobConflictError(key, current?.version ?? null);
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
async get(key) {
|
|
1576
|
+
const blob = this.blobs.get(key);
|
|
1577
|
+
return blob ? { data: new Uint8Array(blob.data), version: blob.version } : null;
|
|
1578
|
+
}
|
|
1579
|
+
async put(key, data, precondition) {
|
|
1580
|
+
this.check(key, precondition);
|
|
1581
|
+
const version = `v${++this.counter}`;
|
|
1582
|
+
const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1583
|
+
this.blobs.set(key, { data: new Uint8Array(data), version, updatedAt });
|
|
1584
|
+
this.log.push({ key, version, size: data.length, updatedAt, deleted: false });
|
|
1585
|
+
return { version };
|
|
1586
|
+
}
|
|
1587
|
+
async delete(key, precondition) {
|
|
1588
|
+
this.check(key, precondition);
|
|
1589
|
+
if (!this.blobs.delete(key)) return;
|
|
1590
|
+
const version = `v${++this.counter}`;
|
|
1591
|
+
this.log.push({ key, version, size: 0, updatedAt: (/* @__PURE__ */ new Date()).toISOString(), deleted: true });
|
|
1592
|
+
}
|
|
1593
|
+
async list(options) {
|
|
1594
|
+
const limit = options.limit ?? 100;
|
|
1595
|
+
const keys = [...this.blobs.keys()].sort().filter((k) => options.prefix === void 0 || k.startsWith(options.prefix)).filter((k) => options.cursor === void 0 || k > options.cursor);
|
|
1596
|
+
const page = keys.slice(0, limit);
|
|
1597
|
+
return {
|
|
1598
|
+
blobs: page.map((key) => {
|
|
1599
|
+
const blob = this.blobs.get(key);
|
|
1600
|
+
return { key, version: blob.version, size: blob.data.length, updatedAt: blob.updatedAt };
|
|
1601
|
+
}),
|
|
1602
|
+
cursor: keys.length > limit ? page[page.length - 1] ?? null : null
|
|
1603
|
+
};
|
|
1604
|
+
}
|
|
1605
|
+
async changes(options) {
|
|
1606
|
+
const from = options.cursor === void 0 ? 0 : Number(options.cursor);
|
|
1607
|
+
const page = this.log.slice(from, from + (options.limit ?? 100));
|
|
1608
|
+
return { changes: page.map((c) => ({ ...c })), cursor: String(from + page.length) };
|
|
1609
|
+
}
|
|
1610
|
+
};
|
|
1611
|
+
var FLAG_DELETED = 1;
|
|
1612
|
+
var MAX_NAME_LENGTH = 1024;
|
|
1613
|
+
var EncryptedBlobStore = class {
|
|
1614
|
+
transport;
|
|
1615
|
+
accountKey;
|
|
1616
|
+
namespace;
|
|
1617
|
+
keyPrefix;
|
|
1618
|
+
revisions;
|
|
1619
|
+
known = /* @__PURE__ */ new Map();
|
|
1620
|
+
keyPromise = null;
|
|
1621
|
+
nameKeyPromise = null;
|
|
1622
|
+
constructor(options) {
|
|
1623
|
+
this.transport = options.transport;
|
|
1624
|
+
this.accountKey = options.accountKey;
|
|
1625
|
+
this.namespace = options.namespace ?? "default";
|
|
1626
|
+
this.keyPrefix = options.keyPrefix ?? "";
|
|
1627
|
+
const memory = /* @__PURE__ */ new Map();
|
|
1628
|
+
this.revisions = options.revisions ?? {
|
|
1629
|
+
get: (key) => memory.get(key),
|
|
1630
|
+
set: (key, revision) => void memory.set(key, revision)
|
|
1631
|
+
};
|
|
1632
|
+
}
|
|
1633
|
+
contentKey() {
|
|
1634
|
+
this.keyPromise ??= deriveAesKey(secretOf(this.accountKey), `sync/${this.namespace}`);
|
|
1635
|
+
return this.keyPromise;
|
|
1636
|
+
}
|
|
1637
|
+
/**
|
|
1638
|
+
* The blob key for a name: an HMAC of the namespace and name under a key
|
|
1639
|
+
* derived from the account key, so the server can't read names or tell
|
|
1640
|
+
* which blob is which across namespaces.
|
|
1641
|
+
*/
|
|
1642
|
+
async blobKey(name) {
|
|
1643
|
+
checkName(name);
|
|
1644
|
+
this.nameKeyPromise ??= hkdf(
|
|
1645
|
+
secretOf(this.accountKey),
|
|
1646
|
+
new Uint8Array(0),
|
|
1647
|
+
label(DOMAIN, "key/sync-names/", this.namespace)
|
|
1648
|
+
);
|
|
1649
|
+
const mac = await hmac(await this.nameKeyPromise, utf8(name));
|
|
1650
|
+
return this.keyPrefix + toBase32(mac.slice(0, 20)).toLowerCase();
|
|
1651
|
+
}
|
|
1652
|
+
aad(prefix, blobKey) {
|
|
1653
|
+
return concat(
|
|
1654
|
+
prefix,
|
|
1655
|
+
encodeAssociatedData("sync", { namespace: this.namespace, key: blobKey })
|
|
1656
|
+
);
|
|
1657
|
+
}
|
|
1658
|
+
async seal(blobKey, revision, flags, name, data) {
|
|
1659
|
+
const raw = secretOf(this.accountKey);
|
|
1660
|
+
const iv = randomBytes(IV_LENGTH);
|
|
1661
|
+
const prefix = writeHeader(new ByteWriter(), Kind.SyncRecord, Alg.Aes256GcmHkdfSha256).u64(revision).bytes(await keyCheck(raw, `sync/${this.namespace}`)).bytes(iv).finish();
|
|
1662
|
+
const plaintext = new ByteWriter().u8(flags).bytes16(utf8(name)).bytes(data).finish();
|
|
1663
|
+
const ct = await aesEncrypt(
|
|
1664
|
+
await this.contentKey(),
|
|
1665
|
+
iv,
|
|
1666
|
+
pad(plaintext),
|
|
1667
|
+
this.aad(prefix, blobKey)
|
|
1668
|
+
);
|
|
1669
|
+
return concat(prefix, ct);
|
|
1670
|
+
}
|
|
1671
|
+
async open(blobKey, record) {
|
|
1672
|
+
const r = new ByteReader(record);
|
|
1673
|
+
readHeader(r, Kind.SyncRecord, [Alg.Aes256GcmHkdfSha256]);
|
|
1674
|
+
const revision = r.u64();
|
|
1675
|
+
await verifyKeyCheck(
|
|
1676
|
+
secretOf(this.accountKey),
|
|
1677
|
+
`sync/${this.namespace}`,
|
|
1678
|
+
r.bytes(CHECK_LENGTH)
|
|
1679
|
+
);
|
|
1680
|
+
const iv = r.bytes(IV_LENGTH);
|
|
1681
|
+
const prefix = r.consumed();
|
|
1682
|
+
const ct = r.rest();
|
|
1683
|
+
const plaintext = unpad(
|
|
1684
|
+
await aesDecrypt(await this.contentKey(), iv, ct, this.aad(prefix, blobKey))
|
|
1685
|
+
);
|
|
1686
|
+
const p = new ByteReader(plaintext);
|
|
1687
|
+
const flags = p.u8();
|
|
1688
|
+
const name = fromUtf8(p.bytes16());
|
|
1689
|
+
const data = p.rest();
|
|
1690
|
+
return { revision, deleted: (flags & FLAG_DELETED) !== 0, name, data };
|
|
1691
|
+
}
|
|
1692
|
+
/** Read by blob key (as `list` returns them). Deleted blobs read as `null`. */
|
|
1693
|
+
async getByKey(blobKey) {
|
|
1694
|
+
const blob = await this.transport.get(blobKey);
|
|
1695
|
+
if (!blob) return null;
|
|
1696
|
+
const record = await this.open(blobKey, blob.data);
|
|
1697
|
+
const seen = await this.revisions.get(blobKey);
|
|
1698
|
+
if (seen !== void 0 && record.revision < seen) {
|
|
1699
|
+
throw new PoolseCryptoError(
|
|
1700
|
+
"rollback",
|
|
1701
|
+
`The server returned revision ${record.revision} of a blob already seen at ${seen}`
|
|
1702
|
+
);
|
|
1703
|
+
}
|
|
1704
|
+
await this.remember(blobKey, blob.version, record.revision);
|
|
1705
|
+
if (record.deleted) return null;
|
|
1706
|
+
return {
|
|
1707
|
+
name: record.name,
|
|
1708
|
+
data: record.data,
|
|
1709
|
+
version: blob.version,
|
|
1710
|
+
revision: record.revision
|
|
1711
|
+
};
|
|
1712
|
+
}
|
|
1713
|
+
/** Download and decrypt a blob. `null` if it doesn't exist or was deleted. */
|
|
1714
|
+
async get(name) {
|
|
1715
|
+
const blobKey = await this.blobKey(name);
|
|
1716
|
+
const blob = await this.getByKey(blobKey);
|
|
1717
|
+
if (blob && blob.name !== name) {
|
|
1718
|
+
throw new PoolseCryptoError("tampered", "The blob belongs to a different name");
|
|
1719
|
+
}
|
|
1720
|
+
return blob;
|
|
1721
|
+
}
|
|
1722
|
+
async getJson(name) {
|
|
1723
|
+
const blob = await this.get(name);
|
|
1724
|
+
if (!blob) return null;
|
|
1725
|
+
const { data, ...rest } = blob;
|
|
1726
|
+
return { ...rest, value: JSON.parse(fromUtf8(data)) };
|
|
1727
|
+
}
|
|
1728
|
+
/**
|
|
1729
|
+
* Encrypt and upload. Throws `BlobConflictError` when another device wrote
|
|
1730
|
+
* first: `get` the newer version, merge, and `put` again (or use `update`).
|
|
1731
|
+
*/
|
|
1732
|
+
async put(name, data, options = {}) {
|
|
1733
|
+
return this.write(name, data, 0, options);
|
|
1734
|
+
}
|
|
1735
|
+
async putJson(name, value, options = {}) {
|
|
1736
|
+
return this.put(name, utf8(JSON.stringify(value)), options);
|
|
1737
|
+
}
|
|
1738
|
+
/**
|
|
1739
|
+
* Delete by writing an encrypted tombstone, so the deletion is authenticated
|
|
1740
|
+
* and the revision keeps counting (a plain DELETE could be forged or undone
|
|
1741
|
+
* by the server). `purge` removes the blob for real.
|
|
1742
|
+
*/
|
|
1743
|
+
async delete(name, options = {}) {
|
|
1744
|
+
await this.write(name, new Uint8Array(0), FLAG_DELETED, options);
|
|
1745
|
+
}
|
|
1746
|
+
/** Remove the blob from the server. Unauthenticated: prefer `delete`. */
|
|
1747
|
+
async purge(name, options = {}) {
|
|
1748
|
+
const blobKey = await this.blobKey(name);
|
|
1749
|
+
const version = options.ifVersion === void 0 ? this.known.get(blobKey)?.version : options.ifVersion;
|
|
1750
|
+
await this.transport.delete(blobKey, version ? { ifMatch: version } : {});
|
|
1751
|
+
this.known.delete(blobKey);
|
|
1752
|
+
}
|
|
1753
|
+
/**
|
|
1754
|
+
* Read, change, write — retried on conflict. `change` gets the current
|
|
1755
|
+
* data (`null` if none) and returns the new data, or `null` to delete.
|
|
1756
|
+
* It may run more than once, so keep it free of side effects.
|
|
1757
|
+
*/
|
|
1758
|
+
async update(name, change, options = {}) {
|
|
1759
|
+
const retries = options.retries ?? 5;
|
|
1760
|
+
for (let attempt = 0; ; attempt++) {
|
|
1761
|
+
const blobKey = await this.blobKey(name);
|
|
1762
|
+
const current = await this.get(name);
|
|
1763
|
+
const next = await change(current ? current.data : null);
|
|
1764
|
+
const ifVersion = current?.version ?? this.known.get(blobKey)?.version ?? null;
|
|
1765
|
+
try {
|
|
1766
|
+
if (next === null) {
|
|
1767
|
+
if (current) await this.delete(name, { ifVersion });
|
|
1768
|
+
return null;
|
|
1769
|
+
}
|
|
1770
|
+
return await this.put(name, next, { ifVersion });
|
|
1771
|
+
} catch (error) {
|
|
1772
|
+
if (!(error instanceof BlobConflictError) || attempt >= retries) throw error;
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
}
|
|
1776
|
+
async updateJson(name, change, options = {}) {
|
|
1777
|
+
let result = null;
|
|
1778
|
+
await this.update(
|
|
1779
|
+
name,
|
|
1780
|
+
async (data) => {
|
|
1781
|
+
result = await change(data ? JSON.parse(fromUtf8(data)) : null);
|
|
1782
|
+
return result === null ? null : utf8(JSON.stringify(result));
|
|
1783
|
+
},
|
|
1784
|
+
options
|
|
1785
|
+
);
|
|
1786
|
+
return result;
|
|
1787
|
+
}
|
|
1788
|
+
/**
|
|
1789
|
+
* One page of this user's blobs (under `keyPrefix`, if set). Read each with
|
|
1790
|
+
* `getByKey`.
|
|
1791
|
+
*/
|
|
1792
|
+
async list(options = {}) {
|
|
1793
|
+
const page = await this.transport.list(
|
|
1794
|
+
this.keyPrefix ? { ...options, prefix: this.keyPrefix } : options
|
|
1795
|
+
);
|
|
1796
|
+
if (!this.keyPrefix) return page;
|
|
1797
|
+
return { ...page, blobs: page.blobs.filter((b) => b.key.startsWith(this.keyPrefix)) };
|
|
1798
|
+
}
|
|
1799
|
+
/**
|
|
1800
|
+
* What changed since `cursor` (writes and deletions, oldest first), under
|
|
1801
|
+
* `keyPrefix` if set. Keep the returned cursor; read changed blobs with
|
|
1802
|
+
* `getByKey` (a deleted one reads as `null`). Needs a transport with
|
|
1803
|
+
* `changes` (the HTTP one has it).
|
|
1804
|
+
*/
|
|
1805
|
+
async changes(options = {}) {
|
|
1806
|
+
if (!this.transport.changes) {
|
|
1807
|
+
throw new PoolseCryptoError("unavailable", "This blob transport has no change feed");
|
|
1808
|
+
}
|
|
1809
|
+
const page = await this.transport.changes(options);
|
|
1810
|
+
if (!this.keyPrefix) return page;
|
|
1811
|
+
return { ...page, changes: page.changes.filter((c) => c.key.startsWith(this.keyPrefix)) };
|
|
1812
|
+
}
|
|
1813
|
+
async write(name, data, flags, options) {
|
|
1814
|
+
const blobKey = await this.blobKey(name);
|
|
1815
|
+
const known = this.known.get(blobKey);
|
|
1816
|
+
const ifVersion = options.ifVersion === void 0 ? known?.version ?? null : options.ifVersion;
|
|
1817
|
+
const seen = await this.revisions.get(blobKey) ?? 0;
|
|
1818
|
+
const revision = Math.max(seen, known?.revision ?? 0) + 1;
|
|
1819
|
+
const record = await this.seal(blobKey, revision, flags, name, data);
|
|
1820
|
+
let result;
|
|
1821
|
+
try {
|
|
1822
|
+
result = await this.transport.put(
|
|
1823
|
+
blobKey,
|
|
1824
|
+
record,
|
|
1825
|
+
ifVersion === null ? { ifNoneMatch: "*" } : { ifMatch: ifVersion }
|
|
1826
|
+
);
|
|
1827
|
+
} catch (error) {
|
|
1828
|
+
if (error instanceof BlobConflictError) this.known.delete(blobKey);
|
|
1829
|
+
throw error;
|
|
1830
|
+
}
|
|
1831
|
+
await this.remember(blobKey, result.version, revision);
|
|
1832
|
+
return { name, data: new Uint8Array(data), version: result.version, revision };
|
|
1833
|
+
}
|
|
1834
|
+
async remember(blobKey, version, revision) {
|
|
1835
|
+
this.known.set(blobKey, { version, revision });
|
|
1836
|
+
const seen = await this.revisions.get(blobKey);
|
|
1837
|
+
if (seen === void 0 || revision > seen) await this.revisions.set(blobKey, revision);
|
|
1838
|
+
}
|
|
1839
|
+
};
|
|
1840
|
+
function checkName(name) {
|
|
1841
|
+
if (typeof name !== "string" || name.length === 0 || utf8(name).length > MAX_NAME_LENGTH) {
|
|
1842
|
+
throw new PoolseCryptoError("malformed", `Blob names are 1\u2026${MAX_NAME_LENGTH} bytes`);
|
|
1843
|
+
}
|
|
1844
|
+
}
|
|
1845
|
+
|
|
1846
|
+
// src/http.ts
|
|
1847
|
+
var BlobTransportError = class extends Error {
|
|
1848
|
+
constructor(code, message, status = 0, serverCode = null, retryAfterMs = null) {
|
|
1849
|
+
super(message);
|
|
1850
|
+
this.code = code;
|
|
1851
|
+
this.status = status;
|
|
1852
|
+
this.serverCode = serverCode;
|
|
1853
|
+
this.retryAfterMs = retryAfterMs;
|
|
1854
|
+
}
|
|
1855
|
+
code;
|
|
1856
|
+
status;
|
|
1857
|
+
serverCode;
|
|
1858
|
+
retryAfterMs;
|
|
1859
|
+
name = "BlobTransportError";
|
|
1860
|
+
/** Worth retrying later as is (rate limit, server error, network). */
|
|
1861
|
+
get retryable() {
|
|
1862
|
+
return this.code === "rate_limited" || this.code === "server" || this.code === "network";
|
|
1863
|
+
}
|
|
1864
|
+
};
|
|
1865
|
+
var KEY_RE = /^[a-z0-9.]{1,128}$/;
|
|
1866
|
+
function isValidBlobKey(key) {
|
|
1867
|
+
return KEY_RE.test(key) && !key.startsWith(".") && !key.endsWith(".") && !key.includes("..");
|
|
1868
|
+
}
|
|
1869
|
+
function checkKey(key) {
|
|
1870
|
+
if (!isValidBlobKey(key)) {
|
|
1871
|
+
throw new BlobTransportError(
|
|
1872
|
+
"invalid_key",
|
|
1873
|
+
`Blob key "${key}" must be 1\u2013128 of a\u2013z, 0\u20139 and "." (no leading, trailing or double dot)`
|
|
1874
|
+
);
|
|
1875
|
+
}
|
|
1876
|
+
}
|
|
1877
|
+
function parseEtag(value) {
|
|
1878
|
+
if (!value) return null;
|
|
1879
|
+
const v = value.trim().replace(/^W\//, "").replace(/^"(.*)"$/, "$1");
|
|
1880
|
+
return v.length > 0 ? v : null;
|
|
1881
|
+
}
|
|
1882
|
+
function retryAfter(value) {
|
|
1883
|
+
if (!value) return null;
|
|
1884
|
+
const seconds = Number(value);
|
|
1885
|
+
if (Number.isFinite(seconds) && seconds >= 0) return Math.round(seconds * 1e3);
|
|
1886
|
+
const date = Date.parse(value);
|
|
1887
|
+
return Number.isNaN(date) ? null : Math.max(0, date - Date.now());
|
|
1888
|
+
}
|
|
1889
|
+
async function serverError(response) {
|
|
1890
|
+
try {
|
|
1891
|
+
const body = await response.json();
|
|
1892
|
+
return {
|
|
1893
|
+
code: typeof body.error?.code === "string" ? body.error.code : null,
|
|
1894
|
+
message: typeof body.error?.message === "string" ? body.error.message : `HTTP ${response.status}`
|
|
1895
|
+
};
|
|
1896
|
+
} catch {
|
|
1897
|
+
return { code: null, message: `HTTP ${response.status}` };
|
|
1898
|
+
}
|
|
1899
|
+
}
|
|
1900
|
+
async function toError(response) {
|
|
1901
|
+
const { code, message } = await serverError(response);
|
|
1902
|
+
const s = response.status;
|
|
1903
|
+
const mapped = s === 413 ? code === "quota_exceeded" ? "quota_exceeded" : "too_large" : s === 403 ? code === "sync_disabled" ? "sync_disabled" : "forbidden" : s === 429 ? "rate_limited" : s === 422 && code === "invalid_key" ? "invalid_key" : s === 401 ? "unauthorized" : s === 404 ? "not_found" : s >= 500 ? "server" : "http";
|
|
1904
|
+
return new BlobTransportError(
|
|
1905
|
+
mapped,
|
|
1906
|
+
message,
|
|
1907
|
+
s,
|
|
1908
|
+
code,
|
|
1909
|
+
s === 429 ? retryAfter(response.headers.get("retry-after")) : null
|
|
1910
|
+
);
|
|
1911
|
+
}
|
|
1912
|
+
function toInfo(raw) {
|
|
1913
|
+
const version = (typeof raw.etag === "string" ? parseEtag(raw.etag) : null) ?? (raw.version !== void 0 && raw.version !== null ? String(raw.version) : null);
|
|
1914
|
+
if (typeof raw.key !== "string" || !version) {
|
|
1915
|
+
throw new BlobTransportError("bad_response", "A listed blob has no key or version");
|
|
1916
|
+
}
|
|
1917
|
+
const info = { key: raw.key, version };
|
|
1918
|
+
const size = typeof raw.size === "number" ? raw.size : raw.size_bytes;
|
|
1919
|
+
if (typeof size === "number") info.size = size;
|
|
1920
|
+
if (typeof raw.updated_at === "string") info.updatedAt = raw.updated_at;
|
|
1921
|
+
return info;
|
|
1922
|
+
}
|
|
1923
|
+
function toLimits(raw) {
|
|
1924
|
+
if (!raw || typeof raw !== "object") return void 0;
|
|
1925
|
+
const r = raw;
|
|
1926
|
+
const limits = {};
|
|
1927
|
+
if (typeof r.max_blob_bytes === "number") limits.maxBlobBytes = r.max_blob_bytes;
|
|
1928
|
+
if (typeof r.max_user_bytes === "number") limits.maxUserBytes = r.max_user_bytes;
|
|
1929
|
+
if (typeof r.max_blobs === "number") limits.maxBlobs = r.max_blobs;
|
|
1930
|
+
return limits;
|
|
1931
|
+
}
|
|
1932
|
+
function createHttpBlobTransport(options) {
|
|
1933
|
+
const base = options.apiUrl.replace(/\/+$/, "");
|
|
1934
|
+
const doFetch = (input, init) => {
|
|
1935
|
+
const f = options.fetch ?? globalThis.fetch;
|
|
1936
|
+
if (typeof f !== "function") {
|
|
1937
|
+
throw new BlobTransportError("network", "fetch is not available; pass options.fetch");
|
|
1938
|
+
}
|
|
1939
|
+
return f(input, init);
|
|
1940
|
+
};
|
|
1941
|
+
async function request(method, path, headers = {}, body) {
|
|
1942
|
+
for (let attempt = 0; ; attempt++) {
|
|
1943
|
+
const token = await options.getToken();
|
|
1944
|
+
const init = {
|
|
1945
|
+
method,
|
|
1946
|
+
headers: { Authorization: `Bearer ${token}`, ...headers }
|
|
1947
|
+
};
|
|
1948
|
+
if (body) init.body = new Uint8Array(body);
|
|
1949
|
+
let response;
|
|
1950
|
+
try {
|
|
1951
|
+
response = await doFetch(`${base}${path}`, init);
|
|
1952
|
+
} catch (error) {
|
|
1953
|
+
if (error instanceof BlobTransportError) throw error;
|
|
1954
|
+
throw new BlobTransportError(
|
|
1955
|
+
"network",
|
|
1956
|
+
`Could not reach the server: ${error instanceof Error ? error.message : String(error)}`
|
|
1957
|
+
);
|
|
1958
|
+
}
|
|
1959
|
+
if (response.status === 401 && attempt === 0) {
|
|
1960
|
+
await response.body?.cancel().catch(() => void 0);
|
|
1961
|
+
continue;
|
|
1962
|
+
}
|
|
1963
|
+
return response;
|
|
1964
|
+
}
|
|
1965
|
+
}
|
|
1966
|
+
function blobPath(key) {
|
|
1967
|
+
checkKey(key);
|
|
1968
|
+
return `/v1/me/blobs/${encodeURIComponent(key)}`;
|
|
1969
|
+
}
|
|
1970
|
+
function query(params) {
|
|
1971
|
+
const q = new URLSearchParams();
|
|
1972
|
+
for (const [k, v] of Object.entries(params)) if (v !== void 0) q.set(k, String(v));
|
|
1973
|
+
const s = q.toString();
|
|
1974
|
+
return s ? `?${s}` : "";
|
|
1975
|
+
}
|
|
1976
|
+
async function json(response) {
|
|
1977
|
+
try {
|
|
1978
|
+
const value = await response.json();
|
|
1979
|
+
if (value && typeof value === "object") return value;
|
|
1980
|
+
} catch {
|
|
1981
|
+
}
|
|
1982
|
+
throw new BlobTransportError(
|
|
1983
|
+
"bad_response",
|
|
1984
|
+
"The server did not answer with JSON",
|
|
1985
|
+
response.status
|
|
1986
|
+
);
|
|
1987
|
+
}
|
|
1988
|
+
async function conflict(key, response) {
|
|
1989
|
+
await response.body?.cancel().catch(() => void 0);
|
|
1990
|
+
return new BlobConflictError(key, parseEtag(response.headers.get("etag")));
|
|
1991
|
+
}
|
|
1992
|
+
return {
|
|
1993
|
+
async get(key) {
|
|
1994
|
+
const response = await request("GET", blobPath(key), { Accept: "application/octet-stream" });
|
|
1995
|
+
if (response.status === 404) {
|
|
1996
|
+
await response.body?.cancel().catch(() => void 0);
|
|
1997
|
+
return null;
|
|
1998
|
+
}
|
|
1999
|
+
if (!response.ok) throw await toError(response);
|
|
2000
|
+
const version = parseEtag(response.headers.get("etag"));
|
|
2001
|
+
if (!version) {
|
|
2002
|
+
throw new BlobTransportError(
|
|
2003
|
+
"bad_response",
|
|
2004
|
+
"The blob came without an ETag (in a browser, expose it with Access-Control-Expose-Headers)",
|
|
2005
|
+
response.status
|
|
2006
|
+
);
|
|
2007
|
+
}
|
|
2008
|
+
return { data: new Uint8Array(await response.arrayBuffer()), version };
|
|
2009
|
+
},
|
|
2010
|
+
async put(key, data, precondition) {
|
|
2011
|
+
const headers = { "Content-Type": "application/octet-stream" };
|
|
2012
|
+
if (precondition.ifMatch !== void 0) headers["If-Match"] = `"${precondition.ifMatch}"`;
|
|
2013
|
+
if (precondition.ifNoneMatch === "*") headers["If-None-Match"] = "*";
|
|
2014
|
+
const response = await request("PUT", blobPath(key), headers, data);
|
|
2015
|
+
if (response.status === 412 || response.status === 409) throw await conflict(key, response);
|
|
2016
|
+
if (!response.ok) throw await toError(response);
|
|
2017
|
+
let version = parseEtag(response.headers.get("etag"));
|
|
2018
|
+
if (!version) {
|
|
2019
|
+
const body = await json(response);
|
|
2020
|
+
if (body.version !== void 0 && body.version !== null) version = String(body.version);
|
|
2021
|
+
}
|
|
2022
|
+
if (!version) {
|
|
2023
|
+
throw new BlobTransportError(
|
|
2024
|
+
"bad_response",
|
|
2025
|
+
"The write came back without a version",
|
|
2026
|
+
response.status
|
|
2027
|
+
);
|
|
2028
|
+
}
|
|
2029
|
+
return { version };
|
|
2030
|
+
},
|
|
2031
|
+
async delete(key, precondition) {
|
|
2032
|
+
const headers = {};
|
|
2033
|
+
if (precondition.ifMatch !== void 0) headers["If-Match"] = `"${precondition.ifMatch}"`;
|
|
2034
|
+
const response = await request("DELETE", blobPath(key), headers);
|
|
2035
|
+
if (response.status === 412 || response.status === 409) throw await conflict(key, response);
|
|
2036
|
+
if (response.status === 404) {
|
|
2037
|
+
await response.body?.cancel().catch(() => void 0);
|
|
2038
|
+
if (precondition.ifMatch !== void 0) throw new BlobConflictError(key, null);
|
|
2039
|
+
return;
|
|
2040
|
+
}
|
|
2041
|
+
if (!response.ok) throw await toError(response);
|
|
2042
|
+
await response.body?.cancel().catch(() => void 0);
|
|
2043
|
+
},
|
|
2044
|
+
async list(listOptions) {
|
|
2045
|
+
const response = await request(
|
|
2046
|
+
"GET",
|
|
2047
|
+
`/v1/me/blobs${query({ prefix: listOptions.prefix, cursor: listOptions.cursor, limit: listOptions.limit })}`,
|
|
2048
|
+
{ Accept: "application/json" }
|
|
2049
|
+
);
|
|
2050
|
+
if (!response.ok) throw await toError(response);
|
|
2051
|
+
const body = await json(response);
|
|
2052
|
+
if (!Array.isArray(body.data))
|
|
2053
|
+
throw new BlobTransportError("bad_response", "No data in the listing");
|
|
2054
|
+
const page = {
|
|
2055
|
+
blobs: body.data.map(toInfo),
|
|
2056
|
+
cursor: typeof body.next_cursor === "string" ? body.next_cursor : null
|
|
2057
|
+
};
|
|
2058
|
+
const limits = toLimits(body.limits);
|
|
2059
|
+
if (limits) page.limits = limits;
|
|
2060
|
+
return page;
|
|
2061
|
+
},
|
|
2062
|
+
async changes(changeOptions) {
|
|
2063
|
+
const response = await request(
|
|
2064
|
+
"GET",
|
|
2065
|
+
`/v1/me/blob-changes${query({ cursor: changeOptions.cursor, limit: changeOptions.limit })}`,
|
|
2066
|
+
{ Accept: "application/json" }
|
|
2067
|
+
);
|
|
2068
|
+
if (!response.ok) throw await toError(response);
|
|
2069
|
+
const body = await json(response);
|
|
2070
|
+
if (!Array.isArray(body.data))
|
|
2071
|
+
throw new BlobTransportError("bad_response", "No data in the changes");
|
|
2072
|
+
const changes = body.data.map((raw) => ({
|
|
2073
|
+
...toInfo(raw),
|
|
2074
|
+
deleted: raw.deleted === true
|
|
2075
|
+
}));
|
|
2076
|
+
const cursor = typeof body.next_cursor === "string" ? body.next_cursor : changeOptions.cursor ?? "";
|
|
2077
|
+
return { changes, cursor };
|
|
2078
|
+
}
|
|
2079
|
+
};
|
|
2080
|
+
}
|
|
2081
|
+
|
|
2082
|
+
// src/notes.ts
|
|
2083
|
+
function noteAssociatedData(noteId, revision, slot) {
|
|
2084
|
+
return { itemId: noteId, version: revision, slot };
|
|
2085
|
+
}
|
|
2086
|
+
function noteAttachmentAssociatedData(noteId, attachmentId) {
|
|
2087
|
+
return { itemId: noteId, attachmentId };
|
|
2088
|
+
}
|
|
2089
|
+
function folderAssociatedData(folderId) {
|
|
2090
|
+
return { itemId: folderId, slot: "folder" };
|
|
2091
|
+
}
|
|
2092
|
+
async function sealNote(key, note, options) {
|
|
2093
|
+
checkRevision(options.revision);
|
|
2094
|
+
const meta = { title: note.title, body: null, metadata: note.metadata ?? {} };
|
|
2095
|
+
return {
|
|
2096
|
+
meta: toBase64Url(
|
|
2097
|
+
await encryptItem(key, meta, noteAssociatedData(options.noteId, options.revision, "meta"))
|
|
2098
|
+
),
|
|
2099
|
+
content: toBase64Url(
|
|
2100
|
+
await encryptItem(
|
|
2101
|
+
key,
|
|
2102
|
+
{ title: note.title, body: note.body, metadata: note.metadata ?? {} },
|
|
2103
|
+
noteAssociatedData(options.noteId, options.revision, "content")
|
|
2104
|
+
)
|
|
2105
|
+
),
|
|
2106
|
+
key_version: key.version
|
|
2107
|
+
};
|
|
2108
|
+
}
|
|
2109
|
+
async function openNoteMeta(key, meta, options) {
|
|
2110
|
+
const m = await decryptItem(
|
|
2111
|
+
key,
|
|
2112
|
+
fromBase64Url(meta),
|
|
2113
|
+
noteAssociatedData(options.noteId, options.revision, "meta")
|
|
2114
|
+
);
|
|
2115
|
+
return { title: m.title, metadata: m.metadata ?? {} };
|
|
2116
|
+
}
|
|
2117
|
+
async function openNoteContent(key, content, options) {
|
|
2118
|
+
return decryptItem(
|
|
2119
|
+
key,
|
|
2120
|
+
fromBase64Url(content),
|
|
2121
|
+
noteAssociatedData(options.noteId, options.revision, "content")
|
|
2122
|
+
);
|
|
2123
|
+
}
|
|
2124
|
+
function envelopeKeyVersion(envelope) {
|
|
2125
|
+
const info = inspectEnvelope(fromBase64Url(envelope));
|
|
2126
|
+
if (info.keyVersion === void 0) {
|
|
2127
|
+
throw new PoolseCryptoError("malformed", "Not an item envelope");
|
|
2128
|
+
}
|
|
2129
|
+
return info.keyVersion;
|
|
2130
|
+
}
|
|
2131
|
+
async function noteKeyForVersion(current, keyHistory, version, options) {
|
|
2132
|
+
if (version > current.version) {
|
|
2133
|
+
throw new PoolseCryptoError("wrong-key", `Key version ${version} is newer than the note's`);
|
|
2134
|
+
}
|
|
2135
|
+
let key = current;
|
|
2136
|
+
while (key.version > version) {
|
|
2137
|
+
const wrap = keyHistory[String(key.version - 1)];
|
|
2138
|
+
if (!wrap) {
|
|
2139
|
+
throw new PoolseCryptoError("wrong-key", `key_history has no key ${key.version - 1}`);
|
|
2140
|
+
}
|
|
2141
|
+
key = await unwrapPreviousItemKey(fromBase64Url(wrap), key, { itemId: options.noteId });
|
|
2142
|
+
}
|
|
2143
|
+
return key;
|
|
2144
|
+
}
|
|
2145
|
+
async function sealFolder(name, accountKey, options) {
|
|
2146
|
+
const key = options.key ?? ItemKey.generate();
|
|
2147
|
+
return {
|
|
2148
|
+
key,
|
|
2149
|
+
name_envelope: toBase64Url(
|
|
2150
|
+
await encryptItem(key, { title: name, body: null }, folderAssociatedData(options.folderId))
|
|
2151
|
+
),
|
|
2152
|
+
key_wrap: toBase64Url(await wrapItemKey(key, accountKey, { itemId: options.folderId }))
|
|
2153
|
+
};
|
|
2154
|
+
}
|
|
2155
|
+
async function openFolderName(key, nameEnvelope, options) {
|
|
2156
|
+
const item = await decryptItem(
|
|
2157
|
+
key,
|
|
2158
|
+
fromBase64Url(nameEnvelope),
|
|
2159
|
+
folderAssociatedData(options.folderId)
|
|
2160
|
+
);
|
|
2161
|
+
return item.title;
|
|
2162
|
+
}
|
|
2163
|
+
async function shareWrapsFor(key, recipients, options) {
|
|
2164
|
+
const out = [];
|
|
2165
|
+
for (const r of recipients) {
|
|
2166
|
+
for (const device of r.devices) {
|
|
2167
|
+
const wrap = await shareItemKey(key, device, {
|
|
2168
|
+
itemId: options.noteId,
|
|
2169
|
+
signer: options.signer
|
|
2170
|
+
});
|
|
2171
|
+
out.push({ member_id: r.memberId, device_id: device.id, wrap: toBase64Url(wrap) });
|
|
2172
|
+
}
|
|
2173
|
+
}
|
|
2174
|
+
return out;
|
|
2175
|
+
}
|
|
2176
|
+
async function rotateNoteKey(previous, note, options) {
|
|
2177
|
+
const key = rotateItemKey(previous);
|
|
2178
|
+
const sealed = await sealNote(key, note, options);
|
|
2179
|
+
return {
|
|
2180
|
+
...sealed,
|
|
2181
|
+
key,
|
|
2182
|
+
key_wrap: toBase64Url(await wrapItemKey(key, options.accountKey, { itemId: options.noteId })),
|
|
2183
|
+
key_history: {
|
|
2184
|
+
[String(previous.version)]: toBase64Url(
|
|
2185
|
+
await wrapPreviousItemKey(previous, key, { itemId: options.noteId })
|
|
2186
|
+
)
|
|
2187
|
+
},
|
|
2188
|
+
share_wraps: await shareWrapsFor(key, options.remaining, options)
|
|
2189
|
+
};
|
|
2190
|
+
}
|
|
2191
|
+
function shareExpired(expiresAt, now = Date.now()) {
|
|
2192
|
+
if (!expiresAt) return false;
|
|
2193
|
+
const t = Date.parse(expiresAt);
|
|
2194
|
+
return Number.isFinite(t) && t <= now;
|
|
2195
|
+
}
|
|
2196
|
+
var RECOVERY_AUTH_LABEL = "recovery-auth";
|
|
2197
|
+
async function recoveryAuth(recoveryKey) {
|
|
2198
|
+
return hkdf(secretOf(recoveryKey), new Uint8Array(0), label(DOMAIN, RECOVERY_AUTH_LABEL), 32);
|
|
2199
|
+
}
|
|
2200
|
+
async function signForServer(device, message) {
|
|
2201
|
+
return ecdsaSign(devicePrivate(device).signing, message);
|
|
2202
|
+
}
|
|
2203
|
+
var SEP = new Uint8Array([0]);
|
|
2204
|
+
async function deviceApprovalMessage(memberId, newDeviceId, grant) {
|
|
2205
|
+
return concat(
|
|
2206
|
+
utf8("poolse-notes/v1/approve"),
|
|
2207
|
+
SEP,
|
|
2208
|
+
utf8(memberId),
|
|
2209
|
+
SEP,
|
|
2210
|
+
utf8(newDeviceId),
|
|
2211
|
+
SEP,
|
|
2212
|
+
await sha256(grant)
|
|
2213
|
+
);
|
|
2214
|
+
}
|
|
2215
|
+
async function recoveryReplaceMessage(memberId, keyId2, wrap, auth) {
|
|
2216
|
+
return concat(
|
|
2217
|
+
utf8("poolse-notes/v1/recovery"),
|
|
2218
|
+
SEP,
|
|
2219
|
+
utf8(memberId),
|
|
2220
|
+
SEP,
|
|
2221
|
+
utf8(keyId2),
|
|
2222
|
+
SEP,
|
|
2223
|
+
await sha256(wrap),
|
|
2224
|
+
await sha256(auth)
|
|
2225
|
+
);
|
|
2226
|
+
}
|
|
2227
|
+
async function signedDeviceGrant(grant, options) {
|
|
2228
|
+
const msg = await deviceApprovalMessage(options.memberId, options.newDeviceId, grant);
|
|
2229
|
+
return {
|
|
2230
|
+
grant: toBase64Url(grant),
|
|
2231
|
+
approver_device_id: options.approver.id,
|
|
2232
|
+
signature: toBase64Url(await signForServer(options.approver, msg))
|
|
2233
|
+
};
|
|
2234
|
+
}
|
|
2235
|
+
function noteAsDocument(note, toMarkdown) {
|
|
2236
|
+
const body = typeof note.body === "string" ? note.body : note.body === null ? "" : toMarkdown ? toMarkdown(note.body) : (() => {
|
|
2237
|
+
throw new PoolseCryptoError("malformed", "Pass toMarkdown for a structured body");
|
|
2238
|
+
})();
|
|
2239
|
+
const title = note.title.trim() || "Untitled note";
|
|
2240
|
+
return { title, markdown: `# ${title}
|
|
2241
|
+
|
|
2242
|
+
${body}`.trimEnd() + "\n" };
|
|
2243
|
+
}
|
|
2244
|
+
function checkRevision(revision) {
|
|
2245
|
+
if (!Number.isInteger(revision) || revision < 1) {
|
|
2246
|
+
throw new PoolseCryptoError("malformed", "revision is the revision the write creates (\u2265 1)");
|
|
2247
|
+
}
|
|
2248
|
+
}
|
|
2249
|
+
|
|
2250
|
+
// src/search.ts
|
|
2251
|
+
var MAX_WORD = 40;
|
|
2252
|
+
var MAX_WORDS_PER_NOTE = 5e3;
|
|
2253
|
+
function searchWords(text) {
|
|
2254
|
+
const norm = text.normalize("NFKD").replace(/\p{M}+/gu, "").toLowerCase();
|
|
2255
|
+
const out = [];
|
|
2256
|
+
for (const m of norm.matchAll(/[\p{L}\p{N}]+/gu)) out.push(m[0].slice(0, MAX_WORD));
|
|
2257
|
+
return out;
|
|
2258
|
+
}
|
|
2259
|
+
var NoteSearchIndex = class _NoteSearchIndex {
|
|
2260
|
+
#docs = /* @__PURE__ */ new Map();
|
|
2261
|
+
/** Notes in the index. */
|
|
2262
|
+
get size() {
|
|
2263
|
+
return this.#docs.size;
|
|
2264
|
+
}
|
|
2265
|
+
/** Add or replace a note. */
|
|
2266
|
+
put(id, doc) {
|
|
2267
|
+
const t = unique(searchWords(doc.title));
|
|
2268
|
+
const w = unique([...t, ...searchWords(doc.text)]).slice(0, MAX_WORDS_PER_NOTE);
|
|
2269
|
+
const u = typeof doc.updatedAt === "number" ? doc.updatedAt : doc.updatedAt ? Date.parse(doc.updatedAt) || 0 : 0;
|
|
2270
|
+
this.#docs.set(id, { t, w, u });
|
|
2271
|
+
}
|
|
2272
|
+
remove(id) {
|
|
2273
|
+
this.#docs.delete(id);
|
|
2274
|
+
}
|
|
2275
|
+
has(id) {
|
|
2276
|
+
return this.#docs.has(id);
|
|
2277
|
+
}
|
|
2278
|
+
clear() {
|
|
2279
|
+
this.#docs.clear();
|
|
2280
|
+
}
|
|
2281
|
+
/** Note ids matching every word of `query`, best first. Empty query → nothing. */
|
|
2282
|
+
search(query, limit = 50) {
|
|
2283
|
+
const words = unique(searchWords(query));
|
|
2284
|
+
if (words.length === 0) return [];
|
|
2285
|
+
const hits = [];
|
|
2286
|
+
for (const [id, doc] of this.#docs) {
|
|
2287
|
+
let score = 0;
|
|
2288
|
+
let all = true;
|
|
2289
|
+
for (const q of words) {
|
|
2290
|
+
let best = 0;
|
|
2291
|
+
for (const w of doc.w) {
|
|
2292
|
+
if (w === q) {
|
|
2293
|
+
best = 2;
|
|
2294
|
+
break;
|
|
2295
|
+
}
|
|
2296
|
+
if (w.startsWith(q)) best = 1;
|
|
2297
|
+
}
|
|
2298
|
+
if (best === 0) {
|
|
2299
|
+
all = false;
|
|
2300
|
+
break;
|
|
2301
|
+
}
|
|
2302
|
+
score += best;
|
|
2303
|
+
if (doc.t.some((w) => w.startsWith(q))) score += 3;
|
|
2304
|
+
}
|
|
2305
|
+
if (all) hits.push({ id, score, u: doc.u });
|
|
2306
|
+
}
|
|
2307
|
+
hits.sort((a, b) => b.score - a.score || b.u - a.u || a.id.localeCompare(b.id));
|
|
2308
|
+
return hits.slice(0, limit).map(({ id, score }) => ({ id, score }));
|
|
2309
|
+
}
|
|
2310
|
+
/** The index encrypted for this device's storage. `name` keeps several indexes apart. */
|
|
2311
|
+
async seal(accountKey, name = "notes") {
|
|
2312
|
+
const docs = {};
|
|
2313
|
+
for (const [id, d] of this.#docs) docs[id] = d;
|
|
2314
|
+
const key = await indexKey(accountKey);
|
|
2315
|
+
return encryptBytes(key, utf8(JSON.stringify({ v: 1, docs })), ad(name));
|
|
2316
|
+
}
|
|
2317
|
+
static async open(sealed, accountKey, name = "notes") {
|
|
2318
|
+
const key = await indexKey(accountKey);
|
|
2319
|
+
const raw = fromUtf8(await decryptBytes(key, sealed, ad(name)));
|
|
2320
|
+
let parsed;
|
|
2321
|
+
try {
|
|
2322
|
+
parsed = JSON.parse(raw);
|
|
2323
|
+
} catch {
|
|
2324
|
+
throw new PoolseCryptoError("malformed", "Search index is not JSON");
|
|
2325
|
+
}
|
|
2326
|
+
const p = parsed;
|
|
2327
|
+
if (p.v !== 1 || !p.docs || typeof p.docs !== "object") {
|
|
2328
|
+
throw new PoolseCryptoError("unsupported", "Unknown search index version");
|
|
2329
|
+
}
|
|
2330
|
+
const index = new _NoteSearchIndex();
|
|
2331
|
+
for (const [id, d] of Object.entries(p.docs)) {
|
|
2332
|
+
if (Array.isArray(d.t) && Array.isArray(d.w)) {
|
|
2333
|
+
index.#docs.set(id, { t: d.t, w: d.w, u: typeof d.u === "number" ? d.u : 0 });
|
|
2334
|
+
}
|
|
2335
|
+
}
|
|
2336
|
+
return index;
|
|
2337
|
+
}
|
|
2338
|
+
};
|
|
2339
|
+
function ad(name) {
|
|
2340
|
+
return { itemId: "search-index", slot: name };
|
|
2341
|
+
}
|
|
2342
|
+
async function indexKey(accountKey) {
|
|
2343
|
+
const raw = await hkdf(
|
|
2344
|
+
secretOf(accountKey),
|
|
2345
|
+
new Uint8Array(0),
|
|
2346
|
+
label(DOMAIN, "key/search-index")
|
|
2347
|
+
);
|
|
2348
|
+
return ItemKey.fromBytes(raw, 1);
|
|
2349
|
+
}
|
|
2350
|
+
function unique(words) {
|
|
2351
|
+
return [...new Set(words)];
|
|
2352
|
+
}
|
|
2353
|
+
|
|
2354
|
+
// src/outbox.ts
|
|
2355
|
+
var NoteOutbox = class _NoteOutbox {
|
|
2356
|
+
#entries;
|
|
2357
|
+
#storage;
|
|
2358
|
+
#key;
|
|
2359
|
+
#flushing = null;
|
|
2360
|
+
constructor(entries, storage, key) {
|
|
2361
|
+
this.#entries = entries;
|
|
2362
|
+
this.#storage = storage;
|
|
2363
|
+
this.#key = key;
|
|
2364
|
+
}
|
|
2365
|
+
static async load(options) {
|
|
2366
|
+
const key = await outboxKey(options.accountKey);
|
|
2367
|
+
const sealed = await options.storage.read();
|
|
2368
|
+
let entries = [];
|
|
2369
|
+
if (sealed && sealed.length > 0) {
|
|
2370
|
+
const text = fromUtf8(await decryptBytes(key, sealed, AD));
|
|
2371
|
+
const parsed = JSON.parse(text);
|
|
2372
|
+
if (parsed.v !== 1 || !Array.isArray(parsed.entries)) {
|
|
2373
|
+
throw new PoolseCryptoError("unsupported", "Unknown outbox version");
|
|
2374
|
+
}
|
|
2375
|
+
entries = parsed.entries;
|
|
2376
|
+
}
|
|
2377
|
+
return new _NoteOutbox(entries, options.storage, key);
|
|
2378
|
+
}
|
|
2379
|
+
/** Waiting writes, oldest first. */
|
|
2380
|
+
get entries() {
|
|
2381
|
+
return this.#entries;
|
|
2382
|
+
}
|
|
2383
|
+
/** Whether a note has unsent edits (show "Not synced yet"). */
|
|
2384
|
+
isPending(noteId) {
|
|
2385
|
+
return this.#entries.some((e) => e.noteId === noteId);
|
|
2386
|
+
}
|
|
2387
|
+
/** Queue an edit (or a new note, `baseRevision` 0). Replaces an earlier queued edit of the note. */
|
|
2388
|
+
async put(noteId, baseRevision, data) {
|
|
2389
|
+
this.#enqueue(noteId, "put", baseRevision, data);
|
|
2390
|
+
await this.#save();
|
|
2391
|
+
}
|
|
2392
|
+
/** Queue a delete. A note made offline and never sent is just forgotten. */
|
|
2393
|
+
async delete(noteId, baseRevision) {
|
|
2394
|
+
const prior = this.#entries.find((e) => e.noteId === noteId);
|
|
2395
|
+
if (prior && prior.baseRevision === 0) {
|
|
2396
|
+
this.#entries = this.#entries.filter((e) => e.noteId !== noteId);
|
|
2397
|
+
} else {
|
|
2398
|
+
this.#enqueue(noteId, "delete", baseRevision, null);
|
|
2399
|
+
}
|
|
2400
|
+
await this.#save();
|
|
2401
|
+
}
|
|
2402
|
+
/** Send everything, in order. Concurrent calls share one run. */
|
|
2403
|
+
flush(options) {
|
|
2404
|
+
this.#flushing ??= this.#flush(options).finally(() => {
|
|
2405
|
+
this.#flushing = null;
|
|
2406
|
+
});
|
|
2407
|
+
return this.#flushing;
|
|
2408
|
+
}
|
|
2409
|
+
async #flush(options) {
|
|
2410
|
+
const result = { written: [], dropped: [], pending: 0 };
|
|
2411
|
+
const maxConflicts = options.maxConflicts ?? 3;
|
|
2412
|
+
while (this.#entries.length > 0) {
|
|
2413
|
+
const entry = this.#entries[0];
|
|
2414
|
+
let conflicts = 0;
|
|
2415
|
+
let current = entry;
|
|
2416
|
+
let done = false;
|
|
2417
|
+
while (!done) {
|
|
2418
|
+
let res;
|
|
2419
|
+
try {
|
|
2420
|
+
res = await options.send(current);
|
|
2421
|
+
} catch (error) {
|
|
2422
|
+
current.attempts += 1;
|
|
2423
|
+
await this.#save();
|
|
2424
|
+
result.pending = this.#entries.length;
|
|
2425
|
+
result.error = error;
|
|
2426
|
+
return result;
|
|
2427
|
+
}
|
|
2428
|
+
if (res.status === "ok") {
|
|
2429
|
+
result.written.push(current.noteId);
|
|
2430
|
+
options.onWritten?.(current.noteId, res.revision);
|
|
2431
|
+
done = true;
|
|
2432
|
+
} else if (res.status === "gone") {
|
|
2433
|
+
result.dropped.push(current.noteId);
|
|
2434
|
+
done = true;
|
|
2435
|
+
} else {
|
|
2436
|
+
conflicts += 1;
|
|
2437
|
+
const merged = current.op === "delete" ? null : options.resolve ? await options.resolve(current.data, res.current, current) : current.data;
|
|
2438
|
+
if (conflicts > maxConflicts || current.op === "put" && merged === null) {
|
|
2439
|
+
result.dropped.push(current.noteId);
|
|
2440
|
+
done = true;
|
|
2441
|
+
} else {
|
|
2442
|
+
current = { ...current, baseRevision: res.revision, data: merged };
|
|
2443
|
+
this.#entries[0] = current;
|
|
2444
|
+
}
|
|
2445
|
+
}
|
|
2446
|
+
}
|
|
2447
|
+
this.#entries.shift();
|
|
2448
|
+
await this.#save();
|
|
2449
|
+
}
|
|
2450
|
+
return result;
|
|
2451
|
+
}
|
|
2452
|
+
#enqueue(noteId, op, baseRevision, data) {
|
|
2453
|
+
const i = this.#entries.findIndex((e) => e.noteId === noteId);
|
|
2454
|
+
if (i !== -1) {
|
|
2455
|
+
const prior = this.#entries[i];
|
|
2456
|
+
this.#entries[i] = { ...prior, op, data, queuedAt: Date.now() };
|
|
2457
|
+
return;
|
|
2458
|
+
}
|
|
2459
|
+
this.#entries.push({ noteId, op, baseRevision, data, queuedAt: Date.now(), attempts: 0 });
|
|
2460
|
+
}
|
|
2461
|
+
async #save() {
|
|
2462
|
+
const text = JSON.stringify({ v: 1, entries: this.#entries });
|
|
2463
|
+
await this.#storage.write(await encryptBytes(this.#key, utf8(text), AD));
|
|
2464
|
+
}
|
|
2465
|
+
};
|
|
2466
|
+
var AD = { itemId: "notes-outbox" };
|
|
2467
|
+
async function outboxKey(accountKey) {
|
|
2468
|
+
const raw = await hkdf(
|
|
2469
|
+
secretOf(accountKey),
|
|
2470
|
+
new Uint8Array(0),
|
|
2471
|
+
label(DOMAIN, "key/notes-outbox")
|
|
2472
|
+
);
|
|
2473
|
+
return ItemKey.fromBytes(raw, 1);
|
|
2474
|
+
}
|
|
2475
|
+
var MemoryOutboxStorage = class {
|
|
2476
|
+
data = null;
|
|
2477
|
+
async read() {
|
|
2478
|
+
return this.data;
|
|
2479
|
+
}
|
|
2480
|
+
async write(data) {
|
|
2481
|
+
this.data = data;
|
|
2482
|
+
}
|
|
2483
|
+
};
|
|
2484
|
+
|
|
2485
|
+
export { ATTACHMENT_HEADER_LENGTH, AccountKey, Alg, BlobConflictError, BlobTransportError, DEFAULT_CHUNK_SIZE, DEFAULT_REQUEST_MAX_AGE_MS, DeviceKeys, EncryptedBlobStore, FORMAT_VERSION, ItemKey, Kind, MAX_CHUNK_SIZE, MIN_CHUNK_SIZE, MemoryBlobTransport, MemoryOutboxStorage, NoteOutbox, NoteSearchIndex, PoolseCryptoError, RecoveryKey, WrapPurpose, acceptDeviceGrant, approveDeviceRequest, checkCryptoSupport, constantTimeEqual, createDeviceRequest, createHttpBlobTransport, decodeDevicePublicKeys, decryptAttachment, decryptAttachmentBytes, decryptBytes, decryptItem, deviceApprovalMessage, deviceFingerprint, devicePublicKeys, encodeAssociatedData, encodeDevicePublicKeys, encryptAttachment, encryptAttachmentBytes, encryptBytes, encryptItem, encryptedAttachmentSize, envelopeKeyVersion, folderAssociatedData, fromBase32, fromBase64Url, fromHex, generateRecoveryKey, inspectEnvelope, isValidBlobKey, noteAsDocument, noteAssociatedData, noteAttachmentAssociatedData, noteKeyForVersion, openFolderName, openNoteContent, openNoteMeta, openSharedItemKey, padmeLength, parseRecoveryKey, readDeviceRequest, recoveryAuth, recoveryReplaceMessage, rotateItemKey, rotateNoteKey, sameDevice, sealFolder, sealNote, searchWords, shareExpired, shareItemKey, shareItemKeyWithDevices, shareWrapsFor, signForServer, signedDeviceGrant, toBase32, toBase64Url, toHex, unwrapAccountKeyForDevice, unwrapAccountKeyWithRecoveryKey, unwrapItemKey, unwrapPreviousItemKey, wrapAccountKeyForDevice, wrapAccountKeyWithRecoveryKey, wrapItemKey, wrapPreviousItemKey };
|
|
2486
|
+
//# sourceMappingURL=index.js.map
|
|
2487
|
+
//# sourceMappingURL=index.js.map
|