@weft-framework/server 0.0.0-stage → 0.0.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/LICENSE +21 -0
- package/README.md +4 -2
- package/dist/account.d.ts +124 -0
- package/dist/account.js +344 -0
- package/dist/action.d.ts +43 -0
- package/dist/action.js +135 -0
- package/dist/admin.d.ts +99 -0
- package/dist/admin.js +431 -0
- package/dist/api.d.ts +21 -0
- package/dist/api.js +72 -0
- package/dist/app.d.ts +202 -0
- package/dist/app.js +3692 -0
- package/dist/assets.d.ts +4 -0
- package/dist/assets.js +91 -0
- package/dist/auth.d.ts +150 -0
- package/dist/auth.js +215 -0
- package/dist/backup.d.ts +46 -0
- package/dist/backup.js +345 -0
- package/dist/build.d.ts +33 -0
- package/dist/build.js +274 -0
- package/dist/bun.d.ts +30 -0
- package/dist/bun.js +53 -0
- package/dist/calendar.d.ts +161 -0
- package/dist/calendar.js +690 -0
- package/dist/compiler.d.ts +13 -0
- package/dist/compiler.js +58 -0
- package/dist/compress.d.ts +6 -0
- package/dist/compress.js +78 -0
- package/dist/config.d.ts +26 -0
- package/dist/config.js +317 -0
- package/dist/context.d.ts +9 -0
- package/dist/context.js +1 -0
- package/dist/contract.d.ts +18 -0
- package/dist/contract.js +171 -0
- package/dist/datamap.d.ts +24 -0
- package/dist/datamap.js +365 -0
- package/dist/db-backup.d.ts +27 -0
- package/dist/db-backup.js +115 -0
- package/dist/dev-events.d.ts +14 -0
- package/dist/dev-events.js +135 -0
- package/dist/dev.d.ts +1 -0
- package/dist/dev.js +240 -0
- package/dist/devtools-client.d.ts +1 -0
- package/dist/devtools-client.js +362 -0
- package/dist/devtools.d.ts +87 -0
- package/dist/devtools.js +68 -0
- package/dist/edge.d.ts +3 -0
- package/dist/edge.js +7 -0
- package/dist/email-signin.d.ts +92 -0
- package/dist/email-signin.js +259 -0
- package/dist/env.d.ts +1 -0
- package/dist/env.js +15 -0
- package/dist/explain.d.ts +12 -0
- package/dist/explain.js +217 -0
- package/dist/files.d.ts +6 -0
- package/dist/files.js +170 -0
- package/dist/grants.d.ts +69 -0
- package/dist/grants.js +206 -0
- package/dist/image/bitmap.d.ts +11 -0
- package/dist/image/bitmap.js +172 -0
- package/dist/image/jpeg.d.ts +10 -0
- package/dist/image/jpeg.js +697 -0
- package/dist/image/png.d.ts +8 -0
- package/dist/image/png.js +282 -0
- package/dist/image/transform.d.ts +20 -0
- package/dist/image/transform.js +52 -0
- package/dist/image/worker.d.ts +1 -0
- package/dist/image/worker.js +11 -0
- package/dist/images.d.ts +39 -0
- package/dist/images.js +283 -0
- package/dist/index.d.ts +64 -0
- package/dist/index.js +31 -0
- package/dist/inspect-hub.d.ts +42 -0
- package/dist/inspect-hub.js +14 -0
- package/dist/inspector.d.ts +51 -0
- package/dist/inspector.js +193 -0
- package/dist/job-admin.d.ts +55 -0
- package/dist/job-admin.js +89 -0
- package/dist/jobs.d.ts +222 -0
- package/dist/jobs.js +789 -0
- package/dist/live.d.ts +72 -0
- package/dist/live.js +481 -0
- package/dist/load-config.d.ts +2 -0
- package/dist/load-config.js +41 -0
- package/dist/log.d.ts +20 -0
- package/dist/log.js +143 -0
- package/dist/mail.d.ts +189 -0
- package/dist/mail.js +999 -0
- package/dist/media.d.ts +129 -0
- package/dist/media.js +470 -0
- package/dist/meta.d.ts +54 -0
- package/dist/meta.js +146 -0
- package/dist/middleware.d.ts +20 -0
- package/dist/middleware.js +101 -0
- package/dist/migrate.d.ts +12 -0
- package/dist/migrate.js +88 -0
- package/dist/node.d.ts +26 -0
- package/dist/node.js +96 -0
- package/dist/notice.d.ts +21 -0
- package/dist/notice.js +48 -0
- package/dist/npm.d.ts +16 -0
- package/dist/npm.js +347 -0
- package/dist/oauth.d.ts +76 -0
- package/dist/oauth.js +408 -0
- package/dist/otel.d.ts +57 -0
- package/dist/otel.js +293 -0
- package/dist/passkey.d.ts +99 -0
- package/dist/passkey.js +572 -0
- package/dist/password.d.ts +8 -0
- package/dist/password.js +65 -0
- package/dist/pdf.d.ts +46 -0
- package/dist/pdf.js +332 -0
- package/dist/personal-data.d.ts +22 -0
- package/dist/personal-data.js +148 -0
- package/dist/pointers.d.ts +9 -0
- package/dist/pointers.js +148 -0
- package/dist/postcss.d.ts +3 -0
- package/dist/postcss.js +89 -0
- package/dist/presence.d.ts +27 -0
- package/dist/presence.js +161 -0
- package/dist/preview.d.ts +25 -0
- package/dist/preview.js +353 -0
- package/dist/production.d.ts +16 -0
- package/dist/production.js +119 -0
- package/dist/project.d.ts +23 -0
- package/dist/project.js +536 -0
- package/dist/regions.d.ts +47 -0
- package/dist/regions.js +511 -0
- package/dist/replay.d.ts +44 -0
- package/dist/replay.js +259 -0
- package/dist/router.d.ts +29 -0
- package/dist/router.js +146 -0
- package/dist/rules-diff.d.ts +18 -0
- package/dist/rules-diff.js +165 -0
- package/dist/rules-test.d.ts +17 -0
- package/dist/rules-test.js +108 -0
- package/dist/saml.d.ts +160 -0
- package/dist/saml.js +959 -0
- package/dist/seal.d.ts +35 -0
- package/dist/seal.js +107 -0
- package/dist/secret.d.ts +14 -0
- package/dist/secret.js +110 -0
- package/dist/security.d.ts +53 -0
- package/dist/security.js +250 -0
- package/dist/seed.d.ts +16 -0
- package/dist/seed.js +94 -0
- package/dist/seo.d.ts +42 -0
- package/dist/seo.js +175 -0
- package/dist/settings.d.ts +79 -0
- package/dist/settings.js +212 -0
- package/dist/shared.d.ts +15 -0
- package/dist/shared.js +283 -0
- package/dist/shell.d.ts +12 -0
- package/dist/shell.js +118 -0
- package/dist/storage.d.ts +13 -0
- package/dist/storage.js +55 -0
- package/dist/support.d.ts +83 -0
- package/dist/support.js +236 -0
- package/dist/sync.d.ts +35 -0
- package/dist/sync.js +167 -0
- package/dist/tailwind.d.ts +14 -0
- package/dist/tailwind.js +117 -0
- package/dist/two-factor.d.ts +103 -0
- package/dist/two-factor.js +435 -0
- package/dist/uploads.d.ts +185 -0
- package/dist/uploads.js +991 -0
- package/dist/webhooks.d.ts +169 -0
- package/dist/webhooks.js +758 -0
- package/dist/webpush.d.ts +97 -0
- package/dist/webpush.js +372 -0
- package/dist/wizard.d.ts +141 -0
- package/dist/wizard.js +410 -0
- package/dist/workflows.d.ts +134 -0
- package/dist/workflows.js +511 -0
- package/package.json +186 -4
package/dist/app.js
ADDED
|
@@ -0,0 +1,3692 @@
|
|
|
1
|
+
import { LIMITS, META_END, META_START, allStyles, decodeClientMessage, defineComponent, encode, escapeAttr, escapeHtml, isSafePath, isHandoff, HANDOFF_MAX, PROTOCOL_VERSION, HELD_FIELD, setComponentStyles, trustHtml, } from "@weft-framework/runtime";
|
|
2
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
3
|
+
import { audit, changes, onReadDone, readOnlyActor, tenantOf } from "@weft-framework/data";
|
|
4
|
+
import { actorLabel, decision, describe, devLog, frame, frameList, note, readsOf } from "./devtools.js";
|
|
5
|
+
import { RECORDING_MAX, outcomeOf, redactPath, redactPayload } from "./replay.js";
|
|
6
|
+
import { addInspectHub, sessionKey } from "./inspect-hub.js";
|
|
7
|
+
import { allowHeader, guardApiResponse, handlerFor, isApiMethod, isExternal, isUnsafeMethod } from "./api.js";
|
|
8
|
+
import { isSiteUrl } from "./config.js";
|
|
9
|
+
import { attachAuth, logout, MemorySessionStore, noteViewing, runsWhileViewing, signInWith, viewingAs, } from "./auth.js";
|
|
10
|
+
import { identityFor as emailIdentity } from "./email-signin.js";
|
|
11
|
+
import { pkceChallenge, SignInError } from "./oauth.js";
|
|
12
|
+
import { attachSeal, openWith, sealWith } from "./seal.js";
|
|
13
|
+
import { compress } from "./compress.js";
|
|
14
|
+
import { ActionError, decodeForm, decodeJson, heldCount } from "./action.js";
|
|
15
|
+
import { createHash, createHmac } from "node:crypto";
|
|
16
|
+
import { LivePage, Redirect } from "./live.js";
|
|
17
|
+
import { applySite, mergeMeta, renderMeta, resolveLang, resolveTitle } from "./meta.js";
|
|
18
|
+
import { copyHeaders, runMiddleware, withExtraHeaders } from "./middleware.js";
|
|
19
|
+
import { checkSitemapOptions, robotsTxt, sitemapEntries, sitemapXml } from "./seo.js";
|
|
20
|
+
import { Router } from "./router.js";
|
|
21
|
+
import { assignRequestId, requestIdOf } from "./log.js";
|
|
22
|
+
import { RegionWriteError } from "./regions.js";
|
|
23
|
+
import { htmlAttributeMarkup, parseShell } from "./shell.js";
|
|
24
|
+
import { addNoticeHub } from "./notice.js";
|
|
25
|
+
import { sharedChange, sharedLeave, sharedMessage } from "./shared.js";
|
|
26
|
+
import { pointLeave, pointMessage } from "./pointers.js";
|
|
27
|
+
import { currentSession, DepsIndex, onStoreWrite, track, withSession } from "./sync.js";
|
|
28
|
+
import { presenceAway, presenceBegin, presenceEnd, presenceHeld, presenceRelease, presenceStartAway } from "./presence.js";
|
|
29
|
+
import { base64url, fromBase64url, MIN_SECRET_LENGTH, RateLimiter, csrfToken, importSecret, parseCookies, randomId, sameOrigin, securityHeaders, checkCspSources, mergeCspSources, sessionCookie, signSession, timingSafeEqual, verifyCsrf, verifySession, } from "./security.js";
|
|
30
|
+
import { checkPdfRoute, pdfFilename } from "./pdf.js";
|
|
31
|
+
import { IMAGES_PATH } from "./images.js";
|
|
32
|
+
const STYLES = "/_weft/styles.css";
|
|
33
|
+
const APP_CSS = "/_weft/app.css";
|
|
34
|
+
function contentVersion(text) {
|
|
35
|
+
let h = 0x811c9dc5;
|
|
36
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
37
|
+
h ^= text.charCodeAt(i);
|
|
38
|
+
h = Math.imul(h, 0x01000193) >>> 0;
|
|
39
|
+
}
|
|
40
|
+
return h.toString(36);
|
|
41
|
+
}
|
|
42
|
+
let bundleCache = null;
|
|
43
|
+
function styleBundle() {
|
|
44
|
+
const css = allStyles();
|
|
45
|
+
if (!css) {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
if (bundleCache?.css !== css) {
|
|
49
|
+
bundleCache = { css, version: contentVersion(css) };
|
|
50
|
+
}
|
|
51
|
+
return bundleCache;
|
|
52
|
+
}
|
|
53
|
+
export class NotFound {
|
|
54
|
+
notFound = true;
|
|
55
|
+
}
|
|
56
|
+
export function notFound() {
|
|
57
|
+
return new NotFound();
|
|
58
|
+
}
|
|
59
|
+
const isComponent = (v) => typeof v === "function" && "def" in v;
|
|
60
|
+
export function checkOg(raw, where) {
|
|
61
|
+
if (isComponent(raw))
|
|
62
|
+
return raw;
|
|
63
|
+
const o = raw;
|
|
64
|
+
const size = (n) => n === undefined || (Number.isInteger(n) && n >= 200 && n <= 2400);
|
|
65
|
+
if (typeof o !== "object" || o === null || !isComponent(o.component) || !size(o.width) || !size(o.height) ||
|
|
66
|
+
Object.keys(o).some((k) => k !== "component" && k !== "width" && k !== "height")) {
|
|
67
|
+
throw new TypeError(`${where}: og is a component, or { component, width, height } with sizes 200-2400`);
|
|
68
|
+
}
|
|
69
|
+
return o;
|
|
70
|
+
}
|
|
71
|
+
export function edgeReason(route, app) {
|
|
72
|
+
if (route.edge === false)
|
|
73
|
+
return "edge: false";
|
|
74
|
+
if (route.load)
|
|
75
|
+
return "load";
|
|
76
|
+
if (typeof route.meta === "function" || route.layouts?.some((l) => typeof l.meta === "function"))
|
|
77
|
+
return "meta from the request";
|
|
78
|
+
if (route.cache === "etag")
|
|
79
|
+
return 'cache: "etag"';
|
|
80
|
+
if (route.status !== undefined && route.status !== 200)
|
|
81
|
+
return `status ${route.status}`;
|
|
82
|
+
if (route.edge !== true) {
|
|
83
|
+
const mw = app.middleware;
|
|
84
|
+
if (Array.isArray(mw) ? mw.length > 0 : mw !== undefined)
|
|
85
|
+
return "middleware (the page may export `edge = true`)";
|
|
86
|
+
if (app.htmlAttributes !== undefined)
|
|
87
|
+
return "htmlAttributes (the page may export `edge = true`)";
|
|
88
|
+
}
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
const POSTS = /\/_weft\/action\/|<form\b[^>]*\bmethod\s*=\s*["']?post\b/i;
|
|
92
|
+
function hashInline(html, nonce) {
|
|
93
|
+
const attr = ` nonce="${escapeAttr(nonce)}"`;
|
|
94
|
+
const script = new Set();
|
|
95
|
+
const style = new Set();
|
|
96
|
+
let ok = true;
|
|
97
|
+
const out = html.replace(/<(script|style)\b([^>]*)>([\s\S]*?)<\/\1\s*>/gi, (m, tag, attrs, body) => {
|
|
98
|
+
if (!attrs.includes(attr))
|
|
99
|
+
return m;
|
|
100
|
+
const rest = attrs.split(attr).join("");
|
|
101
|
+
if (/\bsrc\s*=/i.test(rest))
|
|
102
|
+
ok = false;
|
|
103
|
+
(tag.toLowerCase() === "script" ? script : style).add(`'sha256-${createHash("sha256").update(body).digest("base64")}'`);
|
|
104
|
+
return `<${tag}${rest}>${body}</${tag}>`;
|
|
105
|
+
});
|
|
106
|
+
return ok && !out.includes(nonce) ? { html: out, script: [...script], style: [...style] } : null;
|
|
107
|
+
}
|
|
108
|
+
const READ_SPANS = 100;
|
|
109
|
+
function jsonBytes(v) {
|
|
110
|
+
try {
|
|
111
|
+
return (JSON.stringify(v)?.length ?? 0) * 2;
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
return 0;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
function charge(e, kind, ms, outs) {
|
|
118
|
+
if (!e.cost)
|
|
119
|
+
return;
|
|
120
|
+
e.cost[kind]++;
|
|
121
|
+
e.cost.ms += ms;
|
|
122
|
+
for (const o of outs)
|
|
123
|
+
e.cost.bytes += enc.encode(JSON.stringify(o)).length;
|
|
124
|
+
}
|
|
125
|
+
function because(e, cause) {
|
|
126
|
+
if (!e.dev)
|
|
127
|
+
return;
|
|
128
|
+
const why = (e.why ??= []);
|
|
129
|
+
if (why.length < 5) {
|
|
130
|
+
if (!why.includes(cause))
|
|
131
|
+
why.push(cause);
|
|
132
|
+
}
|
|
133
|
+
else if (why.length === 5) {
|
|
134
|
+
why.push("and more");
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
function changeCause(change, part) {
|
|
138
|
+
let key;
|
|
139
|
+
try {
|
|
140
|
+
key = JSON.stringify(change.key) ?? String(change.key);
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
key = String(change.key);
|
|
144
|
+
}
|
|
145
|
+
if (key.length > 40)
|
|
146
|
+
key = key.slice(0, 39) + "…";
|
|
147
|
+
return `${change.op} ${change.model} ${key} (read in ${part})`;
|
|
148
|
+
}
|
|
149
|
+
const LIVE = "/_weft/live";
|
|
150
|
+
const ACTION = "/_weft/action/";
|
|
151
|
+
const SESSION = "/_weft/session";
|
|
152
|
+
const HEALTH = "/_weft/health";
|
|
153
|
+
const SITEMAP = "/sitemap.xml";
|
|
154
|
+
const ROBOTS = "/robots.txt";
|
|
155
|
+
const READY = "/_weft/ready";
|
|
156
|
+
const AUTH = "/_weft/auth/";
|
|
157
|
+
const DEV_VIEW_AS = "/_weft/dev/view-as";
|
|
158
|
+
const DEV_VIEW_MS = 3600_000;
|
|
159
|
+
const DEV_INSPECT = "/_weft/dev/inspect";
|
|
160
|
+
const DEV_FRAME = "/_weft/dev/frame";
|
|
161
|
+
const DEV_RECORDING = "/_weft/dev/recording";
|
|
162
|
+
const enc = new TextEncoder();
|
|
163
|
+
export function createApp(opts) {
|
|
164
|
+
if (typeof opts.secret !== "string" || opts.secret.length < MIN_SECRET_LENGTH) {
|
|
165
|
+
throw new Error(`@weft-framework/server: the secret must be at least ${MIN_SECRET_LENGTH} characters of random data`);
|
|
166
|
+
}
|
|
167
|
+
if (opts.siteUrl !== undefined && !isSiteUrl(opts.siteUrl)) {
|
|
168
|
+
throw new Error("@weft-framework/server: siteUrl must be an http(s) origin");
|
|
169
|
+
}
|
|
170
|
+
const keyP = importSecret(opts.secret);
|
|
171
|
+
const handoffKeyP = crypto.subtle
|
|
172
|
+
.digest("SHA-256", new TextEncoder().encode(`weft-handoff\0${opts.secret}`))
|
|
173
|
+
.then((raw) => crypto.subtle.importKey("raw", raw, "AES-GCM", false, ["encrypt", "decrypt"]));
|
|
174
|
+
const now = opts.now ?? Date.now;
|
|
175
|
+
const ttl = opts.pageTtlMs ?? 30 * 60_000;
|
|
176
|
+
const maxPages = opts.maxPages ?? 10_000;
|
|
177
|
+
const maxPerSession = opts.maxPagesPerSession ?? 32;
|
|
178
|
+
const degrade = opts.degrade;
|
|
179
|
+
if (degrade !== undefined) {
|
|
180
|
+
const { pages: p, heapBytes: h } = degrade;
|
|
181
|
+
if (p !== undefined && (!Number.isInteger(p) || p < 1))
|
|
182
|
+
throw new Error("@weft-framework/server: degrade.pages is a positive integer");
|
|
183
|
+
if (h !== undefined && (!Number.isFinite(h) || h < 16 * 1024 * 1024))
|
|
184
|
+
throw new Error("@weft-framework/server: degrade.heapBytes is at least 16 MiB");
|
|
185
|
+
}
|
|
186
|
+
let heap = { at: -Infinity, bytes: null };
|
|
187
|
+
const heapUsed = () => {
|
|
188
|
+
const t = now();
|
|
189
|
+
if (t - heap.at >= 1000) {
|
|
190
|
+
const mem = globalThis.process?.memoryUsage;
|
|
191
|
+
heap = { at: t, bytes: typeof mem === "function" ? mem().heapUsed : null };
|
|
192
|
+
}
|
|
193
|
+
return heap.bytes;
|
|
194
|
+
};
|
|
195
|
+
const degradedAt = new Map();
|
|
196
|
+
function overloaded(route) {
|
|
197
|
+
if (degrade === undefined)
|
|
198
|
+
return false;
|
|
199
|
+
let reason = null;
|
|
200
|
+
if (degrade.pages !== undefined && pages.size >= degrade.pages)
|
|
201
|
+
reason = "pages";
|
|
202
|
+
const bytes = degrade.heapBytes === undefined ? null : heapUsed();
|
|
203
|
+
if (reason === null && bytes !== null && bytes > degrade.heapBytes)
|
|
204
|
+
reason = "memory";
|
|
205
|
+
if (reason === null)
|
|
206
|
+
return false;
|
|
207
|
+
const pattern = patternOf.get(route) ?? "unknown";
|
|
208
|
+
const k = `${pattern} ${reason}`;
|
|
209
|
+
const t = now();
|
|
210
|
+
if (degrade.onDegrade && (degradedAt.get(k) ?? -Infinity) <= t - 60_000) {
|
|
211
|
+
if (degradedAt.size >= 1000)
|
|
212
|
+
degradedAt.clear();
|
|
213
|
+
degradedAt.set(k, t);
|
|
214
|
+
try {
|
|
215
|
+
degrade.onDegrade({ route: pattern, reason, pages: pages.size, heapBytes: bytes });
|
|
216
|
+
}
|
|
217
|
+
catch (err) {
|
|
218
|
+
onError(err);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
return true;
|
|
222
|
+
}
|
|
223
|
+
const heartbeatMs = opts.heartbeatMs ?? 25_000;
|
|
224
|
+
const limiter = new RateLimiter(opts.rateLimit ?? { capacity: 30, refillPerSecond: 10 });
|
|
225
|
+
const apiLimiter = new RateLimiter(opts.rateLimit ?? { capacity: 60, refillPerSecond: 20 });
|
|
226
|
+
const prefetchLimiter = new RateLimiter({ capacity: 8, refillPerSecond: 2 });
|
|
227
|
+
const logger = opts.logger;
|
|
228
|
+
const onError = opts.onError ?? (logger ? (err) => logger.error("unhandled error", { error: err }) : (err) => console.error("[weft]", err));
|
|
229
|
+
const patchBudget = opts.patchBudget === undefined ? (opts.devtools ? 64 * 1024 : false) : opts.patchBudget;
|
|
230
|
+
if (patchBudget !== false && (!Number.isInteger(patchBudget) || patchBudget < 1024)) {
|
|
231
|
+
throw new Error("createApp: patchBudget is a whole number of bytes, at least 1024, or false");
|
|
232
|
+
}
|
|
233
|
+
const onPatchBudget = opts.onPatchBudget ??
|
|
234
|
+
((o) => {
|
|
235
|
+
const text = `patch budget: ${o.cause} on ${o.route} sent ${o.bytes} bytes (budget ${o.budget})`;
|
|
236
|
+
const top = o.components.map((c) => `${c.name} ${c.bytes}`).join(", ");
|
|
237
|
+
if (logger)
|
|
238
|
+
logger.warn(text, { components: top });
|
|
239
|
+
else
|
|
240
|
+
console.warn(`[weft] ${text}: ${top}`);
|
|
241
|
+
});
|
|
242
|
+
const budgetSeen = new Map();
|
|
243
|
+
const checkBudget = (e, cause, outs) => {
|
|
244
|
+
if (patchBudget === false)
|
|
245
|
+
return;
|
|
246
|
+
let bytes = 0;
|
|
247
|
+
const by = new Map();
|
|
248
|
+
for (const o of outs) {
|
|
249
|
+
if (o.t !== "patch")
|
|
250
|
+
continue;
|
|
251
|
+
const n = enc.encode(o.html).length;
|
|
252
|
+
bytes += n;
|
|
253
|
+
const name = e.page.componentOf(o.id) ?? "unknown";
|
|
254
|
+
by.set(name, (by.get(name) ?? 0) + n);
|
|
255
|
+
}
|
|
256
|
+
if (bytes <= patchBudget)
|
|
257
|
+
return;
|
|
258
|
+
const components = [...by].map(([name, n]) => ({ name, bytes: n })).sort((a, b) => b.bytes - a.bytes);
|
|
259
|
+
const route = patternOf.get(e.route) ?? "unknown";
|
|
260
|
+
const key = `${route}\0${cause}\0${components[0].name}`;
|
|
261
|
+
const at = Date.now();
|
|
262
|
+
if ((budgetSeen.get(key) ?? -Infinity) > at - 60_000)
|
|
263
|
+
return;
|
|
264
|
+
budgetSeen.delete(key);
|
|
265
|
+
if (budgetSeen.size >= 1000)
|
|
266
|
+
budgetSeen.delete(budgetSeen.keys().next().value);
|
|
267
|
+
budgetSeen.set(key, at);
|
|
268
|
+
if (e.dev) {
|
|
269
|
+
const what = `patch budget: ${cause} sent ${bytes} bytes, budget ${patchBudget}`;
|
|
270
|
+
note(e.dev.messages, { at, dir: "warn", what, out: components.map((c) => `${c.name} ${c.bytes} B`) });
|
|
271
|
+
}
|
|
272
|
+
try {
|
|
273
|
+
onPatchBudget({ route, cause, bytes, budget: patchBudget, components });
|
|
274
|
+
}
|
|
275
|
+
catch (err) {
|
|
276
|
+
onError(err);
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
const untrackFiles = opts.uploads?.track(onError);
|
|
280
|
+
const pages = new Map();
|
|
281
|
+
const readers = new DepsIndex();
|
|
282
|
+
const ETAG_TTL = 60 * 60_000;
|
|
283
|
+
const ETAG_MAX = 10_000;
|
|
284
|
+
const cacheReaders = new DepsIndex();
|
|
285
|
+
const etags = new Map();
|
|
286
|
+
const uncachable = new Set();
|
|
287
|
+
const purge = (r) => {
|
|
288
|
+
if (etags.get(r.key) === r)
|
|
289
|
+
etags.delete(r.key);
|
|
290
|
+
r.deps.load.release();
|
|
291
|
+
r.deps.render.release();
|
|
292
|
+
};
|
|
293
|
+
const etagKey = (req, url, sid) => createHash("sha256")
|
|
294
|
+
.update(`${sid}\0${url.pathname}${url.search}\0${req.headers.get("accept-language") ?? ""}\0${req.headers.get("cookie") ?? ""}`)
|
|
295
|
+
.digest("base64url");
|
|
296
|
+
const matchesTag = (header, tag) => header !== null && header.split(",").some((t) => t.trim().replace(/^W\//, "") === `"${tag}"`);
|
|
297
|
+
const streams = new Map();
|
|
298
|
+
function touch(lid, e) {
|
|
299
|
+
e.seen = now();
|
|
300
|
+
pages.delete(lid);
|
|
301
|
+
pages.set(lid, e);
|
|
302
|
+
}
|
|
303
|
+
let draining = false;
|
|
304
|
+
let inFlight = 0;
|
|
305
|
+
if (opts.sitemap) {
|
|
306
|
+
if (!opts.siteUrl)
|
|
307
|
+
throw new Error("createApp: sitemap needs siteUrl, the origin its URLs are on");
|
|
308
|
+
checkSitemapOptions(opts.sitemap);
|
|
309
|
+
}
|
|
310
|
+
const robots = opts.robots
|
|
311
|
+
? robotsTxt(opts.robots, opts.sitemap ? new URL(SITEMAP, opts.siteUrl).href : undefined)
|
|
312
|
+
: null;
|
|
313
|
+
async function seoRequest(req, path) {
|
|
314
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
315
|
+
return new Response(null, { status: 405, headers: { allow: "GET, HEAD" } });
|
|
316
|
+
}
|
|
317
|
+
let body;
|
|
318
|
+
let type;
|
|
319
|
+
if (path === ROBOTS) {
|
|
320
|
+
body = robots;
|
|
321
|
+
type = "text/plain; charset=utf-8";
|
|
322
|
+
}
|
|
323
|
+
else {
|
|
324
|
+
try {
|
|
325
|
+
const list = Object.entries(opts.routes).map(([pattern, r]) => ({ pattern, meta: r.meta }));
|
|
326
|
+
body = sitemapXml(await sitemapEntries(opts.siteUrl, list, opts.sitemap));
|
|
327
|
+
}
|
|
328
|
+
catch (err) {
|
|
329
|
+
onError(err);
|
|
330
|
+
return status(500);
|
|
331
|
+
}
|
|
332
|
+
type = "application/xml; charset=utf-8";
|
|
333
|
+
}
|
|
334
|
+
return new Response(req.method === "HEAD" ? null : body, {
|
|
335
|
+
headers: {
|
|
336
|
+
"content-type": type,
|
|
337
|
+
"cache-control": `public, max-age=${opts.sitemap?.maxAge ?? 3600}`,
|
|
338
|
+
"x-content-type-options": "nosniff",
|
|
339
|
+
},
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
const readyChecks = Object.entries(opts.ready ?? {});
|
|
343
|
+
for (const [name, check] of readyChecks) {
|
|
344
|
+
if (typeof check !== "function")
|
|
345
|
+
throw new Error(`createApp: ready check ${JSON.stringify(name)} is a function`);
|
|
346
|
+
}
|
|
347
|
+
const readyTimeoutMs = opts.readyTimeoutMs ?? 2000;
|
|
348
|
+
if (!Number.isFinite(readyTimeoutMs) || readyTimeoutMs < 1 || readyTimeoutMs > 60_000) {
|
|
349
|
+
throw new Error("createApp: readyTimeoutMs is 1 to 60 000");
|
|
350
|
+
}
|
|
351
|
+
async function readyNow() {
|
|
352
|
+
const results = await Promise.all(readyChecks.map(async ([name, check]) => {
|
|
353
|
+
let timer;
|
|
354
|
+
try {
|
|
355
|
+
const timeout = new Promise((_, reject) => {
|
|
356
|
+
timer = setTimeout(() => reject(new Error(`timed out after ${readyTimeoutMs} ms`)), readyTimeoutMs);
|
|
357
|
+
});
|
|
358
|
+
const value = await Promise.race([Promise.resolve().then(check), timeout]);
|
|
359
|
+
if (value === false)
|
|
360
|
+
throw new Error("returned false");
|
|
361
|
+
return true;
|
|
362
|
+
}
|
|
363
|
+
catch (err) {
|
|
364
|
+
onError(new Error(`ready check ${JSON.stringify(name)} failed: ${err?.message ?? String(err)}`, { cause: err }));
|
|
365
|
+
return false;
|
|
366
|
+
}
|
|
367
|
+
finally {
|
|
368
|
+
clearTimeout(timer);
|
|
369
|
+
}
|
|
370
|
+
}));
|
|
371
|
+
return results.every(Boolean);
|
|
372
|
+
}
|
|
373
|
+
const HELD_TTL = 24 * 60 * 60_000;
|
|
374
|
+
const HELD_MAX = 4096;
|
|
375
|
+
const heldKey = createHash("sha256").update("weft-held\0").update(opts.secret).digest();
|
|
376
|
+
const heldMac = (sid, body) => createHmac("sha256", heldKey).update(`${sid}\0${body}`).digest("base64url");
|
|
377
|
+
function sealHeld(sid, action, args) {
|
|
378
|
+
const body = Buffer.from(JSON.stringify([action, now() + HELD_TTL, args])).toString("base64url");
|
|
379
|
+
const token = `${body}.${heldMac(sid, body)}`;
|
|
380
|
+
if (token.length > HELD_MAX)
|
|
381
|
+
throw new Error(`@weft-framework/server: ${action}.with(..): the held values are too large`);
|
|
382
|
+
return token;
|
|
383
|
+
}
|
|
384
|
+
function openHeld(sid, action, token) {
|
|
385
|
+
if (typeof token !== "string" || token.length > HELD_MAX)
|
|
386
|
+
return null;
|
|
387
|
+
const dot = token.indexOf(".");
|
|
388
|
+
if (dot <= 0)
|
|
389
|
+
return null;
|
|
390
|
+
const body = token.slice(0, dot);
|
|
391
|
+
if (!timingSafeEqual(token.slice(dot + 1), heldMac(sid, body)))
|
|
392
|
+
return null;
|
|
393
|
+
try {
|
|
394
|
+
const v = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
|
|
395
|
+
if (!Array.isArray(v) || v.length !== 3 || v[0] !== action || typeof v[1] !== "number" || !Array.isArray(v[2]))
|
|
396
|
+
return null;
|
|
397
|
+
return v[1] > now() ? v[2] : null;
|
|
398
|
+
}
|
|
399
|
+
catch {
|
|
400
|
+
return null;
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
const HANDOFF_TTL = 5 * 60_000;
|
|
404
|
+
const handoffBinding = (sid, url) => new TextEncoder().encode(`weft-handoff\0${sid}\0${url.pathname}${url.search}`);
|
|
405
|
+
async function sealHandoff(e) {
|
|
406
|
+
let state;
|
|
407
|
+
try {
|
|
408
|
+
state = e.page.snapshot();
|
|
409
|
+
}
|
|
410
|
+
catch {
|
|
411
|
+
return null;
|
|
412
|
+
}
|
|
413
|
+
if (state.length === 0)
|
|
414
|
+
return null;
|
|
415
|
+
const json = JSON.stringify({ at: now(), s: state });
|
|
416
|
+
if (json.length > HANDOFF_MAX)
|
|
417
|
+
return null;
|
|
418
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
419
|
+
const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: handoffBinding(e.sid, e.ctx.url) }, await handoffKeyP, new TextEncoder().encode(json)));
|
|
420
|
+
const out = new Uint8Array(iv.length + ct.length);
|
|
421
|
+
out.set(iv);
|
|
422
|
+
out.set(ct, iv.length);
|
|
423
|
+
const token = base64url(out);
|
|
424
|
+
return isHandoff(token) ? token : null;
|
|
425
|
+
}
|
|
426
|
+
async function openHandoff(token, sid, url) {
|
|
427
|
+
if (!isHandoff(token))
|
|
428
|
+
return null;
|
|
429
|
+
const bytes = fromBase64url(token);
|
|
430
|
+
if (!bytes || bytes.length < 12 + 16)
|
|
431
|
+
return null;
|
|
432
|
+
let text;
|
|
433
|
+
try {
|
|
434
|
+
const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: new Uint8Array(bytes.slice(0, 12)), additionalData: handoffBinding(sid, url) }, await handoffKeyP, new Uint8Array(bytes.slice(12)));
|
|
435
|
+
text = new TextDecoder().decode(plain);
|
|
436
|
+
}
|
|
437
|
+
catch {
|
|
438
|
+
return null;
|
|
439
|
+
}
|
|
440
|
+
let v;
|
|
441
|
+
try {
|
|
442
|
+
v = JSON.parse(text);
|
|
443
|
+
}
|
|
444
|
+
catch {
|
|
445
|
+
return null;
|
|
446
|
+
}
|
|
447
|
+
const o = v;
|
|
448
|
+
if (typeof o?.at !== "number" || !Array.isArray(o.s))
|
|
449
|
+
return null;
|
|
450
|
+
const t = now();
|
|
451
|
+
if (o.at > t + 60_000 || t - o.at > HANDOFF_TTL)
|
|
452
|
+
return null;
|
|
453
|
+
const ok = o.s.every((x) => Array.isArray(x) &&
|
|
454
|
+
x.length === 4 &&
|
|
455
|
+
typeof x[0] === "string" &&
|
|
456
|
+
typeof x[1] === "string" &&
|
|
457
|
+
Number.isInteger(x[2]) &&
|
|
458
|
+
Array.isArray(x[3]) &&
|
|
459
|
+
x[3].every((p) => Array.isArray(p) && p.length === 2 && Number.isInteger(p[0]) && p[0] >= 0));
|
|
460
|
+
return ok ? o.s : null;
|
|
461
|
+
}
|
|
462
|
+
function drop(lid, handoff) {
|
|
463
|
+
const e = pages.get(lid);
|
|
464
|
+
if (e?.timer) {
|
|
465
|
+
clearTimeout(e.timer);
|
|
466
|
+
}
|
|
467
|
+
pages.delete(lid);
|
|
468
|
+
if (e?.awayTimer)
|
|
469
|
+
clearTimeout(e.awayTimer);
|
|
470
|
+
if (e)
|
|
471
|
+
presenceRelease(e.ctx);
|
|
472
|
+
if (e)
|
|
473
|
+
sharedLeave(e);
|
|
474
|
+
if (e)
|
|
475
|
+
pointLeave(e);
|
|
476
|
+
e?.deps.load.release();
|
|
477
|
+
e?.deps.render.release();
|
|
478
|
+
for (const sink of e?.sinks ?? []) {
|
|
479
|
+
try {
|
|
480
|
+
sink(handoff ? { t: "expired", handoff } : { t: "expired" });
|
|
481
|
+
}
|
|
482
|
+
catch {
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
e?.sinks.clear();
|
|
486
|
+
e?.page.close();
|
|
487
|
+
}
|
|
488
|
+
function register(entry) {
|
|
489
|
+
const sid = entry.sid;
|
|
490
|
+
const t = now();
|
|
491
|
+
for (const [lid, e] of pages) {
|
|
492
|
+
if (t - e.seen <= ttl) {
|
|
493
|
+
break;
|
|
494
|
+
}
|
|
495
|
+
drop(lid);
|
|
496
|
+
}
|
|
497
|
+
let mine = 0;
|
|
498
|
+
for (const e of pages.values()) {
|
|
499
|
+
if (e.sid === sid) {
|
|
500
|
+
mine += 1;
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
if (mine >= maxPerSession) {
|
|
504
|
+
const victim = idleOldest(sid);
|
|
505
|
+
if (victim) {
|
|
506
|
+
drop(victim);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
if (pages.size >= maxPages) {
|
|
510
|
+
const victim = idleOldest(null);
|
|
511
|
+
if (victim) {
|
|
512
|
+
drop(victim);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
entry.seen = t;
|
|
516
|
+
pages.set(entry.page.id, entry);
|
|
517
|
+
entry.deps.load.adopt(entry);
|
|
518
|
+
entry.deps.render.adopt(entry);
|
|
519
|
+
live.add(entry.ctx);
|
|
520
|
+
watchAway(entry);
|
|
521
|
+
}
|
|
522
|
+
const live = new WeakSet();
|
|
523
|
+
const presenceGrace = opts.presenceGraceMs ?? 15_000;
|
|
524
|
+
const staleMode = opts.offline?.stale ?? "run";
|
|
525
|
+
if (staleMode !== "run" && staleMode !== "refuse")
|
|
526
|
+
throw new Error("offline.stale must be \"run\" or \"refuse\"");
|
|
527
|
+
function watchAway(e) {
|
|
528
|
+
if (e.sinks.size > 0 || e.awayTimer)
|
|
529
|
+
return;
|
|
530
|
+
e.awayTimer = setTimeout(() => {
|
|
531
|
+
e.awayTimer = null;
|
|
532
|
+
if (e.sinks.size === 0)
|
|
533
|
+
presenceAway(e.ctx, true);
|
|
534
|
+
}, presenceGrace);
|
|
535
|
+
e.awayTimer.unref?.();
|
|
536
|
+
}
|
|
537
|
+
function pageFor(lid, sid) {
|
|
538
|
+
if (!lid || !sid) {
|
|
539
|
+
return null;
|
|
540
|
+
}
|
|
541
|
+
const e = pages.get(lid);
|
|
542
|
+
if (!e || e.sid !== sid) {
|
|
543
|
+
return null;
|
|
544
|
+
}
|
|
545
|
+
if (now() - e.seen > ttl) {
|
|
546
|
+
drop(lid);
|
|
547
|
+
return null;
|
|
548
|
+
}
|
|
549
|
+
touch(lid, e);
|
|
550
|
+
return e;
|
|
551
|
+
}
|
|
552
|
+
const cookieName = opts.cookieName ?? "weft_sid";
|
|
553
|
+
const instance = opts.instance ?? randomId(6);
|
|
554
|
+
const patternOf = new Map();
|
|
555
|
+
for (const [pattern, r] of Object.entries(opts.routes))
|
|
556
|
+
patternOf.set(r, pattern);
|
|
557
|
+
for (const [pattern, h] of Object.entries(opts.api ?? {}))
|
|
558
|
+
patternOf.set(h, pattern);
|
|
559
|
+
const reported = new WeakSet();
|
|
560
|
+
const rethrown = new WeakSet();
|
|
561
|
+
const telemetry = opts.telemetry ?? null;
|
|
562
|
+
const traces = new WeakMap();
|
|
563
|
+
const routeOfReq = new WeakMap();
|
|
564
|
+
const qw = opts.queryWarnings === undefined ? (opts.devtools ? {} : false) : opts.queryWarnings;
|
|
565
|
+
const queryLimits = qw === false ? null : { repeat: qw.repeat ?? 10, rows: qw.rows ?? 5000 };
|
|
566
|
+
if (queryLimits &&
|
|
567
|
+
(!Number.isInteger(queryLimits.repeat) || queryLimits.repeat < 2 || !Number.isInteger(queryLimits.rows) || queryLimits.rows < 1)) {
|
|
568
|
+
throw new Error("createApp: queryWarnings.repeat is a whole number of at least 2, rows at least 1");
|
|
569
|
+
}
|
|
570
|
+
const onQueryWarning = opts.onQueryWarning ??
|
|
571
|
+
((w) => {
|
|
572
|
+
const text = w.kind === "repeat"
|
|
573
|
+
? `${w.cause} on ${w.route} read ${w.model} ${w.reads} times (an N+1? load the rows in one read)`
|
|
574
|
+
: `${w.cause} on ${w.route} read ${w.rows} rows of ${w.model}`;
|
|
575
|
+
if (logger)
|
|
576
|
+
logger.warn(`query warning: ${text}`, { model: w.model, reads: w.reads, rows: w.rows });
|
|
577
|
+
else
|
|
578
|
+
console.warn(`[weft] query warning: ${text}`);
|
|
579
|
+
});
|
|
580
|
+
const queryWarned = new Map();
|
|
581
|
+
const checkReads = (scope, route, cause, dev) => {
|
|
582
|
+
if (!queryLimits || !scope.models)
|
|
583
|
+
return;
|
|
584
|
+
for (const [model, t] of scope.models) {
|
|
585
|
+
const kinds = [];
|
|
586
|
+
if (t.reads >= queryLimits.repeat)
|
|
587
|
+
kinds.push("repeat");
|
|
588
|
+
if (t.rows >= queryLimits.rows)
|
|
589
|
+
kinds.push("rows");
|
|
590
|
+
for (const kind of kinds) {
|
|
591
|
+
const key = `${route}\0${cause}\0${model}\0${kind}`;
|
|
592
|
+
const at = Date.now();
|
|
593
|
+
if ((queryWarned.get(key) ?? -Infinity) > at - 60_000)
|
|
594
|
+
continue;
|
|
595
|
+
queryWarned.delete(key);
|
|
596
|
+
if (queryWarned.size >= 1000)
|
|
597
|
+
queryWarned.delete(queryWarned.keys().next().value);
|
|
598
|
+
queryWarned.set(key, at);
|
|
599
|
+
const w = { kind, route, cause, model, reads: t.reads, rows: t.rows };
|
|
600
|
+
if (dev) {
|
|
601
|
+
const what = kind === "repeat" ? `query warning: ${model} read ${t.reads} times` : `query warning: ${t.rows} rows of ${model}`;
|
|
602
|
+
note(dev.messages, { at, dir: "warn", what: `${what} (${cause})`, out: [] });
|
|
603
|
+
}
|
|
604
|
+
try {
|
|
605
|
+
onQueryWarning(w);
|
|
606
|
+
}
|
|
607
|
+
catch (err) {
|
|
608
|
+
onError(err);
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
};
|
|
613
|
+
const newScope = (trace) => readScope && (trace || queryLimits) ? { trace, open: true, reads: 0, models: queryLimits ? new Map() : null } : null;
|
|
614
|
+
const readScope = telemetry?.span || queryLimits ? new AsyncLocalStorage() : null;
|
|
615
|
+
const unReads = readScope
|
|
616
|
+
? onReadDone((r) => {
|
|
617
|
+
const scope = readScope.getStore();
|
|
618
|
+
if (!scope || !scope.open)
|
|
619
|
+
return;
|
|
620
|
+
if (scope.models) {
|
|
621
|
+
const t = scope.models.get(r.model) ?? { reads: 0, rows: 0 };
|
|
622
|
+
t.reads += 1;
|
|
623
|
+
t.rows += r.rows;
|
|
624
|
+
scope.models.set(r.model, t);
|
|
625
|
+
}
|
|
626
|
+
if (!scope.trace || !telemetry?.span || ++scope.reads > READ_SPANS)
|
|
627
|
+
return;
|
|
628
|
+
const span = telemetry.span(`read ${r.model}`, {
|
|
629
|
+
parent: scope.trace,
|
|
630
|
+
elapsedMs: r.ms,
|
|
631
|
+
attributes: { "weft.model": r.model, "weft.data.rows": r.rows, "weft.data.scoped": r.scoped },
|
|
632
|
+
});
|
|
633
|
+
span.end();
|
|
634
|
+
})
|
|
635
|
+
: null;
|
|
636
|
+
function report(err, kind, where = {}) {
|
|
637
|
+
if (err !== null && typeof err === "object") {
|
|
638
|
+
if (reported.has(err))
|
|
639
|
+
return;
|
|
640
|
+
reported.add(err);
|
|
641
|
+
}
|
|
642
|
+
const req = where.req ?? where.ctx?.request ?? null;
|
|
643
|
+
const user = where.ctx?.user;
|
|
644
|
+
const id = user && (typeof user.id === "string" || typeof user.id === "number") ? String(user.id) : null;
|
|
645
|
+
const route = where.route;
|
|
646
|
+
const pattern = route ? patternOf.get(route) : undefined;
|
|
647
|
+
const component = route && typeof route === "object" && "component" in route ? route.component.def?.name : undefined;
|
|
648
|
+
const info = {
|
|
649
|
+
kind,
|
|
650
|
+
...(pattern !== undefined ? { route: pattern } : {}),
|
|
651
|
+
...(typeof component === "string" && component !== "" ? { component } : {}),
|
|
652
|
+
...(where.handler ? { handler: where.handler } : {}),
|
|
653
|
+
actor: id,
|
|
654
|
+
requestId: req ? requestIdOf(req) : null,
|
|
655
|
+
...(req ? { method: req.method, path: new URL(req.url).pathname } : {}),
|
|
656
|
+
instance,
|
|
657
|
+
};
|
|
658
|
+
if (!opts.onError && logger) {
|
|
659
|
+
logger.error("unhandled error", { error: err, ...info });
|
|
660
|
+
}
|
|
661
|
+
else {
|
|
662
|
+
try {
|
|
663
|
+
onError(err);
|
|
664
|
+
}
|
|
665
|
+
catch (e) {
|
|
666
|
+
if (e !== null && typeof e === "object")
|
|
667
|
+
rethrown.add(e);
|
|
668
|
+
throw e;
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
if (opts.reportError) {
|
|
672
|
+
try {
|
|
673
|
+
opts.reportError(err, info);
|
|
674
|
+
}
|
|
675
|
+
catch (e) {
|
|
676
|
+
onError(e);
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
if (telemetry) {
|
|
680
|
+
try {
|
|
681
|
+
telemetry.error(err, info, (req && traces.get(req)) ?? null);
|
|
682
|
+
}
|
|
683
|
+
catch (e) {
|
|
684
|
+
onError(e);
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
if (!/^[A-Za-z0-9._-]{1,64}$/.test(instance)) {
|
|
689
|
+
throw new Error("@weft-framework/server: instance names are 1-64 of A-Z a-z 0-9 . _ -");
|
|
690
|
+
}
|
|
691
|
+
if (opts.stickyCookie !== undefined && (!/^[A-Za-z0-9_-]{1,64}$/.test(opts.stickyCookie) || opts.stickyCookie === cookieName)) {
|
|
692
|
+
throw new Error("@weft-framework/server: stickyCookie must be a plain cookie name other than the session cookie");
|
|
693
|
+
}
|
|
694
|
+
function stamped(req, res, secure) {
|
|
695
|
+
res.headers.set("x-weft-instance", instance);
|
|
696
|
+
const sticky = opts.stickyCookie;
|
|
697
|
+
if (sticky && parseCookies(req.headers.get("cookie"))[sticky] !== instance) {
|
|
698
|
+
const parts = [`${sticky}=${instance}`, "Path=/", "HttpOnly", "SameSite=Lax"];
|
|
699
|
+
if (secure) {
|
|
700
|
+
parts.push("Secure");
|
|
701
|
+
}
|
|
702
|
+
res.headers.append("set-cookie", parts.join("; "));
|
|
703
|
+
}
|
|
704
|
+
return res;
|
|
705
|
+
}
|
|
706
|
+
const wsEnabled = (opts.transports ?? ["ws", "sse"]).includes("ws");
|
|
707
|
+
const stateless = opts.transports !== undefined && opts.transports.length === 0;
|
|
708
|
+
const edgeCache = opts.edge === false || opts.devtools ? null : { maxAge: opts.edge?.maxAge ?? 300, stale: opts.edge?.stale ?? 86_400 };
|
|
709
|
+
if (edgeCache && ![edgeCache.maxAge, edgeCache.stale].every((n) => Number.isInteger(n) && n >= 0 && n <= 31_536_000)) {
|
|
710
|
+
throw new RangeError("createApp: edge maxAge and stale are whole seconds, 0 to 31536000");
|
|
711
|
+
}
|
|
712
|
+
let shellShared = true;
|
|
713
|
+
const unshared = (res) => {
|
|
714
|
+
if (!/\bs-maxage=/.test(res.headers.get("cache-control") ?? ""))
|
|
715
|
+
return res;
|
|
716
|
+
if (res.headers.has("set-cookie") || /\bcookie\b/i.test(res.headers.get("vary") ?? "")) {
|
|
717
|
+
res.headers.set("cache-control", "private, no-store");
|
|
718
|
+
res.headers.delete("etag");
|
|
719
|
+
}
|
|
720
|
+
return res;
|
|
721
|
+
};
|
|
722
|
+
const deadHandlers = new Set();
|
|
723
|
+
const assets = new Map();
|
|
724
|
+
for (const [path, source] of Object.entries(opts.assets ?? {})) {
|
|
725
|
+
if (!path.startsWith("/_weft/") || path.startsWith(LIVE)) {
|
|
726
|
+
throw new Error(`@weft-framework/server: asset paths must be under /_weft/: ${path}`);
|
|
727
|
+
}
|
|
728
|
+
assets.set(path, source);
|
|
729
|
+
}
|
|
730
|
+
if (opts.clientScript !== undefined) {
|
|
731
|
+
assets.set("/_weft/client.js", opts.clientScript);
|
|
732
|
+
}
|
|
733
|
+
const clientEntry = opts.clientEntry ?? "/_weft/client.js";
|
|
734
|
+
if (opts.clientEntry !== undefined && !assets.has(clientEntry)) {
|
|
735
|
+
throw new Error(`@weft-framework/server: clientEntry ${clientEntry} is not among the assets`);
|
|
736
|
+
}
|
|
737
|
+
const assetCache = opts.immutableAssets ? "public, max-age=31536000, immutable" : "no-cache";
|
|
738
|
+
if (opts.componentStyles) {
|
|
739
|
+
setComponentStyles(opts.componentStyles);
|
|
740
|
+
}
|
|
741
|
+
const appCss = opts.stylesheet !== undefined ? { css: opts.stylesheet, version: contentVersion(opts.stylesheet) } : null;
|
|
742
|
+
const appCssLink = appCss ? `<link rel="stylesheet" href="${APP_CSS}?v=${appCss.version}">` : "";
|
|
743
|
+
async function sessionOf(req) {
|
|
744
|
+
const cookies = parseCookies(req.headers.get("cookie"));
|
|
745
|
+
return verifySession(await keyP, cookies[cookieName]);
|
|
746
|
+
}
|
|
747
|
+
const authStore = opts.auth?.store ?? new MemorySessionStore();
|
|
748
|
+
const devViewing = opts.devtools === true && process.env.NODE_ENV !== "production";
|
|
749
|
+
const idleMs = opts.auth?.idleMs ?? 14 * 24 * 3600_000;
|
|
750
|
+
const maxAgeMs = opts.auth?.maxAgeMs ?? 30 * 24 * 3600_000;
|
|
751
|
+
const twoFactor = opts.auth?.twoFactor ?? null;
|
|
752
|
+
if (twoFactor && (typeof twoFactor.needed !== "function" || !isSafePath(twoFactor.page))) {
|
|
753
|
+
throw new Error("@weft-framework/server: auth.twoFactor is a `defineTwoFactor({...})` with a same-origin `page`");
|
|
754
|
+
}
|
|
755
|
+
const PENDING_MS = 10 * 60_000;
|
|
756
|
+
async function publicSessionId(sid) {
|
|
757
|
+
const d = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`weft-session\n${sid}`));
|
|
758
|
+
return base64url(new Uint8Array(d)).slice(0, 22);
|
|
759
|
+
}
|
|
760
|
+
async function dropSessionIds(ids) {
|
|
761
|
+
const sids = new Set([...pages.values()].map((e) => e.sid));
|
|
762
|
+
for (const sid of sids) {
|
|
763
|
+
if (ids.has(await publicSessionId(sid)))
|
|
764
|
+
dropSession(sid);
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
const revocations = opts.auth?.revocations ?? null;
|
|
768
|
+
if (revocations) {
|
|
769
|
+
revocations.subscribe((message) => {
|
|
770
|
+
let ids;
|
|
771
|
+
try {
|
|
772
|
+
const m = JSON.parse(message);
|
|
773
|
+
ids = m?.v === 1 && m.t === "revoke" ? m.ids : null;
|
|
774
|
+
}
|
|
775
|
+
catch {
|
|
776
|
+
return;
|
|
777
|
+
}
|
|
778
|
+
if (Array.isArray(ids) && ids.length <= 1000 && ids.every((x) => typeof x === "string")) {
|
|
779
|
+
dropSessionIds(new Set(ids)).catch(onError);
|
|
780
|
+
}
|
|
781
|
+
});
|
|
782
|
+
}
|
|
783
|
+
async function revokeSids(sids) {
|
|
784
|
+
for (const sid of sids) {
|
|
785
|
+
await authStore.delete(sid);
|
|
786
|
+
dropSession(sid);
|
|
787
|
+
}
|
|
788
|
+
if (revocations && sids.length > 0) {
|
|
789
|
+
const ids = await Promise.all(sids.map(publicSessionId));
|
|
790
|
+
for (let i = 0; i < ids.length; i += 1000) {
|
|
791
|
+
await revocations.publish(JSON.stringify({ v: 1, t: "revoke", ids: ids.slice(i, i + 1000) }));
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
function sessionsOf(user) {
|
|
796
|
+
if (typeof authStore.forUser !== "function") {
|
|
797
|
+
throw new Error("@weft-framework/server: this session store cannot list a user's sessions (it needs forUser)");
|
|
798
|
+
}
|
|
799
|
+
return authStore.forUser(user);
|
|
800
|
+
}
|
|
801
|
+
async function userOf(sid) {
|
|
802
|
+
if (!sid) {
|
|
803
|
+
return null;
|
|
804
|
+
}
|
|
805
|
+
const rec = await authStore.get(sid);
|
|
806
|
+
if (!rec) {
|
|
807
|
+
return null;
|
|
808
|
+
}
|
|
809
|
+
const t = now();
|
|
810
|
+
if (rec.pending) {
|
|
811
|
+
if (t - rec.created > PENDING_MS) {
|
|
812
|
+
await authStore.delete(sid);
|
|
813
|
+
}
|
|
814
|
+
return null;
|
|
815
|
+
}
|
|
816
|
+
if (t - rec.seen > idleMs || t - rec.created > maxAgeMs) {
|
|
817
|
+
await authStore.delete(sid);
|
|
818
|
+
return null;
|
|
819
|
+
}
|
|
820
|
+
if (twoFactor && !rec.mfa && (await twoFactor.needed(rec.user, rec.tenant))) {
|
|
821
|
+
const { mfa: _mfa, ...kept } = rec;
|
|
822
|
+
await authStore.set(sid, { ...kept, created: t, seen: t, pending: true });
|
|
823
|
+
return null;
|
|
824
|
+
}
|
|
825
|
+
if (t - rec.seen > Math.min(60_000, idleMs / 10)) {
|
|
826
|
+
await authStore.set(sid, { ...rec, seen: t });
|
|
827
|
+
}
|
|
828
|
+
const actor = opts.auth?.user ? await opts.auth.user(rec.user, rec.tenant) : { id: rec.user };
|
|
829
|
+
if (actor === null || actor === undefined) {
|
|
830
|
+
await authStore.delete(sid);
|
|
831
|
+
return null;
|
|
832
|
+
}
|
|
833
|
+
if (rec.viewAs) {
|
|
834
|
+
const seen = await viewedBy(rec.user, rec.viewAs, t);
|
|
835
|
+
if (seen) {
|
|
836
|
+
return seen;
|
|
837
|
+
}
|
|
838
|
+
const { viewAs: _gone, ...kept } = rec;
|
|
839
|
+
await authStore.set(sid, kept);
|
|
840
|
+
}
|
|
841
|
+
return actor;
|
|
842
|
+
}
|
|
843
|
+
async function viewedBy(operator, v, t) {
|
|
844
|
+
const hook = opts.auth?.viewAs;
|
|
845
|
+
const dev = v.dev === true;
|
|
846
|
+
if (dev ? !devViewing : typeof hook !== "function")
|
|
847
|
+
return null;
|
|
848
|
+
if (!(v.until > t) || v.user === operator) {
|
|
849
|
+
return null;
|
|
850
|
+
}
|
|
851
|
+
try {
|
|
852
|
+
if (!dev && (await hook(operator, v.user)) !== true) {
|
|
853
|
+
return null;
|
|
854
|
+
}
|
|
855
|
+
const target = opts.auth?.user ? await opts.auth.user(v.user, v.tenant) : { id: v.user };
|
|
856
|
+
if (target === null || typeof target !== "object" || (v.tenant !== undefined && tenantOf(target) !== v.tenant)) {
|
|
857
|
+
return null;
|
|
858
|
+
}
|
|
859
|
+
const ro = readOnlyActor(target, { via: operator });
|
|
860
|
+
noteViewing(ro, { user: v.user, operator, until: v.until, ...(v.tenant !== undefined ? { tenant: v.tenant } : {}) });
|
|
861
|
+
return ro;
|
|
862
|
+
}
|
|
863
|
+
catch (err) {
|
|
864
|
+
onError(err);
|
|
865
|
+
return null;
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
function dropSession(sid) {
|
|
869
|
+
for (const [lid, e] of [...pages]) {
|
|
870
|
+
if (e.sid === sid) {
|
|
871
|
+
drop(lid);
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
async function contextFor(req, url, params, sid, refused, onRotate = () => undefined) {
|
|
876
|
+
const ctx = {
|
|
877
|
+
request: req,
|
|
878
|
+
url,
|
|
879
|
+
params,
|
|
880
|
+
query: url.searchParams,
|
|
881
|
+
session: sid,
|
|
882
|
+
user: await userOf(sid),
|
|
883
|
+
};
|
|
884
|
+
const rotate = async (user, o = {}) => {
|
|
885
|
+
const pending = user !== null && !o.mfa && twoFactor !== null && (await twoFactor.needed(user, o.tenant));
|
|
886
|
+
const old = ctx.session;
|
|
887
|
+
const next = randomId(24);
|
|
888
|
+
const t = now();
|
|
889
|
+
await authStore.delete(old);
|
|
890
|
+
if (user !== null) {
|
|
891
|
+
const rec = { user, created: t, seen: t };
|
|
892
|
+
if (o.tenant !== undefined)
|
|
893
|
+
rec.tenant = o.tenant;
|
|
894
|
+
if (o.sso !== undefined)
|
|
895
|
+
rec.sso = o.sso;
|
|
896
|
+
const agent = req.headers.get("user-agent");
|
|
897
|
+
if (agent)
|
|
898
|
+
rec.agent = agent.slice(0, 256);
|
|
899
|
+
if (pending)
|
|
900
|
+
rec.pending = true;
|
|
901
|
+
else if (o.mfa)
|
|
902
|
+
rec.mfa = true;
|
|
903
|
+
await authStore.set(next, rec);
|
|
904
|
+
}
|
|
905
|
+
dropSession(old);
|
|
906
|
+
const value = await signSession(await keyP, next);
|
|
907
|
+
const cookie = sessionCookie(cookieName, value, {
|
|
908
|
+
secure: url.protocol === "https:",
|
|
909
|
+
maxAgeSeconds: user !== null && !pending ? maxAgeMs / 1000 : undefined,
|
|
910
|
+
});
|
|
911
|
+
ctx.session = next;
|
|
912
|
+
ctx.user = user !== null && !pending ? await userOf(next) : null;
|
|
913
|
+
onRotate({ sid: next, cookie });
|
|
914
|
+
return pending ? "two-factor" : "ok";
|
|
915
|
+
};
|
|
916
|
+
const state = async () => {
|
|
917
|
+
const rec = await authStore.get(ctx.session);
|
|
918
|
+
if (!rec)
|
|
919
|
+
return null;
|
|
920
|
+
if (rec.pending ? now() - rec.created > PENDING_MS : ctx.user === null)
|
|
921
|
+
return null;
|
|
922
|
+
const s = { user: rec.user, pending: rec.pending === true, mfa: rec.mfa === true };
|
|
923
|
+
if (rec.tenant !== undefined)
|
|
924
|
+
s.tenant = rec.tenant;
|
|
925
|
+
return s;
|
|
926
|
+
};
|
|
927
|
+
const switchTenant = async (tenant) => {
|
|
928
|
+
const sid = ctx.session;
|
|
929
|
+
const rec = ctx.user !== null ? await authStore.get(sid) : null;
|
|
930
|
+
if (!rec || rec.viewAs) {
|
|
931
|
+
return false;
|
|
932
|
+
}
|
|
933
|
+
const next = { user: rec.user, created: rec.created, seen: rec.seen };
|
|
934
|
+
if (rec.agent !== undefined)
|
|
935
|
+
next.agent = rec.agent;
|
|
936
|
+
if (rec.sso !== undefined)
|
|
937
|
+
next.sso = rec.sso;
|
|
938
|
+
if (tenant !== null) {
|
|
939
|
+
next.tenant = tenant;
|
|
940
|
+
}
|
|
941
|
+
if (rec.mfa) {
|
|
942
|
+
next.mfa = true;
|
|
943
|
+
}
|
|
944
|
+
else if (twoFactor && (await twoFactor.needed(next.user, next.tenant))) {
|
|
945
|
+
return false;
|
|
946
|
+
}
|
|
947
|
+
const actor = opts.auth?.user ? await opts.auth.user(next.user, next.tenant) : { id: next.user };
|
|
948
|
+
if (actor === null || actor === undefined || (tenant !== null && tenantOf(actor) !== tenant)) {
|
|
949
|
+
return false;
|
|
950
|
+
}
|
|
951
|
+
await authStore.set(sid, next);
|
|
952
|
+
reload(sid, actor);
|
|
953
|
+
return true;
|
|
954
|
+
};
|
|
955
|
+
const reload = (sid, actor) => {
|
|
956
|
+
ctx.user = actor;
|
|
957
|
+
for (const e of pages.values()) {
|
|
958
|
+
if (e.sid === sid) {
|
|
959
|
+
e.ctx.user = actor;
|
|
960
|
+
because(e, "the session's actor changed (view as)");
|
|
961
|
+
schedule(e, true);
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
};
|
|
965
|
+
const startViewAs = async (user, tenant, until) => {
|
|
966
|
+
const sid = ctx.session;
|
|
967
|
+
const rec = ctx.user !== null ? await authStore.get(sid) : null;
|
|
968
|
+
if (!rec || rec.pending || rec.viewAs) {
|
|
969
|
+
return false;
|
|
970
|
+
}
|
|
971
|
+
const v = { user, until };
|
|
972
|
+
if (tenant !== undefined)
|
|
973
|
+
v.tenant = tenant;
|
|
974
|
+
const seen = await viewedBy(rec.user, v, now());
|
|
975
|
+
if (!seen) {
|
|
976
|
+
return false;
|
|
977
|
+
}
|
|
978
|
+
await authStore.set(sid, { ...rec, viewAs: v });
|
|
979
|
+
reload(sid, seen);
|
|
980
|
+
return true;
|
|
981
|
+
};
|
|
982
|
+
const stopViewAs = async () => {
|
|
983
|
+
const sid = ctx.session;
|
|
984
|
+
const rec = await authStore.get(sid);
|
|
985
|
+
if (!rec || !rec.viewAs) {
|
|
986
|
+
return false;
|
|
987
|
+
}
|
|
988
|
+
const { viewAs: _gone, ...kept } = rec;
|
|
989
|
+
await authStore.set(sid, kept);
|
|
990
|
+
reload(sid, await userOf(sid));
|
|
991
|
+
return true;
|
|
992
|
+
};
|
|
993
|
+
attachAuth(ctx, {
|
|
994
|
+
refused,
|
|
995
|
+
login: (user, mfa) => rotate(user, { mfa }),
|
|
996
|
+
logout: async () => {
|
|
997
|
+
await rotate(null);
|
|
998
|
+
},
|
|
999
|
+
state,
|
|
1000
|
+
completeTwoFactor: async () => {
|
|
1001
|
+
const s = await state();
|
|
1002
|
+
if (!s)
|
|
1003
|
+
return false;
|
|
1004
|
+
const sso = (await authStore.get(ctx.session))?.sso;
|
|
1005
|
+
await rotate(s.user, { mfa: true, tenant: s.tenant, ...(sso ? { sso } : {}) });
|
|
1006
|
+
return true;
|
|
1007
|
+
},
|
|
1008
|
+
sessions: async () => {
|
|
1009
|
+
const me = await state();
|
|
1010
|
+
if (!me || me.pending)
|
|
1011
|
+
return [];
|
|
1012
|
+
const t = now();
|
|
1013
|
+
const out = [];
|
|
1014
|
+
for (const { sid, record: r } of await sessionsOf(me.user)) {
|
|
1015
|
+
if (r.pending ? t - r.created > PENDING_MS : t - r.seen > idleMs || t - r.created > maxAgeMs)
|
|
1016
|
+
continue;
|
|
1017
|
+
out.push({
|
|
1018
|
+
id: await publicSessionId(sid),
|
|
1019
|
+
created: r.created,
|
|
1020
|
+
seen: r.seen,
|
|
1021
|
+
agent: r.agent ?? null,
|
|
1022
|
+
current: sid === ctx.session,
|
|
1023
|
+
mfa: r.mfa === true,
|
|
1024
|
+
pending: r.pending === true,
|
|
1025
|
+
});
|
|
1026
|
+
}
|
|
1027
|
+
return out.sort((a, b) => b.created - a.created);
|
|
1028
|
+
},
|
|
1029
|
+
revoke: async (user, o) => {
|
|
1030
|
+
const sids = [];
|
|
1031
|
+
for (const { sid, record } of await sessionsOf(user)) {
|
|
1032
|
+
if (record.user !== user || (o.keep && sid === ctx.session))
|
|
1033
|
+
continue;
|
|
1034
|
+
if (o.id !== undefined && (await publicSessionId(sid)) !== o.id)
|
|
1035
|
+
continue;
|
|
1036
|
+
sids.push(sid);
|
|
1037
|
+
}
|
|
1038
|
+
await revokeSids(sids);
|
|
1039
|
+
if (sids.includes(ctx.session)) {
|
|
1040
|
+
await rotate(null);
|
|
1041
|
+
}
|
|
1042
|
+
return sids.length;
|
|
1043
|
+
},
|
|
1044
|
+
switchTenant,
|
|
1045
|
+
startViewAs,
|
|
1046
|
+
stopViewAs,
|
|
1047
|
+
signInWith: async (identity) => {
|
|
1048
|
+
const fn = opts.auth?.signIn;
|
|
1049
|
+
if (typeof fn !== "function") {
|
|
1050
|
+
throw new Error("@weft-framework/server: signing in by email or a provider needs auth.signIn(identity) to say which user it is");
|
|
1051
|
+
}
|
|
1052
|
+
const user = await fn(identity);
|
|
1053
|
+
if (user === null || user === undefined) {
|
|
1054
|
+
return "refused";
|
|
1055
|
+
}
|
|
1056
|
+
if (typeof user !== "string" || user === "") {
|
|
1057
|
+
throw new Error("@weft-framework/server: auth.signIn must return a user id string, or null to refuse");
|
|
1058
|
+
}
|
|
1059
|
+
return rotate(user);
|
|
1060
|
+
},
|
|
1061
|
+
});
|
|
1062
|
+
attachSeal(ctx, { key: () => keyP, session: () => ctx.session });
|
|
1063
|
+
return ctx;
|
|
1064
|
+
}
|
|
1065
|
+
const NOT_HERE = "only work in actions and in API handlers for POST, PUT, PATCH and DELETE";
|
|
1066
|
+
const VIEWING = "Read-only while viewing as another user";
|
|
1067
|
+
const providers = new Map();
|
|
1068
|
+
for (const p of opts.auth?.providers ?? []) {
|
|
1069
|
+
if (providers.has(p.id)) {
|
|
1070
|
+
throw new Error(`@weft-framework/server: two sign-in providers are called ${p.id}`);
|
|
1071
|
+
}
|
|
1072
|
+
providers.set(p.id, p);
|
|
1073
|
+
}
|
|
1074
|
+
if (providers.size > 0 && typeof opts.auth?.signIn !== "function") {
|
|
1075
|
+
throw new Error("@weft-framework/server: sign-in providers need auth.signIn(identity) to say which user signs in");
|
|
1076
|
+
}
|
|
1077
|
+
const signInError = opts.auth?.signInError ?? "/";
|
|
1078
|
+
if (!isSafePath(signInError)) {
|
|
1079
|
+
throw new Error("@weft-framework/server: auth.signInError must be a same-origin path");
|
|
1080
|
+
}
|
|
1081
|
+
const SIGN_IN_COOKIE = "weft_signin";
|
|
1082
|
+
const SIGN_IN_TTL_MS = 10 * 60_000;
|
|
1083
|
+
const emailAuth = opts.auth?.email ?? null;
|
|
1084
|
+
if (providers.has("email")) {
|
|
1085
|
+
throw new Error("@weft-framework/server: the sign-in provider id `email` is taken by email sign-in");
|
|
1086
|
+
}
|
|
1087
|
+
if (emailAuth && typeof opts.auth?.signIn !== "function") {
|
|
1088
|
+
throw new Error("@weft-framework/server: email sign-in needs auth.signIn(identity) to say which user signs in");
|
|
1089
|
+
}
|
|
1090
|
+
const samlAuth = opts.auth?.saml ?? null;
|
|
1091
|
+
if (providers.has("saml")) {
|
|
1092
|
+
throw new Error("@weft-framework/server: the sign-in provider id `saml` is taken by SAML sign-in");
|
|
1093
|
+
}
|
|
1094
|
+
if (samlAuth && typeof opts.auth?.signIn !== "function") {
|
|
1095
|
+
throw new Error("@weft-framework/server: SAML sign-in needs auth.signIn(identity) to say which user signs in");
|
|
1096
|
+
}
|
|
1097
|
+
const samlKeyP = crypto.subtle
|
|
1098
|
+
.digest("SHA-256", new TextEncoder().encode(`weft-saml\0${opts.secret}`))
|
|
1099
|
+
.then((raw) => crypto.subtle.importKey("raw", raw, "AES-GCM", false, ["encrypt", "decrypt"]));
|
|
1100
|
+
const SAML_RESULT_TTL_MS = 2 * 60_000;
|
|
1101
|
+
const SAML_AAD = new TextEncoder().encode("weft-saml-result");
|
|
1102
|
+
async function sealSamlResult(value) {
|
|
1103
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
1104
|
+
const plain = new TextEncoder().encode(JSON.stringify({ e: now() + SAML_RESULT_TTL_MS, v: value }));
|
|
1105
|
+
const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: SAML_AAD }, await samlKeyP, plain));
|
|
1106
|
+
const out = new Uint8Array(12 + ct.length);
|
|
1107
|
+
out.set(iv);
|
|
1108
|
+
out.set(ct, 12);
|
|
1109
|
+
return base64url(out);
|
|
1110
|
+
}
|
|
1111
|
+
async function openSamlResult(token) {
|
|
1112
|
+
if (token === null || token.length > 16_384)
|
|
1113
|
+
return null;
|
|
1114
|
+
const bytes = fromBase64url(token);
|
|
1115
|
+
if (!bytes || bytes.length < 12 + 16)
|
|
1116
|
+
return null;
|
|
1117
|
+
try {
|
|
1118
|
+
const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: new Uint8Array(bytes.slice(0, 12)), additionalData: SAML_AAD }, await samlKeyP, new Uint8Array(bytes.slice(12)));
|
|
1119
|
+
const p = JSON.parse(new TextDecoder().decode(plain));
|
|
1120
|
+
return typeof p.e === "number" && p.e > now() ? p.v : null;
|
|
1121
|
+
}
|
|
1122
|
+
catch {
|
|
1123
|
+
return null;
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
function authRedirect(location, cookies) {
|
|
1127
|
+
const h = new Headers({ location, "cache-control": "no-store", "referrer-policy": "no-referrer" });
|
|
1128
|
+
for (const c of cookies)
|
|
1129
|
+
h.append("set-cookie", c);
|
|
1130
|
+
return new Response(null, { status: 303, headers: h });
|
|
1131
|
+
}
|
|
1132
|
+
function signedIn(outcome, next) {
|
|
1133
|
+
const to = typeof next === "string" && isSafePath(next) ? next : "/";
|
|
1134
|
+
if (outcome !== "two-factor" || !twoFactor)
|
|
1135
|
+
return to;
|
|
1136
|
+
const page = new URL(twoFactor.page, "http://x");
|
|
1137
|
+
page.searchParams.set("next", to);
|
|
1138
|
+
return `${page.pathname}${page.search}`;
|
|
1139
|
+
}
|
|
1140
|
+
function signInFailure(code, cookies = []) {
|
|
1141
|
+
const to = new URL(signInError, "http://x");
|
|
1142
|
+
to.searchParams.set("error", code);
|
|
1143
|
+
return authRedirect(`${to.pathname}${to.search}`, cookies);
|
|
1144
|
+
}
|
|
1145
|
+
async function emailRequest(req, url, sid, auth) {
|
|
1146
|
+
if (req.method !== "POST") {
|
|
1147
|
+
return new Response(null, { status: 405, headers: { allow: "POST" } });
|
|
1148
|
+
}
|
|
1149
|
+
if (!sameOrigin(req)) {
|
|
1150
|
+
return status(403);
|
|
1151
|
+
}
|
|
1152
|
+
const buf = await readLimited(req, 4096);
|
|
1153
|
+
const token = buf ? new URLSearchParams(new TextDecoder().decode(buf)).get("t") ?? "" : "";
|
|
1154
|
+
const used = await auth.consume(token);
|
|
1155
|
+
if (!used) {
|
|
1156
|
+
return signInFailure("expired");
|
|
1157
|
+
}
|
|
1158
|
+
let rotated = null;
|
|
1159
|
+
const ctx = await contextFor(req, url, {}, sid ?? randomId(24), null, (r) => (rotated = r));
|
|
1160
|
+
let outcome;
|
|
1161
|
+
try {
|
|
1162
|
+
outcome = await signInWith(ctx, emailIdentity(used.email));
|
|
1163
|
+
}
|
|
1164
|
+
catch (err) {
|
|
1165
|
+
onError(err);
|
|
1166
|
+
return signInFailure("failed");
|
|
1167
|
+
}
|
|
1168
|
+
if (outcome === "refused") {
|
|
1169
|
+
return signInFailure("refused");
|
|
1170
|
+
}
|
|
1171
|
+
const r = rotated;
|
|
1172
|
+
return authRedirect(signedIn(outcome, used.next), r ? [r.cookie] : []);
|
|
1173
|
+
}
|
|
1174
|
+
async function signInRequest(req, url, path, sid) {
|
|
1175
|
+
const rest = path.slice(AUTH.length).split("/");
|
|
1176
|
+
if (emailAuth && rest.length === 1 && rest[0] === "email") {
|
|
1177
|
+
return emailRequest(req, url, sid, emailAuth);
|
|
1178
|
+
}
|
|
1179
|
+
if (samlAuth && rest[0] === "saml") {
|
|
1180
|
+
return samlRequest(req, url, rest.slice(1), sid, samlAuth);
|
|
1181
|
+
}
|
|
1182
|
+
const provider = providers.get(rest[0]);
|
|
1183
|
+
const callback = rest.length === 2 && rest[1] === "callback";
|
|
1184
|
+
if (!provider || (rest.length !== 1 && !callback)) {
|
|
1185
|
+
return status(404);
|
|
1186
|
+
}
|
|
1187
|
+
if (req.method !== "GET") {
|
|
1188
|
+
return new Response(null, { status: 405, headers: { allow: "GET" } });
|
|
1189
|
+
}
|
|
1190
|
+
const key = await keyP;
|
|
1191
|
+
const secure = url.protocol === "https:";
|
|
1192
|
+
const base = opts.siteUrl ? new URL(opts.siteUrl).origin : url.origin;
|
|
1193
|
+
const redirectUri = `${base}${AUTH}${provider.id}/callback`;
|
|
1194
|
+
const flowCookie = (value, maxAge) => `${SIGN_IN_COOKIE}=${value}; Path=${AUTH}; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure ? "; Secure" : ""}`;
|
|
1195
|
+
const failed = (code) => signInFailure(code, [flowCookie("", 0)]);
|
|
1196
|
+
if (!callback) {
|
|
1197
|
+
const site = req.headers.get("sec-fetch-site");
|
|
1198
|
+
if (site !== null && site !== "same-origin" && site !== "none") {
|
|
1199
|
+
return status(403);
|
|
1200
|
+
}
|
|
1201
|
+
const asked = url.searchParams.get("next");
|
|
1202
|
+
const next = asked !== null && isSafePath(asked) ? asked : "/";
|
|
1203
|
+
let session = sid;
|
|
1204
|
+
const cookies = [];
|
|
1205
|
+
if (!session) {
|
|
1206
|
+
session = randomId(24);
|
|
1207
|
+
cookies.push(sessionCookie(cookieName, await signSession(key, session), { secure }));
|
|
1208
|
+
}
|
|
1209
|
+
const flow = { p: provider.id, s: randomId(32), n: randomId(32), v: randomId(48), next };
|
|
1210
|
+
let location;
|
|
1211
|
+
try {
|
|
1212
|
+
location = await provider.authorize({ redirectUri, state: flow.s, nonce: flow.n, challenge: await pkceChallenge(flow.v) });
|
|
1213
|
+
}
|
|
1214
|
+
catch (err) {
|
|
1215
|
+
onError(err);
|
|
1216
|
+
return failed("failed");
|
|
1217
|
+
}
|
|
1218
|
+
const sealed = await sealWith(key, flow, { purpose: "signin", ttlMs: SIGN_IN_TTL_MS }, session);
|
|
1219
|
+
const res = authRedirect(location, [...cookies, flowCookie(sealed, SIGN_IN_TTL_MS / 1000)]);
|
|
1220
|
+
return new Response(null, { status: 302, headers: res.headers });
|
|
1221
|
+
}
|
|
1222
|
+
const opened = sid ? await openWith(key, parseCookies(req.headers.get("cookie"))[SIGN_IN_COOKIE], { purpose: "signin" }, sid) : null;
|
|
1223
|
+
const flow = opened?.value;
|
|
1224
|
+
const state = url.searchParams.get("state");
|
|
1225
|
+
if (!sid ||
|
|
1226
|
+
!flow ||
|
|
1227
|
+
flow.p !== provider.id ||
|
|
1228
|
+
typeof flow.s !== "string" ||
|
|
1229
|
+
typeof flow.n !== "string" ||
|
|
1230
|
+
typeof flow.v !== "string" ||
|
|
1231
|
+
typeof flow.next !== "string" ||
|
|
1232
|
+
state === null ||
|
|
1233
|
+
!timingSafeEqual(state, flow.s)) {
|
|
1234
|
+
return failed("failed");
|
|
1235
|
+
}
|
|
1236
|
+
const error = url.searchParams.get("error");
|
|
1237
|
+
if (error !== null) {
|
|
1238
|
+
return failed(error === "access_denied" ? "denied" : "failed");
|
|
1239
|
+
}
|
|
1240
|
+
const code = url.searchParams.get("code");
|
|
1241
|
+
if (code === null || code === "" || code.length > 4096) {
|
|
1242
|
+
return failed("failed");
|
|
1243
|
+
}
|
|
1244
|
+
let identity;
|
|
1245
|
+
try {
|
|
1246
|
+
identity = await provider.identify({ code, redirectUri, verifier: flow.v, nonce: flow.n });
|
|
1247
|
+
}
|
|
1248
|
+
catch (err) {
|
|
1249
|
+
onError(err);
|
|
1250
|
+
return failed(err instanceof SignInError ? err.code : "failed");
|
|
1251
|
+
}
|
|
1252
|
+
let rotated = null;
|
|
1253
|
+
const ctx = await contextFor(req, url, {}, sid, null, (r) => (rotated = r));
|
|
1254
|
+
let outcome;
|
|
1255
|
+
try {
|
|
1256
|
+
outcome = await signInWith(ctx, identity);
|
|
1257
|
+
}
|
|
1258
|
+
catch (err) {
|
|
1259
|
+
onError(err);
|
|
1260
|
+
return failed("failed");
|
|
1261
|
+
}
|
|
1262
|
+
if (outcome === "refused") {
|
|
1263
|
+
return failed("refused");
|
|
1264
|
+
}
|
|
1265
|
+
const r = rotated;
|
|
1266
|
+
return authRedirect(signedIn(outcome, flow.next), [flowCookie("", 0), ...(r ? [r.cookie] : [])]);
|
|
1267
|
+
}
|
|
1268
|
+
async function samlRequest(req, url, rest, sid, saml) {
|
|
1269
|
+
const [id, step] = rest;
|
|
1270
|
+
if (id === "logout" && step === undefined) {
|
|
1271
|
+
return samlLogout(req, url, sid, saml);
|
|
1272
|
+
}
|
|
1273
|
+
const steps = [undefined, "acs", "finish", "metadata", "slo"];
|
|
1274
|
+
if (id === undefined || rest.length > 2 || !steps.includes(step)) {
|
|
1275
|
+
return status(404);
|
|
1276
|
+
}
|
|
1277
|
+
const methods = step === "acs" ? ["POST"] : step === "slo" ? ["GET", "POST"] : ["GET"];
|
|
1278
|
+
if (!methods.includes(req.method)) {
|
|
1279
|
+
return new Response(null, { status: 405, headers: { allow: methods.join(", ") } });
|
|
1280
|
+
}
|
|
1281
|
+
const key = await keyP;
|
|
1282
|
+
const secure = url.protocol === "https:";
|
|
1283
|
+
const base = opts.siteUrl ? new URL(opts.siteUrl).origin : url.origin;
|
|
1284
|
+
const flowCookie = (value, maxAge) => `${SIGN_IN_COOKIE}=${value}; Path=${AUTH}; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure ? "; Secure" : ""}`;
|
|
1285
|
+
const failed = (code) => signInFailure(code, [flowCookie("", 0)]);
|
|
1286
|
+
let conn;
|
|
1287
|
+
try {
|
|
1288
|
+
conn = await saml.resolve(id);
|
|
1289
|
+
}
|
|
1290
|
+
catch (err) {
|
|
1291
|
+
onError(err);
|
|
1292
|
+
return step === "acs" || step === "finish" ? failed("failed") : status(500);
|
|
1293
|
+
}
|
|
1294
|
+
if (!conn) {
|
|
1295
|
+
return status(404);
|
|
1296
|
+
}
|
|
1297
|
+
const provider = `saml:${conn.id}`;
|
|
1298
|
+
if (step === "metadata") {
|
|
1299
|
+
return new Response(saml.metadata(base, conn), {
|
|
1300
|
+
headers: { "content-type": "application/samlmetadata+xml; charset=utf-8", "cache-control": "no-store" },
|
|
1301
|
+
});
|
|
1302
|
+
}
|
|
1303
|
+
if (step === "slo") {
|
|
1304
|
+
return samlSingleLogout(req, url, sid, saml, conn, base);
|
|
1305
|
+
}
|
|
1306
|
+
if (step === undefined) {
|
|
1307
|
+
const site = req.headers.get("sec-fetch-site");
|
|
1308
|
+
if (site !== null && site !== "same-origin" && site !== "none") {
|
|
1309
|
+
return status(403);
|
|
1310
|
+
}
|
|
1311
|
+
const asked = url.searchParams.get("next");
|
|
1312
|
+
const next = asked !== null && isSafePath(asked) ? asked : "/";
|
|
1313
|
+
let session = sid;
|
|
1314
|
+
const cookies = [];
|
|
1315
|
+
if (!session) {
|
|
1316
|
+
session = randomId(24);
|
|
1317
|
+
cookies.push(sessionCookie(cookieName, await signSession(key, session), { secure }));
|
|
1318
|
+
}
|
|
1319
|
+
const flow = { p: provider, r: saml.newRequestId(), next };
|
|
1320
|
+
let location;
|
|
1321
|
+
try {
|
|
1322
|
+
location = saml.authorize(conn, { requestId: flow.r, base });
|
|
1323
|
+
}
|
|
1324
|
+
catch (err) {
|
|
1325
|
+
onError(err);
|
|
1326
|
+
return failed("failed");
|
|
1327
|
+
}
|
|
1328
|
+
const sealed = await sealWith(key, flow, { purpose: "signin", ttlMs: SIGN_IN_TTL_MS }, session);
|
|
1329
|
+
const res = authRedirect(location, [...cookies, flowCookie(sealed, SIGN_IN_TTL_MS / 1000)]);
|
|
1330
|
+
return new Response(null, { status: 302, headers: res.headers });
|
|
1331
|
+
}
|
|
1332
|
+
if (step === "acs") {
|
|
1333
|
+
const buf = await readLimited(req, 512 * 1024 + 16_384);
|
|
1334
|
+
if (!buf) {
|
|
1335
|
+
return failed("failed");
|
|
1336
|
+
}
|
|
1337
|
+
const response = new URLSearchParams(new TextDecoder().decode(buf)).get("SAMLResponse");
|
|
1338
|
+
let result;
|
|
1339
|
+
try {
|
|
1340
|
+
result = saml.verify(conn, response ?? "", { base });
|
|
1341
|
+
}
|
|
1342
|
+
catch (err) {
|
|
1343
|
+
if (!(err instanceof SignInError))
|
|
1344
|
+
onError(err);
|
|
1345
|
+
return failed(err instanceof SignInError ? err.code : "failed");
|
|
1346
|
+
}
|
|
1347
|
+
if (!(await saml.claim(`${conn.id}:${result.assertionId}`, result.expires))) {
|
|
1348
|
+
return failed("failed");
|
|
1349
|
+
}
|
|
1350
|
+
let identity = result.identity;
|
|
1351
|
+
let token = await sealSamlResult({ c: conn.id, r: result.inResponseTo, i: identity });
|
|
1352
|
+
if (token.length > 6000) {
|
|
1353
|
+
identity = { ...identity, claims: { ...identity.claims, attributes: {}, truncated: true } };
|
|
1354
|
+
token = await sealSamlResult({ c: conn.id, r: result.inResponseTo, i: identity });
|
|
1355
|
+
}
|
|
1356
|
+
return authRedirect(`${AUTH}saml/${conn.id}/finish?r=${token}`, []);
|
|
1357
|
+
}
|
|
1358
|
+
const opened = sid ? await openWith(key, parseCookies(req.headers.get("cookie"))[SIGN_IN_COOKIE], { purpose: "signin" }, sid) : null;
|
|
1359
|
+
const flow = opened?.value;
|
|
1360
|
+
const got = (await openSamlResult(url.searchParams.get("r")));
|
|
1361
|
+
if (!sid ||
|
|
1362
|
+
!flow ||
|
|
1363
|
+
!got ||
|
|
1364
|
+
flow.p !== provider ||
|
|
1365
|
+
typeof flow.r !== "string" ||
|
|
1366
|
+
typeof flow.next !== "string" ||
|
|
1367
|
+
got.c !== conn.id ||
|
|
1368
|
+
typeof got.r !== "string" ||
|
|
1369
|
+
typeof got.i !== "object" ||
|
|
1370
|
+
got.i === null ||
|
|
1371
|
+
!timingSafeEqual(got.r, flow.r) ||
|
|
1372
|
+
!(await saml.claim(`${conn.id}:finish:${flow.r}`, now() + SAML_RESULT_TTL_MS))) {
|
|
1373
|
+
return failed("failed");
|
|
1374
|
+
}
|
|
1375
|
+
let rotated = null;
|
|
1376
|
+
const ctx = await contextFor(req, url, {}, sid, null, (r) => (rotated = r));
|
|
1377
|
+
let outcome;
|
|
1378
|
+
try {
|
|
1379
|
+
outcome = await signInWith(ctx, got.i);
|
|
1380
|
+
}
|
|
1381
|
+
catch (err) {
|
|
1382
|
+
onError(err);
|
|
1383
|
+
return failed("failed");
|
|
1384
|
+
}
|
|
1385
|
+
if (outcome === "refused") {
|
|
1386
|
+
return failed("refused");
|
|
1387
|
+
}
|
|
1388
|
+
const r = rotated;
|
|
1389
|
+
const ref = samlRef(got.i);
|
|
1390
|
+
if (r && ref) {
|
|
1391
|
+
const rec = await authStore.get(r.sid);
|
|
1392
|
+
if (rec)
|
|
1393
|
+
await authStore.set(r.sid, { ...rec, sso: ref });
|
|
1394
|
+
}
|
|
1395
|
+
return authRedirect(signedIn(outcome, flow.next), [flowCookie("", 0), ...(r ? [r.cookie] : [])]);
|
|
1396
|
+
}
|
|
1397
|
+
function samlRef(identity) {
|
|
1398
|
+
const k = identity.claims;
|
|
1399
|
+
if (typeof k.connection !== "string" || typeof k.nameId !== "string")
|
|
1400
|
+
return null;
|
|
1401
|
+
const ref = {
|
|
1402
|
+
c: k.connection,
|
|
1403
|
+
n: k.nameId,
|
|
1404
|
+
f: typeof k.nameIdFormat === "string" ? k.nameIdFormat : null,
|
|
1405
|
+
s: typeof k.sessionIndex === "string" ? k.sessionIndex : null,
|
|
1406
|
+
};
|
|
1407
|
+
if (typeof k.nameQualifier === "string")
|
|
1408
|
+
ref.nq = k.nameQualifier;
|
|
1409
|
+
if (typeof k.spNameQualifier === "string")
|
|
1410
|
+
ref.spnq = k.spNameQualifier;
|
|
1411
|
+
return ref;
|
|
1412
|
+
}
|
|
1413
|
+
const SAML_LOGOUT_COOKIE = "weft_saml_logout";
|
|
1414
|
+
async function samlLogout(req, url, sid, saml) {
|
|
1415
|
+
if (req.method !== "POST") {
|
|
1416
|
+
return new Response(null, { status: 405, headers: { allow: "POST" } });
|
|
1417
|
+
}
|
|
1418
|
+
if (!sameOrigin(req)) {
|
|
1419
|
+
return status(403);
|
|
1420
|
+
}
|
|
1421
|
+
const buf = await readLimited(req, 4096);
|
|
1422
|
+
const asked = buf ? new URLSearchParams(new TextDecoder().decode(buf)).get("next") : null;
|
|
1423
|
+
const next = asked !== null && isSafePath(asked) ? asked : "/";
|
|
1424
|
+
const rec = sid ? await authStore.get(sid) : null;
|
|
1425
|
+
const ref = rec?.sso;
|
|
1426
|
+
let rotated = null;
|
|
1427
|
+
const ctx = await contextFor(req, url, {}, sid ?? randomId(24), null, (r) => (rotated = r));
|
|
1428
|
+
await logout(ctx);
|
|
1429
|
+
const r = rotated;
|
|
1430
|
+
const cookies = r ? [r.cookie] : [];
|
|
1431
|
+
let conn = null;
|
|
1432
|
+
try {
|
|
1433
|
+
conn = ref ? await saml.resolve(ref.c) : null;
|
|
1434
|
+
}
|
|
1435
|
+
catch (err) {
|
|
1436
|
+
onError(err);
|
|
1437
|
+
}
|
|
1438
|
+
if (!ref || !conn) {
|
|
1439
|
+
return authRedirect(next, cookies);
|
|
1440
|
+
}
|
|
1441
|
+
const base = opts.siteUrl ? new URL(opts.siteUrl).origin : url.origin;
|
|
1442
|
+
const requestId = saml.newRequestId();
|
|
1443
|
+
let location;
|
|
1444
|
+
try {
|
|
1445
|
+
location = saml.logoutRequest(conn, ref, { requestId, base });
|
|
1446
|
+
}
|
|
1447
|
+
catch (err) {
|
|
1448
|
+
onError(err);
|
|
1449
|
+
location = null;
|
|
1450
|
+
}
|
|
1451
|
+
if (location === null) {
|
|
1452
|
+
return authRedirect(next, cookies);
|
|
1453
|
+
}
|
|
1454
|
+
const flow = await sealWith(await keyP, { c: conn.id, r: requestId, next }, { purpose: "saml-logout", ttlMs: SIGN_IN_TTL_MS });
|
|
1455
|
+
const secure = url.protocol === "https:";
|
|
1456
|
+
cookies.push(`${SAML_LOGOUT_COOKIE}=${flow}; Path=${AUTH}saml/; HttpOnly; SameSite=Lax; Max-Age=${SIGN_IN_TTL_MS / 1000}${secure ? "; Secure" : ""}`);
|
|
1457
|
+
return authRedirect(location, cookies);
|
|
1458
|
+
}
|
|
1459
|
+
async function samlSingleLogout(req, url, sid, saml, conn, base) {
|
|
1460
|
+
let form = null;
|
|
1461
|
+
if (req.method === "POST") {
|
|
1462
|
+
const buf = await readLimited(req, 512 * 1024 + 16_384);
|
|
1463
|
+
if (!buf)
|
|
1464
|
+
return status(413);
|
|
1465
|
+
form = new URLSearchParams(new TextDecoder().decode(buf));
|
|
1466
|
+
}
|
|
1467
|
+
const secure = url.protocol === "https:";
|
|
1468
|
+
const clear = `${SAML_LOGOUT_COOKIE}=; Path=${AUTH}saml/; HttpOnly; SameSite=Lax; Max-Age=0${secure ? "; Secure" : ""}`;
|
|
1469
|
+
let msg;
|
|
1470
|
+
try {
|
|
1471
|
+
msg = saml.readLogout(conn, { search: url.search, form, base });
|
|
1472
|
+
}
|
|
1473
|
+
catch (err) {
|
|
1474
|
+
if (!(err instanceof SignInError))
|
|
1475
|
+
onError(err);
|
|
1476
|
+
const isResponse = form ? form.has("SAMLResponse") : url.searchParams.has("SAMLResponse");
|
|
1477
|
+
return isResponse ? authRedirect("/", [clear]) : status(400);
|
|
1478
|
+
}
|
|
1479
|
+
if (msg.kind === "response") {
|
|
1480
|
+
const opened = await openWith(await keyP, parseCookies(req.headers.get("cookie"))[SAML_LOGOUT_COOKIE], { purpose: "saml-logout" });
|
|
1481
|
+
const flow = opened?.value;
|
|
1482
|
+
const ours = flow && flow.c === conn.id && typeof flow.r === "string" && msg.inResponseTo !== null && timingSafeEqual(msg.inResponseTo, flow.r);
|
|
1483
|
+
const next = ours && typeof flow.next === "string" && isSafePath(flow.next) ? flow.next : "/";
|
|
1484
|
+
return authRedirect(next, [clear]);
|
|
1485
|
+
}
|
|
1486
|
+
if (!(await saml.claim(`${conn.id}:slo:${msg.id}`, msg.expires))) {
|
|
1487
|
+
return status(400);
|
|
1488
|
+
}
|
|
1489
|
+
const matches = (ref) => ref !== undefined && ref.c === conn.id && ref.n === msg.nameId && (msg.sessionIndexes.length === 0 || (ref.s !== null && msg.sessionIndexes.includes(ref.s)));
|
|
1490
|
+
const cookies = [];
|
|
1491
|
+
const mine = sid ? await authStore.get(sid) : null;
|
|
1492
|
+
if (sid && mine && matches(mine.sso)) {
|
|
1493
|
+
let rotated = null;
|
|
1494
|
+
const ctx = await contextFor(req, url, {}, sid, null, (r) => (rotated = r));
|
|
1495
|
+
await logout(ctx);
|
|
1496
|
+
const r = rotated;
|
|
1497
|
+
if (r)
|
|
1498
|
+
cookies.push(r.cookie);
|
|
1499
|
+
}
|
|
1500
|
+
try {
|
|
1501
|
+
const user = await saml.userFor({ connection: conn.id, tenant: conn.tenant ?? null, nameId: msg.nameId, sessionIndexes: msg.sessionIndexes });
|
|
1502
|
+
if (user !== null) {
|
|
1503
|
+
const sids = [];
|
|
1504
|
+
for (const { sid: s, record } of await sessionsOf(user)) {
|
|
1505
|
+
if (record.user === user && matches(record.sso))
|
|
1506
|
+
sids.push(s);
|
|
1507
|
+
}
|
|
1508
|
+
await revokeSids(sids);
|
|
1509
|
+
}
|
|
1510
|
+
}
|
|
1511
|
+
catch (err) {
|
|
1512
|
+
onError(err);
|
|
1513
|
+
}
|
|
1514
|
+
const location = saml.logoutResponse(conn, { inResponseTo: msg.id, base, relay: msg.relay });
|
|
1515
|
+
if (location === null) {
|
|
1516
|
+
return new Response(null, { status: 204, headers: cookies.length ? { "set-cookie": cookies[0] } : {} });
|
|
1517
|
+
}
|
|
1518
|
+
return authRedirect(location, cookies);
|
|
1519
|
+
}
|
|
1520
|
+
const router = new Router(opts.routes);
|
|
1521
|
+
const appCsp = opts.csp === undefined ? undefined : checkCspSources(opts.csp, "createApp");
|
|
1522
|
+
const cspByRoute = new Map();
|
|
1523
|
+
for (const [pattern, route] of Object.entries(opts.routes)) {
|
|
1524
|
+
const own = route.csp === undefined ? undefined : checkCspSources(route.csp, `route ${pattern}`);
|
|
1525
|
+
cspByRoute.set(route, mergeCspSources(appCsp, own));
|
|
1526
|
+
}
|
|
1527
|
+
const cspSourcesOf = (route) => cspByRoute.get(route) ?? appCsp ?? {};
|
|
1528
|
+
for (const [pattern, route] of Object.entries(opts.routes)) {
|
|
1529
|
+
if (route.pdf !== undefined)
|
|
1530
|
+
checkPdfRoute(route.pdf, `route ${pattern}`);
|
|
1531
|
+
if (route.og !== undefined) {
|
|
1532
|
+
checkOg(route.og, `route ${pattern}`);
|
|
1533
|
+
if (!opts.pdf?.capture)
|
|
1534
|
+
throw new TypeError(`route ${pattern}: og images are drawn by the \`pdf\` printer (src/pdf.ts: export const pdf = definePdf())`);
|
|
1535
|
+
}
|
|
1536
|
+
}
|
|
1537
|
+
const pdfLimiter = new RateLimiter({ capacity: 3, refillPerSecond: 0.1 });
|
|
1538
|
+
async function printRoute(req, url, path, spec, sid) {
|
|
1539
|
+
if (!pdfLimiter.take(sid ?? "anon"))
|
|
1540
|
+
return status(429);
|
|
1541
|
+
const forward = (h) => {
|
|
1542
|
+
const out = new Headers();
|
|
1543
|
+
for (const name of ["cookie", "accept-language", "user-agent"]) {
|
|
1544
|
+
const v = h.get(name);
|
|
1545
|
+
if (v !== null)
|
|
1546
|
+
out.set(name, v);
|
|
1547
|
+
}
|
|
1548
|
+
return out;
|
|
1549
|
+
};
|
|
1550
|
+
const pageUrl = `${url.origin}${path.slice(0, -4)}${url.search}`;
|
|
1551
|
+
const inner = new Request(pageUrl, { headers: forward(req.headers) });
|
|
1552
|
+
PRINTING.add(inner);
|
|
1553
|
+
const res = (await app.fetch(inner)) ?? status(404);
|
|
1554
|
+
if (res.status !== 200 || !(res.headers.get("content-type") ?? "").startsWith("text/html"))
|
|
1555
|
+
return res;
|
|
1556
|
+
const html = await res.text();
|
|
1557
|
+
let bytes;
|
|
1558
|
+
try {
|
|
1559
|
+
bytes = await opts.pdf.print({
|
|
1560
|
+
url: pageUrl,
|
|
1561
|
+
html,
|
|
1562
|
+
fetch: async (u) => (await app.fetch(new Request(u, { headers: forward(req.headers) }))) ?? status(404),
|
|
1563
|
+
...(spec === true ? {} : { format: spec.format, landscape: spec.landscape }),
|
|
1564
|
+
});
|
|
1565
|
+
}
|
|
1566
|
+
catch (err) {
|
|
1567
|
+
onError(err);
|
|
1568
|
+
return new Response("This page could not be printed right now.", {
|
|
1569
|
+
status: 503,
|
|
1570
|
+
headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" },
|
|
1571
|
+
});
|
|
1572
|
+
}
|
|
1573
|
+
const headers = new Headers({
|
|
1574
|
+
"content-type": "application/pdf",
|
|
1575
|
+
"content-disposition": `inline; filename="${pdfFilename(path.slice(0, -4), spec)}"`,
|
|
1576
|
+
"cache-control": "no-store",
|
|
1577
|
+
"x-content-type-options": "nosniff",
|
|
1578
|
+
});
|
|
1579
|
+
const cookie = res.headers.get("set-cookie");
|
|
1580
|
+
if (cookie)
|
|
1581
|
+
headers.set("set-cookie", cookie);
|
|
1582
|
+
return new Response(bytes, { headers });
|
|
1583
|
+
}
|
|
1584
|
+
const ogLimiter = new RateLimiter({ capacity: 10, refillPerSecond: 0.5 });
|
|
1585
|
+
const ogCache = new Map();
|
|
1586
|
+
let ogHeld = 0;
|
|
1587
|
+
async function ogImage(req, url, path, spec) {
|
|
1588
|
+
const card = isComponent(spec) ? { component: spec } : spec;
|
|
1589
|
+
const pageUrl = `${url.origin}${path.slice(0, -".og.png".length) || "/"}`;
|
|
1590
|
+
const inner = new Request(pageUrl);
|
|
1591
|
+
OG_RENDER.set(inner, card.component);
|
|
1592
|
+
const res = (await app.fetch(inner)) ?? status(404);
|
|
1593
|
+
if (res.status !== 200 || !(res.headers.get("content-type") ?? "").startsWith("text/html")) {
|
|
1594
|
+
await res.body?.cancel();
|
|
1595
|
+
return status(res.status === 200 ? 404 : res.status);
|
|
1596
|
+
}
|
|
1597
|
+
const html = await res.text();
|
|
1598
|
+
const drawn = html.replace(/ nonce="[^"]*"/g, "").replace(/<meta name="weft-csrf" content="[^"]*">/g, "");
|
|
1599
|
+
const tag = createHash("sha256").update(drawn).digest("base64url").slice(0, 27);
|
|
1600
|
+
const headers = {
|
|
1601
|
+
"content-type": "image/png",
|
|
1602
|
+
etag: `"${tag}"`,
|
|
1603
|
+
"cache-control": "public, max-age=3600",
|
|
1604
|
+
"x-content-type-options": "nosniff",
|
|
1605
|
+
"content-security-policy": "default-src 'none'; sandbox",
|
|
1606
|
+
};
|
|
1607
|
+
if (matchesTag(req.headers.get("if-none-match"), tag))
|
|
1608
|
+
return new Response(null, { status: 304, headers });
|
|
1609
|
+
let hit = ogCache.get(path);
|
|
1610
|
+
if (hit?.tag !== tag) {
|
|
1611
|
+
if (!ogLimiter.take("og"))
|
|
1612
|
+
return status(429);
|
|
1613
|
+
const anon = async (u) => (await app.fetch(new Request(u))) ?? status(404);
|
|
1614
|
+
let png;
|
|
1615
|
+
try {
|
|
1616
|
+
png = await opts.pdf.capture({ url: pageUrl, html, fetch: anon, width: card.width ?? 1200, height: card.height ?? 630 });
|
|
1617
|
+
}
|
|
1618
|
+
catch (err) {
|
|
1619
|
+
onError(err);
|
|
1620
|
+
return new Response("This image could not be drawn right now.", {
|
|
1621
|
+
status: 503,
|
|
1622
|
+
headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store", "retry-after": "30" },
|
|
1623
|
+
});
|
|
1624
|
+
}
|
|
1625
|
+
if (hit)
|
|
1626
|
+
ogHeld -= hit.png.byteLength;
|
|
1627
|
+
ogCache.delete(path);
|
|
1628
|
+
hit = { tag, png };
|
|
1629
|
+
ogCache.set(path, hit);
|
|
1630
|
+
ogHeld += png.byteLength;
|
|
1631
|
+
for (const [k, v] of ogCache) {
|
|
1632
|
+
if (ogHeld <= 32 * 1024 * 1024 && ogCache.size <= 256)
|
|
1633
|
+
break;
|
|
1634
|
+
ogCache.delete(k);
|
|
1635
|
+
ogHeld -= v.png.byteLength;
|
|
1636
|
+
}
|
|
1637
|
+
}
|
|
1638
|
+
return new Response(req.method === "HEAD" ? null : hit.png, { headers });
|
|
1639
|
+
}
|
|
1640
|
+
const onCspReport = opts.cspReport ??
|
|
1641
|
+
(opts.devtools
|
|
1642
|
+
? (v) => {
|
|
1643
|
+
const key = CSP_KEY_OF[v.directive.replace(/-elem$|-attr$/, "")];
|
|
1644
|
+
const fix = key && /^[a-z]+:\/\//.test(v.blocked)
|
|
1645
|
+
? `; if this page needs it, add "${v.blocked}" to csp.${key} on ${v.route ?? "the route"}`
|
|
1646
|
+
: "";
|
|
1647
|
+
console.warn(`[weft] csp: ${v.route ?? "a page"} blocked ${v.blocked} (${v.directive})${v.source ? ` from ${v.source}` : ""}${fix}`);
|
|
1648
|
+
}
|
|
1649
|
+
: null);
|
|
1650
|
+
const cspReportLimiter = new RateLimiter({ capacity: 20, refillPerSecond: 1 });
|
|
1651
|
+
const likelyOpts = opts.prefetch === false ? null : (opts.prefetch ?? {});
|
|
1652
|
+
const likelyLinks = likelyOpts?.links ?? 2;
|
|
1653
|
+
const likelyMin = likelyOpts?.minVisits ?? 20;
|
|
1654
|
+
const likelyShare = likelyOpts?.share ?? 0.2;
|
|
1655
|
+
if (likelyOpts) {
|
|
1656
|
+
if (!Number.isInteger(likelyLinks) || likelyLinks < 1 || likelyLinks > 5)
|
|
1657
|
+
throw new RangeError("prefetch.links is a whole number from 1 to 5");
|
|
1658
|
+
if (!Number.isInteger(likelyMin) || likelyMin < 1)
|
|
1659
|
+
throw new RangeError("prefetch.minVisits is a whole number, 1 or more");
|
|
1660
|
+
if (!(likelyShare > 0 && likelyShare <= 1))
|
|
1661
|
+
throw new RangeError("prefetch.share is a number above 0, at most 1");
|
|
1662
|
+
}
|
|
1663
|
+
const transitions = new Map();
|
|
1664
|
+
const patternAt = (path) => {
|
|
1665
|
+
const found = router.match(path);
|
|
1666
|
+
return found ? patternOf.get(found.route.value) : undefined;
|
|
1667
|
+
};
|
|
1668
|
+
function noteVisit(req, url, to) {
|
|
1669
|
+
if (!likelyOpts)
|
|
1670
|
+
return;
|
|
1671
|
+
let from;
|
|
1672
|
+
try {
|
|
1673
|
+
from = new URL(req.headers.get("referer") ?? "");
|
|
1674
|
+
}
|
|
1675
|
+
catch {
|
|
1676
|
+
return;
|
|
1677
|
+
}
|
|
1678
|
+
if (from.origin !== url.origin || from.pathname === url.pathname)
|
|
1679
|
+
return;
|
|
1680
|
+
const pattern = patternAt(from.pathname);
|
|
1681
|
+
if (pattern === undefined)
|
|
1682
|
+
return;
|
|
1683
|
+
let t = transitions.get(pattern);
|
|
1684
|
+
if (!t)
|
|
1685
|
+
transitions.set(pattern, (t = { total: 0, to: new Map() }));
|
|
1686
|
+
t.total += 1;
|
|
1687
|
+
t.to.set(to, (t.to.get(to) ?? 0) + 1);
|
|
1688
|
+
if (t.total > 10_000) {
|
|
1689
|
+
t.total = 0;
|
|
1690
|
+
for (const [k, n] of t.to) {
|
|
1691
|
+
const half = Math.floor(n / 2);
|
|
1692
|
+
if (half === 0)
|
|
1693
|
+
t.to.delete(k);
|
|
1694
|
+
else
|
|
1695
|
+
t.to.set(k, half);
|
|
1696
|
+
t.total += half;
|
|
1697
|
+
}
|
|
1698
|
+
}
|
|
1699
|
+
if (t.to.size > 32) {
|
|
1700
|
+
const least = [...t.to].sort((a, b) => a[1] - b[1])[0];
|
|
1701
|
+
t.to.delete(least[0]);
|
|
1702
|
+
t.total -= least[1];
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1705
|
+
function likelyFrom(route, body, url) {
|
|
1706
|
+
if (!likelyOpts)
|
|
1707
|
+
return [];
|
|
1708
|
+
const from = patternOf.get(route);
|
|
1709
|
+
const t = from === undefined ? undefined : transitions.get(from);
|
|
1710
|
+
if (!t || t.total < likelyMin)
|
|
1711
|
+
return [];
|
|
1712
|
+
const scored = [];
|
|
1713
|
+
const seen = new Set([url.pathname + url.search]);
|
|
1714
|
+
for (const m of body.matchAll(/<a\b[^>]*?\shref="([^"]{1,512})"/g)) {
|
|
1715
|
+
let to;
|
|
1716
|
+
try {
|
|
1717
|
+
to = new URL(m[1].replaceAll("&", "&"), url);
|
|
1718
|
+
}
|
|
1719
|
+
catch {
|
|
1720
|
+
continue;
|
|
1721
|
+
}
|
|
1722
|
+
const path = to.pathname + to.search;
|
|
1723
|
+
if (to.origin !== url.origin || seen.has(path))
|
|
1724
|
+
continue;
|
|
1725
|
+
seen.add(path);
|
|
1726
|
+
const pattern = patternAt(to.pathname);
|
|
1727
|
+
const share = pattern === undefined ? 0 : (t.to.get(pattern) ?? 0) / t.total;
|
|
1728
|
+
if (share >= likelyShare)
|
|
1729
|
+
scored.push({ path, score: share, at: scored.length });
|
|
1730
|
+
if (seen.size > 500)
|
|
1731
|
+
break;
|
|
1732
|
+
}
|
|
1733
|
+
return scored
|
|
1734
|
+
.sort((a, b) => b.score - a.score || a.at - b.at)
|
|
1735
|
+
.slice(0, likelyLinks)
|
|
1736
|
+
.map((s) => s.path);
|
|
1737
|
+
}
|
|
1738
|
+
const apiRouter = new Router(opts.api ?? {});
|
|
1739
|
+
const shell = parseShell(opts.shell);
|
|
1740
|
+
function idleOldest(sid) {
|
|
1741
|
+
let fallback = null;
|
|
1742
|
+
for (const [lid, e] of pages) {
|
|
1743
|
+
if (sid !== null && e.sid !== sid) {
|
|
1744
|
+
continue;
|
|
1745
|
+
}
|
|
1746
|
+
fallback ??= lid;
|
|
1747
|
+
if (e.sinks.size === 0) {
|
|
1748
|
+
return lid;
|
|
1749
|
+
}
|
|
1750
|
+
}
|
|
1751
|
+
return fallback;
|
|
1752
|
+
}
|
|
1753
|
+
async function resolveMeta(src, ctx, data) {
|
|
1754
|
+
return typeof src === "function" ? await src(ctx, data) : src;
|
|
1755
|
+
}
|
|
1756
|
+
function composeRoot(route, ctx) {
|
|
1757
|
+
const page = route.component;
|
|
1758
|
+
const layouts = (route.layouts ?? []).map((l) => l.component);
|
|
1759
|
+
return defineComponent("Root", (props) => ({
|
|
1760
|
+
handlers: {},
|
|
1761
|
+
render: () => {
|
|
1762
|
+
let html = page(props);
|
|
1763
|
+
for (let i = layouts.length - 1; i >= 0; i--) {
|
|
1764
|
+
html = layouts[i]({ children: trustHtml(html), path: ctx.url.pathname, params: ctx.params });
|
|
1765
|
+
}
|
|
1766
|
+
return html;
|
|
1767
|
+
},
|
|
1768
|
+
}), { inert: true });
|
|
1769
|
+
}
|
|
1770
|
+
async function renderPage(req, route, params, status = 200, depth = "page") {
|
|
1771
|
+
let made = null;
|
|
1772
|
+
try {
|
|
1773
|
+
return await renderDocument(req, route, params, status, depth, (c) => {
|
|
1774
|
+
made = c;
|
|
1775
|
+
if (isPrefetch(req))
|
|
1776
|
+
presenceStartAway(c);
|
|
1777
|
+
});
|
|
1778
|
+
}
|
|
1779
|
+
catch (err) {
|
|
1780
|
+
if (err instanceof RegionWriteError && opts.regions && !opts.regions.isPrimary && depth === "page") {
|
|
1781
|
+
opts.regions.remember(route);
|
|
1782
|
+
return await opts.regions.forward(req);
|
|
1783
|
+
}
|
|
1784
|
+
report(err, "page", { route, ctx: made, req });
|
|
1785
|
+
if (depth === "error" || !opts.error) {
|
|
1786
|
+
throw err;
|
|
1787
|
+
}
|
|
1788
|
+
try {
|
|
1789
|
+
return await renderPage(req, opts.error, {}, 500, "error");
|
|
1790
|
+
}
|
|
1791
|
+
catch (again) {
|
|
1792
|
+
report(again, "page", { route: opts.error, req });
|
|
1793
|
+
return serverError(new URL(req.url).protocol === "https:");
|
|
1794
|
+
}
|
|
1795
|
+
}
|
|
1796
|
+
finally {
|
|
1797
|
+
if (made && !live.has(made))
|
|
1798
|
+
presenceRelease(made);
|
|
1799
|
+
}
|
|
1800
|
+
}
|
|
1801
|
+
async function renderDocument(req, route, params, status, depth, onCtx) {
|
|
1802
|
+
const key = await keyP;
|
|
1803
|
+
const url = new URL(req.url);
|
|
1804
|
+
const secure = url.protocol === "https:";
|
|
1805
|
+
let sid = await sessionOf(req);
|
|
1806
|
+
let setCookie = null;
|
|
1807
|
+
if (!sid) {
|
|
1808
|
+
sid = randomId(24);
|
|
1809
|
+
setCookie = sessionCookie(cookieName, await signSession(key, sid), { secure });
|
|
1810
|
+
}
|
|
1811
|
+
const etagRoute = route.cache === "etag" && feed !== null && !setCookie && depth === "page" && status === 200 &&
|
|
1812
|
+
(req.method === "GET" || req.method === "HEAD") && !uncachable.has(route);
|
|
1813
|
+
const cacheKey = etagRoute ? etagKey(req, url, sid) : "";
|
|
1814
|
+
if (etagRoute) {
|
|
1815
|
+
const held = etags.get(cacheKey);
|
|
1816
|
+
if (held && held.until <= now())
|
|
1817
|
+
purge(held);
|
|
1818
|
+
else if (held && matchesTag(req.headers.get("if-none-match"), held.tag)) {
|
|
1819
|
+
return stamped(req, new Response(null, {
|
|
1820
|
+
status: 304,
|
|
1821
|
+
headers: { etag: `"${held.tag}"`, "cache-control": "private, no-cache", vary: "Cookie, Accept-Language" },
|
|
1822
|
+
}), secure);
|
|
1823
|
+
}
|
|
1824
|
+
}
|
|
1825
|
+
const ctx = await contextFor(req, url, params, sid, NOT_HERE);
|
|
1826
|
+
onCtx(ctx);
|
|
1827
|
+
const withCookie = (res) => {
|
|
1828
|
+
if (setCookie) {
|
|
1829
|
+
res.headers.append("set-cookie", setCookie);
|
|
1830
|
+
}
|
|
1831
|
+
return stamped(req, res, secure);
|
|
1832
|
+
};
|
|
1833
|
+
const ogCard = OG_RENDER.get(req);
|
|
1834
|
+
const printing = PRINTING.has(req) || ogCard !== undefined;
|
|
1835
|
+
const oneShot = stateless || printing || overloaded(route);
|
|
1836
|
+
const deps = (etagRoute
|
|
1837
|
+
? { load: cacheReaders.deps(), render: cacheReaders.deps() }
|
|
1838
|
+
: { load: readers.deps(), render: readers.deps() });
|
|
1839
|
+
const loaded = await runLoad(route, ctx, deps);
|
|
1840
|
+
if (loaded instanceof Redirect) {
|
|
1841
|
+
return withCookie(new Response(null, { status: 303, headers: { location: loaded.to } }));
|
|
1842
|
+
}
|
|
1843
|
+
if (loaded instanceof NotFound) {
|
|
1844
|
+
if (!opts.notFound || route === opts.notFound) {
|
|
1845
|
+
return withCookie(status404());
|
|
1846
|
+
}
|
|
1847
|
+
return renderPage(req, opts.notFound, params, 404);
|
|
1848
|
+
}
|
|
1849
|
+
const props = { ...params, ...loaded };
|
|
1850
|
+
const meta = await pageMeta(route, ctx, props);
|
|
1851
|
+
const root = ogCard ?? (route.layouts?.length ? composeRoot(route, ctx) : route.component);
|
|
1852
|
+
let entry = null;
|
|
1853
|
+
const stream = { open: false, dirty: false, wake: null };
|
|
1854
|
+
const restore = !setCookie && req.headers.get("x-weft-nav") === "1"
|
|
1855
|
+
? await openHandoff(req.headers.get("x-weft-handoff"), sid, url)
|
|
1856
|
+
: null;
|
|
1857
|
+
let sealed = false;
|
|
1858
|
+
const page = new LivePage(root, props, {
|
|
1859
|
+
...(restore ? { restore } : {}),
|
|
1860
|
+
sealArgs: (action, args) => {
|
|
1861
|
+
sealed = true;
|
|
1862
|
+
return sealHeld(sid, action, args);
|
|
1863
|
+
},
|
|
1864
|
+
onError: (err, msg) => report(err, "event", { route, ctx, ...(msg ? { handler: msg.handler } : {}) }),
|
|
1865
|
+
onInvalidate: () => {
|
|
1866
|
+
if (stream.open) {
|
|
1867
|
+
stream.dirty = true;
|
|
1868
|
+
const wake = stream.wake;
|
|
1869
|
+
stream.wake = null;
|
|
1870
|
+
wake?.();
|
|
1871
|
+
}
|
|
1872
|
+
else if (entry) {
|
|
1873
|
+
schedule(entry, false);
|
|
1874
|
+
}
|
|
1875
|
+
},
|
|
1876
|
+
aroundRender: feed || etagRoute
|
|
1877
|
+
? (render) => {
|
|
1878
|
+
deps.render = deps.render.renew();
|
|
1879
|
+
track(deps.render, render);
|
|
1880
|
+
}
|
|
1881
|
+
: undefined,
|
|
1882
|
+
});
|
|
1883
|
+
let streaming = false;
|
|
1884
|
+
try {
|
|
1885
|
+
let body = withSession(sid, () => page.render());
|
|
1886
|
+
const timeout = opts.streamTimeoutMs ?? 10_000;
|
|
1887
|
+
const streamable = req.method !== "HEAD" && timeout > 0 && page.awaiting;
|
|
1888
|
+
const deadline = now() + timeout;
|
|
1889
|
+
stream.open = streamable;
|
|
1890
|
+
const settle = async () => {
|
|
1891
|
+
while (!stream.dirty) {
|
|
1892
|
+
const left = deadline - now();
|
|
1893
|
+
if (left <= 0 || (entry && pages.get(page.id) !== entry)) {
|
|
1894
|
+
return false;
|
|
1895
|
+
}
|
|
1896
|
+
let timer;
|
|
1897
|
+
await new Promise((resolve) => {
|
|
1898
|
+
stream.wake = resolve;
|
|
1899
|
+
timer = setTimeout(resolve, left);
|
|
1900
|
+
});
|
|
1901
|
+
clearTimeout(timer);
|
|
1902
|
+
stream.wake = null;
|
|
1903
|
+
}
|
|
1904
|
+
stream.dirty = false;
|
|
1905
|
+
await withSession(sid, () => page.refresh());
|
|
1906
|
+
return true;
|
|
1907
|
+
};
|
|
1908
|
+
const endStream = () => {
|
|
1909
|
+
stream.open = false;
|
|
1910
|
+
stream.wake = null;
|
|
1911
|
+
if (oneShot) {
|
|
1912
|
+
page.close();
|
|
1913
|
+
}
|
|
1914
|
+
else if (stream.dirty && entry) {
|
|
1915
|
+
schedule(entry, false);
|
|
1916
|
+
}
|
|
1917
|
+
};
|
|
1918
|
+
if (streamable && (req.headers.get("x-weft-nav") === "1" || printing)) {
|
|
1919
|
+
try {
|
|
1920
|
+
while (page.awaiting && (await settle())) {
|
|
1921
|
+
}
|
|
1922
|
+
body = page.html();
|
|
1923
|
+
}
|
|
1924
|
+
finally {
|
|
1925
|
+
endStream();
|
|
1926
|
+
}
|
|
1927
|
+
}
|
|
1928
|
+
streaming = streamable && stream.open;
|
|
1929
|
+
const readsAny = (d) => d.reads.size > 0 || d.stores.size > 0;
|
|
1930
|
+
const inert = !streaming && page.inert() && !readsAny(deps.load) && !readsAny(deps.render) && !presenceHeld(ctx);
|
|
1931
|
+
const still = !streaming && page.quiet() && !presenceHeld(ctx);
|
|
1932
|
+
const edge = edgeCache !== null && shellShared && inert && !sealed && depth === "page" && status === 200 && !printing &&
|
|
1933
|
+
(req.method === "GET" || req.method === "HEAD") && edgeReason(route, opts) === null && !POSTS.test(body);
|
|
1934
|
+
let cachedTag = null;
|
|
1935
|
+
if (etagRoute && !still) {
|
|
1936
|
+
uncachable.add(route);
|
|
1937
|
+
onError(new Error(`@weft-framework/server: ${url.pathname}: \`cache: "etag"\` is for pages without server event handlers, presence or streaming; serving it uncached`));
|
|
1938
|
+
}
|
|
1939
|
+
else if (etagRoute) {
|
|
1940
|
+
const old = etags.get(cacheKey);
|
|
1941
|
+
if (old)
|
|
1942
|
+
purge(old);
|
|
1943
|
+
const rec = {
|
|
1944
|
+
key: cacheKey,
|
|
1945
|
+
tag: randomId(12),
|
|
1946
|
+
until: now() + ETAG_TTL,
|
|
1947
|
+
sid,
|
|
1948
|
+
deps: deps,
|
|
1949
|
+
};
|
|
1950
|
+
rec.deps.load.adopt(rec);
|
|
1951
|
+
rec.deps.render.adopt(rec);
|
|
1952
|
+
etags.set(cacheKey, rec);
|
|
1953
|
+
while (etags.size > ETAG_MAX)
|
|
1954
|
+
purge(etags.values().next().value);
|
|
1955
|
+
cachedTag = rec.tag;
|
|
1956
|
+
}
|
|
1957
|
+
if (opts.regions && !opts.regions.isPrimary && depth === "page" && !inert && !still) {
|
|
1958
|
+
page.close();
|
|
1959
|
+
opts.regions.remember(route);
|
|
1960
|
+
return await opts.regions.forward(req);
|
|
1961
|
+
}
|
|
1962
|
+
const noLive = inert || (etagRoute && still);
|
|
1963
|
+
const critical = page.styles().join("");
|
|
1964
|
+
if (noLive && !oneShot) {
|
|
1965
|
+
page.close();
|
|
1966
|
+
}
|
|
1967
|
+
if (oneShot && !streaming) {
|
|
1968
|
+
page.close();
|
|
1969
|
+
}
|
|
1970
|
+
if (stateless) {
|
|
1971
|
+
if (/ data-weft-on-[a-z]/.test(body) && !deadHandlers.has(route)) {
|
|
1972
|
+
deadHandlers.add(route);
|
|
1973
|
+
onError(new Error(`@weft-framework/server: ${new URL(req.url).pathname} binds server event handlers, ` +
|
|
1974
|
+
"which a stateless host (transports: []) cannot run; use actions or client functions"));
|
|
1975
|
+
}
|
|
1976
|
+
}
|
|
1977
|
+
else if (!noLive && !oneShot) {
|
|
1978
|
+
entry = {
|
|
1979
|
+
page,
|
|
1980
|
+
sid,
|
|
1981
|
+
seen: 0,
|
|
1982
|
+
route,
|
|
1983
|
+
ctx,
|
|
1984
|
+
deps,
|
|
1985
|
+
sinks: new Set(),
|
|
1986
|
+
attached: 0,
|
|
1987
|
+
stale: false,
|
|
1988
|
+
version: 0,
|
|
1989
|
+
foreign: false,
|
|
1990
|
+
reload: false,
|
|
1991
|
+
timer: null,
|
|
1992
|
+
head: headOf(meta, req),
|
|
1993
|
+
awayTimer: null,
|
|
1994
|
+
};
|
|
1995
|
+
if (opts.devtools) {
|
|
1996
|
+
entry.dev = devLog();
|
|
1997
|
+
frame(entry.dev, "the page opened", pageHtml(entry));
|
|
1998
|
+
entry.cost = { events: 0, refreshes: 0, ms: 0, bytes: 0, dataBytes: jsonBytes(props) };
|
|
1999
|
+
}
|
|
2000
|
+
else if (watched.size > 0 && watching(keyOf(entry))) {
|
|
2001
|
+
entry.dev = devLog();
|
|
2002
|
+
frame(entry.dev, "the page opened", pageHtml(entry));
|
|
2003
|
+
}
|
|
2004
|
+
register(entry);
|
|
2005
|
+
}
|
|
2006
|
+
const nonce = randomId(16);
|
|
2007
|
+
const csrf = edge ? "" : await csrfToken(key, sid);
|
|
2008
|
+
const script = assets.has(clientEntry) && !inert
|
|
2009
|
+
? `<script type="module" nonce="${nonce}" src="${escapeAttr(clientEntry)}"></script>`
|
|
2010
|
+
: "";
|
|
2011
|
+
const transport = wsEnabled || oneShot || noLive ? "" : `<meta name="weft-transport" content="sse">`;
|
|
2012
|
+
const live = oneShot || noLive ? "" : `<meta name="weft-live" content="${escapeAttr(page.id)}">`;
|
|
2013
|
+
const bundle = styleBundle();
|
|
2014
|
+
const next = inert ? [] : likelyFrom(route, body, url);
|
|
2015
|
+
const likelyMeta = next.length ? `<meta name="weft-likely" content="${escapeAttr(next.join(" "))}">` : "";
|
|
2016
|
+
const head = `${META_START}${renderMeta(meta, { nonce })}${META_END}` +
|
|
2017
|
+
live +
|
|
2018
|
+
(edge ? "" : `<meta name="weft-csrf" content="${escapeAttr(csrf)}">`) +
|
|
2019
|
+
`${transport}${likelyMeta}${appCssLink}` +
|
|
2020
|
+
`<style nonce="${nonce}">weft-c{display:contents}${critical}</style>${script}`;
|
|
2021
|
+
const tail = bundle ? `<link rel="stylesheet" href="${STYLES}?v=${bundle.version}">` : "";
|
|
2022
|
+
const mark = `<!--weft-stream-${randomId(12)}-->`;
|
|
2023
|
+
const asked = edge ? new Request(req.url) : req;
|
|
2024
|
+
let html = shell.render({
|
|
2025
|
+
lang: langOf(meta, asked),
|
|
2026
|
+
head,
|
|
2027
|
+
body: body + tail + (streaming ? mark : ""),
|
|
2028
|
+
nonce,
|
|
2029
|
+
html: htmlAttributeMarkup(opts.htmlAttributes?.(asked)),
|
|
2030
|
+
});
|
|
2031
|
+
const hashed = edge ? hashInline(html, nonce) : null;
|
|
2032
|
+
if (edge && !hashed) {
|
|
2033
|
+
shellShared = false;
|
|
2034
|
+
return renderDocument(req, route, params, status, depth, () => undefined);
|
|
2035
|
+
}
|
|
2036
|
+
if (hashed) {
|
|
2037
|
+
html = hashed.html;
|
|
2038
|
+
const tag = `"${createHash("sha256").update(html).digest("base64url").slice(0, 27)}"`;
|
|
2039
|
+
const headers = new Headers({
|
|
2040
|
+
"content-type": "text/html; charset=utf-8",
|
|
2041
|
+
"cache-control": `public, max-age=0, s-maxage=${edgeCache.maxAge}, stale-while-revalidate=${edgeCache.stale}`,
|
|
2042
|
+
etag: tag,
|
|
2043
|
+
...securityHeaders({
|
|
2044
|
+
nonce: "",
|
|
2045
|
+
hashes: hashed,
|
|
2046
|
+
secure,
|
|
2047
|
+
sources: cspSourcesOf(route),
|
|
2048
|
+
...(onCspReport ? { report: CSP_REPORT } : {}),
|
|
2049
|
+
}),
|
|
2050
|
+
});
|
|
2051
|
+
const fresh = matchesTag(req.headers.get("if-none-match"), tag.slice(1, -1));
|
|
2052
|
+
const res = stamped(req, new Response(fresh || req.method === "HEAD" ? null : html, { status: fresh ? 304 : 200, headers }), secure);
|
|
2053
|
+
res.headers.delete("set-cookie");
|
|
2054
|
+
return res;
|
|
2055
|
+
}
|
|
2056
|
+
const headers = new Headers({
|
|
2057
|
+
"content-type": "text/html; charset=utf-8",
|
|
2058
|
+
"cache-control": "no-store",
|
|
2059
|
+
...securityHeaders({ nonce, secure, sources: cspSourcesOf(route), ...(onCspReport ? { report: CSP_REPORT } : {}) }),
|
|
2060
|
+
});
|
|
2061
|
+
if (cachedTag !== null) {
|
|
2062
|
+
headers.set("cache-control", "private, no-cache");
|
|
2063
|
+
headers.set("etag", `"${cachedTag}"`);
|
|
2064
|
+
headers.set("vary", "Cookie, Accept-Language");
|
|
2065
|
+
}
|
|
2066
|
+
if (emailAuth && url.pathname === emailAuth.page) {
|
|
2067
|
+
headers.set("referrer-policy", "no-referrer");
|
|
2068
|
+
}
|
|
2069
|
+
const httpStatus = depth === "error" ? 500 : (route.status ?? status);
|
|
2070
|
+
if (!streaming) {
|
|
2071
|
+
return withCookie(new Response(req.method === "HEAD" ? null : html, { status: httpStatus, headers }));
|
|
2072
|
+
}
|
|
2073
|
+
headers.set("x-accel-buffering", "no");
|
|
2074
|
+
const cut = html.indexOf(mark);
|
|
2075
|
+
const [shellStart, shellEnd] = [html.slice(0, cut), html.slice(cut + mark.length)];
|
|
2076
|
+
const rootSel = JSON.stringify(`weft-c[data-weft-c="${page.rootId}"]`);
|
|
2077
|
+
const fill = `<script nonce="${nonce}">(function(){var s=document.currentScript,t=s.previousElementSibling,` +
|
|
2078
|
+
`r=document.querySelector(${rootSel.replace(/</g, "\\u003c")});` +
|
|
2079
|
+
`if(t&&r)r.replaceWith(t.content);if(t)t.remove();s.remove()})()</script>`;
|
|
2080
|
+
let cancelled = false;
|
|
2081
|
+
const chunks = new ReadableStream({
|
|
2082
|
+
start(controller) {
|
|
2083
|
+
controller.enqueue(enc.encode(shellStart));
|
|
2084
|
+
},
|
|
2085
|
+
async pull(controller) {
|
|
2086
|
+
try {
|
|
2087
|
+
while (!cancelled && page.awaiting && (await settle())) {
|
|
2088
|
+
if (cancelled) {
|
|
2089
|
+
break;
|
|
2090
|
+
}
|
|
2091
|
+
controller.enqueue(enc.encode(`<template data-weft-stream>${page.html()}</template>${fill}`));
|
|
2092
|
+
}
|
|
2093
|
+
}
|
|
2094
|
+
catch (err) {
|
|
2095
|
+
onError(err);
|
|
2096
|
+
}
|
|
2097
|
+
endStream();
|
|
2098
|
+
if (!cancelled) {
|
|
2099
|
+
controller.enqueue(enc.encode(shellEnd));
|
|
2100
|
+
controller.close();
|
|
2101
|
+
}
|
|
2102
|
+
},
|
|
2103
|
+
cancel() {
|
|
2104
|
+
cancelled = true;
|
|
2105
|
+
stream.dirty = true;
|
|
2106
|
+
stream.wake?.();
|
|
2107
|
+
},
|
|
2108
|
+
});
|
|
2109
|
+
return withCookie(new Response(chunks, { status: httpStatus, headers }));
|
|
2110
|
+
}
|
|
2111
|
+
catch (err) {
|
|
2112
|
+
if (streaming) {
|
|
2113
|
+
stream.open = false;
|
|
2114
|
+
if (oneShot) {
|
|
2115
|
+
page.close();
|
|
2116
|
+
}
|
|
2117
|
+
}
|
|
2118
|
+
if (entry && pages.get(page.id) === entry) {
|
|
2119
|
+
drop(page.id);
|
|
2120
|
+
}
|
|
2121
|
+
else {
|
|
2122
|
+
page.close();
|
|
2123
|
+
}
|
|
2124
|
+
throw err;
|
|
2125
|
+
}
|
|
2126
|
+
}
|
|
2127
|
+
async function pageMeta(route, ctx, props) {
|
|
2128
|
+
const metas = [opts.meta];
|
|
2129
|
+
await withSession(ctx.session, async () => {
|
|
2130
|
+
for (const l of route.layouts ?? []) {
|
|
2131
|
+
metas.push(await resolveMeta(l.meta, ctx, undefined));
|
|
2132
|
+
}
|
|
2133
|
+
metas.push(route.title !== undefined ? { title: route.title } : undefined);
|
|
2134
|
+
if (route.og) {
|
|
2135
|
+
const image = ctx.url.pathname === "/" ? "/.og.png" : `${ctx.url.pathname.replace(/\/+$/, "")}.og.png`;
|
|
2136
|
+
metas.push({ openGraph: { image }, twitter: { card: "summary_large_image", image } });
|
|
2137
|
+
}
|
|
2138
|
+
metas.push(await resolveMeta(route.meta, ctx, props));
|
|
2139
|
+
});
|
|
2140
|
+
return applySite(mergeMeta(...metas), opts.siteUrl);
|
|
2141
|
+
}
|
|
2142
|
+
function headOf(meta, req) {
|
|
2143
|
+
return { meta: renderMeta(meta), title: resolveTitle(meta), lang: langOf(meta, req) };
|
|
2144
|
+
}
|
|
2145
|
+
function langOf(meta, req) {
|
|
2146
|
+
if (meta.lang === undefined && opts.htmlAttributes) {
|
|
2147
|
+
const lang = opts.htmlAttributes(req).lang;
|
|
2148
|
+
if (typeof lang === "string")
|
|
2149
|
+
return resolveLang({ lang });
|
|
2150
|
+
}
|
|
2151
|
+
return resolveLang(meta);
|
|
2152
|
+
}
|
|
2153
|
+
async function runLoad(route, ctx, deps) {
|
|
2154
|
+
if (!route.load) {
|
|
2155
|
+
return {};
|
|
2156
|
+
}
|
|
2157
|
+
const load = route.load;
|
|
2158
|
+
let loaded;
|
|
2159
|
+
try {
|
|
2160
|
+
if (feed) {
|
|
2161
|
+
deps.load = deps.load.renew();
|
|
2162
|
+
presenceBegin(ctx);
|
|
2163
|
+
try {
|
|
2164
|
+
loaded = await withSession(ctx.session, () => track(deps.load, () => load(ctx)));
|
|
2165
|
+
}
|
|
2166
|
+
catch (err) {
|
|
2167
|
+
if (err instanceof Redirect || err instanceof NotFound)
|
|
2168
|
+
presenceEnd(ctx);
|
|
2169
|
+
throw err;
|
|
2170
|
+
}
|
|
2171
|
+
presenceEnd(ctx);
|
|
2172
|
+
}
|
|
2173
|
+
else {
|
|
2174
|
+
loaded = await withSession(ctx.session, () => load(ctx));
|
|
2175
|
+
}
|
|
2176
|
+
}
|
|
2177
|
+
catch (err) {
|
|
2178
|
+
if (!(err instanceof Redirect) && !(err instanceof NotFound)) {
|
|
2179
|
+
throw err;
|
|
2180
|
+
}
|
|
2181
|
+
loaded = err;
|
|
2182
|
+
}
|
|
2183
|
+
if (loaded instanceof Redirect && !isSafePath(loaded.to)) {
|
|
2184
|
+
throw new Error(`@weft-framework/server: redirect target must be a same-origin path: ${loaded.to}`);
|
|
2185
|
+
}
|
|
2186
|
+
return loaded;
|
|
2187
|
+
}
|
|
2188
|
+
const devDecisions = new Map();
|
|
2189
|
+
const devList = (sid) => {
|
|
2190
|
+
let list = devDecisions.get(sid);
|
|
2191
|
+
if (!list) {
|
|
2192
|
+
if (devDecisions.size >= 256)
|
|
2193
|
+
devDecisions.delete(devDecisions.keys().next().value);
|
|
2194
|
+
list = [];
|
|
2195
|
+
devDecisions.set(sid, list);
|
|
2196
|
+
}
|
|
2197
|
+
return list;
|
|
2198
|
+
};
|
|
2199
|
+
const devNote = (sid, action, actor) => note(devList(sid), { at: now(), model: "(view as)", action, outcome: "allowed", count: 0, actor });
|
|
2200
|
+
const unaudit = opts.devtools
|
|
2201
|
+
? audit((ev) => {
|
|
2202
|
+
const sid = currentSession();
|
|
2203
|
+
if (sid === undefined)
|
|
2204
|
+
return;
|
|
2205
|
+
note(devList(sid), decision(ev));
|
|
2206
|
+
}, { reads: true })
|
|
2207
|
+
: null;
|
|
2208
|
+
function costOf(e) {
|
|
2209
|
+
const held = (x) => x.page.html().length * 2 + (x.cost?.dataBytes ?? 0);
|
|
2210
|
+
const c = e.cost ?? { events: 0, refreshes: 0, ms: 0, bytes: 0, dataBytes: 0 };
|
|
2211
|
+
const cost = { events: c.events, refreshes: c.refreshes, ms: Math.round(c.ms * 100) / 100, bytes: c.bytes, heldBytes: held(e) };
|
|
2212
|
+
const proc = globalThis.process;
|
|
2213
|
+
const v8 = proc?.getBuiltinModule?.("node:v8");
|
|
2214
|
+
let limit = v8?.getHeapStatistics?.().heap_size_limit ?? null;
|
|
2215
|
+
if (degrade?.heapBytes !== undefined)
|
|
2216
|
+
limit = limit === null ? degrade.heapBytes : Math.min(limit, degrade.heapBytes);
|
|
2217
|
+
const used = proc?.memoryUsage?.().heapUsed ?? null;
|
|
2218
|
+
if (limit === null || used === null)
|
|
2219
|
+
return { cost, capacity: null };
|
|
2220
|
+
let total = 0;
|
|
2221
|
+
let count = 0;
|
|
2222
|
+
for (const x of pages.values()) {
|
|
2223
|
+
if (x.route === e.route) {
|
|
2224
|
+
total += held(x);
|
|
2225
|
+
count++;
|
|
2226
|
+
}
|
|
2227
|
+
}
|
|
2228
|
+
const perPage = Math.max(1, Math.round(total / Math.max(1, count)));
|
|
2229
|
+
const free = Math.max(0, limit - used);
|
|
2230
|
+
return { cost, capacity: { route: patternOf.get(e.route) ?? "unknown", heapLimit: limit, heapUsed: used, perPage, pages: Math.floor(free / perPage) } };
|
|
2231
|
+
}
|
|
2232
|
+
async function devViewAs(req) {
|
|
2233
|
+
if (req.method !== "POST")
|
|
2234
|
+
return status(405);
|
|
2235
|
+
if (!sameOrigin(req) || !(req.headers.get("content-type") ?? "").startsWith("application/json"))
|
|
2236
|
+
return status(403);
|
|
2237
|
+
const sid = await sessionOf(req);
|
|
2238
|
+
const rec = sid ? await authStore.get(sid) : undefined;
|
|
2239
|
+
const answer = (body, code = 200) => new Response(JSON.stringify(body), {
|
|
2240
|
+
status: code,
|
|
2241
|
+
headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" },
|
|
2242
|
+
});
|
|
2243
|
+
if (!sid || !rec || rec.pending)
|
|
2244
|
+
return answer({ ok: false, reason: "Sign in first: view as works for a signed-in session." }, 409);
|
|
2245
|
+
let body;
|
|
2246
|
+
try {
|
|
2247
|
+
const text = await req.text();
|
|
2248
|
+
if (text.length > 4096)
|
|
2249
|
+
return status(413);
|
|
2250
|
+
body = JSON.parse(text);
|
|
2251
|
+
}
|
|
2252
|
+
catch {
|
|
2253
|
+
return status(400);
|
|
2254
|
+
}
|
|
2255
|
+
if (body.user === null) {
|
|
2256
|
+
if (rec.viewAs?.dev) {
|
|
2257
|
+
const { viewAs: _gone, ...kept } = rec;
|
|
2258
|
+
await authStore.set(sid, kept);
|
|
2259
|
+
reloadSession(sid, await userOf(sid));
|
|
2260
|
+
devNote(sid, "stop", `id ${rec.user}`);
|
|
2261
|
+
}
|
|
2262
|
+
return answer({ ok: true, viewing: null });
|
|
2263
|
+
}
|
|
2264
|
+
const user = body.user;
|
|
2265
|
+
const tenant = body.tenant;
|
|
2266
|
+
if (typeof user !== "string" || user === "" || user.length > 256)
|
|
2267
|
+
return answer({ ok: false, reason: "Give a user id." }, 400);
|
|
2268
|
+
if (tenant !== undefined && (typeof tenant !== "string" || tenant === "" || tenant.length > 256)) {
|
|
2269
|
+
return answer({ ok: false, reason: "A tenant is an id." }, 400);
|
|
2270
|
+
}
|
|
2271
|
+
if (rec.viewAs && !rec.viewAs.dev)
|
|
2272
|
+
return answer({ ok: false, reason: "This session is already viewing as someone." }, 409);
|
|
2273
|
+
const v = { user, until: now() + DEV_VIEW_MS, dev: true };
|
|
2274
|
+
if (tenant !== undefined)
|
|
2275
|
+
v.tenant = tenant;
|
|
2276
|
+
const seen = await viewedBy(rec.user, v, now());
|
|
2277
|
+
if (!seen) {
|
|
2278
|
+
const why = user === rec.user ? "That is you." : "The app does not know that user (in that tenant).";
|
|
2279
|
+
return answer({ ok: false, reason: why }, 404);
|
|
2280
|
+
}
|
|
2281
|
+
await authStore.set(sid, { ...rec, viewAs: v });
|
|
2282
|
+
reloadSession(sid, seen);
|
|
2283
|
+
devNote(sid, "start", `id ${user} (via id ${rec.user})`);
|
|
2284
|
+
return answer({ ok: true, viewing: { user, ...(tenant !== undefined ? { tenant } : {}), until: v.until } });
|
|
2285
|
+
}
|
|
2286
|
+
function reloadSession(sid, actor) {
|
|
2287
|
+
for (const e of pages.values()) {
|
|
2288
|
+
if (e.sid === sid) {
|
|
2289
|
+
e.ctx.user = actor;
|
|
2290
|
+
because(e, "the session's actor changed (view as)");
|
|
2291
|
+
schedule(e, true);
|
|
2292
|
+
}
|
|
2293
|
+
}
|
|
2294
|
+
}
|
|
2295
|
+
function pageHtml(e) {
|
|
2296
|
+
const cur = e.page.current();
|
|
2297
|
+
return cur.t === "patch" ? cur.html : "";
|
|
2298
|
+
}
|
|
2299
|
+
function devRecording(e) {
|
|
2300
|
+
const rec = {
|
|
2301
|
+
weft: "recording",
|
|
2302
|
+
v: 1,
|
|
2303
|
+
path: redactPath(e.ctx.url),
|
|
2304
|
+
actor: actorLabel(e.ctx.user),
|
|
2305
|
+
at: e.dev?.opened ?? Date.now(),
|
|
2306
|
+
steps: e.dev?.steps ?? [],
|
|
2307
|
+
};
|
|
2308
|
+
return new Response(JSON.stringify(rec, null, 2) + "\n", {
|
|
2309
|
+
headers: {
|
|
2310
|
+
"content-type": "application/json; charset=utf-8",
|
|
2311
|
+
"content-disposition": 'attachment; filename="page.weft-recording.json"',
|
|
2312
|
+
"cache-control": "no-store",
|
|
2313
|
+
"x-content-type-options": "nosniff",
|
|
2314
|
+
},
|
|
2315
|
+
});
|
|
2316
|
+
}
|
|
2317
|
+
function devFrame(e, n) {
|
|
2318
|
+
const f = e.dev?.frames.find((x) => x.n === n);
|
|
2319
|
+
if (!f)
|
|
2320
|
+
return status(404);
|
|
2321
|
+
return new Response(JSON.stringify({ n: f.n, at: f.at, what: f.what, html: f.html }), {
|
|
2322
|
+
headers: {
|
|
2323
|
+
"content-type": "application/json; charset=utf-8",
|
|
2324
|
+
"cache-control": "no-store",
|
|
2325
|
+
"x-content-type-options": "nosniff",
|
|
2326
|
+
},
|
|
2327
|
+
});
|
|
2328
|
+
}
|
|
2329
|
+
const watched = new Map();
|
|
2330
|
+
const keyOf = (e) => (e.sidKey ??= sessionKey(e.sid));
|
|
2331
|
+
const watching = (key) => (watched.get(key)?.until ?? 0) > now();
|
|
2332
|
+
const unwatch = (key) => {
|
|
2333
|
+
const w = watched.get(key);
|
|
2334
|
+
if (w)
|
|
2335
|
+
clearTimeout(w.timer);
|
|
2336
|
+
watched.delete(key);
|
|
2337
|
+
if (opts.devtools)
|
|
2338
|
+
return;
|
|
2339
|
+
for (const e of pages.values())
|
|
2340
|
+
if (keyOf(e) === key)
|
|
2341
|
+
e.dev = undefined;
|
|
2342
|
+
};
|
|
2343
|
+
const removeHub = addInspectHub({
|
|
2344
|
+
pages: (key) => [...pages.values()].filter((e) => keyOf(e) === key).map((e) => ({ page: e.page.id, path: e.ctx.url.pathname })),
|
|
2345
|
+
watch(key, until) {
|
|
2346
|
+
if (until <= now()) {
|
|
2347
|
+
unwatch(key);
|
|
2348
|
+
return;
|
|
2349
|
+
}
|
|
2350
|
+
const old = watched.get(key);
|
|
2351
|
+
if (old)
|
|
2352
|
+
clearTimeout(old.timer);
|
|
2353
|
+
const timer = setTimeout(() => unwatch(key), Math.min(until - now(), 2 ** 31 - 1));
|
|
2354
|
+
timer.unref?.();
|
|
2355
|
+
watched.set(key, { until, timer });
|
|
2356
|
+
for (const e of pages.values()) {
|
|
2357
|
+
if (!e.dev && keyOf(e) === key) {
|
|
2358
|
+
e.dev = devLog();
|
|
2359
|
+
frame(e.dev, "inspection started", pageHtml(e));
|
|
2360
|
+
}
|
|
2361
|
+
}
|
|
2362
|
+
},
|
|
2363
|
+
view(key, page) {
|
|
2364
|
+
const e = pages.get(page);
|
|
2365
|
+
if (!e?.dev || keyOf(e) !== key || !watching(key))
|
|
2366
|
+
return null;
|
|
2367
|
+
return {
|
|
2368
|
+
page,
|
|
2369
|
+
path: e.ctx.url.pathname,
|
|
2370
|
+
tree: e.page.inspect(),
|
|
2371
|
+
messages: e.dev.messages,
|
|
2372
|
+
frames: frameList(e.dev),
|
|
2373
|
+
reads: { load: readsOf(e.deps.load), render: readsOf(e.deps.render) },
|
|
2374
|
+
};
|
|
2375
|
+
},
|
|
2376
|
+
frame(key, page, n) {
|
|
2377
|
+
const e = pages.get(page);
|
|
2378
|
+
if (!e?.dev || keyOf(e) !== key || !watching(key))
|
|
2379
|
+
return null;
|
|
2380
|
+
const f = e.dev.frames.find((x) => x.n === n);
|
|
2381
|
+
return f ? { n: f.n, at: f.at, what: f.what, html: f.html } : null;
|
|
2382
|
+
},
|
|
2383
|
+
});
|
|
2384
|
+
function inspect(e) {
|
|
2385
|
+
const seeing = viewingAs(e.ctx);
|
|
2386
|
+
const snap = {
|
|
2387
|
+
viewing: seeing ? { user: seeing.user, operator: seeing.operator, until: seeing.until, ...(seeing.tenant ? { tenant: seeing.tenant } : {}) } : null,
|
|
2388
|
+
lid: e.page.id,
|
|
2389
|
+
path: e.ctx.url.pathname,
|
|
2390
|
+
tree: e.page.inspect(),
|
|
2391
|
+
messages: e.dev?.messages ?? [],
|
|
2392
|
+
frames: frameList(e.dev),
|
|
2393
|
+
decisions: devDecisions.get(e.sid) ?? [],
|
|
2394
|
+
reads: { load: readsOf(e.deps.load), render: readsOf(e.deps.render) },
|
|
2395
|
+
stores: e.deps.load.stores.size,
|
|
2396
|
+
...costOf(e),
|
|
2397
|
+
};
|
|
2398
|
+
return new Response(JSON.stringify(snap), {
|
|
2399
|
+
headers: {
|
|
2400
|
+
"content-type": "application/json; charset=utf-8",
|
|
2401
|
+
"cache-control": "no-store",
|
|
2402
|
+
"x-content-type-options": "nosniff",
|
|
2403
|
+
},
|
|
2404
|
+
});
|
|
2405
|
+
}
|
|
2406
|
+
const feed = opts.sync === false || stateless ? null : (opts.sync ?? changes);
|
|
2407
|
+
const syncDelay = opts.syncDelayMs ?? 15;
|
|
2408
|
+
const unwatchStores = feed
|
|
2409
|
+
? onStoreWrite((store, sid) => {
|
|
2410
|
+
for (const r of cacheReaders.readersOfStore(store)) {
|
|
2411
|
+
if (store.scope === "app" || r.sid === sid)
|
|
2412
|
+
purge(r);
|
|
2413
|
+
}
|
|
2414
|
+
for (const e of readers.readersOfStore(store)) {
|
|
2415
|
+
if (e.deps.load.stores.has(store) && (store.scope === "app" || e.sid === sid)) {
|
|
2416
|
+
because(e, `${store.scope} store ${store.name} written (read in load)`);
|
|
2417
|
+
schedule(e, true);
|
|
2418
|
+
}
|
|
2419
|
+
}
|
|
2420
|
+
})
|
|
2421
|
+
: null;
|
|
2422
|
+
const unGap = feed?.onGap(() => {
|
|
2423
|
+
for (const r of [...etags.values()])
|
|
2424
|
+
purge(r);
|
|
2425
|
+
for (const e of pages.values()) {
|
|
2426
|
+
if (e.deps.load.reads.size > 0 || e.deps.render.reads.size > 0) {
|
|
2427
|
+
because(e, "changes from other instances may have been missed (feed gap)");
|
|
2428
|
+
schedule(e, true);
|
|
2429
|
+
}
|
|
2430
|
+
}
|
|
2431
|
+
});
|
|
2432
|
+
const unNotices = stateless
|
|
2433
|
+
? null
|
|
2434
|
+
: addNoticeHub((model, row, notice, self) => {
|
|
2435
|
+
const key = row[model.key];
|
|
2436
|
+
const change = { model: model.name, op: "update", key, before: row, after: row };
|
|
2437
|
+
const sid = self ? undefined : currentSession();
|
|
2438
|
+
const msg = notice.data === undefined
|
|
2439
|
+
? { t: "notice", text: notice.text, kind: notice.kind }
|
|
2440
|
+
: { t: "notice", text: notice.text, kind: notice.kind, data: notice.data };
|
|
2441
|
+
let n = 0;
|
|
2442
|
+
for (const e of readers.readersOf(model.name)) {
|
|
2443
|
+
if (e.sid === sid || e.sinks.size === 0)
|
|
2444
|
+
continue;
|
|
2445
|
+
if (e.deps.load.admits(change) || e.deps.render.admits(change)) {
|
|
2446
|
+
send(e, msg);
|
|
2447
|
+
n++;
|
|
2448
|
+
}
|
|
2449
|
+
}
|
|
2450
|
+
return n;
|
|
2451
|
+
});
|
|
2452
|
+
const unsubscribe = feed?.subscribe((change) => {
|
|
2453
|
+
sharedChange(change);
|
|
2454
|
+
for (const r of cacheReaders.readersOf(change.model)) {
|
|
2455
|
+
if (r.deps.load.concerns(change) || r.deps.render.concerns(change))
|
|
2456
|
+
purge(r);
|
|
2457
|
+
}
|
|
2458
|
+
for (const e of readers.readersOf(change.model)) {
|
|
2459
|
+
const inLoad = e.deps.load.concerns(change);
|
|
2460
|
+
if (inLoad || e.deps.render.concerns(change)) {
|
|
2461
|
+
if (e.dev)
|
|
2462
|
+
because(e, changeCause(change, inLoad ? "load" : "render"));
|
|
2463
|
+
schedule(e, true);
|
|
2464
|
+
}
|
|
2465
|
+
}
|
|
2466
|
+
});
|
|
2467
|
+
const dispatching = new Set();
|
|
2468
|
+
function schedule(e, reload) {
|
|
2469
|
+
e.reload ||= reload;
|
|
2470
|
+
if (reload && !dispatching.has(e))
|
|
2471
|
+
e.foreign = true;
|
|
2472
|
+
if (e.timer === null) {
|
|
2473
|
+
e.timer = setTimeout(() => void refresh(e), syncDelay);
|
|
2474
|
+
e.timer.unref?.();
|
|
2475
|
+
}
|
|
2476
|
+
}
|
|
2477
|
+
function send(e, msg) {
|
|
2478
|
+
for (const sink of e.sinks) {
|
|
2479
|
+
sink(msg);
|
|
2480
|
+
}
|
|
2481
|
+
}
|
|
2482
|
+
function sharedOn(e, msg) {
|
|
2483
|
+
sharedMessage(e, e.ctx.user, msg, (m) => send(e, m), {
|
|
2484
|
+
...opts.sharedFields,
|
|
2485
|
+
onError: (err) => report(err, "event", { route: e.route, ctx: e.ctx, handler: "(shared field)" }),
|
|
2486
|
+
});
|
|
2487
|
+
}
|
|
2488
|
+
async function dispatchTo(e, sid, msg, req) {
|
|
2489
|
+
const stale = (msg.base ?? 0) !== e.version || e.foreign;
|
|
2490
|
+
if (msg.queued)
|
|
2491
|
+
msg.event.queued = true;
|
|
2492
|
+
if (stale)
|
|
2493
|
+
msg.event.stale = true;
|
|
2494
|
+
if (msg.queued && stale && staleMode === "refuse") {
|
|
2495
|
+
return [{ t: "conflict", ack: msg.seq, reason: "stale" }];
|
|
2496
|
+
}
|
|
2497
|
+
const started = performance.now();
|
|
2498
|
+
let span = null;
|
|
2499
|
+
if (telemetry?.span) {
|
|
2500
|
+
try {
|
|
2501
|
+
const component = e.page.componentOf(msg.id) ?? "unknown";
|
|
2502
|
+
const handler = component === "unknown" ? "unknown" : msg.handler;
|
|
2503
|
+
const attrs = { "weft.component": component, "weft.handler": handler };
|
|
2504
|
+
span = telemetry.span(`event ${component}.${handler}`, {
|
|
2505
|
+
parent: (req && traces.get(req)) ?? null,
|
|
2506
|
+
attributes: { ...attrs, "http.route": patternOf.get(e.route) },
|
|
2507
|
+
metric: { name: "weft.live.event.duration", attributes: attrs },
|
|
2508
|
+
});
|
|
2509
|
+
}
|
|
2510
|
+
catch (err) {
|
|
2511
|
+
onError(err);
|
|
2512
|
+
}
|
|
2513
|
+
}
|
|
2514
|
+
let outs;
|
|
2515
|
+
const scope = newScope(span ? span.context : null);
|
|
2516
|
+
const run = () => withSession(sid, () => e.page.dispatch(msg));
|
|
2517
|
+
dispatching.add(e);
|
|
2518
|
+
try {
|
|
2519
|
+
outs = await (scope ? readScope.run(scope, run) : run());
|
|
2520
|
+
}
|
|
2521
|
+
catch (err) {
|
|
2522
|
+
span?.end({ error: err });
|
|
2523
|
+
throw err;
|
|
2524
|
+
}
|
|
2525
|
+
finally {
|
|
2526
|
+
dispatching.delete(e);
|
|
2527
|
+
if (scope)
|
|
2528
|
+
scope.open = false;
|
|
2529
|
+
}
|
|
2530
|
+
if (span) {
|
|
2531
|
+
const failed = outs.find((o) => o.t === "error");
|
|
2532
|
+
span.end(failed ? { error: new Error(failed.message) } : {});
|
|
2533
|
+
}
|
|
2534
|
+
charge(e, "events", performance.now() - started, outs);
|
|
2535
|
+
if (patchBudget !== false || scope?.models) {
|
|
2536
|
+
const component = e.page.componentOf(msg.id);
|
|
2537
|
+
const cause = component === undefined ? "unknown.unknown" : `${component}.${msg.handler}`;
|
|
2538
|
+
checkBudget(e, cause, outs);
|
|
2539
|
+
if (scope)
|
|
2540
|
+
checkReads(scope, patternOf.get(e.route) ?? "unknown", cause, e.dev);
|
|
2541
|
+
}
|
|
2542
|
+
if (e.dev) {
|
|
2543
|
+
note(e.dev.messages, {
|
|
2544
|
+
at: Date.now(),
|
|
2545
|
+
dir: "in",
|
|
2546
|
+
what: `${msg.event.type} -> ${msg.handler} on ${msg.id}`,
|
|
2547
|
+
ms: Math.round((performance.now() - started) * 100) / 100,
|
|
2548
|
+
out: outs.map(describe),
|
|
2549
|
+
});
|
|
2550
|
+
if (outs.some((o) => o.t === "patch"))
|
|
2551
|
+
frame(e.dev, `${msg.event.type} -> ${msg.handler}`, pageHtml(e));
|
|
2552
|
+
if (e.dev.steps.length < RECORDING_MAX) {
|
|
2553
|
+
e.dev.steps.push({
|
|
2554
|
+
at: Date.now() - e.dev.opened,
|
|
2555
|
+
id: msg.id,
|
|
2556
|
+
handler: msg.handler,
|
|
2557
|
+
event: redactPayload(msg.event),
|
|
2558
|
+
...(msg.args !== undefined ? { args: msg.args } : {}),
|
|
2559
|
+
outcome: outcomeOf(outs),
|
|
2560
|
+
});
|
|
2561
|
+
}
|
|
2562
|
+
}
|
|
2563
|
+
return outs;
|
|
2564
|
+
}
|
|
2565
|
+
async function refresh(e) {
|
|
2566
|
+
e.timer = null;
|
|
2567
|
+
if (pages.get(e.page.id) !== e) {
|
|
2568
|
+
return;
|
|
2569
|
+
}
|
|
2570
|
+
if (e.sinks.size === 0) {
|
|
2571
|
+
e.stale = true;
|
|
2572
|
+
return;
|
|
2573
|
+
}
|
|
2574
|
+
e.stale = false;
|
|
2575
|
+
const withLoad = e.reload;
|
|
2576
|
+
e.reload = false;
|
|
2577
|
+
const foreign = e.foreign;
|
|
2578
|
+
e.foreign = false;
|
|
2579
|
+
const why = e.why ?? [];
|
|
2580
|
+
e.why = undefined;
|
|
2581
|
+
const reload = async () => {
|
|
2582
|
+
if (!e.route.load) {
|
|
2583
|
+
return { props: { ...e.ctx.params } };
|
|
2584
|
+
}
|
|
2585
|
+
const loaded = await runLoad(e.route, e.ctx, e.deps);
|
|
2586
|
+
if (loaded instanceof Redirect) {
|
|
2587
|
+
return { message: { t: "redirect", to: loaded.to } };
|
|
2588
|
+
}
|
|
2589
|
+
if (loaded instanceof NotFound) {
|
|
2590
|
+
return { message: { t: "redirect", to: e.ctx.url.pathname + e.ctx.url.search } };
|
|
2591
|
+
}
|
|
2592
|
+
fresh = { ...e.ctx.params, ...loaded };
|
|
2593
|
+
if (e.cost)
|
|
2594
|
+
e.cost.dataBytes = jsonBytes(fresh);
|
|
2595
|
+
return { props: fresh };
|
|
2596
|
+
};
|
|
2597
|
+
let fresh = null;
|
|
2598
|
+
try {
|
|
2599
|
+
const started = performance.now();
|
|
2600
|
+
const scope = queryLimits ? newScope(null) : null;
|
|
2601
|
+
const again = () => withSession(e.sid, () => e.page.refresh(withLoad ? reload : undefined));
|
|
2602
|
+
let msgs;
|
|
2603
|
+
try {
|
|
2604
|
+
msgs = await (scope ? readScope.run(scope, again) : again());
|
|
2605
|
+
}
|
|
2606
|
+
finally {
|
|
2607
|
+
if (scope)
|
|
2608
|
+
scope.open = false;
|
|
2609
|
+
}
|
|
2610
|
+
if (withLoad && foreign && msgs.some((m) => m.t === "patch")) {
|
|
2611
|
+
e.version += 1;
|
|
2612
|
+
msgs = msgs.map((m) => (m.t === "patch" ? { ...m, v: e.version } : m));
|
|
2613
|
+
}
|
|
2614
|
+
for (const msg of msgs) {
|
|
2615
|
+
send(e, msg);
|
|
2616
|
+
}
|
|
2617
|
+
charge(e, "refreshes", performance.now() - started, msgs);
|
|
2618
|
+
const cause = withLoad ? "data change" : "re-render";
|
|
2619
|
+
checkBudget(e, cause, msgs);
|
|
2620
|
+
if (scope)
|
|
2621
|
+
checkReads(scope, patternOf.get(e.route) ?? "unknown", cause, e.dev);
|
|
2622
|
+
if (e.dev && msgs.length > 0) {
|
|
2623
|
+
note(e.dev.messages, {
|
|
2624
|
+
at: Date.now(),
|
|
2625
|
+
dir: "push",
|
|
2626
|
+
what: (withLoad ? "data changed: load and render again" : "render again (a settled await or a store)") +
|
|
2627
|
+
(why.length > 0 ? ` because: ${why.join("; ")}` : ""),
|
|
2628
|
+
ms: Math.round((performance.now() - started) * 100) / 100,
|
|
2629
|
+
out: msgs.map(describe),
|
|
2630
|
+
});
|
|
2631
|
+
if (msgs.some((m) => m.t === "patch"))
|
|
2632
|
+
frame(e.dev, withLoad ? "data changed" : "rendered again", pageHtml(e));
|
|
2633
|
+
}
|
|
2634
|
+
if (fresh && pages.get(e.page.id) === e) {
|
|
2635
|
+
const head = headOf(await pageMeta(e.route, e.ctx, fresh), e.ctx.request);
|
|
2636
|
+
if (head.meta !== e.head.meta || head.title !== e.head.title || head.lang !== e.head.lang) {
|
|
2637
|
+
e.head = head;
|
|
2638
|
+
send(e, { t: "head", ...head });
|
|
2639
|
+
}
|
|
2640
|
+
}
|
|
2641
|
+
}
|
|
2642
|
+
catch (err) {
|
|
2643
|
+
onError(err);
|
|
2644
|
+
}
|
|
2645
|
+
}
|
|
2646
|
+
function attach(e, sink) {
|
|
2647
|
+
e.sinks.add(sink);
|
|
2648
|
+
if (e.awayTimer) {
|
|
2649
|
+
clearTimeout(e.awayTimer);
|
|
2650
|
+
e.awayTimer = null;
|
|
2651
|
+
}
|
|
2652
|
+
presenceAway(e.ctx, false);
|
|
2653
|
+
if (e.attached++ > 0) {
|
|
2654
|
+
sink(e.page.current());
|
|
2655
|
+
}
|
|
2656
|
+
if (e.stale) {
|
|
2657
|
+
schedule(e, false);
|
|
2658
|
+
}
|
|
2659
|
+
return () => {
|
|
2660
|
+
e.sinks.delete(sink);
|
|
2661
|
+
if (pages.get(e.page.id) === e)
|
|
2662
|
+
watchAway(e);
|
|
2663
|
+
};
|
|
2664
|
+
}
|
|
2665
|
+
const sockets = new Map();
|
|
2666
|
+
function openSse(entry) {
|
|
2667
|
+
const id = randomId();
|
|
2668
|
+
let timer = null;
|
|
2669
|
+
let detach = null;
|
|
2670
|
+
const body = new ReadableStream({
|
|
2671
|
+
start(controller) {
|
|
2672
|
+
const stream = {
|
|
2673
|
+
entry,
|
|
2674
|
+
push(msg) {
|
|
2675
|
+
controller.enqueue(enc.encode(`data: ${encode(msg)}\n\n`));
|
|
2676
|
+
},
|
|
2677
|
+
};
|
|
2678
|
+
streams.set(id, stream);
|
|
2679
|
+
stream.push({ t: "hello", session: id, p: PROTOCOL_VERSION });
|
|
2680
|
+
detach = attach(entry, (msg) => stream.push(msg));
|
|
2681
|
+
timer = setInterval(() => controller.enqueue(enc.encode(": ping\n\n")), heartbeatMs);
|
|
2682
|
+
timer.unref?.();
|
|
2683
|
+
},
|
|
2684
|
+
cancel() {
|
|
2685
|
+
streams.delete(id);
|
|
2686
|
+
detach?.();
|
|
2687
|
+
if (timer !== null) {
|
|
2688
|
+
clearInterval(timer);
|
|
2689
|
+
}
|
|
2690
|
+
},
|
|
2691
|
+
});
|
|
2692
|
+
return new Response(body, {
|
|
2693
|
+
headers: {
|
|
2694
|
+
"content-type": "text/event-stream",
|
|
2695
|
+
"cache-control": "no-store",
|
|
2696
|
+
"x-content-type-options": "nosniff",
|
|
2697
|
+
"x-weft-instance": instance,
|
|
2698
|
+
},
|
|
2699
|
+
});
|
|
2700
|
+
}
|
|
2701
|
+
async function uploadRequest(req, url, path, sid) {
|
|
2702
|
+
const refuse = (code, error) => new Response(JSON.stringify({ ok: false, error }), {
|
|
2703
|
+
status: code,
|
|
2704
|
+
headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" },
|
|
2705
|
+
});
|
|
2706
|
+
if (!sameOrigin(req)) {
|
|
2707
|
+
return refuse(403, "Cross-origin request refused");
|
|
2708
|
+
}
|
|
2709
|
+
if (!sid) {
|
|
2710
|
+
return refuse(403, "Session expired; reload the page");
|
|
2711
|
+
}
|
|
2712
|
+
if (req.method !== "PUT" && !(await verifyCsrf(await keyP, sid, req.headers.get("x-weft-csrf")))) {
|
|
2713
|
+
return refuse(403, "Session expired; reload the page");
|
|
2714
|
+
}
|
|
2715
|
+
if (req.method !== "PUT" && !limiter.take(sid)) {
|
|
2716
|
+
return refuse(429, "Too many requests");
|
|
2717
|
+
}
|
|
2718
|
+
const ctx = await contextFor(req, url, {}, sid, null);
|
|
2719
|
+
if (viewingAs(ctx)) {
|
|
2720
|
+
return refuse(403, VIEWING);
|
|
2721
|
+
}
|
|
2722
|
+
try {
|
|
2723
|
+
return await withSession(sid, () => opts.uploads.handle(ctx, req, path));
|
|
2724
|
+
}
|
|
2725
|
+
catch (err) {
|
|
2726
|
+
report(err, "upload", { ctx });
|
|
2727
|
+
return refuse(500, "Server error");
|
|
2728
|
+
}
|
|
2729
|
+
}
|
|
2730
|
+
async function postEvent(req) {
|
|
2731
|
+
if (!sameOrigin(req)) {
|
|
2732
|
+
return status(403);
|
|
2733
|
+
}
|
|
2734
|
+
const sid = await sessionOf(req);
|
|
2735
|
+
if (!sid || !(await verifyCsrf(await keyP, sid, req.headers.get("x-weft-csrf")))) {
|
|
2736
|
+
return status(403);
|
|
2737
|
+
}
|
|
2738
|
+
const stream = streams.get(req.headers.get("x-weft-session") ?? "");
|
|
2739
|
+
if (!stream || stream.entry.sid !== sid || !pages.has(stream.entry.page.id)) {
|
|
2740
|
+
return status(404);
|
|
2741
|
+
}
|
|
2742
|
+
if (!limiter.take(sid)) {
|
|
2743
|
+
return status(429);
|
|
2744
|
+
}
|
|
2745
|
+
const declared = Number(req.headers.get("content-length") ?? "0");
|
|
2746
|
+
if (declared > LIMITS.message) {
|
|
2747
|
+
return status(413);
|
|
2748
|
+
}
|
|
2749
|
+
const raw = await req.text();
|
|
2750
|
+
if (raw.length > LIMITS.message) {
|
|
2751
|
+
return status(413);
|
|
2752
|
+
}
|
|
2753
|
+
const msg = decodeClientMessage(raw);
|
|
2754
|
+
if (!msg) {
|
|
2755
|
+
return status(400);
|
|
2756
|
+
}
|
|
2757
|
+
touch(stream.entry.page.id, stream.entry);
|
|
2758
|
+
if (msg.t === "text") {
|
|
2759
|
+
sharedOn(stream.entry, msg);
|
|
2760
|
+
return status(204);
|
|
2761
|
+
}
|
|
2762
|
+
if (msg.t === "point") {
|
|
2763
|
+
pointMessage(stream.entry, stream.entry.ctx, msg, (m) => send(stream.entry, m));
|
|
2764
|
+
return status(204);
|
|
2765
|
+
}
|
|
2766
|
+
const outs = await dispatchTo(stream.entry, sid, msg, req);
|
|
2767
|
+
for (const out of outs) {
|
|
2768
|
+
stream.push(out);
|
|
2769
|
+
}
|
|
2770
|
+
return status(204);
|
|
2771
|
+
}
|
|
2772
|
+
const actions = new Map();
|
|
2773
|
+
for (const [name, a] of Object.entries(opts.actions ?? {})) {
|
|
2774
|
+
if (a.name !== name) {
|
|
2775
|
+
throw new Error(`@weft-framework/server: action registered as ${name} is named ${a.name}`);
|
|
2776
|
+
}
|
|
2777
|
+
actions.set(name, a);
|
|
2778
|
+
}
|
|
2779
|
+
const maxActionBytes = opts.maxActionBytes ?? 256 * 1024;
|
|
2780
|
+
function actionName(url) {
|
|
2781
|
+
if (!url.search.startsWith("?/")) {
|
|
2782
|
+
return null;
|
|
2783
|
+
}
|
|
2784
|
+
const name = url.search.slice(2).split("&")[0];
|
|
2785
|
+
return /^[A-Za-z_$][\w$]*$/.test(name) ? name : "";
|
|
2786
|
+
}
|
|
2787
|
+
async function postAction(req, name, params, standalone = false) {
|
|
2788
|
+
const url = new URL(req.url);
|
|
2789
|
+
const jsonBody = (req.headers.get("content-type") ?? "").split(";")[0].trim() === "application/json";
|
|
2790
|
+
const json = standalone || jsonBody || req.headers.get("x-weft-enhanced") === "1";
|
|
2791
|
+
const answer = (code, body) => json ? jsonResponse(code, body) : formFailure(code, body.error ?? "Request refused", url);
|
|
2792
|
+
if (!sameOrigin(req)) {
|
|
2793
|
+
return answer(403, { ok: false, error: "Cross-origin request refused" });
|
|
2794
|
+
}
|
|
2795
|
+
const sid = await sessionOf(req);
|
|
2796
|
+
if (!sid) {
|
|
2797
|
+
return answer(403, { ok: false, error: "Session expired; reload the page" });
|
|
2798
|
+
}
|
|
2799
|
+
if (json && !(await verifyCsrf(await keyP, sid, req.headers.get("x-weft-csrf")))) {
|
|
2800
|
+
return answer(403, { ok: false, error: "Session expired; reload the page" });
|
|
2801
|
+
}
|
|
2802
|
+
const action = actions.get(name);
|
|
2803
|
+
if (!action) {
|
|
2804
|
+
return answer(404, { ok: false, error: "Unknown action" });
|
|
2805
|
+
}
|
|
2806
|
+
if (!limiter.take(sid)) {
|
|
2807
|
+
return answer(429, { ok: false, error: "Too many requests" });
|
|
2808
|
+
}
|
|
2809
|
+
if (Number(req.headers.get("content-length") ?? "0") > maxActionBytes) {
|
|
2810
|
+
return answer(413, { ok: false, error: "Request too large" });
|
|
2811
|
+
}
|
|
2812
|
+
const buf = await req.arrayBuffer();
|
|
2813
|
+
if (buf.byteLength > maxActionBytes) {
|
|
2814
|
+
return answer(413, { ok: false, error: "Request too large" });
|
|
2815
|
+
}
|
|
2816
|
+
const held = heldCount(action.params);
|
|
2817
|
+
let heldArgs = [];
|
|
2818
|
+
if (held > 0) {
|
|
2819
|
+
const opened = openHeld(sid, name, url.searchParams.get(HELD_FIELD));
|
|
2820
|
+
const checked = opened && opened.length === held
|
|
2821
|
+
? decodeJson(action.params.slice(0, held), Object.fromEntries(action.params.slice(0, held).map((p, i) => [p.name, opened[i]])))
|
|
2822
|
+
: null;
|
|
2823
|
+
if (!checked?.ok) {
|
|
2824
|
+
return answer(400, { ok: false, error: "This form has expired; reload the page" });
|
|
2825
|
+
}
|
|
2826
|
+
heldArgs = checked.args;
|
|
2827
|
+
}
|
|
2828
|
+
const fields = action.params.slice(held);
|
|
2829
|
+
let decoded;
|
|
2830
|
+
try {
|
|
2831
|
+
decoded = jsonBody
|
|
2832
|
+
? decodeJson(fields, JSON.parse(new TextDecoder().decode(buf)))
|
|
2833
|
+
: decodeForm(fields, await new Response(buf, { headers: { "content-type": req.headers.get("content-type") ?? "" } }).formData());
|
|
2834
|
+
}
|
|
2835
|
+
catch {
|
|
2836
|
+
return answer(400, { ok: false, error: "Malformed request body" });
|
|
2837
|
+
}
|
|
2838
|
+
if (!decoded.ok) {
|
|
2839
|
+
return answer(400, { ok: false, error: decoded.error });
|
|
2840
|
+
}
|
|
2841
|
+
let rotated = null;
|
|
2842
|
+
const ctx = await contextFor(req, url, params, sid, null, (r) => (rotated = r));
|
|
2843
|
+
if (viewingAs(ctx) && !runsWhileViewing(action)) {
|
|
2844
|
+
return answer(403, { ok: false, error: VIEWING });
|
|
2845
|
+
}
|
|
2846
|
+
const res = await (async () => {
|
|
2847
|
+
let value;
|
|
2848
|
+
try {
|
|
2849
|
+
value = await withSession(sid, () => action.run(ctx, ...[...heldArgs, ...decoded.args]));
|
|
2850
|
+
}
|
|
2851
|
+
catch (err) {
|
|
2852
|
+
if (err instanceof ActionError) {
|
|
2853
|
+
return answer(err.status, { ok: false, error: String(err.message ?? "Request refused") });
|
|
2854
|
+
}
|
|
2855
|
+
if (err instanceof NotFound) {
|
|
2856
|
+
return answer(404, { ok: false, error: "Not found" });
|
|
2857
|
+
}
|
|
2858
|
+
if (!(err instanceof Redirect)) {
|
|
2859
|
+
report(err, "action", { ctx, handler: name });
|
|
2860
|
+
return answer(500, { ok: false, error: "Server error" });
|
|
2861
|
+
}
|
|
2862
|
+
value = err;
|
|
2863
|
+
}
|
|
2864
|
+
if (value instanceof Redirect) {
|
|
2865
|
+
if (!isSafePath(value.to)) {
|
|
2866
|
+
onError(new Error(`@weft-framework/server: redirect target must be a same-origin path: ${value.to}`));
|
|
2867
|
+
return answer(500, { ok: false, error: "Server error" });
|
|
2868
|
+
}
|
|
2869
|
+
return json ? jsonResponse(200, { ok: true, redirect: value.to }) : seeOther(value.to);
|
|
2870
|
+
}
|
|
2871
|
+
if (!json) {
|
|
2872
|
+
return seeOther(url.pathname);
|
|
2873
|
+
}
|
|
2874
|
+
const body = { ok: true };
|
|
2875
|
+
if (value !== undefined) {
|
|
2876
|
+
body.value = value;
|
|
2877
|
+
}
|
|
2878
|
+
if (rotated && !standalone) {
|
|
2879
|
+
body.redirect = url.pathname;
|
|
2880
|
+
}
|
|
2881
|
+
return jsonResponse(200, body);
|
|
2882
|
+
})();
|
|
2883
|
+
const r = rotated;
|
|
2884
|
+
if (r) {
|
|
2885
|
+
res.headers.append("set-cookie", r.cookie);
|
|
2886
|
+
res.headers.set("x-weft-csrf", await csrfToken(await keyP, r.sid));
|
|
2887
|
+
}
|
|
2888
|
+
return res;
|
|
2889
|
+
}
|
|
2890
|
+
async function sessionBootstrap(req) {
|
|
2891
|
+
if (!sameOrigin(req)) {
|
|
2892
|
+
return jsonResponse(403, { error: "Cross-origin request refused" });
|
|
2893
|
+
}
|
|
2894
|
+
const key = await keyP;
|
|
2895
|
+
let sid = await sessionOf(req);
|
|
2896
|
+
let setCookie = null;
|
|
2897
|
+
if (!sid) {
|
|
2898
|
+
sid = randomId(24);
|
|
2899
|
+
setCookie = sessionCookie(cookieName, await signSession(key, sid), {
|
|
2900
|
+
secure: new URL(req.url).protocol === "https:",
|
|
2901
|
+
});
|
|
2902
|
+
}
|
|
2903
|
+
const res = jsonResponse(200, { csrf: await csrfToken(key, sid) });
|
|
2904
|
+
if (setCookie) {
|
|
2905
|
+
res.headers.append("set-cookie", setCookie);
|
|
2906
|
+
}
|
|
2907
|
+
return res;
|
|
2908
|
+
}
|
|
2909
|
+
const maxApiBytes = opts.maxApiBytes ?? 256 * 1024;
|
|
2910
|
+
async function callApi(req, handlers, params) {
|
|
2911
|
+
const url = new URL(req.url);
|
|
2912
|
+
const method = req.method.toUpperCase();
|
|
2913
|
+
const allow = allowHeader(handlers);
|
|
2914
|
+
if (method === "OPTIONS" && !handlers.OPTIONS) {
|
|
2915
|
+
return new Response(null, {
|
|
2916
|
+
status: 204,
|
|
2917
|
+
headers: { allow, "cache-control": "no-store", "x-content-type-options": "nosniff" },
|
|
2918
|
+
});
|
|
2919
|
+
}
|
|
2920
|
+
const fn = isApiMethod(method) ? handlerFor(handlers, method) : undefined;
|
|
2921
|
+
if (!fn) {
|
|
2922
|
+
return new Response(null, { status: 405, headers: { allow, "x-content-type-options": "nosniff" } });
|
|
2923
|
+
}
|
|
2924
|
+
if (isExternal(fn)) {
|
|
2925
|
+
return callExternal(req, url, method, handlers, fn, params);
|
|
2926
|
+
}
|
|
2927
|
+
if (isUnsafeMethod(method) && !sameOrigin(req)) {
|
|
2928
|
+
return jsonResponse(403, { error: "Cross-origin request refused" });
|
|
2929
|
+
}
|
|
2930
|
+
const key = await keyP;
|
|
2931
|
+
const secure = url.protocol === "https:";
|
|
2932
|
+
let sid = await sessionOf(req);
|
|
2933
|
+
if (isUnsafeMethod(method)) {
|
|
2934
|
+
if (!sid || !(await verifyCsrf(key, sid, req.headers.get("x-weft-csrf")))) {
|
|
2935
|
+
return jsonResponse(403, { error: "Session expired; reload the page" });
|
|
2936
|
+
}
|
|
2937
|
+
}
|
|
2938
|
+
let setCookie = null;
|
|
2939
|
+
if (!sid) {
|
|
2940
|
+
sid = randomId(24);
|
|
2941
|
+
setCookie = sessionCookie(cookieName, await signSession(key, sid), { secure });
|
|
2942
|
+
}
|
|
2943
|
+
let active = sid;
|
|
2944
|
+
const stamp = async (res, head) => {
|
|
2945
|
+
const headers = copyHeaders(res.headers);
|
|
2946
|
+
if (setCookie) {
|
|
2947
|
+
headers.append("set-cookie", setCookie);
|
|
2948
|
+
}
|
|
2949
|
+
if (!headers.has("x-content-type-options")) {
|
|
2950
|
+
headers.set("x-content-type-options", "nosniff");
|
|
2951
|
+
}
|
|
2952
|
+
if (!headers.has("cache-control")) {
|
|
2953
|
+
headers.set("cache-control", "no-store");
|
|
2954
|
+
}
|
|
2955
|
+
headers.set("x-weft-csrf", await csrfToken(key, active));
|
|
2956
|
+
if (head) {
|
|
2957
|
+
await res.body?.cancel().catch(() => undefined);
|
|
2958
|
+
}
|
|
2959
|
+
return new Response(head ? null : res.body, { status: res.status, statusText: res.statusText, headers });
|
|
2960
|
+
};
|
|
2961
|
+
if (!apiLimiter.take(sid)) {
|
|
2962
|
+
return stamp(jsonResponse(429, { error: "Too many requests" }), false);
|
|
2963
|
+
}
|
|
2964
|
+
let next = req;
|
|
2965
|
+
if (method !== "GET" && method !== "HEAD" && method !== "OPTIONS") {
|
|
2966
|
+
const declared = Number(req.headers.get("content-length") ?? "0");
|
|
2967
|
+
if (Number.isFinite(declared) && declared > maxApiBytes) {
|
|
2968
|
+
return stamp(jsonResponse(413, { error: "Request too large" }), false);
|
|
2969
|
+
}
|
|
2970
|
+
const buf = await readLimited(req, maxApiBytes);
|
|
2971
|
+
if (!buf) {
|
|
2972
|
+
return stamp(jsonResponse(413, { error: "Request too large" }), false);
|
|
2973
|
+
}
|
|
2974
|
+
next = new Request(req.url, {
|
|
2975
|
+
method: req.method,
|
|
2976
|
+
headers: req.headers,
|
|
2977
|
+
body: buf.byteLength > 0 ? new Uint8Array(buf) : undefined,
|
|
2978
|
+
});
|
|
2979
|
+
}
|
|
2980
|
+
const ctx = await contextFor(next, url, params, sid, isUnsafeMethod(method) ? null : NOT_HERE, (r) => {
|
|
2981
|
+
active = r.sid;
|
|
2982
|
+
setCookie = r.cookie;
|
|
2983
|
+
});
|
|
2984
|
+
const head = method === "HEAD" && !handlers.HEAD;
|
|
2985
|
+
if (isUnsafeMethod(method) && viewingAs(ctx)) {
|
|
2986
|
+
return stamp(jsonResponse(403, { error: VIEWING }), false);
|
|
2987
|
+
}
|
|
2988
|
+
try {
|
|
2989
|
+
const value = await withSession(sid, () => fn(ctx));
|
|
2990
|
+
if (!(value instanceof Response)) {
|
|
2991
|
+
onError(new Error("@weft-framework/server: an api handler did not return a Response"));
|
|
2992
|
+
return stamp(jsonResponse(500, { error: "Server error" }), false);
|
|
2993
|
+
}
|
|
2994
|
+
if (!guardApiResponse(value, url.origin)) {
|
|
2995
|
+
onError(new Error("@weft-framework/server: an api response redirected off-site"));
|
|
2996
|
+
await value.body?.cancel().catch(() => undefined);
|
|
2997
|
+
return stamp(jsonResponse(500, { error: "Server error" }), false);
|
|
2998
|
+
}
|
|
2999
|
+
return stamp(value, head);
|
|
3000
|
+
}
|
|
3001
|
+
catch (err) {
|
|
3002
|
+
if (err instanceof Redirect) {
|
|
3003
|
+
if (!isSafePath(err.to)) {
|
|
3004
|
+
onError(new Error("@weft-framework/server: redirect target must be a same-origin path"));
|
|
3005
|
+
return stamp(jsonResponse(500, { error: "Server error" }), false);
|
|
3006
|
+
}
|
|
3007
|
+
return stamp(new Response(null, { status: 303, headers: { location: err.to } }), false);
|
|
3008
|
+
}
|
|
3009
|
+
if (err instanceof NotFound) {
|
|
3010
|
+
return stamp(jsonResponse(404, { error: "Not found" }), false);
|
|
3011
|
+
}
|
|
3012
|
+
report(err, "api", { route: handlers, ctx });
|
|
3013
|
+
return stamp(jsonResponse(500, { error: "Server error" }), false);
|
|
3014
|
+
}
|
|
3015
|
+
}
|
|
3016
|
+
async function callExternal(req, url, method, handlers, fn, params) {
|
|
3017
|
+
const plain = (res, head) => {
|
|
3018
|
+
const headers = copyHeaders(res.headers);
|
|
3019
|
+
headers.delete("set-cookie");
|
|
3020
|
+
if (!headers.has("x-content-type-options"))
|
|
3021
|
+
headers.set("x-content-type-options", "nosniff");
|
|
3022
|
+
if (!headers.has("cache-control"))
|
|
3023
|
+
headers.set("cache-control", "no-store");
|
|
3024
|
+
if (head)
|
|
3025
|
+
void res.body?.cancel().catch(() => undefined);
|
|
3026
|
+
return new Response(head ? null : res.body, { status: res.status, statusText: res.statusText, headers });
|
|
3027
|
+
};
|
|
3028
|
+
let next = req;
|
|
3029
|
+
if (method !== "GET" && method !== "HEAD" && method !== "OPTIONS") {
|
|
3030
|
+
const declared = Number(req.headers.get("content-length") ?? "0");
|
|
3031
|
+
const buf = Number.isFinite(declared) && declared > maxApiBytes ? null : await readLimited(req, maxApiBytes);
|
|
3032
|
+
if (!buf)
|
|
3033
|
+
return plain(jsonResponse(413, { error: "Request too large" }), false);
|
|
3034
|
+
next = new Request(req.url, { method: req.method, headers: req.headers, body: buf.byteLength > 0 ? new Uint8Array(buf) : undefined });
|
|
3035
|
+
}
|
|
3036
|
+
const ctx = await contextFor(next, url, params, randomId(24), "do not work in external API handlers (no browser session)");
|
|
3037
|
+
try {
|
|
3038
|
+
const value = await fn(ctx);
|
|
3039
|
+
if (!(value instanceof Response)) {
|
|
3040
|
+
onError(new Error("@weft-framework/server: an api handler did not return a Response"));
|
|
3041
|
+
return plain(jsonResponse(500, { error: "Server error" }), false);
|
|
3042
|
+
}
|
|
3043
|
+
if (!guardApiResponse(value, url.origin)) {
|
|
3044
|
+
onError(new Error("@weft-framework/server: an api response redirected off-site"));
|
|
3045
|
+
await value.body?.cancel().catch(() => undefined);
|
|
3046
|
+
return plain(jsonResponse(500, { error: "Server error" }), false);
|
|
3047
|
+
}
|
|
3048
|
+
return plain(value, method === "HEAD" && !handlers.HEAD);
|
|
3049
|
+
}
|
|
3050
|
+
catch (err) {
|
|
3051
|
+
if (err instanceof NotFound)
|
|
3052
|
+
return plain(jsonResponse(404, { error: "Not found" }), false);
|
|
3053
|
+
report(err, "api", { route: handlers, ctx });
|
|
3054
|
+
return plain(jsonResponse(500, { error: "Server error" }), false);
|
|
3055
|
+
}
|
|
3056
|
+
}
|
|
3057
|
+
function harden(res, secure) {
|
|
3058
|
+
const headers = copyHeaders(res.headers);
|
|
3059
|
+
const type = headers.get("content-type") ?? "";
|
|
3060
|
+
if (type.includes("text/html")) {
|
|
3061
|
+
for (const [name, value] of Object.entries(securityHeaders({ nonce: randomId(16), secure }))) {
|
|
3062
|
+
headers.set(name, value);
|
|
3063
|
+
}
|
|
3064
|
+
if (!headers.has("cache-control")) {
|
|
3065
|
+
headers.set("cache-control", "no-store");
|
|
3066
|
+
}
|
|
3067
|
+
}
|
|
3068
|
+
else if (!headers.has("x-content-type-options")) {
|
|
3069
|
+
headers.set("x-content-type-options", "nosniff");
|
|
3070
|
+
}
|
|
3071
|
+
return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
|
|
3072
|
+
}
|
|
3073
|
+
const regionRouted = new WeakSet();
|
|
3074
|
+
const app = {
|
|
3075
|
+
async fetch(req, server) {
|
|
3076
|
+
if (opts.regions && !regionRouted.has(req)) {
|
|
3077
|
+
const regions = opts.regions;
|
|
3078
|
+
const served = await regions.handle(req);
|
|
3079
|
+
if (served)
|
|
3080
|
+
return served;
|
|
3081
|
+
const routed = await regions.route(req, {
|
|
3082
|
+
routeOf: (p) => router.match(p)?.route.value ?? null,
|
|
3083
|
+
holdsPage: (lid) => lid !== null && pages.has(lid),
|
|
3084
|
+
});
|
|
3085
|
+
if (routed instanceof Response)
|
|
3086
|
+
return routed;
|
|
3087
|
+
const next = routed ?? req;
|
|
3088
|
+
regionRouted.add(next);
|
|
3089
|
+
const res = await app.fetch(next, server);
|
|
3090
|
+
return res ? regions.stamp(next, res) : res;
|
|
3091
|
+
}
|
|
3092
|
+
const url = new URL(req.url);
|
|
3093
|
+
const path = url.pathname;
|
|
3094
|
+
try {
|
|
3095
|
+
if (path === HEALTH || path === READY) {
|
|
3096
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
3097
|
+
return new Response(null, { status: 405, headers: { allow: "GET, HEAD" } });
|
|
3098
|
+
}
|
|
3099
|
+
const ok = path === HEALTH || (!draining && (await readyNow()));
|
|
3100
|
+
return new Response(req.method === "HEAD" ? null : ok ? "ok\n" : "unavailable\n", {
|
|
3101
|
+
status: ok ? 200 : 503,
|
|
3102
|
+
headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store", "x-content-type-options": "nosniff" },
|
|
3103
|
+
});
|
|
3104
|
+
}
|
|
3105
|
+
if (path === LIVE && req.method === "GET") {
|
|
3106
|
+
if (!wsEnabled || req.headers.get("upgrade")?.toLowerCase() !== "websocket") {
|
|
3107
|
+
return status(426);
|
|
3108
|
+
}
|
|
3109
|
+
if (!sameOrigin(req)) {
|
|
3110
|
+
return status(403);
|
|
3111
|
+
}
|
|
3112
|
+
const sid = await sessionOf(req);
|
|
3113
|
+
const entry = pageFor(url.searchParams.get("lid"), sid);
|
|
3114
|
+
const data = entry && sid ? { lid: entry.page.id, sid } : { lid: "", sid: "" };
|
|
3115
|
+
if (!server?.upgrade(req, { data })) {
|
|
3116
|
+
return status(426);
|
|
3117
|
+
}
|
|
3118
|
+
return undefined;
|
|
3119
|
+
}
|
|
3120
|
+
if (path === `${LIVE}/sse` && req.method === "GET") {
|
|
3121
|
+
const entry = pageFor(url.searchParams.get("lid"), await sessionOf(req));
|
|
3122
|
+
return entry ? openSse(entry) : status(404);
|
|
3123
|
+
}
|
|
3124
|
+
if (path === DEV_VIEW_AS && devViewing) {
|
|
3125
|
+
return await devViewAs(req);
|
|
3126
|
+
}
|
|
3127
|
+
if (path === DEV_INSPECT && opts.devtools && req.method === "GET") {
|
|
3128
|
+
const entry = pageFor(url.searchParams.get("lid"), await sessionOf(req));
|
|
3129
|
+
return entry ? inspect(entry) : status(404);
|
|
3130
|
+
}
|
|
3131
|
+
if (path === DEV_RECORDING && opts.devtools && req.method === "GET") {
|
|
3132
|
+
const entry = pageFor(url.searchParams.get("lid"), await sessionOf(req));
|
|
3133
|
+
return entry ? devRecording(entry) : status(404);
|
|
3134
|
+
}
|
|
3135
|
+
if (path === DEV_FRAME && opts.devtools && req.method === "GET") {
|
|
3136
|
+
const entry = pageFor(url.searchParams.get("lid"), await sessionOf(req));
|
|
3137
|
+
const n = Number(url.searchParams.get("n"));
|
|
3138
|
+
return entry && Number.isInteger(n) && n >= 0 ? devFrame(entry, n) : status(404);
|
|
3139
|
+
}
|
|
3140
|
+
if (path === IMAGES_PATH && opts.images) {
|
|
3141
|
+
if (req.method !== "GET" && req.method !== "HEAD")
|
|
3142
|
+
return status(405);
|
|
3143
|
+
const pass = new Headers();
|
|
3144
|
+
for (const name of ["cookie", "accept-language", "user-agent"]) {
|
|
3145
|
+
const v = req.headers.get(name);
|
|
3146
|
+
if (v !== null)
|
|
3147
|
+
pass.set(name, v);
|
|
3148
|
+
}
|
|
3149
|
+
return await opts.images.handle(req, async (src, ifNoneMatch) => {
|
|
3150
|
+
const h = new Headers(pass);
|
|
3151
|
+
if (ifNoneMatch)
|
|
3152
|
+
h.set("if-none-match", ifNoneMatch);
|
|
3153
|
+
return (await app.fetch(new Request(`${url.origin}${src}`, { headers: h }))) ?? status(404);
|
|
3154
|
+
});
|
|
3155
|
+
}
|
|
3156
|
+
if (path === CSP_REPORT && onCspReport) {
|
|
3157
|
+
if (req.method !== "POST")
|
|
3158
|
+
return status(405);
|
|
3159
|
+
if (!cspReportLimiter.take("csp"))
|
|
3160
|
+
return status(429);
|
|
3161
|
+
const text = await readCapped(req, 8192);
|
|
3162
|
+
for (const v of text === null ? [] : parseCspReports(text, url.origin, patternAt)) {
|
|
3163
|
+
try {
|
|
3164
|
+
onCspReport(v);
|
|
3165
|
+
}
|
|
3166
|
+
catch (err) {
|
|
3167
|
+
onError(err);
|
|
3168
|
+
}
|
|
3169
|
+
}
|
|
3170
|
+
return new Response(null, { status: 204 });
|
|
3171
|
+
}
|
|
3172
|
+
if (path === `${LIVE}/event`) {
|
|
3173
|
+
return req.method === "POST" ? await postEvent(req) : status(405);
|
|
3174
|
+
}
|
|
3175
|
+
if (path === `${LIVE}/leave`) {
|
|
3176
|
+
if (req.method !== "POST") {
|
|
3177
|
+
return status(405);
|
|
3178
|
+
}
|
|
3179
|
+
if (!sameOrigin(req)) {
|
|
3180
|
+
return status(403);
|
|
3181
|
+
}
|
|
3182
|
+
const entry = pageFor(url.searchParams.get("lid"), await sessionOf(req));
|
|
3183
|
+
if (entry) {
|
|
3184
|
+
if (entry.awayTimer) {
|
|
3185
|
+
clearTimeout(entry.awayTimer);
|
|
3186
|
+
entry.awayTimer = null;
|
|
3187
|
+
}
|
|
3188
|
+
presenceAway(entry.ctx, true);
|
|
3189
|
+
}
|
|
3190
|
+
return status(204);
|
|
3191
|
+
}
|
|
3192
|
+
if (path === SESSION) {
|
|
3193
|
+
return req.method === "GET" ? await sessionBootstrap(req) : status(405);
|
|
3194
|
+
}
|
|
3195
|
+
if ((path === STYLES || (path === APP_CSS && appCss)) && (req.method === "GET" || req.method === "HEAD")) {
|
|
3196
|
+
const bundle = path === APP_CSS ? appCss : styleBundle();
|
|
3197
|
+
if (!bundle) {
|
|
3198
|
+
return status(404);
|
|
3199
|
+
}
|
|
3200
|
+
return new Response(req.method === "HEAD" ? null : bundle.css, {
|
|
3201
|
+
headers: {
|
|
3202
|
+
"content-type": "text/css; charset=utf-8",
|
|
3203
|
+
"cache-control": url.searchParams.get("v") === bundle.version ? "public, max-age=31536000, immutable" : "no-cache",
|
|
3204
|
+
"x-content-type-options": "nosniff",
|
|
3205
|
+
},
|
|
3206
|
+
});
|
|
3207
|
+
}
|
|
3208
|
+
const asset = req.method === "GET" ? assets.get(path) : undefined;
|
|
3209
|
+
if (asset !== undefined) {
|
|
3210
|
+
return new Response(asset, {
|
|
3211
|
+
headers: {
|
|
3212
|
+
"content-type": "text/javascript; charset=utf-8",
|
|
3213
|
+
"cache-control": assetCache,
|
|
3214
|
+
"x-content-type-options": "nosniff",
|
|
3215
|
+
},
|
|
3216
|
+
});
|
|
3217
|
+
}
|
|
3218
|
+
if ((path === SITEMAP && opts.sitemap) || (path === ROBOTS && robots !== null)) {
|
|
3219
|
+
return await seoRequest(req, path);
|
|
3220
|
+
}
|
|
3221
|
+
const standalone = path.startsWith(ACTION);
|
|
3222
|
+
const signingIn = path.startsWith(AUTH) && (providers.size > 0 || emailAuth !== null || samlAuth !== null);
|
|
3223
|
+
const uploading = opts.uploads !== undefined && path.startsWith("/_weft/uploads/");
|
|
3224
|
+
if (opts.uploads && path.startsWith("/_weft/files/")) {
|
|
3225
|
+
return opts.uploads.serve(req, path);
|
|
3226
|
+
}
|
|
3227
|
+
if (path.startsWith("/_weft/") && !standalone && !signingIn && !uploading) {
|
|
3228
|
+
return status(404);
|
|
3229
|
+
}
|
|
3230
|
+
const sid = await sessionOf(req);
|
|
3231
|
+
const gate = await runMiddleware(opts.middleware, { request: req, url, session: sid, user: await userOf(sid) });
|
|
3232
|
+
if (gate.response) {
|
|
3233
|
+
return harden(gate.response, url.protocol === "https:");
|
|
3234
|
+
}
|
|
3235
|
+
const finish = (res) => unshared(withExtraHeaders(res, gate.headers));
|
|
3236
|
+
if (signingIn) {
|
|
3237
|
+
return finish(await signInRequest(req, url, path, sid));
|
|
3238
|
+
}
|
|
3239
|
+
if (uploading) {
|
|
3240
|
+
return finish(await uploadRequest(req, url, path, sid));
|
|
3241
|
+
}
|
|
3242
|
+
if (standalone) {
|
|
3243
|
+
if (req.method !== "POST") {
|
|
3244
|
+
return finish(new Response(null, { status: 405, headers: { allow: "POST" } }));
|
|
3245
|
+
}
|
|
3246
|
+
let name = "";
|
|
3247
|
+
try {
|
|
3248
|
+
name = decodeURIComponent(path.slice(ACTION.length));
|
|
3249
|
+
}
|
|
3250
|
+
catch {
|
|
3251
|
+
}
|
|
3252
|
+
return finish(await postAction(req, /^[A-Za-z_$][\w$]*$/.test(name) ? name : "", {}, true));
|
|
3253
|
+
}
|
|
3254
|
+
const routed = gate.rewrite ?? path;
|
|
3255
|
+
const apiHit = apiRouter.match(routed);
|
|
3256
|
+
if (apiHit) {
|
|
3257
|
+
const pattern = patternOf.get(apiHit.route.value);
|
|
3258
|
+
if (pattern !== undefined)
|
|
3259
|
+
routeOfReq.set(req, pattern);
|
|
3260
|
+
return finish(await callApi(req, apiHit.route.value, apiHit.params));
|
|
3261
|
+
}
|
|
3262
|
+
if (opts.pdf && req.method === "GET" && routed.endsWith(".pdf") && path.endsWith(".pdf")) {
|
|
3263
|
+
const page = router.match(routed.slice(0, -4));
|
|
3264
|
+
const spec = page?.route.value.pdf;
|
|
3265
|
+
if (spec)
|
|
3266
|
+
return finish(await printRoute(req, url, path, spec, sid));
|
|
3267
|
+
}
|
|
3268
|
+
if ((req.method === "GET" || req.method === "HEAD") && routed.endsWith(".og.png") && path.endsWith(".og.png")) {
|
|
3269
|
+
const spec = router.match(routed.slice(0, -".og.png".length) || "/")?.route.value.og;
|
|
3270
|
+
if (spec && opts.pdf?.capture)
|
|
3271
|
+
return finish(await ogImage(req, url, path, spec));
|
|
3272
|
+
}
|
|
3273
|
+
const found = router.match(routed);
|
|
3274
|
+
if (found) {
|
|
3275
|
+
const pattern = patternOf.get(found.route.value);
|
|
3276
|
+
if (pattern !== undefined)
|
|
3277
|
+
routeOfReq.set(req, pattern);
|
|
3278
|
+
const action = req.method === "POST" ? actionName(url) : null;
|
|
3279
|
+
if (action !== null) {
|
|
3280
|
+
return finish(await postAction(req, action, found.params));
|
|
3281
|
+
}
|
|
3282
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
3283
|
+
return finish(status(405));
|
|
3284
|
+
}
|
|
3285
|
+
if (req.method === "GET" && isPrefetch(req) && !prefetchLimiter.take(sid ?? "anon")) {
|
|
3286
|
+
return finish(status(429));
|
|
3287
|
+
}
|
|
3288
|
+
if (req.method === "GET" && !isPrefetch(req) && pattern !== undefined)
|
|
3289
|
+
noteVisit(req, url, pattern);
|
|
3290
|
+
return finish(await renderPage(req, found.route.value, found.params));
|
|
3291
|
+
}
|
|
3292
|
+
if (opts.files && (req.method === "GET" || req.method === "HEAD")) {
|
|
3293
|
+
const file = await opts.files(path, req);
|
|
3294
|
+
if (file) {
|
|
3295
|
+
return finish(file);
|
|
3296
|
+
}
|
|
3297
|
+
}
|
|
3298
|
+
if (opts.notFound && (req.method === "GET" || req.method === "HEAD")) {
|
|
3299
|
+
if (req.method === "GET" && isPrefetch(req) && !prefetchLimiter.take(sid ?? "anon")) {
|
|
3300
|
+
return finish(status(429));
|
|
3301
|
+
}
|
|
3302
|
+
return finish(await renderPage(req, opts.notFound, {}, 404));
|
|
3303
|
+
}
|
|
3304
|
+
return finish(status404());
|
|
3305
|
+
}
|
|
3306
|
+
catch (err) {
|
|
3307
|
+
if (err !== null && typeof err === "object" && rethrown.has(err))
|
|
3308
|
+
throw err;
|
|
3309
|
+
report(err, "request", { req });
|
|
3310
|
+
return status(500);
|
|
3311
|
+
}
|
|
3312
|
+
},
|
|
3313
|
+
websocket: {
|
|
3314
|
+
open(ws) {
|
|
3315
|
+
const entry = pageFor(ws.data.lid, ws.data.sid);
|
|
3316
|
+
if (!entry) {
|
|
3317
|
+
ws.send(encode({ t: "expired" }));
|
|
3318
|
+
ws.close(1008, "expired");
|
|
3319
|
+
return;
|
|
3320
|
+
}
|
|
3321
|
+
ws.send(encode({ t: "hello", session: randomId(), p: PROTOCOL_VERSION }));
|
|
3322
|
+
sockets.set(ws, attach(entry, (msg) => ws.send(encode(msg))));
|
|
3323
|
+
},
|
|
3324
|
+
async message(ws, data) {
|
|
3325
|
+
const raw = typeof data === "string" ? data : new TextDecoder().decode(data);
|
|
3326
|
+
const entry = pageFor(ws.data.lid, ws.data.sid);
|
|
3327
|
+
if (!entry) {
|
|
3328
|
+
ws.send(encode({ t: "expired" }));
|
|
3329
|
+
ws.close(1008, "expired");
|
|
3330
|
+
return;
|
|
3331
|
+
}
|
|
3332
|
+
if (!limiter.take(ws.data.sid)) {
|
|
3333
|
+
ws.send(encode({ t: "error", message: "Rate limited" }));
|
|
3334
|
+
return;
|
|
3335
|
+
}
|
|
3336
|
+
const msg = decodeClientMessage(raw);
|
|
3337
|
+
if (!msg) {
|
|
3338
|
+
ws.close(1008, "bad message");
|
|
3339
|
+
return;
|
|
3340
|
+
}
|
|
3341
|
+
if (msg.t === "text") {
|
|
3342
|
+
sharedOn(entry, msg);
|
|
3343
|
+
return;
|
|
3344
|
+
}
|
|
3345
|
+
if (msg.t === "point") {
|
|
3346
|
+
pointMessage(entry, entry.ctx, msg, (m) => send(entry, m));
|
|
3347
|
+
return;
|
|
3348
|
+
}
|
|
3349
|
+
try {
|
|
3350
|
+
const outs = await dispatchTo(entry, entry.sid, msg);
|
|
3351
|
+
for (const out of outs) {
|
|
3352
|
+
ws.send(encode(out));
|
|
3353
|
+
}
|
|
3354
|
+
}
|
|
3355
|
+
catch (err) {
|
|
3356
|
+
report(err, "event", { route: entry.route, ctx: entry.ctx, handler: msg.handler });
|
|
3357
|
+
ws.send(encode({ t: "error", message: "Server error", ack: msg.seq }));
|
|
3358
|
+
}
|
|
3359
|
+
},
|
|
3360
|
+
close(ws) {
|
|
3361
|
+
sockets.get(ws)?.();
|
|
3362
|
+
sockets.delete(ws);
|
|
3363
|
+
},
|
|
3364
|
+
},
|
|
3365
|
+
async drain(o = {}) {
|
|
3366
|
+
const delayMs = o.delayMs ?? 0;
|
|
3367
|
+
const timeoutMs = o.timeoutMs ?? 10_000;
|
|
3368
|
+
for (const [k, v] of [["delayMs", delayMs], ["timeoutMs", timeoutMs]]) {
|
|
3369
|
+
if (!Number.isFinite(v) || v < 0)
|
|
3370
|
+
throw new RangeError(`drain: ${k} is a number of ms, 0 or more`);
|
|
3371
|
+
}
|
|
3372
|
+
draining = true;
|
|
3373
|
+
if (delayMs > 0)
|
|
3374
|
+
await new Promise((r) => setTimeout(r, delayMs));
|
|
3375
|
+
const until = Date.now() + timeoutMs;
|
|
3376
|
+
while (inFlight > 0 && Date.now() < until) {
|
|
3377
|
+
await new Promise((r) => setTimeout(r, Math.min(25, Math.max(1, until - Date.now()))));
|
|
3378
|
+
}
|
|
3379
|
+
const settled = inFlight === 0;
|
|
3380
|
+
for (const [lid, e] of [...pages]) {
|
|
3381
|
+
let token = null;
|
|
3382
|
+
if (e.sinks.size > 0 && o.handoff !== false) {
|
|
3383
|
+
try {
|
|
3384
|
+
token = await sealHandoff(e);
|
|
3385
|
+
}
|
|
3386
|
+
catch {
|
|
3387
|
+
token = null;
|
|
3388
|
+
}
|
|
3389
|
+
}
|
|
3390
|
+
drop(lid, token);
|
|
3391
|
+
}
|
|
3392
|
+
return settled;
|
|
3393
|
+
},
|
|
3394
|
+
close() {
|
|
3395
|
+
removeHub();
|
|
3396
|
+
for (const r of [...etags.values()])
|
|
3397
|
+
purge(r);
|
|
3398
|
+
for (const w of watched.values())
|
|
3399
|
+
clearTimeout(w.timer);
|
|
3400
|
+
watched.clear();
|
|
3401
|
+
unReads?.();
|
|
3402
|
+
unsubscribe?.();
|
|
3403
|
+
unNotices?.();
|
|
3404
|
+
untrackFiles?.();
|
|
3405
|
+
unGap?.();
|
|
3406
|
+
unaudit?.();
|
|
3407
|
+
devDecisions.clear();
|
|
3408
|
+
unwatchStores?.();
|
|
3409
|
+
for (const lid of [...pages.keys()]) {
|
|
3410
|
+
drop(lid);
|
|
3411
|
+
}
|
|
3412
|
+
streams.clear();
|
|
3413
|
+
sockets.clear();
|
|
3414
|
+
},
|
|
3415
|
+
};
|
|
3416
|
+
{
|
|
3417
|
+
const route = app.fetch;
|
|
3418
|
+
app.fetch = async (req, server) => {
|
|
3419
|
+
inFlight++;
|
|
3420
|
+
let trace = null;
|
|
3421
|
+
if (telemetry) {
|
|
3422
|
+
try {
|
|
3423
|
+
trace = telemetry.startRequest(req);
|
|
3424
|
+
traces.set(req, trace);
|
|
3425
|
+
}
|
|
3426
|
+
catch (err) {
|
|
3427
|
+
onError(err);
|
|
3428
|
+
}
|
|
3429
|
+
}
|
|
3430
|
+
let status = 500;
|
|
3431
|
+
const scope = newScope(trace);
|
|
3432
|
+
const call = scope ? () => readScope.run(scope, () => route(req, server)) : () => route(req, server);
|
|
3433
|
+
try {
|
|
3434
|
+
if (!logger) {
|
|
3435
|
+
const res = await call();
|
|
3436
|
+
status = res ? res.status : 101;
|
|
3437
|
+
return res;
|
|
3438
|
+
}
|
|
3439
|
+
const id = assignRequestId(req, opts.trustRequestId === true);
|
|
3440
|
+
const started = Date.now();
|
|
3441
|
+
const line = { requestId: id, method: req.method, path: new URL(req.url).pathname };
|
|
3442
|
+
let res;
|
|
3443
|
+
try {
|
|
3444
|
+
res = await call();
|
|
3445
|
+
}
|
|
3446
|
+
catch (err) {
|
|
3447
|
+
logger.error("request failed", { ...line, ms: Date.now() - started, error: err });
|
|
3448
|
+
throw err;
|
|
3449
|
+
}
|
|
3450
|
+
if (res) {
|
|
3451
|
+
try {
|
|
3452
|
+
res.headers.set("x-request-id", id);
|
|
3453
|
+
}
|
|
3454
|
+
catch {
|
|
3455
|
+
res = new Response(res.body, res);
|
|
3456
|
+
res.headers.set("x-request-id", id);
|
|
3457
|
+
}
|
|
3458
|
+
}
|
|
3459
|
+
status = res ? res.status : 101;
|
|
3460
|
+
logger.info("request", { ...line, status, ms: Date.now() - started });
|
|
3461
|
+
return res;
|
|
3462
|
+
}
|
|
3463
|
+
finally {
|
|
3464
|
+
inFlight--;
|
|
3465
|
+
if (scope) {
|
|
3466
|
+
scope.open = false;
|
|
3467
|
+
if (scope.models && scope.models.size > 0) {
|
|
3468
|
+
checkReads(scope, routeOfReq.get(req) ?? "unknown", `${req.method} request`, undefined);
|
|
3469
|
+
}
|
|
3470
|
+
}
|
|
3471
|
+
if (telemetry && trace) {
|
|
3472
|
+
try {
|
|
3473
|
+
const route = routeOfReq.get(req);
|
|
3474
|
+
const info = { method: req.method, path: new URL(req.url).pathname, status };
|
|
3475
|
+
telemetry.endRequest(trace, route !== undefined ? { ...info, route } : info);
|
|
3476
|
+
}
|
|
3477
|
+
catch (err) {
|
|
3478
|
+
onError(err);
|
|
3479
|
+
}
|
|
3480
|
+
}
|
|
3481
|
+
}
|
|
3482
|
+
};
|
|
3483
|
+
}
|
|
3484
|
+
const compression = opts.compress === false ? null : opts.compress === true ? {} : (opts.compress ?? {});
|
|
3485
|
+
if (compression) {
|
|
3486
|
+
const route = app.fetch;
|
|
3487
|
+
app.fetch = async (req, server) => {
|
|
3488
|
+
const res = await route(req, server);
|
|
3489
|
+
return res ? compress(req, res, compression) : res;
|
|
3490
|
+
};
|
|
3491
|
+
}
|
|
3492
|
+
return app;
|
|
3493
|
+
}
|
|
3494
|
+
const CSP_REPORT = "/_weft/csp";
|
|
3495
|
+
const PRINTING = new WeakSet();
|
|
3496
|
+
const OG_RENDER = new WeakMap();
|
|
3497
|
+
const CSP_KEY_OF = {
|
|
3498
|
+
"connect-src": "connect",
|
|
3499
|
+
"img-src": "img",
|
|
3500
|
+
"media-src": "media",
|
|
3501
|
+
"font-src": "font",
|
|
3502
|
+
"frame-src": "frame",
|
|
3503
|
+
"style-src": "style",
|
|
3504
|
+
"form-action": "form",
|
|
3505
|
+
"worker-src": "worker",
|
|
3506
|
+
};
|
|
3507
|
+
async function readCapped(req, max) {
|
|
3508
|
+
const declared = Number(req.headers.get("content-length") ?? "0");
|
|
3509
|
+
if (declared > max)
|
|
3510
|
+
return null;
|
|
3511
|
+
const reader = req.body?.getReader();
|
|
3512
|
+
if (!reader)
|
|
3513
|
+
return "";
|
|
3514
|
+
const parts = [];
|
|
3515
|
+
let size = 0;
|
|
3516
|
+
for (;;) {
|
|
3517
|
+
const { done, value } = await reader.read();
|
|
3518
|
+
if (done)
|
|
3519
|
+
break;
|
|
3520
|
+
size += value.byteLength;
|
|
3521
|
+
if (size > max) {
|
|
3522
|
+
void reader.cancel();
|
|
3523
|
+
return null;
|
|
3524
|
+
}
|
|
3525
|
+
parts.push(value);
|
|
3526
|
+
}
|
|
3527
|
+
return Buffer.concat(parts).toString("utf8");
|
|
3528
|
+
}
|
|
3529
|
+
export function parseCspReports(text, origin, patternAt) {
|
|
3530
|
+
let raw;
|
|
3531
|
+
try {
|
|
3532
|
+
raw = JSON.parse(text);
|
|
3533
|
+
}
|
|
3534
|
+
catch {
|
|
3535
|
+
return [];
|
|
3536
|
+
}
|
|
3537
|
+
const bodies = [];
|
|
3538
|
+
if (Array.isArray(raw)) {
|
|
3539
|
+
for (const r of raw.slice(0, 10)) {
|
|
3540
|
+
const o = r;
|
|
3541
|
+
if (o && o.type === "csp-violation" && o.body && typeof o.body === "object")
|
|
3542
|
+
bodies.push(o.body);
|
|
3543
|
+
}
|
|
3544
|
+
}
|
|
3545
|
+
else if (raw && typeof raw === "object" && raw["csp-report"]) {
|
|
3546
|
+
const r = raw["csp-report"];
|
|
3547
|
+
if (r && typeof r === "object")
|
|
3548
|
+
bodies.push(r);
|
|
3549
|
+
}
|
|
3550
|
+
const str = (b, ...keys) => {
|
|
3551
|
+
for (const k of keys)
|
|
3552
|
+
if (typeof b[k] === "string")
|
|
3553
|
+
return b[k].slice(0, 2048);
|
|
3554
|
+
return "";
|
|
3555
|
+
};
|
|
3556
|
+
const out = [];
|
|
3557
|
+
for (const b of bodies) {
|
|
3558
|
+
let page;
|
|
3559
|
+
try {
|
|
3560
|
+
page = new URL(str(b, "documentURL", "document-uri"));
|
|
3561
|
+
}
|
|
3562
|
+
catch {
|
|
3563
|
+
continue;
|
|
3564
|
+
}
|
|
3565
|
+
if (page.origin !== origin)
|
|
3566
|
+
continue;
|
|
3567
|
+
const directive = str(b, "effectiveDirective", "effective-directive", "violated-directive").split(" ")[0];
|
|
3568
|
+
if (!/^[a-z-]{1,32}$/.test(directive))
|
|
3569
|
+
continue;
|
|
3570
|
+
const where = (u, ownPath) => {
|
|
3571
|
+
if (/^(inline|eval|data|blob|wasm-eval|trusted-types-sink)$/.test(u))
|
|
3572
|
+
return u;
|
|
3573
|
+
try {
|
|
3574
|
+
const p = new URL(u);
|
|
3575
|
+
if (p.protocol === "data:" || p.protocol === "blob:")
|
|
3576
|
+
return p.protocol.slice(0, -1);
|
|
3577
|
+
if (p.origin === origin)
|
|
3578
|
+
return ownPath ? p.pathname.slice(0, 200) : "self";
|
|
3579
|
+
return /^(https?|wss?):$/.test(p.protocol) ? p.origin : null;
|
|
3580
|
+
}
|
|
3581
|
+
catch {
|
|
3582
|
+
return null;
|
|
3583
|
+
}
|
|
3584
|
+
};
|
|
3585
|
+
const blocked = where(str(b, "blockedURL", "blocked-uri"), false);
|
|
3586
|
+
if (blocked === null)
|
|
3587
|
+
continue;
|
|
3588
|
+
out.push({
|
|
3589
|
+
route: patternAt(page.pathname) ?? null,
|
|
3590
|
+
directive,
|
|
3591
|
+
blocked,
|
|
3592
|
+
source: where(str(b, "sourceFile", "source-file"), true),
|
|
3593
|
+
});
|
|
3594
|
+
}
|
|
3595
|
+
return out;
|
|
3596
|
+
}
|
|
3597
|
+
function isPrefetch(req) {
|
|
3598
|
+
if (req.headers.get("x-weft-prefetch") === "1") {
|
|
3599
|
+
return true;
|
|
3600
|
+
}
|
|
3601
|
+
const purpose = (req.headers.get("purpose") ?? req.headers.get("sec-purpose") ?? "").toLowerCase();
|
|
3602
|
+
return purpose === "prefetch";
|
|
3603
|
+
}
|
|
3604
|
+
async function readLimited(req, max) {
|
|
3605
|
+
if (!req.body) {
|
|
3606
|
+
return new Uint8Array();
|
|
3607
|
+
}
|
|
3608
|
+
const reader = req.body.getReader();
|
|
3609
|
+
const chunks = [];
|
|
3610
|
+
let seen = 0;
|
|
3611
|
+
for (;;) {
|
|
3612
|
+
const { done, value } = await reader.read();
|
|
3613
|
+
if (done) {
|
|
3614
|
+
break;
|
|
3615
|
+
}
|
|
3616
|
+
seen += value.byteLength;
|
|
3617
|
+
if (seen > max) {
|
|
3618
|
+
await reader.cancel().catch(() => undefined);
|
|
3619
|
+
return null;
|
|
3620
|
+
}
|
|
3621
|
+
chunks.push(value);
|
|
3622
|
+
}
|
|
3623
|
+
const out = new Uint8Array(seen);
|
|
3624
|
+
let offset = 0;
|
|
3625
|
+
for (const chunk of chunks) {
|
|
3626
|
+
out.set(chunk, offset);
|
|
3627
|
+
offset += chunk.byteLength;
|
|
3628
|
+
}
|
|
3629
|
+
return out;
|
|
3630
|
+
}
|
|
3631
|
+
function serverError(secure) {
|
|
3632
|
+
return new Response("Server error", {
|
|
3633
|
+
status: 500,
|
|
3634
|
+
headers: {
|
|
3635
|
+
"content-type": "text/plain; charset=utf-8",
|
|
3636
|
+
"cache-control": "no-store",
|
|
3637
|
+
...securityHeaders({ nonce: randomId(16), secure }),
|
|
3638
|
+
},
|
|
3639
|
+
});
|
|
3640
|
+
}
|
|
3641
|
+
function status(code) {
|
|
3642
|
+
return new Response(null, { status: code });
|
|
3643
|
+
}
|
|
3644
|
+
function seeOther(to) {
|
|
3645
|
+
return new Response(null, { status: 303, headers: { location: to } });
|
|
3646
|
+
}
|
|
3647
|
+
function jsonSafe(value, depth = 0) {
|
|
3648
|
+
if (value instanceof Error)
|
|
3649
|
+
return { name: value.name, message: String(value.message) };
|
|
3650
|
+
if (value === null || typeof value !== "object" || depth > 8)
|
|
3651
|
+
return value;
|
|
3652
|
+
if (Array.isArray(value))
|
|
3653
|
+
return value.map((item) => jsonSafe(item, depth + 1));
|
|
3654
|
+
const proto = Object.getPrototypeOf(value);
|
|
3655
|
+
if (proto !== Object.prototype && proto !== null)
|
|
3656
|
+
return value;
|
|
3657
|
+
const out = {};
|
|
3658
|
+
for (const [k, v] of Object.entries(value)) {
|
|
3659
|
+
if (k === "stack")
|
|
3660
|
+
continue;
|
|
3661
|
+
out[k] = jsonSafe(v, depth + 1);
|
|
3662
|
+
}
|
|
3663
|
+
return out;
|
|
3664
|
+
}
|
|
3665
|
+
function jsonResponse(code, body) {
|
|
3666
|
+
return new Response(JSON.stringify(jsonSafe(body)), {
|
|
3667
|
+
status: code,
|
|
3668
|
+
headers: {
|
|
3669
|
+
"content-type": "application/json; charset=utf-8",
|
|
3670
|
+
"cache-control": "no-store",
|
|
3671
|
+
"x-content-type-options": "nosniff",
|
|
3672
|
+
},
|
|
3673
|
+
});
|
|
3674
|
+
}
|
|
3675
|
+
function formFailure(code, message, url) {
|
|
3676
|
+
const html = `<!doctype html><meta charset="utf-8"><title>${escapeHtml(message)}</title>` +
|
|
3677
|
+
`<p>${escapeHtml(message)}</p><p><a href="${escapeAttr(url.pathname)}">Back</a></p>`;
|
|
3678
|
+
return new Response(html, {
|
|
3679
|
+
status: code,
|
|
3680
|
+
headers: {
|
|
3681
|
+
"content-type": "text/html; charset=utf-8",
|
|
3682
|
+
"cache-control": "no-store",
|
|
3683
|
+
...securityHeaders({ nonce: randomId(16), secure: url.protocol === "https:" }),
|
|
3684
|
+
},
|
|
3685
|
+
});
|
|
3686
|
+
}
|
|
3687
|
+
function status404() {
|
|
3688
|
+
return new Response("Not found", {
|
|
3689
|
+
status: 404,
|
|
3690
|
+
headers: { "content-type": "text/plain; charset=utf-8", "x-content-type-options": "nosniff" },
|
|
3691
|
+
});
|
|
3692
|
+
}
|