@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
package/src/index.ts ADDED
@@ -0,0 +1,41 @@
1
+ /**
2
+ * @c9up/archive — File storage abstraction for the Ream framework.
3
+ *
4
+ * Drivers:
5
+ * - LocalDriver (filesystem)
6
+ * - S3Driver (S3 / R2 / MinIO via SigV4)
7
+ *
8
+ * Plus a StaticMiddleware for serving files over HTTP and a
9
+ * signed-route handler for serving HMAC-signed Local URLs.
10
+ */
11
+
12
+ export { ArchiveError } from "./errors.js";
13
+ export {
14
+ type GcsConfig,
15
+ GcsDriver,
16
+ type GcsServiceAccount,
17
+ } from "./GcsDriver.js";
18
+ export { type S3Config, S3Driver } from "./S3Driver.js";
19
+ export {
20
+ type StaticConfig,
21
+ StaticMiddleware,
22
+ type StaticMiddlewareHttpContext,
23
+ type StaticMiddlewareResponse,
24
+ } from "./StaticMiddleware.js";
25
+ export {
26
+ LocalDriver,
27
+ type LocalDriverOptions,
28
+ type Metadata,
29
+ type PutStreamOptions,
30
+ type SignedUrlOptions,
31
+ type StorageDriver,
32
+ type StorageEntry,
33
+ StorageManager,
34
+ type Visibility,
35
+ } from "./StorageManager.js";
36
+ export {
37
+ createSignedRouteHandler,
38
+ type SignedRouteHttpContext,
39
+ type SignedRouteOptions,
40
+ type SignedRouteResponse,
41
+ } from "./signed-route.js";
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Shared MIME-type table used by `StaticMiddleware` and the signed-route
3
+ * handler. Keeping a single table avoids drift between the two code
4
+ * paths that serve files from disk.
5
+ */
6
+
7
+ export const MIME_TYPES: Record<string, string> = {
8
+ ".avif": "image/avif",
9
+ ".css": "text/css",
10
+ ".eot": "application/vnd.ms-fontobject",
11
+ ".gif": "image/gif",
12
+ ".html": "text/html",
13
+ ".ico": "image/x-icon",
14
+ ".jpeg": "image/jpeg",
15
+ ".jpg": "image/jpeg",
16
+ ".js": "application/javascript",
17
+ ".json": "application/json",
18
+ ".map": "application/json",
19
+ ".mjs": "application/javascript",
20
+ ".mp3": "audio/mpeg",
21
+ ".mp4": "video/mp4",
22
+ ".ogg": "audio/ogg",
23
+ ".pdf": "application/pdf",
24
+ ".png": "image/png",
25
+ ".svg": "image/svg+xml",
26
+ ".ttf": "font/ttf",
27
+ ".txt": "text/plain",
28
+ ".wasm": "application/wasm",
29
+ ".webm": "video/webm",
30
+ ".webp": "image/webp",
31
+ ".woff": "font/woff",
32
+ ".woff2": "font/woff2",
33
+ ".xml": "application/xml",
34
+ ".zip": "application/zip",
35
+ };
36
+
37
+ /**
38
+ * Extensions served by the static middleware by default. Derived from
39
+ * {@link MIME_TYPES} so new entries auto-apply — no drift possible.
40
+ * Sorted deterministically via `localeCompare` for stable snapshots.
41
+ */
42
+ export const DEFAULT_EXTENSIONS: readonly string[] = Object.keys(
43
+ MIME_TYPES,
44
+ ).sort((a, b) => a.localeCompare(b));
45
+
46
+ /** Resolve a file extension (including the dot, lowercase) to a MIME
47
+ * type. Falls back to `application/octet-stream` for unknown
48
+ * extensions — the caller decides whether that's acceptable. */
49
+ export function inferMimeType(ext: string): string {
50
+ return MIME_TYPES[ext] ?? "application/octet-stream";
51
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Default `StorageManager` singleton — mirror of Adonis's
3
+ * `import drive from '@adonisjs/drive/services/main'` shape.
4
+ *
5
+ * import storage from '@c9up/archive/services/main'
6
+ *
7
+ * await storage.put('uploads/avatar.png', buffer)
8
+ * const bytes = await storage.get('uploads/avatar.png')
9
+ *
10
+ * Populated by `ArchiveProvider.boot()`.
11
+ */
12
+
13
+ import type { StorageManager } from "../StorageManager.js";
14
+
15
+ let instance: StorageManager | undefined;
16
+
17
+ /** @internal Bind the singleton (called by ArchiveProvider). */
18
+ export function setStorage(value: StorageManager): void {
19
+ instance = value;
20
+ }
21
+
22
+ /** @internal Read the singleton (or `undefined` pre-boot). */
23
+ export function getStorage(): StorageManager | undefined {
24
+ return instance;
25
+ }
26
+
27
+ const storage: StorageManager = new Proxy({} as StorageManager, {
28
+ get(_target, prop) {
29
+ if (!instance) {
30
+ throw new Error(
31
+ "[archive] StorageManager singleton accessed before ArchiveProvider.boot() ran. " +
32
+ "Check that `@c9up/archive/provider` is listed in your reamrc.ts providers, " +
33
+ "and that an `archive` config block is set.",
34
+ );
35
+ }
36
+ const value = Reflect.get(instance, prop, instance);
37
+ return typeof value === "function" ? value.bind(instance) : value;
38
+ },
39
+ });
40
+
41
+ export default storage;
@@ -0,0 +1,223 @@
1
+ /**
2
+ * Signed-URL middleware for the Local storage driver.
3
+ *
4
+ * Verifies the HMAC produced by {@link LocalDriver.getSignedUrl} and,
5
+ * on success, serves the file from the driver. Tampered signatures →
6
+ * 403 `E_INVALID_SIGNATURE`. Expired `exp` → 403 `E_EXPIRED_SIGNATURE`.
7
+ * Missing query params → falls through to `next()` so unsigned routes
8
+ * can coexist on the same prefix.
9
+ *
10
+ * @implements Story 43.2 AC 5
11
+ */
12
+
13
+ import { createHmac, timingSafeEqual } from "node:crypto";
14
+ import * as path from "node:path";
15
+ import { inferMimeType } from "./mime-types.js";
16
+ import type { LocalDriver, StorageManager } from "./StorageManager.js";
17
+
18
+ /**
19
+ * Minimal request/response contract the signed-route handler needs.
20
+ * Matches Ream's `HttpContext` structurally — the Ream HttpContext
21
+ * naturally satisfies it via structural subtyping — but avoids
22
+ * importing the concrete Ream type, which keeps the coupling light
23
+ * and lets tests build plain-object mocks without double-casts.
24
+ */
25
+ export interface SignedRouteResponse {
26
+ status(code: number): SignedRouteResponse;
27
+ header(name: string, value: string): SignedRouteResponse;
28
+ sendBuffer(buf: Buffer): void;
29
+ json(data: unknown): void;
30
+ }
31
+
32
+ export interface SignedRouteHttpContext {
33
+ request: {
34
+ method(): string;
35
+ path(): string;
36
+ /**
37
+ * Parsed query string as an object — matches Ream's real
38
+ * `Request.qs()` contract (which returns
39
+ * `Record<string, unknown>`). The middleware pulls `exp` and
40
+ * `sig` by key; this is why the earlier string-returning
41
+ * variant silently bypassed verification in production.
42
+ */
43
+ qs?(): Record<string, unknown>;
44
+ header(name: string): string | undefined;
45
+ };
46
+ response: SignedRouteResponse;
47
+ }
48
+
49
+ export interface SignedRouteOptions {
50
+ storage: StorageManager;
51
+ /**
52
+ * The LocalDriver instance that produced the signatures. The
53
+ * middleware reads its HMAC secret via `getSigningSecret()` to
54
+ * recompute the expected signature.
55
+ */
56
+ driver: LocalDriver;
57
+ /** URL prefix for signed file serving (default: `/storage`). Must
58
+ * match the prefix used by `LocalDriver.url()`. */
59
+ prefix?: string;
60
+ }
61
+
62
+ type SignedRouteMiddleware = (
63
+ ctx: SignedRouteHttpContext,
64
+ next: () => Promise<void>,
65
+ ) => Promise<void>;
66
+
67
+ /**
68
+ * Build an async Ream middleware that verifies HMAC-signed URLs
69
+ * generated by `LocalDriver.getSignedUrl`.
70
+ */
71
+ export function createSignedRouteHandler(
72
+ options: SignedRouteOptions,
73
+ ): SignedRouteMiddleware {
74
+ const prefix = options.prefix ?? "/storage";
75
+ if (prefix === "") {
76
+ throw new Error(
77
+ "createSignedRouteHandler: prefix cannot be empty. Use '/storage' (default) or a specific path.",
78
+ );
79
+ }
80
+ const secret = options.driver.getSigningSecret();
81
+ if (secret === null) {
82
+ throw new Error(
83
+ "createSignedRouteHandler: driver has no signingSecret configured. Pass { signingSecret } to LocalDriver first.",
84
+ );
85
+ }
86
+ const storage = options.storage;
87
+
88
+ return async (ctx, next) => {
89
+ if (ctx.request.method() !== "GET" && ctx.request.method() !== "HEAD") {
90
+ return next();
91
+ }
92
+
93
+ const reqPath = ctx.request.path();
94
+ if (!reqPath.startsWith(prefix)) return next();
95
+ const after = reqPath[prefix.length];
96
+ if (after !== undefined && after !== "/") return next();
97
+
98
+ // Extract filePath from the URL — URL-DECODED so it matches
99
+ // what the signer used. `LocalDriver.getSignedUrl` encodes each
100
+ // path segment; we decode here before recomputing the HMAC.
101
+ const encodedPath = reqPath.slice(prefix.length).replace(/^\//, "");
102
+ if (encodedPath === "") return next();
103
+ let filePath: string;
104
+ try {
105
+ filePath = decodeSegments(encodedPath);
106
+ } catch {
107
+ ctx.response.status(403).json({
108
+ error: { code: "E_INVALID_SIGNATURE", message: "Malformed path" },
109
+ });
110
+ return;
111
+ }
112
+
113
+ // Pull `exp`/`sig` from the parsed query object — matches
114
+ // Ream's `Request.qs()` contract (`Record<string, unknown>`).
115
+ const qs = readQueryObject(ctx);
116
+ const expRaw = readStringParam(qs, "exp");
117
+ const sigHex = readStringParam(qs, "sig");
118
+ if (expRaw === null || sigHex === null) {
119
+ // No signature present — hand off to the next middleware so
120
+ // unsigned routes (e.g. StaticMiddleware) can handle it.
121
+ return next();
122
+ }
123
+
124
+ // Validate sig shape up-front: 64 hex chars (sha256). Rejects
125
+ // truncated/garbage sigs with a distinct code before we hit the
126
+ // HMAC path. `Buffer.from(x, 'hex')` silently truncates invalid
127
+ // input, so relying on length-after-decode is the wrong guard.
128
+ if (!/^[a-f0-9]{64}$/.test(sigHex)) {
129
+ ctx.response.status(403).json({
130
+ error: {
131
+ code: "E_INVALID_SIGNATURE",
132
+ message: "Malformed signature",
133
+ },
134
+ });
135
+ return;
136
+ }
137
+
138
+ // Strict canonical decimal: parseInt accepts trailing garbage,
139
+ // signs, leading whitespace, etc., which would let multiple
140
+ // `expRaw` query-strings collide on the same valid signature.
141
+ const exp = Number.parseInt(expRaw, 10);
142
+ if (!/^\d+$/.test(expRaw) || !Number.isFinite(exp)) {
143
+ ctx.response.status(403).json({
144
+ error: { code: "E_INVALID_SIGNATURE", message: "Malformed expiry" },
145
+ });
146
+ return;
147
+ }
148
+
149
+ // Constant-time HMAC verification on the decoded path. The regex
150
+ // check above already guarantees 32 bytes, so `timingSafeEqual`
151
+ // cannot throw on a length mismatch here. Run BEFORE the expiry
152
+ // check so the response time cannot leak whether a sig was valid
153
+ // for an expired URL versus invalid for a fresh one.
154
+ const expected = createHmac("sha256", secret)
155
+ .update(`${filePath}\n${exp}`)
156
+ .digest();
157
+ const provided = Buffer.from(sigHex, "hex");
158
+ if (!timingSafeEqual(provided, expected)) {
159
+ ctx.response.status(403).json({
160
+ error: { code: "E_INVALID_SIGNATURE", message: "Invalid signature" },
161
+ });
162
+ return;
163
+ }
164
+
165
+ if (exp * 1000 <= Date.now()) {
166
+ ctx.response.status(403).json({
167
+ error: { code: "E_EXPIRED_SIGNATURE", message: "Signed URL expired" },
168
+ });
169
+ return;
170
+ }
171
+
172
+ // Signature verified — serve the file.
173
+ const content = await storage.get(filePath);
174
+ if (content === null) {
175
+ ctx.response
176
+ .status(404)
177
+ .json({ error: { code: "E_NOT_FOUND", message: "File not found" } });
178
+ return;
179
+ }
180
+ const ext = path.extname(filePath).toLowerCase();
181
+ ctx.response.header("Content-Type", inferMimeType(ext));
182
+ ctx.response.header("Content-Length", String(content.length));
183
+ if (ctx.request.method() === "HEAD") {
184
+ ctx.response.status(200);
185
+ return;
186
+ }
187
+ ctx.response.status(200).sendBuffer(content);
188
+ };
189
+ }
190
+
191
+ /**
192
+ * Read the parsed query object from the HttpContext. Matches Ream's
193
+ * `Request.qs()` contract (object). Returns an empty object when the
194
+ * adapter does not expose `qs()` — in that rare case every request
195
+ * will fall through to `next()`, which is the safe behaviour.
196
+ */
197
+ function readQueryObject(ctx: SignedRouteHttpContext): Record<string, unknown> {
198
+ if (typeof ctx.request.qs === "function") {
199
+ return ctx.request.qs();
200
+ }
201
+ return {};
202
+ }
203
+
204
+ /** Read a query param as string, or return `null` if absent / non-string. */
205
+ function readStringParam(
206
+ qs: Record<string, unknown>,
207
+ key: string,
208
+ ): string | null {
209
+ const raw = qs[key];
210
+ return typeof raw === "string" ? raw : null;
211
+ }
212
+
213
+ /**
214
+ * Decode each URL-encoded path segment. Throws if any segment
215
+ * contains invalid percent-escapes (`decodeURIComponent` throws on
216
+ * malformed input).
217
+ */
218
+ function decodeSegments(encodedPath: string): string {
219
+ return encodedPath
220
+ .split("/")
221
+ .map((seg) => decodeURIComponent(seg))
222
+ .join("/");
223
+ }