@crombolo/server 0.35.2 → 0.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,236 @@
1
+ /**
2
+ * Running a site's middleware chain (story 210): each stage an onion, its
3
+ * middleware matched by path, under one time budget for the whole chain that
4
+ * stops while a middleware waits on `next()`, so crombolo's own work never
5
+ * counts against it. docs/rendering.md, "Middleware".
6
+ */
7
+ import type {
8
+ Matcher,
9
+ MatcherCondition,
10
+ Middleware,
11
+ MiddlewareContext,
12
+ MiddlewareHandler,
13
+ MiddlewareStage,
14
+ } from '@crombolo/common'
15
+
16
+ /** A middleware that threw, overran, or tried what its stage refuses, by name. */
17
+ export class MiddlewareError extends Error {
18
+ constructor(
19
+ readonly middleware: string,
20
+ message: string,
21
+ override readonly cause?: unknown,
22
+ ) {
23
+ super(message)
24
+ }
25
+ }
26
+
27
+ /** Any middleware, whatever its context is bound to: the runner hands each the context it gets. */
28
+ type AnyMiddleware = Middleware<never, never, never>
29
+
30
+ /** The chain's time, shared by every middleware in a request. */
31
+ export interface MiddlewareBudget {
32
+ remainingMs: number
33
+ }
34
+
35
+ const nameOf = (middleware: AnyMiddleware, index: number, stage: MiddlewareStage) =>
36
+ typeof middleware === 'function'
37
+ ? middleware.name || `${stage} middleware ${index + 1}`
38
+ : middleware.name
39
+
40
+ const handlerOf = (middleware: AnyMiddleware): MiddlewareHandler =>
41
+ (typeof middleware === 'function' ? middleware : middleware.handle) as MiddlewareHandler
42
+
43
+ function cookieValue(request: Request, name: string): string | undefined {
44
+ for (const part of (request.headers.get('cookie') ?? '').split(';')) {
45
+ const at = part.indexOf('=')
46
+ if (at > 0 && part.slice(0, at).trim() === name)
47
+ return decodeURIComponent(part.slice(at + 1).trim())
48
+ }
49
+ return undefined
50
+ }
51
+
52
+ function conditionHolds(condition: MatcherCondition, request: Request, url: URL): boolean {
53
+ const value =
54
+ condition.type === 'header'
55
+ ? request.headers.get(condition.key)
56
+ : condition.type === 'cookie'
57
+ ? cookieValue(request, condition.key)
58
+ : url.searchParams.get(condition.key)
59
+ if (value === null || value === undefined) return false
60
+ return condition.value === undefined || new RegExp(`^(?:${condition.value})$`).test(value)
61
+ }
62
+
63
+ const patterns = new Map<string, URLPattern>()
64
+
65
+ /** Whether a matcher, in Next.js's syntax, selects this request. Pure but for a pattern cache. */
66
+ export function matches(
67
+ matcher: Matcher | Matcher[] | undefined,
68
+ request: Request,
69
+ url: URL,
70
+ ): boolean {
71
+ if (matcher === undefined) return true
72
+ const list = Array.isArray(matcher) ? matcher : [matcher]
73
+ return list.some((entry) => {
74
+ const { source, has = [], missing = [] } = typeof entry === 'string' ? { source: entry } : entry
75
+ let pattern = patterns.get(source)
76
+ if (!pattern) {
77
+ pattern = new URLPattern({ pathname: source })
78
+ patterns.set(source, pattern)
79
+ }
80
+ return (
81
+ pattern.test({ pathname: url.pathname }) &&
82
+ has.every((c) => conditionHolds(c, request, url)) &&
83
+ !missing.some((c) => conditionHolds(c, request, url))
84
+ )
85
+ })
86
+ }
87
+
88
+ /** Runs one handler, its clock stopped while it waits on `next()`. */
89
+ function timed(
90
+ name: string,
91
+ budget: MiddlewareBudget,
92
+ run: (next: (request?: Request) => Promise<Response>) => Response | Promise<Response>,
93
+ next: (request?: Request) => Promise<Response>,
94
+ ): Promise<Response> {
95
+ return new Promise((resolve, reject) => {
96
+ let settled = false
97
+ let timer: ReturnType<typeof setTimeout> | undefined
98
+ let armedAt = 0
99
+ const arm = () => {
100
+ armedAt = Date.now()
101
+ if (!Number.isFinite(budget.remainingMs)) return
102
+ timer = setTimeout(
103
+ () => {
104
+ if (settled) return
105
+ settled = true
106
+ budget.remainingMs = 0
107
+ reject(
108
+ new MiddlewareError(
109
+ name,
110
+ `${name} took longer than the middleware chain's time limit.`,
111
+ ),
112
+ )
113
+ },
114
+ Math.max(0, budget.remainingMs),
115
+ )
116
+ }
117
+ const pause = () => {
118
+ clearTimeout(timer)
119
+ if (Number.isFinite(budget.remainingMs)) budget.remainingMs -= Date.now() - armedAt
120
+ }
121
+ arm()
122
+ const waiting = async (request?: Request) => {
123
+ pause()
124
+ try {
125
+ return await next(request)
126
+ } finally {
127
+ if (!settled) arm()
128
+ }
129
+ }
130
+ Promise.resolve()
131
+ .then(() => run(waiting))
132
+ .then(
133
+ (response) => {
134
+ if (settled) return
135
+ settled = true
136
+ pause()
137
+ if (!(response instanceof Response))
138
+ reject(new MiddlewareError(name, `${name} did not answer with a Response.`))
139
+ else resolve(response)
140
+ },
141
+ (error: unknown) => {
142
+ if (settled) return
143
+ settled = true
144
+ clearTimeout(timer)
145
+ reject(
146
+ error instanceof MiddlewareError
147
+ ? error
148
+ : new MiddlewareError(
149
+ name,
150
+ `${name} failed: ${error instanceof Error ? error.message : String(error)}`,
151
+ error,
152
+ ),
153
+ )
154
+ },
155
+ )
156
+ })
157
+ }
158
+
159
+ export interface StageOptions {
160
+ stage: MiddlewareStage
161
+ chain: readonly AnyMiddleware[] | undefined
162
+ request: Request
163
+ /** What follows the stage: the next stage, or crombolo itself. */
164
+ inner: (request: Request) => Promise<Response>
165
+ /** The context each middleware is given, less what the runner fills in. */
166
+ context: (request: Request) => Omit<MiddlewareContext, 'stage'>
167
+ budget: MiddlewareBudget
168
+ }
169
+
170
+ /** One stage of the chain as an onion, outermost first; the matching middleware only. */
171
+ export function runStage(options: StageOptions): Promise<Response> {
172
+ const chain = options.chain ?? []
173
+ const step = (index: number, request: Request): Promise<Response> => {
174
+ if (index >= chain.length) return options.inner(request)
175
+ const middleware = chain[index] as AnyMiddleware
176
+ const url = new URL(request.url)
177
+ if (typeof middleware !== 'function' && !matches(middleware.matcher, request, url))
178
+ return step(index + 1, request)
179
+ const name = nameOf(middleware, index, options.stage)
180
+ return timed(
181
+ name,
182
+ options.budget,
183
+ // Assigned, not spread: spreading would read `cookies`, which marks the answer personal.
184
+ (next) =>
185
+ handlerOf(middleware)(
186
+ request,
187
+ next,
188
+ Object.assign(options.context(request), { stage: options.stage }) as MiddlewareContext,
189
+ ),
190
+ (changed) => step(index + 1, changed ?? request),
191
+ )
192
+ }
193
+ return step(0, options.request)
194
+ }
195
+
196
+ /** Whether a chain has anything in it. */
197
+ export const hasMiddleware = (chain: readonly AnyMiddleware[] | undefined): boolean =>
198
+ (chain?.length ?? 0) > 0
199
+
200
+ /** The request's cookies, read-only, as 206's `cookies()` gives them. */
201
+ export function requestCookies(request: Request) {
202
+ const all: Array<{ name: string; value: string }> = []
203
+ for (const part of (request.headers.get('cookie') ?? '').split(';')) {
204
+ const at = part.indexOf('=')
205
+ if (at <= 0) continue
206
+ let value = part.slice(at + 1).trim()
207
+ try {
208
+ value = decodeURIComponent(value)
209
+ } catch {}
210
+ all.push({ name: part.slice(0, at).trim(), value })
211
+ }
212
+ const first = new Map<string, { name: string; value: string }>()
213
+ for (const cookie of all) if (!first.has(cookie.name)) first.set(cookie.name, cookie)
214
+ return Object.freeze({
215
+ get: (name: string) => first.get(name),
216
+ getAll: (name?: string) => (name === undefined ? [...all] : all.filter((c) => c.name === name)),
217
+ has: (name: string) => first.has(name),
218
+ size: first.size,
219
+ [Symbol.iterator]: () => first.entries(),
220
+ })
221
+ }
222
+
223
+ /**
224
+ * Whether a path is one of the site's own, which a rewrite may go to: never the
225
+ * back office, the APIs, crombolo's endpoints or `/media/`. Pure.
226
+ */
227
+ export function isSitePath(pathname: string, backOfficePath: string): boolean {
228
+ const lower = pathname.toLowerCase()
229
+ if (['/sitemap.xml', '/robots.txt', '/health'].includes(lower)) return false
230
+ return ![
231
+ '/umbraco',
232
+ '/crombolo',
233
+ '/media',
234
+ backOfficePath.toLowerCase().replace(/\/+$/, ''),
235
+ ].some((prefix) => lower === prefix || lower.startsWith(`${prefix}/`))
236
+ }
package/src/ports.ts CHANGED
@@ -393,6 +393,8 @@ export function schemaFiles(config: CromboloConfig): SchemaFiles {
393
393
  }
394
394
 
395
395
  export interface DepsOptions {
396
+ /** Published pages a site route answers in place of, for the health check (story 211). */
397
+ hiddenByRoutes?: () => Promise<Array<{ route: string; owner: string; page: string; url: string }>>
396
398
  config: CromboloConfig
397
399
  paths: BackOfficePaths
398
400
  /** The site's installed npm extensions, which contribute their manifests. */
@@ -518,6 +520,7 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
518
520
  email,
519
521
  nodeState: options.schema?.nodeState,
520
522
  fetch: options.fetch,
523
+ hiddenByRoutes: options.hiddenByRoutes,
521
524
  })
522
525
  const tags = new TagRepository(options.db)
523
526
  deps.tags = { list: (filter) => tags.all(filter) }
package/src/routes.ts ADDED
@@ -0,0 +1,420 @@
1
+ /**
2
+ * Route handlers (story 211): a site's own endpoints and a server bundle's, at
3
+ * the paths they declare. One pipeline for both: the method, the rate limit,
4
+ * the member check, CSRF, the handler under a time limit, and its answer made a
5
+ * response — a `Result`'s value as JSON, an outcome as its status, an error as
6
+ * problem+json or the status page. docs/rendering.md, "Route handlers".
7
+ */
8
+ import { type CorsPolicy, isPreflight, preflightResponse, withCors } from '@crombolo/api-delivery'
9
+ import {
10
+ type CookieOptions,
11
+ type FieldError,
12
+ isOutcome,
13
+ Ok,
14
+ type Outcome,
15
+ type RouteMethod,
16
+ type RouteOptions,
17
+ type SiteRoute,
18
+ } from '@crombolo/common'
19
+ import { ANTIFORGERY_HEADER, type PageOutcome, requestScope } from '@crombolo/render'
20
+ import { isSitePath, requestCookies } from './middleware.ts'
21
+ import { RateLimiter } from './rate-limit.ts'
22
+
23
+ /** A member as a route sees them: their key, for limits, and their group names. */
24
+ export interface RouteMember {
25
+ key: string
26
+ roles: readonly string[]
27
+ }
28
+
29
+ export interface RouteDeps<Member extends RouteMember> {
30
+ backOfficePath: string
31
+ /** The handler's time limit; 0 for none. */
32
+ timeoutMs: number
33
+ /** The site-wide limit per caller a minute; 0 for none. */
34
+ defaultPerMinute: number
35
+ /** The site's services for a caller, the member looked up when asked. */
36
+ siteFor(member: () => Promise<Member | undefined>): () => unknown
37
+ /** The member signed in by cookie, and how to check their anti-forgery token. */
38
+ session(
39
+ request: Request,
40
+ ): Promise<{ member: Member; verify(token: string | null): Promise<boolean> } | undefined>
41
+ /** The member a bearer token names. */
42
+ memberByToken?(token: string): Promise<Member | undefined>
43
+ callerAddress(request: Request): string
44
+ /** 206's status page for a request that prefers HTML. */
45
+ statusPage(request: Request, outcome: PageOutcome): Promise<Response>
46
+ logError(message: string, properties: Record<string, unknown>): void
47
+ showDetails: boolean
48
+ /** The origins a route with `cors: true` answers. */
49
+ cors?: CorsPolicy
50
+ now?: () => number
51
+ }
52
+
53
+ /** A route with what it needs added to its context, such as a bundle's capabilities. */
54
+ export interface DeclaredRoute {
55
+ route: SiteRoute
56
+ /** Who declared it, for errors and logs: the site, or a bundle by id. */
57
+ owner: string
58
+ extra?: (caller: { member?: RouteMember; via: 'cookie' | 'token' }) => Record<string, unknown>
59
+ }
60
+
61
+ const BEARER = /^Bearer\s+(\S+)$/i
62
+ const UNSAFE = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])
63
+ const MINUTE = 60_000
64
+
65
+ /** Every reason a set of site routes cannot be mounted: reserved paths and two routes on one path. */
66
+ export function siteRouteProblems(
67
+ routes: readonly DeclaredRoute[],
68
+ backOfficePath: string,
69
+ ): string[] {
70
+ const problems: string[] = []
71
+ const seen = new Map<string, string>()
72
+ for (const { route, owner } of routes) {
73
+ if (!route.path.startsWith('/') || route.path.startsWith('//'))
74
+ problems.push(`${owner}: the route "${route.path}" must be a path starting with /.`)
75
+ else if (!isSitePath(route.path.replace(/[:*(].*$/, ''), backOfficePath))
76
+ problems.push(
77
+ `${owner}: the route "${route.path}" is under one of crombolo's own paths (/umbraco, /crombolo, /media or the back office).`,
78
+ )
79
+ try {
80
+ new URLPattern({ pathname: route.path })
81
+ } catch {
82
+ problems.push(`${owner}: "${route.path}" is not a path pattern.`)
83
+ }
84
+ const key = route.path.toLowerCase().replace(/:[^/]+/g, ':')
85
+ const other = seen.get(key)
86
+ if (other) problems.push(`${owner} and ${other} both claim the route "${route.path}".`)
87
+ else seen.set(key, owner)
88
+ }
89
+ return problems
90
+ }
91
+
92
+ /** The methods a route answers, `HEAD` and `OPTIONS` included. */
93
+ function allowed(route: SiteRoute): string {
94
+ const methods = new Set(Object.keys(route.handlers))
95
+ if (methods.has('GET')) methods.add('HEAD')
96
+ methods.add('OPTIONS')
97
+ return [...methods].join(', ')
98
+ }
99
+
100
+ const TITLES: Record<number, string> = {
101
+ 400: 'Bad Request',
102
+ 401: 'Unauthorized',
103
+ 403: 'Forbidden',
104
+ 404: 'Not Found',
105
+ 405: 'Method Not Allowed',
106
+ 410: 'Gone',
107
+ 422: 'Unprocessable Content',
108
+ 429: 'Too Many Requests',
109
+ 500: 'Internal Server Error',
110
+ 504: 'Gateway Timeout',
111
+ }
112
+
113
+ const prefersHtml = (request: Request) => {
114
+ const accept = request.headers.get('accept') ?? ''
115
+ const html = accept.indexOf('text/html')
116
+ const json = accept.search(/application\/(problem\+)?json/)
117
+ return html >= 0 && (json < 0 || html < json)
118
+ }
119
+
120
+ /** Builds the site's route pipeline over its routes and its bundles'. */
121
+ export function createRoutes<Member extends RouteMember>(
122
+ declared: readonly DeclaredRoute[],
123
+ deps: RouteDeps<Member>,
124
+ ) {
125
+ const compiled = declared.map((entry) => ({
126
+ ...entry,
127
+ pattern: new URLPattern({ pathname: entry.route.path }),
128
+ }))
129
+ const defaultLimiter =
130
+ deps.defaultPerMinute > 0
131
+ ? new RateLimiter({ max: deps.defaultPerMinute, windowMs: MINUTE, now: deps.now })
132
+ : undefined
133
+ const ownLimiters = new Map<SiteRoute, RateLimiter>()
134
+ const limiterFor = (route: SiteRoute): RateLimiter | undefined => {
135
+ const limit = route.options.rateLimit
136
+ if (limit === false) return undefined
137
+ if (!limit) return defaultLimiter
138
+ let own = ownLimiters.get(route)
139
+ if (!own) {
140
+ own = new RateLimiter({ max: limit.perMinute, windowMs: MINUTE, now: deps.now })
141
+ ownLimiters.set(route, own)
142
+ }
143
+ return own
144
+ }
145
+
146
+ /** A refusal or failure, as problem+json, or as the status page for a browser. */
147
+ const problem = async (
148
+ request: Request,
149
+ status: number,
150
+ details: {
151
+ message?: string
152
+ errors?: readonly FieldError[]
153
+ reference?: string
154
+ headers?: Record<string, string>
155
+ } = {},
156
+ ): Promise<Response> => {
157
+ const headers = { 'cache-control': 'private, no-store', ...details.headers }
158
+ if (prefersHtml(request) && status !== 405 && status !== 429) {
159
+ const page = await deps.statusPage(request, {
160
+ status,
161
+ name: status === 500 ? 'serverError' : (TITLES[status] ?? 'error'),
162
+ message: details.message,
163
+ errors: details.errors ?? [],
164
+ ...(details.reference ? { reference: details.reference } : {}),
165
+ })
166
+ const out = new Headers(page.headers)
167
+ for (const [name, value] of Object.entries(headers)) out.set(name, value)
168
+ return new Response(page.body, { status, headers: out })
169
+ }
170
+ return Response.json(
171
+ {
172
+ type: 'about:blank',
173
+ title: TITLES[status] ?? 'Error',
174
+ status,
175
+ ...(details.message ? { detail: details.message } : {}),
176
+ ...(details.errors?.length ? { errors: details.errors } : {}),
177
+ ...(details.reference ? { reference: details.reference } : {}),
178
+ },
179
+ { status, headers: { 'content-type': 'application/problem+json', ...headers } },
180
+ )
181
+ }
182
+
183
+ const fromOutcome = (request: Request, outcome: Outcome) =>
184
+ outcome.isRedirect
185
+ ? new Response(null, {
186
+ status: outcome.status,
187
+ headers: { location: outcome.location as string, 'cache-control': 'no-store' },
188
+ })
189
+ : problem(request, outcome.status, { message: outcome.message, errors: outcome.errors })
190
+
191
+ /** Whether an unsafe, cookie-authenticated request came from a page of this site. */
192
+ const fromThisSite = async (
193
+ request: Request,
194
+ url: URL,
195
+ verify: (token: string | null) => Promise<boolean>,
196
+ ): Promise<boolean> => {
197
+ const site = request.headers.get('sec-fetch-site')
198
+ if (site === 'same-origin') return true
199
+ const origin = request.headers.get('origin')
200
+ if (!site && origin && origin === url.origin) return true
201
+ if (await verify(request.headers.get(ANTIFORGERY_HEADER))) return true
202
+ const type = request.headers.get('content-type') ?? ''
203
+ if (/application\/x-www-form-urlencoded|multipart\/form-data/.test(type)) {
204
+ const form = await request
205
+ .clone()
206
+ .formData()
207
+ .catch(() => undefined)
208
+ const token = form?.get('__antiforgery')
209
+ if (typeof token === 'string' && (await verify(token))) return true
210
+ }
211
+ return false
212
+ }
213
+
214
+ /**
215
+ * Answers a request with one route: everything but matching, which
216
+ * `handle` does for site routes and a bundle does for its back-office ones.
217
+ */
218
+ async function invoke(
219
+ entry: DeclaredRoute,
220
+ request: Request,
221
+ url: URL,
222
+ params: Record<string, string>,
223
+ options: { checks: boolean; extra?: Record<string, unknown> } = { checks: true },
224
+ ): Promise<Response> {
225
+ const policy = entry.route.options.cors ? deps.cors : undefined
226
+ if (!policy) return answer(entry, request, url, params, options)
227
+ if (isPreflight(request)) return preflightResponse(policy, request, allowed(entry.route))
228
+ return withCors(policy, request, await answer(entry, request, url, params, options))
229
+ }
230
+
231
+ async function answer(
232
+ entry: DeclaredRoute,
233
+ request: Request,
234
+ url: URL,
235
+ params: Record<string, string>,
236
+ options: { checks: boolean; extra?: Record<string, unknown> },
237
+ ): Promise<Response> {
238
+ const { route } = entry
239
+ const method = request.method.toUpperCase() as RouteMethod
240
+ let handler = route.handlers[method]
241
+ if (!handler && method === 'HEAD') handler = route.handlers.GET
242
+ if (!handler && method === 'OPTIONS')
243
+ return new Response(null, { status: 204, headers: { allow: allowed(route) } })
244
+ if (!handler)
245
+ return problem(request, 405, {
246
+ message: `${url.pathname} answers ${allowed(route)}.`,
247
+ headers: { allow: allowed(route) },
248
+ })
249
+
250
+ // Who is calling: a bearer token, or the member's session cookie, looked up once.
251
+ const bearer = BEARER.exec(request.headers.get('authorization') ?? '')?.[1]
252
+ let identified:
253
+ | Promise<{ member: Member | undefined; verify?: (token: string | null) => Promise<boolean> }>
254
+ | undefined
255
+ const identify = () => {
256
+ identified ??= bearer
257
+ ? (deps.memberByToken?.(bearer) ?? Promise.resolve(undefined)).then((member) => ({
258
+ member,
259
+ }))
260
+ : deps
261
+ .session(request)
262
+ .then((session) => ({ member: session?.member, verify: session?.verify }))
263
+ return identified
264
+ }
265
+ const member = async () => (await identify()).member
266
+
267
+ if (options.checks) {
268
+ const limiter = limiterFor(route)
269
+ if (limiter) {
270
+ const signedIn = await member()
271
+ const limit = route.options.rateLimit
272
+ const by = limit ? limit.by : undefined
273
+ const key =
274
+ signedIn && by !== 'caller'
275
+ ? `member:${signedIn.key.toLowerCase()}`
276
+ : `caller:${deps.callerAddress(request)}`
277
+ const wait = limiter.take(key)
278
+ if (wait)
279
+ return problem(request, 429, {
280
+ message: 'Too many requests. Try again in a moment.',
281
+ headers: { 'retry-after': String(wait) },
282
+ })
283
+ }
284
+ const required = route.options.members
285
+ if (required) {
286
+ const signedIn = await member()
287
+ if (!signedIn) return problem(request, 401, { message: 'Sign in to continue.' })
288
+ if (
289
+ typeof required === 'object' &&
290
+ !required.groups.some((group) =>
291
+ signedIn.roles.some((role) => role.toLowerCase() === group.toLowerCase()),
292
+ )
293
+ )
294
+ return problem(request, 403, { message: 'Your account does not have access to this.' })
295
+ }
296
+ if (route.options.csrf !== false && UNSAFE.has(method) && !bearer) {
297
+ const { member: cookieMember, verify } = await identify()
298
+ if (cookieMember && verify && !(await fromThisSite(request, url, verify)))
299
+ return problem(request, 403, {
300
+ message:
301
+ 'This request was refused because it did not come from a page of this site. Send it with crombolo.fetch from /crombolo/bundle.js, or include the anti-forgery token.',
302
+ })
303
+ }
304
+ }
305
+
306
+ const cookies: string[] = []
307
+ const deadline = new AbortController()
308
+ const signal = AbortSignal.any([request.signal, deadline.signal])
309
+ const site = deps.siteFor(member)
310
+ const context = {
311
+ params,
312
+ url,
313
+ cookies: requestCookies(request),
314
+ setCookie: (name: string, value: string, cookie: CookieOptions = {}) => {
315
+ const parts = [`${name}=${encodeURIComponent(value)}`, `Path=${cookie.path ?? '/'}`]
316
+ if (cookie.maxAge !== undefined) parts.push(`Max-Age=${Math.floor(cookie.maxAge)}`)
317
+ if (cookie.expires) parts.push(`Expires=${cookie.expires.toUTCString()}`)
318
+ if (cookie.domain) parts.push(`Domain=${cookie.domain}`)
319
+ if (cookie.secure ?? true) parts.push('Secure')
320
+ if (cookie.httpOnly ?? true) parts.push('HttpOnly')
321
+ parts.push(`SameSite=${cookie.sameSite ?? 'Lax'}`)
322
+ cookies.push(parts.join('; '))
323
+ },
324
+ site,
325
+ member,
326
+ signal,
327
+ ...(entry.extra?.({ member: await member(), via: bearer ? 'token' : 'cookie' }) ?? {}),
328
+ ...options.extra,
329
+ }
330
+
331
+ let timer: ReturnType<typeof setTimeout> | undefined
332
+ const overran = new Promise<'overran'>((resolve) => {
333
+ if (deps.timeoutMs > 0)
334
+ timer = setTimeout(() => {
335
+ deadline.abort(new Error(`${url.pathname} took longer than ${deps.timeoutMs}ms.`))
336
+ resolve('overran')
337
+ }, deps.timeoutMs)
338
+ })
339
+ let response: Response
340
+ try {
341
+ const work = Promise.resolve().then(() =>
342
+ requestScope({ headers: request.headers }, site, () => handler(request, context as never)),
343
+ )
344
+ work.catch(() => {})
345
+ const answer = await Promise.race([work, overran])
346
+ if (answer === 'overran')
347
+ response = await problem(request, 504, { message: 'This took too long to answer.' })
348
+ else if (answer instanceof Response) response = answer
349
+ else if (isOutcome(answer)) response = await fromOutcome(request, answer)
350
+ else if (answer instanceof Ok) response = Response.json(answer.value)
351
+ else
352
+ throw new Error(
353
+ `${entry.owner}'s ${method} ${route.path} answered with neither a Response nor a Result.`,
354
+ )
355
+ } catch (error) {
356
+ if (isOutcome(error)) response = await fromOutcome(request, error)
357
+ else {
358
+ const reference = crypto.randomUUID().replaceAll('-', '').slice(0, 10).toUpperCase()
359
+ const message = error instanceof Error ? error.message : String(error)
360
+ deps.logError(
361
+ 'The route {method} {path} ({owner}) failed, reference {reference}: {error}',
362
+ {
363
+ method,
364
+ path: url.pathname,
365
+ owner: entry.owner,
366
+ reference,
367
+ error: error instanceof Error ? (error.stack ?? message) : message,
368
+ },
369
+ )
370
+ response = await problem(request, 500, {
371
+ reference,
372
+ ...(deps.showDetails ? { message } : {}),
373
+ })
374
+ }
375
+ } finally {
376
+ clearTimeout(timer)
377
+ }
378
+
379
+ const headers = new Headers(response.headers)
380
+ for (const cookie of cookies) headers.append('set-cookie', cookie)
381
+ // Kept only where the handler said so, and only for a read.
382
+ if (!headers.has('cache-control') || (method !== 'GET' && method !== 'HEAD'))
383
+ headers.set('cache-control', 'private, no-store')
384
+ const body = method === 'HEAD' ? null : response.body
385
+ return new Response(body, { status: response.status, statusText: response.statusText, headers })
386
+ }
387
+
388
+ /** The route a site path matches, with its params. */
389
+ function match(pathname: string) {
390
+ for (const entry of compiled) {
391
+ const found = entry.pattern.exec({ pathname })
392
+ if (found)
393
+ return {
394
+ entry,
395
+ params: Object.fromEntries(
396
+ Object.entries(found.pathname.groups).filter(
397
+ (pair): pair is [string, string] =>
398
+ typeof pair[1] === 'string' && !/^\d+$/.test(pair[0]),
399
+ ),
400
+ ),
401
+ }
402
+ }
403
+ return undefined
404
+ }
405
+
406
+ return {
407
+ routes: declared,
408
+ match,
409
+ invoke,
410
+ /** A site request a route answers, or undefined for content finding to have it. */
411
+ async handle(request: Request, url: URL): Promise<Response | undefined> {
412
+ const found = match(url.pathname)
413
+ if (!found) return undefined
414
+ return invoke(found.entry, request, url, found.params)
415
+ },
416
+ }
417
+ }
418
+
419
+ export type SiteRoutes = ReturnType<typeof createRoutes>
420
+ export type { RouteOptions }