@crombolo/server 0.36.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.
package/src/bundles.ts CHANGED
@@ -45,9 +45,14 @@
45
45
  * site's files.
46
46
  */
47
47
 
48
- import { type CorsPolicy, isPreflight, preflightResponse, withCors } from '@crombolo/api-delivery'
49
48
  import { hasCultureAccess, hasSection, type Principal } from '@crombolo/api-management'
50
- import { BUNDLE_ID, type BundlePackage, peerRangeProblem } from '@crombolo/backoffice-host'
49
+ import {
50
+ BUNDLE_ID,
51
+ BUNDLE_SCHEMA_VERSION,
52
+ type BundlePackage,
53
+ peerRangeProblem,
54
+ } from '@crombolo/backoffice-host'
55
+ import type { Middleware, RouteMethod, SiteRoute } from '@crombolo/common'
51
56
  import {
52
57
  type AppAlias,
53
58
  type ExtensionSectionAlias,
@@ -67,29 +72,30 @@ import {
67
72
  type RedirectTargetKind,
68
73
  } from '@crombolo/data'
69
74
  import {
70
- ANTIFORGERY_HEADER,
71
- BUNDLE_SITE_PATH,
72
75
  normaliseRedirectPath,
73
76
  type PublishedCache,
77
+ type PublishedContent,
78
+ type RequestMember,
79
+ type SiteServices,
74
80
  } from '@crombolo/render'
75
81
  import type { BundleMedia, BundleMediaDeclaration } from './bundle-media.ts'
76
82
  import type { BundleForms } from './form-types.ts'
77
83
  import type { BundleIdentityProviders } from './identity-provider-overrides.ts'
78
- import { RateLimiter } from './rate-limit.ts'
84
+ import type { DeclaredRoute } from './routes.ts'
79
85
  import type { BundleEvents } from './webhooks.ts'
80
86
 
81
87
  /** The segment every bundle's routes hang below, inside the plugin API. */
82
88
  export const BUNDLE_API_SEGMENT = 'bundle'
83
89
 
84
90
  /**
85
- * A route path below the bundle's namespace. Literal segments, optionally one
86
- * `:name` parameter each, and no leading or trailing slash — so a path cannot
87
- * traverse, and `''` means the namespace root.
91
+ * A back-office route's path below the bundle's namespace. Literal segments,
92
+ * optionally one `:name` parameter each, and no leading or trailing slash — so
93
+ * a path cannot traverse, and `''` means the namespace root.
88
94
  */
89
95
  const ROUTE_PATH =
90
96
  /^(?:[a-z0-9][a-z0-9-]*|:[a-z][a-z0-9]*)(?:\/(?:[a-z0-9][a-z0-9-]*|:[a-z][a-z0-9]*))*$/
91
97
 
92
- export type BundleMethod = 'GET' | 'POST' | 'PUT' | 'DELETE'
98
+ export type BundleMethod = RouteMethod
93
99
 
94
100
  /** What the host writes to the site's log on the bundle's behalf. */
95
101
  export interface BundleLog {
@@ -227,123 +233,40 @@ export interface BundleMember {
227
233
  }
228
234
 
229
235
  /**
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.
236
+ * Who a request is from, as the host resolved it before dispatch: a back-office
237
+ * route's user, a signed-in member, or the public. Frozen.
254
238
  */
255
239
  export type BundleCaller =
256
240
  | { readonly kind: 'backoffice'; readonly principal: Principal }
257
241
  | { readonly kind: 'member'; readonly member: BundleMember; readonly via: 'cookie' | 'token' }
258
242
  | { readonly kind: 'public' }
259
243
 
260
- interface BundleRequestBase<C extends BundleCapability, T extends BundleTables> {
261
- request: Request
262
- url: URL
263
- /** The `:name` segments of the matched route. */
264
- params: Record<string, string>
265
- /** Only what the bundle declared, frozen. */
266
- host: HostFor<C, T>
267
- /** Who is asking, which is what a capability acting for the caller reads. */
268
- caller: BundleCaller
269
- }
270
-
271
- /** What a back-office route's handler is given. */
272
- export interface BundleRequest<
273
- C extends BundleCapability = BundleCapability,
274
- T extends BundleTables = BundleTables,
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 {
301
- method: BundleMethod
302
- /** Below the bundle's namespace; `''` is the namespace root. */
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
313
- handler(context: BundleRequest<C, T>): Response | Promise<Response>
314
- }
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<
244
+ /**
245
+ * What a bundle's route handler is given besides 211's context: its declared
246
+ * capabilities, acting for the caller, and on a back-office route the user.
247
+ */
248
+ export interface BundleRouteContext<
328
249
  C extends BundleCapability = BundleCapability,
329
250
  T extends BundleTables = BundleTables,
330
- > extends BundleRouteBase {
331
- audience: 'public'
332
- rateLimit?: BundleRateLimit
333
- handler(context: BundlePublicRequest<C, T>): Response | Promise<Response>
251
+ > {
252
+ /** Only what the bundle declared, frozen. */
253
+ bundle: HostFor<C, T>
254
+ caller: BundleCaller
255
+ /** On a back-office route: already authenticated, and holding the bundle's section. */
256
+ principal?: Principal
334
257
  }
335
258
 
336
- export type ServerBundleRoute<
259
+ /**
260
+ * A bundle's route (story 211): 211's contract, with its capabilities in the
261
+ * context. `audience: 'backoffice'` answers below the bundle's back-office
262
+ * namespace at a relative path; otherwise it answers on the site at its path.
263
+ */
264
+ export type BundleRoute<
337
265
  C extends BundleCapability = BundleCapability,
338
266
  T extends BundleTables = BundleTables,
339
- > = BackofficeBundleRoute<C, T> | MemberBundleRoute<C, T> | PublicBundleRoute<C, T>
267
+ > = SiteRoute<SiteServices, RequestMember, BundleRouteContext<C, T>>
340
268
 
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'
269
+ const onSite = (route: BundleRoute) => route.options.audience !== 'backoffice'
347
270
 
348
271
  export interface ServerBundle<
349
272
  C extends BundleCapability = BundleCapability,
@@ -360,7 +283,8 @@ export interface ServerBundle<
360
283
  */
361
284
  section: BundleSection
362
285
  capabilities: readonly C[]
363
- routes: readonly ServerBundleRoute<C, T>[]
286
+ /** Its routes, in 211's contract: back-office ones for its screens, site ones at their paths. */
287
+ routes?: readonly BundleRoute<C, T>[]
364
288
  /** Tables the bundle owns, from `defineBundleTables`, under its own id. */
365
289
  tables?: T
366
290
  /**
@@ -376,6 +300,12 @@ export interface ServerBundle<
376
300
  * retried on failure, and in the delivery log (docs/webhooks.md).
377
301
  */
378
302
  events?: BundleEvents
303
+ /**
304
+ * Middleware the bundle offers a site (story 210). It runs only where the
305
+ * site lists it in its config's `middleware`: installing a bundle never adds
306
+ * to the chain by itself.
307
+ */
308
+ middleware?: Middleware<SiteServices, PublishedContent, RequestMember>
379
309
  }
380
310
 
381
311
  /** A bundle as mounted, with the prefix its routes answer below. */
@@ -388,9 +318,7 @@ export interface MountedBundle {
388
318
  capabilities: readonly BundleCapability[]
389
319
  /** `<backoffice>/crombolo/api/bundle/<id>`. */
390
320
  prefix: string
391
- /** `/crombolo/bundle/<id>`, where its member and public routes answer. */
392
- sitePrefix: string
393
- routes: readonly { method: BundleMethod; path: string; audience: BundleAudience }[]
321
+ routes: readonly { methods: readonly string[]; path: string; audience: 'site' | 'backoffice' }[]
394
322
  }
395
323
 
396
324
  /**
@@ -465,19 +393,32 @@ export function validateServerBundles(
465
393
  }
466
394
  for (const problem of mediaProblems(bundle))
467
395
  problems.push(`Bundle "${label}" media: ${problem}.`)
396
+ const owner = packages.find((pkg) => pkg.id === bundle.id)
397
+ if (owner?.carries.server && (owner.field.schemaVersion ?? 1) < BUNDLE_SCHEMA_VERSION)
398
+ problems.push(
399
+ `Bundle "${label}" is written for bundle schema ${owner.field.schemaVersion ?? 1}; this release reads ${BUNDLE_SCHEMA_VERSION}. Its routes are route handlers since 0.37: see "Routes" in docs/bundles.md, then set "crombolo.schemaVersion": ${BUNDLE_SCHEMA_VERSION}.`,
400
+ )
468
401
  const routes = new Set<string>()
469
- for (const route of bundle.routes) {
470
- if (route.path !== '' && !ROUTE_PATH.test(route.path))
402
+ for (const route of bundle.routes ?? []) {
403
+ if (!route || typeof route !== 'object' || !route.handlers || !route.options) {
404
+ problems.push(`Bundle "${label}" declares a route not built with route(path, handlers).`)
405
+ continue
406
+ }
407
+ if (!onSite(route) && route.path !== '' && !ROUTE_PATH.test(route.path))
408
+ problems.push(
409
+ `Bundle "${label}" declares the back-office route "${route.path}", which is not a plain path of segments below its namespace.`,
410
+ )
411
+ if (
412
+ !onSite(route) &&
413
+ (route.options.members || route.options.rateLimit || route.options.cors)
414
+ )
471
415
  problems.push(
472
- `Bundle "${label}" declares the route path "${route.path}", which is not a plain path of segments.`,
416
+ `Bundle "${label}" route "${route.path}": members, rateLimit and cors apply to site routes, not back-office ones.`,
473
417
  )
474
- const signature = `${route.method} ${route.path}`
475
418
  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}.`)
419
+ if (routes.has(`${where} ${route.path}`))
420
+ problems.push(`Bundle "${label}" declares the route "${route.path}" twice.`)
421
+ routes.add(`${where} ${route.path}`)
481
422
  }
482
423
  }
483
424
  return problems
@@ -526,57 +467,13 @@ function mediaProblems(bundle: ServerBundle): string[] {
526
467
  return problems
527
468
  }
528
469
 
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
470
  /** Member group names a site route requires, for checking at boot that they exist. */
573
471
  export function bundleRouteGroups(bundles: readonly ServerBundle[]): string[] {
574
472
  const groups = new Set<string>()
575
473
  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)
474
+ for (const route of bundle.routes ?? []) {
475
+ const members = route.options.members
476
+ if (typeof members === 'object') for (const group of members.groups) groups.add(group)
580
477
  }
581
478
  return [...groups]
582
479
  }
@@ -743,24 +640,6 @@ export type CallerCapabilities = {
743
640
  ) => BundleHost[K]
744
641
  }
745
642
 
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
-
764
643
  export interface ServerBundlesOptions {
765
644
  bundles: readonly ServerBundle[]
766
645
  /** The bundle packages the site depends on, from discovery. */
@@ -776,53 +655,45 @@ export interface ServerBundlesOptions {
776
655
  log(bundleId: string): BundleLog
777
656
  /** A bundle's own tables, resolved against its schema alone; absent where none are offered. */
778
657
  tables?(bundle: ServerBundle): BundleTablesCapability | undefined
779
- /** Without it no member can be identified, so a member route answers 401. */
780
- site?: BundleSiteOptions
781
658
  }
782
659
 
660
+ /** Runs a route through 211's pipeline: the server's `routes.invoke`. */
661
+ export type RouteInvoker = (
662
+ entry: DeclaredRoute,
663
+ request: Request,
664
+ url: URL,
665
+ params: Record<string, string>,
666
+ options?: { checks: boolean; extra?: Record<string, unknown> },
667
+ ) => Promise<Response>
668
+
783
669
  export interface ServerBundles {
784
670
  readonly mounted: readonly MountedBundle[]
785
- /** The prefix every bundle route sits below, including the trailing slash. */
671
+ /** The prefix every back-office bundle route sits below, including the trailing slash. */
786
672
  readonly basePath: string
787
- /** The prefix member and public routes sit below, including the trailing slash. */
788
- readonly sitePath: string
789
673
  /**
790
- * Answers a request in the bundle namespace. `undefined` means the path belongs
791
- * to no bundle, so the caller falls through to its own 404.
674
+ * Answers a request in the back-office namespace through `invoke`.
675
+ * `undefined` means the path belongs to no bundle, so the caller falls
676
+ * through to its own 404.
792
677
  */
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>
678
+ handle(
679
+ request: Request,
680
+ url: URL,
681
+ principal: Principal,
682
+ invoke: RouteInvoker,
683
+ ): Promise<Response | undefined>
684
+ /** The bundles' site routes, for the server's route table, each given its bundle's capabilities. */
685
+ siteRoutes(): DeclaredRoute[]
799
686
  }
800
687
 
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 =>
688
+ const freezeMember = (member: RequestMember): BundleMember =>
812
689
  Object.freeze({
813
690
  key: member.key,
814
691
  name: member.name,
815
692
  username: member.username,
816
693
  email: member.email,
817
- groups: Object.freeze([...member.groups]),
694
+ groups: Object.freeze([...member.roles]),
818
695
  })
819
696
 
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()))
824
- }
825
-
826
697
  /**
827
698
  * Mounts the site's bundles, or fails the boot saying why.
828
699
  *
@@ -836,7 +707,6 @@ export function createServerBundles(options: ServerBundlesOptions): ServerBundle
836
707
  throw new Error(`The configured bundles cannot be mounted:\n- ${problems.join('\n- ')}`)
837
708
 
838
709
  const basePath = `${options.pluginApiPath}/${BUNDLE_API_SEGMENT}/`
839
- const sitePath = `${BUNDLE_SITE_PATH}/`
840
710
  const byId = new Map(options.bundles.map((bundle) => [bundle.id, bundle]))
841
711
  const logs = new Map(options.bundles.map((bundle) => [bundle.id, options.log(bundle.id)]))
842
712
 
@@ -850,15 +720,13 @@ export function createServerBundles(options: ServerBundlesOptions): ServerBundle
850
720
  section: bundle.section,
851
721
  capabilities: bundle.capabilities,
852
722
  prefix: `${basePath}${bundle.id}`,
853
- sitePrefix: `${sitePath}${bundle.id}`,
854
- routes: bundle.routes.map((route) => ({
855
- method: route.method,
723
+ routes: (bundle.routes ?? []).map((route) => ({
724
+ methods: Object.keys(route.handlers),
856
725
  path: route.path,
857
- audience: routeAudience(route),
726
+ audience: onSite(route) ? ('site' as const) : ('backoffice' as const),
858
727
  })),
859
728
  }
860
729
  })
861
- const names = new Map(mounted.map((bundle) => [bundle.id, bundle.name]))
862
730
 
863
731
  // Built once per bundle, each over that bundle's schema alone.
864
732
  const tables = new Map(
@@ -885,195 +753,58 @@ export function createServerBundles(options: ServerBundlesOptions): ServerBundle
885
753
  return Object.freeze(host) as Pick<BundleHost, BundleCapability>
886
754
  }
887
755
 
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
-
1044
756
  return {
1045
757
  mounted,
1046
758
  basePath,
1047
- sitePath,
1048
- async handle(request, url, principal) {
759
+ siteRoutes() {
760
+ return options.bundles.flatMap((bundle) =>
761
+ (bundle.routes ?? []).filter(onSite).map(
762
+ (route): DeclaredRoute => ({
763
+ route: route as SiteRoute,
764
+ owner: `the bundle ${bundle.id}`,
765
+ extra: ({ member, via }) => {
766
+ const caller: BundleCaller = member
767
+ ? Object.freeze({
768
+ kind: 'member',
769
+ member: freezeMember(member as RequestMember),
770
+ via,
771
+ })
772
+ : PUBLIC_CALLER
773
+ return { bundle: contextFor(bundle, caller), caller }
774
+ },
775
+ }),
776
+ ),
777
+ )
778
+ },
779
+ async handle(request, url, principal, invoke) {
1049
780
  const pathname = url.pathname
1050
781
  if (!pathname.startsWith(basePath)) return undefined
1051
- const { bundle, requested } = locate(pathname, basePath)
782
+ const rest = pathname.slice(basePath.length)
783
+ const slash = rest.indexOf('/')
784
+ const bundle = byId.get(slash === -1 ? rest : rest.slice(0, slash))
1052
785
  if (!bundle) return undefined
786
+ const requested = (slash === -1 ? '' : rest.slice(slash + 1)).replace(/\/$/, '')
1053
787
 
1054
788
  // Authorisation is the host's, not the bundle's: every route is gated on
1055
789
  // the declared section, and a bundle has no way to opt a route out.
1056
790
  if (!hasSection(principal, bundle.section)) return new Response('Forbidden', { status: 403 })
1057
791
 
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 }),
1070
- })
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
792
+ for (const route of (bundle.routes ?? []).filter((candidate) => !onSite(candidate))) {
793
+ const params = matchRoute(route.path, requested)
794
+ if (!params) continue
795
+ const caller: BundleCaller = Object.freeze({ kind: 'backoffice', principal })
796
+ return invoke(
797
+ { route: route as SiteRoute, owner: `the bundle ${bundle.id}` },
798
+ request,
799
+ url,
800
+ params,
801
+ {
802
+ checks: false,
803
+ extra: { bundle: contextFor(bundle, caller), caller, principal },
804
+ },
805
+ )
806
+ }
807
+ return new Response('Not Found', { status: 404 })
1077
808
  },
1078
809
  }
1079
810
  }