@c9up/archive 0.1.13 → 0.1.15

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.
Files changed (41) hide show
  1. package/dist/ArchiveProvider.d.ts +1 -0
  2. package/dist/ArchiveProvider.d.ts.map +1 -1
  3. package/dist/ArchiveProvider.js +53 -17
  4. package/dist/ArchiveProvider.js.map +1 -1
  5. package/dist/DriveManager.js +2 -2
  6. package/dist/DriveManager.js.map +1 -1
  7. package/dist/GcsDriver.js +5 -5
  8. package/dist/GcsDriver.js.map +1 -1
  9. package/dist/S3Driver.js +6 -6
  10. package/dist/S3Driver.js.map +1 -1
  11. package/dist/StaticMiddleware.d.ts.map +1 -1
  12. package/dist/StaticMiddleware.js +31 -11
  13. package/dist/StaticMiddleware.js.map +1 -1
  14. package/dist/StorageManager.d.ts +16 -8
  15. package/dist/StorageManager.d.ts.map +1 -1
  16. package/dist/StorageManager.js +176 -115
  17. package/dist/StorageManager.js.map +1 -1
  18. package/dist/etag.d.ts +32 -0
  19. package/dist/etag.d.ts.map +1 -0
  20. package/dist/etag.js +41 -0
  21. package/dist/etag.js.map +1 -0
  22. package/dist/expiry.d.ts +2 -2
  23. package/dist/expiry.js +6 -6
  24. package/dist/expiry.js.map +1 -1
  25. package/dist/services/main.d.ts +11 -0
  26. package/dist/services/main.d.ts.map +1 -1
  27. package/dist/services/main.js +21 -0
  28. package/dist/services/main.js.map +1 -1
  29. package/dist/testing/FakeStorage.js +7 -7
  30. package/dist/testing/FakeStorage.js.map +1 -1
  31. package/package.json +1 -1
  32. package/src/ArchiveProvider.ts +64 -24
  33. package/src/DriveManager.ts +2 -2
  34. package/src/GcsDriver.ts +5 -5
  35. package/src/S3Driver.ts +6 -6
  36. package/src/StaticMiddleware.ts +32 -11
  37. package/src/StorageManager.ts +182 -118
  38. package/src/etag.ts +44 -0
  39. package/src/expiry.ts +6 -6
  40. package/src/services/main.ts +21 -0
  41. package/src/testing/FakeStorage.ts +7 -7
@@ -6,6 +6,7 @@
6
6
 
7
7
  import { createHash, createHmac } from "node:crypto";
8
8
  import * as fs from "node:fs";
9
+ import * as fsp from "node:fs/promises";
9
10
  import * as path from "node:path";
10
11
  import { pipeline } from "node:stream/promises";
11
12
  import * as url from "node:url";
@@ -158,12 +159,12 @@ export interface StorageDriver {
158
159
  get(filePath: string): Promise<Buffer | null>;
159
160
  /**
160
161
  * Contents as a `Uint8Array`. AdonisJS Drive parity. Throws
161
- * `ARCHIVE_NOT_FOUND` when the object is absent (unlike {@link get},
162
+ * `E_ARCHIVE_NOT_FOUND` when the object is absent (unlike {@link get},
162
163
  * a byte accessor can't express absence as a value).
163
164
  */
164
165
  getBytes(filePath: string): Promise<Uint8Array>;
165
166
  /**
166
- * Download as a readable stream. Throws `ARCHIVE_NOT_FOUND` when
167
+ * Download as a readable stream. Throws `E_ARCHIVE_NOT_FOUND` when
167
168
  * the object is missing — streams can't express absence as a value.
168
169
  */
169
170
  getStream(filePath: string): Promise<NodeJS.ReadableStream>;
@@ -185,7 +186,7 @@ export interface StorageDriver {
185
186
  * Return a time-boxed URL that grants read access to `filePath`.
186
187
  * Implementations must validate `options.expiresIn` via
187
188
  * {@link assertValidExpiry} and reject out-of-range values with
188
- * `ARCHIVE_INVALID_EXPIRY`.
189
+ * `E_ARCHIVE_INVALID_EXPIRY`.
189
190
  */
190
191
  getSignedUrl(
191
192
  filePath: string,
@@ -195,14 +196,14 @@ export interface StorageDriver {
195
196
  * Return a time-boxed URL that grants **write** (PUT) access, letting
196
197
  * a client upload directly to the backend. AdonisJS Drive parity.
197
198
  * Cloud-only — the LocalDriver has no presigned-upload equivalent and
198
- * throws `ARCHIVE_SIGNED_UPLOAD_UNSUPPORTED`.
199
+ * throws `E_ARCHIVE_SIGNED_UPLOAD_UNSUPPORTED`.
199
200
  */
200
201
  getSignedUploadUrl(
201
202
  filePath: string,
202
203
  options?: SignedUrlOptions,
203
204
  ): string | Promise<string>;
204
205
  /**
205
- * Resolve object metadata. Throws `ArchiveError('ARCHIVE_NOT_FOUND', ...)`
206
+ * Resolve object metadata. Throws `ArchiveError('E_ARCHIVE_NOT_FOUND', ...)`
206
207
  * when the object does not exist.
207
208
  */
208
209
  getMetadata(filePath: string): Promise<Metadata>;
@@ -217,7 +218,7 @@ export interface StorageDriver {
217
218
  */
218
219
  setVisibility(filePath: string, visibility: Visibility): Promise<void>;
219
220
  /**
220
- * Duplicate an object. Throws `ARCHIVE_NOT_FOUND` if `from` is
221
+ * Duplicate an object. Throws `E_ARCHIVE_NOT_FOUND` if `from` is
221
222
  * missing. Target is overwritten if it exists. Visibility is NOT
222
223
  * carried over unless `options.visibility` is passed — the new object
223
224
  * takes default visibility.
@@ -255,7 +256,7 @@ export interface LocalDriverOptions {
255
256
  /**
256
257
  * HMAC-SHA256 secret used by {@link LocalDriver.getSignedUrl}.
257
258
  * When omitted, signing is disabled and `getSignedUrl` throws
258
- * `ARCHIVE_SIGNING_DISABLED`. The non-signing methods
259
+ * `E_ARCHIVE_SIGNING_DISABLED`. The non-signing methods
259
260
  * (`put`/`get`/`delete`/`exists`/`url`) work either way.
260
261
  */
261
262
  signingSecret?: string;
@@ -265,6 +266,14 @@ export class LocalDriver implements StorageDriver {
265
266
  #root: string;
266
267
  #signingSecret: string | null;
267
268
 
269
+ /**
270
+ * The only synchronous filesystem access left in this driver, and the only
271
+ * one that cannot be anything else: a constructor cannot await. It runs
272
+ * once, at boot, before the server is serving. Every method below is
273
+ * asynchronous — they used to be async signatures over `writeFileSync` /
274
+ * `readFileSync`, so a large upload or download stalled every other
275
+ * request in the process for its whole duration.
276
+ */
268
277
  constructor(root: string, options?: LocalDriverOptions) {
269
278
  const resolved = path.resolve(root);
270
279
  if (!fs.existsSync(resolved)) {
@@ -280,7 +289,7 @@ export class LocalDriver implements StorageDriver {
280
289
  // values without being annoyingly strict about format.
281
290
  if (typeof secret !== "string" || secret.length < 16) {
282
291
  throw new ArchiveError(
283
- "ARCHIVE_WEAK_SIGNING_SECRET",
292
+ "E_ARCHIVE_WEAK_SIGNING_SECRET",
284
293
  `LocalDriver signingSecret must be a string of at least 16 chars (got length ${typeof secret === "string" ? secret.length : "non-string"})`,
285
294
  {
286
295
  hint: "Use a cryptographically random secret, e.g. `crypto.randomBytes(32).toString('hex')`.",
@@ -292,16 +301,16 @@ export class LocalDriver implements StorageDriver {
292
301
  }
293
302
 
294
303
  /**
295
- * Resolve and validate a file path — prevents traversal outside
296
- * the root, INCLUDING via symlinks planted inside the root.
304
+ * The half of the guard that touches nothing: control characters and
305
+ * lexical containment.
297
306
  *
298
- * For existing files the check walks `fs.realpathSync(full)` to
299
- * defeat symlink redirection. For new writes (target doesn't exist
300
- * yet) we walk the nearest existing ancestor via `realpathSync` so
301
- * an attacker who planted a symlink at `<root>/evil -> /etc`
302
- * cannot redirect a put through it.
307
+ * Split out because `getSignedUrl` is synchronous in the driver contract
308
+ * and cannot await the symlink walk. Keeping ONE implementation of each
309
+ * half — rather than a sync copy of the whole check beside an async one —
310
+ * is what stops the two from drifting apart, which for a containment guard
311
+ * is the failure that matters.
303
312
  */
304
- #safePath(filePath: string): string {
313
+ #lexicalPath(filePath: string): string {
305
314
  // Reject control chars that would smuggle HMAC delimiters or
306
315
  // confuse path handling. `\n` (10) is the signing payload
307
316
  // separator — a filename containing `\n` could otherwise forge
@@ -315,30 +324,50 @@ export class LocalDriver implements StorageDriver {
315
324
  }
316
325
  }
317
326
  const full = path.resolve(this.#root, filePath);
318
- // Lexical guard first — cheap and covers the `..` case.
327
+ // Lexical guard — cheap and covers the `..` case.
319
328
  if (!full.startsWith(this.#root + path.sep) && full !== this.#root) {
320
329
  throw new Error(
321
330
  `Path traversal blocked: '${filePath}' resolves outside storage root`,
322
331
  );
323
332
  }
333
+ return full;
334
+ }
335
+
336
+ /**
337
+ * Resolve and validate a file path — prevents traversal outside
338
+ * the root, INCLUDING via symlinks planted inside the root.
339
+ *
340
+ * For existing files the check walks `realpath(full)` to defeat symlink
341
+ * redirection. For new writes (target doesn't exist yet) we walk the
342
+ * nearest existing ancestor so an attacker who planted a symlink at
343
+ * `<root>/evil -> /etc` cannot redirect a put through it.
344
+ */
345
+ async #safePath(filePath: string): Promise<string> {
346
+ const full = this.#lexicalPath(filePath);
324
347
  // Realpath guard — walk up to the nearest existing ancestor and
325
348
  // confirm its canonical form is still under root.
326
349
  let probe = full;
327
- while (!fs.existsSync(probe)) {
328
- const parent = path.dirname(probe);
329
- if (parent === probe) break;
330
- probe = parent;
331
- }
332
- const realProbe = fs.realpathSync(probe);
333
- if (
334
- !realProbe.startsWith(this.#root + path.sep) &&
335
- realProbe !== this.#root
336
- ) {
337
- throw new Error(
338
- `Path traversal blocked: '${filePath}' resolves outside storage root via symlink`,
339
- );
350
+ for (;;) {
351
+ try {
352
+ const realProbe = await fsp.realpath(probe);
353
+ if (
354
+ !realProbe.startsWith(this.#root + path.sep) &&
355
+ realProbe !== this.#root
356
+ ) {
357
+ throw new Error(
358
+ `Path traversal blocked: '${filePath}' resolves outside storage root via symlink`,
359
+ );
360
+ }
361
+ return full;
362
+ } catch (err) {
363
+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
364
+ const parent = path.dirname(probe);
365
+ // The root itself is canonicalised at construction, so the walk
366
+ // always terminates at something that resolves.
367
+ if (parent === probe) return full;
368
+ probe = parent;
369
+ }
340
370
  }
341
- return full;
342
371
  }
343
372
 
344
373
  async put(
@@ -346,12 +375,9 @@ export class LocalDriver implements StorageDriver {
346
375
  content: Buffer | string,
347
376
  options?: WriteOptions,
348
377
  ): Promise<void> {
349
- const full = this.#safePath(filePath);
350
- const dir = path.dirname(full);
351
- if (!fs.existsSync(dir)) {
352
- fs.mkdirSync(dir, { recursive: true });
353
- }
354
- fs.writeFileSync(full, content);
378
+ const full = await this.#safePath(filePath);
379
+ await fsp.mkdir(path.dirname(full), { recursive: true });
380
+ await fsp.writeFile(full, content);
355
381
  // Only `visibility` has a filesystem-equivalent (the sidecar).
356
382
  // contentType/cacheControl/... have no local meaning.
357
383
  if (options?.visibility !== undefined) {
@@ -363,7 +389,7 @@ export class LocalDriver implements StorageDriver {
363
389
  const buf = await this.get(filePath);
364
390
  if (buf === null) {
365
391
  throw new ArchiveError(
366
- "ARCHIVE_NOT_FOUND",
392
+ "E_ARCHIVE_NOT_FOUND",
367
393
  `File does not exist at path '${filePath}'`,
368
394
  { hint: "Confirm the path and that the file was put() first." },
369
395
  );
@@ -378,27 +404,30 @@ export class LocalDriver implements StorageDriver {
378
404
  // getMetadata) and contentLength (FS knows its own size).
379
405
  _options?: PutStreamOptions,
380
406
  ): Promise<void> {
381
- const full = this.#safePath(filePath);
382
- const dir = path.dirname(full);
383
- if (!fs.existsSync(dir)) {
384
- fs.mkdirSync(dir, { recursive: true });
385
- }
407
+ const full = await this.#safePath(filePath);
408
+ await fsp.mkdir(path.dirname(full), { recursive: true });
386
409
  // `pipeline` propagates errors and destroys the write target on
387
410
  // failure — no manual cleanup needed.
388
411
  await pipeline(readable, fs.createWriteStream(full));
389
412
  }
390
413
 
391
414
  async get(filePath: string): Promise<Buffer | null> {
392
- const full = this.#safePath(filePath);
393
- if (!fs.existsSync(full)) return null;
394
- return fs.readFileSync(full);
415
+ const full = await this.#safePath(filePath);
416
+ try {
417
+ return await fsp.readFile(full);
418
+ } catch (err) {
419
+ // One syscall instead of exists-then-read: the pair also answered
420
+ // `null` for a file that was deleted between the two.
421
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;
422
+ throw err;
423
+ }
395
424
  }
396
425
 
397
426
  async getStream(filePath: string): Promise<NodeJS.ReadableStream> {
398
- const full = this.#safePath(filePath);
399
- if (!fs.existsSync(full)) {
427
+ const full = await this.#safePath(filePath);
428
+ if (!(await exists(full))) {
400
429
  throw new ArchiveError(
401
- "ARCHIVE_NOT_FOUND",
430
+ "E_ARCHIVE_NOT_FOUND",
402
431
  `File does not exist at path '${filePath}'`,
403
432
  { hint: "Confirm the path and that the file was put() first." },
404
433
  );
@@ -407,16 +436,20 @@ export class LocalDriver implements StorageDriver {
407
436
  }
408
437
 
409
438
  async delete(filePath: string): Promise<boolean> {
410
- const full = this.#safePath(filePath);
411
- if (!fs.existsSync(full)) return false;
412
- fs.unlinkSync(full);
439
+ const full = await this.#safePath(filePath);
440
+ try {
441
+ await fsp.unlink(full);
442
+ } catch (err) {
443
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return false;
444
+ throw err;
445
+ }
413
446
  // Sidecar cleanup is best-effort. The main file is already gone
414
447
  // — any sidecar failure (ENOENT, EACCES, EPERM) would corrupt
415
448
  // the `delete` contract if we threw here (caller would see a
416
449
  // rejected Promise AFTER the file was already deleted).
417
450
  const sidecar = full + VISIBILITY_SIDECAR_SUFFIX;
418
451
  try {
419
- fs.unlinkSync(sidecar);
452
+ await fsp.unlink(sidecar);
420
453
  } catch {
421
454
  // swallow: cleanup is best-effort.
422
455
  }
@@ -427,7 +460,7 @@ export class LocalDriver implements StorageDriver {
427
460
  // Sidecars are an implementation detail — pretend they don't
428
461
  // exist from the public API's point of view.
429
462
  if (filePath.endsWith(VISIBILITY_SIDECAR_SUFFIX)) return false;
430
- return fs.existsSync(this.#safePath(filePath));
463
+ return exists(await this.#safePath(filePath));
431
464
  }
432
465
 
433
466
  publicUrl(filePath: string): string {
@@ -443,20 +476,20 @@ export class LocalDriver implements StorageDriver {
443
476
  }
444
477
 
445
478
  async url(filePath: string): Promise<string> {
446
- const visibility = this.#readVisibility(filePath);
479
+ const visibility = await this.#readVisibility(filePath);
447
480
  if (visibility === "public") return this.publicUrl(filePath);
448
481
  return this.getSignedUrl(filePath);
449
482
  }
450
483
 
451
484
  async getMetadata(filePath: string): Promise<Metadata> {
452
- const full = this.#safePath(filePath);
485
+ const full = await this.#safePath(filePath);
453
486
  let stat: fs.Stats;
454
487
  try {
455
- stat = fs.statSync(full);
488
+ stat = await fsp.stat(full);
456
489
  } catch (err) {
457
490
  if ((err as NodeJS.ErrnoException).code === "ENOENT") {
458
491
  throw new ArchiveError(
459
- "ARCHIVE_NOT_FOUND",
492
+ "E_ARCHIVE_NOT_FOUND",
460
493
  `File does not exist at path '${filePath}'`,
461
494
  { hint: "Confirm the path and that the file was put() first." },
462
495
  );
@@ -478,7 +511,7 @@ export class LocalDriver implements StorageDriver {
478
511
  contentType: mimeType,
479
512
  lastModified: stat.mtime,
480
513
  etag: `W/"${etagBody}"`,
481
- visibility: this.#readVisibility(filePath),
514
+ visibility: await this.#readVisibility(filePath),
482
515
  };
483
516
  }
484
517
 
@@ -487,16 +520,16 @@ export class LocalDriver implements StorageDriver {
487
520
  }
488
521
 
489
522
  async setVisibility(filePath: string, visibility: Visibility): Promise<void> {
490
- const full = this.#safePath(filePath);
491
- if (!fs.existsSync(full)) {
523
+ const full = await this.#safePath(filePath);
524
+ if (!(await exists(full))) {
492
525
  throw new ArchiveError(
493
- "ARCHIVE_NOT_FOUND",
526
+ "E_ARCHIVE_NOT_FOUND",
494
527
  `Cannot set visibility — file does not exist at path '${filePath}'`,
495
528
  { hint: "put() the file before calling setVisibility()." },
496
529
  );
497
530
  }
498
531
  const sidecar = full + VISIBILITY_SIDECAR_SUFFIX;
499
- fs.writeFileSync(sidecar, JSON.stringify({ visibility }), { flag: "w" });
532
+ await fsp.writeFile(sidecar, JSON.stringify({ visibility }), { flag: "w" });
500
533
  }
501
534
 
502
535
  /**
@@ -508,15 +541,18 @@ export class LocalDriver implements StorageDriver {
508
541
  * blip into a private→public downgrade for an existing private file.
509
542
  * Refuse to serve undetermined visibility instead.
510
543
  */
511
- #readVisibility(filePath: string): Visibility {
512
- const sidecar = this.#safePath(filePath) + VISIBILITY_SIDECAR_SUFFIX;
513
- if (!fs.existsSync(sidecar)) return "public";
544
+ async #readVisibility(filePath: string): Promise<Visibility> {
545
+ const sidecar =
546
+ (await this.#safePath(filePath)) + VISIBILITY_SIDECAR_SUFFIX;
514
547
  let raw: string;
515
548
  try {
516
- raw = fs.readFileSync(sidecar, "utf8");
549
+ raw = await fsp.readFile(sidecar, "utf8");
517
550
  } catch (err) {
551
+ // Absent sidecar is the documented default, and it is the common
552
+ // case: one syscall answers both that and a real read failure.
553
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return "public";
518
554
  throw new ArchiveError(
519
- "ARCHIVE_VISIBILITY_CORRUPT",
555
+ "E_ARCHIVE_VISIBILITY_CORRUPT",
520
556
  `Failed to read visibility sidecar for '${filePath}' (${(err as NodeJS.ErrnoException).code ?? "I/O error"}); refusing to default to 'public'.`,
521
557
  {
522
558
  hint: "Inspect the sidecar file or re-apply visibility via setVisibility().",
@@ -528,7 +564,7 @@ export class LocalDriver implements StorageDriver {
528
564
  parsed = JSON.parse(raw) as { visibility?: unknown };
529
565
  } catch {
530
566
  throw new ArchiveError(
531
- "ARCHIVE_VISIBILITY_CORRUPT",
567
+ "E_ARCHIVE_VISIBILITY_CORRUPT",
532
568
  `Sidecar for '${filePath}' is not valid JSON; refusing to default to 'public'.`,
533
569
  {
534
570
  hint: "Delete the sidecar file and re-apply visibility via setVisibility().",
@@ -542,13 +578,20 @@ export class LocalDriver implements StorageDriver {
542
578
  // Fail fast on unsafe paths instead of producing a signed URL that
543
579
  // can never be served — `storage.get()` would reject it later via
544
580
  // `#safePath`, but signing-time errors are easier to diagnose.
545
- this.#safePath(filePath);
581
+ //
582
+ // The lexical half only: this method is synchronous in the driver
583
+ // contract and cannot await the symlink walk. Nothing is lost, because
584
+ // signing a URL reads no file — the read it leads to goes through the
585
+ // full check. What must NOT be skipped here is the control-character
586
+ // rejection, since `\n` is this signature's own payload separator, and
587
+ // `#lexicalPath` is where that lives.
588
+ this.#lexicalPath(filePath);
546
589
  const expiresIn = parseExpiry(options?.expiresIn ?? DEFAULT_EXPIRES_IN);
547
590
  assertValidExpiry(expiresIn);
548
591
  const secret = this.#signingSecret;
549
592
  if (secret === null) {
550
593
  throw new ArchiveError(
551
- "ARCHIVE_SIGNING_DISABLED",
594
+ "E_ARCHIVE_SIGNING_DISABLED",
552
595
  "LocalDriver.getSignedUrl requires a signingSecret at construction time",
553
596
  {
554
597
  hint: "Pass { signingSecret: <hex or random string> } to the LocalDriver constructor, or set config.archive.local.signingSecret. Private files require a signing secret.",
@@ -571,7 +614,7 @@ export class LocalDriver implements StorageDriver {
571
614
  */
572
615
  getSignedUploadUrl(_filePath: string, _options?: SignedUrlOptions): string {
573
616
  throw new ArchiveError(
574
- "ARCHIVE_SIGNED_UPLOAD_UNSUPPORTED",
617
+ "E_ARCHIVE_SIGNED_UPLOAD_UNSUPPORTED",
575
618
  "LocalDriver does not support presigned upload URLs",
576
619
  {
577
620
  hint: "Presigned uploads are an S3/GCS feature. For local storage, upload through your app's HTTP handler.",
@@ -588,18 +631,17 @@ export class LocalDriver implements StorageDriver {
588
631
  }
589
632
 
590
633
  async copy(from: string, to: string, options?: WriteOptions): Promise<void> {
591
- const fromFull = this.#safePath(from);
592
- const toFull = this.#safePath(to);
593
- if (!fs.existsSync(fromFull)) {
634
+ const fromFull = await this.#safePath(from);
635
+ const toFull = await this.#safePath(to);
636
+ if (!(await exists(fromFull))) {
594
637
  throw new ArchiveError(
595
- "ARCHIVE_NOT_FOUND",
638
+ "E_ARCHIVE_NOT_FOUND",
596
639
  `Cannot copy — source does not exist at path '${from}'`,
597
640
  { hint: "Confirm the source path was put() first." },
598
641
  );
599
642
  }
600
- const dir = path.dirname(toFull);
601
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
602
- fs.copyFileSync(fromFull, toFull);
643
+ await fsp.mkdir(path.dirname(toFull), { recursive: true });
644
+ await fsp.copyFile(fromFull, toFull);
603
645
  // Intentionally do NOT copy the visibility sidecar — new object
604
646
  // takes default visibility unless the caller asks otherwise.
605
647
  if (options?.visibility !== undefined) {
@@ -608,11 +650,11 @@ export class LocalDriver implements StorageDriver {
608
650
  }
609
651
 
610
652
  async move(from: string, to: string, options?: WriteOptions): Promise<void> {
611
- const fromFull = this.#safePath(from);
612
- const toFull = this.#safePath(to);
613
- if (!fs.existsSync(fromFull)) {
653
+ const fromFull = await this.#safePath(from);
654
+ const toFull = await this.#safePath(to);
655
+ if (!(await exists(fromFull))) {
614
656
  throw new ArchiveError(
615
- "ARCHIVE_NOT_FOUND",
657
+ "E_ARCHIVE_NOT_FOUND",
616
658
  `Cannot move — source does not exist at path '${from}'`,
617
659
  { hint: "Confirm the source path was put() first." },
618
660
  );
@@ -624,20 +666,19 @@ export class LocalDriver implements StorageDriver {
624
666
  // corruption, which surfaces here BEFORE we mutate anything.
625
667
  const fromSidecar = fromFull + VISIBILITY_SIDECAR_SUFFIX;
626
668
  const toSidecar = toFull + VISIBILITY_SIDECAR_SUFFIX;
627
- const capturedVisibility: Visibility | undefined = fs.existsSync(
669
+ const capturedVisibility: Visibility | undefined = (await exists(
628
670
  fromSidecar,
629
- )
630
- ? this.#readVisibility(from)
671
+ ))
672
+ ? await this.#readVisibility(from)
631
673
  : undefined;
632
- const dir = path.dirname(toFull);
633
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
674
+ await fsp.mkdir(path.dirname(toFull), { recursive: true });
634
675
  try {
635
- fs.renameSync(fromFull, toFull);
676
+ await fsp.rename(fromFull, toFull);
636
677
  } catch (err) {
637
678
  // Cross-device rename — fall back to copy+unlink.
638
679
  if ((err as NodeJS.ErrnoException).code === "EXDEV") {
639
- fs.copyFileSync(fromFull, toFull);
640
- fs.unlinkSync(fromFull);
680
+ await fsp.copyFile(fromFull, toFull);
681
+ await fsp.unlink(fromFull);
641
682
  } else {
642
683
  throw err;
643
684
  }
@@ -648,14 +689,14 @@ export class LocalDriver implements StorageDriver {
648
689
  // Public is the default, so an absent source sidecar means no work.
649
690
  if (capturedVisibility !== undefined) {
650
691
  try {
651
- fs.writeFileSync(
692
+ await fsp.writeFile(
652
693
  toSidecar,
653
694
  JSON.stringify({ visibility: capturedVisibility }),
654
695
  { flag: "w" },
655
696
  );
656
697
  } catch (err) {
657
698
  throw new ArchiveError(
658
- "ARCHIVE_VISIBILITY_MOVE_FAILED",
699
+ "E_ARCHIVE_VISIBILITY_MOVE_FAILED",
659
700
  `move('${from}' -> '${to}'): main file moved but visibility sidecar write failed (${(err as NodeJS.ErrnoException).code ?? "unknown"}). Target visibility is undefined.`,
660
701
  {
661
702
  hint: "Re-apply visibility via setVisibility() on the target path.",
@@ -665,12 +706,10 @@ export class LocalDriver implements StorageDriver {
665
706
  // Best-effort cleanup of the source sidecar — visibility is already
666
707
  // preserved on the target side. A failure here leaves a stale
667
708
  // sidecar pointing at the now-missing source file; benign.
668
- if (fs.existsSync(fromSidecar)) {
669
- try {
670
- fs.unlinkSync(fromSidecar);
671
- } catch {
672
- // benign — source dir may be cleaned up by later operations.
673
- }
709
+ try {
710
+ await fsp.unlink(fromSidecar);
711
+ } catch {
712
+ // benign — source dir may be cleaned up by later operations.
674
713
  }
675
714
  }
676
715
  // An explicit visibility override wins over the preserved value.
@@ -691,12 +730,12 @@ export class LocalDriver implements StorageDriver {
691
730
  }
692
731
  // Prune the prefix directory itself when it is now empty, mirroring
693
732
  // flydrive's "the folder is deleted" behaviour. Best-effort.
694
- const dir = this.#safePath(prefix);
695
- if (dir !== this.#root && fs.existsSync(dir)) {
733
+ const dir = await this.#safePath(prefix);
734
+ if (dir !== this.#root) {
696
735
  try {
697
- const stat = fs.statSync(dir);
698
- if (stat.isDirectory() && fs.readdirSync(dir).length === 0) {
699
- fs.rmdirSync(dir);
736
+ const stat = await fsp.stat(dir);
737
+ if (stat.isDirectory() && (await fsp.readdir(dir)).length === 0) {
738
+ await fsp.rmdir(dir);
700
739
  }
701
740
  } catch {
702
741
  // benign — leave non-empty / vanished dirs alone.
@@ -719,7 +758,9 @@ export class LocalDriver implements StorageDriver {
719
758
  : `${prefix}/`;
720
759
  for await (const entry of this.list(normalizedPrefix)) {
721
760
  if (recursive) {
722
- files.push(new DriveFile(entry.path, this, this.#entryMetadata(entry)));
761
+ files.push(
762
+ new DriveFile(entry.path, this, await this.#entryMetadata(entry)),
763
+ );
723
764
  continue;
724
765
  }
725
766
  // Non-recursive: collapse anything below the immediate level
@@ -727,7 +768,9 @@ export class LocalDriver implements StorageDriver {
727
768
  const rest = entry.path.slice(normalizedPrefix.length);
728
769
  const slash = rest.indexOf("/");
729
770
  if (slash === -1) {
730
- files.push(new DriveFile(entry.path, this, this.#entryMetadata(entry)));
771
+ files.push(
772
+ new DriveFile(entry.path, this, await this.#entryMetadata(entry)),
773
+ );
731
774
  } else {
732
775
  const dirPrefix = normalizedPrefix + rest.slice(0, slash);
733
776
  if (!directories.has(dirPrefix)) {
@@ -739,7 +782,7 @@ export class LocalDriver implements StorageDriver {
739
782
  }
740
783
 
741
784
  /** Build a metadata snapshot from a cheap `list()` entry (no extra stat). */
742
- #entryMetadata(entry: StorageEntry): Metadata {
785
+ async #entryMetadata(entry: StorageEntry): Promise<Metadata> {
743
786
  const mimeType = inferMimeType(path.extname(entry.path).toLowerCase());
744
787
  return {
745
788
  size: entry.size,
@@ -748,19 +791,24 @@ export class LocalDriver implements StorageDriver {
748
791
  contentType: mimeType,
749
792
  lastModified: entry.lastModified,
750
793
  etag: "",
751
- visibility: this.#readVisibility(entry.path),
794
+ visibility: await this.#readVisibility(entry.path),
752
795
  };
753
796
  }
754
797
 
755
798
  async *list(prefix: string): AsyncIterable<StorageEntry> {
756
- if (!fs.existsSync(this.#root)) return;
757
- // `recursive: true` on readdirSync gives us every descendant in
758
- // one call; `withFileTypes: true` lets us skip directories and
759
- // inspect each entry without a follow-up stat for type.
760
- const entries = fs.readdirSync(this.#root, {
761
- recursive: true,
762
- withFileTypes: true,
763
- });
799
+ // `recursive: true` gives us every descendant in one call;
800
+ // `withFileTypes: true` lets us skip directories and inspect each
801
+ // entry without a follow-up stat for type.
802
+ let entries: fs.Dirent[];
803
+ try {
804
+ entries = await fsp.readdir(this.#root, {
805
+ recursive: true,
806
+ withFileTypes: true,
807
+ });
808
+ } catch (err) {
809
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return;
810
+ throw err;
811
+ }
764
812
  for (const entry of entries) {
765
813
  if (!entry.isFile()) continue;
766
814
  // `parentPath` is typed on Dirent since Node 20.12, which the engine
@@ -773,12 +821,28 @@ export class LocalDriver implements StorageDriver {
773
821
  // Exclude sidecars — implementation detail.
774
822
  if (rel.endsWith(VISIBILITY_SIDECAR_SUFFIX)) continue;
775
823
  if (!rel.startsWith(prefix)) continue;
776
- const stat = fs.statSync(full);
824
+ const stat = await fsp.stat(full);
777
825
  yield { path: rel, size: stat.size, lastModified: stat.mtime };
778
826
  }
779
827
  }
780
828
  }
781
829
 
830
+ /**
831
+ * Whether a path exists, without `existsSync` blocking the event loop.
832
+ *
833
+ * Used only where the answer is genuinely needed on its own; where a read or
834
+ * unlink follows, the operation's own ENOENT answers it in one syscall and
835
+ * without the window between the two.
836
+ */
837
+ async function exists(target: string): Promise<boolean> {
838
+ try {
839
+ await fsp.access(target);
840
+ return true;
841
+ } catch {
842
+ return false;
843
+ }
844
+ }
845
+
782
846
  /** A local path, given either plainly or as a `file:` URL. */
783
847
  function localPath(source: string | URL): string {
784
848
  return source instanceof URL ? url.fileURLToPath(source) : source;
@@ -890,7 +954,7 @@ export class StorageManager {
890
954
  return this.#driver.get(filePath);
891
955
  }
892
956
 
893
- /** Contents as a `Uint8Array`. Throws `ARCHIVE_NOT_FOUND` if absent. */
957
+ /** Contents as a `Uint8Array`. Throws `E_ARCHIVE_NOT_FOUND` if absent. */
894
958
  getBytes(filePath: string): Promise<Uint8Array> {
895
959
  return this.#driver.getBytes(filePath);
896
960
  }
package/src/etag.ts ADDED
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Entity tags for static responses.
3
+ *
4
+ * Two rules from RFC 9110 that a hand-rolled digest tends to miss, and that
5
+ * both cost a conditional request when missed:
6
+ *
7
+ * - §8.8.3 — an entity-tag IS a quoted string. A bare hex digest is not one,
8
+ * and a strict cache is entitled to ignore it, which turns every
9
+ * revalidation back into a full transfer.
10
+ * - §13.1.2 — `If-None-Match` is a LIST, compared with the WEAK comparison
11
+ * function, so `W/"x"` and `"x"` match. Raw equality against the whole
12
+ * header value fails a client that sends two tags, and fails every client
13
+ * that sends back the weak form of a strong tag.
14
+ *
15
+ * Archive is agnostic, so this lives here rather than being imported from the
16
+ * framework; `@c9up/ream` carries the same two rules in its own `http/etag`.
17
+ */
18
+
19
+ /**
20
+ * The tag for a file, from its metadata rather than its bytes.
21
+ *
22
+ * `W/"<size hex>-<mtime hex>"`, which is what the `etag` package produces for
23
+ * a `Stats` and therefore what every static file server people have cached
24
+ * against emits. Weak because it is derived from metadata: two files with the
25
+ * same size and mtime are equivalent for caching, not provably identical.
26
+ */
27
+ export function statTag(stat: { size: number; mtimeMs: number }): string {
28
+ return `W/"${stat.size.toString(16)}-${Math.floor(stat.mtimeMs).toString(16)}"`;
29
+ }
30
+
31
+ /** Whether `If-None-Match` covers `tag` (RFC 9110 §13.1.2). */
32
+ export function matchesIfNoneMatch(
33
+ header: string | undefined,
34
+ tag: string,
35
+ ): boolean {
36
+ if (!header || tag === "") return false;
37
+ if (header.trim() === "*") return true;
38
+ const bare = (value: string): string =>
39
+ value.startsWith("W/") ? value.slice(2) : value;
40
+ const current = bare(tag);
41
+ return header
42
+ .split(",")
43
+ .some((candidate) => bare(candidate.trim()) === current);
44
+ }