@solobrand/storage 0.0.0-stage → 0.1.1

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/README.md CHANGED
@@ -1,3 +1,51 @@
1
- # Temporary Holding Version
1
+ # @solobrand/storage
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Files in the app R2 bucket with signed URLs and limits.
4
+
5
+ Part of the [SoloBrand framework](../../README.md). Public API: the frozen types in `src/index.ts` (see CONTRIBUTING.md).
6
+
7
+ ## Use
8
+
9
+ ```ts
10
+ import { storageProvider, storageToken, userKey, userPrefix, signedFileHandler } from '@solobrand/storage';
11
+
12
+ app.register(storageProvider()); // env.FILES (R2) + env.APP_KEY (32+ random chars)
13
+
14
+ const storage = app.make(storageToken);
15
+ const put = await storage.put(userKey(user.id, 'avatar.png'), request.body!, {
16
+ contentType: request.headers.get('content-type') ?? '',
17
+ accept: ['image/png', 'image/jpeg'],
18
+ maxBytes: 2 * 1024 * 1024,
19
+ });
20
+ if (!put.ok) return put; // validation_failed / payload_too_large, with errors.file
21
+
22
+ const url = await storage.signedUrl(put.value.key, 300); // /files/users/7/avatar.png?expires=…&signature=…
23
+ await storage.list(userPrefix(user.id));
24
+
25
+ router.get('/files/{key...}', signedFileHandler()); // verifies and serves
26
+
27
+ // A file the app decided is public (a published listing's photo): cacheable, same safe headers.
28
+ return servePublic(ctx.request, storage, key, { cache: 'public, max-age=3600' });
29
+ ```
30
+
31
+ ## Rules
32
+
33
+ | Rule | Where |
34
+ |---|---|
35
+ | Keys: no `..` / `.` / empty segments, no leading `/`, no `\`, no `%`, no C0/C1 controls, U+2028/2029 or BOM, ≤ 512 chars, NFC-normalized. Checked on `put`, `get`, `delete`, `signedUrl` and on the decoded path of a signed URL. | `keys.ts` |
36
+ | `userKey(id, name)` → `users/<id>/<name>`; `name` is validated, so it cannot leave the folder. `list('')`, a prefix without a trailing `/` (`users/1` would match `users/10/`, AUD-08) and any invalid prefix throw. | `keys.ts`, `storage.ts` |
37
+ | Size: counted on the bytes that arrive (a `Content-Length` is never trusted); one byte over `maxBytes` (default 10 MiB, hard cap 25 MiB) cancels the source and returns `payload_too_large`. The upload is held in memory once (R2 needs a known length): an in-memory body goes to R2 as is, a streamed one as its chunks through `FixedLengthStream` — never a second concatenated copy (AUD-07). Magic bytes are sniffed from the first 512 bytes only. | `storage.ts` |
38
+ | MIME: the declared type must be in `accept` (default: png, jpeg, gif, webp, pdf, text/plain). `image/*` never matches SVG/HTML/XML/JS; those pass only when named exactly. Declared png/jpeg/gif/webp/pdf must carry their magic bytes; markup under any non-markup type (e.g. SVG as `text/plain`) is refused. | `mime.ts` |
39
+ | Signed URLs: `HMAC-SHA256(APP_KEY, "sb-storage-v1\n" + key + "\n" + expires)`, base64url; verified with `crypto.subtle.verify` (constant time) before the expiry is looked at; TTL 1 s – 7 days; duplicated/odd parameters refused. | `signing.ts` |
40
+ | Serving: `inline` only for png/jpeg/gif/webp, everything else `attachment` as `application/octet-stream` (text as `text/plain`); always `X-Content-Type-Options: nosniff`, `Content-Security-Policy: …; sandbox`, `Cross-Origin-Resource-Policy: same-origin`, `Referrer-Policy: no-referrer`, `Cache-Control: private, no-store`. Bad/expired links throw `forbidden`, a missing object `not_found`. | `serve.ts` |
41
+ | Public serving: `servePublic(request, storage, key, { cache, download, crossOrigin })` checks no signature (the app's own rule decides what is public). Same `inline`/`attachment` and safe headers as `serveSigned`; `Cache-Control` defaults to `public, max-age=3600` and must start with `public` (no line breaks); `ETag` + `If-None-Match` answer 304; `Cross-Origin-Resource-Policy: same-origin` unless `crossOrigin`. An invalid key or a missing object throws `not_found` (the bucket is not asked). | `serve.ts` |
42
+ | Secret: `createStorage` / `storageProvider` accept only the shape of ≥ 32 random bytes (64+ hex, or 43+ base64/base64url chars), ≥ 8 distinct, not periodic, no placeholder word once separators are dropped (`CHANGE_ME_…`) — http's `testKeyAcceptable` criterion (SEC-012, SEC-017). | `storage.ts` |
43
+
44
+ Messages: `storageMessages` (es, en), added by `storageProvider()`.
45
+
46
+ ## Status — TERMINADO (F8, 2026-11-28)
47
+
48
+ - **Implemented**: `createStorage` (+ `createStorageWith(bucket, secret, { basePath, origin, now })`), `put` / `get` / `delete` / `list` / `signedUrl`, `normalizeKey`, `normalizePrefix`, `userKey`, `userPrefix`, `verifySignedUrl`, `serveSigned`, `servePublic`, `signedFileHandler`, `storageProvider`, `isR2Bucket`, `isStrongSecret`, MIME helpers, es/en messages.
49
+ - **Tested** (in-memory R2 fake `src/memory-r2.test-helper.ts`; 100 % lines): traversal (`..`, `%2e%2e`, `%2F`, `\`, NUL, controls, leading `/`) on every method and on the signed path; spoofed MIME (HTML as png, SVG as text, SVG via `image/*`, markup split over tiny chunks); oversized and endless streams (cancelled), lying `Content-Length`; tampered key / expiry / signature, foreign secret, expired links, TTL cap, duplicate params; serving headers for images, SVG, text, HEAD, 405; `list('')` and `list('users/1')`; typed secrets refused, random 32-byte keys accepted; single-copy uploads; provider bindings.
50
+ - **Fixed after review**: SEC-017, AUD-07, AUD-08 — `765020e`.
51
+ - **Left** (out of scope for v1): multipart uploads, `Range` requests, puts above 25 MiB.
@@ -0,0 +1,37 @@
1
+ /**
2
+ * @solobrand/storage — public contracts (FROZEN by F0) + stubs. Implemented by F8 (P24-63).
3
+ * Files live in the app's own R2 bucket (binding `FILES`).
4
+ */
5
+ import { type Result, type Token } from '@solobrand/core';
6
+ export interface StoredFile {
7
+ readonly key: string;
8
+ readonly size: number;
9
+ readonly contentType: string;
10
+ readonly uploadedAt: string;
11
+ }
12
+ export interface PutOptions {
13
+ readonly contentType: string;
14
+ /** Refused above this (default 10 MiB). */
15
+ readonly maxBytes?: number;
16
+ /** MIME allowlist, e.g. ['image/png', 'image/jpeg']. */
17
+ readonly accept?: readonly string[];
18
+ }
19
+ export interface Storage {
20
+ put(key: string, body: ReadableStream | ArrayBuffer | string, options: PutOptions): Promise<Result<StoredFile>>;
21
+ get(key: string): Promise<R2ObjectBody | null>;
22
+ delete(key: string): Promise<void>;
23
+ list(prefix: string, limit?: number): Promise<StoredFile[]>;
24
+ /** A URL the app serves that expires (HMAC with the app secret). */
25
+ signedUrl(key: string, ttlSeconds: number): Promise<string>;
26
+ }
27
+ export declare const storageToken: Token<Storage>;
28
+ /** Throws `internal` (`storage.errors.app_key_missing`) for a weak secret. */
29
+ export declare function createStorage(bucket: R2Bucket, secret: string): Storage;
30
+ export { createStorageWith, isStrongSecret, DEFAULT_MAX_BYTES, HARD_MAX_BYTES, DEFAULT_LIST_LIMIT, MAX_LIST_LIMIT, type StorageOptions } from './storage.js';
31
+ export { normalizeKey, normalizePrefix, assertKey, userKey, userPrefix, encodeKeyPath, decodeKeyPath, MAX_KEY_LENGTH } from './keys.js';
32
+ export { DEFAULT_ACCEPT, ACTIVE_TYPES, INLINE_TYPES, normalizeMime, isAccepted, sniff, looksLikeMarkup, checkContent } from './mime.js';
33
+ export { signUrl, verifySignedUrl, MAX_TTL_SECONDS, DEFAULT_BASE_PATH, type SignOptions } from './signing.js';
34
+ export { serveSigned, servePublic, signedFileHandler, contentDisposition, DEFAULT_PUBLIC_CACHE, type ServeOptions, type PublicServeOptions, type SignedFileContext, } from './serve.js';
35
+ export { storageProvider, isR2Bucket, type StorageProviderOptions } from './provider.js';
36
+ export { storageMessages } from './messages.js';
37
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAS,KAAK,MAAM,EAAE,KAAK,KAAK,EAAE,MAAM,iBAAiB,CAAC;AAGjE,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;CAC7B;A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AE,cAAc,EAAE,YAAY,EAAE,YAAY,EAAE,aAAa,EAAE,UAAU,EAAE,KAAK,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACxI,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,iBAAiB,EAAE,KAAK,WAAW,EAAE,MAAM,cAAc,CAAC;AAC9G,OAAO,EACL,WAAW,EACX,WAAW,EACX,iBAAiB,EACjB,kBAAkB,EAClB,oBAAoB,EACpB,KAAK,YAAY,EACjB,KAAK,kBAAkB,EACvB,KAAK,iBAAiB,GACvB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,KAAK,sBAAsB,EAAE,MAAM,eAAe,CAAC;AACzF,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @solobrand/storage — public contracts (FROZEN by F0) + stubs. Implemented by F8 (P24-63).
3
+ * Files live in the app's own R2 bucket (binding `FILES`).
4
+ */
5
+ import { token } from '@solobrand/core';
6
+ import { createStorageWith } from './storage.js';
7
+ export const storageToken = token('storage');
8
+ /** Throws `internal` (`storage.errors.app_key_missing`) for a weak secret. */
9
+ export function createStorage(bucket, secret) {
10
+ return createStorageWith(bucket, secret);
11
+ }
12
+ export { createStorageWith, isStrongSecret, DEFAULT_MAX_BYTES, HARD_MAX_BYTES, DEFAULT_LIST_LIMIT, MAX_LIST_LIMIT } from './storage.js';
13
+ export { normalizeKey, normalizePrefix, assertKey, userKey, userPrefix, encodeKeyPath, decodeKeyPath, MAX_KEY_LENGTH } from './keys.js';
14
+ export { DEFAULT_ACCEPT, ACTIVE_TYPES, INLINE_TYPES, normalizeMime, isAccepted, sniff, looksLikeMarkup, checkContent } from './mime.js';
15
+ export { signUrl, verifySignedUrl, MAX_TTL_SECONDS, DEFAULT_BASE_PATH } from './signing.js';
16
+ export { serveSigned, servePublic, signedFileHandler, contentDisposition, DEFAULT_PUBLIC_CACHE, } from './serve.js';
17
+ export { storageProvider, isR2Bucket } from './provider.js';
18
+ export { storageMessages } from './messages.js';
19
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,KAAK,EAA2B,MAAM,iBAAiB,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AA0BjD,MAAM,CAAC,MAAM,YAAY,GAAmB,KAAK,CAAU,SAAS,CAAC,CAAC;AAEtE,8EAA8E;AAC9E,MAAM,UAAU,aAAa,CAAC,MAAgB,EAAE,MAAc;IAC5D,OAAO,iBAAiB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAC3C,CAAC;AAED,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAAE,iBAAiB,EAAE,cAAc,EAAE,kBAAkB,EAAE,cAAc,EAAuB,MAAM,cAAc,CAAC;AAC7J,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,SAAS,EAAE,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AACxI,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,YAAY,EAAE,aAAa,EAAE,UAAU,EAAE,KAAK,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACxI,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,iBAAiB,EAAoB,MAAM,cAAc,CAAC;AAC9G,OAAO,EACL,WAAW,EACX,WAAW,EACX,iBAAiB,EACjB,kBAAkB,EAClB,oBAAoB,GAIrB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,eAAe,EAAE,UAAU,EAA+B,MAAM,eAAe,CAAC;AACzF,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC"}
package/dist/keys.d.ts ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Object keys (T-ST-1). A key is a `/`-separated path of non-empty segments; it never
3
+ * starts with `/`, never holds `.` / `..` segments, backslashes, `%` (so `%2e%2e` and
4
+ * `%2f` cannot be decoded into traversal later), or control characters. Keys are NFC
5
+ * normalized so two spellings of the same name are the same key.
6
+ */
7
+ import { AppError, type Result } from '@solobrand/core';
8
+ /** R2 allows 1024 bytes; we stay well below so prefixes always fit. */
9
+ export declare const MAX_KEY_LENGTH = 512;
10
+ /** The normalized key, or `validation_failed` (`storage.errors.invalid_key`). */
11
+ export declare function normalizeKey(key: unknown): Result<string, AppError>;
12
+ /**
13
+ * A list prefix: a folder — same rules as a key, never empty (T-ST-4), and it MUST end
14
+ * in `/`, or `users/1` would also list `users/10/…` (AUD-08).
15
+ */
16
+ export declare function normalizePrefix(prefix: unknown): Result<string, AppError>;
17
+ /** Throws the `AppError` instead of returning it. */
18
+ export declare function assertKey(key: unknown): string;
19
+ /** `users/<id>/` — the only prefix a user's own listing should use. */
20
+ export declare function userPrefix(userId: number | string): string;
21
+ /**
22
+ * `users/<id>/<name>`: namespaces a file per user. `name` is validated as a key, so
23
+ * `../2/x` or `/etc` can never escape the user's folder. Throws `validation_failed`.
24
+ */
25
+ export declare function userKey(userId: number | string, name: string): string;
26
+ /** Percent-encodes each segment for a URL path; `decodeKeyPath` reverses it. */
27
+ export declare function encodeKeyPath(key: string): string;
28
+ export declare function decodeKeyPath(path: string): Result<string, AppError>;
29
+ //# sourceMappingURL=keys.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keys.d.ts","sourceRoot":"","sources":["../src/keys.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,QAAQ,EAAW,KAAK,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAEjE,uEAAuE;AACvE,eAAO,MAAM,cAAc,MAAM,CAAC;AA2BlC,iFAAiF;AACjF,wBAAgB,YAAY,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAEnE;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAIzE;AAED,qDAAqD;AACrD,wBAAgB,SAAS,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,CAI9C;AASD,uEAAuE;AACvE,wBAAgB,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAE1D;AAED;;;GAGG;AACH,wBAAgB,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAErE;AAED,gFAAgF;AAChF,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAEjD;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAMpE"}
package/dist/keys.js ADDED
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Object keys (T-ST-1). A key is a `/`-separated path of non-empty segments; it never
3
+ * starts with `/`, never holds `.` / `..` segments, backslashes, `%` (so `%2e%2e` and
4
+ * `%2f` cannot be decoded into traversal later), or control characters. Keys are NFC
5
+ * normalized so two spellings of the same name are the same key.
6
+ */
7
+ import { AppError, err, ok } from '@solobrand/core';
8
+ /** R2 allows 1024 bytes; we stay well below so prefixes always fit. */
9
+ export const MAX_KEY_LENGTH = 512;
10
+ // C0/C1 controls, backslash, `%`, line/paragraph separators and the BOM.
11
+ const FORBIDDEN = new RegExp('[\\x00-\\x1f\\x7f-\\x9f\\\\%' + String.fromCharCode(0x2028, 0x2029, 0xfeff) + ']');
12
+ function invalid(field) {
13
+ const messageKey = field === 'key' ? 'storage.errors.invalid_key' : 'storage.errors.invalid_prefix';
14
+ return new AppError('validation_failed', messageKey, { errors: { [field]: [messageKey] } });
15
+ }
16
+ function check(value, field) {
17
+ if (typeof value !== 'string')
18
+ return err(invalid(field));
19
+ const key = value.normalize('NFC');
20
+ if (key.length === 0 || key.length > MAX_KEY_LENGTH)
21
+ return err(invalid(field));
22
+ if (FORBIDDEN.test(key) || key.startsWith('/'))
23
+ return err(invalid(field));
24
+ const segments = key.split('/');
25
+ // A prefix ends in `/` (its last segment is then empty); a key may not.
26
+ const last = segments.length - 1;
27
+ for (let i = 0; i < segments.length; i++) {
28
+ const s = segments[i];
29
+ if (s === '' && field === 'prefix' && i === last && i > 0)
30
+ continue;
31
+ // Empty (`a//b`), whitespace-only and dot segments are refused.
32
+ if (s.trim() === '' || s === '.' || s === '..')
33
+ return err(invalid(field));
34
+ }
35
+ return ok(key);
36
+ }
37
+ /** The normalized key, or `validation_failed` (`storage.errors.invalid_key`). */
38
+ export function normalizeKey(key) {
39
+ return check(key, 'key');
40
+ }
41
+ /**
42
+ * A list prefix: a folder — same rules as a key, never empty (T-ST-4), and it MUST end
43
+ * in `/`, or `users/1` would also list `users/10/…` (AUD-08).
44
+ */
45
+ export function normalizePrefix(prefix) {
46
+ const p = check(prefix, 'prefix');
47
+ if (p.ok && !p.value.endsWith('/'))
48
+ return err(invalid('prefix'));
49
+ return p;
50
+ }
51
+ /** Throws the `AppError` instead of returning it. */
52
+ export function assertKey(key) {
53
+ const r = normalizeKey(key);
54
+ if (!r.ok)
55
+ throw r.error;
56
+ return r.value;
57
+ }
58
+ function userSegment(userId) {
59
+ const id = typeof userId === 'number' ? String(userId) : userId;
60
+ if (typeof userId === 'number' && !(Number.isSafeInteger(userId) && userId > 0))
61
+ throw invalid('key');
62
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(id))
63
+ throw invalid('key');
64
+ return id;
65
+ }
66
+ /** `users/<id>/` — the only prefix a user's own listing should use. */
67
+ export function userPrefix(userId) {
68
+ return `users/${userSegment(userId)}/`;
69
+ }
70
+ /**
71
+ * `users/<id>/<name>`: namespaces a file per user. `name` is validated as a key, so
72
+ * `../2/x` or `/etc` can never escape the user's folder. Throws `validation_failed`.
73
+ */
74
+ export function userKey(userId, name) {
75
+ return assertKey(userPrefix(userId) + assertKey(name));
76
+ }
77
+ /** Percent-encodes each segment for a URL path; `decodeKeyPath` reverses it. */
78
+ export function encodeKeyPath(key) {
79
+ return key.split('/').map(encodeURIComponent).join('/');
80
+ }
81
+ export function decodeKeyPath(path) {
82
+ try {
83
+ return normalizeKey(path.split('/').map(decodeURIComponent).join('/'));
84
+ }
85
+ catch {
86
+ return err(invalid('key'));
87
+ }
88
+ }
89
+ //# sourceMappingURL=keys.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keys.js","sourceRoot":"","sources":["../src/keys.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,QAAQ,EAAE,GAAG,EAAE,EAAE,EAAe,MAAM,iBAAiB,CAAC;AAEjE,uEAAuE;AACvE,MAAM,CAAC,MAAM,cAAc,GAAG,GAAG,CAAC;AAElC,yEAAyE;AACzE,MAAM,SAAS,GAAG,IAAI,MAAM,CAAC,8BAA8B,GAAG,MAAM,CAAC,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,GAAG,GAAG,CAAC,CAAC;AAEjH,SAAS,OAAO,CAAC,KAAuB;IACtC,MAAM,UAAU,GAAG,KAAK,KAAK,KAAK,CAAC,CAAC,CAAC,4BAA4B,CAAC,CAAC,CAAC,+BAA+B,CAAC;IACpG,OAAO,IAAI,QAAQ,CAAC,mBAAmB,EAAE,UAAU,EAAE,EAAE,MAAM,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,UAAU,CAAC,EAAE,EAAE,CAAC,CAAC;AAC9F,CAAC;AAED,SAAS,KAAK,CAAC,KAAc,EAAE,KAAuB;IACpD,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;IAC1D,MAAM,GAAG,GAAG,KAAK,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IACnC,IAAI,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G,CAAC,CAAC;AAC1D,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,IAAY;IACxC,IAAI,CAAC;QACH,OAAO,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;IACzE,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;IAC7B,CAAC;AACH,CAAC"}
@@ -0,0 +1,3 @@
1
+ /** The messages @solobrand/storage ships, in es and en. `storageProvider()` adds them. */
2
+ export declare const storageMessages: Readonly<Record<'es' | 'en', Readonly<Record<string, string>>>>;
3
+ //# sourceMappingURL=messages.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../src/messages.ts"],"names":[],"mappings":"AAAA,0FAA0F;AAC1F,eAAO,MAAM,eAAe,EAAE,QAAQ,CAAC,MAAM,CAAC,IAAI,GAAG,IAAI,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,CAiC3F,CAAC"}
@@ -0,0 +1,36 @@
1
+ /** The messages @solobrand/storage ships, in es and en. `storageProvider()` adds them. */
2
+ export const storageMessages = {
3
+ en: {
4
+ 'storage.errors.invalid_key': 'The file name is not valid.',
5
+ 'storage.errors.invalid_prefix': 'The folder is not valid.',
6
+ 'storage.errors.too_large': 'The file is too large (maximum {max} bytes).',
7
+ 'storage.errors.type_not_allowed': 'This type of file is not allowed.',
8
+ 'storage.errors.content_mismatch': 'The file contents do not match its type.',
9
+ 'storage.errors.invalid_signature': 'This link is not valid.',
10
+ 'storage.errors.link_expired': 'This link has expired.',
11
+ 'storage.errors.not_found': 'The file does not exist.',
12
+ 'storage.errors.invalid_ttl': 'Invalid link lifetime: {ttl} (1 to {max} seconds).',
13
+ 'storage.errors.invalid_base_path': 'Invalid storage base path "{basePath}".',
14
+ 'storage.errors.invalid_max_bytes': 'Invalid maxBytes: {maxBytes}.',
15
+ 'storage.errors.binding_missing': 'The R2 binding "{binding}" is not configured.',
16
+ 'storage.errors.app_key_missing': 'APP_KEY is missing or too weak (at least 32 random characters).',
17
+ 'storage.errors.public_cache_invalid': 'The Cache-Control of a public file must start with "public".',
18
+ },
19
+ es: {
20
+ 'storage.errors.invalid_key': 'El nombre del archivo no es válido.',
21
+ 'storage.errors.invalid_prefix': 'La carpeta no es válida.',
22
+ 'storage.errors.too_large': 'El archivo es demasiado grande (máximo {max} bytes).',
23
+ 'storage.errors.type_not_allowed': 'Este tipo de archivo no está permitido.',
24
+ 'storage.errors.content_mismatch': 'El contenido del archivo no corresponde a su tipo.',
25
+ 'storage.errors.invalid_signature': 'Este enlace no es válido.',
26
+ 'storage.errors.link_expired': 'Este enlace ha caducado.',
27
+ 'storage.errors.not_found': 'El archivo no existe.',
28
+ 'storage.errors.invalid_ttl': 'Duración de enlace no válida: {ttl} (de 1 a {max} segundos).',
29
+ 'storage.errors.invalid_base_path': 'Ruta base de almacenamiento no válida: "{basePath}".',
30
+ 'storage.errors.invalid_max_bytes': 'maxBytes no válido: {maxBytes}.',
31
+ 'storage.errors.binding_missing': 'El binding de R2 "{binding}" no está configurado.',
32
+ 'storage.errors.app_key_missing': 'Falta APP_KEY o es débil (al menos 32 caracteres aleatorios).',
33
+ 'storage.errors.public_cache_invalid': 'El Cache-Control de un archivo público debe empezar con "public".',
34
+ },
35
+ };
36
+ //# sourceMappingURL=messages.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"messages.js","sourceRoot":"","sources":["../src/messages.ts"],"names":[],"mappings":"AAAA,0FAA0F;AAC1F,MAAM,CAAC,MAAM,eAAe,GAAoE;IAC9F,EAAE,EAAE;QACF,4BAA4B,EAAE,6BAA6B;QAC3D,+BAA+B,EAAE,0BAA0B;QAC3D,0BAA0B,EAAE,8CAA8C;QAC1E,iCAAiC,EAAE,mCAAmC;QACtE,iCAAiC,EAAE,0CAA0C;QAC7E,kCAAkC,EAAE,yBAAyB;QAC7D,6BAA6B,EAAE,wBAAwB;QACvD,0BAA0B,EAAE,0BAA0B;QACtD,4BAA4B,EAAE,oDAAoD;QAClF,kCAAkC,EAAE,yCAAyC;QAC7E,kCAAkC,EAAE,+BAA+B;QACnE,gCAAgC,EAAE,+CAA+C;QACjF,gCAAgC,EAAE,iEAAiE;QACnG,qCAAqC,EAAE,8DAA8D;KACtG;IACD,EAAE,EAAE;QACF,4BAA4B,EAAE,qCAAqC;QACnE,+BAA+B,EAAE,0BAA0B;QAC3D,0BAA0B,EAAE,sDAAsD;QAClF,iCAAiC,EAAE,yCAAyC;QAC5E,iCAAiC,EAAE,oDAAoD;QACvF,kCAAkC,EAAE,2BAA2B;QAC/D,6BAA6B,EAAE,0BAA0B;QACzD,0BAA0B,EAAE,uBAAuB;QACnD,4BAA4B,EAAE,8DAA8D;QAC5F,kCAAkC,EAAE,sDAAsD;QAC1F,kCAAkC,EAAE,iCAAiC;QACrE,gCAAgC,EAAE,mDAAmD;QACrF,gCAAgC,EAAE,+DAA+D;QACjG,qCAAqC,EAAE,mEAAmE;KAC3G;CACF,CAAC"}
package/dist/mime.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ /**
2
+ * MIME allowlist + magic bytes (T-ST-3, T-RC-6). The declared type must be in `accept`;
3
+ * for the types we can recognise, the first bytes must agree with it; and markup
4
+ * (HTML/SVG/XML) is refused under any declared type that is not explicitly markup.
5
+ */
6
+ /** Used when `PutOptions.accept` is not given. Never includes markup. */
7
+ export declare const DEFAULT_ACCEPT: readonly string[];
8
+ /** Types that can run script when rendered: allowed only when named exactly in `accept`. */
9
+ export declare const ACTIVE_TYPES: readonly string[];
10
+ /** Served `inline`; everything else is `attachment` (T-ST-3). */
11
+ export declare const INLINE_TYPES: readonly string[];
12
+ /** How many leading bytes the checks need. */
13
+ export declare const SNIFF_BYTES = 512;
14
+ /** `Image/PNG; charset=x` → `image/png`; `null` when it is not a `type/subtype`. */
15
+ export declare function normalizeMime(value: string): string | null;
16
+ export declare function isAccepted(type: string, accept: readonly string[]): boolean;
17
+ /** The type the bytes prove, for the formats we recognise; `null` otherwise. */
18
+ export declare function sniff(head: Uint8Array): string | null;
19
+ /** True when the head looks like HTML, SVG, XML or script a browser might render. */
20
+ export declare function looksLikeMarkup(head: Uint8Array): boolean;
21
+ export type ContentCheck = 'ok' | 'mismatch';
22
+ /** Declared type vs. the first bytes. */
23
+ export declare function checkContent(declared: string, head: Uint8Array): ContentCheck;
24
+ //# sourceMappingURL=mime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mime.d.ts","sourceRoot":"","sources":["../src/mime.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,yEAAyE;AACzE,eAAO,MAAM,cAAc,EAAE,SAAS,MAAM,EAA4F,CAAC;AAEzI,4FAA4F;AAC5F,eAAO,MAAM,YAAY,EAAE,SAAS,MAAM,EAWzC,CAAC;AAEF,iEAAiE;AACjE,eAAO,MAAM,YAAY,EAAE,SAAS,MAAM,EAA2D,CAAC;AAEtG,8CAA8C;AAC9C,eAAO,MAAM,WAAW,MAAM,CAAC;AAE/B,oFAAoF;AACpF,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAG1D;AAED,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAQ3E;AAOD,gFAAgF;AAChF,wBAAgB,KAAK,CAAC,IAAI,EAAE,UAAU,GAAG,MAAM,GAAG,IAAI,CAOrD;AAED,qFAAqF;AACrF,wBAAgB,eAAe,CAAC,IAAI,EAAE,UAAU,GAAG,OAAO,CAUzD;AAKD,MAAM,MAAM,YAAY,GAAG,IAAI,GAAG,UAAU,CAAC;AAE7C,yCAAyC;AACzC,wBAAgB,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,GAAG,YAAY,CAI7E"}
package/dist/mime.js ADDED
@@ -0,0 +1,80 @@
1
+ /**
2
+ * MIME allowlist + magic bytes (T-ST-3, T-RC-6). The declared type must be in `accept`;
3
+ * for the types we can recognise, the first bytes must agree with it; and markup
4
+ * (HTML/SVG/XML) is refused under any declared type that is not explicitly markup.
5
+ */
6
+ /** Used when `PutOptions.accept` is not given. Never includes markup. */
7
+ export const DEFAULT_ACCEPT = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'application/pdf', 'text/plain'];
8
+ /** Types that can run script when rendered: allowed only when named exactly in `accept`. */
9
+ export const ACTIVE_TYPES = [
10
+ 'image/svg+xml',
11
+ 'text/html',
12
+ 'application/xhtml+xml',
13
+ 'text/xml',
14
+ 'application/xml',
15
+ 'text/javascript',
16
+ 'application/javascript',
17
+ 'application/x-javascript',
18
+ 'text/xsl',
19
+ 'application/x-shockwave-flash',
20
+ ];
21
+ /** Served `inline`; everything else is `attachment` (T-ST-3). */
22
+ export const INLINE_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];
23
+ /** How many leading bytes the checks need. */
24
+ export const SNIFF_BYTES = 512;
25
+ /** `Image/PNG; charset=x` → `image/png`; `null` when it is not a `type/subtype`. */
26
+ export function normalizeMime(value) {
27
+ const base = (value.split(';')[0] ?? '').trim().toLowerCase();
28
+ return /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/.test(base) ? base : null;
29
+ }
30
+ export function isAccepted(type, accept) {
31
+ for (const raw of accept) {
32
+ const entry = raw.trim().toLowerCase();
33
+ if (entry === type)
34
+ return true;
35
+ // `image/*` never reaches an active type such as image/svg+xml.
36
+ if (entry.endsWith('/*') && !ACTIVE_TYPES.includes(type) && type.startsWith(entry.slice(0, -1)))
37
+ return true;
38
+ }
39
+ return false;
40
+ }
41
+ const startsWith = (b, sig, at = 0) => b.length >= at + sig.length && sig.every((v, i) => b[at + i] === v);
42
+ const ascii = (s) => [...s].map((c) => c.charCodeAt(0));
43
+ /** The type the bytes prove, for the formats we recognise; `null` otherwise. */
44
+ export function sniff(head) {
45
+ if (startsWith(head, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))
46
+ return 'image/png';
47
+ if (startsWith(head, [0xff, 0xd8, 0xff]))
48
+ return 'image/jpeg';
49
+ if (startsWith(head, ascii('GIF87a')) || startsWith(head, ascii('GIF89a')))
50
+ return 'image/gif';
51
+ if (startsWith(head, ascii('RIFF')) && startsWith(head, ascii('WEBP'), 8))
52
+ return 'image/webp';
53
+ if (startsWith(head, ascii('%PDF-')))
54
+ return 'application/pdf';
55
+ return null;
56
+ }
57
+ /** True when the head looks like HTML, SVG, XML or script a browser might render. */
58
+ export function looksLikeMarkup(head) {
59
+ // ignoreBOM: false strips a leading BOM; NULs (UTF-16 tricks) are dropped before matching.
60
+ const text = new TextDecoder('utf-8', { fatal: false, ignoreBOM: false })
61
+ .decode(head)
62
+ .split(String.fromCharCode(0))
63
+ .join('')
64
+ .trimStart()
65
+ .toLowerCase();
66
+ if (!text.startsWith('<'))
67
+ return false;
68
+ return /^<[a-z!?/]/.test(text);
69
+ }
70
+ /** Recognised formats: a declared one of these must carry its signature. */
71
+ const SIGNED_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'application/pdf'];
72
+ /** Declared type vs. the first bytes. */
73
+ export function checkContent(declared, head) {
74
+ if (SIGNED_TYPES.includes(declared))
75
+ return sniff(head) === declared ? 'ok' : 'mismatch';
76
+ if (!ACTIVE_TYPES.includes(declared) && looksLikeMarkup(head))
77
+ return 'mismatch';
78
+ return 'ok';
79
+ }
80
+ //# sourceMappingURL=mime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mime.js","sourceRoot":"","sources":["../src/mime.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,yEAAyE;AACzE,MAAM,CAAC,MAAM,cAAc,GAAsB,CAAC,WAAW,EAAE,YAAY,EAAE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;AACd,CAAC;AAED,qFAAqF;AACrF,MAAM,UAAU,eAAe,CAAC,IAAgB;IAC9C,2FAA2F;IAC3F,MAAM,IAAI,GAAG,IAAI,WAAW,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC;SACtE,MAAM,CAAC,IAAI,CAAC;SACZ,KAAK,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;SAC7B,IAAI,CAAC,EAAE,CAAC;SACR,SAAS,EAAE;SACX,WAAW,EAAE,CAAC;IACjB,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC;QAAE,OAAO,KAAK,CAAC;IACxC,OAAO,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACjC,CAAC;AAED,4EAA4E;AAC5E,MAAM,YAAY,GAAsB,CAAC,WAAW,EAAE,YAAY,EAAE,WAAW,EAAE,YAAY,EAAE,iBAAiB,CAAC,CAAC;AAIlH,yCAAyC;AACzC,MAAM,UAAU,YAAY,CAAC,QAAgB,EAAE,IAAgB;IAC7D,IAAI,YAAY,CAAC,QAAQ,CAAC,QAAQ,CAAC;QAAE,OAAO,KAAK,CAAC,IAAI,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC;IACzF,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,eAAe,CAAC,IAAI,CAAC;QAAE,OAAO,UAAU,CAAC;IACjF,OAAO,IAAI,CAAC;AACd,CAAC"}
@@ -0,0 +1,13 @@
1
+ /** `storageProvider()` — binds `storageToken` from `env.FILES` and `env.APP_KEY`. */
2
+ import { type ServiceProvider } from '@solobrand/core';
3
+ import { type StorageOptions } from './storage.js';
4
+ export interface StorageProviderOptions extends StorageOptions {
5
+ /** R2 binding name (default `FILES`). */
6
+ readonly binding?: string;
7
+ /** Secret binding name (default `APP_KEY`). */
8
+ readonly secretBinding?: string;
9
+ }
10
+ export declare function isR2Bucket(value: unknown): value is R2Bucket;
11
+ /** Lazy: the bucket and secret are checked the first time `storageToken` is made. */
12
+ export declare function storageProvider(options?: StorageProviderOptions): ServiceProvider;
13
+ //# sourceMappingURL=provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA,qFAAqF;AACrF,OAAO,EAA8B,KAAK,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAGnF,OAAO,EAAqC,KAAK,cAAc,EAAE,MAAM,cAAc,CAAC;AAEtF,MAAM,WAAW,sBAAuB,SAAQ,cAAc;IAC5D,yCAAyC;IACzC,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B,+CAA+C;IAC/C,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;CACjC;AAED,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,QAAQ,CAI5D;AAED,qFAAqF;AACrF,wBAAgB,eAAe,CAAC,OAAO,GAAE,sBAA2B,GAAG,eAAe,CAkBrF"}
@@ -0,0 +1,34 @@
1
+ /** `storageProvider()` — binds `storageToken` from `env.FILES` and `env.APP_KEY`. */
2
+ import { AppError } from '@solobrand/core';
3
+ import { storageToken } from './index.js';
4
+ import { storageMessages } from './messages.js';
5
+ import { createStorageWith, isStrongSecret } from './storage.js';
6
+ export function isR2Bucket(value) {
7
+ if (typeof value !== 'object' || value === null)
8
+ return false;
9
+ const v = value;
10
+ return ['put', 'get', 'head', 'delete', 'list'].every((m) => typeof v[m] === 'function');
11
+ }
12
+ /** Lazy: the bucket and secret are checked the first time `storageToken` is made. */
13
+ export function storageProvider(options = {}) {
14
+ const binding = options.binding ?? 'FILES';
15
+ const secretBinding = options.secretBinding ?? 'APP_KEY';
16
+ const { binding: _b, secretBinding: _s, ...storageOptions } = options;
17
+ return {
18
+ name: 'storage',
19
+ register(app) {
20
+ app.i18n.add('en', storageMessages.en);
21
+ app.i18n.add('es', storageMessages.es);
22
+ app.singleton(storageToken, () => {
23
+ const bucket = app.env[binding];
24
+ if (!isR2Bucket(bucket))
25
+ throw new AppError('internal', 'storage.errors.binding_missing', { params: { binding } });
26
+ const secret = app.env[secretBinding];
27
+ if (!isStrongSecret(secret))
28
+ throw new AppError('internal', 'storage.errors.app_key_missing');
29
+ return createStorageWith(bucket, secret, storageOptions);
30
+ });
31
+ },
32
+ };
33
+ }
34
+ //# sourceMappingURL=provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.js","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA,qFAAqF;AACrF,OAAO,EAAE,QAAQ,EAA0C,MAAM,iBAAiB,CAAC;AACnF,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAAuB,MAAM,cAAc,CAAC;AAStF,MAAM,UAAU,UAAU,CAAC,KAAc;IACvC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,KAAK,CAAC;IAC9D,MAAM,CAAC,GAAG,KAAgC,CAAC;IAC3C,OAAO,CAAC,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,UAAU,CAAC,CAAC;AAC3F,CAAC;AAED,qFAAqF;AACrF,MAAM,UAAU,eAAe,CAAC,UAAkC,EAAE;IAClE,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,OAAO,CAAC;IAC3C,MAAM,aAAa,GAAG,OAAO,CAAC,aAAa,IAAI,SAAS,CAAC;IACzD,MAAM,EAAE,OAAO,EAAE,EAAE,EAAE,aAAa,EAAE,EAAE,EAAE,GAAG,cAAc,EAAE,GAAG,OAAO,CAAC;IACtE,OAAO;QACL,IAAI,EAAE,SAAS;QACf,QAAQ,CAAC,GAAgB;YACvB,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,eAAe,CAAC,EAAE,CAAC,CAAC;YACvC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,eAAe,CAAC,EAAE,CAAC,CAAC;YACvC,GAAG,CAAC,SAAS,CAAC,YAAY,EAAE,GAAG,EAAE;gBAC/B,MAAM,MAAM,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;gBAChC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC;oBAAE,MAAM,IAAI,QAAQ,CAAC,UAAU,EAAE,gCAAgC,EAAE,EAAE,MAAM,EAAE,EAAE,OAAO,EAAE,EAAE,CAAC,CAAC;gBACnH,MAAM,MAAM,GAAG,GAAG,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;gBACtC,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC;oBAAE,MAAM,IAAI,QAAQ,CAAC,UAAU,EAAE,gCAAgC,CAAC,CAAC;gBAC9F,OAAO,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,cAAc,CAAC,CAAC;YAC3D,CAAC,CAAC,CAAC;QACL,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,52 @@
1
+ /**
2
+ * `serveSigned()` — answers a signed URL (T-ST-2, T-ST-3). Verifies the HMAC in
3
+ * constant time, refuses expired links, and serves with `X-Content-Type-Options:
4
+ * nosniff`, a sandboxing CSP, and `Content-Disposition: attachment` for everything
5
+ * but raster images, so an uploaded HTML/SVG never runs on the app's origin.
6
+ * `servePublic()` serves a file the app made public with the same headers, cacheable.
7
+ */
8
+ import { type Application } from '@solobrand/core';
9
+ import { type SignOptions } from './signing.js';
10
+ import { type Storage } from './index.js';
11
+ export interface ServeOptions extends SignOptions {
12
+ /** Always `attachment`, even for images. */
13
+ readonly download?: boolean;
14
+ }
15
+ /** `filename="ascii"; filename*=UTF-8''utf8` for the key's last segment. */
16
+ export declare function contentDisposition(kind: 'inline' | 'attachment', key: string): string;
17
+ /**
18
+ * The response for a signed `request`, or throws `AppError`: `forbidden` for a bad or
19
+ * expired link, `not_found` when the object is gone. Use it as a route handler body;
20
+ * the kernel renders the error.
21
+ */
22
+ export declare function serveSigned(request: Request, storage: Storage, secret: string, options?: ServeOptions): Promise<Response>;
23
+ export declare const DEFAULT_PUBLIC_CACHE = "public, max-age=3600";
24
+ export interface PublicServeOptions {
25
+ /** `Cache-Control`. Default `public, max-age=3600`. Must start with `public`. */
26
+ readonly cache?: string;
27
+ /** Always `attachment`, even for images. */
28
+ readonly download?: boolean;
29
+ /** `Cross-Origin-Resource-Policy: cross-origin`, so other sites may embed it (default `same-origin`). */
30
+ readonly crossOrigin?: boolean;
31
+ }
32
+ /**
33
+ * Serves `key` to anyone, cacheable: for files the app has decided are public (a published
34
+ * listing's photo, a logo). No signature is checked, so call it only after the app's own
35
+ * rule says the file is public. Same safe headers as `serveSigned` (inline only for raster
36
+ * images, nosniff, sandboxing CSP); `If-None-Match` with the object's ETag answers 304.
37
+ * Throws `not_found` when the object is missing and for an invalid key.
38
+ */
39
+ export declare function servePublic(request: Request, storage: Storage, key: string, options?: PublicServeOptions): Promise<Response>;
40
+ /** The slice of `HttpContext` `signedFileHandler` needs (keeps storage free of http). */
41
+ export interface SignedFileContext {
42
+ readonly request: Request;
43
+ readonly app: Pick<Application, 'make' | 'env'>;
44
+ }
45
+ /**
46
+ * A route handler: `router.get('/files/{key...}', signedFileHandler())`. Takes the
47
+ * `Storage` from the container and the secret from `env.APP_KEY`.
48
+ */
49
+ export declare function signedFileHandler(options?: ServeOptions & {
50
+ readonly secretBinding?: string;
51
+ }): (ctx: SignedFileContext) => Promise<Response>;
52
+ //# sourceMappingURL=serve.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serve.d.ts","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AC,CAAC;CACjD;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,GAAE,YAAY,GAAG;IAAE,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAA;CAAO,GAAG,CAAC,GAAG,EAAE,iBAAiB,KAAK,OAAO,CAAC,QAAQ,CAAC,CAMjJ"}
package/dist/serve.js ADDED
@@ -0,0 +1,116 @@
1
+ /**
2
+ * `serveSigned()` — answers a signed URL (T-ST-2, T-ST-3). Verifies the HMAC in
3
+ * constant time, refuses expired links, and serves with `X-Content-Type-Options:
4
+ * nosniff`, a sandboxing CSP, and `Content-Disposition: attachment` for everything
5
+ * but raster images, so an uploaded HTML/SVG never runs on the app's origin.
6
+ * `servePublic()` serves a file the app made public with the same headers, cacheable.
7
+ */
8
+ import { AppError } from '@solobrand/core';
9
+ import { normalizeKey } from './keys.js';
10
+ import { INLINE_TYPES, normalizeMime } from './mime.js';
11
+ import { verifySignedUrl } from './signing.js';
12
+ import { storageToken } from './index.js';
13
+ /** `filename="ascii"; filename*=UTF-8''utf8` for the key's last segment. */
14
+ export function contentDisposition(kind, key) {
15
+ const name = key.slice(key.lastIndexOf('/') + 1);
16
+ const fallback = name.replace(/[^\x20-\x7e]|["\\;]/g, '_');
17
+ const encoded = encodeURIComponent(name).replace(/['()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
18
+ return `${kind}; filename="${fallback}"; filename*=UTF-8''${encoded}`;
19
+ }
20
+ /**
21
+ * The response for a signed `request`, or throws `AppError`: `forbidden` for a bad or
22
+ * expired link, `not_found` when the object is gone. Use it as a route handler body;
23
+ * the kernel renders the error.
24
+ */
25
+ export async function serveSigned(request, storage, secret, options = {}) {
26
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
27
+ return new Response(null, { status: 405, headers: { Allow: 'GET, HEAD' } });
28
+ }
29
+ const verified = await verifySignedUrl(new URL(request.url), secret, options);
30
+ if (!verified.ok)
31
+ throw verified.error;
32
+ const key = verified.value;
33
+ const object = await storage.get(key);
34
+ if (!object)
35
+ throw new AppError('not_found', 'storage.errors.not_found');
36
+ const headers = safeHeaders(object, key, options.download === true, 'private, no-store', 'same-origin');
37
+ if (request.method === 'HEAD') {
38
+ await object.body.cancel().catch(() => undefined);
39
+ return new Response(null, { status: 200, headers });
40
+ }
41
+ return new Response(object.body, { status: 200, headers });
42
+ }
43
+ /** The headers both serving paths share: inline only for raster images, nosniff, sandboxing CSP. */
44
+ function safeHeaders(object, key, download, cache, corp) {
45
+ const stored = normalizeMime(object.httpMetadata?.contentType ?? '') ?? 'application/octet-stream';
46
+ const inline = !download && INLINE_TYPES.includes(stored);
47
+ const headers = new Headers({
48
+ 'Content-Type': inline ? stored : stored.startsWith('text/') ? 'text/plain; charset=utf-8' : 'application/octet-stream',
49
+ 'Content-Length': String(object.size),
50
+ 'Content-Disposition': contentDisposition(inline ? 'inline' : 'attachment', key),
51
+ 'X-Content-Type-Options': 'nosniff',
52
+ 'Content-Security-Policy': "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; sandbox",
53
+ 'Cross-Origin-Resource-Policy': corp,
54
+ 'Referrer-Policy': 'no-referrer',
55
+ 'Cache-Control': cache,
56
+ });
57
+ if (object.httpEtag)
58
+ headers.set('ETag', object.httpEtag);
59
+ return headers;
60
+ }
61
+ export const DEFAULT_PUBLIC_CACHE = 'public, max-age=3600';
62
+ /**
63
+ * Serves `key` to anyone, cacheable: for files the app has decided are public (a published
64
+ * listing's photo, a logo). No signature is checked, so call it only after the app's own
65
+ * rule says the file is public. Same safe headers as `serveSigned` (inline only for raster
66
+ * images, nosniff, sandboxing CSP); `If-None-Match` with the object's ETag answers 304.
67
+ * Throws `not_found` when the object is missing and for an invalid key.
68
+ */
69
+ export async function servePublic(request, storage, key, options = {}) {
70
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
71
+ return new Response(null, { status: 405, headers: { Allow: 'GET, HEAD' } });
72
+ }
73
+ const cache = options.cache ?? DEFAULT_PUBLIC_CACHE;
74
+ if (!/^public(,|$)/.test(cache.trim()) || /[\r\n]/.test(cache))
75
+ throw new AppError('internal', 'storage.errors.public_cache_invalid');
76
+ const valid = normalizeKey(key);
77
+ if (!valid.ok)
78
+ throw new AppError('not_found', 'storage.errors.not_found');
79
+ const object = await storage.get(valid.value);
80
+ if (!object)
81
+ throw new AppError('not_found', 'storage.errors.not_found');
82
+ const headers = safeHeaders(object, valid.value, options.download === true, cache.trim(), options.crossOrigin === true ? 'cross-origin' : 'same-origin');
83
+ headers.set('Vary', 'Accept-Encoding');
84
+ const etag = object.httpEtag;
85
+ const ifNoneMatch = request.headers.get('If-None-Match');
86
+ if (etag && ifNoneMatch !== null && matchesEtag(ifNoneMatch, etag)) {
87
+ await object.body.cancel().catch(() => undefined);
88
+ headers.delete('Content-Length');
89
+ return new Response(null, { status: 304, headers });
90
+ }
91
+ if (request.method === 'HEAD') {
92
+ await object.body.cancel().catch(() => undefined);
93
+ return new Response(null, { status: 200, headers });
94
+ }
95
+ return new Response(object.body, { status: 200, headers });
96
+ }
97
+ /** `If-None-Match`: `*`, or a list of (weak or strong) tags compared weakly. */
98
+ function matchesEtag(header, etag) {
99
+ const bare = (t) => t.trim().replace(/^W\//, '');
100
+ if (header.trim() === '*')
101
+ return true;
102
+ return header.split(',').some((t) => bare(t) === bare(etag));
103
+ }
104
+ /**
105
+ * A route handler: `router.get('/files/{key...}', signedFileHandler())`. Takes the
106
+ * `Storage` from the container and the secret from `env.APP_KEY`.
107
+ */
108
+ export function signedFileHandler(options = {}) {
109
+ return async (ctx) => {
110
+ const secret = ctx.app.env[options.secretBinding ?? 'APP_KEY'];
111
+ if (typeof secret !== 'string')
112
+ throw new AppError('internal', 'storage.errors.app_key_missing');
113
+ return serveSigned(ctx.request, ctx.app.make(storageToken), secret, options);
114
+ };
115
+ }
116
+ //# sourceMappingURL=serve.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serve.js","sourceRoot":"","sources":["../src/serve.ts"],"names":[],"mappings":"AAA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storage-v1\n" + key + "\n" + expires)`,
3
+ * base64url, verified with `crypto.subtle.verify` (constant time). Expiry is a Unix
4
+ * timestamp in seconds, enforced on verify; lifetimes are capped at `MAX_TTL_SECONDS`.
5
+ */
6
+ import { AppError, type Result } from '@solobrand/core';
7
+ /** Seven days, like S3 presigned URLs. */
8
+ export declare const MAX_TTL_SECONDS: number;
9
+ /** Where `signedUrl()` points and `serveSigned()` answers by default. */
10
+ export declare const DEFAULT_BASE_PATH = "/files/";
11
+ export declare function sign(secret: string, key: string, expires: number): Promise<string>;
12
+ export interface SignOptions {
13
+ /** Path prefix the app serves files under (default `/files/`). */
14
+ readonly basePath?: string;
15
+ /** Prepended to the path to make an absolute URL, e.g. `https://app.example.com`. */
16
+ readonly origin?: string;
17
+ /** Unix milliseconds; defaults to `Date.now()`. */
18
+ readonly now?: () => number;
19
+ }
20
+ export declare function signUrl(secret: string, key: string, ttlSeconds: number, options?: SignOptions): Promise<string>;
21
+ /**
22
+ * The key a signed URL grants, or `forbidden`: `storage.errors.invalid_signature`
23
+ * (tampered key/expiry/signature, wrong path) or `storage.errors.link_expired`.
24
+ * The signature is checked before the expiry, so an attacker learns nothing from it.
25
+ */
26
+ export declare function verifySignedUrl(url: URL | string, secret: string, options?: SignOptions): Promise<Result<string, AppError>>;
27
+ //# sourceMappingURL=signing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signing.d.ts","sourceRoot":"","sources":["../src/signing.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,QAAQ,EAA0B,KAAK,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAGhF,0CAA0C;AAC1C,eAAO,MAAM,eAAe,QAAmB,CAAC;AAChD,yEAAyE;AACzE,eAAO,MAAM,iBAAiB,YAAY,CAAC;AA8B3C,wBAAsB,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAExF;AAED,MAAM,WAAW,WAAW;IAC1B,kEAAkE;IAClE,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,qFAAqF;IACrF,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB,mDAAmD;IACnD,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CAC7B;AAUD,wBAAsB,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,OAAO,GAAE,WAAgB,GAAG,OAAO,CAAC,MAAM,CAAC,CAWzH;AAID;;;;GAIG;AACH,wBAAsB,eAAe,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,WAAgB,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC,CAsBrI"}
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Signed URLs (T-ST-2): `HMAC-SHA256(secret, "sb-storage-v1\n" + key + "\n" + expires)`,
3
+ * base64url, verified with `crypto.subtle.verify` (constant time). Expiry is a Unix
4
+ * timestamp in seconds, enforced on verify; lifetimes are capped at `MAX_TTL_SECONDS`.
5
+ */
6
+ import { AppError, err, internalError, ok } from '@solobrand/core';
7
+ import { decodeKeyPath, encodeKeyPath, normalizeKey } from './keys.js';
8
+ /** Seven days, like S3 presigned URLs. */
9
+ export const MAX_TTL_SECONDS = 7 * 24 * 60 * 60;
10
+ /** Where `signedUrl()` points and `serveSigned()` answers by default. */
11
+ export const DEFAULT_BASE_PATH = '/files/';
12
+ const CONTEXT = 'sb-storage-v1';
13
+ const encoder = new TextEncoder();
14
+ const keyCache = new Map();
15
+ function hmacKey(secret) {
16
+ let k = keyCache.get(secret);
17
+ if (!k) {
18
+ k = crypto.subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign', 'verify']);
19
+ if (keyCache.size > 16)
20
+ keyCache.clear();
21
+ keyCache.set(secret, k);
22
+ }
23
+ return k;
24
+ }
25
+ const payload = (key, expires) => encoder.encode(`${CONTEXT}\n${key}\n${expires}`);
26
+ function toBase64Url(bytes) {
27
+ let s = '';
28
+ for (const b of new Uint8Array(bytes))
29
+ s += String.fromCharCode(b);
30
+ return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
31
+ }
32
+ function fromBase64Url(text) {
33
+ if (!/^[A-Za-z0-9_-]{43}$/.test(text))
34
+ return null; // 32 bytes, unpadded
35
+ const bin = atob(text.replace(/-/g, '+').replace(/_/g, '/') + '=');
36
+ return Uint8Array.from(bin, (c) => c.charCodeAt(0));
37
+ }
38
+ export async function sign(secret, key, expires) {
39
+ return toBase64Url(await crypto.subtle.sign('HMAC', await hmacKey(secret), payload(key, expires)));
40
+ }
41
+ function basePathOf(options) {
42
+ const base = options.basePath ?? DEFAULT_BASE_PATH;
43
+ if (!/^\/([A-Za-z0-9._~-]+\/)*$/.test(base)) {
44
+ throw internalError('storage.errors.invalid_base_path', { basePath: base }, `Invalid storage basePath "${base}": it must start and end with "/".`);
45
+ }
46
+ return base;
47
+ }
48
+ export async function signUrl(secret, key, ttlSeconds, options = {}) {
49
+ const k = normalizeKey(key);
50
+ if (!k.ok)
51
+ throw k.error;
52
+ if (!Number.isSafeInteger(ttlSeconds) || ttlSeconds < 1 || ttlSeconds > MAX_TTL_SECONDS) {
53
+ throw new AppError('internal', 'storage.errors.invalid_ttl', { params: { ttl: String(ttlSeconds), max: MAX_TTL_SECONDS } });
54
+ }
55
+ const now = (options.now ?? Date.now)();
56
+ const expires = Math.floor(now / 1000) + ttlSeconds;
57
+ const signature = await sign(secret, k.value, expires);
58
+ const path = `${basePathOf(options)}${encodeKeyPath(k.value)}?expires=${expires}&signature=${signature}`;
59
+ return (options.origin ?? '').replace(/\/+$/, '') + path;
60
+ }
61
+ const forbidden = (messageKey) => new AppError('forbidden', messageKey);
62
+ /**
63
+ * The key a signed URL grants, or `forbidden`: `storage.errors.invalid_signature`
64
+ * (tampered key/expiry/signature, wrong path) or `storage.errors.link_expired`.
65
+ * The signature is checked before the expiry, so an attacker learns nothing from it.
66
+ */
67
+ export async function verifySignedUrl(url, secret, options = {}) {
68
+ const u = typeof url === 'string' ? new URL(url, 'http://localhost') : url;
69
+ const base = basePathOf(options);
70
+ const bad = err(forbidden('storage.errors.invalid_signature'));
71
+ if (!u.pathname.startsWith(base))
72
+ return bad;
73
+ const key = decodeKeyPath(u.pathname.slice(base.length));
74
+ if (!key.ok)
75
+ return bad;
76
+ const expiresRaw = u.searchParams.getAll('expires');
77
+ const sigRaw = u.searchParams.getAll('signature');
78
+ if (expiresRaw.length !== 1 || sigRaw.length !== 1)
79
+ return bad;
80
+ const expiresText = expiresRaw[0];
81
+ if (!/^[1-9][0-9]{0,11}$/.test(expiresText))
82
+ return bad;
83
+ const expires = Number(expiresText);
84
+ const signature = fromBase64Url(sigRaw[0]);
85
+ if (!signature)
86
+ return bad;
87
+ const valid = await crypto.subtle.verify('HMAC', await hmacKey(secret), signature, payload(key.value, expires));
88
+ if (!valid)
89
+ return bad;
90
+ const nowSeconds = Math.floor((options.now ?? Date.now)() / 1000);
91
+ if (expires <= nowSeconds)
92
+ return err(forbidden('storage.errors.link_expired'));
93
+ // A link minted with a longer lifetime than we allow (an old secret, a bug) is refused too.
94
+ if (expires - nowSeconds > MAX_TTL_SECONDS)
95
+ return bad;
96
+ return ok(key.value);
97
+ }
98
+ //# sourceMappingURL=signing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signing.js","sourceRoot":"","sources":["../src/signing.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,QAAQ,EAAE,GAAG,EAAE,aAAa,EAAE,EAAE,EAAe,MAAM,iBAAiB,CAAC;AAChF,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEvE,0CAA0C;AAC1C,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UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,IAAI,CAAC,CAAC;IAClE,IAAI,OAAO,IAAI,UAAU;QAAE,OAAO,GAAG,CAAC,SAAS,CAAC,6BAA6B,CAAC,CAAC,CAAC;IAChF,4FAA4F;IAC5F,IAAI,OAAO,GAAG,UAAU,GAAG,eAAe;QAAE,OAAO,GAAG,CAAC;IACvD,OAAO,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;AACvB,CAAC"}
@@ -0,0 +1,23 @@
1
+ import type { Storage } from './index.js';
2
+ import { type SignOptions } from './signing.js';
3
+ /** `PutOptions.maxBytes` default: 10 MiB. */
4
+ export declare const DEFAULT_MAX_BYTES: number;
5
+ /**
6
+ * A streamed body is held in memory once (R2 needs a known length), so no single put may
7
+ * exceed this: 25 MiB leaves room in a 128 MB isolate for the request and the app (AUD-07).
8
+ */
9
+ export declare const HARD_MAX_BYTES: number;
10
+ export declare const DEFAULT_LIST_LIMIT = 100;
11
+ export declare const MAX_LIST_LIMIT = 1000;
12
+ export interface StorageOptions extends SignOptions {
13
+ }
14
+ /**
15
+ * A signing secret we accept (SEC-012, SEC-017) — the criterion of http's
16
+ * `testKeyAcceptable`: the shape of ≥ 32 random bytes (64+ hex, or 43+ base64/base64url
17
+ * characters before any `=` padding), ≥ 8 distinct characters, not periodic
18
+ * (`abcdefgh` × 4), and no placeholder word once separators are dropped (`CHANGE_ME_…`).
19
+ * What `sb new` / `sb dev` write (32 random bytes, base64url) always passes.
20
+ */
21
+ export declare function isStrongSecret(secret: unknown): secret is string;
22
+ export declare function createStorageWith(bucket: R2Bucket, secret: string, options?: StorageOptions): Storage;
23
+ //# sourceMappingURL=storage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["../src/storage.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAc,OAAO,EAAc,MAAM,YAAY,CAAC;AAGlE,OAAO,EAAW,KAAK,WAAW,EAAE,MAAM,cAAc,CAAC;AAEzD,6CAA6C;AAC7C,eAAO,MAAM,iBAAiB,QAAmB,CAAC;AAClD;;;GAGG;AACH,eAAO,MAAM,cAAc,QAAmB,CAAC;AAC/C,eAAO,MAAM,kBAAkB,MAAM,CAAC;AACtC,eAAO,MAAM,cAAc,OAAO,CAAC;AAEnC,MAAM,WAAW,cAAe,SAAQ,WAAW;CAAG;AAmHtD;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,OAAO,GAAG,MAAM,IAAI,MAAM,CAahE;AAED,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,cAAmB,GAAG,OAAO,CA8CzG"}
@@ -0,0 +1,196 @@
1
+ /** `createStorage(bucket, secret)` — the R2-backed `Storage`. */
2
+ import { AppError, err, ok } from '@solobrand/core';
3
+ import { assertKey, normalizeKey, normalizePrefix } from './keys.js';
4
+ import { DEFAULT_ACCEPT, SNIFF_BYTES, checkContent, isAccepted, normalizeMime } from './mime.js';
5
+ import { signUrl } from './signing.js';
6
+ /** `PutOptions.maxBytes` default: 10 MiB. */
7
+ export const DEFAULT_MAX_BYTES = 10 * 1024 * 1024;
8
+ /**
9
+ * A streamed body is held in memory once (R2 needs a known length), so no single put may
10
+ * exceed this: 25 MiB leaves room in a 128 MB isolate for the request and the app (AUD-07).
11
+ */
12
+ export const HARD_MAX_BYTES = 25 * 1024 * 1024;
13
+ export const DEFAULT_LIST_LIMIT = 100;
14
+ export const MAX_LIST_LIMIT = 1000;
15
+ const fieldError = (code, messageKey, params) => new AppError(code, messageKey, params ? { params, errors: { file: [messageKey] } } : { errors: { file: [messageKey] } });
16
+ /** An in-memory body is used as is: its size is its byteLength, nothing is copied. */
17
+ function fromBytes(body) {
18
+ if (typeof body === 'string')
19
+ return new TextEncoder().encode(body);
20
+ if (body instanceof ArrayBuffer)
21
+ return new Uint8Array(body);
22
+ return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
23
+ }
24
+ /** The first `SNIFF_BYTES` across the chunks (a small copy only when the first chunk is short). */
25
+ function headOf(chunks) {
26
+ const first = chunks[0] ?? new Uint8Array(0);
27
+ if (first.byteLength >= SNIFF_BYTES || chunks.length <= 1)
28
+ return first.subarray(0, SNIFF_BYTES);
29
+ const head = new Uint8Array(SNIFF_BYTES);
30
+ let at = 0;
31
+ for (const c of chunks) {
32
+ if (at >= SNIFF_BYTES)
33
+ break;
34
+ const part = c.subarray(0, SNIFF_BYTES - at);
35
+ head.set(part, at);
36
+ at += part.byteLength;
37
+ }
38
+ return head.subarray(0, at);
39
+ }
40
+ /**
41
+ * Reads at most `maxBytes`, counting what actually arrives (never trusting a declared
42
+ * length). One byte over and the source is cancelled: the rest is never read.
43
+ */
44
+ async function readCapped(stream, maxBytes) {
45
+ const reader = stream.getReader();
46
+ const chunks = [];
47
+ let size = 0;
48
+ try {
49
+ for (;;) {
50
+ const { done, value } = await reader.read();
51
+ if (done)
52
+ break;
53
+ const chunk = value instanceof Uint8Array ? value : new Uint8Array(value);
54
+ size += chunk.byteLength;
55
+ if (size > maxBytes) {
56
+ await reader.cancel('payload_too_large').catch(() => undefined);
57
+ return null;
58
+ }
59
+ if (chunk.byteLength > 0)
60
+ chunks.push(chunk);
61
+ }
62
+ }
63
+ finally {
64
+ reader.releaseLock();
65
+ }
66
+ return { chunks, size, head: headOf(chunks) };
67
+ }
68
+ /**
69
+ * What goes to R2, without concatenating the chunks into a second copy (AUD-07): one chunk
70
+ * as is; several through the Workers `FixedLengthStream` (R2 then knows the length). Only
71
+ * outside Workers, where it does not exist, are they joined.
72
+ */
73
+ function r2Value(body) {
74
+ if (body.chunks.length <= 1)
75
+ return body.chunks[0] ?? new Uint8Array(0);
76
+ const Fixed = globalThis.FixedLengthStream;
77
+ if (Fixed) {
78
+ const { readable, writable } = new Fixed(body.size);
79
+ void (async () => {
80
+ const writer = writable.getWriter();
81
+ try {
82
+ for (const c of body.chunks)
83
+ await writer.write(c);
84
+ await writer.close();
85
+ }
86
+ catch (e) {
87
+ await writer.abort(e).catch(() => undefined);
88
+ }
89
+ })();
90
+ return readable;
91
+ }
92
+ const out = new Uint8Array(body.size);
93
+ let at = 0;
94
+ for (const c of body.chunks) {
95
+ out.set(c, at);
96
+ at += c.byteLength;
97
+ }
98
+ return out;
99
+ }
100
+ function toStoredFile(o) {
101
+ return {
102
+ key: o.key,
103
+ size: o.size,
104
+ contentType: o.httpMetadata?.contentType ?? 'application/octet-stream',
105
+ uploadedAt: o.uploaded.toISOString(),
106
+ };
107
+ }
108
+ function resolveMaxBytes(value) {
109
+ if (value === undefined)
110
+ return DEFAULT_MAX_BYTES;
111
+ if (!Number.isSafeInteger(value) || value < 1) {
112
+ throw new AppError('internal', 'storage.errors.invalid_max_bytes', { params: { maxBytes: String(value) } });
113
+ }
114
+ return Math.min(value, HARD_MAX_BYTES);
115
+ }
116
+ const MIN_HEX_LENGTH = 64;
117
+ const MIN_ENCODED_LENGTH = 43;
118
+ const MIN_DISTINCT_CHARS = 8;
119
+ const MAX_PATTERN_PERIOD = 16;
120
+ const PLACEHOLDERS = ['changeme', 'password', 'secret', 'letmein', 'qwerty', 'solobrand', 'testkey', 'example', 'default', 'placeholder', 'yourapp', '123456', 'abcdef'];
121
+ /**
122
+ * A signing secret we accept (SEC-012, SEC-017) — the criterion of http's
123
+ * `testKeyAcceptable`: the shape of ≥ 32 random bytes (64+ hex, or 43+ base64/base64url
124
+ * characters before any `=` padding), ≥ 8 distinct characters, not periodic
125
+ * (`abcdefgh` × 4), and no placeholder word once separators are dropped (`CHANGE_ME_…`).
126
+ * What `sb new` / `sb dev` write (32 random bytes, base64url) always passes.
127
+ */
128
+ export function isStrongSecret(secret) {
129
+ if (typeof secret !== 'string')
130
+ return false;
131
+ const hex = /^[0-9a-f]+$/i.test(secret);
132
+ const body = secret.replace(/={1,2}$/, '');
133
+ if (hex ? secret.length < MIN_HEX_LENGTH : !/^[A-Za-z0-9_\-+/]+$/.test(body) || body.length < MIN_ENCODED_LENGTH)
134
+ return false;
135
+ if (new Set(body.toLowerCase()).size < MIN_DISTINCT_CHARS)
136
+ return false;
137
+ for (let period = 1; period <= MAX_PATTERN_PERIOD; period++) {
138
+ let periodic = true;
139
+ for (let i = period; i < body.length && periodic; i++)
140
+ if (body[i] !== body[i - period])
141
+ periodic = false;
142
+ if (periodic)
143
+ return false;
144
+ }
145
+ const lower = body.toLowerCase().replace(/[-_+/]/g, '');
146
+ return !PLACEHOLDERS.some((word) => lower.includes(word));
147
+ }
148
+ export function createStorageWith(bucket, secret, options = {}) {
149
+ if (!isStrongSecret(secret))
150
+ throw new AppError('internal', 'storage.errors.app_key_missing');
151
+ return {
152
+ async put(key, body, putOptions) {
153
+ const k = normalizeKey(key);
154
+ if (!k.ok)
155
+ return k;
156
+ const maxBytes = resolveMaxBytes(putOptions.maxBytes);
157
+ const type = normalizeMime(putOptions.contentType);
158
+ if (type === null || !isAccepted(type, putOptions.accept ?? DEFAULT_ACCEPT)) {
159
+ return err(fieldError('validation_failed', 'storage.errors.type_not_allowed'));
160
+ }
161
+ let read;
162
+ if (body instanceof ReadableStream) {
163
+ read = await readCapped(body, maxBytes);
164
+ }
165
+ else {
166
+ const bytes = fromBytes(body);
167
+ read = bytes.byteLength > maxBytes ? null : { chunks: [bytes], size: bytes.byteLength, head: bytes.subarray(0, SNIFF_BYTES) };
168
+ }
169
+ if (read === null)
170
+ return err(fieldError('payload_too_large', 'storage.errors.too_large', { max: maxBytes }));
171
+ if (checkContent(type, read.head) !== 'ok') {
172
+ return err(fieldError('validation_failed', 'storage.errors.content_mismatch'));
173
+ }
174
+ const stored = await bucket.put(k.value, r2Value(read), { httpMetadata: { contentType: type } });
175
+ return ok(stored ? toStoredFile(stored) : { key: k.value, size: read.size, contentType: type, uploadedAt: new Date((options.now ?? Date.now)()).toISOString() });
176
+ },
177
+ async get(key) {
178
+ return bucket.get(assertKey(key));
179
+ },
180
+ async delete(key) {
181
+ await bucket.delete(assertKey(key));
182
+ },
183
+ async list(prefix, limit = DEFAULT_LIST_LIMIT) {
184
+ const p = normalizePrefix(prefix);
185
+ if (!p.ok)
186
+ throw p.error;
187
+ const n = Number.isSafeInteger(limit) ? Math.min(Math.max(limit, 1), MAX_LIST_LIMIT) : DEFAULT_LIST_LIMIT;
188
+ const listed = await bucket.list({ prefix: p.value, limit: n, include: ['httpMetadata'] });
189
+ return listed.objects.map(toStoredFile);
190
+ },
191
+ signedUrl(key, ttlSeconds) {
192
+ return signUrl(secret, key, ttlSeconds, options);
193
+ },
194
+ };
195
+ }
196
+ //# sourceMappingURL=storage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storage.js","sourceRoot":"","sources":["../src/storage.ts"],"names":[],"mappings":"AAAA,iEAAiE;AACjE,OAAO,EAAE,QAAQ,EAAE,GAAG,EAAE,EAAE,EAAe,MAAM,iBAAiB,CAAC;AAEjE,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AACrE,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,YAAY,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AACjG,OAAO,EAAE,OAAO,EAAoB,MAAM,cAAc,CAAC;AAEzD,6CAA6C;AAC7C,MAAM,CAAC,MAAM,iBAAiB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAClD;;;GAGG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAC/C,MAAM,CAAC,MAAM,kBAAkB,GAAG,GAAG,CAAC;AACtC,MAAM,CAAC,MAAM,cAAc,GAAG,IAAI,CAAC;AAInC,MAAM,UAAU,GAAG,CAAC,IAA+C,EAAE,UAAkB,EAAE,MAAwC,EAAY,EAAE,CAC7I,IAAI,QAAQ,CAAC,IAAI,EAAE,UAAU,EAAE,MAA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E,OAAO,CAAC,CAAC;QACnD,CAAC;KACF,CAAC;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@solobrand/storage",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Files in the app R2 bucket with signed URLs and limits.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md"
18
+ ],
19
+ "sideEffects": false,
20
+ "scripts": {
21
+ "build": "tsc -b",
22
+ "test": "vitest run",
23
+ "typecheck": "tsc -b --noEmit"
24
+ },
25
+ "dependencies": {
26
+ "@solobrand/core": "0.1.1"
27
+ },
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "https://github.com/innoboxrr/solobrand-framework.git",
31
+ "directory": "packages/storage"
32
+ },
33
+ "publishConfig": {
34
+ "access": "public"
35
+ }
36
+ }