@nage-api/storage 1.0.0-beta.2

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,116 @@
1
+ # @nage-api/storage
2
+
3
+ Uploads, validation and a pluggable CDN (PLAN.md §8, §12, §25 P1).
4
+
5
+ The package exists mostly to make three attacks unavailable by construction: a
6
+ mislabelled file a browser later executes, a filename that escapes the storage
7
+ root, and a "fetch this URL for me" feature that reaches the cloud metadata
8
+ endpoint.
9
+
10
+ <!-- docs-example: fragment -->
11
+
12
+ ```ts
13
+ import { StorageService } from '@nage-api/storage';
14
+
15
+ // Exported by `NageStorageModule.forRoot`, so injecting the class is enough.
16
+ declare const storage: StorageService;
17
+ // Whatever the upload middleware hands the handler. No interceptor ships with
18
+ // this package, so the three untrusted fields arrive under whichever names it
19
+ // uses; these are multer's.
20
+ declare const file: { originalname: string; buffer: Buffer; mimetype: string };
21
+
22
+ const stored = await storage.upload({
23
+ filename: file.originalname, // untrusted
24
+ content: file.buffer,
25
+ contentType: file.mimetype, // also untrusted
26
+ directory: 'avatars',
27
+ });
28
+ // → { key: 'avatars/k3f9x2-my-photo.png', contentType: 'image/png', checksum, url }
29
+ ```
30
+
31
+ Every write goes through the same three steps in the same order — validate the
32
+ bytes, build a safe key, then store. No method skips one, because the single
33
+ call site that skipped validation is where the stored XSS came from.
34
+
35
+ ## The bytes decide, not the client
36
+
37
+ `Content-Type` is a claim and the extension is a claim; both are
38
+ attacker-controlled. The magic bytes are not. A file that says `image/png` and
39
+ starts with `<?php` is refused, and the **verified** type is what gets stored,
40
+ served back, and used to pick the stored extension — so a `.php` that somehow
41
+ survived every other check is still written as `.png`.
42
+
43
+ Also refused: empty files, oversized files, denied extensions (including `.svg`,
44
+ which is a script container), and double extensions like `photo.png.php` — which
45
+ a server that dispatches on the last extension it _recognises_ will happily
46
+ execute.
47
+
48
+ The signature table is short by design. It covers what applications actually
49
+ allow people to upload, and anything outside it fails closed.
50
+
51
+ ## Keys cannot escape
52
+
53
+ A client-supplied filename reaches a filesystem path, so none of it is used
54
+ directly. The key is a random prefix plus a heavily sanitised stem, drawn from
55
+ `[a-z0-9-_]` by allow-list — sanitising by replacement rather than removal, so
56
+ `a/b` and `ab` do not collapse into the same key.
57
+
58
+ `assertSafeKey` then runs before every read and delete, and the local driver
59
+ independently resolves the path and checks it is still under the root. Two
60
+ checks, because path traversal is the failure mode where one missed check is a
61
+ compromise.
62
+
63
+ ## Fetching a URL is an SSRF primitive
64
+
65
+ `uploadFromUrl` is defended in layers, because each layer alone is bypassable:
66
+
67
+ 1. **scheme allow-list** — `https:` only by default;
68
+ 2. **DNS resolution before connecting** — a hostname that _resolves_ to a
69
+ private address is refused. Checking the hostname's text is useless: an
70
+ attacker owns a public domain pointed at `127.0.0.1`;
71
+ 3. **every redirect re-checked** — redirects are followed manually, because a
72
+ public URL that 302s to `169.254.169.254` defeats a check that ran once;
73
+ 4. **size and time limits** — a URL that streams forever is a denial of
74
+ service, not a download.
75
+
76
+ Private means loopback, link-local (including the metadata endpoint), the RFC
77
+ 1918 ranges, carrier-grade NAT, multicast, and their IPv6 equivalents including
78
+ IPv4-mapped forms. Anything that is not parseable as an address is refused
79
+ rather than guessed at.
80
+
81
+ Error messages are split: the client sees "That URL is not reachable from
82
+ here", the log gets which hostname resolved to what.
83
+
84
+ **A residual DNS-rebinding window remains.** Resolution and connection are two
85
+ separate operations, so a name can answer publicly for the check and privately
86
+ for the connection. Closing it needs a custom agent that pins the resolved
87
+ address to the socket; that is not written, and pretending otherwise would be
88
+ worse than saying so.
89
+
90
+ ## Drivers
91
+
92
+ `local` is built in. `s3` and `azure` are declared in `StorageConfig` and must
93
+ be supplied by the application — their SDKs are large, and neither belongs in
94
+ an install that does not use them. A CDN the module cannot build is refused at
95
+ composition time rather than at the first upload.
96
+
97
+ `storage.bucket` and `storage.region` are part of `StorageConfig` for such a
98
+ driver to read. This package never reads them, so setting them without passing a
99
+ `driver` changes nothing.
100
+
101
+ ## Not yet implemented
102
+
103
+ - The S3 and Azure drivers themselves. `StorageDriver` is the seam.
104
+ - The per-field upload decorator §12 asks for. The legacy `@FileUploads`
105
+ decorator, its interceptor and its exception filter have no replacement here:
106
+ a route parses its own multipart body and calls `upload` itself.
107
+ - Serving files back in `local` mode. Nothing in the framework mounts a static
108
+ handler, so `publicBaseUrl` describes a URL you have arranged elsewhere.
109
+ - Wildcard MIME patterns. `validation.mime` is matched exactly, so `image/*`
110
+ accepts nothing rather than every image.
111
+ - The optional anti-virus hook §12 mentions.
112
+ - Streaming uploads; `UploadInput.content` is a `Buffer`, so a very large file
113
+ is held in memory.
114
+ - Image processing (resize, strip EXIF). Stripping metadata before serving a
115
+ user-supplied image is a privacy measure worth having.
116
+ - Signed URLs are on the port and unimplemented by the local driver.
@@ -0,0 +1,19 @@
1
+ /**
2
+ * `@nage-api/storage` — uploads, validation and a pluggable CDN (PLAN.md §8, §12,
3
+ * §25 P1).
4
+ *
5
+ * The package exists mostly to make three attacks unavailable by construction:
6
+ * a mislabelled file that a browser later executes, a filename that escapes the
7
+ * storage root, and a "fetch this URL" feature that reaches the cloud metadata
8
+ * endpoint.
9
+ */
10
+ export type * from '@nage-api/contracts';
11
+ export { NageStorageModule, parseSize, type NageStorageModuleOptions } from './storage.module.js';
12
+ export { StorageService, type StorageServiceOptions } from './storage.service.js';
13
+ export { LocalStorageDriver, type LocalStorageDriverOptions } from './local.driver.js';
14
+ export { RemoteFetcher, isPrivateAddress, type FetchedFile, type RemoteFetchOptions, } from './remote-fetch.js';
15
+ export { DEFAULT_ALLOWED_MIME_TYPES, DEFAULT_DENIED_EXTENSIONS, DEFAULT_MAX_SIZE_BYTES, MAGIC_SIGNATURES, defaultUploadPolicy, detectMimeType, extensionOf, validateUpload, type MagicSignature, } from './validation.js';
16
+ export { assertSafeKey, buildStorageKey, extensionForMimeType, sanitiseDirectory, sanitiseSegment, type BuildKeyOptions, } from './keys.js';
17
+ export { NAGE_STORAGE, NAGE_STORAGE_DRIVER } from './tokens.js';
18
+ export { systemClock, type Clock, type StorageDriver, type StoredFile, type UploadInput, type UploadPolicy, } from './ports.js';
19
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ /**
3
+ * `@nage-api/storage` — uploads, validation and a pluggable CDN (PLAN.md §8, §12,
4
+ * §25 P1).
5
+ *
6
+ * The package exists mostly to make three attacks unavailable by construction:
7
+ * a mislabelled file that a browser later executes, a filename that escapes the
8
+ * storage root, and a "fetch this URL" feature that reaches the cloud metadata
9
+ * endpoint.
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.systemClock = exports.NAGE_STORAGE_DRIVER = exports.NAGE_STORAGE = exports.sanitiseSegment = exports.sanitiseDirectory = exports.extensionForMimeType = exports.buildStorageKey = exports.assertSafeKey = exports.validateUpload = exports.extensionOf = exports.detectMimeType = exports.defaultUploadPolicy = exports.MAGIC_SIGNATURES = exports.DEFAULT_MAX_SIZE_BYTES = exports.DEFAULT_DENIED_EXTENSIONS = exports.DEFAULT_ALLOWED_MIME_TYPES = exports.isPrivateAddress = exports.RemoteFetcher = exports.LocalStorageDriver = exports.StorageService = exports.parseSize = exports.NageStorageModule = void 0;
13
+ var storage_module_js_1 = require("./storage.module.js");
14
+ Object.defineProperty(exports, "NageStorageModule", { enumerable: true, get: function () { return storage_module_js_1.NageStorageModule; } });
15
+ Object.defineProperty(exports, "parseSize", { enumerable: true, get: function () { return storage_module_js_1.parseSize; } });
16
+ var storage_service_js_1 = require("./storage.service.js");
17
+ Object.defineProperty(exports, "StorageService", { enumerable: true, get: function () { return storage_service_js_1.StorageService; } });
18
+ var local_driver_js_1 = require("./local.driver.js");
19
+ Object.defineProperty(exports, "LocalStorageDriver", { enumerable: true, get: function () { return local_driver_js_1.LocalStorageDriver; } });
20
+ var remote_fetch_js_1 = require("./remote-fetch.js");
21
+ Object.defineProperty(exports, "RemoteFetcher", { enumerable: true, get: function () { return remote_fetch_js_1.RemoteFetcher; } });
22
+ Object.defineProperty(exports, "isPrivateAddress", { enumerable: true, get: function () { return remote_fetch_js_1.isPrivateAddress; } });
23
+ var validation_js_1 = require("./validation.js");
24
+ Object.defineProperty(exports, "DEFAULT_ALLOWED_MIME_TYPES", { enumerable: true, get: function () { return validation_js_1.DEFAULT_ALLOWED_MIME_TYPES; } });
25
+ Object.defineProperty(exports, "DEFAULT_DENIED_EXTENSIONS", { enumerable: true, get: function () { return validation_js_1.DEFAULT_DENIED_EXTENSIONS; } });
26
+ Object.defineProperty(exports, "DEFAULT_MAX_SIZE_BYTES", { enumerable: true, get: function () { return validation_js_1.DEFAULT_MAX_SIZE_BYTES; } });
27
+ Object.defineProperty(exports, "MAGIC_SIGNATURES", { enumerable: true, get: function () { return validation_js_1.MAGIC_SIGNATURES; } });
28
+ Object.defineProperty(exports, "defaultUploadPolicy", { enumerable: true, get: function () { return validation_js_1.defaultUploadPolicy; } });
29
+ Object.defineProperty(exports, "detectMimeType", { enumerable: true, get: function () { return validation_js_1.detectMimeType; } });
30
+ Object.defineProperty(exports, "extensionOf", { enumerable: true, get: function () { return validation_js_1.extensionOf; } });
31
+ Object.defineProperty(exports, "validateUpload", { enumerable: true, get: function () { return validation_js_1.validateUpload; } });
32
+ var keys_js_1 = require("./keys.js");
33
+ Object.defineProperty(exports, "assertSafeKey", { enumerable: true, get: function () { return keys_js_1.assertSafeKey; } });
34
+ Object.defineProperty(exports, "buildStorageKey", { enumerable: true, get: function () { return keys_js_1.buildStorageKey; } });
35
+ Object.defineProperty(exports, "extensionForMimeType", { enumerable: true, get: function () { return keys_js_1.extensionForMimeType; } });
36
+ Object.defineProperty(exports, "sanitiseDirectory", { enumerable: true, get: function () { return keys_js_1.sanitiseDirectory; } });
37
+ Object.defineProperty(exports, "sanitiseSegment", { enumerable: true, get: function () { return keys_js_1.sanitiseSegment; } });
38
+ var tokens_js_1 = require("./tokens.js");
39
+ Object.defineProperty(exports, "NAGE_STORAGE", { enumerable: true, get: function () { return tokens_js_1.NAGE_STORAGE; } });
40
+ Object.defineProperty(exports, "NAGE_STORAGE_DRIVER", { enumerable: true, get: function () { return tokens_js_1.NAGE_STORAGE_DRIVER; } });
41
+ var ports_js_1 = require("./ports.js");
42
+ Object.defineProperty(exports, "systemClock", { enumerable: true, get: function () { return ports_js_1.systemClock; } });
43
+ //# sourceMappingURL=index.js.map
package/dist/keys.d.ts ADDED
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Turning a client-supplied filename into a storage key (PLAN.md §12).
3
+ *
4
+ * The filename in a multipart upload is attacker-controlled, and it reaches a
5
+ * filesystem path. `../../etc/cron.d/x`, a null byte, a 4000-character name and
6
+ * a name that differs from another only by a Unicode homoglyph are all things a
7
+ * client can send.
8
+ *
9
+ * So none of it is used directly: the key is built from a random prefix plus a
10
+ * heavily sanitised version of the original, and the sanitiser is
11
+ * allow-list-based — anything outside `[a-z0-9-_]` is replaced rather than
12
+ * escaped. Escaping is where these bugs live.
13
+ */
14
+ export interface BuildKeyOptions {
15
+ readonly filename: string;
16
+ /** Logical folder, e.g. `avatars`. Sanitised the same way. */
17
+ readonly directory?: string;
18
+ /** Extension to force, derived from the **verified** content type. */
19
+ readonly extension?: string;
20
+ /** Injected so a test can assert on an exact key. */
21
+ readonly prefix?: string;
22
+ }
23
+ /**
24
+ * Build a storage key.
25
+ *
26
+ * The result always has the shape `[directory/]<random>-<stem><ext>`, and every
27
+ * component is drawn from a restricted alphabet, so it cannot escape a prefix
28
+ * or mean anything to a shell.
29
+ */
30
+ export declare function buildStorageKey(options: BuildKeyOptions): string;
31
+ /**
32
+ * Reduce a path segment to `[a-z0-9-_]`.
33
+ *
34
+ * Replacement rather than removal, so `a/b` becomes `a-b` rather than `ab` —
35
+ * two different inputs should not silently become the same key.
36
+ */
37
+ export declare function sanitiseSegment(segment: string): string;
38
+ /** A directory of up to three sanitised segments, e.g. `avatars/2026/01`. */
39
+ export declare function sanitiseDirectory(directory: string): string;
40
+ /**
41
+ * Verify a key is one this package could have produced.
42
+ *
43
+ * Called before every read and delete, because a key can arrive from a database
44
+ * row that was written before a validation rule existed, or from a request
45
+ * parameter.
46
+ */
47
+ export declare function assertSafeKey(key: string): void;
48
+ /** The conventional extension for a verified MIME type. */
49
+ export declare function extensionForMimeType(mime: string): string;
50
+ //# sourceMappingURL=keys.d.ts.map
package/dist/keys.js ADDED
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+ /**
3
+ * Turning a client-supplied filename into a storage key (PLAN.md §12).
4
+ *
5
+ * The filename in a multipart upload is attacker-controlled, and it reaches a
6
+ * filesystem path. `../../etc/cron.d/x`, a null byte, a 4000-character name and
7
+ * a name that differs from another only by a Unicode homoglyph are all things a
8
+ * client can send.
9
+ *
10
+ * So none of it is used directly: the key is built from a random prefix plus a
11
+ * heavily sanitised version of the original, and the sanitiser is
12
+ * allow-list-based — anything outside `[a-z0-9-_]` is replaced rather than
13
+ * escaped. Escaping is where these bugs live.
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.buildStorageKey = buildStorageKey;
17
+ exports.sanitiseSegment = sanitiseSegment;
18
+ exports.sanitiseDirectory = sanitiseDirectory;
19
+ exports.assertSafeKey = assertSafeKey;
20
+ exports.extensionForMimeType = extensionForMimeType;
21
+ const core_1 = require("@nage-api/core");
22
+ const core_2 = require("@nage-api/core");
23
+ /** Enough entropy that two uploads of the same name never collide. */
24
+ const PREFIX_LENGTH = 12;
25
+ const MAX_STEM_LENGTH = 64;
26
+ const MAX_DIRECTORY_LENGTH = 64;
27
+ /**
28
+ * Build a storage key.
29
+ *
30
+ * The result always has the shape `[directory/]<random>-<stem><ext>`, and every
31
+ * component is drawn from a restricted alphabet, so it cannot escape a prefix
32
+ * or mean anything to a shell.
33
+ */
34
+ function buildStorageKey(options) {
35
+ const prefix = options.prefix ?? (0, core_1.randomString)(PREFIX_LENGTH).toLowerCase();
36
+ const stem = sanitiseSegment(stemOf(options.filename)).slice(0, MAX_STEM_LENGTH) || 'file';
37
+ const extension = normaliseExtension(options.extension ?? extensionOf(options.filename));
38
+ const directory = options.directory === undefined ? '' : sanitiseDirectory(options.directory);
39
+ const name = `${prefix}-${stem}${extension}`;
40
+ return directory === '' ? name : `${directory}/${name}`;
41
+ }
42
+ /**
43
+ * Reduce a path segment to `[a-z0-9-_]`.
44
+ *
45
+ * Replacement rather than removal, so `a/b` becomes `a-b` rather than `ab` —
46
+ * two different inputs should not silently become the same key.
47
+ */
48
+ function sanitiseSegment(segment) {
49
+ return segment
50
+ .normalize('NFKD')
51
+ .toLowerCase()
52
+ .replace(/[^a-z0-9]+/g, '-')
53
+ .replace(/^-+|-+$/g, '')
54
+ .replace(/-{2,}/g, '-');
55
+ }
56
+ /** A directory of up to three sanitised segments, e.g. `avatars/2026/01`. */
57
+ function sanitiseDirectory(directory) {
58
+ const segments = directory
59
+ .split('/')
60
+ .map((segment) => sanitiseSegment(segment))
61
+ .filter((segment) => segment !== '')
62
+ .slice(0, 3);
63
+ return segments.join('/').slice(0, MAX_DIRECTORY_LENGTH);
64
+ }
65
+ /**
66
+ * Verify a key is one this package could have produced.
67
+ *
68
+ * Called before every read and delete, because a key can arrive from a database
69
+ * row that was written before a validation rule existed, or from a request
70
+ * parameter.
71
+ */
72
+ function assertSafeKey(key) {
73
+ const safe = /^[a-z0-9][a-z0-9\-_]*(?:\/[a-z0-9][a-z0-9\-_]*)*(?:\.[a-z0-9]+)?$/;
74
+ if (key === '' || key.includes('..') || key.includes('\0') || !safe.test(key)) {
75
+ throw new core_2.ConfigurationError({
76
+ detail: `"${key}" is not a storage key this package could have produced`,
77
+ meta: { key },
78
+ });
79
+ }
80
+ }
81
+ function stemOf(filename) {
82
+ const base = filename.split(/[/\\]/).pop() ?? filename;
83
+ const index = base.lastIndexOf('.');
84
+ return index <= 0 ? base : base.slice(0, index);
85
+ }
86
+ function extensionOf(filename) {
87
+ const base = filename.split(/[/\\]/).pop() ?? filename;
88
+ const index = base.lastIndexOf('.');
89
+ return index <= 0 ? '' : base.slice(index);
90
+ }
91
+ function normaliseExtension(extension) {
92
+ const cleaned = extension.toLowerCase().replace(/[^a-z0-9.]/g, '');
93
+ if (cleaned === '' || cleaned === '.')
94
+ return '';
95
+ return cleaned.startsWith('.') ? cleaned : `.${cleaned}`;
96
+ }
97
+ /** The conventional extension for a verified MIME type. */
98
+ function extensionForMimeType(mime) {
99
+ const table = {
100
+ 'image/jpeg': '.jpg',
101
+ 'image/png': '.png',
102
+ 'image/gif': '.gif',
103
+ 'image/webp': '.webp',
104
+ 'application/pdf': '.pdf',
105
+ 'application/zip': '.zip',
106
+ };
107
+ return table[mime] ?? '';
108
+ }
109
+ //# sourceMappingURL=keys.js.map
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Files on the local disk (PLAN.md §8: `cdn: 'local' | 's3' | 'azure'`).
3
+ *
4
+ * The default driver, and the one every development environment uses. Its whole
5
+ * job beyond `writeFile` is refusing to write outside its own root: every path
6
+ * is resolved and then checked against the root, because `path.join` will
7
+ * happily produce `/etc/passwd` from a key that starts with enough `../`.
8
+ *
9
+ * Keys are validated before they get here too, so this is the second of two
10
+ * independent checks. That redundancy is deliberate — path traversal is the
11
+ * failure mode where one missed check is a compromise.
12
+ */
13
+ import type { StorageDriver } from './ports.js';
14
+ export interface LocalStorageDriverOptions {
15
+ /** Directory every file lives under. Created on first write. */
16
+ readonly root: string;
17
+ /** Base URL files are served from, when they are served at all. */
18
+ readonly publicBaseUrl?: string;
19
+ }
20
+ export declare class LocalStorageDriver implements StorageDriver {
21
+ #private;
22
+ readonly name = "local";
23
+ constructor(options: LocalStorageDriverOptions);
24
+ put(key: string, content: Buffer, _contentType: string): Promise<void>;
25
+ get(key: string): Promise<Buffer | undefined>;
26
+ delete(key: string): Promise<void>;
27
+ exists(key: string): Promise<boolean>;
28
+ /** Where a file is served from, when a base URL is configured. */
29
+ publicUrl(key: string): string | undefined;
30
+ get root(): string;
31
+ }
32
+ //# sourceMappingURL=local.driver.d.ts.map
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ /**
3
+ * Files on the local disk (PLAN.md §8: `cdn: 'local' | 's3' | 'azure'`).
4
+ *
5
+ * The default driver, and the one every development environment uses. Its whole
6
+ * job beyond `writeFile` is refusing to write outside its own root: every path
7
+ * is resolved and then checked against the root, because `path.join` will
8
+ * happily produce `/etc/passwd` from a key that starts with enough `../`.
9
+ *
10
+ * Keys are validated before they get here too, so this is the second of two
11
+ * independent checks. That redundancy is deliberate — path traversal is the
12
+ * failure mode where one missed check is a compromise.
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.LocalStorageDriver = void 0;
16
+ const promises_1 = require("node:fs/promises");
17
+ const node_fs_1 = require("node:fs");
18
+ const node_path_1 = require("node:path");
19
+ const core_1 = require("@nage-api/core");
20
+ const keys_js_1 = require("./keys.js");
21
+ class LocalStorageDriver {
22
+ name = 'local';
23
+ #root;
24
+ #publicBaseUrl;
25
+ constructor(options) {
26
+ if (options.root.trim() === '') {
27
+ throw new core_1.ConfigurationError({
28
+ detail: 'The local storage driver needs a root directory',
29
+ meta: { setting: 'storage.root' },
30
+ });
31
+ }
32
+ this.#root = (0, node_path_1.resolve)(options.root);
33
+ this.#publicBaseUrl = options.publicBaseUrl;
34
+ }
35
+ async put(key, content, _contentType) {
36
+ const path = this.#resolve(key);
37
+ await (0, promises_1.mkdir)((0, node_path_1.dirname)(path), { recursive: true });
38
+ await (0, promises_1.writeFile)(path, content);
39
+ }
40
+ async get(key) {
41
+ const path = this.#resolve(key);
42
+ if (!(0, node_fs_1.existsSync)(path))
43
+ return undefined;
44
+ return (0, promises_1.readFile)(path);
45
+ }
46
+ async delete(key) {
47
+ await (0, promises_1.rm)(this.#resolve(key), { force: true });
48
+ }
49
+ async exists(key) {
50
+ await Promise.resolve();
51
+ return (0, node_fs_1.existsSync)(this.#resolve(key));
52
+ }
53
+ /** Where a file is served from, when a base URL is configured. */
54
+ publicUrl(key) {
55
+ if (this.#publicBaseUrl === undefined)
56
+ return undefined;
57
+ (0, keys_js_1.assertSafeKey)(key);
58
+ return `${this.#publicBaseUrl.replace(/\/$/, '')}/${key}`;
59
+ }
60
+ get root() {
61
+ return this.#root;
62
+ }
63
+ /**
64
+ * Resolve a key under the root, refusing anything that escapes it.
65
+ *
66
+ * Both halves matter: `assertSafeKey` rejects the shapes this package never
67
+ * produces, and the `relative` check catches anything that still resolves
68
+ * outside — including through a symlinked parent.
69
+ */
70
+ #resolve(key) {
71
+ (0, keys_js_1.assertSafeKey)(key);
72
+ const path = (0, node_path_1.resolve)((0, node_path_1.join)(this.#root, key));
73
+ const relation = (0, node_path_1.relative)(this.#root, path);
74
+ if (relation.startsWith('..') || relation === '') {
75
+ throw new core_1.ConfigurationError({
76
+ detail: `"${key}" resolves outside the storage root`,
77
+ meta: { key },
78
+ });
79
+ }
80
+ return path;
81
+ }
82
+ }
83
+ exports.LocalStorageDriver = LocalStorageDriver;
84
+ //# sourceMappingURL=local.driver.js.map