@uppercut-labs/static-file-server 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 +21 -0
- package/README.md +75 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +79 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +4 -0
- package/dist/mime.d.ts +7 -0
- package/dist/mime.js +50 -0
- package/dist/path.d.ts +22 -0
- package/dist/path.js +52 -0
- package/dist/range.d.ts +13 -0
- package/dist/range.js +29 -0
- package/dist/server.d.ts +67 -0
- package/dist/server.js +208 -0
- package/package.json +50 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Uppercut Labs
|
|
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,76 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @uppercut-labs/static-file-server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Serves a folder over HTTP from Node with no dependencies. It rejects path traversal (including encoded dots and symlinks that leave the folder), sends the right content type, answers range requests so video can seek, and can fall back to `index.html` for client-side routes. It works as a function you call from code and as a small command line tool.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install @uppercut-labs/static-file-server
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { startStaticServer } from '@uppercut-labs/static-file-server';
|
|
11
|
+
|
|
12
|
+
const site = await startStaticServer({ root: './dist', spaFallback: true });
|
|
13
|
+
console.log(site.url); // http://127.0.0.1:<free port>
|
|
14
|
+
// ...
|
|
15
|
+
await site.close();
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
To use your own server, build a handler:
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import { createServer } from 'node:http';
|
|
22
|
+
import { createStaticHandler } from '@uppercut-labs/static-file-server';
|
|
23
|
+
|
|
24
|
+
const handle = createStaticHandler({ root: './dist', cleanUrls: true });
|
|
25
|
+
createServer((req, res) => void handle(req, res)).listen(3000);
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Command line:
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
npx static-file-server ./dist --port 8080 --spa
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Functions
|
|
35
|
+
|
|
36
|
+
| Function | Returns |
|
|
37
|
+
| --- | --- |
|
|
38
|
+
| `startStaticServer(options)` | `Promise<{ server, host, port, url, close() }>`, listening |
|
|
39
|
+
| `createStaticServer(options)` | an `http.Server`, not yet listening |
|
|
40
|
+
| `createStaticHandler(options)` | `(request, response) => Promise<void>` |
|
|
41
|
+
| `resolveStaticPath(root, urlPath)` | `{ ok: true, file, isDirectory }` or `{ ok: false, problem }` where `problem` is `bad-request`, `forbidden` or `not-found` |
|
|
42
|
+
| `parseRange(header, size)` | `{ start, end }`, `'unsatisfiable'`, or `null` to send the whole file |
|
|
43
|
+
| `contentTypeFor(file, extra?)` | content type string |
|
|
44
|
+
| `MIME_TYPES` | the built-in extension table |
|
|
45
|
+
|
|
46
|
+
## Options
|
|
47
|
+
|
|
48
|
+
| Option | Default | Meaning |
|
|
49
|
+
| --- | --- | --- |
|
|
50
|
+
| `root` | required | Folder to serve |
|
|
51
|
+
| `port` | `0` | Port for `startStaticServer`; 0 picks a free one |
|
|
52
|
+
| `host` | `127.0.0.1` | Interface for `startStaticServer` |
|
|
53
|
+
| `index` | `index.html` | Index file name |
|
|
54
|
+
| `spaFallback` | `false` | Send the index file for unknown paths without an extension. `{ exclude: ['/api'] }` keeps prefixes out |
|
|
55
|
+
| `cleanUrls` | `false` | Try `<path>.html` and `<path>/index.html` |
|
|
56
|
+
| `ranges` | `true` | Answer `Range` requests with 206 and 416 |
|
|
57
|
+
| `cacheControl` | `no-cache` | A string, or a function of the URL path |
|
|
58
|
+
| `headers` | none | Extra response headers, or a function of the file path |
|
|
59
|
+
| `mime` | none | Extra content types by extension |
|
|
60
|
+
| `notFoundFile` | none | File sent with 404 responses |
|
|
61
|
+
| `blockDotfiles` | `false` | 404 for any path segment that starts with a dot |
|
|
62
|
+
| `basePath` | none | URL prefix the site is served under |
|
|
63
|
+
| `allowedHosts` | any | Accepted `Host` names; others get 403 |
|
|
64
|
+
| `onRequest` | none | Called with `{ method, path, status, served }` for each request |
|
|
65
|
+
|
|
66
|
+
Only `GET` and `HEAD` are accepted; other methods get 405. A directory requested without a trailing slash is redirected with 301.
|
|
67
|
+
|
|
68
|
+
Command line flags: `--port`, `--host`, `--spa`, `--clean-urls`, `--no-ranges`, `--cache`, `--dotfiles`. Paths with dot segments are hidden unless `--dotfiles` is given.
|
|
69
|
+
|
|
70
|
+
## Errors
|
|
71
|
+
|
|
72
|
+
`startStaticServer` rejects if the port cannot be bound. Requests never throw: bad paths get 400, paths outside the root get 403, and read failures get 500.
|
|
73
|
+
|
|
74
|
+
## License
|
|
75
|
+
|
|
76
|
+
MIT
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { parseArgs } from 'node:util';
|
|
3
|
+
import { startStaticServer } from './server.js';
|
|
4
|
+
const HELP = `Usage: static-file-server [folder] [options]
|
|
5
|
+
|
|
6
|
+
Serves a folder over HTTP. The folder defaults to the current directory.
|
|
7
|
+
|
|
8
|
+
Options:
|
|
9
|
+
-p, --port <n> Port to listen on (default 8080, 0 picks a free port)
|
|
10
|
+
--host <name> Interface to bind (default 127.0.0.1)
|
|
11
|
+
--spa Answer extensionless unknown paths with index.html
|
|
12
|
+
--clean-urls Try <path>.html and <path>/index.html
|
|
13
|
+
--no-ranges Ignore Range requests
|
|
14
|
+
--cache <value> Cache-Control header (default no-cache)
|
|
15
|
+
--dotfiles Serve paths with dot segments (hidden by default)
|
|
16
|
+
-h, --help Show this help
|
|
17
|
+
`;
|
|
18
|
+
async function main(argv) {
|
|
19
|
+
let parsed;
|
|
20
|
+
try {
|
|
21
|
+
parsed = parseArgs({
|
|
22
|
+
args: argv,
|
|
23
|
+
allowPositionals: true,
|
|
24
|
+
options: {
|
|
25
|
+
port: { type: 'string', short: 'p' },
|
|
26
|
+
host: { type: 'string' },
|
|
27
|
+
spa: { type: 'boolean' },
|
|
28
|
+
'clean-urls': { type: 'boolean' },
|
|
29
|
+
'no-ranges': { type: 'boolean' },
|
|
30
|
+
cache: { type: 'string' },
|
|
31
|
+
dotfiles: { type: 'boolean' },
|
|
32
|
+
help: { type: 'boolean', short: 'h' },
|
|
33
|
+
},
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
process.stderr.write(`${error.message}\n\n${HELP}`);
|
|
38
|
+
return 2;
|
|
39
|
+
}
|
|
40
|
+
const { values, positionals } = parsed;
|
|
41
|
+
if (values.help) {
|
|
42
|
+
process.stdout.write(HELP);
|
|
43
|
+
return 0;
|
|
44
|
+
}
|
|
45
|
+
if (positionals.length > 1) {
|
|
46
|
+
process.stderr.write(`Expected at most one folder.\n\n${HELP}`);
|
|
47
|
+
return 2;
|
|
48
|
+
}
|
|
49
|
+
const port = values.port === undefined ? 8080 : Number(values.port);
|
|
50
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) {
|
|
51
|
+
process.stderr.write(`Invalid port: ${values.port}\n`);
|
|
52
|
+
return 2;
|
|
53
|
+
}
|
|
54
|
+
const folder = positionals[0] ?? '.';
|
|
55
|
+
const running = await startStaticServer({
|
|
56
|
+
root: folder,
|
|
57
|
+
port,
|
|
58
|
+
host: values.host,
|
|
59
|
+
spaFallback: values.spa,
|
|
60
|
+
cleanUrls: values['clean-urls'],
|
|
61
|
+
ranges: !values['no-ranges'],
|
|
62
|
+
cacheControl: values.cache,
|
|
63
|
+
blockDotfiles: !values.dotfiles,
|
|
64
|
+
});
|
|
65
|
+
process.stdout.write(`Serving ${folder} at ${running.url}\n`);
|
|
66
|
+
const stop = () => {
|
|
67
|
+
void running.close().then(() => process.exit(0));
|
|
68
|
+
};
|
|
69
|
+
process.on('SIGINT', stop);
|
|
70
|
+
process.on('SIGTERM', stop);
|
|
71
|
+
return -1;
|
|
72
|
+
}
|
|
73
|
+
main(process.argv.slice(2)).then((code) => {
|
|
74
|
+
if (code >= 0)
|
|
75
|
+
process.exit(code);
|
|
76
|
+
}, (error) => {
|
|
77
|
+
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
|
78
|
+
process.exit(1);
|
|
79
|
+
});
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { MIME_TYPES, contentTypeFor } from './mime.js';
|
|
2
|
+
export { isInside, resolveStaticPath } from './path.js';
|
|
3
|
+
export type { PathProblem, ResolvedPath } from './path.js';
|
|
4
|
+
export { parseRange } from './range.js';
|
|
5
|
+
export type { ByteRange } from './range.js';
|
|
6
|
+
export { createStaticHandler, createStaticServer, startStaticServer } from './server.js';
|
|
7
|
+
export type { RunningServer, ServedRequest, StartOptions, StaticHandler, StaticOptions } from './server.js';
|
package/dist/index.js
ADDED
package/dist/mime.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** Content types for common web files. Text types carry a UTF-8 charset. */
|
|
2
|
+
export declare const MIME_TYPES: Readonly<Record<string, string>>;
|
|
3
|
+
/**
|
|
4
|
+
* Content type for a file name. `extra` entries (keys like `.glb`, case-insensitive) win over the
|
|
5
|
+
* built-in table. Unknown extensions get `application/octet-stream`.
|
|
6
|
+
*/
|
|
7
|
+
export declare function contentTypeFor(file: string, extra?: Readonly<Record<string, string>>): string;
|
package/dist/mime.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
/** Content types for common web files. Text types carry a UTF-8 charset. */
|
|
3
|
+
export const MIME_TYPES = {
|
|
4
|
+
'.html': 'text/html; charset=utf-8',
|
|
5
|
+
'.htm': 'text/html; charset=utf-8',
|
|
6
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
7
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
8
|
+
'.css': 'text/css; charset=utf-8',
|
|
9
|
+
'.json': 'application/json; charset=utf-8',
|
|
10
|
+
'.map': 'application/json; charset=utf-8',
|
|
11
|
+
'.webmanifest': 'application/manifest+json; charset=utf-8',
|
|
12
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
13
|
+
'.md': 'text/markdown; charset=utf-8',
|
|
14
|
+
'.xml': 'application/xml; charset=utf-8',
|
|
15
|
+
'.csv': 'text/csv; charset=utf-8',
|
|
16
|
+
'.svg': 'image/svg+xml',
|
|
17
|
+
'.png': 'image/png',
|
|
18
|
+
'.jpg': 'image/jpeg',
|
|
19
|
+
'.jpeg': 'image/jpeg',
|
|
20
|
+
'.gif': 'image/gif',
|
|
21
|
+
'.webp': 'image/webp',
|
|
22
|
+
'.avif': 'image/avif',
|
|
23
|
+
'.ico': 'image/x-icon',
|
|
24
|
+
'.woff': 'font/woff',
|
|
25
|
+
'.woff2': 'font/woff2',
|
|
26
|
+
'.ttf': 'font/ttf',
|
|
27
|
+
'.otf': 'font/otf',
|
|
28
|
+
'.mp3': 'audio/mpeg',
|
|
29
|
+
'.wav': 'audio/wav',
|
|
30
|
+
'.ogg': 'audio/ogg',
|
|
31
|
+
'.mp4': 'video/mp4',
|
|
32
|
+
'.webm': 'video/webm',
|
|
33
|
+
'.pdf': 'application/pdf',
|
|
34
|
+
'.wasm': 'application/wasm',
|
|
35
|
+
'.zip': 'application/zip',
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* Content type for a file name. `extra` entries (keys like `.glb`, case-insensitive) win over the
|
|
39
|
+
* built-in table. Unknown extensions get `application/octet-stream`.
|
|
40
|
+
*/
|
|
41
|
+
export function contentTypeFor(file, extra) {
|
|
42
|
+
const ext = path.extname(file).toLowerCase();
|
|
43
|
+
if (extra) {
|
|
44
|
+
for (const [key, value] of Object.entries(extra)) {
|
|
45
|
+
if (key.toLowerCase() === ext)
|
|
46
|
+
return value;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return MIME_TYPES[ext] ?? 'application/octet-stream';
|
|
50
|
+
}
|
package/dist/path.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Why a URL path could not be turned into a file inside the root. */
|
|
2
|
+
export type PathProblem = 'bad-request' | 'forbidden' | 'not-found';
|
|
3
|
+
export type ResolvedPath = {
|
|
4
|
+
ok: true;
|
|
5
|
+
file: string;
|
|
6
|
+
isDirectory: boolean;
|
|
7
|
+
} | {
|
|
8
|
+
ok: false;
|
|
9
|
+
problem: PathProblem;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Maps a URL path (no query string) to a file or directory inside `root`.
|
|
13
|
+
*
|
|
14
|
+
* The path is percent-decoded first, so `%2e%2e` is treated like `..`. Backslashes and NUL bytes are
|
|
15
|
+
* rejected (`bad-request`), a path that leaves the root is `forbidden`, and a missing entry is
|
|
16
|
+
* `not-found`. The real path after following symlinks must still be inside the real root, so a link
|
|
17
|
+
* that points outside the folder is `forbidden`. Names that merely contain `..`, such as `a..b.txt`,
|
|
18
|
+
* are allowed.
|
|
19
|
+
*/
|
|
20
|
+
export declare function resolveStaticPath(root: string, urlPath: string): Promise<ResolvedPath>;
|
|
21
|
+
/** True when `target` is `root` itself or lies below it. */
|
|
22
|
+
export declare function isInside(root: string, target: string): boolean;
|
package/dist/path.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { realpath, stat } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
/**
|
|
4
|
+
* Maps a URL path (no query string) to a file or directory inside `root`.
|
|
5
|
+
*
|
|
6
|
+
* The path is percent-decoded first, so `%2e%2e` is treated like `..`. Backslashes and NUL bytes are
|
|
7
|
+
* rejected (`bad-request`), a path that leaves the root is `forbidden`, and a missing entry is
|
|
8
|
+
* `not-found`. The real path after following symlinks must still be inside the real root, so a link
|
|
9
|
+
* that points outside the folder is `forbidden`. Names that merely contain `..`, such as `a..b.txt`,
|
|
10
|
+
* are allowed.
|
|
11
|
+
*/
|
|
12
|
+
export async function resolveStaticPath(root, urlPath) {
|
|
13
|
+
let decoded;
|
|
14
|
+
try {
|
|
15
|
+
decoded = decodeURIComponent(urlPath);
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return { ok: false, problem: 'bad-request' };
|
|
19
|
+
}
|
|
20
|
+
if (decoded.includes('\0') || decoded.includes(String.fromCharCode(92)))
|
|
21
|
+
return { ok: false, problem: 'bad-request' };
|
|
22
|
+
const base = path.resolve(root);
|
|
23
|
+
const candidate = path.resolve(base, `.${decoded.startsWith('/') ? decoded : `/${decoded}`}`);
|
|
24
|
+
if (!isInside(base, candidate))
|
|
25
|
+
return { ok: false, problem: 'forbidden' };
|
|
26
|
+
let info;
|
|
27
|
+
let real;
|
|
28
|
+
try {
|
|
29
|
+
info = await stat(candidate);
|
|
30
|
+
real = await realpath(candidate);
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return { ok: false, problem: 'not-found' };
|
|
34
|
+
}
|
|
35
|
+
let realRoot;
|
|
36
|
+
try {
|
|
37
|
+
realRoot = await realpath(base);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return { ok: false, problem: 'not-found' };
|
|
41
|
+
}
|
|
42
|
+
if (!isInside(realRoot, real))
|
|
43
|
+
return { ok: false, problem: 'forbidden' };
|
|
44
|
+
return { ok: true, file: candidate, isDirectory: info.isDirectory() };
|
|
45
|
+
}
|
|
46
|
+
/** True when `target` is `root` itself or lies below it. */
|
|
47
|
+
export function isInside(root, target) {
|
|
48
|
+
if (target === root)
|
|
49
|
+
return true;
|
|
50
|
+
const prefix = root.endsWith(path.sep) ? root : root + path.sep;
|
|
51
|
+
return target.startsWith(prefix);
|
|
52
|
+
}
|
package/dist/range.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export interface ByteRange {
|
|
2
|
+
start: number;
|
|
3
|
+
end: number;
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Parses one `Range: bytes=...` header against a file size.
|
|
7
|
+
*
|
|
8
|
+
* Returns a satisfiable inclusive range, `'unsatisfiable'` when it lies outside the file (answer 416),
|
|
9
|
+
* or `null` when the whole file should be sent: no header, another unit, a malformed value or several
|
|
10
|
+
* ranges. Suffix ranges (`bytes=-500`) and open-ended ranges (`bytes=100-`) are supported, and an end
|
|
11
|
+
* past the last byte is clamped.
|
|
12
|
+
*/
|
|
13
|
+
export declare function parseRange(header: string | undefined, size: number): ByteRange | 'unsatisfiable' | null;
|
package/dist/range.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parses one `Range: bytes=...` header against a file size.
|
|
3
|
+
*
|
|
4
|
+
* Returns a satisfiable inclusive range, `'unsatisfiable'` when it lies outside the file (answer 416),
|
|
5
|
+
* or `null` when the whole file should be sent: no header, another unit, a malformed value or several
|
|
6
|
+
* ranges. Suffix ranges (`bytes=-500`) and open-ended ranges (`bytes=100-`) are supported, and an end
|
|
7
|
+
* past the last byte is clamped.
|
|
8
|
+
*/
|
|
9
|
+
export function parseRange(header, size) {
|
|
10
|
+
if (header === undefined)
|
|
11
|
+
return null;
|
|
12
|
+
const match = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
|
|
13
|
+
if (match === null)
|
|
14
|
+
return null;
|
|
15
|
+
const [, first, last] = match;
|
|
16
|
+
if (first === '' && last === '')
|
|
17
|
+
return null;
|
|
18
|
+
if (first === '') {
|
|
19
|
+
const suffix = Number(last);
|
|
20
|
+
if (suffix === 0 || size === 0)
|
|
21
|
+
return 'unsatisfiable';
|
|
22
|
+
return { start: Math.max(0, size - suffix), end: size - 1 };
|
|
23
|
+
}
|
|
24
|
+
const start = Number(first);
|
|
25
|
+
const end = last === '' ? size - 1 : Math.min(Number(last), size - 1);
|
|
26
|
+
if (start >= size || start > end)
|
|
27
|
+
return 'unsatisfiable';
|
|
28
|
+
return { start, end };
|
|
29
|
+
}
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import type { IncomingMessage, Server, ServerResponse } from 'node:http';
|
|
2
|
+
export interface ServedRequest {
|
|
3
|
+
method: string;
|
|
4
|
+
/** URL path of the request, or the raw target when it could not be parsed. */
|
|
5
|
+
path: string;
|
|
6
|
+
status: number;
|
|
7
|
+
/**
|
|
8
|
+
* `file`: the file named by the URL. `index`: a directory's index file. `clean-url`: `.html` or
|
|
9
|
+
* `/index.html` added to the path. `fallback`: the SPA index for a client route. `none`: no file was sent.
|
|
10
|
+
*/
|
|
11
|
+
served: 'file' | 'index' | 'clean-url' | 'fallback' | 'none';
|
|
12
|
+
}
|
|
13
|
+
export interface StaticOptions {
|
|
14
|
+
/** Folder to serve. */
|
|
15
|
+
root: string;
|
|
16
|
+
/** Name of a directory's index file. Default `index.html`. */
|
|
17
|
+
index?: string;
|
|
18
|
+
/**
|
|
19
|
+
* Answer unknown paths without a file extension with the index file (status 200), for client-side
|
|
20
|
+
* routing. Paths whose last segment has an extension stay 404, so a missing asset is never hidden.
|
|
21
|
+
* Pass `{ exclude: ['/api'] }` to keep path prefixes out of the fallback.
|
|
22
|
+
*/
|
|
23
|
+
spaFallback?: boolean | {
|
|
24
|
+
exclude?: string[];
|
|
25
|
+
};
|
|
26
|
+
/** Try `<path>.html` and `<path>/index.html` for extensionless paths. Default false. */
|
|
27
|
+
cleanUrls?: boolean;
|
|
28
|
+
/** Answer `Range` requests with 206 and 416. Default true. */
|
|
29
|
+
ranges?: boolean;
|
|
30
|
+
/** `Cache-Control` value, or a function of the URL path. Default `no-cache`. */
|
|
31
|
+
cacheControl?: string | ((urlPath: string) => string);
|
|
32
|
+
/** Extra response headers, or a function of the file path that returns them. */
|
|
33
|
+
headers?: Record<string, string> | ((file: string) => Record<string, string>);
|
|
34
|
+
/** Extra content types by extension, for example `{ '.glb': 'model/gltf-binary' }`. */
|
|
35
|
+
mime?: Record<string, string>;
|
|
36
|
+
/** File inside the root sent with 404 responses, for example `404.html`. */
|
|
37
|
+
notFoundFile?: string;
|
|
38
|
+
/** Answer 404 for any path with a segment that starts with a dot. Default false. */
|
|
39
|
+
blockDotfiles?: boolean;
|
|
40
|
+
/** URL prefix the site is mounted under, for example `/docs`. Paths outside it are 404. */
|
|
41
|
+
basePath?: string;
|
|
42
|
+
/** Accepted `Host` header names (without port). Others get 403. Default: any host. */
|
|
43
|
+
allowedHosts?: string[];
|
|
44
|
+
/** Called once per finished request. */
|
|
45
|
+
onRequest?: (request: ServedRequest) => void;
|
|
46
|
+
}
|
|
47
|
+
export interface StartOptions extends StaticOptions {
|
|
48
|
+
/** Port to listen on; 0 picks a free one. Default 0. */
|
|
49
|
+
port?: number;
|
|
50
|
+
/** Interface to bind. Default `127.0.0.1`. */
|
|
51
|
+
host?: string;
|
|
52
|
+
}
|
|
53
|
+
export interface RunningServer {
|
|
54
|
+
server: Server;
|
|
55
|
+
host: string;
|
|
56
|
+
port: number;
|
|
57
|
+
/** `http://host:port`. */
|
|
58
|
+
url: string;
|
|
59
|
+
close(): Promise<void>;
|
|
60
|
+
}
|
|
61
|
+
export type StaticHandler = (request: IncomingMessage, response: ServerResponse) => Promise<void>;
|
|
62
|
+
/** Builds a `(req, res)` handler that serves `options.root`. Use it with `http.createServer` or inside another server. */
|
|
63
|
+
export declare function createStaticHandler(options: StaticOptions): StaticHandler;
|
|
64
|
+
/** An `http.Server` that serves `options.root`. It is not listening yet. */
|
|
65
|
+
export declare function createStaticServer(options: StaticOptions): Server;
|
|
66
|
+
/** Starts serving `options.root` and resolves once the server is listening. */
|
|
67
|
+
export declare function startStaticServer(options: StartOptions): Promise<RunningServer>;
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import { createReadStream } from 'node:fs';
|
|
2
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
3
|
+
import { createServer } from 'node:http';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { contentTypeFor } from './mime.js';
|
|
6
|
+
import { resolveStaticPath } from './path.js';
|
|
7
|
+
import { parseRange } from './range.js';
|
|
8
|
+
/** Builds a `(req, res)` handler that serves `options.root`. Use it with `http.createServer` or inside another server. */
|
|
9
|
+
export function createStaticHandler(options) {
|
|
10
|
+
const root = path.resolve(options.root);
|
|
11
|
+
const indexName = options.index ?? 'index.html';
|
|
12
|
+
const rangesOn = options.ranges ?? true;
|
|
13
|
+
const basePath = normalizeBase(options.basePath);
|
|
14
|
+
const hosts = options.allowedHosts ? new Set(options.allowedHosts.map((host) => host.toLowerCase())) : null;
|
|
15
|
+
const exclude = typeof options.spaFallback === 'object' ? (options.spaFallback.exclude ?? []) : [];
|
|
16
|
+
async function locate(local, decoded) {
|
|
17
|
+
const first = await resolveStaticPath(root, local);
|
|
18
|
+
if (!first.ok) {
|
|
19
|
+
if (first.problem === 'bad-request')
|
|
20
|
+
return 'bad-request';
|
|
21
|
+
if (first.problem === 'forbidden')
|
|
22
|
+
return 'forbidden';
|
|
23
|
+
}
|
|
24
|
+
else if (first.isDirectory) {
|
|
25
|
+
if (!local.endsWith('/'))
|
|
26
|
+
return 'redirect';
|
|
27
|
+
const inner = await resolveStaticPath(root, `${local}${indexName}`);
|
|
28
|
+
if (inner.ok && !inner.isDirectory)
|
|
29
|
+
return { file: inner.file, served: 'index' };
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
return { file: first.file, served: 'file' };
|
|
33
|
+
}
|
|
34
|
+
const lastSegment = decoded.split('/').filter(Boolean).pop() ?? '';
|
|
35
|
+
const extensionless = path.extname(lastSegment) === '';
|
|
36
|
+
if (options.cleanUrls && extensionless && lastSegment !== '' && !decoded.endsWith('/')) {
|
|
37
|
+
for (const candidate of [`${local}.html`, `${local}/${indexName}`]) {
|
|
38
|
+
const hit = await resolveStaticPath(root, candidate);
|
|
39
|
+
if (hit.ok && !hit.isDirectory)
|
|
40
|
+
return { file: hit.file, served: 'clean-url' };
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const excluded = exclude.some((prefix) => decoded === prefix || decoded.startsWith(`${prefix.replace(/\/$/, '')}/`));
|
|
44
|
+
if (options.spaFallback && extensionless && !excluded) {
|
|
45
|
+
const shell = await resolveStaticPath(root, `/${indexName}`);
|
|
46
|
+
if (shell.ok && !shell.isDirectory)
|
|
47
|
+
return { file: shell.file, served: 'fallback' };
|
|
48
|
+
}
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
return async (request, response) => {
|
|
52
|
+
const method = request.method ?? 'GET';
|
|
53
|
+
let logged = false;
|
|
54
|
+
const finish = (status, urlPath, served) => {
|
|
55
|
+
if (logged)
|
|
56
|
+
return;
|
|
57
|
+
logged = true;
|
|
58
|
+
options.onRequest?.({ method, path: urlPath, status, served });
|
|
59
|
+
};
|
|
60
|
+
const reply = (status, urlPath, body, extra = {}) => {
|
|
61
|
+
response.writeHead(status, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store', ...extra });
|
|
62
|
+
response.end(method === 'HEAD' ? undefined : body);
|
|
63
|
+
finish(status, urlPath, 'none');
|
|
64
|
+
};
|
|
65
|
+
const notFound = async (urlPath) => {
|
|
66
|
+
if (options.notFoundFile) {
|
|
67
|
+
const page = await resolveStaticPath(root, `/${options.notFoundFile}`);
|
|
68
|
+
if (page.ok && !page.isDirectory) {
|
|
69
|
+
const body = await readFile(page.file);
|
|
70
|
+
response.writeHead(404, { 'content-type': contentTypeFor(page.file, options.mime), 'content-length': body.length, 'cache-control': 'no-store' });
|
|
71
|
+
response.end(method === 'HEAD' ? undefined : body);
|
|
72
|
+
finish(404, urlPath, 'none');
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
reply(404, urlPath, 'Not found\n');
|
|
77
|
+
};
|
|
78
|
+
const send = async (found, urlPath) => {
|
|
79
|
+
const info = await stat(found.file);
|
|
80
|
+
const cache = typeof options.cacheControl === 'function' ? options.cacheControl(urlPath) : (options.cacheControl ?? 'no-cache');
|
|
81
|
+
const custom = typeof options.headers === 'function' ? options.headers(found.file) : (options.headers ?? {});
|
|
82
|
+
const headers = {
|
|
83
|
+
...custom,
|
|
84
|
+
'content-type': contentTypeFor(found.file, options.mime),
|
|
85
|
+
'cache-control': cache,
|
|
86
|
+
'last-modified': info.mtime.toUTCString(),
|
|
87
|
+
};
|
|
88
|
+
if (rangesOn)
|
|
89
|
+
headers['accept-ranges'] = 'bytes';
|
|
90
|
+
const range = rangesOn ? parseRange(request.headers.range, info.size) : null;
|
|
91
|
+
if (range === 'unsatisfiable') {
|
|
92
|
+
response.writeHead(416, { ...headers, 'content-range': `bytes */${info.size}`, 'content-length': 0 });
|
|
93
|
+
response.end();
|
|
94
|
+
finish(416, urlPath, 'none');
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
const status = range === null ? 200 : 206;
|
|
98
|
+
headers['content-length'] = range === null ? info.size : range.end - range.start + 1;
|
|
99
|
+
if (range !== null)
|
|
100
|
+
headers['content-range'] = `bytes ${range.start}-${range.end}/${info.size}`;
|
|
101
|
+
response.writeHead(status, headers);
|
|
102
|
+
finish(status, urlPath, found.served);
|
|
103
|
+
if (method === 'HEAD' || info.size === 0) {
|
|
104
|
+
response.end();
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
createReadStream(found.file, range === null ? undefined : { start: range.start, end: range.end })
|
|
108
|
+
.on('error', () => response.destroy())
|
|
109
|
+
.pipe(response);
|
|
110
|
+
};
|
|
111
|
+
try {
|
|
112
|
+
if (hosts !== null) {
|
|
113
|
+
const host = (request.headers.host ?? '').toLowerCase().replace(/:\d+$/, '').replace(/^\[(.*)\]$/, '$1');
|
|
114
|
+
if (!hosts.has(host))
|
|
115
|
+
return reply(403, request.url ?? '/', 'Host not allowed\n');
|
|
116
|
+
}
|
|
117
|
+
if (method !== 'GET' && method !== 'HEAD')
|
|
118
|
+
return reply(405, request.url ?? '/', 'Method not allowed\n', { allow: 'GET, HEAD' });
|
|
119
|
+
let urlPath;
|
|
120
|
+
try {
|
|
121
|
+
urlPath = new URL(request.url ?? '/', 'http://localhost').pathname;
|
|
122
|
+
decodeURIComponent(urlPath);
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
return reply(400, request.url ?? '/', 'Bad request\n');
|
|
126
|
+
}
|
|
127
|
+
let local = urlPath;
|
|
128
|
+
if (basePath !== '') {
|
|
129
|
+
if (urlPath === basePath) {
|
|
130
|
+
response.writeHead(301, { location: `${basePath}/` });
|
|
131
|
+
response.end();
|
|
132
|
+
return finish(301, urlPath, 'none');
|
|
133
|
+
}
|
|
134
|
+
if (!urlPath.startsWith(`${basePath}/`))
|
|
135
|
+
return await notFound(urlPath);
|
|
136
|
+
local = urlPath.slice(basePath.length);
|
|
137
|
+
}
|
|
138
|
+
const decoded = safeDecode(local);
|
|
139
|
+
if (options.blockDotfiles && decoded.split('/').some((segment) => segment.startsWith('.')))
|
|
140
|
+
return await notFound(urlPath);
|
|
141
|
+
const outcome = await locate(local, decoded);
|
|
142
|
+
if (outcome === 'redirect') {
|
|
143
|
+
response.writeHead(301, { location: `${urlPath}/` });
|
|
144
|
+
response.end();
|
|
145
|
+
return finish(301, urlPath, 'none');
|
|
146
|
+
}
|
|
147
|
+
if (outcome === 'bad-request')
|
|
148
|
+
return reply(400, urlPath, 'Bad request\n');
|
|
149
|
+
if (outcome === 'forbidden')
|
|
150
|
+
return reply(403, urlPath, 'Forbidden\n');
|
|
151
|
+
if (outcome === null)
|
|
152
|
+
return await notFound(urlPath);
|
|
153
|
+
await send(outcome, urlPath);
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
if (!response.headersSent) {
|
|
157
|
+
response.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
|
|
158
|
+
response.end('Server error\n');
|
|
159
|
+
}
|
|
160
|
+
else
|
|
161
|
+
response.destroy();
|
|
162
|
+
finish(500, request.url ?? '/', 'none');
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
/** An `http.Server` that serves `options.root`. It is not listening yet. */
|
|
167
|
+
export function createStaticServer(options) {
|
|
168
|
+
const handler = createStaticHandler(options);
|
|
169
|
+
return createServer((request, response) => {
|
|
170
|
+
void handler(request, response);
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
/** Starts serving `options.root` and resolves once the server is listening. */
|
|
174
|
+
export async function startStaticServer(options) {
|
|
175
|
+
const host = options.host ?? '127.0.0.1';
|
|
176
|
+
const server = createStaticServer(options);
|
|
177
|
+
await new Promise((resolve, reject) => {
|
|
178
|
+
server.once('error', reject);
|
|
179
|
+
server.listen(options.port ?? 0, host, () => {
|
|
180
|
+
server.off('error', reject);
|
|
181
|
+
resolve();
|
|
182
|
+
});
|
|
183
|
+
});
|
|
184
|
+
const port = server.address().port;
|
|
185
|
+
const shown = host.includes(':') ? `[${host}]` : host;
|
|
186
|
+
return {
|
|
187
|
+
server,
|
|
188
|
+
host,
|
|
189
|
+
port,
|
|
190
|
+
url: `http://${shown}:${port}`,
|
|
191
|
+
close: () => new Promise((resolve) => {
|
|
192
|
+
server.close(() => resolve());
|
|
193
|
+
server.closeAllConnections();
|
|
194
|
+
}),
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
function normalizeBase(base) {
|
|
198
|
+
const trimmed = (base ?? '').split('/').filter(Boolean).join('/');
|
|
199
|
+
return trimmed === '' ? '' : `/${trimmed}`;
|
|
200
|
+
}
|
|
201
|
+
function safeDecode(value) {
|
|
202
|
+
try {
|
|
203
|
+
return decodeURIComponent(value);
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
return value;
|
|
207
|
+
}
|
|
208
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,52 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@uppercut-labs/static-file-server",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Dependency-free Node static file server with a path-traversal guard, MIME map, range requests and optional SPA fallback.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Uppercut Labs <packages@uppercut-labs.com>",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"default": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"main": "./dist/index.js",
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"bin": {
|
|
17
|
+
"static-file-server": "./dist/cli.js"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist",
|
|
21
|
+
"README.md",
|
|
22
|
+
"LICENSE"
|
|
23
|
+
],
|
|
24
|
+
"sideEffects": false,
|
|
25
|
+
"scripts": {
|
|
26
|
+
"build": "tsc -p tsconfig.json",
|
|
27
|
+
"prepack": "node -e \"require('fs').copyFileSync('../../LICENSE','LICENSE')\""
|
|
28
|
+
},
|
|
29
|
+
"keywords": [
|
|
30
|
+
"static",
|
|
31
|
+
"file-server",
|
|
32
|
+
"http",
|
|
33
|
+
"spa",
|
|
34
|
+
"range",
|
|
35
|
+
"preview"
|
|
36
|
+
],
|
|
37
|
+
"repository": {
|
|
38
|
+
"type": "git",
|
|
39
|
+
"url": "git+https://github.com/uppercut-labs/js-kit.git",
|
|
40
|
+
"directory": "packages/static-file-server"
|
|
41
|
+
},
|
|
42
|
+
"bugs": {
|
|
43
|
+
"url": "https://github.com/uppercut-labs/js-kit/issues"
|
|
44
|
+
},
|
|
45
|
+
"homepage": "https://github.com/uppercut-labs/js-kit/tree/main/packages/static-file-server#readme",
|
|
46
|
+
"engines": {
|
|
47
|
+
"node": ">=18"
|
|
48
|
+
},
|
|
49
|
+
"publishConfig": {
|
|
50
|
+
"access": "public"
|
|
51
|
+
}
|
|
52
|
+
}
|