@c9up/archive 0.1.3

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 (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +35 -0
  3. package/dist/ArchiveProvider.d.ts +32 -0
  4. package/dist/ArchiveProvider.d.ts.map +1 -0
  5. package/dist/ArchiveProvider.js +91 -0
  6. package/dist/ArchiveProvider.js.map +1 -0
  7. package/dist/GcsDriver.d.ts +41 -0
  8. package/dist/GcsDriver.d.ts.map +1 -0
  9. package/dist/GcsDriver.js +387 -0
  10. package/dist/GcsDriver.js.map +1 -0
  11. package/dist/S3Driver.d.ts +50 -0
  12. package/dist/S3Driver.d.ts.map +1 -0
  13. package/dist/S3Driver.js +642 -0
  14. package/dist/S3Driver.js.map +1 -0
  15. package/dist/StaticMiddleware.d.ts +46 -0
  16. package/dist/StaticMiddleware.d.ts.map +1 -0
  17. package/dist/StaticMiddleware.js +121 -0
  18. package/dist/StaticMiddleware.js.map +1 -0
  19. package/dist/StorageManager.d.ts +178 -0
  20. package/dist/StorageManager.d.ts.map +1 -0
  21. package/dist/StorageManager.js +405 -0
  22. package/dist/StorageManager.js.map +1 -0
  23. package/dist/errors.d.ts +11 -0
  24. package/dist/errors.d.ts.map +1 -0
  25. package/dist/errors.js +14 -0
  26. package/dist/errors.js.map +1 -0
  27. package/dist/expiry.d.ts +15 -0
  28. package/dist/expiry.d.ts.map +1 -0
  29. package/dist/expiry.js +26 -0
  30. package/dist/expiry.js.map +1 -0
  31. package/dist/index.d.ts +17 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +17 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/mime-types.d.ts +17 -0
  36. package/dist/mime-types.d.ts.map +1 -0
  37. package/dist/mime-types.js +47 -0
  38. package/dist/mime-types.js.map +1 -0
  39. package/dist/services/main.d.ts +19 -0
  40. package/dist/services/main.d.ts.map +1 -0
  41. package/dist/services/main.js +33 -0
  42. package/dist/services/main.js.map +1 -0
  43. package/dist/signed-route.d.ts +61 -0
  44. package/dist/signed-route.d.ts.map +1 -0
  45. package/dist/signed-route.js +155 -0
  46. package/dist/signed-route.js.map +1 -0
  47. package/dist/testing/FakeStorage.d.ts +72 -0
  48. package/dist/testing/FakeStorage.d.ts.map +1 -0
  49. package/dist/testing/FakeStorage.js +266 -0
  50. package/dist/testing/FakeStorage.js.map +1 -0
  51. package/package.json +67 -0
  52. package/src/ArchiveProvider.ts +134 -0
  53. package/src/GcsDriver.ts +490 -0
  54. package/src/S3Driver.ts +791 -0
  55. package/src/StaticMiddleware.ts +175 -0
  56. package/src/StorageManager.ts +627 -0
  57. package/src/errors.ts +14 -0
  58. package/src/expiry.ts +41 -0
  59. package/src/index.ts +41 -0
  60. package/src/mime-types.ts +51 -0
  61. package/src/services/main.ts +41 -0
  62. package/src/signed-route.ts +223 -0
  63. package/src/testing/FakeStorage.ts +372 -0
@@ -0,0 +1,627 @@
1
+ /**
2
+ * Storage — file storage abstraction with driver pattern.
3
+ *
4
+ * @implements MISS-24
5
+ */
6
+
7
+ import { createHash, createHmac } from "node:crypto";
8
+ import * as fs from "node:fs";
9
+ import * as path from "node:path";
10
+ import { pipeline } from "node:stream/promises";
11
+ import { ArchiveError } from "./errors.js";
12
+ import { assertValidExpiry, DEFAULT_EXPIRES_IN } from "./expiry.js";
13
+ import { inferMimeType } from "./mime-types.js";
14
+
15
+ /** Options for {@link StorageDriver.getSignedUrl}. */
16
+ export interface SignedUrlOptions {
17
+ /** URL lifetime in seconds. Default: 300 (5 minutes). Bounds: 1–604800. */
18
+ expiresIn?: number;
19
+ }
20
+
21
+ /** Options for {@link StorageDriver.putStream}. */
22
+ export interface PutStreamOptions {
23
+ /** MIME type — sent as unsigned `Content-Type` on S3 uploads. Local ignores it. */
24
+ contentType?: string;
25
+ /**
26
+ * Declared byte length. S3 uses this to pick single-PUT (≤ 5 MiB) vs
27
+ * multipart (> 5 MiB). Undefined → always multipart. Local ignores it.
28
+ */
29
+ contentLength?: number;
30
+ }
31
+
32
+ /** Public/private visibility for a stored object. */
33
+ export type Visibility = "public" | "private";
34
+
35
+ /** Suffix appended to the target filename to store its visibility marker
36
+ * on the LocalDriver. Kept as a package-internal constant so the static
37
+ * middleware can exclude it by the same name. */
38
+ export const VISIBILITY_SIDECAR_SUFFIX = ".archive-visibility.json";
39
+
40
+ /**
41
+ * Metadata surfaced by {@link StorageDriver.getMetadata}. Shape is driver-
42
+ * agnostic: S3 returns HEAD-derived values, Local reads `fs.stat` + the
43
+ * MIME table + a sidecar for visibility.
44
+ */
45
+ /** One entry yielded by {@link StorageDriver.list}. */
46
+ export interface StorageEntry {
47
+ /** Full path (includes the prefix argument). */
48
+ path: string;
49
+ /** Size in bytes. */
50
+ size: number;
51
+ /** Last-modified timestamp. */
52
+ lastModified: Date;
53
+ }
54
+
55
+ export interface Metadata {
56
+ /** Size in bytes. */
57
+ size: number;
58
+ /** Content type. Driver-inferred for Local (extension-based), server-
59
+ * reported for S3. Falls back to `application/octet-stream`. */
60
+ mimeType: string;
61
+ /** Last-modified timestamp as a `Date` — not a string, not epoch ms. */
62
+ lastModified: Date;
63
+ /** Strong or weak ETag with surrounding quotes stripped. `W/` prefix
64
+ * is preserved when the origin reports a weak tag. */
65
+ etag: string;
66
+ /** Public/private visibility. Missing-sidecar on Local = `'public'`. */
67
+ visibility: Visibility;
68
+ }
69
+
70
+ /**
71
+ * StorageDriver contract — frozen at v1.0 (Epic 43, 2026-05-05).
72
+ *
73
+ * Driver authors implement this interface verbatim. The interface is treated
74
+ * as a stable contract: new methods are NOT added without a version-bump + a
75
+ * 2-epic deprecation window. Optional fields are added in minor versions.
76
+ * Method signatures never change in-place — a renamed method ships as a new
77
+ * method + the old one delegating, deprecated for ≥1 epic.
78
+ */
79
+ export interface StorageDriver {
80
+ put(filePath: string, content: Buffer | string): Promise<void>;
81
+ /**
82
+ * Upload from a readable stream. Local pipes to disk; S3 uses
83
+ * single-PUT if `contentLength ≤ 5 MiB`, otherwise multipart.
84
+ */
85
+ putStream(
86
+ filePath: string,
87
+ readable: NodeJS.ReadableStream,
88
+ options?: PutStreamOptions,
89
+ ): Promise<void>;
90
+ get(filePath: string): Promise<Buffer | null>;
91
+ /**
92
+ * Download as a readable stream. Throws `ARCHIVE_NOT_FOUND` when
93
+ * the object is missing — streams can't express absence as a value.
94
+ */
95
+ getStream(filePath: string): Promise<NodeJS.ReadableStream>;
96
+ delete(filePath: string): Promise<boolean>;
97
+ exists(filePath: string): Promise<boolean>;
98
+ /**
99
+ * Visibility-aware URL. `public` → {@link publicUrl}, `private` →
100
+ * {@link getSignedUrl} (default 5 min expiry). Async because reading
101
+ * visibility may require a driver round-trip (S3 GET ?acl).
102
+ */
103
+ url(filePath: string): Promise<string>;
104
+ /**
105
+ * Unsigned, direct URL that ignores visibility. Useful when the
106
+ * caller already knows the object is public or wants to build a
107
+ * template before visibility is set.
108
+ */
109
+ publicUrl(filePath: string): string;
110
+ /**
111
+ * Return a time-boxed URL that grants read access to `filePath`.
112
+ * Implementations must validate `options.expiresIn` via
113
+ * {@link assertValidExpiry} and reject out-of-range values with
114
+ * `ARCHIVE_INVALID_EXPIRY`.
115
+ */
116
+ getSignedUrl(
117
+ filePath: string,
118
+ options?: SignedUrlOptions,
119
+ ): string | Promise<string>;
120
+ /**
121
+ * Resolve object metadata. Throws `ArchiveError('ARCHIVE_NOT_FOUND', ...)`
122
+ * when the object does not exist.
123
+ */
124
+ getMetadata(filePath: string): Promise<Metadata>;
125
+ /**
126
+ * Set `public` / `private` visibility. Idempotent — re-applying the
127
+ * same visibility succeeds silently.
128
+ */
129
+ setVisibility(filePath: string, visibility: Visibility): Promise<void>;
130
+ /**
131
+ * Duplicate an object. Throws `ARCHIVE_NOT_FOUND` if `from` is
132
+ * missing. Target is overwritten if it exists. Visibility is NOT
133
+ * carried over — the new object takes default visibility.
134
+ */
135
+ copy(from: string, to: string): Promise<void>;
136
+ /**
137
+ * Relocate an object. Equivalent to `copy` + `delete` on cloud
138
+ * drivers (non-atomic between the two steps); atomic `rename` on
139
+ * Local. Visibility IS preserved because identity is preserved.
140
+ */
141
+ move(from: string, to: string): Promise<void>;
142
+ /**
143
+ * Yield one {@link StorageEntry} per object whose path starts with
144
+ * `prefix`. Pagination (S3/GCS) and filesystem walk (Local) happen
145
+ * lazily — callers can `break` early and no further requests are
146
+ * issued.
147
+ */
148
+ list(prefix: string): AsyncIterable<StorageEntry>;
149
+ }
150
+
151
+ export interface LocalDriverOptions {
152
+ /**
153
+ * HMAC-SHA256 secret used by {@link LocalDriver.getSignedUrl}.
154
+ * When omitted, signing is disabled and `getSignedUrl` throws
155
+ * `ARCHIVE_SIGNING_DISABLED`. The non-signing methods
156
+ * (`put`/`get`/`delete`/`exists`/`url`) work either way.
157
+ */
158
+ signingSecret?: string;
159
+ }
160
+
161
+ export class LocalDriver implements StorageDriver {
162
+ #root: string;
163
+ #signingSecret: string | null;
164
+
165
+ constructor(root: string, options?: LocalDriverOptions) {
166
+ const resolved = path.resolve(root);
167
+ if (!fs.existsSync(resolved)) {
168
+ fs.mkdirSync(resolved, { recursive: true });
169
+ }
170
+ // Canonicalise the root once so subsequent realpath-based
171
+ // escape checks compare apples to apples.
172
+ this.#root = fs.realpathSync(resolved);
173
+ const secret = options?.signingSecret;
174
+ if (secret !== undefined) {
175
+ // Empty or trivially short secrets defeat the whole point of
176
+ // HMAC signing. 16 bytes is the floor: rejects obviously weak
177
+ // values without being annoyingly strict about format.
178
+ if (typeof secret !== "string" || secret.length < 16) {
179
+ throw new ArchiveError(
180
+ "ARCHIVE_WEAK_SIGNING_SECRET",
181
+ `LocalDriver signingSecret must be a string of at least 16 chars (got length ${typeof secret === "string" ? secret.length : "non-string"})`,
182
+ {
183
+ hint: "Use a cryptographically random secret, e.g. `crypto.randomBytes(32).toString('hex')`.",
184
+ },
185
+ );
186
+ }
187
+ }
188
+ this.#signingSecret = secret ?? null;
189
+ }
190
+
191
+ /**
192
+ * Resolve and validate a file path — prevents traversal outside
193
+ * the root, INCLUDING via symlinks planted inside the root.
194
+ *
195
+ * For existing files the check walks `fs.realpathSync(full)` to
196
+ * defeat symlink redirection. For new writes (target doesn't exist
197
+ * yet) we walk the nearest existing ancestor via `realpathSync` so
198
+ * an attacker who planted a symlink at `<root>/evil -> /etc`
199
+ * cannot redirect a put through it.
200
+ */
201
+ #safePath(filePath: string): string {
202
+ // Reject control chars that would smuggle HMAC delimiters or
203
+ // confuse path handling. `\n` (10) is the signing payload
204
+ // separator — a filename containing `\n` could otherwise forge
205
+ // `exp`. `\r` (13) and NUL (0) round out the trio.
206
+ for (let i = 0; i < filePath.length; i++) {
207
+ const code = filePath.charCodeAt(i);
208
+ if (code === 0 || code === 10 || code === 13) {
209
+ throw new Error(
210
+ "Invalid filePath: control characters (NUL, LF, CR) are not allowed",
211
+ );
212
+ }
213
+ }
214
+ const full = path.resolve(this.#root, filePath);
215
+ // Lexical guard first — cheap and covers the `..` case.
216
+ if (!full.startsWith(this.#root + path.sep) && full !== this.#root) {
217
+ throw new Error(
218
+ `Path traversal blocked: '${filePath}' resolves outside storage root`,
219
+ );
220
+ }
221
+ // Realpath guard — walk up to the nearest existing ancestor and
222
+ // confirm its canonical form is still under root.
223
+ let probe = full;
224
+ while (!fs.existsSync(probe)) {
225
+ const parent = path.dirname(probe);
226
+ if (parent === probe) break;
227
+ probe = parent;
228
+ }
229
+ const realProbe = fs.realpathSync(probe);
230
+ if (
231
+ !realProbe.startsWith(this.#root + path.sep) &&
232
+ realProbe !== this.#root
233
+ ) {
234
+ throw new Error(
235
+ `Path traversal blocked: '${filePath}' resolves outside storage root via symlink`,
236
+ );
237
+ }
238
+ return full;
239
+ }
240
+
241
+ async put(filePath: string, content: Buffer | string): Promise<void> {
242
+ const full = this.#safePath(filePath);
243
+ const dir = path.dirname(full);
244
+ if (!fs.existsSync(dir)) {
245
+ fs.mkdirSync(dir, { recursive: true });
246
+ }
247
+ fs.writeFileSync(full, content);
248
+ }
249
+
250
+ async putStream(
251
+ filePath: string,
252
+ readable: NodeJS.ReadableStream,
253
+ // LocalDriver ignores contentType (inferred from extension via
254
+ // getMetadata) and contentLength (FS knows its own size).
255
+ _options?: PutStreamOptions,
256
+ ): Promise<void> {
257
+ const full = this.#safePath(filePath);
258
+ const dir = path.dirname(full);
259
+ if (!fs.existsSync(dir)) {
260
+ fs.mkdirSync(dir, { recursive: true });
261
+ }
262
+ // `pipeline` propagates errors and destroys the write target on
263
+ // failure — no manual cleanup needed.
264
+ await pipeline(readable, fs.createWriteStream(full));
265
+ }
266
+
267
+ async get(filePath: string): Promise<Buffer | null> {
268
+ const full = this.#safePath(filePath);
269
+ if (!fs.existsSync(full)) return null;
270
+ return fs.readFileSync(full);
271
+ }
272
+
273
+ async getStream(filePath: string): Promise<NodeJS.ReadableStream> {
274
+ const full = this.#safePath(filePath);
275
+ if (!fs.existsSync(full)) {
276
+ throw new ArchiveError(
277
+ "ARCHIVE_NOT_FOUND",
278
+ `File does not exist at path '${filePath}'`,
279
+ { hint: "Confirm the path and that the file was put() first." },
280
+ );
281
+ }
282
+ return fs.createReadStream(full);
283
+ }
284
+
285
+ async delete(filePath: string): Promise<boolean> {
286
+ const full = this.#safePath(filePath);
287
+ if (!fs.existsSync(full)) return false;
288
+ fs.unlinkSync(full);
289
+ // Sidecar cleanup is best-effort. The main file is already gone
290
+ // — any sidecar failure (ENOENT, EACCES, EPERM) would corrupt
291
+ // the `delete` contract if we threw here (caller would see a
292
+ // rejected Promise AFTER the file was already deleted).
293
+ const sidecar = full + VISIBILITY_SIDECAR_SUFFIX;
294
+ try {
295
+ fs.unlinkSync(sidecar);
296
+ } catch {
297
+ // swallow: cleanup is best-effort.
298
+ }
299
+ return true;
300
+ }
301
+
302
+ async exists(filePath: string): Promise<boolean> {
303
+ // Sidecars are an implementation detail — pretend they don't
304
+ // exist from the public API's point of view.
305
+ if (filePath.endsWith(VISIBILITY_SIDECAR_SUFFIX)) return false;
306
+ return fs.existsSync(this.#safePath(filePath));
307
+ }
308
+
309
+ publicUrl(filePath: string): string {
310
+ // Encode each segment so special chars (`?`, `#`, spaces, unicode)
311
+ // survive the trip through an HTTP layer. The middleware mirrors
312
+ // this by decoding each segment before recomputing the HMAC —
313
+ // skipping encoding here would leave the URL unparseable.
314
+ const encoded = filePath
315
+ .split("/")
316
+ .map((seg) => encodeURIComponent(seg))
317
+ .join("/");
318
+ return `/storage/${encoded}`;
319
+ }
320
+
321
+ async url(filePath: string): Promise<string> {
322
+ const visibility = this.#readVisibility(filePath);
323
+ if (visibility === "public") return this.publicUrl(filePath);
324
+ return this.getSignedUrl(filePath);
325
+ }
326
+
327
+ async getMetadata(filePath: string): Promise<Metadata> {
328
+ const full = this.#safePath(filePath);
329
+ let stat: fs.Stats;
330
+ try {
331
+ stat = fs.statSync(full);
332
+ } catch (err) {
333
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") {
334
+ throw new ArchiveError(
335
+ "ARCHIVE_NOT_FOUND",
336
+ `File does not exist at path '${filePath}'`,
337
+ { hint: "Confirm the path and that the file was put() first." },
338
+ );
339
+ }
340
+ throw err;
341
+ }
342
+ // Stat-based weak ETag: inode+size+mtime is cheap and matches
343
+ // the behaviour of nginx/Apache for static files. A strong ETag
344
+ // would require reading the full content — not worth it for a
345
+ // HEAD-equivalent call.
346
+ const etagBody = createHash("sha1")
347
+ .update(`${stat.ino}-${stat.size}-${stat.mtimeMs}`)
348
+ .digest("hex");
349
+ return {
350
+ size: stat.size,
351
+ mimeType: inferMimeType(path.extname(filePath).toLowerCase()),
352
+ lastModified: stat.mtime,
353
+ etag: `W/"${etagBody}"`,
354
+ visibility: this.#readVisibility(filePath),
355
+ };
356
+ }
357
+
358
+ async setVisibility(filePath: string, visibility: Visibility): Promise<void> {
359
+ const full = this.#safePath(filePath);
360
+ if (!fs.existsSync(full)) {
361
+ throw new ArchiveError(
362
+ "ARCHIVE_NOT_FOUND",
363
+ `Cannot set visibility — file does not exist at path '${filePath}'`,
364
+ { hint: "put() the file before calling setVisibility()." },
365
+ );
366
+ }
367
+ const sidecar = full + VISIBILITY_SIDECAR_SUFFIX;
368
+ fs.writeFileSync(sidecar, JSON.stringify({ visibility }), { flag: "w" });
369
+ }
370
+
371
+ /**
372
+ * Read the sidecar marker.
373
+ * - Missing sidecar → `'public'` (the documented default; sidecar is only
374
+ * written when `setVisibility('private')` was explicitly called).
375
+ * - Corrupted sidecar (unreadable file / malformed JSON) → THROW. A
376
+ * silent fallback to `'public'` would turn any disk corruption or I/O
377
+ * blip into a private→public downgrade for an existing private file.
378
+ * Refuse to serve undetermined visibility instead.
379
+ */
380
+ #readVisibility(filePath: string): Visibility {
381
+ const sidecar = this.#safePath(filePath) + VISIBILITY_SIDECAR_SUFFIX;
382
+ if (!fs.existsSync(sidecar)) return "public";
383
+ let raw: string;
384
+ try {
385
+ raw = fs.readFileSync(sidecar, "utf8");
386
+ } catch (err) {
387
+ throw new ArchiveError(
388
+ "ARCHIVE_VISIBILITY_CORRUPT",
389
+ `Failed to read visibility sidecar for '${filePath}' (${(err as NodeJS.ErrnoException).code ?? "I/O error"}); refusing to default to 'public'.`,
390
+ {
391
+ hint: "Inspect the sidecar file or re-apply visibility via setVisibility().",
392
+ },
393
+ );
394
+ }
395
+ let parsed: { visibility?: unknown };
396
+ try {
397
+ parsed = JSON.parse(raw) as { visibility?: unknown };
398
+ } catch {
399
+ throw new ArchiveError(
400
+ "ARCHIVE_VISIBILITY_CORRUPT",
401
+ `Sidecar for '${filePath}' is not valid JSON; refusing to default to 'public'.`,
402
+ {
403
+ hint: "Delete the sidecar file and re-apply visibility via setVisibility().",
404
+ },
405
+ );
406
+ }
407
+ return parsed.visibility === "private" ? "private" : "public";
408
+ }
409
+
410
+ getSignedUrl(filePath: string, options?: SignedUrlOptions): string {
411
+ // Fail fast on unsafe paths instead of producing a signed URL that
412
+ // can never be served — `storage.get()` would reject it later via
413
+ // `#safePath`, but signing-time errors are easier to diagnose.
414
+ this.#safePath(filePath);
415
+ const expiresIn = options?.expiresIn ?? DEFAULT_EXPIRES_IN;
416
+ assertValidExpiry(expiresIn);
417
+ const secret = this.#signingSecret;
418
+ if (secret === null) {
419
+ throw new ArchiveError(
420
+ "ARCHIVE_SIGNING_DISABLED",
421
+ "LocalDriver.getSignedUrl requires a signingSecret at construction time",
422
+ {
423
+ hint: "Pass { signingSecret: <hex or random string> } to the LocalDriver constructor, or set config.archive.local.signingSecret. Private files require a signing secret.",
424
+ },
425
+ );
426
+ }
427
+ const exp = Math.floor(Date.now() / 1000) + expiresIn;
428
+ // Newline-delimited payload: a filePath cannot forge `exp` by
429
+ // embedding `&exp=...` in its own bytes (URL-decoding still
430
+ // keeps the literal `\n` separator in the signed material).
431
+ const message = `${filePath}\n${exp}`;
432
+ const sig = createHmac("sha256", secret).update(message).digest("hex");
433
+ return `${this.publicUrl(filePath)}?exp=${exp}&sig=${sig}`;
434
+ }
435
+
436
+ /**
437
+ * @internal Used by the signed-route middleware to re-compute the
438
+ * HMAC server-side. Not part of the public `StorageDriver` contract.
439
+ */
440
+ getSigningSecret(): string | null {
441
+ return this.#signingSecret;
442
+ }
443
+
444
+ async copy(from: string, to: string): Promise<void> {
445
+ const fromFull = this.#safePath(from);
446
+ const toFull = this.#safePath(to);
447
+ if (!fs.existsSync(fromFull)) {
448
+ throw new ArchiveError(
449
+ "ARCHIVE_NOT_FOUND",
450
+ `Cannot copy — source does not exist at path '${from}'`,
451
+ { hint: "Confirm the source path was put() first." },
452
+ );
453
+ }
454
+ const dir = path.dirname(toFull);
455
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
456
+ fs.copyFileSync(fromFull, toFull);
457
+ // Intentionally do NOT copy the visibility sidecar — new object
458
+ // takes default visibility. Documented in the story spec.
459
+ }
460
+
461
+ async move(from: string, to: string): Promise<void> {
462
+ const fromFull = this.#safePath(from);
463
+ const toFull = this.#safePath(to);
464
+ if (!fs.existsSync(fromFull)) {
465
+ throw new ArchiveError(
466
+ "ARCHIVE_NOT_FOUND",
467
+ `Cannot move — source does not exist at path '${from}'`,
468
+ { hint: "Confirm the source path was put() first." },
469
+ );
470
+ }
471
+ // Capture source visibility BEFORE the main move. Re-writing the new
472
+ // sidecar from captured data (instead of renaming the source sidecar)
473
+ // is robust against EXDEV/permission errors that would otherwise
474
+ // silently downgrade private→public. `#readVisibility` throws on
475
+ // corruption, which surfaces here BEFORE we mutate anything.
476
+ const fromSidecar = fromFull + VISIBILITY_SIDECAR_SUFFIX;
477
+ const toSidecar = toFull + VISIBILITY_SIDECAR_SUFFIX;
478
+ const capturedVisibility: Visibility | undefined = fs.existsSync(
479
+ fromSidecar,
480
+ )
481
+ ? this.#readVisibility(from)
482
+ : undefined;
483
+ const dir = path.dirname(toFull);
484
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
485
+ try {
486
+ fs.renameSync(fromFull, toFull);
487
+ } catch (err) {
488
+ // Cross-device rename — fall back to copy+unlink.
489
+ if ((err as NodeJS.ErrnoException).code === "EXDEV") {
490
+ fs.copyFileSync(fromFull, toFull);
491
+ fs.unlinkSync(fromFull);
492
+ } else {
493
+ throw err;
494
+ }
495
+ }
496
+ // Visibility carries forward by re-writing the new sidecar from
497
+ // captured data — atomic relative to the rename, immune to the
498
+ // EXDEV/perm failure modes that plagued the rename-the-sidecar path.
499
+ // Public is the default, so an absent source sidecar means no work.
500
+ if (capturedVisibility !== undefined) {
501
+ try {
502
+ fs.writeFileSync(
503
+ toSidecar,
504
+ JSON.stringify({ visibility: capturedVisibility }),
505
+ { flag: "w" },
506
+ );
507
+ } catch (err) {
508
+ throw new ArchiveError(
509
+ "ARCHIVE_VISIBILITY_MOVE_FAILED",
510
+ `move('${from}' -> '${to}'): main file moved but visibility sidecar write failed (${(err as NodeJS.ErrnoException).code ?? "unknown"}). Target visibility is undefined.`,
511
+ {
512
+ hint: "Re-apply visibility via setVisibility() on the target path.",
513
+ },
514
+ );
515
+ }
516
+ // Best-effort cleanup of the source sidecar — visibility is already
517
+ // preserved on the target side. A failure here leaves a stale
518
+ // sidecar pointing at the now-missing source file; benign.
519
+ if (fs.existsSync(fromSidecar)) {
520
+ try {
521
+ fs.unlinkSync(fromSidecar);
522
+ } catch {
523
+ // benign — source dir may be cleaned up by later operations.
524
+ }
525
+ }
526
+ }
527
+ }
528
+
529
+ async *list(prefix: string): AsyncIterable<StorageEntry> {
530
+ if (!fs.existsSync(this.#root)) return;
531
+ // `recursive: true` on readdirSync gives us every descendant in
532
+ // one call; `withFileTypes: true` lets us skip directories and
533
+ // inspect each entry without a follow-up stat for type.
534
+ const entries = fs.readdirSync(this.#root, {
535
+ recursive: true,
536
+ withFileTypes: true,
537
+ });
538
+ for (const entry of entries) {
539
+ if (!entry.isFile()) continue;
540
+ // Node's readdirSync returns `parentPath` on the Dirent (Node
541
+ // 20.12+); fall back to `path` for older shapes.
542
+ const parent =
543
+ (entry as unknown as { parentPath?: string; path?: string })
544
+ .parentPath ??
545
+ (entry as unknown as { path?: string }).path ??
546
+ this.#root;
547
+ const full = path.join(parent, entry.name);
548
+ const rel = path.relative(this.#root, full).split(path.sep).join("/");
549
+ // Exclude sidecars — implementation detail.
550
+ if (rel.endsWith(VISIBILITY_SIDECAR_SUFFIX)) continue;
551
+ if (!rel.startsWith(prefix)) continue;
552
+ const stat = fs.statSync(full);
553
+ yield { path: rel, size: stat.size, lastModified: stat.mtime };
554
+ }
555
+ }
556
+ }
557
+
558
+ export class StorageManager {
559
+ #driver: StorageDriver;
560
+
561
+ constructor(driver: StorageDriver) {
562
+ this.#driver = driver;
563
+ }
564
+
565
+ put(filePath: string, content: Buffer | string): Promise<void> {
566
+ return this.#driver.put(filePath, content);
567
+ }
568
+
569
+ putStream(
570
+ filePath: string,
571
+ readable: NodeJS.ReadableStream,
572
+ options?: PutStreamOptions,
573
+ ): Promise<void> {
574
+ return this.#driver.putStream(filePath, readable, options);
575
+ }
576
+
577
+ get(filePath: string): Promise<Buffer | null> {
578
+ return this.#driver.get(filePath);
579
+ }
580
+
581
+ getStream(filePath: string): Promise<NodeJS.ReadableStream> {
582
+ return this.#driver.getStream(filePath);
583
+ }
584
+
585
+ delete(filePath: string): Promise<boolean> {
586
+ return this.#driver.delete(filePath);
587
+ }
588
+
589
+ exists(filePath: string): Promise<boolean> {
590
+ return this.#driver.exists(filePath);
591
+ }
592
+
593
+ url(filePath: string): Promise<string> {
594
+ return this.#driver.url(filePath);
595
+ }
596
+
597
+ publicUrl(filePath: string): string {
598
+ return this.#driver.publicUrl(filePath);
599
+ }
600
+
601
+ getSignedUrl(
602
+ filePath: string,
603
+ options?: SignedUrlOptions,
604
+ ): string | Promise<string> {
605
+ return this.#driver.getSignedUrl(filePath, options);
606
+ }
607
+
608
+ getMetadata(filePath: string): Promise<Metadata> {
609
+ return this.#driver.getMetadata(filePath);
610
+ }
611
+
612
+ setVisibility(filePath: string, visibility: Visibility): Promise<void> {
613
+ return this.#driver.setVisibility(filePath, visibility);
614
+ }
615
+
616
+ copy(from: string, to: string): Promise<void> {
617
+ return this.#driver.copy(from, to);
618
+ }
619
+
620
+ move(from: string, to: string): Promise<void> {
621
+ return this.#driver.move(from, to);
622
+ }
623
+
624
+ list(prefix: string): AsyncIterable<StorageEntry> {
625
+ return this.#driver.list(prefix);
626
+ }
627
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * ArchiveError — structured error (agnostic; no @c9up/ream dependency).
3
+ */
4
+ export class ArchiveError extends Error {
5
+ readonly code: string;
6
+ readonly hint?: string;
7
+
8
+ constructor(code: string, message: string, options?: { hint?: string }) {
9
+ super(message);
10
+ this.name = "ArchiveError";
11
+ this.code = code;
12
+ this.hint = options?.hint;
13
+ }
14
+ }
package/src/expiry.ts ADDED
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Shared expiry bounds for signed URLs. Both the S3 and Local drivers
3
+ * enforce the same 1 s – 7 days envelope so surface behaviour stays
4
+ * consistent across backends.
5
+ */
6
+
7
+ import { ArchiveError } from "./errors.js";
8
+
9
+ /** Default expiry for signed URLs when the caller does not specify one. */
10
+ export const DEFAULT_EXPIRES_IN = 300; // 5 minutes
11
+
12
+ /** Maximum allowed expiry (AWS SigV4 cap). */
13
+ export const MAX_EXPIRES_IN = 604_800; // 7 days
14
+
15
+ /**
16
+ * Reject non-finite, zero, negative, or out-of-range expiries. Throws
17
+ * `ARCHIVE_INVALID_EXPIRY` so callers get a typed error with a hint.
18
+ */
19
+ export function assertValidExpiry(expiresIn: number): void {
20
+ if (!Number.isFinite(expiresIn)) {
21
+ throw new ArchiveError(
22
+ "ARCHIVE_INVALID_EXPIRY",
23
+ `Signed-URL expiresIn must be finite, got ${expiresIn}`,
24
+ { hint: "Pass a positive number of seconds between 1 and 604800." },
25
+ );
26
+ }
27
+ if (expiresIn <= 0) {
28
+ throw new ArchiveError(
29
+ "ARCHIVE_INVALID_EXPIRY",
30
+ `Signed-URL expiresIn must be > 0 seconds, got ${expiresIn}`,
31
+ { hint: "Pass a positive number of seconds between 1 and 604800." },
32
+ );
33
+ }
34
+ if (expiresIn > MAX_EXPIRES_IN) {
35
+ throw new ArchiveError(
36
+ "ARCHIVE_INVALID_EXPIRY",
37
+ `Signed-URL expiresIn must be <= ${MAX_EXPIRES_IN} seconds (7 days), got ${expiresIn}`,
38
+ { hint: "AWS SigV4 caps presigned URLs at 7 days." },
39
+ );
40
+ }
41
+ }