noofpi 0.0.0-stage → 1.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 +47 -2
- package/bin/noofpi.mjs +2 -0
- package/client.d.ts +79 -0
- package/dist/build-63DMFZJY.js +48 -0
- package/dist/chunk-2XCZWFIQ.js +253 -0
- package/dist/chunk-6OWKWAIW.js +68 -0
- package/dist/chunk-ELXCFUA4.js +97 -0
- package/dist/chunk-EZPJF4D4.js +314 -0
- package/dist/chunk-FIJJ3EGL.js +353 -0
- package/dist/chunk-G35DW4NA.js +129 -0
- package/dist/chunk-KGZP2RCF.js +51 -0
- package/dist/chunk-MTWSTW7V.js +44 -0
- package/dist/chunk-MTXQR32N.js +8 -0
- package/dist/chunk-NALDZ3PS.js +90 -0
- package/dist/chunk-NX6BO7UB.js +284 -0
- package/dist/chunk-SSJ2KKBZ.js +996 -0
- package/dist/chunk-WX2V6EYH.js +102 -0
- package/dist/chunk-X34Y6ESE.js +810 -0
- package/dist/chunk-Y3NBZ6DW.js +55 -0
- package/dist/chunk-YZAZ7IWK.js +27 -0
- package/dist/cli.js +93 -0
- package/dist/dev-USSN6KFV.js +149 -0
- package/dist/devtools-KTDSD5PR.js +564 -0
- package/dist/images-BNwTAi50.d.ts +36 -0
- package/dist/index.d.ts +115 -0
- package/dist/index.js +15 -0
- package/dist/route-rules-COilNsVT.d.ts +127 -0
- package/dist/runtime/default-app.js +15 -0
- package/dist/runtime/entry-client.js +70 -0
- package/dist/runtime/entry-server.js +107 -0
- package/dist/runtime/index.d.ts +523 -0
- package/dist/runtime/index.js +224 -0
- package/dist/runtime/routes.js +14 -0
- package/dist/server/bun.js +47 -0
- package/dist/server/index.d.ts +109 -0
- package/dist/server/index.js +48 -0
- package/dist/server/node.js +15 -0
- package/dist/start-U6A3PBRI.js +61 -0
- package/dist/validation-ClXd_DAW.d.ts +159 -0
- package/package.json +101 -4
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
// src/cookies.ts
|
|
2
|
+
var stringCodec = {
|
|
3
|
+
encode: (value) => value,
|
|
4
|
+
decode: (raw) => raw
|
|
5
|
+
};
|
|
6
|
+
var numberCodec = {
|
|
7
|
+
encode: (value) => String(value),
|
|
8
|
+
decode: (raw) => {
|
|
9
|
+
const value = Number(raw);
|
|
10
|
+
if (raw.trim() === "" || Number.isNaN(value))
|
|
11
|
+
throw new Error(`Not a number: ${raw}`);
|
|
12
|
+
return value;
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
var booleanCodec = {
|
|
16
|
+
encode: (value) => value ? "true" : "false",
|
|
17
|
+
decode: (raw) => {
|
|
18
|
+
if (raw === "true") return true;
|
|
19
|
+
if (raw === "false") return false;
|
|
20
|
+
throw new Error(`Not a boolean: ${raw}`);
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
function jsonCodec() {
|
|
24
|
+
return {
|
|
25
|
+
encode: (value) => JSON.stringify(value),
|
|
26
|
+
decode: (raw) => JSON.parse(raw)
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
function enumCodec(values) {
|
|
30
|
+
return {
|
|
31
|
+
encode: (value) => value,
|
|
32
|
+
decode: (raw) => {
|
|
33
|
+
if (!values.includes(raw))
|
|
34
|
+
throw new Error(`Unexpected value: ${raw}`);
|
|
35
|
+
return raw;
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
function defineCookie(name, options = {}) {
|
|
40
|
+
const { codec, ...rest } = options;
|
|
41
|
+
return { name, codec: codec ?? stringCodec, options: rest };
|
|
42
|
+
}
|
|
43
|
+
var safeDecode = (value) => {
|
|
44
|
+
try {
|
|
45
|
+
return decodeURIComponent(value);
|
|
46
|
+
} catch {
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
function parseCookies(header) {
|
|
51
|
+
const cookies = /* @__PURE__ */ Object.create(null);
|
|
52
|
+
if (!header) return cookies;
|
|
53
|
+
for (const part of header.split(";")) {
|
|
54
|
+
const eq = part.indexOf("=");
|
|
55
|
+
if (eq < 1) continue;
|
|
56
|
+
const name = part.slice(0, eq).trim();
|
|
57
|
+
if (!name || name in cookies) continue;
|
|
58
|
+
let value = part.slice(eq + 1).trim();
|
|
59
|
+
if (value.length > 1 && value.startsWith('"') && value.endsWith('"'))
|
|
60
|
+
value = value.slice(1, -1);
|
|
61
|
+
cookies[name] = safeDecode(value);
|
|
62
|
+
}
|
|
63
|
+
return cookies;
|
|
64
|
+
}
|
|
65
|
+
var NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
66
|
+
var ATTRIBUTE = /^[\x20-\x3a\x3c-\x7e]+$/;
|
|
67
|
+
var MAX_SIZE = 4096;
|
|
68
|
+
function mergeCookieOptions(...layers) {
|
|
69
|
+
const merged = {};
|
|
70
|
+
for (const layer of layers)
|
|
71
|
+
for (const [key, value] of Object.entries(layer ?? {}))
|
|
72
|
+
if (value !== void 0) merged[key] = value;
|
|
73
|
+
return merged;
|
|
74
|
+
}
|
|
75
|
+
function serializeCookie(name, value, options = {}) {
|
|
76
|
+
if (!NAME.test(name))
|
|
77
|
+
throw new Error(`[noofpi] Invalid cookie name: ${name}`);
|
|
78
|
+
const pair = `${name}=${encodeURIComponent(value)}`;
|
|
79
|
+
if (new TextEncoder().encode(pair).length > MAX_SIZE)
|
|
80
|
+
throw new Error(
|
|
81
|
+
`[noofpi] Cookie "${name}" is larger than ${MAX_SIZE} bytes, browsers would drop it`
|
|
82
|
+
);
|
|
83
|
+
const { maxAge, expires, domain, path, httpOnly, sameSite, partitioned } = options;
|
|
84
|
+
const secure = options.secure || sameSite === "none" || partitioned || name.startsWith("__Secure-") || name.startsWith("__Host-");
|
|
85
|
+
const parts = [pair];
|
|
86
|
+
if (path !== void 0) {
|
|
87
|
+
if (!ATTRIBUTE.test(path))
|
|
88
|
+
throw new Error(`[noofpi] Invalid cookie path: ${path}`);
|
|
89
|
+
parts.push(`Path=${path}`);
|
|
90
|
+
}
|
|
91
|
+
if (domain !== void 0) {
|
|
92
|
+
if (!ATTRIBUTE.test(domain))
|
|
93
|
+
throw new Error(`[noofpi] Invalid cookie domain: ${domain}`);
|
|
94
|
+
parts.push(`Domain=${domain}`);
|
|
95
|
+
}
|
|
96
|
+
if (maxAge !== void 0) {
|
|
97
|
+
if (!Number.isFinite(maxAge))
|
|
98
|
+
throw new Error(`[noofpi] Invalid cookie maxAge: ${maxAge}`);
|
|
99
|
+
parts.push(`Max-Age=${Math.trunc(maxAge)}`);
|
|
100
|
+
}
|
|
101
|
+
if (expires !== void 0) {
|
|
102
|
+
if (Number.isNaN(expires.getTime()))
|
|
103
|
+
throw new Error("[noofpi] Invalid cookie expires date");
|
|
104
|
+
parts.push(`Expires=${expires.toUTCString()}`);
|
|
105
|
+
}
|
|
106
|
+
if (httpOnly) parts.push("HttpOnly");
|
|
107
|
+
if (secure) parts.push("Secure");
|
|
108
|
+
if (sameSite)
|
|
109
|
+
parts.push(
|
|
110
|
+
`SameSite=${sameSite.charAt(0).toUpperCase()}${sameSite.slice(1)}`
|
|
111
|
+
);
|
|
112
|
+
if (partitioned) parts.push("Partitioned");
|
|
113
|
+
return parts.join("; ");
|
|
114
|
+
}
|
|
115
|
+
function createCookieJar(init = {}) {
|
|
116
|
+
const { write } = init;
|
|
117
|
+
const defaults = mergeCookieOptions(
|
|
118
|
+
{ path: "/", sameSite: "lax", httpOnly: true },
|
|
119
|
+
init.defaults
|
|
120
|
+
);
|
|
121
|
+
const source = typeof init.cookie === "function" ? /* @__PURE__ */ ((header) => () => parseCookies(header()))(init.cookie) : /* @__PURE__ */ ((parsed) => () => parsed)(parseCookies(init.cookie));
|
|
122
|
+
const queue = /* @__PURE__ */ new Map();
|
|
123
|
+
const overrides = /* @__PURE__ */ new Map();
|
|
124
|
+
const read = () => {
|
|
125
|
+
const all = Object.assign(
|
|
126
|
+
/* @__PURE__ */ Object.create(null),
|
|
127
|
+
source()
|
|
128
|
+
);
|
|
129
|
+
for (const [name, value] of overrides)
|
|
130
|
+
if (value === null) delete all[name];
|
|
131
|
+
else all[name] = value;
|
|
132
|
+
return all;
|
|
133
|
+
};
|
|
134
|
+
const emit = (name, value, options) => {
|
|
135
|
+
const header = serializeCookie(
|
|
136
|
+
name,
|
|
137
|
+
value ?? "",
|
|
138
|
+
write ? { ...options, httpOnly: false } : options
|
|
139
|
+
);
|
|
140
|
+
if (write) {
|
|
141
|
+
write(header);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
queue.set(`${name}|${options.domain ?? ""}|${options.path ?? ""}`, header);
|
|
145
|
+
overrides.set(name, value);
|
|
146
|
+
};
|
|
147
|
+
const definition = (target, codec) => typeof target === "string" ? { name: target, codec: codec ?? stringCodec, options: {} } : target;
|
|
148
|
+
return {
|
|
149
|
+
has: (name) => name in read(),
|
|
150
|
+
get(target, codec) {
|
|
151
|
+
const cookie = definition(target, codec);
|
|
152
|
+
const raw = read()[cookie.name];
|
|
153
|
+
if (raw === void 0) return void 0;
|
|
154
|
+
try {
|
|
155
|
+
return cookie.codec.decode(raw);
|
|
156
|
+
} catch {
|
|
157
|
+
return void 0;
|
|
158
|
+
}
|
|
159
|
+
},
|
|
160
|
+
getAll: () => ({ ...read() }),
|
|
161
|
+
set(target, value, options = {}) {
|
|
162
|
+
const { codec, ...rest } = options;
|
|
163
|
+
const cookie = definition(target, codec);
|
|
164
|
+
emit(
|
|
165
|
+
cookie.name,
|
|
166
|
+
String(cookie.codec.encode(value)),
|
|
167
|
+
mergeCookieOptions(defaults, cookie.options, rest)
|
|
168
|
+
);
|
|
169
|
+
},
|
|
170
|
+
remove(target, options) {
|
|
171
|
+
const cookie = definition(target);
|
|
172
|
+
emit(
|
|
173
|
+
cookie.name,
|
|
174
|
+
null,
|
|
175
|
+
mergeCookieOptions(defaults, cookie.options, options, {
|
|
176
|
+
maxAge: 0,
|
|
177
|
+
expires: /* @__PURE__ */ new Date(0)
|
|
178
|
+
})
|
|
179
|
+
);
|
|
180
|
+
},
|
|
181
|
+
toSetCookieHeaders: () => [...queue.values()]
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
function applyCookies(response, jar) {
|
|
185
|
+
const cookies = jar.toSetCookieHeaders();
|
|
186
|
+
if (!cookies.length) return response;
|
|
187
|
+
try {
|
|
188
|
+
for (const cookie of cookies) response.headers.append("set-cookie", cookie);
|
|
189
|
+
return response;
|
|
190
|
+
} catch {
|
|
191
|
+
const headers = new Headers(response.headers);
|
|
192
|
+
for (const cookie of cookies) headers.append("set-cookie", cookie);
|
|
193
|
+
return new Response(response.body, {
|
|
194
|
+
status: response.status,
|
|
195
|
+
statusText: response.statusText,
|
|
196
|
+
headers
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// src/error.ts
|
|
202
|
+
var STATUS_TEXT = {
|
|
203
|
+
400: "Bad Request",
|
|
204
|
+
401: "Unauthorized",
|
|
205
|
+
403: "Forbidden",
|
|
206
|
+
404: "Not Found",
|
|
207
|
+
500: "Internal Server Error",
|
|
208
|
+
503: "Service Unavailable"
|
|
209
|
+
};
|
|
210
|
+
var validStatus = (value) => Number.isInteger(value) && value >= 400 && value <= 599;
|
|
211
|
+
var BRAND = "__noofpiError";
|
|
212
|
+
var NoofpiError = class extends Error {
|
|
213
|
+
[BRAND] = true;
|
|
214
|
+
statusCode;
|
|
215
|
+
statusMessage;
|
|
216
|
+
url;
|
|
217
|
+
constructor(input = {}) {
|
|
218
|
+
const statusCode = validStatus(input.statusCode) ? input.statusCode : 500;
|
|
219
|
+
const statusMessage = input.statusMessage ?? STATUS_TEXT[statusCode] ?? "Error";
|
|
220
|
+
super(input.message ?? statusMessage);
|
|
221
|
+
this.name = "NoofpiError";
|
|
222
|
+
this.statusCode = statusCode;
|
|
223
|
+
this.statusMessage = statusMessage;
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
function createError(input) {
|
|
227
|
+
return new NoofpiError(
|
|
228
|
+
typeof input === "string" ? { message: input } : input
|
|
229
|
+
);
|
|
230
|
+
}
|
|
231
|
+
function isNoofpiError(error) {
|
|
232
|
+
return error instanceof Error && error[BRAND] === true;
|
|
233
|
+
}
|
|
234
|
+
function toErrorData(error, url) {
|
|
235
|
+
const known = isNoofpiError(error) ? error : createError({});
|
|
236
|
+
return {
|
|
237
|
+
statusCode: known.statusCode,
|
|
238
|
+
statusMessage: known.statusMessage,
|
|
239
|
+
message: known.message,
|
|
240
|
+
...(known.url ?? url) !== void 0 ? { url: known.url ?? url } : {}
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
function parseErrorData(value) {
|
|
244
|
+
if (!value || typeof value !== "object") return void 0;
|
|
245
|
+
const { statusCode, statusMessage, message, url } = value;
|
|
246
|
+
if (typeof statusCode !== "number") return void 0;
|
|
247
|
+
return {
|
|
248
|
+
statusCode,
|
|
249
|
+
statusMessage: typeof statusMessage === "string" ? statusMessage : "Error",
|
|
250
|
+
message: typeof message === "string" ? message : "",
|
|
251
|
+
...typeof url === "string" ? { url } : {}
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// src/requests.ts
|
|
256
|
+
var isEntry = (value) => {
|
|
257
|
+
const entry = value;
|
|
258
|
+
return typeof entry === "object" && entry !== null && (entry.side === "server" || entry.side === "browser") && typeof entry.mode === "string" && (entry.transport === "in-process" || entry.transport === "http") && typeof entry.method === "string" && typeof entry.url === "string";
|
|
259
|
+
};
|
|
260
|
+
var parseEntries = (value) => Array.isArray(value) ? value.filter(isEntry) : [];
|
|
261
|
+
|
|
262
|
+
// src/payload.ts
|
|
263
|
+
var PAYLOAD_ELEMENT_ID = "__noofpi_payload__";
|
|
264
|
+
var isEmptyPayload = (payload) => Object.keys(payload.data).length === 0 && Object.keys(payload.errors).length === 0 && Object.keys(payload.state ?? {}).length === 0 && !payload.error && !payload.locale && !payload.requests?.length;
|
|
265
|
+
function serializePayload(payload) {
|
|
266
|
+
const json = JSON.stringify(payload).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
|
|
267
|
+
return `<script type="application/json" id="${PAYLOAD_ELEMENT_ID}">${json}</script>`;
|
|
268
|
+
}
|
|
269
|
+
function injectPayload(html, payload) {
|
|
270
|
+
if (isEmptyPayload(payload)) return html;
|
|
271
|
+
const script = serializePayload(payload);
|
|
272
|
+
return html.includes("</body>") ? html.replace("</body>", () => script + "</body>") : html + script;
|
|
273
|
+
}
|
|
274
|
+
function readPayload() {
|
|
275
|
+
const element = document.getElementById(PAYLOAD_ELEMENT_ID);
|
|
276
|
+
if (!element) return { data: {}, errors: {} };
|
|
277
|
+
element.remove();
|
|
278
|
+
try {
|
|
279
|
+
const parsed = JSON.parse(
|
|
280
|
+
element.textContent ?? ""
|
|
281
|
+
);
|
|
282
|
+
const error = parseErrorData(parsed.error);
|
|
283
|
+
const requests = parseEntries(parsed.requests);
|
|
284
|
+
const locale = typeof parsed.locale === "string" ? parsed.locale : void 0;
|
|
285
|
+
const state = parsed.state && typeof parsed.state === "object" ? parsed.state : {};
|
|
286
|
+
return {
|
|
287
|
+
data: parsed.data ?? {},
|
|
288
|
+
errors: parsed.errors ?? {},
|
|
289
|
+
state,
|
|
290
|
+
...error ? { error } : {},
|
|
291
|
+
...locale ? { locale } : {},
|
|
292
|
+
...requests.length ? { requests } : {}
|
|
293
|
+
};
|
|
294
|
+
} catch {
|
|
295
|
+
return { data: {}, errors: {} };
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
export {
|
|
300
|
+
stringCodec,
|
|
301
|
+
numberCodec,
|
|
302
|
+
booleanCodec,
|
|
303
|
+
jsonCodec,
|
|
304
|
+
enumCodec,
|
|
305
|
+
defineCookie,
|
|
306
|
+
mergeCookieOptions,
|
|
307
|
+
createCookieJar,
|
|
308
|
+
applyCookies,
|
|
309
|
+
createError,
|
|
310
|
+
isNoofpiError,
|
|
311
|
+
toErrorData,
|
|
312
|
+
injectPayload,
|
|
313
|
+
readPayload
|
|
314
|
+
};
|
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
// src/fetch-mode.ts
|
|
2
|
+
var FETCH_MODES = ["dfetch", "pfetch", "lfetch", "sfetch"];
|
|
3
|
+
|
|
4
|
+
// src/csp.ts
|
|
5
|
+
var NONCE_TOKEN = "'nonce'";
|
|
6
|
+
var DIRECTIVE_NAME = /^[a-z][a-z0-9-]*$/;
|
|
7
|
+
var FORBIDDEN_VALUE = /[;,\u0000-\u001f\u007f]/;
|
|
8
|
+
function sources(value) {
|
|
9
|
+
if (typeof value === "boolean") return [];
|
|
10
|
+
return (Array.isArray(value) ? value : value.split(/\s+/)).filter(Boolean);
|
|
11
|
+
}
|
|
12
|
+
function validateCsp(csp) {
|
|
13
|
+
if (!csp || typeof csp.directives !== "object" || csp.directives === null || Array.isArray(csp.directives))
|
|
14
|
+
throw new Error("[noofpi] security.csp.directives must be an object");
|
|
15
|
+
for (const [name, value] of Object.entries(csp.directives)) {
|
|
16
|
+
if (!DIRECTIVE_NAME.test(name))
|
|
17
|
+
throw new Error(
|
|
18
|
+
`[noofpi] security.csp: "${name}" is not a valid directive name (use lowercase kebab-case, e.g. "script-src")`
|
|
19
|
+
);
|
|
20
|
+
if (value === void 0) continue;
|
|
21
|
+
if (typeof value !== "boolean" && typeof value !== "string" && !(Array.isArray(value) && value.every((s) => typeof s === "string")))
|
|
22
|
+
throw new Error(
|
|
23
|
+
`[noofpi] security.csp: "${name}" must be a string, an array of strings or a boolean`
|
|
24
|
+
);
|
|
25
|
+
for (const source of sources(value))
|
|
26
|
+
if (FORBIDDEN_VALUE.test(source))
|
|
27
|
+
throw new Error(
|
|
28
|
+
`[noofpi] security.csp: "${name}" has an invalid source "${source}" (no ";", "," or control characters)`
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function usesNonce(csp) {
|
|
33
|
+
return Object.values(csp?.directives ?? {}).some(
|
|
34
|
+
(value) => value !== void 0 && sources(value).includes(NONCE_TOKEN)
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
function generateNonce() {
|
|
38
|
+
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
|
39
|
+
let binary = "";
|
|
40
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
41
|
+
return btoa(binary);
|
|
42
|
+
}
|
|
43
|
+
function buildCspHeader(csp, nonce) {
|
|
44
|
+
const parts = [];
|
|
45
|
+
for (const [name, value] of Object.entries(csp.directives)) {
|
|
46
|
+
if (value === void 0 || value === false) continue;
|
|
47
|
+
const list = sources(value).map(
|
|
48
|
+
(source) => source === NONCE_TOKEN && nonce ? `'nonce-${nonce}'` : source
|
|
49
|
+
);
|
|
50
|
+
parts.push([name, ...list].join(" "));
|
|
51
|
+
}
|
|
52
|
+
return [
|
|
53
|
+
csp.reportOnly ? "Content-Security-Policy-Report-Only" : "Content-Security-Policy",
|
|
54
|
+
parts.join("; ")
|
|
55
|
+
];
|
|
56
|
+
}
|
|
57
|
+
var NONCED_LINK_REL = /\brel\s*=\s*["']?(stylesheet|modulepreload|preload)\b/i;
|
|
58
|
+
function withNonce(tag, attrs, nonce) {
|
|
59
|
+
if (/\snonce\s*=/i.test(attrs)) return `<${tag}${attrs}>`;
|
|
60
|
+
const selfClosing = /\/\s*$/.test(attrs);
|
|
61
|
+
const open = attrs.replace(/\s*\/?\s*$/, "");
|
|
62
|
+
return `<${tag}${open} nonce="${nonce}"${selfClosing ? " /" : ""}>`;
|
|
63
|
+
}
|
|
64
|
+
function injectNonce(html, nonce) {
|
|
65
|
+
let result = html.replace(
|
|
66
|
+
/<(script|style)\b([^>]*)>/gi,
|
|
67
|
+
(_whole, tag, attrs) => withNonce(tag, attrs, nonce)
|
|
68
|
+
);
|
|
69
|
+
result = result.replace(
|
|
70
|
+
/<link\b([^>]*)>/gi,
|
|
71
|
+
(whole, attrs) => NONCED_LINK_REL.test(attrs) ? withNonce("link", attrs, nonce) : whole
|
|
72
|
+
);
|
|
73
|
+
const meta = ` <meta property="csp-nonce" nonce="${nonce}" />
|
|
74
|
+
`;
|
|
75
|
+
return result.includes("</head>") ? result.replace("</head>", () => meta + " </head>") : result;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// src/security.ts
|
|
79
|
+
var DEFAULT_BODY_LIMIT = 10 * 1024 * 1024;
|
|
80
|
+
var HSTS = "Strict-Transport-Security";
|
|
81
|
+
var DEFAULT_HEADERS = {
|
|
82
|
+
"X-Content-Type-Options": "nosniff",
|
|
83
|
+
"X-Frame-Options": "SAMEORIGIN",
|
|
84
|
+
"Referrer-Policy": "strict-origin-when-cross-origin",
|
|
85
|
+
"Permissions-Policy": "camera=(), microphone=(), geolocation=()",
|
|
86
|
+
[HSTS]: "max-age=15552000"
|
|
87
|
+
};
|
|
88
|
+
var HEADER_NAME = /^[A-Za-z0-9-]+$/;
|
|
89
|
+
var FORBIDDEN_HEADER_VALUE = /[\u0000-\u001f\u007f]/;
|
|
90
|
+
function overlayHeaders(base, input) {
|
|
91
|
+
if (input === false) return {};
|
|
92
|
+
const merged = { ...base };
|
|
93
|
+
if (input && typeof input === "object") {
|
|
94
|
+
for (const [name, value] of Object.entries(input)) {
|
|
95
|
+
if (!HEADER_NAME.test(name))
|
|
96
|
+
throw new Error(
|
|
97
|
+
`[noofpi] security.headers: "${name}" is not a valid header name`
|
|
98
|
+
);
|
|
99
|
+
if (value !== false && (typeof value !== "string" || FORBIDDEN_HEADER_VALUE.test(value)))
|
|
100
|
+
throw new Error(
|
|
101
|
+
`[noofpi] security.headers: "${name}" must be a string without control characters, or false`
|
|
102
|
+
);
|
|
103
|
+
const existing = Object.keys(merged).find(
|
|
104
|
+
(key) => key.toLowerCase() === name.toLowerCase()
|
|
105
|
+
);
|
|
106
|
+
if (existing && existing !== name) delete merged[existing];
|
|
107
|
+
merged[name] = value;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return Object.fromEntries(
|
|
111
|
+
Object.entries(merged).filter(
|
|
112
|
+
(entry) => entry[1] !== false
|
|
113
|
+
)
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
function resolveHeaders(input, csp) {
|
|
117
|
+
const defaults = { ...DEFAULT_HEADERS };
|
|
118
|
+
if (csp && "frame-ancestors" in csp.directives)
|
|
119
|
+
delete defaults["X-Frame-Options"];
|
|
120
|
+
return overlayHeaders(defaults, input);
|
|
121
|
+
}
|
|
122
|
+
function parseOrigin(origin, option) {
|
|
123
|
+
try {
|
|
124
|
+
const parsed = new URL(origin);
|
|
125
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
|
|
126
|
+
throw new Error();
|
|
127
|
+
return parsed.origin;
|
|
128
|
+
} catch {
|
|
129
|
+
throw new Error(
|
|
130
|
+
`[noofpi] security.csrf.${option} must be absolute http(s) origins (got "${origin}")`
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
function resolveCsrf(input) {
|
|
135
|
+
if (input === false) return false;
|
|
136
|
+
const config = typeof input === "object" ? input : void 0;
|
|
137
|
+
const resolved = {
|
|
138
|
+
allowedOrigins: (config?.allowedOrigins ?? []).map(
|
|
139
|
+
(origin) => parseOrigin(origin, "allowedOrigins")
|
|
140
|
+
)
|
|
141
|
+
};
|
|
142
|
+
if (config?.publicOrigin !== void 0)
|
|
143
|
+
resolved.publicOrigin = parseOrigin(config.publicOrigin, "publicOrigin");
|
|
144
|
+
return resolved;
|
|
145
|
+
}
|
|
146
|
+
function resolveBodyLimit(input) {
|
|
147
|
+
if (input === void 0) return DEFAULT_BODY_LIMIT;
|
|
148
|
+
if (input === false) return false;
|
|
149
|
+
if (!Number.isInteger(input) || input <= 0)
|
|
150
|
+
throw new Error(
|
|
151
|
+
`[noofpi] security.bodyLimit must be a positive number of bytes or false (got ${String(input)})`
|
|
152
|
+
);
|
|
153
|
+
return input;
|
|
154
|
+
}
|
|
155
|
+
function resolveAllowedHosts(input) {
|
|
156
|
+
if (input === void 0) return void 0;
|
|
157
|
+
return input.map((host) => {
|
|
158
|
+
if (typeof host !== "string" || !/^(\*\.)?[^\s/*@]+$/.test(host))
|
|
159
|
+
throw new Error(
|
|
160
|
+
`[noofpi] security.allowedHosts must be hostnames like "app.example.com" or "*.example.com" (got "${String(host)}")`
|
|
161
|
+
);
|
|
162
|
+
return host.toLowerCase();
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
function resolveSecurity(input = {}) {
|
|
166
|
+
if (input.csp) validateCsp(input.csp);
|
|
167
|
+
return {
|
|
168
|
+
csp: input.csp,
|
|
169
|
+
headers: resolveHeaders(input.headers, input.csp),
|
|
170
|
+
csrf: resolveCsrf(input.csrf),
|
|
171
|
+
bodyLimit: resolveBodyLimit(input.bodyLimit),
|
|
172
|
+
allowedHosts: resolveAllowedHosts(input.allowedHosts)
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
function applyRouteSecurity(base, rule) {
|
|
176
|
+
if (!rule) return base;
|
|
177
|
+
if (rule.csp) validateCsp(rule.csp);
|
|
178
|
+
const result = { ...base };
|
|
179
|
+
if (rule.csp !== void 0) result.csp = rule.csp || void 0;
|
|
180
|
+
if (rule.headers !== void 0)
|
|
181
|
+
result.headers = overlayHeaders(base?.headers ?? {}, rule.headers);
|
|
182
|
+
if (rule.csrf !== void 0) result.csrf = resolveCsrf(rule.csrf);
|
|
183
|
+
if (rule.bodyLimit !== void 0)
|
|
184
|
+
result.bodyLimit = resolveBodyLimit(rule.bodyLimit);
|
|
185
|
+
return result;
|
|
186
|
+
}
|
|
187
|
+
function isAllowedHost(url, allowed) {
|
|
188
|
+
if (!allowed) return true;
|
|
189
|
+
const host = url.host.toLowerCase();
|
|
190
|
+
const hostname = url.hostname.toLowerCase();
|
|
191
|
+
return allowed.some(
|
|
192
|
+
(entry) => entry.startsWith("*.") ? hostname.endsWith(entry.slice(1)) : entry === host || entry === hostname
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
|
|
196
|
+
function limitRequestBody(request, limit) {
|
|
197
|
+
if (SAFE_METHODS.has(request.method) || !request.body)
|
|
198
|
+
return { request, tooLarge: () => false };
|
|
199
|
+
if (Number(request.headers.get("content-length")) > limit)
|
|
200
|
+
return { request, tooLarge: () => true };
|
|
201
|
+
let received = 0;
|
|
202
|
+
let exceeded = false;
|
|
203
|
+
const body = request.body.pipeThrough(
|
|
204
|
+
new TransformStream({
|
|
205
|
+
transform(chunk, controller) {
|
|
206
|
+
received += chunk.byteLength;
|
|
207
|
+
if (received > limit) {
|
|
208
|
+
exceeded = true;
|
|
209
|
+
controller.error(new Error("[noofpi] Request body too large"));
|
|
210
|
+
} else controller.enqueue(chunk);
|
|
211
|
+
}
|
|
212
|
+
})
|
|
213
|
+
);
|
|
214
|
+
return {
|
|
215
|
+
request: new Request(request.url, {
|
|
216
|
+
method: request.method,
|
|
217
|
+
headers: request.headers,
|
|
218
|
+
body,
|
|
219
|
+
signal: request.signal,
|
|
220
|
+
duplex: "half"
|
|
221
|
+
}),
|
|
222
|
+
tooLarge: () => exceeded
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
function isCrossSiteWrite(request, url, csrf) {
|
|
226
|
+
if (SAFE_METHODS.has(request.method)) return false;
|
|
227
|
+
const origin = request.headers.get("origin");
|
|
228
|
+
if (origin !== null) {
|
|
229
|
+
if (csrf.allowedOrigins.includes(origin)) return false;
|
|
230
|
+
if (csrf.publicOrigin !== void 0) return origin !== csrf.publicOrigin;
|
|
231
|
+
try {
|
|
232
|
+
return new URL(origin).host !== url.host;
|
|
233
|
+
} catch {
|
|
234
|
+
return true;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
const site = request.headers.get("sec-fetch-site");
|
|
238
|
+
return site !== null && site !== "same-origin" && site !== "none";
|
|
239
|
+
}
|
|
240
|
+
function applySecurityHeaders(response, headers, https) {
|
|
241
|
+
const missing = Object.entries(headers).filter(
|
|
242
|
+
([name]) => !response.headers.has(name) && (https || name.toLowerCase() !== HSTS.toLowerCase())
|
|
243
|
+
);
|
|
244
|
+
if (!missing.length) return response;
|
|
245
|
+
const apply = (target) => {
|
|
246
|
+
for (const [name, value] of missing) target.set(name, value);
|
|
247
|
+
};
|
|
248
|
+
try {
|
|
249
|
+
apply(response.headers);
|
|
250
|
+
return response;
|
|
251
|
+
} catch {
|
|
252
|
+
const copy = new Headers(response.headers);
|
|
253
|
+
apply(copy);
|
|
254
|
+
return new Response(response.body, {
|
|
255
|
+
status: response.status,
|
|
256
|
+
statusText: response.statusText,
|
|
257
|
+
headers: copy
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// src/route-rules.ts
|
|
263
|
+
function patternToRegExp(pattern) {
|
|
264
|
+
const source = pattern.split("/").map(
|
|
265
|
+
(segment) => segment === "**" ? ".*" : segment.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join("[^/]*")
|
|
266
|
+
).join("/").replace(/\/\.\*$/, "(?:/.*)?");
|
|
267
|
+
return new RegExp(`^${source}/?$`, "i");
|
|
268
|
+
}
|
|
269
|
+
function validateRouteRules(rules, ssr) {
|
|
270
|
+
for (const [pattern, rule] of Object.entries(rules)) {
|
|
271
|
+
if (!pattern.startsWith("/"))
|
|
272
|
+
throw new Error(
|
|
273
|
+
`[noofpi] routeRules patterns must start with "/" (got "${pattern}")`
|
|
274
|
+
);
|
|
275
|
+
if (rule.ssr !== void 0 && typeof rule.ssr !== "boolean")
|
|
276
|
+
throw new Error(
|
|
277
|
+
`[noofpi] routeRules["${pattern}"].ssr must be a boolean`
|
|
278
|
+
);
|
|
279
|
+
if (rule.ssr === true && !ssr)
|
|
280
|
+
throw new Error(
|
|
281
|
+
`[noofpi] routeRules["${pattern}"].ssr: true needs ssr: true in the config (routeRules can only turn SSR off)`
|
|
282
|
+
);
|
|
283
|
+
if (rule.fetch !== void 0) {
|
|
284
|
+
if (!FETCH_MODES.includes(rule.fetch))
|
|
285
|
+
throw new Error(
|
|
286
|
+
`[noofpi] routeRules["${pattern}"].fetch must be one of ${FETCH_MODES.join(", ")} (got "${String(rule.fetch)}")`
|
|
287
|
+
);
|
|
288
|
+
if (rule.fetch === "sfetch" && (!ssr || rule.ssr === false))
|
|
289
|
+
throw new Error(
|
|
290
|
+
`[noofpi] routeRules["${pattern}"].fetch "sfetch" only fetches on the server, so the route must be server-rendered`
|
|
291
|
+
);
|
|
292
|
+
}
|
|
293
|
+
if (rule.security !== void 0) {
|
|
294
|
+
if (typeof rule.security !== "object" || rule.security === null)
|
|
295
|
+
throw new Error(
|
|
296
|
+
`[noofpi] routeRules["${pattern}"].security must be an object`
|
|
297
|
+
);
|
|
298
|
+
try {
|
|
299
|
+
applyRouteSecurity(void 0, rule.security);
|
|
300
|
+
} catch (error) {
|
|
301
|
+
throw new Error(
|
|
302
|
+
`[noofpi] routeRules["${pattern}"]: ${error.message.replace("[noofpi] ", "")}`
|
|
303
|
+
);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
function matchRouteRules(rules, pathname) {
|
|
309
|
+
const merged = {};
|
|
310
|
+
Object.keys(rules).filter((pattern) => patternToRegExp(pattern).test(pathname)).sort((a, b) => a.length - b.length).forEach((pattern) => {
|
|
311
|
+
const { security, ...rest } = rules[pattern];
|
|
312
|
+
Object.assign(merged, rest);
|
|
313
|
+
if (security) merged.security = { ...merged.security, ...security };
|
|
314
|
+
});
|
|
315
|
+
return merged;
|
|
316
|
+
}
|
|
317
|
+
function toPublicRouteRules(rules) {
|
|
318
|
+
return Object.fromEntries(
|
|
319
|
+
Object.entries(rules).map(([pattern, { security: _security, ...rule }]) => [
|
|
320
|
+
pattern,
|
|
321
|
+
rule
|
|
322
|
+
])
|
|
323
|
+
);
|
|
324
|
+
}
|
|
325
|
+
function resolveFetchMode(defaultMode, rules, pathname) {
|
|
326
|
+
return rules && matchRouteRules(rules, pathname).fetch || defaultMode;
|
|
327
|
+
}
|
|
328
|
+
function usesFetchMode(defaultMode, rules, mode) {
|
|
329
|
+
return defaultMode === mode || Object.values(rules ?? {}).some((rule) => rule.fetch === mode);
|
|
330
|
+
}
|
|
331
|
+
function isServerRendered(ssr, rules, pathname) {
|
|
332
|
+
return ssr && (!rules || matchRouteRules(rules, pathname).ssr !== false);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
export {
|
|
336
|
+
FETCH_MODES,
|
|
337
|
+
usesNonce,
|
|
338
|
+
generateNonce,
|
|
339
|
+
buildCspHeader,
|
|
340
|
+
injectNonce,
|
|
341
|
+
resolveSecurity,
|
|
342
|
+
applyRouteSecurity,
|
|
343
|
+
isAllowedHost,
|
|
344
|
+
limitRequestBody,
|
|
345
|
+
isCrossSiteWrite,
|
|
346
|
+
applySecurityHeaders,
|
|
347
|
+
validateRouteRules,
|
|
348
|
+
matchRouteRules,
|
|
349
|
+
toPublicRouteRules,
|
|
350
|
+
resolveFetchMode,
|
|
351
|
+
usesFetchMode,
|
|
352
|
+
isServerRendered
|
|
353
|
+
};
|