workers-start 0.1.1 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -1
- package/README.md +28 -15
- package/biome.preset.json +31 -13
- package/dist/accept.d.ts +18 -0
- package/dist/accept.d.ts.map +1 -0
- package/dist/accept.js +54 -0
- package/dist/accept.js.map +1 -0
- package/dist/check-bundle-cli.d.ts +1 -1
- package/dist/check-bundle-cli.js +50 -25
- package/dist/check-bundle-cli.js.map +1 -1
- package/dist/check-bundle.d.ts +36 -8
- package/dist/check-bundle.d.ts.map +1 -1
- package/dist/check-bundle.js +122 -31
- package/dist/check-bundle.js.map +1 -1
- package/dist/entry.d.ts +40 -18
- package/dist/entry.d.ts.map +1 -1
- package/dist/entry.js +99 -35
- package/dist/entry.js.map +1 -1
- package/dist/head.d.ts +34 -10
- package/dist/head.d.ts.map +1 -1
- package/dist/head.js +46 -26
- package/dist/head.js.map +1 -1
- package/dist/index.d.ts +5 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/scripts.d.ts +34 -6
- package/dist/scripts.d.ts.map +1 -1
- package/dist/scripts.js +36 -11
- package/dist/scripts.js.map +1 -1
- package/dist/workers.d.ts +6 -4
- package/dist/workers.d.ts.map +1 -1
- package/dist/workers.js +17 -13
- package/dist/workers.js.map +1 -1
- package/package.json +21 -9
- package/src/accept.ts +63 -0
- package/src/check-bundle-cli.ts +57 -23
- package/src/check-bundle.ts +133 -34
- package/src/entry.ts +117 -44
- package/src/head.ts +75 -40
- package/src/index.ts +14 -3
- package/src/scripts.ts +62 -14
- package/src/workers.ts +19 -15
package/src/check-bundle-cli.ts
CHANGED
|
@@ -1,45 +1,78 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
/**
|
|
3
|
-
* workers-start-check-bundle [--dist
|
|
3
|
+
* workers-start-check-bundle [--dist dir ...] [--root dir] [--skip path ...] [--allow KEY ...] [--public-prefix PREFIX ...]
|
|
4
4
|
*
|
|
5
5
|
* Exits 1 if any local env value appears in a built file. Run it between the
|
|
6
6
|
* build and the deploy.
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
9
|
import { relative, resolve } from "node:path";
|
|
10
|
-
import { checkBundle, DEFAULT_SKIP } from "./check-bundle.js";
|
|
10
|
+
import { checkBundle, DEFAULT_PUBLIC_PREFIXES, DEFAULT_SKIP } from "./check-bundle.js";
|
|
11
11
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
12
|
+
const USAGE = `Usage: workers-start-check-bundle [options]
|
|
13
|
+
|
|
14
|
+
--dist <dir> Build directory to scan, relative to --root. Repeatable. Default: dist
|
|
15
|
+
--root <dir> Directory holding the .env and .dev.vars files. Default: .
|
|
16
|
+
--skip <path> Path inside a build directory that never ships. Repeatable.
|
|
17
|
+
Always skipped: ${DEFAULT_SKIP.join(", ")}
|
|
18
|
+
--allow <KEY> Env key whose value is public. Repeatable.
|
|
19
|
+
--public-prefix <PREFIX>
|
|
20
|
+
Key prefix whose values are public, such as NEXT_PUBLIC_. Repeatable.
|
|
21
|
+
Always public: ${DEFAULT_PUBLIC_PREFIXES.join(", ")}`;
|
|
22
|
+
|
|
23
|
+
interface Args {
|
|
24
|
+
dists: string[];
|
|
25
|
+
root: string;
|
|
26
|
+
skip: string[];
|
|
27
|
+
allow: string[];
|
|
28
|
+
publicPrefixes: string[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function parseArgs(argv: string[]): Args {
|
|
32
|
+
const args: Args = {
|
|
33
|
+
dists: [],
|
|
34
|
+
root: ".",
|
|
35
|
+
skip: [...DEFAULT_SKIP],
|
|
36
|
+
allow: [],
|
|
37
|
+
publicPrefixes: [...DEFAULT_PUBLIC_PREFIXES],
|
|
38
|
+
};
|
|
16
39
|
for (let i = 0; i < argv.length; i++) {
|
|
17
40
|
const flag = argv[i];
|
|
41
|
+
if (flag === "--help" || flag === "-h") {
|
|
42
|
+
console.log(USAGE);
|
|
43
|
+
process.exit(0);
|
|
44
|
+
}
|
|
18
45
|
const value = argv[i + 1];
|
|
19
|
-
if (
|
|
20
|
-
|
|
46
|
+
if (
|
|
47
|
+
!(flag === "--dist" || flag === "--root" || flag === "--skip" || flag === "--allow" || flag === "--public-prefix")
|
|
48
|
+
) {
|
|
49
|
+
throw new Error(`Unknown argument: ${flag}\n\n${USAGE}`);
|
|
21
50
|
}
|
|
22
|
-
if (
|
|
23
|
-
|
|
24
|
-
i++;
|
|
25
|
-
} else if (flag === "--root") {
|
|
26
|
-
root = value as string;
|
|
27
|
-
i++;
|
|
28
|
-
} else if (flag === "--skip") {
|
|
29
|
-
skip.push(value as string);
|
|
30
|
-
i++;
|
|
31
|
-
} else {
|
|
32
|
-
throw new Error(`Unknown argument: ${flag}`);
|
|
51
|
+
if (value === undefined || value.startsWith("--")) {
|
|
52
|
+
throw new Error(`${flag} needs a value`);
|
|
33
53
|
}
|
|
54
|
+
i++;
|
|
55
|
+
if (flag === "--dist") args.dists.push(value);
|
|
56
|
+
else if (flag === "--root") args.root = value;
|
|
57
|
+
else if (flag === "--skip") args.skip.push(value.replace(/^\.?\//, ""));
|
|
58
|
+
else if (flag === "--allow") args.allow.push(value);
|
|
59
|
+
else args.publicPrefixes.push(value);
|
|
60
|
+
}
|
|
61
|
+
if (args.dists.length === 0) {
|
|
62
|
+
args.dists.push("dist");
|
|
34
63
|
}
|
|
35
|
-
return
|
|
64
|
+
return args;
|
|
36
65
|
}
|
|
37
66
|
|
|
38
67
|
function main(): void {
|
|
39
68
|
const args = parseArgs(process.argv.slice(2));
|
|
40
69
|
const root = resolve(args.root);
|
|
41
|
-
const
|
|
42
|
-
const result = checkBundle(root,
|
|
70
|
+
const dists = args.dists.map((dist) => resolve(root, dist));
|
|
71
|
+
const result = checkBundle(root, dists, {
|
|
72
|
+
skip: args.skip,
|
|
73
|
+
allow: args.allow,
|
|
74
|
+
publicPrefixes: args.publicPrefixes,
|
|
75
|
+
});
|
|
43
76
|
|
|
44
77
|
if (result.leaked.length === 0) {
|
|
45
78
|
console.log(` ok none of ${result.envValues} local env value(s) appear in ${result.files} built file(s)`);
|
|
@@ -50,8 +83,9 @@ function main(): void {
|
|
|
50
83
|
for (const key of result.leaked) {
|
|
51
84
|
console.error(` ${key}`);
|
|
52
85
|
}
|
|
86
|
+
const where = dists.map((dist) => `${relative(process.cwd(), dist) || "."}/`).join(", ");
|
|
53
87
|
console.error(
|
|
54
|
-
`\n Find where it is read at build time (import.meta.env, define, a module-scope\n process.env read) under ${
|
|
88
|
+
`\n Find where it is read at build time (import.meta.env, define, a module-scope\n process.env read) under ${where} and fix that. If the value is meant to be\n public, pass --allow <KEY> or --public-prefix <PREFIX>.\n`,
|
|
55
89
|
);
|
|
56
90
|
process.exit(1);
|
|
57
91
|
}
|
package/src/check-bundle.ts
CHANGED
|
@@ -1,43 +1,114 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Finds local secrets compiled into a build.
|
|
3
3
|
*
|
|
4
|
-
* Reads every value in the local `.env*` and `.dev.vars*` files (examples
|
|
5
|
-
* excluded) and searches the built files for each one
|
|
4
|
+
* Reads every value in the local `.env*` and `.dev.vars*` files (examples and
|
|
5
|
+
* `.tpl` templates excluded) and searches the built files for each one, raw
|
|
6
|
+
* and in the encodings a bundler or a URL would give it. A match means a key
|
|
6
7
|
* reached something that ships, whichever tool put it there.
|
|
7
8
|
*/
|
|
8
9
|
|
|
9
|
-
import { existsSync, readdirSync, readFileSync
|
|
10
|
-
import { join } from "node:path";
|
|
10
|
+
import { existsSync, lstatSync, readdirSync, readFileSync } from "node:fs";
|
|
11
|
+
import { join, relative, sep } from "node:path";
|
|
12
|
+
import { brotliDecompressSync, gunzipSync } from "node:zlib";
|
|
11
13
|
|
|
12
14
|
/** Values shorter than this are flags or placeholders, not secrets. */
|
|
13
15
|
export const MIN_SECRET_LENGTH = 12;
|
|
14
16
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
17
|
+
/**
|
|
18
|
+
* Paths, relative to a build directory, that are never uploaded: the copy of
|
|
19
|
+
* the local env the Cloudflare Vite plugin writes for `vite preview`.
|
|
20
|
+
*/
|
|
21
|
+
export const DEFAULT_SKIP = ["server/.dev.vars"];
|
|
22
|
+
|
|
23
|
+
/** Keys Vite inlines on purpose; their values are public. */
|
|
24
|
+
export const DEFAULT_PUBLIC_PREFIXES = ["VITE_"];
|
|
19
25
|
|
|
20
|
-
|
|
21
|
-
|
|
26
|
+
const ENV_FILE = /^(\.env(\..+)?|\.dev\.vars(\..+)?)$/;
|
|
27
|
+
const NOT_SECRETS = /\.(example|sample|template|tpl)$/;
|
|
28
|
+
const KEY = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(.*)$/;
|
|
29
|
+
const INLINE_COMMENT = /\s+#.*$/;
|
|
30
|
+
const ESCAPES: Record<string, string> = { n: "\n", r: "\r", t: "\t", '"': '"', "\\": "\\" };
|
|
22
31
|
|
|
23
|
-
/**
|
|
32
|
+
/**
|
|
33
|
+
* KEY=value pairs from a dotenv file, parsed the way dotenv does: `#`
|
|
34
|
+
* comments, inline ` #` comments on unquoted values, single quotes taken
|
|
35
|
+
* literally, double quotes with `\n` escapes and multi-line values.
|
|
36
|
+
*/
|
|
24
37
|
export function parseEnvFile(source: string): [string, string][] {
|
|
25
38
|
const pairs: [string, string][] = [];
|
|
26
|
-
|
|
27
|
-
|
|
39
|
+
const lines = source.replace(/\r\n?/g, "\n").split("\n");
|
|
40
|
+
for (let i = 0; i < lines.length; i++) {
|
|
41
|
+
const match = (lines[i] ?? "").match(KEY);
|
|
28
42
|
if (!(match?.[1] && match[2] !== undefined)) {
|
|
29
43
|
continue;
|
|
30
44
|
}
|
|
31
|
-
|
|
45
|
+
const key = match[1];
|
|
46
|
+
let raw = match[2].trim();
|
|
47
|
+
const quote = raw[0];
|
|
48
|
+
if (quote === '"' || quote === "'" || quote === "`") {
|
|
49
|
+
// Gather lines until the closing quote, for multi-line values.
|
|
50
|
+
let body = raw.slice(1);
|
|
51
|
+
while (!hasClosingQuote(body, quote) && i + 1 < lines.length) {
|
|
52
|
+
i++;
|
|
53
|
+
body += `\n${lines[i]}`;
|
|
54
|
+
}
|
|
55
|
+
const end = closingQuoteIndex(body, quote);
|
|
56
|
+
raw = end === -1 ? body : body.slice(0, end);
|
|
57
|
+
pairs.push([key, quote === '"' ? raw.replace(/\\(.)/g, (m, c: string) => ESCAPES[c] ?? m) : raw]);
|
|
58
|
+
} else {
|
|
59
|
+
pairs.push([key, raw.replace(INLINE_COMMENT, "").trim()]);
|
|
60
|
+
}
|
|
32
61
|
}
|
|
33
62
|
return pairs;
|
|
34
63
|
}
|
|
35
64
|
|
|
36
|
-
|
|
37
|
-
|
|
65
|
+
function closingQuoteIndex(body: string, quote: string): number {
|
|
66
|
+
for (let i = 0; i < body.length; i++) {
|
|
67
|
+
if (body[i] === "\\" && quote === '"') {
|
|
68
|
+
i++;
|
|
69
|
+
} else if (body[i] === quote) {
|
|
70
|
+
return i;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return -1;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function hasClosingQuote(body: string, quote: string): boolean {
|
|
77
|
+
return closingQuoteIndex(body, quote) !== -1;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The forms a value can take once it is in a bundle or a URL. */
|
|
81
|
+
export function encodings(value: string): string[] {
|
|
82
|
+
const forms = new Set([
|
|
83
|
+
value,
|
|
84
|
+
encodeURIComponent(value),
|
|
85
|
+
JSON.stringify(value).slice(1, -1),
|
|
86
|
+
Buffer.from(value).toString("base64").replace(/=+$/, ""),
|
|
87
|
+
Buffer.from(value).toString("base64url").replace(/=+$/, ""),
|
|
88
|
+
]);
|
|
89
|
+
return [...forms].filter((form) => form.length >= MIN_SECRET_LENGTH);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export interface LeakOptions {
|
|
93
|
+
/** Keys whose values are public. Matched exactly. */
|
|
94
|
+
allow?: readonly string[];
|
|
95
|
+
/** Key prefixes whose values are public. Default `["VITE_"]`. */
|
|
96
|
+
publicPrefixes?: readonly string[];
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The env keys whose values appear, in any encoding, in any of the given file contents. */
|
|
100
|
+
export function leakedKeys(pairs: [string, string][], contents: string[], options: LeakOptions = {}): string[] {
|
|
101
|
+
const publicPrefixes = options.publicPrefixes ?? DEFAULT_PUBLIC_PREFIXES;
|
|
38
102
|
const leaked = new Set<string>();
|
|
39
103
|
for (const [key, value] of pairs) {
|
|
40
|
-
if (value.length
|
|
104
|
+
if (value.length < MIN_SECRET_LENGTH || value.startsWith("op://")) {
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
if (options.allow?.includes(key) || publicPrefixes.some((prefix) => key.startsWith(prefix))) {
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
const forms = encodings(value);
|
|
111
|
+
if (contents.some((text) => forms.some((form) => text.includes(form)))) {
|
|
41
112
|
leaked.add(key);
|
|
42
113
|
}
|
|
43
114
|
}
|
|
@@ -47,39 +118,67 @@ export function leakedKeys(pairs: [string, string][], contents: string[]): strin
|
|
|
47
118
|
/** Every KEY=value pair in the local env files of `dir`. */
|
|
48
119
|
export function localEnvPairs(dir: string): [string, string][] {
|
|
49
120
|
return readdirSync(dir)
|
|
50
|
-
.filter((name) => ENV_FILE.test(name) && !
|
|
121
|
+
.filter((name) => ENV_FILE.test(name) && !NOT_SECRETS.test(name))
|
|
51
122
|
.flatMap((name) => parseEnvFile(readFileSync(join(dir, name), "utf8")));
|
|
52
123
|
}
|
|
53
124
|
|
|
54
|
-
/**
|
|
125
|
+
/**
|
|
126
|
+
* Every regular file under `dir`, recursively. Symlinks are skipped, so the
|
|
127
|
+
* walk never loops or leaves the directory. `skip` holds paths relative to
|
|
128
|
+
* `dir`, with forward slashes.
|
|
129
|
+
*/
|
|
55
130
|
export function listFiles(dir: string, skip: readonly string[] = DEFAULT_SKIP): string[] {
|
|
56
131
|
const files: string[] = [];
|
|
57
|
-
|
|
58
|
-
const
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
132
|
+
const walk = (current: string): void => {
|
|
133
|
+
for (const name of readdirSync(current)) {
|
|
134
|
+
const path = join(current, name);
|
|
135
|
+
const stat = lstatSync(path);
|
|
136
|
+
if (stat.isSymbolicLink()) {
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
if (stat.isDirectory()) {
|
|
140
|
+
walk(path);
|
|
141
|
+
} else if (stat.isFile() && !skip.includes(relative(dir, path).split(sep).join("/"))) {
|
|
142
|
+
files.push(path);
|
|
143
|
+
}
|
|
63
144
|
}
|
|
64
|
-
}
|
|
145
|
+
};
|
|
146
|
+
walk(dir);
|
|
65
147
|
return files;
|
|
66
148
|
}
|
|
67
149
|
|
|
150
|
+
/** File contents as text, decompressing `.gz` and `.br` files. */
|
|
151
|
+
export function readBuilt(path: string): string {
|
|
152
|
+
const bytes = readFileSync(path);
|
|
153
|
+
try {
|
|
154
|
+
if (path.endsWith(".gz")) return gunzipSync(bytes).toString("latin1");
|
|
155
|
+
if (path.endsWith(".br")) return brotliDecompressSync(bytes).toString("latin1");
|
|
156
|
+
} catch {
|
|
157
|
+
// Not really compressed; scan the bytes as they are.
|
|
158
|
+
}
|
|
159
|
+
return bytes.toString("latin1");
|
|
160
|
+
}
|
|
161
|
+
|
|
68
162
|
export interface CheckResult {
|
|
69
163
|
envValues: number;
|
|
70
164
|
files: number;
|
|
71
165
|
leaked: string[];
|
|
72
166
|
}
|
|
73
167
|
|
|
74
|
-
export
|
|
75
|
-
|
|
76
|
-
|
|
168
|
+
export interface CheckOptions extends LeakOptions {
|
|
169
|
+
skip?: readonly string[];
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Scan one or more build directories against the local env files in `root`. */
|
|
173
|
+
export function checkBundle(root: string, dists: string | readonly string[], options: CheckOptions = {}): CheckResult {
|
|
174
|
+
const dirs = typeof dists === "string" ? [dists] : dists;
|
|
175
|
+
for (const dir of dirs) {
|
|
176
|
+
if (!existsSync(dir)) {
|
|
177
|
+
throw new Error(`${dir} does not exist. Build first.`);
|
|
178
|
+
}
|
|
77
179
|
}
|
|
78
180
|
const pairs = localEnvPairs(root);
|
|
79
|
-
const files = listFiles(
|
|
80
|
-
const leaked = leakedKeys(
|
|
81
|
-
pairs,
|
|
82
|
-
files.map((path) => readFileSync(path, "latin1")),
|
|
83
|
-
);
|
|
181
|
+
const files = dirs.flatMap((dir) => listFiles(dir, options.skip ?? DEFAULT_SKIP));
|
|
182
|
+
const leaked = leakedKeys(pairs, files.map(readBuilt), options);
|
|
84
183
|
return { envValues: pairs.length, files: files.length, leaked };
|
|
85
184
|
}
|
package/src/entry.ts
CHANGED
|
@@ -2,15 +2,18 @@
|
|
|
2
2
|
* A Worker entry that sits in front of a TanStack Start handler (or any
|
|
3
3
|
* `{ fetch }` handler) and fixes what Start leaves to the app:
|
|
4
4
|
*
|
|
5
|
-
* - A page request
|
|
6
|
-
*
|
|
7
|
-
* - A page request whose Accept header
|
|
8
|
-
*
|
|
9
|
-
* -
|
|
10
|
-
* - Paths under a read-only prefix (default `/api
|
|
11
|
-
* than GET and
|
|
5
|
+
* - A page request that prefers text/markdown gets the Markdown rendering the
|
|
6
|
+
* app provides, on the same URL.
|
|
7
|
+
* - A page request whose Accept header rules out HTML gets HTML anyway,
|
|
8
|
+
* instead of Start's 406.
|
|
9
|
+
* - When Markdown is on, every page response carries `Vary: Accept`.
|
|
10
|
+
* - Paths under a read-only prefix (default `/api`) answer OPTIONS with 204
|
|
11
|
+
* and anything other than GET, HEAD and OPTIONS with 405, instead of an
|
|
12
|
+
* empty 200 page shell.
|
|
12
13
|
*/
|
|
13
14
|
|
|
15
|
+
import { parseAccept, quality } from "./accept.js";
|
|
16
|
+
|
|
14
17
|
type MaybePromise<T> = T | Promise<T>;
|
|
15
18
|
|
|
16
19
|
/** What a Markdown renderer returns: a body, a body with a status, or null to serve HTML. */
|
|
@@ -25,98 +28,168 @@ export interface EntryOptions {
|
|
|
25
28
|
/** The framework handler, usually the default export of `@tanstack/react-start/server-entry`. */
|
|
26
29
|
handler: FetchHandler;
|
|
27
30
|
/**
|
|
28
|
-
* Markdown rendering of a page. Called for GET and HEAD page requests
|
|
29
|
-
*
|
|
31
|
+
* Markdown rendering of a page. Called for GET and HEAD page requests that
|
|
32
|
+
* prefer text/markdown, with the decoded path, no trailing slash. Return
|
|
33
|
+
* null to serve HTML instead. If it throws, the error is logged and HTML is
|
|
34
|
+
* served.
|
|
30
35
|
*/
|
|
31
|
-
markdown?: (
|
|
32
|
-
/** Path prefixes that only accept GET and HEAD. Default `["/api/"]`. Pass `[]` to turn off. */
|
|
33
|
-
readOnlyPrefixes?: string[];
|
|
36
|
+
markdown?: (path: string, request: Request) => MaybePromise<MarkdownResult>;
|
|
34
37
|
/**
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
+
* Path prefixes that only accept GET, HEAD and OPTIONS. Matched by segment,
|
|
39
|
+
* case-insensitively, after decoding: `/api` covers `/api`, `/api/x` and
|
|
40
|
+
* `/API/x`, not `/apiary`. Default `["/api"]`. Pass `[]` to turn off.
|
|
38
41
|
*/
|
|
39
|
-
|
|
42
|
+
readOnlyPrefixes?: string[];
|
|
43
|
+
/** Whether a path is a page. Receives the normalized path. Default: {@link defaultIsPage}. */
|
|
44
|
+
isPage?: (path: string) => boolean;
|
|
40
45
|
}
|
|
41
46
|
|
|
42
|
-
|
|
47
|
+
/** Last-segment extensions that mark a file rather than a page. */
|
|
48
|
+
const FILE_EXTENSION =
|
|
49
|
+
/\.(?:js|mjs|cjs|css|map|json|xml|txt|md|csv|ico|png|jpe?g|gif|svg|webp|avif|bmp|woff2?|ttf|otf|eot|pdf|mp[34]|webm|wav|ogg|zip|gz|br|wasm|webmanifest|html?|rss|atom)$/i;
|
|
50
|
+
const DEV_INTERNALS = ["/@vite/", "/@fs/", "/@id/", "/@react-refresh", "/node_modules/"];
|
|
51
|
+
const DUPLICATE_SLASHES = /\/{2,}/g;
|
|
43
52
|
const TRAILING_SLASHES = /\/+$/;
|
|
44
53
|
|
|
45
|
-
export const MARKDOWN_HEADERS: Readonly<Record<string, string>> = {
|
|
54
|
+
export const MARKDOWN_HEADERS: Readonly<Record<string, string>> = Object.freeze({
|
|
46
55
|
"content-type": "text/markdown; charset=utf-8",
|
|
47
56
|
vary: "Accept",
|
|
48
57
|
// A Markdown body is a second representation of a page, not a page of its own.
|
|
49
58
|
"x-robots-tag": "noindex",
|
|
50
|
-
};
|
|
59
|
+
});
|
|
51
60
|
|
|
61
|
+
/**
|
|
62
|
+
* True when the client names text/markdown with q > 0 and rates it at least
|
|
63
|
+
* as high as HTML. Wildcards alone never select Markdown.
|
|
64
|
+
*/
|
|
52
65
|
export function wantsMarkdown(request: Request): boolean {
|
|
53
|
-
|
|
66
|
+
const ranges = parseAccept(request.headers.get("accept"));
|
|
67
|
+
const markdown = quality(ranges, "text/markdown", { exactOnly: true });
|
|
68
|
+
return markdown > 0 && markdown >= quality(ranges, "text/html");
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function acceptsHtml(request: Request): boolean {
|
|
72
|
+
return quality(parseAccept(request.headers.get("accept")), "text/html") > 0;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Decodes the path, collapses repeated slashes and drops trailing ones:
|
|
77
|
+
* `/learn//caf%C3%A9/` becomes `/learn/café`. `/` stays `/`. A path that is
|
|
78
|
+
* not valid percent-encoding is returned with only the slash fixes.
|
|
79
|
+
*/
|
|
80
|
+
export function normalizePath(pathname: string): string {
|
|
81
|
+
let path = pathname;
|
|
82
|
+
try {
|
|
83
|
+
path = decodeURIComponent(pathname);
|
|
84
|
+
} catch {
|
|
85
|
+
// Malformed escapes: match on the raw path.
|
|
86
|
+
}
|
|
87
|
+
path = path.replace(DUPLICATE_SLASHES, "/");
|
|
88
|
+
return path.length > 1 ? path.replace(TRAILING_SLASHES, "") || "/" : path;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Whether `path` sits under `prefix`, by whole segments and ignoring case. */
|
|
92
|
+
export function underPrefix(path: string, prefix: string): boolean {
|
|
93
|
+
const p = path.toLowerCase();
|
|
94
|
+
const base = prefix.toLowerCase().replace(TRAILING_SLASHES, "");
|
|
95
|
+
return base === "" || p === base || p.startsWith(`${base}/`);
|
|
54
96
|
}
|
|
55
97
|
|
|
56
|
-
|
|
57
|
-
|
|
98
|
+
/**
|
|
99
|
+
* Default page test: not under a read-only prefix, not a Start or Vite
|
|
100
|
+
* internal (`/_…`, `/@vite/…` and similar), and no file extension such as
|
|
101
|
+
* `.js` or `.xml` on the last segment. A dotted slug like `/blog/node.js-tips`
|
|
102
|
+
* is still a page.
|
|
103
|
+
*/
|
|
104
|
+
export function defaultIsPage(path: string, readOnlyPrefixes: readonly string[] = ["/api"]): boolean {
|
|
105
|
+
if (readOnlyPrefixes.some((prefix) => underPrefix(path, prefix))) {
|
|
58
106
|
return false;
|
|
59
107
|
}
|
|
60
|
-
if (
|
|
108
|
+
if (path.startsWith("/_") || DEV_INTERNALS.some((prefix) => path.startsWith(prefix))) {
|
|
61
109
|
return false;
|
|
62
110
|
}
|
|
63
|
-
|
|
64
|
-
return !lastSegment.includes(".");
|
|
111
|
+
return !FILE_EXTENSION.test(path);
|
|
65
112
|
}
|
|
66
113
|
|
|
67
|
-
/**
|
|
68
|
-
export function
|
|
69
|
-
|
|
114
|
+
/** Appends `token` to a Vary header value unless it is already there or the value is `*`. */
|
|
115
|
+
export function mergeVary(existing: string | null, token: string): string {
|
|
116
|
+
if (!existing?.trim()) {
|
|
117
|
+
return token;
|
|
118
|
+
}
|
|
119
|
+
const tokens = existing.split(",").map((t) => t.trim().toLowerCase());
|
|
120
|
+
if (tokens.includes("*") || tokens.includes(token.toLowerCase())) {
|
|
121
|
+
return existing;
|
|
122
|
+
}
|
|
123
|
+
return `${existing}, ${token}`;
|
|
70
124
|
}
|
|
71
125
|
|
|
126
|
+
const NULL_BODY_STATUS = new Set([101, 204, 205, 304]);
|
|
127
|
+
|
|
72
128
|
function markdownResponse(result: Exclude<MarkdownResult, null | undefined>, head: boolean): Response {
|
|
73
129
|
const { body, status = 200 } = typeof result === "string" ? { body: result } : result;
|
|
74
|
-
|
|
130
|
+
const noBody = head || NULL_BODY_STATUS.has(status);
|
|
131
|
+
return new Response(noBody ? null : body, { status, headers: MARKDOWN_HEADERS });
|
|
75
132
|
}
|
|
76
133
|
|
|
77
134
|
function withVaryAccept(response: Response): Response {
|
|
78
|
-
|
|
135
|
+
const vary = mergeVary(response.headers.get("vary"), "Accept");
|
|
136
|
+
if (vary === response.headers.get("vary")) {
|
|
79
137
|
return response;
|
|
80
138
|
}
|
|
81
139
|
const headers = new Headers(response.headers);
|
|
82
|
-
headers.
|
|
140
|
+
headers.set("vary", vary);
|
|
83
141
|
return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
|
|
84
142
|
}
|
|
85
143
|
|
|
86
144
|
export function createEntry(options: EntryOptions): {
|
|
87
145
|
fetch(request: Request, ...rest: unknown[]): Promise<Response>;
|
|
88
146
|
} {
|
|
89
|
-
const readOnlyPrefixes = options.readOnlyPrefixes ?? ["/api
|
|
90
|
-
const isPage = options.isPage ?? ((
|
|
147
|
+
const readOnlyPrefixes = options.readOnlyPrefixes ?? ["/api"];
|
|
148
|
+
const isPage = options.isPage ?? ((path: string) => defaultIsPage(path, readOnlyPrefixes));
|
|
91
149
|
|
|
92
150
|
return {
|
|
93
151
|
async fetch(request, ...rest) {
|
|
94
|
-
const
|
|
95
|
-
const
|
|
152
|
+
const path = normalizePath(new URL(request.url).pathname);
|
|
153
|
+
const method = request.method.toUpperCase();
|
|
154
|
+
const isRead = method === "GET" || method === "HEAD";
|
|
96
155
|
|
|
97
|
-
if (
|
|
98
|
-
|
|
156
|
+
if (readOnlyPrefixes.some((prefix) => underPrefix(path, prefix))) {
|
|
157
|
+
if (method === "OPTIONS") {
|
|
158
|
+
return new Response(null, { status: 204, headers: { allow: "GET, HEAD, OPTIONS" } });
|
|
159
|
+
}
|
|
160
|
+
if (!isRead) {
|
|
161
|
+
return Response.json(
|
|
162
|
+
{ error: "Method not allowed" },
|
|
163
|
+
{ status: 405, headers: { allow: "GET, HEAD, OPTIONS" } },
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
return options.handler.fetch(request, ...rest);
|
|
99
167
|
}
|
|
100
168
|
|
|
101
|
-
if (!isPage(
|
|
169
|
+
if (!(isRead && isPage(path))) {
|
|
102
170
|
return options.handler.fetch(request, ...rest);
|
|
103
171
|
}
|
|
104
172
|
|
|
105
|
-
if (
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
173
|
+
if (options.markdown && wantsMarkdown(request)) {
|
|
174
|
+
try {
|
|
175
|
+
const result = await options.markdown(path, request);
|
|
176
|
+
if (result !== null && result !== undefined) {
|
|
177
|
+
return markdownResponse(result, method === "HEAD");
|
|
178
|
+
}
|
|
179
|
+
} catch (error) {
|
|
180
|
+
console.error("workers-start: markdown renderer failed, serving HTML", error);
|
|
109
181
|
}
|
|
110
182
|
}
|
|
111
183
|
|
|
112
184
|
let pageRequest = request;
|
|
113
|
-
if (
|
|
185
|
+
if (!acceptsHtml(request)) {
|
|
114
186
|
const headers = new Headers(request.headers);
|
|
115
187
|
headers.set("accept", "text/html");
|
|
116
188
|
pageRequest = new Request(request, { headers });
|
|
117
189
|
}
|
|
118
190
|
|
|
119
|
-
|
|
191
|
+
const response = await options.handler.fetch(pageRequest, ...rest);
|
|
192
|
+
return options.markdown ? withVaryAccept(response) : response;
|
|
120
193
|
},
|
|
121
194
|
};
|
|
122
195
|
}
|