@formless63/file-delivery 0.0.0-stage → 0.1.0

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 formless63
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,60 @@
1
- # Temporary Holding Version
1
+ # @formless63/file-delivery
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
+ Response headers for serving user uploads from your own origin without letting
4
+ one of them run script as the viewer.
5
+
6
+ A stored content type is usually whatever the uploader claimed. Served inline, a
7
+ file claiming `text/html` is a page on your site. `nosniff` does not help: the
8
+ type is wrong, not sniffed.
9
+
10
+ ```ts
11
+ import { fileDelivery } from '@formless63/file-delivery';
12
+
13
+ const { headers } = fileDelivery({ contentType: stored.type, filename: stored.name });
14
+ return new Response(stream, { headers: { ...headers, 'Cache-Control': 'private' } });
15
+ ```
16
+
17
+ | Stored type | Served as |
18
+ | ------------------------------------ | -------------------------------------------------------------------------- |
19
+ | Image, audio, video, text, JSON, CSV | Inline, sandboxed by a `Content-Security-Policy` |
20
+ | SVG | The same: works in `<img>`, cannot run script when opened |
21
+ | PDF | Inline, not sandboxed, because Chromium's viewer refuses to open sandboxed |
22
+ | Anything else, or malformed | `application/octet-stream` download |
23
+
24
+ Always `nosniff`, and a `Content-Disposition` that is legal for any filename.
25
+
26
+ **Comma-joined types.** Browsers use the last type in a comma-joined value, so
27
+ Chromium renders `application/pdf;x=1, text/html` as HTML, `nosniff` or not, while
28
+ code splitting on `;` sees a PDF. Such values are refused here. The browser suite
29
+ demonstrates the attack and the defence.
30
+
31
+ ## Accepting uploads
32
+
33
+ ```ts
34
+ import { fileTypeFromBuffer } from 'file-type';
35
+ import { uploadType } from '@formless63/file-delivery';
36
+
37
+ const type = uploadType({
38
+ detected: (await fileTypeFromBuffer(bytes))?.mime,
39
+ declared: file.type,
40
+ filename: file.name,
41
+ opaqueZipExtensions: ['lbx'], // ZIP inside, but must download under its own name
42
+ });
43
+ if (!type.ok) return new Response('Contents do not match the declared type', { status: 415 });
44
+ ```
45
+
46
+ Detected bytes beat the declaration and real conflicts are refused, with known
47
+ alternative spellings (GLB, STL, ZIP) allowed. Text formats have no signature and
48
+ keep the declared type, which is why delivery does not trust it.
49
+
50
+ ## Untrusted documents
51
+
52
+ `untrustedDocumentHeaders()` is for captured pages and stored emails that should
53
+ render: no script, no network, no origin. It isolates; it does not sanitise.
54
+
55
+ ## Limits
56
+
57
+ This is defence in depth. Serving uploads from a separate origin is stronger.
58
+ It does not do caching, conditional or range requests, or malware scanning.
59
+ Verified in Chromium; Firefox and Safari follow the same standards but are not
60
+ tested. `frame-ancestors 'self'` allows embedding by your own pages only.
@@ -0,0 +1 @@
1
+ {"version":"7.0.2","root":[[71,73]],"packageJsons":["../package.json"],"fileNames":["lib.es5.d.ts","lib.es2015.d.ts","lib.es2016.d.ts","lib.es2017.d.ts","lib.es2018.d.ts","lib.es2019.d.ts","lib.es2020.d.ts","lib.es2021.d.ts","lib.es2022.d.ts","lib.es2023.d.ts","lib.es2024.d.ts","lib.dom.d.ts","lib.es2015.core.d.ts","lib.es2015.collection.d.ts","lib.es2015.generator.d.ts","lib.es2015.iterable.d.ts","lib.es2015.promise.d.ts","lib.es2015.proxy.d.ts","lib.es2015.reflect.d.ts","lib.es2015.symbol.d.ts","lib.es2015.symbol.wellknown.d.ts","lib.es2016.array.include.d.ts","lib.es2016.intl.d.ts","lib.es2017.arraybuffer.d.ts","lib.es2017.date.d.ts","lib.es2017.object.d.ts","lib.es2017.sharedmemory.d.ts","lib.es2017.string.d.ts","lib.es2017.intl.d.ts","lib.es2017.typedarrays.d.ts","lib.es2018.asyncgenerator.d.ts","lib.es2018.asynciterable.d.ts","lib.es2018.intl.d.ts","lib.es2018.promise.d.ts","lib.es2018.regexp.d.ts","lib.es2019.array.d.ts","lib.es2019.object.d.ts","lib.es2019.string.d.ts","lib.es2019.symbol.d.ts","lib.es2019.intl.d.ts","lib.es2020.bigint.d.ts","lib.es2020.date.d.ts","lib.es2020.promise.d.ts","lib.es2020.sharedmemory.d.ts","lib.es2020.string.d.ts","lib.es2020.symbol.wellknown.d.ts","lib.es2020.intl.d.ts","lib.es2020.number.d.ts","lib.es2021.promise.d.ts","lib.es2021.string.d.ts","lib.es2021.weakref.d.ts","lib.es2021.intl.d.ts","lib.es2022.array.d.ts","lib.es2022.error.d.ts","lib.es2022.intl.d.ts","lib.es2022.object.d.ts","lib.es2022.string.d.ts","lib.es2022.regexp.d.ts","lib.es2023.array.d.ts","lib.es2023.collection.d.ts","lib.es2023.intl.d.ts","lib.es2024.arraybuffer.d.ts","lib.es2024.collection.d.ts","lib.es2024.object.d.ts","lib.es2024.promise.d.ts","lib.es2024.regexp.d.ts","lib.es2024.sharedmemory.d.ts","lib.es2024.string.d.ts","lib.decorators.d.ts","lib.decorators.legacy.d.ts","../src/delivery.ts","../src/upload.ts","../src/index.ts"],"fileInfos":[{"version":"16934abaab7026ac114da441aabea1a0","affectsGlobalScope":true,"impliedNodeFormat":1},"d4306fb2e47f74835e8674ffac07d76f","e437c5c1302869326c3bb93da85bbbcf","e4324975a566567b21d350615f1fc6ac","333b1b9a2a9ac3b8497dba5c63b5ba50","6cffacd662b6eb5fa7a36aa2ea366bfa","b4c34f9c23304dbef2d23698637ed638","e5cb86a5fc491796ecd1d2dd348d208f","feb6c6fb19cdb246a5d8acb36a6901c7","9443a7f109277ffaa79d893ed2549995","793cee405385076e27c24f409659dccd",{"version":"aae8996e8b5684814785a42cbbefcd79","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"926204c28cd3d073865348473ae28d2e","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"f25e42c801b2cb3cf2b39792006a9beb","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"6344b55f26a4e81d9608777dbfb877dd","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"3c0ed28e53d3695b363e256ec1c023fd","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"4c2761daba7f17141c25baa0821ac5da","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"b87656acabd63e69379ff6ffcfe52fc7","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"597469522da047a5af5222cc6989f405","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"1708ea4d34dc37fadadc63ca01127e80","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"55d97a8c6fbf34a30450a7b1e5f7a298","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"0ee05eb59426d33e374226d8dcfa708b","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"e347c14030993906efcfbb88915b6a05","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"b0231263857c9b6a03641acdc9280ceb","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"3b15c4a83b598cacb4067676e6f0abed","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"b417d97b7934cef63b1889abec0bbfbf","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"09a6cf4032ebba60ce22a501e663f881","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"2b056277dd138e8f5650fc04e20eaa8d","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"e22cc07e3f3cc242ba52fa3f8ea1fc58","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"2c45da767a1bfbb220848df1bc4029e4","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"b44c3e0fbaf2130cdcf6ac38b120ffa1","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"b612fb5cf8e5d964b92063a75207632a","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"02705151a5e1551b9162a9ed8ab763f7","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"41025e398be9215d32e4337335da8f0b","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"52684c2b1f353a5538e4f275182a54cd","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"6dedb6a4f90d1df3a6fbe5693e44886c","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"ca3f36fe3562c07e0f0d71c2bebd3f6d","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"409974d6129befbb8226ddd1c6558568","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"4d9cfde2a1ae1b4925f1f9bc10848e5d","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"7e1daecc66dd564144e3bb1a0266b5fd","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"a8e1d9bb35fd0637f2f9fd2b2a54f2ec","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"4f168501772a6543182765bfd5f2fbfe","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"a19c80aad1b2162103496f5ba293a732","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"b69afa63cd5d059851c78adb2856ee09","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"ae2fc5d954e9b0f5feee3d481b953c27","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"1cfd3091a071d8b6feec15277643bafe","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"1da2c1f258970fd3cc91184f69e91a9d","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"a0d87491913d843139e0c993650a3235","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"4ef72aa378127e7b7abba915b0110b1e","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"3ec74c6a7d4463f0254db3a74cf75646","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"84c2bdfa470d075526cce6322d81b0b6","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"0b3844c2b8c73e4e1ab91431411cad11","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"4fc71cf4a15b8d99675a31df77f26e07","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"d1b49564ddaeca3df5b6dbae925d2242","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"6a25be566d60ccfc2d6e8b7bfdeefa83","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"8a20e27646985dfd58c57ca6566553dd","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"9969f02ad3cdcbf4f709405cda44167f","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"9c9be4792a7a4f42c15ae7360bf28779","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"8cf777fe00349b71ee9c4b6f3fe7fd19","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"74f96bc192530c9723f572bfff3d3078","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"1df91c56b25955c56387426f378173c5","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"38856f70edcd2115c355d96ec77cc09e","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"de8700156c1275465bcd473c28b359aa","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"d47cfdb6ede40518357bb5a4cd7cd9fb","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"6e5773860cd9e5b15e683113f642ab47","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"30ff5fe1682f7fcd629880476ca3c2e0","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"bf23d7d1b40b9015b694ddc2f011752f","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"2cc585d42e2c548f9f24a30a1989fd33","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"f64453cbf9671f28158677fa5c43967a","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"33f317af5428801f944a478d2c1e38e5","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"d57d5fa460c3194cbe7cea0724a40319","signature":"6ce3d73884cc30c5e9498dad9e6019c6","impliedNodeFormat":99},{"version":"638e6eeaae692a46e30f699223205c49","signature":"d9bb32cdc170637cb40a6f311f120639","impliedNodeFormat":99},{"version":"7bff3f61b7cc5cd1dd483e26f7c680b4","impliedNodeFormat":99}],"fileIdsList":[[71,72],[71]],"options":{"allowImportingTsExtensions":true,"composite":true,"declaration":true,"declarationMap":true,"erasableSyntaxOnly":true,"exactOptionalPropertyTypes":true,"module":199,"noUncheckedIndexedAccess":true,"outDir":"./","rewriteRelativeImportExtensions":true,"rootDir":"../src","skipLibCheck":true,"strict":true,"sourceMap":true,"target":10,"tsBuildInfoFile":"./.tsbuildinfo","verbatimModuleSyntax":true},"referencedMap":[[73,1],[72,2]],"latestChangedDtsFile":"./index.d.ts"}
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Response headers for serving stored uploads from an application's own origin.
3
+ *
4
+ * The stored content type is untrusted: it is often whatever the uploader
5
+ * claimed, and formats without a signature cannot be checked. Served inline, a
6
+ * file claiming `text/html` runs script with the viewer's session. So:
7
+ *
8
+ * - Only allowlisted passive types are inline, with their own type.
9
+ * - Inline responses carry an opaque-origin, no-script `sandbox` policy. PDF is
10
+ * the exception: Chromium will not open its viewer in a sandboxed document.
11
+ * - Everything else is an `application/octet-stream` attachment.
12
+ * - `nosniff` always.
13
+ *
14
+ * Pure: no framework, no I/O.
15
+ */
16
+ /**
17
+ * Types safe to render. SVG can carry script but is here because pages embed it
18
+ * with `<img>`, where script never runs; the sandbox policy covers opening it
19
+ * directly.
20
+ */
21
+ export declare const INLINE_CONTENT_TYPES: readonly string[];
22
+ /** Opaque origin, no script, nothing loaded except same-origin media. */
23
+ export declare const INLINE_POLICY: string;
24
+ /** For untrusted HTML documents, such as captured pages: nothing loaded at all. */
25
+ export declare const DOCUMENT_POLICY: string;
26
+ /**
27
+ * The bare lower-case type, or null when it is missing or malformed.
28
+ *
29
+ * Commas matter. Browsers take the LAST valid type in a comma-joined value, so
30
+ * `application/pdf;x=1, text/html` is HTML to Chromium, `nosniff` or not, while
31
+ * code that splits on `;` sees a PDF. Any comma makes the value invalid here.
32
+ */
33
+ export declare function bareContentType(contentType: string | null | undefined): string | null;
34
+ export interface FileDeliveryInput {
35
+ /** What the store recorded. Untrusted. */
36
+ contentType: string | null | undefined;
37
+ filename: string;
38
+ /** Force a download. Can only make the response safer. */
39
+ download?: boolean | undefined;
40
+ /** Replace the allowlist. Never add a type that can run script. */
41
+ inlineTypes?: readonly string[] | undefined;
42
+ }
43
+ export interface FileDelivery {
44
+ contentType: string;
45
+ disposition: 'inline' | 'attachment';
46
+ /** Every security-relevant header. Add caching, length and range headers. */
47
+ headers: Record<string, string>;
48
+ }
49
+ export declare function fileDelivery(input: FileDeliveryInput): FileDelivery;
50
+ /**
51
+ * Headers for an untrusted HTML document the reader should see rendered. The
52
+ * policy is on the response, not only on an iframe, because the URL can be
53
+ * opened on its own. Isolation, not sanitising. Do not add `'self'` sources:
54
+ * they would let the document make the reader's authenticated requests.
55
+ */
56
+ export declare function untrustedDocumentHeaders(contentType?: string): Record<string, string>;
57
+ /**
58
+ * A `Content-Disposition` that is always a legal header, whatever the filename:
59
+ * an ASCII `filename` plus an RFC 8187 `filename*`.
60
+ */
61
+ export declare function contentDisposition(disposition: 'inline' | 'attachment', filename: string): string;
62
+ //# sourceMappingURL=delivery.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delivery.d.ts","sourceRoot":"","sources":["../src/delivery.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,EAAE,SAAS,MAAM,EA6BjD,CAAC;AAEF,yEAAyE;AACzE,eAAO,MAAM,aAAa,EAAE,MAA2D,CAAC;AAExF,mFAAmF;AACnF,eAAO,MAAM,eAAe,EAAE,MAM7B,CAAC;AAqBF;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,GAAG,IAAI,CAIrF;AAED,MAAM,WAAW,iBAAiB;IAChC,0CAA0C;IAC1C,WAAW,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IACvC,QAAQ,EAAE,MAAM,CAAC;IACjB,0DAA0D;IAC1D,QAAQ,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAC/B,mEAAmE;IACnE,WAAW,CAAC,EAAE,SAAS,MAAM,EAAE,GAAG,SAAS,CAAC;CAC7C;AAED,MAAM,WAAW,YAAY;IAC3B,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,QAAQ,GAAG,YAAY,CAAC;IACrC,6EAA6E;IAC7E,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACjC;AAED,wBAAgB,YAAY,CAAC,KAAK,EAAE,iBAAiB,GAAG,YAAY,CAcnE;AAED;;;;;GAKG;AACH,wBAAgB,wBAAwB,CACtC,WAAW,SAA6B,GACvC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAQxB;AAWD;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,WAAW,EAAE,QAAQ,GAAG,YAAY,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAcjG"}
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Response headers for serving stored uploads from an application's own origin.
3
+ *
4
+ * The stored content type is untrusted: it is often whatever the uploader
5
+ * claimed, and formats without a signature cannot be checked. Served inline, a
6
+ * file claiming `text/html` runs script with the viewer's session. So:
7
+ *
8
+ * - Only allowlisted passive types are inline, with their own type.
9
+ * - Inline responses carry an opaque-origin, no-script `sandbox` policy. PDF is
10
+ * the exception: Chromium will not open its viewer in a sandboxed document.
11
+ * - Everything else is an `application/octet-stream` attachment.
12
+ * - `nosniff` always.
13
+ *
14
+ * Pure: no framework, no I/O.
15
+ */
16
+ /**
17
+ * Types safe to render. SVG can carry script but is here because pages embed it
18
+ * with `<img>`, where script never runs; the sandbox policy covers opening it
19
+ * directly.
20
+ */
21
+ export const INLINE_CONTENT_TYPES = [
22
+ 'image/png',
23
+ 'image/jpeg',
24
+ 'image/gif',
25
+ 'image/webp',
26
+ 'image/avif',
27
+ 'image/bmp',
28
+ 'image/x-icon',
29
+ 'image/vnd.microsoft.icon',
30
+ 'image/apng',
31
+ 'image/svg+xml',
32
+ 'application/pdf',
33
+ 'text/plain',
34
+ 'text/csv',
35
+ 'text/markdown',
36
+ 'text/x-markdown',
37
+ 'application/json',
38
+ 'audio/mpeg',
39
+ 'audio/mp4',
40
+ 'audio/aac',
41
+ 'audio/ogg',
42
+ 'audio/wav',
43
+ 'audio/x-wav',
44
+ 'audio/webm',
45
+ 'audio/flac',
46
+ 'video/mp4',
47
+ 'video/webm',
48
+ 'video/ogg',
49
+ 'video/quicktime',
50
+ ];
51
+ /** Opaque origin, no script, nothing loaded except same-origin media. */
52
+ export const INLINE_POLICY = policy("img-src 'self' data:", "media-src 'self'");
53
+ /** For untrusted HTML documents, such as captured pages: nothing loaded at all. */
54
+ export const DOCUMENT_POLICY = policy('img-src data:', 'font-src data:', 'media-src data:', "connect-src 'none'", "frame-src 'none'");
55
+ function policy(...sources) {
56
+ return [
57
+ 'sandbox',
58
+ "default-src 'none'",
59
+ "script-src 'none'",
60
+ "style-src 'unsafe-inline'",
61
+ ...sources,
62
+ "object-src 'none'",
63
+ "base-uri 'none'",
64
+ "form-action 'none'",
65
+ "frame-ancestors 'self'",
66
+ ].join('; ');
67
+ }
68
+ // RFC 9110 token. A value that is not exactly token/token is not a type.
69
+ const TOKEN = "[!#$%&'*+.^_`|~0-9a-z-]+";
70
+ const TYPE = new RegExp(`^${TOKEN}/${TOKEN}$`);
71
+ const CHARSET = new RegExp(`^charset="?(${TOKEN})"?$`);
72
+ /**
73
+ * The bare lower-case type, or null when it is missing or malformed.
74
+ *
75
+ * Commas matter. Browsers take the LAST valid type in a comma-joined value, so
76
+ * `application/pdf;x=1, text/html` is HTML to Chromium, `nosniff` or not, while
77
+ * code that splits on `;` sees a PDF. Any comma makes the value invalid here.
78
+ */
79
+ export function bareContentType(contentType) {
80
+ if (typeof contentType !== 'string' || contentType.includes(','))
81
+ return null;
82
+ const bare = contentType.split(';', 1)[0].trim().toLowerCase();
83
+ return TYPE.test(bare) ? bare : null;
84
+ }
85
+ export function fileDelivery(input) {
86
+ const bare = bareContentType(input.contentType);
87
+ const safe = bare !== null && (input.inlineTypes ?? INLINE_CONTENT_TYPES).includes(bare);
88
+ const contentType = safe ? withCharset(bare, input.contentType) : 'application/octet-stream';
89
+ const disposition = safe && input.download !== true ? 'inline' : 'attachment';
90
+ const headers = {
91
+ 'Content-Type': contentType,
92
+ 'Content-Disposition': contentDisposition(disposition, input.filename),
93
+ 'X-Content-Type-Options': 'nosniff',
94
+ };
95
+ if (disposition === 'inline' && bare !== 'application/pdf') {
96
+ headers['Content-Security-Policy'] = INLINE_POLICY;
97
+ }
98
+ return { contentType, disposition, headers };
99
+ }
100
+ /**
101
+ * Headers for an untrusted HTML document the reader should see rendered. The
102
+ * policy is on the response, not only on an iframe, because the URL can be
103
+ * opened on its own. Isolation, not sanitising. Do not add `'self'` sources:
104
+ * they would let the document make the reader's authenticated requests.
105
+ */
106
+ export function untrustedDocumentHeaders(contentType = 'text/html; charset=utf-8') {
107
+ const bare = bareContentType(contentType);
108
+ return {
109
+ 'Content-Type': bare === null ? 'application/octet-stream' : withCharset(bare, contentType),
110
+ 'Content-Security-Policy': DOCUMENT_POLICY,
111
+ 'X-Content-Type-Options': 'nosniff',
112
+ 'Referrer-Policy': 'no-referrer',
113
+ };
114
+ }
115
+ /** The type rebuilt from validated parts; only a plain charset survives. */
116
+ function withCharset(bare, original) {
117
+ for (const part of original.split(';').slice(1)) {
118
+ const charset = CHARSET.exec(part.trim().toLowerCase())?.[1];
119
+ if (charset)
120
+ return `${bare}; charset=${charset}`;
121
+ }
122
+ return bare;
123
+ }
124
+ /**
125
+ * A `Content-Disposition` that is always a legal header, whatever the filename:
126
+ * an ASCII `filename` plus an RFC 8187 `filename*`.
127
+ */
128
+ export function contentDisposition(disposition, filename) {
129
+ const cleaned = filename
130
+ // Controls, and bidi overrides that disguise an extension ("exe.gpj").
131
+ // oxlint-disable-next-line no-control-regex
132
+ .replace(/[\u0000-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, '')
133
+ .trim()
134
+ .toWellFormed() || 'download';
135
+ const ascii = cleaned.replace(/[^\x20-\x7e]|["\\%]/g, '_');
136
+ const encoded = encodeURIComponent(cleaned).replace(/['()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
137
+ return `${disposition}; filename="${ascii}"; filename*=UTF-8''${encoded}`;
138
+ }
139
+ //# sourceMappingURL=delivery.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delivery.js","sourceRoot":"","sources":["../src/delivery.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH;;;;GAIG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAsB;IACrD,WAAW;IACX,YAAY;IACZ,WAAW;IACX,YAAY;IACZ,YAAY;IACZ,WAAW;IACX,cAAc;IACd,0BAA0B;IAC1B,YAAY;IACZ,eAAe;IACf,iBAAiB;IACjB,YAAY;IACZ,UAAU;IACV,eAAe;IAC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CAAC;AAED,4EAA4E;AAC5E,SAAS,WAAW,CAAC,IAAY,EAAE,QAAgB;IACjD,KAAK,MAAM,IAAI,IAAI,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;QAChD,MAAM,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;QAC7D,IAAI,OAAO;YAAE,OAAO,GAAG,IAAI,aAAa,OAAO,EAAE,CAAC;IACpD,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CAAC,WAAoC,EAAE,QAAgB;IACvF,MAAM,OAAO,GACX,QAAQ;QACN,uEAAuE;QACvE,4CAA4C;SAC3C,OAAO,CAAC,qEAAqE,EAAE,EAAE,CAAC;SAClF,IAAI,EAAE;SACN,YAAY,EAAE,IAAI,UAAU,CAAC;IAClC,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,sBAAsB,EAAE,GAAG,CAAC,CAAC;IAC3D,MAAM,OAAO,GAAG,kBAAkB,CAAC,OAAO,CAAC,CAAC,OAAO,CACjD,SAAS,EACT,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,WAAW,EAAE,EAAE,CACxD,CAAC;IACF,OAAO,GAAG,WAAW,eAAe,KAAK,uBAAuB,OAAO,EAAE,CAAC;AAC5E,CAAC"}
@@ -0,0 +1,3 @@
1
+ export * from './delivery.ts';
2
+ export * from './upload.ts';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,eAAe,CAAC;AAC9B,cAAc,aAAa,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from './delivery.js';
2
+ export * from './upload.js';
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,eAAe,CAAC;AAC9B,cAAc,aAAa,CAAC"}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Declared types that describe the same format as a detected one. Browsers
3
+ * declare from the file extension and the OS, so these are honest spellings, not
4
+ * disguises. Extending a row is safe; it never accepts a different format.
5
+ */
6
+ export declare const SAME_FORMAT_TYPES: Readonly<Record<string, readonly string[]>>;
7
+ export interface UploadTypeInput {
8
+ /** From the bytes, e.g. `fileTypeFromBuffer` of `file-type`. Null when unrecognised. */
9
+ detected: string | null | undefined;
10
+ /** What the client said. */
11
+ declared: string | null | undefined;
12
+ filename: string;
13
+ sameFormat?: Readonly<Record<string, readonly string[]>> | undefined;
14
+ /**
15
+ * Extensions of formats that are ZIP files inside but not archives, such as
16
+ * `lbx`. Stored as `application/zip`, Chromium would rename the download to
17
+ * `.zip`; stored as octet-stream it keeps its name.
18
+ */
19
+ opaqueZipExtensions?: readonly string[] | undefined;
20
+ }
21
+ export type UploadType = {
22
+ ok: true;
23
+ contentType: string;
24
+ }
25
+ /** The bytes are a different format from the one declared. */
26
+ | {
27
+ ok: false;
28
+ detected: string;
29
+ declared: string;
30
+ };
31
+ /**
32
+ * Decide the type to store for an upload.
33
+ *
34
+ * Detected bytes beat the declaration, and a real conflict is refused. Bytes
35
+ * with no signature (text, CSV, SVG) keep the declared type, which is why
36
+ * delivery must not trust it: see `fileDelivery`.
37
+ */
38
+ export declare function uploadType(input: UploadTypeInput): UploadType;
39
+ //# sourceMappingURL=upload.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upload.d.ts","sourceRoot":"","sources":["../src/upload.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC,CAgBzE,CAAC;AAEF,MAAM,WAAW,eAAe;IAC9B,wFAAwF;IACxF,QAAQ,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IACpC,4BAA4B;IAC5B,QAAQ,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IACpC,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC,CAAC,GAAG,SAAS,CAAC;IACrE;;;;OAIG;IACH,mBAAmB,CAAC,EAAE,SAAS,MAAM,EAAE,GAAG,SAAS,CAAC;CACrD;AAED,MAAM,MAAM,UAAU,GAClB;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE;AACnC,8DAA8D;GAC5D;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,CAAC;AAEtD;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,eAAe,GAAG,UAAU,CAuB7D"}
package/dist/upload.js ADDED
@@ -0,0 +1,52 @@
1
+ import { bareContentType } from './delivery.js';
2
+ /**
3
+ * Declared types that describe the same format as a detected one. Browsers
4
+ * declare from the file extension and the OS, so these are honest spellings, not
5
+ * disguises. Extending a row is safe; it never accepts a different format.
6
+ */
7
+ export const SAME_FORMAT_TYPES = {
8
+ 'model/gltf-binary': ['model/gltf+json', 'model/gltf.binary', 'application/octet-stream'],
9
+ 'model/stl': [
10
+ 'application/sla',
11
+ 'application/vnd.ms-pki.stl',
12
+ 'application/x-navistyle',
13
+ 'model/x.stl-ascii',
14
+ 'model/x.stl-binary',
15
+ 'application/octet-stream',
16
+ ],
17
+ 'application/zip': [
18
+ 'application/octet-stream',
19
+ 'application/x-zip-compressed',
20
+ 'application/x-zip',
21
+ 'multipart/x-zip',
22
+ ],
23
+ };
24
+ /**
25
+ * Decide the type to store for an upload.
26
+ *
27
+ * Detected bytes beat the declaration, and a real conflict is refused. Bytes
28
+ * with no signature (text, CSV, SVG) keep the declared type, which is why
29
+ * delivery must not trust it: see `fileDelivery`.
30
+ */
31
+ export function uploadType(input) {
32
+ const detected = bareContentType(input.detected);
33
+ const declared = bareContentType(input.declared);
34
+ const sameFormat = input.sameFormat ?? SAME_FORMAT_TYPES;
35
+ if (detected !== null &&
36
+ declared !== null &&
37
+ detected !== declared &&
38
+ !(Object.hasOwn(sameFormat, detected) && sameFormat[detected].includes(declared))) {
39
+ return { ok: false, detected, declared };
40
+ }
41
+ const contentType = detected ?? declared ?? 'application/octet-stream';
42
+ const extension = /\.([^./\\]+)$/.exec(input.filename.trim())?.[1]?.toLowerCase();
43
+ const zip = contentType === 'application/zip' ||
44
+ (Object.hasOwn(sameFormat, 'application/zip') &&
45
+ contentType !== 'application/octet-stream' &&
46
+ sameFormat['application/zip'].includes(contentType));
47
+ if (zip && extension !== undefined && input.opaqueZipExtensions?.includes(extension)) {
48
+ return { ok: true, contentType: 'application/octet-stream' };
49
+ }
50
+ return { ok: true, contentType };
51
+ }
52
+ //# sourceMappingURL=upload.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upload.js","sourceRoot":"","sources":["../src/upload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAEhD;;;;GAIG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAgD;IAC5E,mBAAmB,EAAE,CAAC,iBAAiB,EAAE,mBAAmB,EAAE,0BAA0B,CAAC;IACzF,WAAW,EAAE;QACX,iBAAiB;QACjB,4BAA4B;QAC5B,yBAAyB;QACzB,mBAAmB;QACnB,oBAAoB;QACpB,0BAA0B;KAC3B;IACD,iBAAiB,EAAE;QACjB,0BAA0B;QAC1B,8BAA8B;QAC9B,mBAAmB;QACn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,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,CAAC;AACnC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@formless63/file-delivery",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Response headers that make serving user uploads safe.",
5
+ "keywords": [
6
+ "upload",
7
+ "security",
8
+ "content-disposition",
9
+ "csp",
10
+ "headers"
11
+ ],
12
+ "license": "MIT",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/formless63/netlibs.git",
16
+ "directory": "packages/file-delivery"
17
+ },
18
+ "homepage": "https://github.com/formless63/netlibs/tree/main/packages/file-delivery#readme",
19
+ "bugs": {
20
+ "url": "https://github.com/formless63/netlibs/issues"
21
+ },
22
+ "type": "module",
23
+ "sideEffects": false,
24
+ "engines": {
25
+ "node": ">=22"
26
+ },
27
+ "files": [
28
+ "dist",
29
+ "README.md",
30
+ "LICENSE"
31
+ ],
32
+ "exports": {
33
+ ".": {
34
+ "types": "./dist/index.d.ts",
35
+ "default": "./dist/index.js"
36
+ },
37
+ "./package.json": "./package.json"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ }
42
+ }