@crombolo/server 0.33.1 → 0.35.2

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/src/bundles.ts CHANGED
@@ -19,8 +19,12 @@
19
19
  * route path are validated, so a bundle can neither shadow a core route nor
20
20
  * reach another bundle's.
21
21
  * - The host authenticates and checks the declared section **before** dispatch. A
22
- * handler never sees an anonymous request, and a bundle cannot declare a public
23
- * route or widen its own authorisation.
22
+ * back-office handler never sees an anonymous request, and a bundle cannot
23
+ * widen its own authorisation.
24
+ * - A route that declares a `member` or `public` audience (story 186) answers on
25
+ * the site instead, under `/crombolo/bundle/<id>/`, and nowhere else. The host
26
+ * identifies the member, checks their groups, the anti-forgery token and the
27
+ * rate limit before dispatch.
24
28
  * - It receives only the capabilities it declared, frozen. No `Db`, no config, no
25
29
  * filesystem. A capability is a narrow interface this file owns and implements,
26
30
  * so the blast radius is what core chose to expose rather than what the bundle
@@ -41,12 +45,14 @@
41
45
  * site's files.
42
46
  */
43
47
 
48
+ import { type CorsPolicy, isPreflight, preflightResponse, withCors } from '@crombolo/api-delivery'
44
49
  import { hasCultureAccess, hasSection, type Principal } from '@crombolo/api-management'
45
50
  import { BUNDLE_ID, type BundlePackage, peerRangeProblem } from '@crombolo/backoffice-host'
46
51
  import {
47
52
  type AppAlias,
48
53
  type ExtensionSectionAlias,
49
54
  isExtensionSectionAlias,
55
+ MEMBER_FILE_TYPES,
50
56
  SECTION_ALIASES,
51
57
  } from '@crombolo/core'
52
58
  import {
@@ -60,9 +66,16 @@ import {
60
66
  type RedirectRow,
61
67
  type RedirectTargetKind,
62
68
  } from '@crombolo/data'
63
- import { normaliseRedirectPath, type PublishedCache } from '@crombolo/render'
69
+ import {
70
+ ANTIFORGERY_HEADER,
71
+ BUNDLE_SITE_PATH,
72
+ normaliseRedirectPath,
73
+ type PublishedCache,
74
+ } from '@crombolo/render'
75
+ import type { BundleMedia, BundleMediaDeclaration } from './bundle-media.ts'
64
76
  import type { BundleForms } from './form-types.ts'
65
77
  import type { BundleIdentityProviders } from './identity-provider-overrides.ts'
78
+ import { RateLimiter } from './rate-limit.ts'
66
79
  import type { BundleEvents } from './webhooks.ts'
67
80
 
68
81
  /** The segment every bundle's routes hang below, inside the plugin API. */
@@ -147,6 +160,11 @@ export interface BundleHost {
147
160
  identityProviders: BundleIdentityProviders
148
161
  /** The bundle's own tables, and only for a bundle that declares some. */
149
162
  tables: BundleTablesCapability
163
+ /**
164
+ * Media items in the folders the bundle declares, as the member a route was
165
+ * given or the back-office user; refused on a public route (story 198).
166
+ */
167
+ media: BundleMedia
150
168
  }
151
169
 
152
170
  export type BundleCapability = keyof BundleHost
@@ -186,6 +204,7 @@ export const BUNDLE_CAPABILITIES: readonly BundleCapability[] = [
186
204
  'log',
187
205
  'tables',
188
206
  'identityProviders',
207
+ 'media',
189
208
  ]
190
209
 
191
210
  /** What a handler is handed: the declared capabilities, with `tables` typed from the declaration. */
@@ -197,30 +216,135 @@ export type HostFor<C extends BundleCapability, T extends BundleTables> = Pick<
197
216
  ? { tables: T extends BundleTables<infer S> ? BundleTablesCapability<S> : never }
198
217
  : unknown)
199
218
 
200
- export interface BundleRequest<
201
- C extends BundleCapability = BundleCapability,
202
- T extends BundleTables = BundleTables,
203
- > {
219
+ /** A signed-in member as a member route is given them: nothing of the back office. */
220
+ export interface BundleMember {
221
+ readonly key: string
222
+ readonly name: string
223
+ readonly username: string
224
+ readonly email: string
225
+ /** Member group names. */
226
+ readonly groups: readonly string[]
227
+ }
228
+
229
+ /**
230
+ * Who may call a route. `backoffice`, the default, mounts it in the back office
231
+ * behind the bundle's section; the others mount it on the site, for any
232
+ * signed-in member, for members of the named groups, or for anyone.
233
+ */
234
+ export type BundleAudience =
235
+ | 'backoffice'
236
+ | 'member'
237
+ | { member: { groups: readonly string[] } }
238
+ | 'public'
239
+
240
+ /**
241
+ * At most `max` requests every `perSeconds`, counted by the member's key or by
242
+ * the caller's address, on each server separately.
243
+ */
244
+ export interface BundleRateLimit {
245
+ max: number
246
+ perSeconds: number
247
+ by: 'member' | 'caller'
248
+ }
249
+
250
+ /**
251
+ * Who a request is from, as the host resolved it before dispatch: the route's
252
+ * audience decides which. A public route's caller is always `public`, even
253
+ * when a member happens to be signed in. Frozen.
254
+ */
255
+ export type BundleCaller =
256
+ | { readonly kind: 'backoffice'; readonly principal: Principal }
257
+ | { readonly kind: 'member'; readonly member: BundleMember; readonly via: 'cookie' | 'token' }
258
+ | { readonly kind: 'public' }
259
+
260
+ interface BundleRequestBase<C extends BundleCapability, T extends BundleTables> {
204
261
  request: Request
205
262
  url: URL
206
- /** Already authenticated, and already holding the bundle's declared section. */
207
- principal: Principal
208
263
  /** The `:name` segments of the matched route. */
209
264
  params: Record<string, string>
210
265
  /** Only what the bundle declared, frozen. */
211
266
  host: HostFor<C, T>
267
+ /** Who is asking, which is what a capability acting for the caller reads. */
268
+ caller: BundleCaller
212
269
  }
213
270
 
214
- export interface ServerBundleRoute<
271
+ /** What a back-office route's handler is given. */
272
+ export interface BundleRequest<
215
273
  C extends BundleCapability = BundleCapability,
216
274
  T extends BundleTables = BundleTables,
217
- > {
275
+ > extends BundleRequestBase<C, T> {
276
+ /** Already authenticated, and already holding the bundle's declared section. */
277
+ principal: Principal
278
+ member?: undefined
279
+ }
280
+
281
+ /** What a member route's handler is given. */
282
+ export interface BundleMemberRequest<
283
+ C extends BundleCapability = BundleCapability,
284
+ T extends BundleTables = BundleTables,
285
+ > extends BundleRequestBase<C, T> {
286
+ /** Signed in, approved, not locked out, and in the route's groups. Frozen. */
287
+ member: BundleMember
288
+ principal?: undefined
289
+ }
290
+
291
+ /** What a public route's handler is given: nobody. */
292
+ export interface BundlePublicRequest<
293
+ C extends BundleCapability = BundleCapability,
294
+ T extends BundleTables = BundleTables,
295
+ > extends BundleRequestBase<C, T> {
296
+ principal?: undefined
297
+ member?: undefined
298
+ }
299
+
300
+ interface BundleRouteBase {
218
301
  method: BundleMethod
219
302
  /** Below the bundle's namespace; `''` is the namespace root. */
220
303
  path: string
304
+ }
305
+
306
+ /** A route in the back office, behind the bundle's section: every route unless it says otherwise. */
307
+ export interface BackofficeBundleRoute<
308
+ C extends BundleCapability = BundleCapability,
309
+ T extends BundleTables = BundleTables,
310
+ > extends BundleRouteBase {
311
+ audience?: 'backoffice'
312
+ rateLimit?: undefined
221
313
  handler(context: BundleRequest<C, T>): Response | Promise<Response>
222
314
  }
223
315
 
316
+ /** A route on the site for signed-in members, under `/crombolo/bundle/<id>/`. */
317
+ export interface MemberBundleRoute<
318
+ C extends BundleCapability = BundleCapability,
319
+ T extends BundleTables = BundleTables,
320
+ > extends BundleRouteBase {
321
+ audience: 'member' | { member: { groups: readonly string[] } }
322
+ rateLimit?: BundleRateLimit
323
+ handler(context: BundleMemberRequest<C, T>): Response | Promise<Response>
324
+ }
325
+
326
+ /** A route on the site for anyone, under `/crombolo/bundle/<id>/`. */
327
+ export interface PublicBundleRoute<
328
+ C extends BundleCapability = BundleCapability,
329
+ T extends BundleTables = BundleTables,
330
+ > extends BundleRouteBase {
331
+ audience: 'public'
332
+ rateLimit?: BundleRateLimit
333
+ handler(context: BundlePublicRequest<C, T>): Response | Promise<Response>
334
+ }
335
+
336
+ export type ServerBundleRoute<
337
+ C extends BundleCapability = BundleCapability,
338
+ T extends BundleTables = BundleTables,
339
+ > = BackofficeBundleRoute<C, T> | MemberBundleRoute<C, T> | PublicBundleRoute<C, T>
340
+
341
+ /** A route's audience as the host reads it: `backoffice` when none was declared. */
342
+ export function routeAudience(route: { audience?: BundleAudience }): BundleAudience {
343
+ return route.audience ?? 'backoffice'
344
+ }
345
+
346
+ const onSite = (route: { audience?: BundleAudience }) => routeAudience(route) !== 'backoffice'
347
+
224
348
  export interface ServerBundle<
225
349
  C extends BundleCapability = BundleCapability,
226
350
  T extends BundleTables = BundleTables,
@@ -231,8 +355,8 @@ export interface ServerBundle<
231
355
  */
232
356
  id: string
233
357
  /**
234
- * The section a caller must have access to. Every route is gated on it; there
235
- * is no per-route override and no public route.
358
+ * The section a caller must have access to. Every back-office route is gated
359
+ * on it; a route reaches anyone else only by declaring a site `audience`.
236
360
  */
237
361
  section: BundleSection
238
362
  capabilities: readonly C[]
@@ -244,6 +368,8 @@ export interface ServerBundle<
244
368
  * are honoured on every node, because forms render and submit on `web` nodes.
245
369
  */
246
370
  forms?: BundleForms
371
+ /** The media folders it uses, by path, and what it accepts: needed for the `media` capability. */
372
+ media?: BundleMediaDeclaration
247
373
  /**
248
374
  * Handlers for webhook events, by alias. Each event reaches each handler
249
375
  * through the webhook delivery queue: once per cluster, after the change,
@@ -262,7 +388,9 @@ export interface MountedBundle {
262
388
  capabilities: readonly BundleCapability[]
263
389
  /** `<backoffice>/crombolo/api/bundle/<id>`. */
264
390
  prefix: string
265
- routes: readonly { method: BundleMethod; path: string }[]
391
+ /** `/crombolo/bundle/<id>`, where its member and public routes answer. */
392
+ sitePrefix: string
393
+ routes: readonly { method: BundleMethod; path: string; audience: BundleAudience }[]
266
394
  }
267
395
 
268
396
  /**
@@ -335,6 +463,8 @@ export function validateServerBundles(
335
463
  )
336
464
  }
337
465
  }
466
+ for (const problem of mediaProblems(bundle))
467
+ problems.push(`Bundle "${label}" media: ${problem}.`)
338
468
  const routes = new Set<string>()
339
469
  for (const route of bundle.routes) {
340
470
  if (route.path !== '' && !ROUTE_PATH.test(route.path))
@@ -342,13 +472,115 @@ export function validateServerBundles(
342
472
  `Bundle "${label}" declares the route path "${route.path}", which is not a plain path of segments.`,
343
473
  )
344
474
  const signature = `${route.method} ${route.path}`
345
- if (routes.has(signature)) problems.push(`Bundle "${label}" declares "${signature}" twice.`)
346
- routes.add(signature)
475
+ const where = onSite(route) ? 'site' : 'backoffice'
476
+ if (routes.has(`${where} ${signature}`))
477
+ problems.push(`Bundle "${label}" declares "${signature}" twice.`)
478
+ routes.add(`${where} ${signature}`)
479
+ for (const problem of routeProblems(route))
480
+ problems.push(`Bundle "${label}" route "${signature}": ${problem}.`)
347
481
  }
348
482
  }
349
483
  return problems
350
484
  }
351
485
 
486
+ const isPositiveInteger = (value: unknown) =>
487
+ typeof value === 'number' && Number.isInteger(value) && value > 0
488
+
489
+ /** What is wrong with a bundle's media declaration, read as untyped config. */
490
+ function mediaProblems(bundle: ServerBundle): string[] {
491
+ const asks = bundle.capabilities.includes('media')
492
+ const media = bundle.media as unknown as Record<string, unknown> | undefined
493
+ if (!asks)
494
+ return media === undefined ? [] : ['it declares media folders but not the "media" capability']
495
+ if (typeof media !== 'object' || media === null)
496
+ return [
497
+ 'the "media" capability needs { folders: ["/Folder/Path"], maxBytes } to say where it writes',
498
+ ]
499
+ const problems: string[] = []
500
+ const folders = media.folders
501
+ if (!Array.isArray(folders) || folders.length === 0)
502
+ problems.push('it names no folders; give each by its path, such as "/Observations/Photos"')
503
+ else
504
+ for (const folder of folders)
505
+ if (
506
+ typeof folder !== 'string' ||
507
+ !folder.startsWith('/') ||
508
+ folder
509
+ .split('/')
510
+ .slice(1)
511
+ .some((segment) => segment.trim() === '')
512
+ )
513
+ problems.push(
514
+ `the folder ${JSON.stringify(folder)} is not a path such as "/Observations/Photos"`,
515
+ )
516
+ if (!isPositiveInteger(media.maxBytes))
517
+ problems.push('maxBytes is a whole number of bytes above 0')
518
+ if (media.types !== undefined) {
519
+ const known = MEMBER_FILE_TYPES.map((type) => type.id)
520
+ if (!Array.isArray(media.types)) problems.push(`types is a list of ${known.join(', ')}`)
521
+ else
522
+ for (const type of media.types)
523
+ if (!known.includes(type as string))
524
+ problems.push(`the type ${JSON.stringify(type)} is not one of ${known.join(', ')}`)
525
+ }
526
+ return problems
527
+ }
528
+
529
+ /** What is wrong with a route's audience and rate limit, read as untyped config. */
530
+ function routeProblems(route: ServerBundleRoute): string[] {
531
+ const problems: string[] = []
532
+ const audience = route.audience as unknown
533
+ if (typeof audience === 'object' && audience !== null) {
534
+ const groups = (audience as { member?: { groups?: unknown } }).member?.groups
535
+ if (
536
+ Object.keys(audience).join() !== 'member' ||
537
+ !Array.isArray(groups) ||
538
+ groups.length === 0 ||
539
+ groups.some((group) => typeof group !== 'string' || group.trim() === '')
540
+ )
541
+ problems.push('a member audience names its groups as { member: { groups: ["Name", …] } }')
542
+ } else if (
543
+ audience !== undefined &&
544
+ audience !== 'backoffice' &&
545
+ audience !== 'member' &&
546
+ audience !== 'public'
547
+ )
548
+ problems.push(
549
+ `the audience "${String(audience)}" is not one of backoffice, member, { member: { groups } } or public`,
550
+ )
551
+
552
+ const limit = route.rateLimit as unknown as Record<string, unknown> | undefined
553
+ if (limit === undefined) return problems
554
+ if (!onSite(route)) {
555
+ problems.push('a rate limit applies only to member and public routes')
556
+ return problems
557
+ }
558
+ if (typeof limit !== 'object' || limit === null)
559
+ problems.push('a rate limit is { max, perSeconds, by }')
560
+ else {
561
+ if (!isPositiveInteger(limit.max)) problems.push("a rate limit's max is a whole number above 0")
562
+ if (!isPositiveInteger(limit.perSeconds))
563
+ problems.push("a rate limit's perSeconds is a whole number above 0")
564
+ if (limit.by !== 'member' && limit.by !== 'caller')
565
+ problems.push('a rate limit counts by "member" or by "caller"')
566
+ else if (limit.by === 'member' && audience === 'public')
567
+ problems.push('a public route has no member to count by; count by "caller"')
568
+ }
569
+ return problems
570
+ }
571
+
572
+ /** Member group names a site route requires, for checking at boot that they exist. */
573
+ export function bundleRouteGroups(bundles: readonly ServerBundle[]): string[] {
574
+ const groups = new Set<string>()
575
+ for (const bundle of bundles)
576
+ for (const route of bundle.routes) {
577
+ const audience = routeAudience(route)
578
+ if (typeof audience === 'object')
579
+ for (const group of audience.member.groups) groups.add(group)
580
+ }
581
+ return [...groups]
582
+ }
583
+
352
584
  /** `rules/:key` against `rules/abc` — the params, or undefined when it does not match. */
353
585
  function matchRoute(path: string, requested: string): Record<string, string> | undefined {
354
586
  if (path === '' && requested === '') return {}
@@ -499,6 +731,36 @@ export function createBundleRedirects(options: {
499
731
  }
500
732
  }
501
733
 
734
+ /**
735
+ * A capability built for each request from its caller, so it can act as them:
736
+ * story 198's media, for one, which writes as the member a route was given and
737
+ * refuses a public caller. It is told the bundle too, for what it declared.
738
+ */
739
+ export type CallerCapabilities = {
740
+ [K in Exclude<BundleCapability, 'tables'>]?: (
741
+ caller: BundleCaller,
742
+ bundle: ServerBundle,
743
+ ) => BundleHost[K]
744
+ }
745
+
746
+ /** How the site dispatcher identifies a member and the caller (story 186). */
747
+ export interface BundleSiteOptions {
748
+ /**
749
+ * The member the site's cookie signs in, and a check that an anti-forgery
750
+ * token belongs to that session.
751
+ */
752
+ session(
753
+ request: Request,
754
+ ): Promise<{ member: BundleMember; verify(token: string | null): Promise<boolean> } | undefined>
755
+ /** The member a Delivery API member token names, when they may sign in now. */
756
+ memberByToken?(token: string): Promise<BundleMember | undefined>
757
+ /** The Delivery API's allowed origins, which get CORS headers. */
758
+ cors?: CorsPolicy
759
+ /** The real client address, for a limit counted by caller. */
760
+ callerAddress(request: Request): string
761
+ now?(): number
762
+ }
763
+
502
764
  export interface ServerBundlesOptions {
503
765
  bundles: readonly ServerBundle[]
504
766
  /** The bundle packages the site depends on, from discovery. */
@@ -507,22 +769,58 @@ export interface ServerBundlesOptions {
507
769
  coreVersion: string
508
770
  /** `<backoffice>/crombolo/api`, from `createBackOfficePaths`. */
509
771
  pluginApiPath: string
510
- host: Omit<BundleHost, 'tables'>
772
+ host: Omit<BundleHost, 'tables' | 'media'> & { media?: BundleMedia }
773
+ /** Capabilities built per request from the caller, in place of the ones in `host`. */
774
+ callerHost?: CallerCapabilities
511
775
  /** Named per bundle, so a log line says which one wrote it. */
512
776
  log(bundleId: string): BundleLog
513
777
  /** A bundle's own tables, resolved against its schema alone; absent where none are offered. */
514
778
  tables?(bundle: ServerBundle): BundleTablesCapability | undefined
779
+ /** Without it no member can be identified, so a member route answers 401. */
780
+ site?: BundleSiteOptions
515
781
  }
516
782
 
517
783
  export interface ServerBundles {
518
784
  readonly mounted: readonly MountedBundle[]
519
785
  /** The prefix every bundle route sits below, including the trailing slash. */
520
786
  readonly basePath: string
787
+ /** The prefix member and public routes sit below, including the trailing slash. */
788
+ readonly sitePath: string
521
789
  /**
522
790
  * Answers a request in the bundle namespace. `undefined` means the path belongs
523
791
  * to no bundle, so the caller falls through to its own 404.
524
792
  */
525
793
  handle(request: Request, url: URL, principal: Principal): Promise<Response | undefined>
794
+ /**
795
+ * Answers a member or public route below `/crombolo/bundle/`; `undefined`
796
+ * only for a path outside it.
797
+ */
798
+ site(request: Request, url: URL): Promise<Response | undefined>
799
+ }
800
+
801
+ const SAFE_METHODS = new Set(['GET', 'HEAD'])
802
+ const SITE_METHODS = 'GET, POST, PUT, DELETE'
803
+ const BEARER = /^Bearer\s+(\S+)\s*$/i
804
+
805
+ const text = (body: string, status: number, headers: Record<string, string> = {}) =>
806
+ new Response(body, {
807
+ status,
808
+ headers: { 'content-type': 'text/plain; charset=utf-8', ...headers },
809
+ })
810
+
811
+ const freezeMember = (member: BundleMember): BundleMember =>
812
+ Object.freeze({
813
+ key: member.key,
814
+ name: member.name,
815
+ username: member.username,
816
+ email: member.email,
817
+ groups: Object.freeze([...member.groups]),
818
+ })
819
+
820
+ /** Whether a member is in one of the groups, matched as `memberMay` matches them: in any case. */
821
+ const inGroups = (member: BundleMember, groups: readonly string[]) => {
822
+ const held = new Set(member.groups.map((group) => group.toLowerCase()))
823
+ return groups.some((group) => held.has(group.toLowerCase()))
526
824
  }
527
825
 
528
826
  /**
@@ -538,6 +836,7 @@ export function createServerBundles(options: ServerBundlesOptions): ServerBundle
538
836
  throw new Error(`The configured bundles cannot be mounted:\n- ${problems.join('\n- ')}`)
539
837
 
540
838
  const basePath = `${options.pluginApiPath}/${BUNDLE_API_SEGMENT}/`
839
+ const sitePath = `${BUNDLE_SITE_PATH}/`
541
840
  const byId = new Map(options.bundles.map((bundle) => [bundle.id, bundle]))
542
841
  const logs = new Map(options.bundles.map((bundle) => [bundle.id, options.log(bundle.id)]))
543
842
 
@@ -551,77 +850,232 @@ export function createServerBundles(options: ServerBundlesOptions): ServerBundle
551
850
  section: bundle.section,
552
851
  capabilities: bundle.capabilities,
553
852
  prefix: `${basePath}${bundle.id}`,
554
- routes: bundle.routes.map((route) => ({ method: route.method, path: route.path })),
853
+ sitePrefix: `${sitePath}${bundle.id}`,
854
+ routes: bundle.routes.map((route) => ({
855
+ method: route.method,
856
+ path: route.path,
857
+ audience: routeAudience(route),
858
+ })),
555
859
  }
556
860
  })
557
861
  const names = new Map(mounted.map((bundle) => [bundle.id, bundle.name]))
558
862
 
559
- /** Only the declared capabilities, frozen, so a handler cannot reach further. */
560
863
  // Built once per bundle, each over that bundle's schema alone.
561
864
  const tables = new Map(
562
865
  options.bundles
563
866
  .filter((bundle) => bundle.capabilities.includes('tables'))
564
867
  .map((bundle) => [bundle.id, options.tables?.(bundle)]),
565
868
  )
566
- const contextFor = (bundle: ServerBundle): Pick<BundleHost, BundleCapability> => {
869
+ /** Only the declared capabilities, frozen, so a handler cannot reach further. */
870
+ const contextFor = (
871
+ bundle: ServerBundle,
872
+ caller: BundleCaller,
873
+ ): Pick<BundleHost, BundleCapability> => {
567
874
  const host: Record<string, unknown> = {}
568
- for (const capability of bundle.capabilities)
569
- host[capability] =
570
- capability === 'log'
875
+ for (const capability of bundle.capabilities) {
876
+ const forCaller = capability === 'tables' ? undefined : options.callerHost?.[capability]
877
+ host[capability] = forCaller
878
+ ? forCaller(caller, bundle)
879
+ : capability === 'log'
571
880
  ? (logs.get(bundle.id) as BundleLog)
572
881
  : capability === 'tables'
573
882
  ? tables.get(bundle.id)
574
883
  : options.host[capability]
884
+ }
575
885
  return Object.freeze(host) as Pick<BundleHost, BundleCapability>
576
886
  }
577
887
 
888
+ /** The bundle and the path below it, for a request under `prefix`. */
889
+ const locate = (pathname: string, prefix: string) => {
890
+ const rest = pathname.slice(prefix.length)
891
+ const slash = rest.indexOf('/')
892
+ const bundle = byId.get(slash === -1 ? rest : rest.slice(0, slash))
893
+ const requested = (slash === -1 ? '' : rest.slice(slash + 1)).replace(/\/$/, '')
894
+ return { bundle, requested }
895
+ }
896
+
897
+ /** The route for this path and method among `routes`, or the 404 or 405 to answer. */
898
+ const find = (
899
+ routes: readonly ServerBundleRoute[],
900
+ requested: string,
901
+ method: string,
902
+ ): { route: ServerBundleRoute; params: Record<string, string> } | { refused: Response } => {
903
+ let pathExists = false
904
+ for (const route of routes) {
905
+ const params = matchRoute(route.path, requested)
906
+ if (!params) continue
907
+ pathExists = true
908
+ if (route.method === method) return { route, params }
909
+ }
910
+ return {
911
+ refused: pathExists
912
+ ? text('Method Not Allowed', 405, { allow: SITE_METHODS })
913
+ : text('Not Found', 404),
914
+ }
915
+ }
916
+
917
+ /** A bundle's mistake is its own 500, named, rather than an unhandled rejection in the request path. */
918
+ const dispatch = async (
919
+ bundle: ServerBundle,
920
+ route: ServerBundleRoute,
921
+ context: Omit<BundleRequestBase<BundleCapability, BundleTables>, 'host'> & {
922
+ principal?: Principal
923
+ member?: BundleMember
924
+ },
925
+ ): Promise<Response> => {
926
+ try {
927
+ const handler = route.handler as (context: unknown) => Response | Promise<Response>
928
+ return await handler({ ...context, host: contextFor(bundle, context.caller) })
929
+ } catch (error) {
930
+ logs.get(bundle.id)?.error('The bundle {bundle} failed to answer {method} {path}', {
931
+ bundle: names.get(bundle.id),
932
+ method: context.request.method.toUpperCase(),
933
+ path: context.url.pathname,
934
+ error,
935
+ })
936
+ return new Response('Internal Server Error', { status: 500 })
937
+ }
938
+ }
939
+
940
+ const limiters = new Map<ServerBundleRoute, RateLimiter>()
941
+ for (const bundle of options.bundles)
942
+ for (const route of bundle.routes)
943
+ if (route.rateLimit)
944
+ limiters.set(
945
+ route,
946
+ new RateLimiter({
947
+ max: route.rateLimit.max,
948
+ windowMs: route.rateLimit.perSeconds * 1000,
949
+ now: options.site?.now,
950
+ }),
951
+ )
952
+ const tooMany = (wait: number) =>
953
+ text('Too many requests. Try again in a moment.', 429, { 'retry-after': String(wait) })
954
+
955
+ /** Who is calling a member route, or the refusal to answer instead. */
956
+ const identify = async (
957
+ request: Request,
958
+ route: ServerBundleRoute,
959
+ ): Promise<{ caller: BundleCaller & { kind: 'member' } } | { refused: Response }> => {
960
+ const bearer = BEARER.exec(request.headers.get('authorization') ?? '')?.[1]
961
+ let caller: BundleCaller & { kind: 'member' }
962
+ if (bearer) {
963
+ // A token's scopes never widen the route: it says only who the member is.
964
+ const member = await options.site?.memberByToken?.(bearer)
965
+ if (!member)
966
+ return {
967
+ refused: text('Sign in to continue.', 401, {
968
+ 'www-authenticate': 'Bearer error="invalid_token"',
969
+ }),
970
+ }
971
+ caller = Object.freeze({ kind: 'member', member: freezeMember(member), via: 'token' })
972
+ } else {
973
+ const session = await options.site?.session(request)
974
+ if (!session) return { refused: text('Sign in to continue.', 401) }
975
+ // A cookie is sent whichever site made the request; only a page of this
976
+ // one can read the token to send with it.
977
+ if (
978
+ !SAFE_METHODS.has(request.method.toUpperCase()) &&
979
+ !(await session.verify(request.headers.get(ANTIFORGERY_HEADER)))
980
+ )
981
+ return {
982
+ refused: text(
983
+ `This request was refused because it did not come from a page of this site. Add <AntiforgeryMeta /> to the page's layout, and send the request with crombolo.fetch from /crombolo/bundle.js, which adds the ${ANTIFORGERY_HEADER} header.`,
984
+ 403,
985
+ ),
986
+ }
987
+ caller = Object.freeze({
988
+ kind: 'member',
989
+ member: freezeMember(session.member),
990
+ via: 'cookie',
991
+ })
992
+ }
993
+ const audience = routeAudience(route)
994
+ if (typeof audience === 'object' && !inGroups(caller.member, audience.member.groups))
995
+ return { refused: text('Your account does not have access to this.', 403) }
996
+ return { caller }
997
+ }
998
+
999
+ const answerSite = async (request: Request, url: URL): Promise<Response> => {
1000
+ const { bundle, requested } = locate(url.pathname, sitePath)
1001
+ if (!bundle) return text('Not Found', 404)
1002
+ const cors = options.site?.cors
1003
+ if (isPreflight(request) && cors && (cors.any || cors.origins.size > 0))
1004
+ return preflightResponse(cors, request, SITE_METHODS)
1005
+
1006
+ // Back-office routes are not routes here at all.
1007
+ const found = find(bundle.routes.filter(onSite), requested, request.method.toUpperCase())
1008
+ if ('refused' in found) return found.refused
1009
+ const { route, params } = found
1010
+ const limiter = limiters.get(route)
1011
+
1012
+ if (limiter && route.rateLimit?.by === 'caller') {
1013
+ const address = options.site?.callerAddress(request) ?? 'unknown'
1014
+ const wait = limiter.take(address)
1015
+ if (wait) return tooMany(wait)
1016
+ }
1017
+ if (routeAudience(route) === 'public')
1018
+ return dispatch(bundle, route, { request, url, params, caller: PUBLIC_CALLER })
1019
+
1020
+ const identified = await identify(request, route)
1021
+ if ('refused' in identified) return identified.refused
1022
+ const { caller } = identified
1023
+ if (limiter && route.rateLimit?.by === 'member') {
1024
+ const wait = limiter.take(caller.member.key.toLowerCase())
1025
+ if (wait) return tooMany(wait)
1026
+ }
1027
+ const response = await dispatch(bundle, route, {
1028
+ request,
1029
+ url,
1030
+ params,
1031
+ caller,
1032
+ member: caller.member,
1033
+ })
1034
+ // One member's answer is never a shared cache's to keep.
1035
+ if (!response.headers.has('cache-control'))
1036
+ try {
1037
+ response.headers.set('cache-control', 'private, no-store')
1038
+ } catch {
1039
+ // A response built with immutable headers keeps them.
1040
+ }
1041
+ return response
1042
+ }
1043
+
578
1044
  return {
579
1045
  mounted,
580
1046
  basePath,
1047
+ sitePath,
581
1048
  async handle(request, url, principal) {
582
1049
  const pathname = url.pathname
583
1050
  if (!pathname.startsWith(basePath)) return undefined
584
- const rest = pathname.slice(basePath.length)
585
- const slash = rest.indexOf('/')
586
- const id = slash === -1 ? rest : rest.slice(0, slash)
587
- const bundle = byId.get(id)
1051
+ const { bundle, requested } = locate(pathname, basePath)
588
1052
  if (!bundle) return undefined
589
1053
 
590
1054
  // Authorisation is the host's, not the bundle's: every route is gated on
591
1055
  // the declared section, and a bundle has no way to opt a route out.
592
1056
  if (!hasSection(principal, bundle.section)) return new Response('Forbidden', { status: 403 })
593
1057
 
594
- const requested = (slash === -1 ? '' : rest.slice(slash + 1)).replace(/\/$/, '')
595
- const method = request.method.toUpperCase()
596
- let pathExists = false
597
- for (const route of bundle.routes) {
598
- const params = matchRoute(route.path, requested)
599
- if (!params) continue
600
- pathExists = true
601
- if (route.method !== method) continue
602
- try {
603
- return await route.handler({
604
- request,
605
- url,
606
- principal,
607
- params,
608
- host: contextFor(bundle),
609
- })
610
- } catch (error) {
611
- // A bundle's mistake is its own 500, named, rather than an unhandled
612
- // rejection in the request path.
613
- logs.get(bundle.id)?.error('The bundle {bundle} failed to answer {method} {path}', {
614
- bundle: names.get(bundle.id),
615
- method,
616
- path: pathname,
617
- error,
618
- })
619
- return new Response('Internal Server Error', { status: 500 })
620
- }
621
- }
622
- return new Response(pathExists ? 'Method Not Allowed' : 'Not Found', {
623
- status: pathExists ? 405 : 404,
1058
+ const routes = bundle.routes.filter((route) => !onSite(route))
1059
+ const found = find(routes, requested, request.method.toUpperCase())
1060
+ if ('refused' in found)
1061
+ return new Response(found.refused.status === 405 ? 'Method Not Allowed' : 'Not Found', {
1062
+ status: found.refused.status,
1063
+ })
1064
+ return dispatch(bundle, found.route, {
1065
+ request,
1066
+ url,
1067
+ params: found.params,
1068
+ principal,
1069
+ caller: Object.freeze({ kind: 'backoffice', principal }),
624
1070
  })
625
1071
  },
1072
+ async site(request, url) {
1073
+ if (!url.pathname.startsWith(sitePath)) return undefined
1074
+ const response = await answerSite(request, url)
1075
+ const cors = options.site?.cors
1076
+ return cors ? withCors(cors, request, response) : response
1077
+ },
626
1078
  }
627
1079
  }
1080
+
1081
+ const PUBLIC_CALLER: BundleCaller = Object.freeze({ kind: 'public' })