phantomdisk 0.0.0-stage → 0.1.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/dist/index.js ADDED
@@ -0,0 +1,865 @@
1
+ // ../shared/src/bytes.ts
2
+ var utf8 = (s) => new TextEncoder().encode(s);
3
+ var hex = (b) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
4
+ function b64(b) {
5
+ let s = "";
6
+ for (let i = 0; i < b.length; i += 32768) s += String.fromCharCode(...b.subarray(i, i + 32768));
7
+ return btoa(s);
8
+ }
9
+ function fromB64(s) {
10
+ let bin;
11
+ try {
12
+ bin = atob(s);
13
+ } catch {
14
+ throw new FormatError("bad base64");
15
+ }
16
+ return Uint8Array.from(bin, (c) => c.charCodeAt(0));
17
+ }
18
+ var b64url = (b) => b64(b).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
19
+ function fromB64url(s) {
20
+ if (/[+/=]/.test(s)) throw new FormatError("bad base64url");
21
+ return fromB64(s.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - s.length % 4) % 4));
22
+ }
23
+ function concat(...parts2) {
24
+ const out = new Uint8Array(parts2.reduce((n, p) => n + p.length, 0));
25
+ let at = 0;
26
+ for (const p of parts2) {
27
+ out.set(p, at);
28
+ at += p.length;
29
+ }
30
+ return out;
31
+ }
32
+ var sha256 = async (b) => new Uint8Array(await crypto.subtle.digest("SHA-256", b));
33
+ var sha256Hex = async (b) => hex(await sha256(b));
34
+ var randomBytes = (n) => crypto.getRandomValues(new Uint8Array(n));
35
+ var FormatError = class extends Error {
36
+ name = "FormatError";
37
+ };
38
+
39
+ // ../shared/src/format.ts
40
+ var FORMAT_VERSION = 1;
41
+ var PIECE_SIZE = 8 * 1024 * 1024;
42
+ var BLOCK_SIZE = 128 * 1024;
43
+ var TAG_SIZE = 16;
44
+ var STORED_BLOCK_SIZE = BLOCK_SIZE + TAG_SIZE;
45
+ var Layout = class {
46
+ constructor(plaintextSize, encrypted) {
47
+ this.plaintextSize = plaintextSize;
48
+ this.encrypted = encrypted;
49
+ if (!Number.isSafeInteger(plaintextSize) || plaintextSize < 0) throw new RangeError("bad size");
50
+ }
51
+ plaintextSize;
52
+ encrypted;
53
+ get pieceCount() {
54
+ return Math.ceil(this.plaintextSize / PIECE_SIZE);
55
+ }
56
+ plaintextLength(piece) {
57
+ return Math.min(PIECE_SIZE, this.plaintextSize - piece * PIECE_SIZE);
58
+ }
59
+ blockCount(piece) {
60
+ return Math.ceil(this.plaintextLength(piece) / BLOCK_SIZE);
61
+ }
62
+ blockLength(piece, block) {
63
+ return Math.min(BLOCK_SIZE, this.plaintextLength(piece) - block * BLOCK_SIZE);
64
+ }
65
+ storedLength(piece) {
66
+ return this.plaintextLength(piece) + (this.encrypted ? this.blockCount(piece) * TAG_SIZE : 0);
67
+ }
68
+ isFinalBlock(piece, block) {
69
+ return piece === this.pieceCount - 1 && block === this.blockCount(piece) - 1;
70
+ }
71
+ /** The per-piece fetches for plaintext [start, end), clamped to the file. */
72
+ reads(start, end) {
73
+ const lo0 = Math.max(0, Math.min(start, this.plaintextSize));
74
+ const hi0 = Math.max(lo0, Math.min(end, this.plaintextSize));
75
+ if (lo0 === hi0) return [];
76
+ const stored = this.encrypted ? STORED_BLOCK_SIZE : BLOCK_SIZE;
77
+ const out = [];
78
+ for (let piece = Math.floor(lo0 / PIECE_SIZE); piece <= Math.floor((hi0 - 1) / PIECE_SIZE); piece++) {
79
+ const base = piece * PIECE_SIZE;
80
+ const lo = Math.max(lo0, base) - base;
81
+ const hi = Math.min(hi0, base + this.plaintextLength(piece)) - base;
82
+ const first = Math.floor(lo / BLOCK_SIZE);
83
+ const last = Math.floor((hi - 1) / BLOCK_SIZE);
84
+ out.push({
85
+ piece,
86
+ blockStart: first,
87
+ blockEnd: last + 1,
88
+ storedStart: first * stored,
89
+ storedEnd: last * stored + this.blockLength(piece, last) + (this.encrypted ? TAG_SIZE : 0),
90
+ sliceStart: lo - first * BLOCK_SIZE,
91
+ sliceEnd: hi - first * BLOCK_SIZE
92
+ });
93
+ }
94
+ return out;
95
+ }
96
+ };
97
+ function uuidv7() {
98
+ const b = randomBytes(16);
99
+ const t = Date.now();
100
+ for (let i = 0; i < 6; i++) b[i] = Math.floor(t / 2 ** (8 * (5 - i))) & 255;
101
+ b[6] = b[6] & 15 | 112;
102
+ b[8] = b[8] & 63 | 128;
103
+ const h = hex(b);
104
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
105
+ }
106
+
107
+ // ../shared/src/crypto.ts
108
+ var subtle = () => crypto.subtle;
109
+ var aesKey = (raw) => subtle().importKey("raw", raw, "AES-GCM", false, ["encrypt", "decrypt"]);
110
+ function be32(n) {
111
+ const b = new Uint8Array(4);
112
+ new DataView(b.buffer).setUint32(0, n);
113
+ return b;
114
+ }
115
+ async function gcmSeal(key, nonce, plain, aad) {
116
+ return new Uint8Array(await subtle().encrypt({ name: "AES-GCM", iv: nonce, ...aad ? { additionalData: aad } : {} }, key, plain));
117
+ }
118
+ async function gcmOpen(key, nonce, sealed, aad) {
119
+ try {
120
+ return new Uint8Array(await subtle().decrypt({ name: "AES-GCM", iv: nonce, ...aad ? { additionalData: aad } : {} }, key, sealed));
121
+ } catch {
122
+ throw new FormatError("decryption failed");
123
+ }
124
+ }
125
+ async function hkdf(ikm, info) {
126
+ const key = await subtle().importKey("raw", ikm, "HKDF", false, ["deriveBits"]);
127
+ return new Uint8Array(await subtle().deriveBits({ name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info }, key, 256));
128
+ }
129
+ var blockNonce = (piece, block) => concat(be32(piece), be32(block), new Uint8Array(4));
130
+ var BlockCipher = class _BlockCipher {
131
+ constructor(key, versionId) {
132
+ this.key = key;
133
+ this.versionId = versionId;
134
+ }
135
+ key;
136
+ versionId;
137
+ static async create(fileKey, versionId) {
138
+ if (versionId.length !== 36 || /[^\x00-\x7f]/.test(versionId)) throw new FormatError("bad versionId");
139
+ return new _BlockCipher(await aesKey(fileKey), utf8(versionId));
140
+ }
141
+ aad(piece, block, final) {
142
+ return concat(this.versionId, be32(piece), be32(block), Uint8Array.of(final ? 1 : 0));
143
+ }
144
+ /** `ciphertext || tag`. */
145
+ sealBlock(plain, piece, block, final) {
146
+ return gcmSeal(this.key, blockNonce(piece, block), plain, this.aad(piece, block, final));
147
+ }
148
+ /** Throws if the block was altered, moved, swapped or its final flag is wrong. */
149
+ openBlock(stored, piece, block, final) {
150
+ if (stored.length < TAG_SIZE) throw new FormatError("short block");
151
+ return gcmOpen(this.key, blockNonce(piece, block), stored, this.aad(piece, block, final));
152
+ }
153
+ async sealPiece(plain, piece, layout) {
154
+ if (!layout.encrypted || piece >= layout.pieceCount || plain.length !== layout.plaintextLength(piece)) throw new FormatError("bad piece");
155
+ const parts2 = [];
156
+ for (let b = 0; b < layout.blockCount(piece); b++)
157
+ parts2.push(await this.sealBlock(plain.subarray(b * BLOCK_SIZE, b * BLOCK_SIZE + layout.blockLength(piece, b)), piece, b, layout.isFinalBlock(piece, b)));
158
+ return concat(...parts2);
159
+ }
160
+ /** Opens a whole stored piece; a wrong length counts as truncation. */
161
+ async openPiece(stored, piece, layout) {
162
+ if (!layout.encrypted || piece >= layout.pieceCount || stored.length !== layout.storedLength(piece)) throw new FormatError("bad piece");
163
+ return this.openBlocks(stored, piece, 0, layout.blockCount(piece), layout);
164
+ }
165
+ /** Opens blocks [first, end) of a piece from their stored bytes (a PieceRead's stored range). */
166
+ async openBlocks(stored, piece, first, end, layout) {
167
+ const parts2 = [];
168
+ for (let b = first; b < end; b++) {
169
+ const at = (b - first) * STORED_BLOCK_SIZE;
170
+ parts2.push(await this.openBlock(stored.subarray(at, at + layout.blockLength(piece, b) + TAG_SIZE), piece, b, layout.isFinalBlock(piece, b)));
171
+ }
172
+ return concat(...parts2);
173
+ }
174
+ };
175
+ var generateKey = () => randomBytes(32);
176
+ async function wrapKey(key, wrappingKey, nonce = randomBytes(12)) {
177
+ return concat(nonce, await gcmSeal(await aesKey(wrappingKey), nonce, key));
178
+ }
179
+ async function unwrapKey(wrapped, wrappingKey) {
180
+ if (wrapped.length < 12 + TAG_SIZE) throw new FormatError("short wrapped key");
181
+ const raw = await gcmOpen(await aesKey(wrappingKey), wrapped.subarray(0, 12), wrapped.subarray(12));
182
+ if (raw.length !== 32) throw new FormatError("bad key length");
183
+ return raw;
184
+ }
185
+ var wrapFileKey = async (fileKey, masterKey, nonce) => b64(await wrapKey(fileKey, masterKey, nonce));
186
+ var unwrapFileKey = (wrappedB64, masterKey) => unwrapKey(fromB64(wrappedB64), masterKey);
187
+ var nameKey = (masterKey) => hkdf(masterKey, utf8("phantomdrive/names/v1"));
188
+ var NAMES_V2_PREFIX = "2.";
189
+ function nameAad(nodeId) {
190
+ if (!/^[0-9a-f-]{36}$/.test(nodeId)) throw new FormatError("bad nodeId");
191
+ return utf8(`phantomdrive/names/v2${nodeId}`);
192
+ }
193
+ async function sealName(nameKeyRaw, name, nodeId, nonce = randomBytes(12)) {
194
+ return NAMES_V2_PREFIX + b64url(concat(nonce, await gcmSeal(await aesKey(nameKeyRaw), nonce, utf8(name.normalize("NFC")), nameAad(nodeId))));
195
+ }
196
+ async function openName(nameKeyRaw, sealed, nodeId, v1Allowed = true) {
197
+ const v2 = sealed.startsWith(NAMES_V2_PREFIX);
198
+ if (!v2 && !v1Allowed) throw new FormatError("v1 name refused");
199
+ const data = fromB64url(v2 ? sealed.slice(NAMES_V2_PREFIX.length) : sealed);
200
+ if (data.length < 28) throw new FormatError("short name");
201
+ const raw = await gcmOpen(await aesKey(nameKeyRaw), data.subarray(0, 12), data.subarray(12), v2 ? nameAad(nodeId) : void 0);
202
+ try {
203
+ return new TextDecoder("utf-8", { fatal: true }).decode(raw);
204
+ } catch {
205
+ throw new FormatError("bad name");
206
+ }
207
+ }
208
+
209
+ // ../shared/src/manifest.ts
210
+ var newManifest = (versionId, plaintextSize, pieceHashes, wrappedFileKey) => ({
211
+ formatVersion: FORMAT_VERSION,
212
+ versionId,
213
+ plaintextSize,
214
+ pieceSize: PIECE_SIZE,
215
+ blockSize: BLOCK_SIZE,
216
+ encrypted: wrappedFileKey !== void 0,
217
+ pieceHashes,
218
+ ...wrappedFileKey === void 0 ? {} : { wrappedFileKey }
219
+ });
220
+ function manifestJson(m) {
221
+ const { blockSize, encrypted, formatVersion, pieceHashes, pieceSize, plaintextSize, versionId, wrappedFileKey } = m;
222
+ return JSON.stringify({ blockSize, encrypted, formatVersion, pieceHashes, pieceSize, plaintextSize, versionId, wrappedFileKey });
223
+ }
224
+ async function pipe(bytes, stream, limit = Infinity) {
225
+ const reader = new Blob([bytes]).stream().pipeThrough(stream).getReader();
226
+ const parts2 = [];
227
+ let total = 0;
228
+ for (; ; ) {
229
+ const { done, value } = await reader.read();
230
+ if (done) break;
231
+ total += value.byteLength;
232
+ if (total > limit) {
233
+ await reader.cancel();
234
+ throw new FormatError("manifest too large");
235
+ }
236
+ parts2.push(value);
237
+ }
238
+ const out = new Uint8Array(total);
239
+ let at = 0;
240
+ for (const p of parts2) out.set(p, (at += p.byteLength) - p.byteLength);
241
+ return out;
242
+ }
243
+ var encodeManifest = (m) => pipe(utf8(manifestJson(m)), new CompressionStream("gzip"));
244
+ var manifestHash = (stored) => sha256Hex(stored);
245
+ async function decodeManifest(stored) {
246
+ let m;
247
+ try {
248
+ m = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(await pipe(stored, new DecompressionStream("gzip"), 64 << 20)));
249
+ } catch (e) {
250
+ throw e instanceof FormatError ? e : new FormatError("corrupt manifest");
251
+ }
252
+ if (m?.formatVersion !== FORMAT_VERSION) throw new FormatError(`unsupported manifest version ${m?.formatVersion}`);
253
+ const ok = m.pieceSize === PIECE_SIZE && m.blockSize === BLOCK_SIZE && Number.isSafeInteger(m.plaintextSize) && m.plaintextSize >= 0 && typeof m.versionId === "string" && m.versionId.length === 36 && typeof m.encrypted === "boolean" && Array.isArray(m.pieceHashes) && m.pieceHashes.every((h) => typeof h === "string" && /^[0-9a-f]{64}$/.test(h)) && m.pieceHashes.length === new Layout(m.plaintextSize, m.encrypted).pieceCount && m.encrypted === (typeof m.wrappedFileKey === "string");
254
+ if (!ok) throw new FormatError("corrupt manifest");
255
+ return m;
256
+ }
257
+
258
+ // ../shared/src/md5.ts
259
+ var S = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21];
260
+ var K = Array.from({ length: 64 }, (_, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 2 ** 32) >>> 0);
261
+ function md5Hex(data) {
262
+ const n = data.length;
263
+ const padded = new Uint8Array((n + 8 >> 6) + 1 << 6);
264
+ padded.set(data);
265
+ padded[n] = 128;
266
+ const view = new DataView(padded.buffer);
267
+ view.setUint32(padded.length - 8, n * 8 >>> 0, true);
268
+ view.setUint32(padded.length - 4, Math.floor(n / 2 ** 29), true);
269
+ let a0 = 1732584193, b0 = 4023233417, c0 = 2562383102, d0 = 271733878;
270
+ const m = new Uint32Array(16);
271
+ for (let off = 0; off < padded.length; off += 64) {
272
+ for (let j = 0; j < 16; j++) m[j] = view.getUint32(off + j * 4, true);
273
+ let a = a0, b = b0, c = c0, d = d0;
274
+ for (let i = 0; i < 64; i++) {
275
+ const r = i >> 4;
276
+ const f = r === 0 ? b & c | ~b & d : r === 1 ? d & b | ~d & c : r === 2 ? b ^ c ^ d : c ^ (b | ~d);
277
+ const g = r === 0 ? i : r === 1 ? 5 * i + 1 & 15 : r === 2 ? 3 * i + 5 & 15 : 7 * i & 15;
278
+ const t = a + f + K[i] + m[g] | 0;
279
+ const s = S[r << 2 | i & 3];
280
+ a = d;
281
+ d = c;
282
+ c = b;
283
+ b = b + (t << s | t >>> 32 - s) | 0;
284
+ }
285
+ a0 = a0 + a | 0;
286
+ b0 = b0 + b | 0;
287
+ c0 = c0 + c | 0;
288
+ d0 = d0 + d | 0;
289
+ }
290
+ const out = new Uint8Array(16);
291
+ const ov = new DataView(out.buffer);
292
+ [a0, b0, c0, d0].forEach((w, i) => ov.setUint32(i * 4, w >>> 0, true));
293
+ return hex(out);
294
+ }
295
+
296
+ // ../shared/src/transfer.ts
297
+ var StaleUploadError = class extends Error {
298
+ name = "StaleUploadError";
299
+ };
300
+ var BATCH = 100;
301
+ var URL_FRESH_MS = 5 * 6e4;
302
+ var READ_FRESH_MS = 50 * 6e4;
303
+ function urlCache(fetchBatch, total, freshMs, first) {
304
+ const batches = /* @__PURE__ */ new Map();
305
+ const keep = (start, p, known) => {
306
+ const at = Date.now();
307
+ const e = { until: at + freshMs, p };
308
+ const shorten = (b) => void (b.expiresIn !== void 0 && (e.until = Math.min(e.until, at + b.expiresIn * 800)));
309
+ batches.set(start, e);
310
+ if (known) shorten(known);
311
+ else p.then(shorten, () => batches.delete(start));
312
+ return p;
313
+ };
314
+ if (first) keep(0, Promise.resolve(first), first);
315
+ const get = (start) => {
316
+ const hit = batches.get(start);
317
+ if (hit && Date.now() < hit.until) return hit.p;
318
+ return keep(start, fetchBatch(start, Math.max(1, Math.min(BATCH, total - start))));
319
+ };
320
+ return {
321
+ async piece(i) {
322
+ const b = await get(Math.floor(i / BATCH) * BATCH);
323
+ const e = b.pieceUrls.find((u) => u.index === i);
324
+ if (!e) throw new Error(`no URL for piece ${i}`);
325
+ return e.url;
326
+ }
327
+ };
328
+ }
329
+ var sleep = (ms, signal) => new Promise((resolve, reject) => {
330
+ const t = setTimeout(resolve, ms);
331
+ signal?.addEventListener("abort", () => (clearTimeout(t), reject(signal.reason)), { once: true });
332
+ });
333
+ async function retry(fn, signal, attempts = 5, baseMs = 500) {
334
+ for (let n = 1; ; n++) {
335
+ try {
336
+ return await fn();
337
+ } catch (e) {
338
+ if (signal?.aborted || n >= attempts) throw e;
339
+ await sleep(baseMs * 2 ** (n - 1), signal);
340
+ }
341
+ }
342
+ }
343
+ async function pool(count, parallel, work) {
344
+ let next = 0;
345
+ let failed = false;
346
+ await Promise.all(
347
+ Array.from({ length: Math.min(parallel, count) }, async () => {
348
+ while (!failed && next < count) {
349
+ const i = next++;
350
+ try {
351
+ await work(i);
352
+ } catch (e) {
353
+ failed = true;
354
+ throw e;
355
+ }
356
+ }
357
+ })
358
+ );
359
+ }
360
+ async function storedPiece(src, layout, piece, cipher) {
361
+ const start = piece * PIECE_SIZE;
362
+ const plain = new Uint8Array(await src.slice(start, start + layout.plaintextLength(piece)).arrayBuffer());
363
+ if (plain.length !== layout.plaintextLength(piece)) throw new FormatError("the file changed while uploading");
364
+ return cipher ? cipher.sealPiece(plain, piece, layout) : plain;
365
+ }
366
+ async function uploadVersion(src, opts, target) {
367
+ const layout = new Layout(src.size, !!opts.encryption);
368
+ const cipher = opts.encryption ? await BlockCipher.create(opts.encryption.fileKey, opts.versionId) : void 0;
369
+ const urls = urlCache((f, c) => target.urls(f, c), layout.pieceCount, URL_FRESH_MS, opts.first);
370
+ const hashes = new Array(layout.pieceCount);
371
+ const sent = new Array(layout.pieceCount).fill(0);
372
+ const report = () => opts.onProgress?.(sent.reduce((a, b) => a + b, 0), src.size);
373
+ const have = new Map(opts.resume && target.objects ? (await target.objects()).map((o) => [o.key, o.etag]) : []);
374
+ const sameAsStored = (key, body) => {
375
+ const etag = have.get(key);
376
+ if (etag === void 0) return false;
377
+ if (etag !== md5Hex(body)) throw new StaleUploadError("the upload already holds different bytes");
378
+ return true;
379
+ };
380
+ const send = async (indexes, alreadyStored = false) => pool(indexes.length, opts.parallel ?? 4, async (k) => {
381
+ opts.signal?.throwIfAborted();
382
+ const i = indexes[k];
383
+ const body = await storedPiece(src, layout, i, cipher);
384
+ const h = await sha256Hex(body);
385
+ if (hashes[i] !== void 0 && hashes[i] !== h) throw new FormatError("the file changed while uploading");
386
+ hashes[i] = h;
387
+ if (!(alreadyStored && sameAsStored(`p/${String(i).padStart(8, "0")}`, body))) await retry(async () => target.put(await urls.piece(i), body, opts.signal), opts.signal);
388
+ sent[i] = layout.plaintextLength(i);
389
+ report();
390
+ });
391
+ const all = Array.from({ length: layout.pieceCount }, (_, i) => i);
392
+ const isStored = (i) => have.has(`p/${String(i).padStart(8, "0")}`);
393
+ await send(all.filter(isStored), true);
394
+ await send(all.filter((i) => !isStored(i)));
395
+ const manifest = newManifest(opts.versionId, src.size, hashes, opts.encryption?.wrappedFileKey);
396
+ const stored = await encodeManifest(manifest);
397
+ const hash = await manifestHash(stored);
398
+ const manifestStored = sameAsStored("manifest", stored);
399
+ for (let round = 0; ; round++) {
400
+ if (!manifestStored || round > 0) await retry(async () => target.put(await target.manifestUrl(stored.length), stored, opts.signal), opts.signal);
401
+ const missing = await target.complete(hash);
402
+ if (missing === null) return { manifest, manifestHash: hash };
403
+ if (round >= 3 || missing.some((i) => !(i >= 0 && i < layout.pieceCount))) throw new Error("the server kept reporting missing pieces");
404
+ for (const i of missing) sent[i] = 0;
405
+ await send(missing);
406
+ }
407
+ }
408
+ async function fileKeyOf(m, keys) {
409
+ if (keys.fileKey) return keys.fileKey;
410
+ if (!keys.masterKey || !m.wrappedFileKey) throw new FormatError("this file is encrypted and the key is not unlocked");
411
+ return unwrapFileKey(m.wrappedFileKey, keys.masterKey);
412
+ }
413
+ async function fetchManifest(src, first, signal) {
414
+ const want = src.versionId ?? first.versionId;
415
+ if (first.versionId !== want) throw new FormatError("the server answered for another version");
416
+ const stored = await retry(() => src.get(first.manifestUrl, signal), signal, 3);
417
+ if (await manifestHash(stored) !== first.manifestHash) throw new FormatError("the manifest does not match the file tree");
418
+ const m = await decodeManifest(stored);
419
+ if (m.versionId !== want) throw new FormatError("the manifest is for another version");
420
+ if (m.plaintextSize !== first.size) throw new FormatError("the manifest does not match the file tree");
421
+ return m;
422
+ }
423
+ async function downloadVersion(src, keys, sink, opts = {}) {
424
+ const first = await src.readUrls(0, BATCH);
425
+ const m = await fetchManifest(src, first, opts.signal);
426
+ const layout = new Layout(m.plaintextSize, m.encrypted);
427
+ const cipher = m.encrypted ? await BlockCipher.create(await fileKeyOf(m, keys), m.versionId) : void 0;
428
+ const urls = urlCache((f, c) => src.readUrls(f, c), layout.pieceCount, READ_FRESH_MS, first);
429
+ const fetchPiece = async (i) => {
430
+ const stored = await retry(async () => src.get(await urls.piece(i), opts.signal), opts.signal, 3);
431
+ if (stored.length !== layout.storedLength(i) || await sha256Hex(stored) !== m.pieceHashes[i]) throw new FormatError(`piece ${i} failed verification`);
432
+ return cipher ? cipher.openPiece(stored, i, layout) : stored;
433
+ };
434
+ const ahead = [];
435
+ let done = 0;
436
+ for (let i = 0; i < layout.pieceCount; i++) {
437
+ while (ahead.length < 4 && i + ahead.length < layout.pieceCount) {
438
+ const p = fetchPiece(i + ahead.length);
439
+ p.catch(() => {
440
+ });
441
+ ahead.push(p);
442
+ }
443
+ const plain = await ahead.shift();
444
+ await sink(plain);
445
+ opts.onProgress?.(done += plain.length, m.plaintextSize);
446
+ }
447
+ return m;
448
+ }
449
+
450
+ // src/index.ts
451
+ var DEFAULT_API_URL = "https://api.phantomdisk.com";
452
+ var PhantomDiskError = class extends Error {
453
+ constructor(code, message, status = 0, details) {
454
+ super(message);
455
+ this.code = code;
456
+ this.status = status;
457
+ this.details = details;
458
+ this.name = "PhantomDiskError";
459
+ }
460
+ code;
461
+ status;
462
+ details;
463
+ };
464
+ var env = (name) => typeof process !== "undefined" ? process.env?.[name] : void 0;
465
+ var parts = (path) => path.normalize("NFC").split("/").filter((p) => p !== "" && p !== ".");
466
+ var PhantomDisk = class _PhantomDisk {
467
+ constructor(token, master, nameKeyRaw, apiUrl, doFetch, account, driveId) {
468
+ this.token = token;
469
+ this.master = master;
470
+ this.nameKeyRaw = nameKeyRaw;
471
+ this.apiUrl = apiUrl;
472
+ this.doFetch = doFetch;
473
+ this.account = account;
474
+ this.driveId = driveId;
475
+ }
476
+ token;
477
+ master;
478
+ nameKeyRaw;
479
+ apiUrl;
480
+ doFetch;
481
+ account;
482
+ driveId;
483
+ nodes = /* @__PURE__ */ new Map();
484
+ names = /* @__PURE__ */ new Map();
485
+ cursor = 0;
486
+ /** Connects with an access key and loads the drive's file tree. */
487
+ static async open(opts = {}) {
488
+ const credential = (opts.key ?? env("PHANTOMDISK_KEY") ?? "").trim();
489
+ const dot = credential.indexOf(".");
490
+ const token = dot < 0 ? credential : credential.slice(0, dot);
491
+ if (!/^pdk_[A-Za-z0-9-]+_[A-Za-z0-9_-]+$/.test(token))
492
+ throw new PhantomDiskError("NO_KEY", "Give an access key (pdk_\u2026): pass `key`, or set PHANTOMDISK_KEY. Make one on the Access keys page.");
493
+ const master = dot < 0 ? void 0 : fromB64url(credential.slice(dot + 1));
494
+ if (master && master.length !== 32) throw new PhantomDiskError("BAD_KEY", "The part of the key after the dot is not a 32-byte key.");
495
+ const apiUrl = (opts.apiUrl ?? env("PHANTOMDRIVE_API_URL") ?? DEFAULT_API_URL).replace(/\/+$/, "");
496
+ const doFetch = opts.fetch ?? fetch;
497
+ const probe = new _PhantomDisk(token, master, void 0, apiUrl, doFetch, {}, "");
498
+ const account = await probe.api("GET", "/v1/account");
499
+ if (account.encryption && !master)
500
+ throw new PhantomDiskError("LOCKED", "This account is encrypted. Use the whole key as it was shown when it was made: pdk_\u2026, a dot, then the key.");
501
+ const driveId = opts.drive ?? account.key?.driveIds?.[0] ?? account.accountId;
502
+ const disk = new _PhantomDisk(token, master, master && await nameKey(master), apiUrl, doFetch, account, driveId);
503
+ await disk.refresh();
504
+ return disk;
505
+ }
506
+ /** False for a read-only key, and when the account's plan has ended. */
507
+ get writable() {
508
+ return this.account.writable && this.account.key?.access !== "read";
509
+ }
510
+ get encrypted() {
511
+ return this.account.encryption;
512
+ }
513
+ /* ---------- reading the tree ---------- */
514
+ /** Everything in a folder (the top folder by default), folders first, then by name. */
515
+ async list(path = "") {
516
+ await this.refresh();
517
+ const folder = parts(path).length ? this.need(path, "folder") : null;
518
+ const base = parts(path).join("/");
519
+ return this.children(folder?.id ?? null).map((n) => this.entry(n, base ? `${base}/${this.nameOf(n)}` : this.nameOf(n))).sort((a, b) => a.kind === b.kind ? a.name.localeCompare(b.name) : a.kind === "folder" ? -1 : 1);
520
+ }
521
+ /** The file or folder at `path`, or null when there is none. */
522
+ async stat(path) {
523
+ await this.refresh();
524
+ const n = this.find(path);
525
+ return n ? this.entry(n, parts(path).join("/")) : null;
526
+ }
527
+ /**
528
+ * A file's bytes: all of them, or `length` bytes from `offset`, fetching only the blocks that hold them (a few
529
+ * hundred KB of a 50 GB file costs a few hundred KB). `version` reads an older version from `history`.
530
+ */
531
+ async read(path, opts = {}) {
532
+ await this.refresh();
533
+ const versionId = opts.version ?? this.need(path, "file").versionId;
534
+ const src = this.source(versionId);
535
+ const keys = { masterKey: this.master };
536
+ if (opts.offset === void 0 && opts.length === void 0) {
537
+ const out2 = [];
538
+ await downloadVersion(src, keys, (c) => void out2.push(c));
539
+ return concat(...out2);
540
+ }
541
+ const first = await src.readUrls(0, 1);
542
+ const m = await fetchManifest(src, first);
543
+ const layout = new Layout(m.plaintextSize, m.encrypted);
544
+ const cipher = m.encrypted ? await BlockCipher.create(await fileKeyOf(m, keys), m.versionId) : void 0;
545
+ const start = opts.offset ?? 0;
546
+ const out = [];
547
+ for (const r of layout.reads(start, opts.length === void 0 ? m.plaintextSize : start + opts.length)) {
548
+ const url = r.piece === 0 && first.pieceUrls[0] ? first.pieceUrls[0].url : (await src.readUrls(r.piece, 1)).pieceUrls[0].url;
549
+ const stored = await retry(() => this.getRange(url, r.storedStart, r.storedEnd), void 0, 3);
550
+ const plain = cipher ? await cipher.openBlocks(stored, r.piece, r.blockStart, r.blockEnd, layout) : stored;
551
+ out.push(plain.subarray(r.sliceStart, r.sliceEnd));
552
+ }
553
+ return concat(...out);
554
+ }
555
+ /** A text file's content (UTF-8). */
556
+ async readText(path, opts = {}) {
557
+ return new TextDecoder().decode(await this.read(path, opts));
558
+ }
559
+ /* ---------- changing the drive ---------- */
560
+ /**
561
+ * Writes a file, making the folders above it. An existing file gets a new version: the old one stays in `history`
562
+ * for 30 days. The upload is verified piece by piece before it counts.
563
+ */
564
+ async write(path, data, opts = {}) {
565
+ const names = parts(path);
566
+ const name = names.pop();
567
+ if (!name) throw new PhantomDiskError("INVALID_PATH", "Give the file a name.");
568
+ const parentId = names.length ? (await this.mkdir(names.join("/"))).id : (await this.refresh(), null);
569
+ const existing = this.children(parentId).find((n) => this.nameOf(n) === name);
570
+ if (existing?.kind === "folder") throw new PhantomDiskError("IS_A_FOLDER", `\u201C${path}\u201D is a folder.`);
571
+ const blob = data instanceof Blob ? data : new Blob([typeof data === "string" ? utf8(data) : data]);
572
+ const sealing = this.sealing;
573
+ const nodeId = existing?.id ?? uuidv7();
574
+ const versionId = uuidv7();
575
+ const fileKey = sealing ? generateKey() : void 0;
576
+ const wrappedFileKey = fileKey && await wrapFileKey(fileKey, this.master);
577
+ const conflictNodeId = uuidv7();
578
+ const dot = name.lastIndexOf(".");
579
+ const conflict = dot > 0 ? `${name.slice(0, dot)} (conflict from SDK)${name.slice(dot)}` : `${name} (conflict from SDK)`;
580
+ const reply = await this.api("POST", "/v1/uploads", {
581
+ nodeId,
582
+ versionId,
583
+ parentId,
584
+ name: await this.stored(name, nodeId),
585
+ ...sealing ? { conflictName: await this.stored(conflict, conflictNodeId), conflictNodeId } : {},
586
+ size: blob.size,
587
+ pieceCount: new Layout(blob.size, sealing).pieceCount,
588
+ encrypted: sealing,
589
+ baseVersionId: existing?.versionId ?? null,
590
+ mtime: (opts.mtime ?? /* @__PURE__ */ new Date()).getTime()
591
+ });
592
+ if (reply.state !== "committed") {
593
+ const base = `/v1/uploads/${reply.uploadId}`;
594
+ const target = {
595
+ urls: (from, count) => this.api("POST", `${base}/urls`, { from, count }),
596
+ manifestUrl: async (manifestSize) => (await this.api("POST", `${base}/urls`, { from: 0, count: 1, manifestSize })).manifestUrl,
597
+ put: async (url, body, signal) => {
598
+ const r = await this.doFetch(url, { method: "PUT", body, headers: { "If-None-Match": "*" }, signal });
599
+ if (!r.ok && r.status !== 412) throw new PhantomDiskError("STORAGE", `Storage refused a piece (${r.status}).`, r.status);
600
+ },
601
+ complete: async (manifestHash2) => {
602
+ try {
603
+ this.apply((await this.api("POST", `${base}/complete`, { manifestHash: manifestHash2 })).change);
604
+ return null;
605
+ } catch (e) {
606
+ const d = e instanceof PhantomDiskError && e.code === "UPLOAD_INCOMPLETE" ? e.details : null;
607
+ if (d && d.manifest === "ok" && d.missing.length + d.wrongSize.length > 0) return [...d.missing, ...d.wrongSize];
608
+ throw e;
609
+ }
610
+ }
611
+ };
612
+ await uploadVersion(blob, { versionId, encryption: fileKey && { fileKey, wrappedFileKey }, first: { manifestUrl: null, pieceUrls: reply.pieceUrls } }, target);
613
+ }
614
+ fileKey?.fill(0);
615
+ await this.refresh();
616
+ return this.entry(this.nodes.get(nodeId) ?? this.need(path), parts(path).join("/"));
617
+ }
618
+ /** Makes a folder and any missing folders above it; an existing folder is returned as it is. */
619
+ async mkdir(path) {
620
+ await this.refresh();
621
+ let parentId = null;
622
+ const walked = [];
623
+ for (const name of parts(path)) {
624
+ walked.push(name);
625
+ const found = this.children(parentId).find((n) => this.nameOf(n) === name);
626
+ if (found && found.kind !== "folder") throw new PhantomDiskError("NOT_A_FOLDER", `\u201C${walked.join("/")}\u201D is a file.`);
627
+ if (found) parentId = found.id;
628
+ else {
629
+ const nodeId = uuidv7();
630
+ await this.ops([{ type: "createFolder", nodeId, parentId, name: await this.stored(name, nodeId) }]);
631
+ parentId = nodeId;
632
+ }
633
+ }
634
+ if (parentId === null) throw new PhantomDiskError("INVALID_PATH", "Give the folder a name.");
635
+ return this.entry(this.nodes.get(parentId), walked.join("/"));
636
+ }
637
+ /** Renames or moves a file or folder; the folders above the new place are made when missing. */
638
+ async move(from, to) {
639
+ await this.refresh();
640
+ const node = this.need(from);
641
+ const names = parts(to);
642
+ const name = names.pop();
643
+ if (!name) throw new PhantomDiskError("INVALID_PATH", "Give the new place a name.");
644
+ const parentId = names.length ? (await this.mkdir(names.join("/"))).id : null;
645
+ const list = [];
646
+ if (parentId !== node.parentId) list.push({ type: "move", nodeId: node.id, parentId });
647
+ if (name !== this.nameOf(node)) list.push({ type: "rename", nodeId: node.id, name: await this.stored(name, node.id) });
648
+ if (list.length) await this.ops(list);
649
+ return this.entry(this.nodes.get(node.id), parts(to).join("/"));
650
+ }
651
+ /** Moves a file or folder to Recently Deleted, where it can be brought back for 30 days. A key cannot delete for good. */
652
+ async remove(path) {
653
+ await this.refresh();
654
+ const n = this.need(path);
655
+ await this.ops([{ type: "trash", nodeId: n.id, baseVersionId: n.kind === "file" ? n.versionId : null }]);
656
+ }
657
+ /* ---------- copies and forks ---------- */
658
+ /**
659
+ * Copies a file, or a folder and everything in it, to `to`. Nothing is uploaded or downloaded: the copy shares the
660
+ * stored bytes, and from then on the two change apart. It counts against the plan like any other file.
661
+ */
662
+ async copy(from, to) {
663
+ await this.refresh();
664
+ const node = this.need(from);
665
+ const names = parts(to);
666
+ const name = names.pop();
667
+ if (!name) throw new PhantomDiskError("INVALID_PATH", "Give the copy a name.");
668
+ const parentId = names.length ? (await this.mkdir(names.join("/"))).id : null;
669
+ if (this.children(parentId).some((n) => this.nameOf(n) === name)) throw new PhantomDiskError("ALREADY_EXISTS", `There is already something at \u201C${to}\u201D.`, 409);
670
+ for (let up = parentId; up !== null; up = this.nodes.get(up)?.parentId ?? null)
671
+ if (up === node.id) throw new PhantomDiskError("INVALID_COPY", "A folder cannot be copied into itself.");
672
+ const id = await this.copyTree(node, this, parentId, name);
673
+ return this.entry(this.nodes.get(id), parts(to).join("/"));
674
+ }
675
+ /**
676
+ * A fork: a new drive holding everything in this one as it is now, made without moving any file's bytes. Work in
677
+ * the fork changes nothing here, and the other way round; delete either and the other is whole. Needs a key for
678
+ * every drive (a key limited to some drives cannot make one). Returns the fork, open.
679
+ */
680
+ async fork(name) {
681
+ await this.refresh();
682
+ const id = uuidv7();
683
+ await this.api("POST", "/v1/drives", { id, name: await this.stored(name, id) });
684
+ const fork = new _PhantomDisk(this.token, this.master, this.nameKeyRaw, this.apiUrl, this.doFetch, this.account, id);
685
+ await this.copyTree(null, fork, null);
686
+ return fork;
687
+ }
688
+ /** Copies `root` (null: everything in this drive) into `target` under `parentId`; the id of the copy of `root`. */
689
+ async copyTree(root, target, parentId, name) {
690
+ const kids = /* @__PURE__ */ new Map();
691
+ for (const n of this.nodes.values()) if (n.trashedAt === null) kids.set(n.parentId, [...kids.get(n.parentId) ?? [], n]);
692
+ const list = [];
693
+ let first = null;
694
+ const add = async (n, parent, as = this.nameOf(n)) => {
695
+ const nodeId = uuidv7();
696
+ first ??= nodeId;
697
+ const stored = await target.stored(as, nodeId);
698
+ if (n.kind === "file") list.push({ type: "copy", nodeId, from: n.id, parentId: parent, name: stored });
699
+ else {
700
+ list.push({ type: "createFolder", nodeId, parentId: parent, name: stored });
701
+ for (const c of kids.get(n.id) ?? []) await add(c, nodeId);
702
+ }
703
+ };
704
+ if (root) await add(root, parentId, name);
705
+ else for (const c of kids.get(null) ?? []) await add(c, null);
706
+ for (let i = 0; i < list.length; i += 100) await target.ops(list.slice(i, i + 100));
707
+ return first;
708
+ }
709
+ /* ---------- versions ---------- */
710
+ /** A file's versions, newest first. Replaced versions are kept for 30 days. */
711
+ async history(path) {
712
+ await this.refresh();
713
+ const n = this.need(path, "file");
714
+ const out = [];
715
+ for (let offset = 0; ; offset += 100) {
716
+ const page = await this.api(
717
+ "GET",
718
+ `/v1/files/${n.id}/versions?limit=100&offset=${offset}`
719
+ );
720
+ for (const v of page.versions) out.push({ id: v.id, size: v.size, createdAt: new Date(v.createdAt), current: v.current, purgeAt: v.purgeAt === null ? null : new Date(v.purgeAt) });
721
+ if (!page.hasMore) return out;
722
+ }
723
+ }
724
+ /** Makes an older version current again. Nothing is copied, and the version it replaces stays in `history`. */
725
+ async restore(path, versionId) {
726
+ await this.refresh();
727
+ const n = this.need(path, "file");
728
+ this.apply((await this.api("POST", `/v1/files/${n.id}/versions/${versionId}/restore`, { opId: uuidv7() })).change);
729
+ return this.entry(this.nodes.get(n.id), parts(path).join("/"));
730
+ }
731
+ /** Catches up with changes made elsewhere (the Mac app, the web, another agent). Every call above does this first. */
732
+ async refresh() {
733
+ for (; ; ) {
734
+ let page;
735
+ try {
736
+ page = await this.api("GET", `/v1/changes?after=${this.cursor}&limit=1000`);
737
+ } catch (e) {
738
+ if (!(e instanceof PhantomDiskError && e.code === "RESYNC_REQUIRED")) throw e;
739
+ await this.snapshot();
740
+ continue;
741
+ }
742
+ for (const c of page.changes) this.apply(c);
743
+ this.cursor = page.cursor;
744
+ if (!page.hasMore) break;
745
+ }
746
+ if (!this.nameKeyRaw) return;
747
+ for (const n of this.nodes.values()) {
748
+ const k = `${n.id}:${n.name}`;
749
+ if (!this.names.has(k)) this.names.set(k, await openName(this.nameKeyRaw, n.name, n.id, this.account.namesVersion !== 2).catch(() => n.name));
750
+ }
751
+ }
752
+ /* ---------- inside ---------- */
753
+ get sealing() {
754
+ return this.account.encryptionState === "on" || this.account.encryptionState === "turning_on";
755
+ }
756
+ async stored(name, nodeId) {
757
+ return this.sealing ? sealName(this.nameKeyRaw, name.normalize("NFC"), nodeId) : name.normalize("NFC");
758
+ }
759
+ nameOf(n) {
760
+ return this.nameKeyRaw ? this.names.get(`${n.id}:${n.name}`) ?? n.name : n.name;
761
+ }
762
+ children(parentId) {
763
+ return [...this.nodes.values()].filter((n) => n.parentId === parentId && n.trashedAt === null);
764
+ }
765
+ find(path) {
766
+ let at = null;
767
+ for (const name of parts(path)) {
768
+ const parent = at ? at.id : null;
769
+ at = this.children(parent).find((n) => this.nameOf(n) === name) ?? null;
770
+ if (!at) return null;
771
+ }
772
+ return at;
773
+ }
774
+ need(path, kind) {
775
+ const n = this.find(path);
776
+ if (!n) throw new PhantomDiskError("NOT_FOUND", `There is nothing at \u201C${path}\u201D.`, 404);
777
+ if (kind && n.kind !== kind) throw new PhantomDiskError(kind === "file" ? "IS_A_FOLDER" : "NOT_A_FOLDER", `\u201C${path}\u201D is a ${n.kind}.`);
778
+ return n;
779
+ }
780
+ entry(n, path) {
781
+ return { path, name: this.nameOf(n), kind: n.kind, size: n.size, modified: new Date(n.mtime), id: n.id, versionId: n.versionId };
782
+ }
783
+ apply(c) {
784
+ for (const n of c.op.nodes) if (n.driveId === this.driveId) this.nodes.set(n.id, n);
785
+ for (const id of c.op.removed) this.nodes.delete(id);
786
+ }
787
+ async snapshot() {
788
+ const nodes = /* @__PURE__ */ new Map();
789
+ let cursor = null;
790
+ for (let start = ""; ; ) {
791
+ const p = await this.api("GET", `/v1/changes/snapshot?limit=1000&start=${encodeURIComponent(start)}`);
792
+ cursor ??= p.cursor;
793
+ for (const n of p.nodes) nodes.set(n.id, n);
794
+ if (!p.hasMore || !p.next) break;
795
+ start = p.next;
796
+ }
797
+ this.nodes = nodes;
798
+ this.cursor = cursor ?? 0;
799
+ }
800
+ async ops(list) {
801
+ const { results } = await this.api(
802
+ "POST",
803
+ "/v1/changes",
804
+ { ops: list.map((o) => ({ opId: uuidv7(), ...o })) }
805
+ );
806
+ let rejected = null;
807
+ for (const r of results) {
808
+ if (r.status === "applied") this.apply(r.change);
809
+ else rejected ??= new PhantomDiskError(r.error.code, r.error.message, r.error.status);
810
+ }
811
+ if (rejected) throw rejected;
812
+ }
813
+ source(versionId) {
814
+ return {
815
+ versionId,
816
+ readUrls: (from, count) => this.api("POST", `/v1/files/${versionId}/read-urls`, { from, count }),
817
+ get: async (url, signal) => {
818
+ const r = await this.doFetch(url, { signal });
819
+ if (!r.ok) throw new PhantomDiskError("STORAGE", `Storage refused a read (${r.status}).`, r.status);
820
+ return new Uint8Array(await r.arrayBuffer());
821
+ }
822
+ };
823
+ }
824
+ async getRange(url, start, end) {
825
+ const r = await this.doFetch(url, { headers: { Range: `bytes=${start}-${end - 1}` } });
826
+ if (r.status !== 206 && !(r.status === 200 && start === 0)) throw new PhantomDiskError("STORAGE", `Storage refused a read (${r.status}).`, r.status);
827
+ const bytes = new Uint8Array(await r.arrayBuffer());
828
+ return r.status === 200 ? bytes.subarray(0, end) : bytes;
829
+ }
830
+ /** One API call. A busy or rate-limited answer is tried again a few times, after the wait the server names. */
831
+ async api(method, path, body) {
832
+ for (let attempt = 0; ; attempt++) {
833
+ let r;
834
+ try {
835
+ r = await this.doFetch(this.apiUrl + path, {
836
+ method,
837
+ headers: {
838
+ Authorization: `Bearer ${this.token}`,
839
+ ...this.driveId ? { "X-Drive": this.driveId } : {},
840
+ ...body === void 0 ? {} : { "Content-Type": "application/json" }
841
+ },
842
+ body: body === void 0 ? void 0 : JSON.stringify(body)
843
+ });
844
+ } catch {
845
+ if (attempt < 3) {
846
+ await new Promise((done) => setTimeout(done, 500 * 2 ** attempt));
847
+ continue;
848
+ }
849
+ throw new PhantomDiskError("OFFLINE", "Can't reach PhantomDisk. Check the connection and the API address.");
850
+ }
851
+ const data = await r.json().catch(() => null);
852
+ if (r.ok) return data;
853
+ if ((r.status === 429 || r.status === 503) && attempt < 3) {
854
+ await new Promise((done) => setTimeout(done, Math.min(10, data?.error?.details?.retryAfter ?? 2 ** attempt) * 1e3));
855
+ continue;
856
+ }
857
+ throw new PhantomDiskError(data?.error?.code ?? "HTTP_ERROR", data?.error?.message ?? `PhantomDisk answered ${r.status}.`, r.status, data?.error?.details);
858
+ }
859
+ }
860
+ };
861
+ export {
862
+ DEFAULT_API_URL,
863
+ PhantomDisk,
864
+ PhantomDiskError
865
+ };