@crombolo/server 0.36.2 → 0.38.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/package.json +15 -13
- package/src/access.ts +29 -27
- package/src/adapters/audit.ts +1 -1
- package/src/adapters/blueprints.ts +22 -13
- package/src/adapters/content.ts +1 -1
- package/src/adapters/dictionary.ts +1 -1
- package/src/adapters/documents.ts +17 -10
- package/src/adapters/elements.ts +47 -37
- package/src/adapters/file-system.ts +1 -1
- package/src/adapters/health.ts +33 -5
- package/src/adapters/media.ts +12 -8
- package/src/adapters/member-groups.ts +8 -6
- package/src/adapters/members.ts +6 -4
- package/src/adapters/public-access.ts +7 -5
- package/src/adapters/redirects.ts +1 -1
- package/src/adapters/references.ts +1 -1
- package/src/adapters/relations.ts +1 -1
- package/src/adapters/schema-files.ts +33 -1
- package/src/adapters/search-index.ts +1 -1
- package/src/adapters/template-files.ts +6 -1
- package/src/adapters/template-query.ts +1 -1
- package/src/adapters/users.ts +13 -13
- package/src/adapters/webhooks.ts +1 -1
- package/src/anonymise-rules.ts +83 -0
- package/src/approvals-api.ts +1 -1
- package/src/approvals.ts +75 -38
- package/src/back-office-url.ts +20 -0
- package/src/backup.ts +26 -2
- package/src/bundle-code.ts +1 -1
- package/src/bundle-grants.ts +265 -0
- package/src/bundle-install.ts +13 -2
- package/src/bundle-media.ts +12 -11
- package/src/bundles.ts +258 -444
- package/src/component-snippets.ts +1 -1
- package/src/components.ts +48 -7
- package/src/config.ts +141 -4
- package/src/content-notifications.ts +13 -9
- package/src/content-operations.ts +23 -65
- package/src/content-query.ts +1 -1
- package/src/core.ts +663 -0
- package/src/cron.ts +139 -0
- package/src/custom-tables.ts +274 -0
- package/src/database.ts +22 -14
- package/src/dictionary-transfer.ts +1 -1
- package/src/git-routes.ts +1 -1
- package/src/identity-provider-overrides.ts +18 -16
- package/src/imaging.ts +65 -15
- package/src/index.ts +14 -1
- package/src/islands.ts +197 -0
- package/src/job-wake.ts +23 -0
- package/src/live-reload.ts +195 -0
- package/src/log-viewer.ts +6 -1
- package/src/marketplace.ts +82 -10
- package/src/media-access.ts +12 -9
- package/src/member-auth.ts +6 -4
- package/src/middleware.ts +236 -0
- package/src/models-builder.ts +1 -1
- package/src/node-operations.ts +122 -0
- package/src/owner-jobs.ts +428 -0
- package/src/ports.ts +39 -154
- package/src/preview-tokens.ts +6 -12
- package/src/remote.ts +3 -1
- package/src/routes.ts +420 -0
- package/src/schema.ts +8 -3
- package/src/seed/compile.ts +7 -5
- package/src/seed/export.ts +6 -4
- package/src/seo.ts +2 -2
- package/src/server.ts +866 -483
- package/src/settings.ts +49 -2
- package/src/site-data.ts +195 -0
- package/src/site-file.ts +30 -4
- package/src/site-queries.ts +140 -0
- package/src/site-replace.ts +25 -19
- package/src/site-sections.ts +1 -1
- package/src/site-services.ts +116 -0
- package/src/status-pages.ts +142 -0
- package/src/status.ts +11 -9
- package/src/url-settings.ts +1 -2
- package/src/webhook-files.ts +18 -1
- package/src/webhooks.ts +83 -15
- package/src/worker-watch.ts +73 -0
- package/src/worker.ts +138 -0
- package/src/bundle-tables.ts +0 -161
package/src/bundles.ts
CHANGED
|
@@ -38,16 +38,23 @@
|
|
|
38
38
|
* release refuses the boot.
|
|
39
39
|
*
|
|
40
40
|
* - A bundle that declares `tables` owns them: its own ledgered chain, written
|
|
41
|
-
* with the declarative builder in `@crombolo/data`,
|
|
42
|
-
*
|
|
41
|
+
* with the declarative builder in `@crombolo/data`, in a schema or file of
|
|
42
|
+
* its own, and `context.bundle.database`, a Kysely handle on the connection
|
|
43
|
+
* that reaches only them (`docs/bundles.md`, Part 4; story 189).
|
|
43
44
|
*
|
|
44
|
-
* Deliberately not offered:
|
|
45
|
+
* Deliberately not offered: crombolo's own `Db`, and anything that writes the
|
|
45
46
|
* site's files.
|
|
46
47
|
*/
|
|
47
48
|
|
|
48
|
-
import {
|
|
49
|
-
import {
|
|
50
|
-
|
|
49
|
+
import { hasCultureAccess, hasSection, type Principal } from '@crombolo/api-management/domain'
|
|
50
|
+
import {
|
|
51
|
+
BUNDLE_ID,
|
|
52
|
+
BUNDLE_SCHEMA_VERSION,
|
|
53
|
+
type BundlePackage,
|
|
54
|
+
peerRangeProblem,
|
|
55
|
+
schemaProblem,
|
|
56
|
+
} from '@crombolo/backoffice-host/registry'
|
|
57
|
+
import type { Middleware, RouteMethod, SiteRoute } from '@crombolo/common'
|
|
51
58
|
import {
|
|
52
59
|
type AppAlias,
|
|
53
60
|
type ExtensionSectionAlias,
|
|
@@ -57,39 +64,44 @@ import {
|
|
|
57
64
|
} from '@crombolo/core'
|
|
58
65
|
import {
|
|
59
66
|
type BundleTables,
|
|
60
|
-
type BundleTablesCapability,
|
|
61
67
|
bundleTablesCompatibility,
|
|
62
|
-
|
|
68
|
+
compileTables,
|
|
63
69
|
type Db,
|
|
64
70
|
type RedirectMatchKind,
|
|
65
71
|
RedirectRepository,
|
|
66
72
|
type RedirectRow,
|
|
67
73
|
type RedirectTargetKind,
|
|
74
|
+
SITE_OWNER,
|
|
75
|
+
type TablesDatabase,
|
|
68
76
|
} from '@crombolo/data'
|
|
69
77
|
import {
|
|
70
|
-
ANTIFORGERY_HEADER,
|
|
71
|
-
BUNDLE_SITE_PATH,
|
|
72
78
|
normaliseRedirectPath,
|
|
73
79
|
type PublishedCache,
|
|
80
|
+
type PublishedContent,
|
|
81
|
+
type RequestMember,
|
|
82
|
+
type SiteServices,
|
|
74
83
|
} from '@crombolo/render'
|
|
84
|
+
import { anonymiseProblems } from './anonymise-rules.ts'
|
|
85
|
+
import { declaredPermissions, gated, permissionProblems, waitingResponse } from './bundle-grants.ts'
|
|
75
86
|
import type { BundleMedia, BundleMediaDeclaration } from './bundle-media.ts'
|
|
76
87
|
import type { BundleForms } from './form-types.ts'
|
|
77
88
|
import type { BundleIdentityProviders } from './identity-provider-overrides.ts'
|
|
78
|
-
import {
|
|
89
|
+
import { type JobInfo, type JobSchedule, jobProblems, type OwnerJobs } from './owner-jobs.ts'
|
|
90
|
+
import type { DeclaredRoute } from './routes.ts'
|
|
79
91
|
import type { BundleEvents } from './webhooks.ts'
|
|
80
92
|
|
|
81
93
|
/** The segment every bundle's routes hang below, inside the plugin API. */
|
|
82
94
|
export const BUNDLE_API_SEGMENT = 'bundle'
|
|
83
95
|
|
|
84
96
|
/**
|
|
85
|
-
* A route path below the bundle's namespace. Literal segments,
|
|
86
|
-
* `:name` parameter each, and no leading or trailing slash — so
|
|
87
|
-
* traverse, and `''` means the namespace root.
|
|
97
|
+
* A back-office route's path below the bundle's namespace. Literal segments,
|
|
98
|
+
* optionally one `:name` parameter each, and no leading or trailing slash — so
|
|
99
|
+
* a path cannot traverse, and `''` means the namespace root.
|
|
88
100
|
*/
|
|
89
101
|
const ROUTE_PATH =
|
|
90
102
|
/^(?:[a-z0-9][a-z0-9-]*|:[a-z][a-z0-9]*)(?:\/(?:[a-z0-9][a-z0-9-]*|:[a-z][a-z0-9]*))*$/
|
|
91
103
|
|
|
92
|
-
export type BundleMethod =
|
|
104
|
+
export type BundleMethod = RouteMethod
|
|
93
105
|
|
|
94
106
|
/** What the host writes to the site's log on the bundle's behalf. */
|
|
95
107
|
export interface BundleLog {
|
|
@@ -158,8 +170,6 @@ export interface BundleHost {
|
|
|
158
170
|
log: BundleLog
|
|
159
171
|
/** The identity providers the config declares, and an administrator's overrides of their settings (story 033). */
|
|
160
172
|
identityProviders: BundleIdentityProviders
|
|
161
|
-
/** The bundle's own tables, and only for a bundle that declares some. */
|
|
162
|
-
tables: BundleTablesCapability
|
|
163
173
|
/**
|
|
164
174
|
* Media items in the folders the bundle declares, as the member a route was
|
|
165
175
|
* given or the back-office user; refused on a public route (story 198).
|
|
@@ -202,19 +212,20 @@ export const BUNDLE_CAPABILITIES: readonly BundleCapability[] = [
|
|
|
202
212
|
'redirects',
|
|
203
213
|
'documents',
|
|
204
214
|
'log',
|
|
205
|
-
'tables',
|
|
206
215
|
'identityProviders',
|
|
207
216
|
'media',
|
|
208
217
|
]
|
|
209
218
|
|
|
210
|
-
/**
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
> &
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
219
|
+
/**
|
|
220
|
+
* What a handler is handed: the declared capabilities, and for a bundle that
|
|
221
|
+
* declares tables, `database`, typed from the declaration (story 189).
|
|
222
|
+
*/
|
|
223
|
+
export type HostFor<C extends BundleCapability, T extends BundleTables> = Pick<BundleHost, C> & {
|
|
224
|
+
/** Only for a bundle that declares tables: a Kysely handle on them and nothing else. */
|
|
225
|
+
readonly database: TablesDatabase<T>
|
|
226
|
+
/** Only for a bundle that declares jobs: queue one, or read how one is going (story 187). */
|
|
227
|
+
readonly jobs: OwnerJobs
|
|
228
|
+
}
|
|
218
229
|
|
|
219
230
|
/** A signed-in member as a member route is given them: nothing of the back office. */
|
|
220
231
|
export interface BundleMember {
|
|
@@ -227,123 +238,42 @@ export interface BundleMember {
|
|
|
227
238
|
}
|
|
228
239
|
|
|
229
240
|
/**
|
|
230
|
-
* Who
|
|
231
|
-
*
|
|
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.
|
|
241
|
+
* Who a request is from, as the host resolved it before dispatch: a back-office
|
|
242
|
+
* route's user, a signed-in member, or the public. Frozen.
|
|
254
243
|
*/
|
|
255
244
|
export type BundleCaller =
|
|
256
245
|
| { readonly kind: 'backoffice'; readonly principal: Principal }
|
|
257
246
|
| { readonly kind: 'member'; readonly member: BundleMember; readonly via: 'cookie' | 'token' }
|
|
258
247
|
| { readonly kind: 'public' }
|
|
248
|
+
/** A background job (story 187): nobody, treated as the public. */
|
|
249
|
+
| { readonly kind: 'job' }
|
|
259
250
|
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
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<
|
|
251
|
+
/**
|
|
252
|
+
* What a bundle's route handler is given besides 211's context: its declared
|
|
253
|
+
* capabilities, acting for the caller, and on a back-office route the user.
|
|
254
|
+
*/
|
|
255
|
+
export interface BundleRouteContext<
|
|
328
256
|
C extends BundleCapability = BundleCapability,
|
|
329
257
|
T extends BundleTables = BundleTables,
|
|
330
|
-
>
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
258
|
+
> {
|
|
259
|
+
/** Only what the bundle declared, frozen. */
|
|
260
|
+
bundle: HostFor<C, T>
|
|
261
|
+
caller: BundleCaller
|
|
262
|
+
/** On a back-office route: already authenticated, and holding the bundle's section. */
|
|
263
|
+
principal?: Principal
|
|
334
264
|
}
|
|
335
265
|
|
|
336
|
-
|
|
266
|
+
/**
|
|
267
|
+
* A bundle's route (story 211): 211's contract, with its capabilities in the
|
|
268
|
+
* context. `audience: 'backoffice'` answers below the bundle's back-office
|
|
269
|
+
* namespace at a relative path; otherwise it answers on the site at its path.
|
|
270
|
+
*/
|
|
271
|
+
export type BundleRoute<
|
|
337
272
|
C extends BundleCapability = BundleCapability,
|
|
338
273
|
T extends BundleTables = BundleTables,
|
|
339
|
-
> =
|
|
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
|
-
}
|
|
274
|
+
> = SiteRoute<SiteServices, RequestMember, BundleRouteContext<C, T>>
|
|
345
275
|
|
|
346
|
-
const onSite = (route:
|
|
276
|
+
const onSite = (route: BundleRoute) => route.options.audience !== 'backoffice'
|
|
347
277
|
|
|
348
278
|
export interface ServerBundle<
|
|
349
279
|
C extends BundleCapability = BundleCapability,
|
|
@@ -360,7 +290,8 @@ export interface ServerBundle<
|
|
|
360
290
|
*/
|
|
361
291
|
section: BundleSection
|
|
362
292
|
capabilities: readonly C[]
|
|
363
|
-
routes:
|
|
293
|
+
/** Its routes, in 211's contract: back-office ones for its screens, site ones at their paths. */
|
|
294
|
+
routes?: readonly BundleRoute<C, T>[]
|
|
364
295
|
/** Tables the bundle owns, from `defineBundleTables`, under its own id. */
|
|
365
296
|
tables?: T
|
|
366
297
|
/**
|
|
@@ -376,8 +307,30 @@ export interface ServerBundle<
|
|
|
376
307
|
* retried on failure, and in the delivery log (docs/webhooks.md).
|
|
377
308
|
*/
|
|
378
309
|
events?: BundleEvents
|
|
310
|
+
/**
|
|
311
|
+
* Middleware the bundle offers a site (story 210). It runs only where the
|
|
312
|
+
* site lists it in its config's `middleware`: installing a bundle never adds
|
|
313
|
+
* to the chain by itself.
|
|
314
|
+
*/
|
|
315
|
+
middleware?: Middleware<SiteServices, PublishedContent, RequestMember>
|
|
316
|
+
/**
|
|
317
|
+
* Its background jobs, by name (story 187): each `(payload, context)`, given
|
|
318
|
+
* its capabilities for no caller and its own `database`, as a public route
|
|
319
|
+
* would be, with `context.job` for its progress and its signal.
|
|
320
|
+
*/
|
|
321
|
+
jobs?: Record<string, BundleJob<C, T>>
|
|
322
|
+
/** When its jobs run by themselves: cron expressions in a timezone. */
|
|
323
|
+
schedules?: readonly JobSchedule[]
|
|
379
324
|
}
|
|
380
325
|
|
|
326
|
+
/** A bundle's background job (story 187). */
|
|
327
|
+
export type BundleJob<
|
|
328
|
+
C extends BundleCapability = BundleCapability,
|
|
329
|
+
T extends BundleTables = BundleTables,
|
|
330
|
+
// biome-ignore lint/suspicious/noExplicitAny: a payload is the bundle's to type
|
|
331
|
+
P = any,
|
|
332
|
+
> = (payload: P, context: { bundle: HostFor<C, T>; job: JobInfo }) => unknown
|
|
333
|
+
|
|
381
334
|
/** A bundle as mounted, with the prefix its routes answer below. */
|
|
382
335
|
export interface MountedBundle {
|
|
383
336
|
id: string
|
|
@@ -388,9 +341,7 @@ export interface MountedBundle {
|
|
|
388
341
|
capabilities: readonly BundleCapability[]
|
|
389
342
|
/** `<backoffice>/crombolo/api/bundle/<id>`. */
|
|
390
343
|
prefix: string
|
|
391
|
-
|
|
392
|
-
sitePrefix: string
|
|
393
|
-
routes: readonly { method: BundleMethod; path: string; audience: BundleAudience }[]
|
|
344
|
+
routes: readonly { methods: readonly string[]; path: string; audience: 'site' | 'backoffice' }[]
|
|
394
345
|
}
|
|
395
346
|
|
|
396
347
|
/**
|
|
@@ -441,9 +392,13 @@ export function validateServerBundles(
|
|
|
441
392
|
problems.push(
|
|
442
393
|
`Bundle "${label}" asked for the capability "${capability}", which no host offers.`,
|
|
443
394
|
)
|
|
444
|
-
if (bundle.capabilities.includes('tables')
|
|
395
|
+
if ((bundle.capabilities as readonly string[]).includes('tables'))
|
|
396
|
+
problems.push(
|
|
397
|
+
`Bundle "${label}" asks for "tables", which is gone: declaring tables gives its handlers context.bundle.database (docs/bundles.md, Part 4).`,
|
|
398
|
+
)
|
|
399
|
+
if (bundle.tables && bundle.id === SITE_OWNER)
|
|
445
400
|
problems.push(
|
|
446
|
-
`Bundle "${label}"
|
|
401
|
+
`Bundle "${label}" declares tables under the id "${SITE_OWNER}", which names the site's own tables.`,
|
|
447
402
|
)
|
|
448
403
|
if (bundle.tables) {
|
|
449
404
|
if (bundle.tables.id !== bundle.id)
|
|
@@ -451,8 +406,12 @@ export function validateServerBundles(
|
|
|
451
406
|
`Bundle "${label}" declares its tables under the id "${bundle.tables.id}"; a bundle's tables are under its own id.`,
|
|
452
407
|
)
|
|
453
408
|
const owner = packages.find((pkg) => pkg.id === bundle.id)
|
|
454
|
-
|
|
409
|
+
const compiled = compileTables(bundle.tables, owner?.version)
|
|
410
|
+
for (const problem of compiled.problems)
|
|
455
411
|
problems.push(`Bundle "${label}" tables: ${problem}.`)
|
|
412
|
+
if (owner?.field.anonymise !== undefined && compiled.problems.length === 0)
|
|
413
|
+
for (const problem of anonymiseProblems(owner.field.anonymise, compiled.schema))
|
|
414
|
+
problems.push(`Bundle "${label}"'s package.json: crombolo.${problem}.`)
|
|
456
415
|
// Read by an operator's tooling before anything is installed, so it must
|
|
457
416
|
// say what the plan does — derived, not asserted, as core's is.
|
|
458
417
|
if (owner) {
|
|
@@ -463,21 +422,42 @@ export function validateServerBundles(
|
|
|
463
422
|
)
|
|
464
423
|
}
|
|
465
424
|
}
|
|
425
|
+
if (!bundle.tables && packages.find((pkg) => pkg.id === bundle.id)?.field.anonymise)
|
|
426
|
+
problems.push(
|
|
427
|
+
`Bundle "${label}"'s package.json declares "crombolo.anonymise", and the bundle declares no tables for it to describe.`,
|
|
428
|
+
)
|
|
466
429
|
for (const problem of mediaProblems(bundle))
|
|
467
430
|
problems.push(`Bundle "${label}" media: ${problem}.`)
|
|
431
|
+
problems.push(...jobProblems(`Bundle "${label}"`, bundle.jobs, bundle.schedules))
|
|
432
|
+
{
|
|
433
|
+
const pkg = packages.find((candidate) => candidate.id === bundle.id)
|
|
434
|
+
if (pkg?.carries.server && Array.isArray(pkg.field.permissions))
|
|
435
|
+
problems.push(...permissionProblems(label, bundle.capabilities, declaredPermissions(pkg)))
|
|
436
|
+
}
|
|
437
|
+
const owner = packages.find((pkg) => pkg.id === bundle.id)
|
|
438
|
+
if (owner?.carries.server && (owner.field.schemaVersion ?? 1) < BUNDLE_SCHEMA_VERSION)
|
|
439
|
+
problems.push(`Bundle "${label}": ${schemaProblem(owner.field.schemaVersion ?? 1)}.`)
|
|
468
440
|
const routes = new Set<string>()
|
|
469
|
-
for (const route of bundle.routes) {
|
|
470
|
-
if (route
|
|
441
|
+
for (const route of bundle.routes ?? []) {
|
|
442
|
+
if (!route || typeof route !== 'object' || !route.handlers || !route.options) {
|
|
443
|
+
problems.push(`Bundle "${label}" declares a route not built with route(path, handlers).`)
|
|
444
|
+
continue
|
|
445
|
+
}
|
|
446
|
+
if (!onSite(route) && route.path !== '' && !ROUTE_PATH.test(route.path))
|
|
447
|
+
problems.push(
|
|
448
|
+
`Bundle "${label}" declares the back-office route "${route.path}", which is not a plain path of segments below its namespace.`,
|
|
449
|
+
)
|
|
450
|
+
if (
|
|
451
|
+
!onSite(route) &&
|
|
452
|
+
(route.options.members || route.options.rateLimit || route.options.cors)
|
|
453
|
+
)
|
|
471
454
|
problems.push(
|
|
472
|
-
`Bundle "${label}"
|
|
455
|
+
`Bundle "${label}" route "${route.path}": members, rateLimit and cors apply to site routes, not back-office ones.`,
|
|
473
456
|
)
|
|
474
|
-
const signature = `${route.method} ${route.path}`
|
|
475
457
|
const where = onSite(route) ? 'site' : 'backoffice'
|
|
476
|
-
if (routes.has(`${where} ${
|
|
477
|
-
problems.push(`Bundle "${label}" declares "${
|
|
478
|
-
routes.add(`${where} ${
|
|
479
|
-
for (const problem of routeProblems(route))
|
|
480
|
-
problems.push(`Bundle "${label}" route "${signature}": ${problem}.`)
|
|
458
|
+
if (routes.has(`${where} ${route.path}`))
|
|
459
|
+
problems.push(`Bundle "${label}" declares the route "${route.path}" twice.`)
|
|
460
|
+
routes.add(`${where} ${route.path}`)
|
|
481
461
|
}
|
|
482
462
|
}
|
|
483
463
|
return problems
|
|
@@ -526,57 +506,13 @@ function mediaProblems(bundle: ServerBundle): string[] {
|
|
|
526
506
|
return problems
|
|
527
507
|
}
|
|
528
508
|
|
|
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
509
|
/** Member group names a site route requires, for checking at boot that they exist. */
|
|
573
510
|
export function bundleRouteGroups(bundles: readonly ServerBundle[]): string[] {
|
|
574
511
|
const groups = new Set<string>()
|
|
575
512
|
for (const bundle of bundles)
|
|
576
|
-
for (const route of bundle.routes) {
|
|
577
|
-
const
|
|
578
|
-
if (typeof
|
|
579
|
-
for (const group of audience.member.groups) groups.add(group)
|
|
513
|
+
for (const route of bundle.routes ?? []) {
|
|
514
|
+
const members = route.options.members
|
|
515
|
+
if (typeof members === 'object') for (const group of members.groups) groups.add(group)
|
|
580
516
|
}
|
|
581
517
|
return [...groups]
|
|
582
518
|
}
|
|
@@ -737,28 +673,7 @@ export function createBundleRedirects(options: {
|
|
|
737
673
|
* refuses a public caller. It is told the bundle too, for what it declared.
|
|
738
674
|
*/
|
|
739
675
|
export type CallerCapabilities = {
|
|
740
|
-
[K in
|
|
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
|
|
676
|
+
[K in BundleCapability]?: (caller: BundleCaller, bundle: ServerBundle) => BundleHost[K]
|
|
762
677
|
}
|
|
763
678
|
|
|
764
679
|
export interface ServerBundlesOptions {
|
|
@@ -769,60 +684,73 @@ export interface ServerBundlesOptions {
|
|
|
769
684
|
coreVersion: string
|
|
770
685
|
/** `<backoffice>/crombolo/api`, from `createBackOfficePaths`. */
|
|
771
686
|
pluginApiPath: string
|
|
772
|
-
host: Omit<BundleHost, '
|
|
687
|
+
host: Omit<BundleHost, 'media'> & { media?: BundleMedia }
|
|
773
688
|
/** Capabilities built per request from the caller, in place of the ones in `host`. */
|
|
774
689
|
callerHost?: CallerCapabilities
|
|
775
690
|
/** Named per bundle, so a log line says which one wrote it. */
|
|
776
691
|
log(bundleId: string): BundleLog
|
|
777
|
-
/** A bundle's own tables,
|
|
778
|
-
|
|
779
|
-
/**
|
|
780
|
-
|
|
692
|
+
/** A bundle's own tables, on the connection that reaches only them; absent where none are. */
|
|
693
|
+
database?(bundle: ServerBundle): TablesDatabase | undefined
|
|
694
|
+
/**
|
|
695
|
+
* Whether a bundle is turned on: its grant covers what it declares (story
|
|
696
|
+
* 222). A bundle that is off answers every route as waiting. Absent, all are on.
|
|
697
|
+
*/
|
|
698
|
+
isOn?(bundleId: string): boolean
|
|
699
|
+
/** A bundle's queue, recording who queued from the caller (story 187). */
|
|
700
|
+
jobs?(bundleId: string, queuedBy: string | null): OwnerJobs
|
|
781
701
|
}
|
|
782
702
|
|
|
703
|
+
/** Runs a route through 211's pipeline: the server's `routes.invoke`. */
|
|
704
|
+
export type RouteInvoker = (
|
|
705
|
+
entry: DeclaredRoute,
|
|
706
|
+
request: Request,
|
|
707
|
+
url: URL,
|
|
708
|
+
params: Record<string, string>,
|
|
709
|
+
options?: { checks: boolean; extra?: Record<string, unknown> },
|
|
710
|
+
) => Promise<Response>
|
|
711
|
+
|
|
783
712
|
export interface ServerBundles {
|
|
784
713
|
readonly mounted: readonly MountedBundle[]
|
|
785
|
-
/** The prefix every bundle route sits below, including the trailing slash. */
|
|
714
|
+
/** The prefix every back-office bundle route sits below, including the trailing slash. */
|
|
786
715
|
readonly basePath: string
|
|
787
|
-
/** The prefix member and public routes sit below, including the trailing slash. */
|
|
788
|
-
readonly sitePath: string
|
|
789
|
-
/**
|
|
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.
|
|
792
|
-
*/
|
|
793
|
-
handle(request: Request, url: URL, principal: Principal): Promise<Response | undefined>
|
|
794
716
|
/**
|
|
795
|
-
* Answers a
|
|
796
|
-
*
|
|
717
|
+
* Answers a request in the back-office namespace through `invoke`.
|
|
718
|
+
* `undefined` means the path belongs to no bundle, so the caller falls
|
|
719
|
+
* through to its own 404.
|
|
797
720
|
*/
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
721
|
+
handle(
|
|
722
|
+
request: Request,
|
|
723
|
+
url: URL,
|
|
724
|
+
principal: Principal,
|
|
725
|
+
invoke: RouteInvoker,
|
|
726
|
+
): Promise<Response | undefined>
|
|
727
|
+
/** The bundles' site routes, for the server's route table, each given its bundle's capabilities. */
|
|
728
|
+
siteRoutes(): DeclaredRoute[]
|
|
729
|
+
/** What a bundle's job is given: its capabilities for no caller, as on a public route (story 187). */
|
|
730
|
+
jobContext(bundleId: string): Pick<BundleHost, BundleCapability> | undefined
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
const JOB_CALLER: BundleCaller = Object.freeze({ kind: 'job' })
|
|
734
|
+
|
|
735
|
+
/** Who queued a job, for administrators to read: it grants nothing. */
|
|
736
|
+
const queuedByOf = (caller: BundleCaller): string | null =>
|
|
737
|
+
caller.kind === 'member'
|
|
738
|
+
? `member ${caller.member.username}`
|
|
739
|
+
: caller.kind === 'backoffice'
|
|
740
|
+
? `user ${caller.principal.email}`
|
|
741
|
+
: caller.kind === 'job'
|
|
742
|
+
? 'a job'
|
|
743
|
+
: 'a visitor'
|
|
744
|
+
|
|
745
|
+
const freezeMember = (member: RequestMember): BundleMember =>
|
|
812
746
|
Object.freeze({
|
|
813
747
|
key: member.key,
|
|
814
748
|
name: member.name,
|
|
815
749
|
username: member.username,
|
|
816
750
|
email: member.email,
|
|
817
|
-
groups: Object.freeze([...member.
|
|
751
|
+
groups: Object.freeze([...member.roles]),
|
|
818
752
|
})
|
|
819
753
|
|
|
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
754
|
/**
|
|
827
755
|
* Mounts the site's bundles, or fails the boot saying why.
|
|
828
756
|
*
|
|
@@ -836,7 +764,6 @@ export function createServerBundles(options: ServerBundlesOptions): ServerBundle
|
|
|
836
764
|
throw new Error(`The configured bundles cannot be mounted:\n- ${problems.join('\n- ')}`)
|
|
837
765
|
|
|
838
766
|
const basePath = `${options.pluginApiPath}/${BUNDLE_API_SEGMENT}/`
|
|
839
|
-
const sitePath = `${BUNDLE_SITE_PATH}/`
|
|
840
767
|
const byId = new Map(options.bundles.map((bundle) => [bundle.id, bundle]))
|
|
841
768
|
const logs = new Map(options.bundles.map((bundle) => [bundle.id, options.log(bundle.id)]))
|
|
842
769
|
|
|
@@ -850,230 +777,117 @@ export function createServerBundles(options: ServerBundlesOptions): ServerBundle
|
|
|
850
777
|
section: bundle.section,
|
|
851
778
|
capabilities: bundle.capabilities,
|
|
852
779
|
prefix: `${basePath}${bundle.id}`,
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
method: route.method,
|
|
780
|
+
routes: (bundle.routes ?? []).map((route) => ({
|
|
781
|
+
methods: Object.keys(route.handlers),
|
|
856
782
|
path: route.path,
|
|
857
|
-
audience:
|
|
783
|
+
audience: onSite(route) ? ('site' as const) : ('backoffice' as const),
|
|
858
784
|
})),
|
|
859
785
|
}
|
|
860
786
|
})
|
|
861
|
-
const names = new Map(mounted.map((bundle) => [bundle.id, bundle.name]))
|
|
862
787
|
|
|
863
|
-
//
|
|
864
|
-
const
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
788
|
+
// Made once per bundle, at its first request, each on its own tables alone.
|
|
789
|
+
const databases = new Map<string, TablesDatabase>()
|
|
790
|
+
const databaseOf = (bundle: ServerBundle): TablesDatabase | undefined => {
|
|
791
|
+
if (!bundle.tables) return undefined
|
|
792
|
+
let opened = databases.get(bundle.id)
|
|
793
|
+
if (!opened) {
|
|
794
|
+
opened = options.database?.(bundle)
|
|
795
|
+
if (!opened) return undefined
|
|
796
|
+
databases.set(bundle.id, opened)
|
|
797
|
+
}
|
|
798
|
+
return opened
|
|
799
|
+
}
|
|
869
800
|
/** Only the declared capabilities, frozen, so a handler cannot reach further. */
|
|
870
801
|
const contextFor = (
|
|
871
802
|
bundle: ServerBundle,
|
|
872
803
|
caller: BundleCaller,
|
|
873
804
|
): Pick<BundleHost, BundleCapability> => {
|
|
874
805
|
const host: Record<string, unknown> = {}
|
|
806
|
+
const declared = declaredPermissions(owners.get(bundle.id))
|
|
875
807
|
for (const capability of bundle.capabilities) {
|
|
876
|
-
const forCaller =
|
|
877
|
-
|
|
808
|
+
const forCaller = options.callerHost?.[capability]
|
|
809
|
+
const given = forCaller
|
|
878
810
|
? forCaller(caller, bundle)
|
|
879
811
|
: capability === 'log'
|
|
880
812
|
? (logs.get(bundle.id) as BundleLog)
|
|
881
|
-
: capability
|
|
882
|
-
|
|
883
|
-
|
|
813
|
+
: options.host[capability]
|
|
814
|
+
// Only what its declared permissions allow (story 222).
|
|
815
|
+
host[capability] = given ? gated(bundle.id, capability, given, declared) : given
|
|
884
816
|
}
|
|
817
|
+
const database = databaseOf(bundle)
|
|
818
|
+
if (database) host.database = database
|
|
819
|
+
if (bundle.jobs && options.jobs) host.jobs = options.jobs(bundle.id, queuedByOf(caller))
|
|
885
820
|
return Object.freeze(host) as Pick<BundleHost, BundleCapability>
|
|
886
821
|
}
|
|
887
822
|
|
|
888
|
-
/**
|
|
889
|
-
const
|
|
890
|
-
const
|
|
891
|
-
|
|
892
|
-
const
|
|
893
|
-
|
|
894
|
-
|
|
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
|
|
823
|
+
/** A site route that answers as waiting while its bundle is off. */
|
|
824
|
+
const whileOn = (bundleId: string, route: SiteRoute): SiteRoute => {
|
|
825
|
+
const isOn = options.isOn
|
|
826
|
+
if (!isOn) return route
|
|
827
|
+
const handlers: SiteRoute['handlers'] = {}
|
|
828
|
+
for (const [method, handler] of Object.entries(route.handlers))
|
|
829
|
+
handlers[method as RouteMethod] = (request, context) =>
|
|
830
|
+
isOn(bundleId) ? handler(request, context) : waitingResponse(bundleId)
|
|
831
|
+
return { ...route, handlers }
|
|
1042
832
|
}
|
|
1043
833
|
|
|
1044
834
|
return {
|
|
1045
835
|
mounted,
|
|
1046
836
|
basePath,
|
|
1047
|
-
|
|
1048
|
-
|
|
837
|
+
jobContext(bundleId) {
|
|
838
|
+
const bundle = byId.get(bundleId)
|
|
839
|
+
return bundle ? contextFor(bundle, JOB_CALLER) : undefined
|
|
840
|
+
},
|
|
841
|
+
siteRoutes() {
|
|
842
|
+
return options.bundles.flatMap((bundle) =>
|
|
843
|
+
(bundle.routes ?? []).filter(onSite).map(
|
|
844
|
+
(route): DeclaredRoute => ({
|
|
845
|
+
route: whileOn(bundle.id, route as SiteRoute),
|
|
846
|
+
owner: `the bundle ${bundle.id}`,
|
|
847
|
+
extra: ({ member, via }) => {
|
|
848
|
+
const caller: BundleCaller = member
|
|
849
|
+
? Object.freeze({
|
|
850
|
+
kind: 'member',
|
|
851
|
+
member: freezeMember(member as RequestMember),
|
|
852
|
+
via,
|
|
853
|
+
})
|
|
854
|
+
: PUBLIC_CALLER
|
|
855
|
+
return { bundle: contextFor(bundle, caller), caller }
|
|
856
|
+
},
|
|
857
|
+
}),
|
|
858
|
+
),
|
|
859
|
+
)
|
|
860
|
+
},
|
|
861
|
+
async handle(request, url, principal, invoke) {
|
|
1049
862
|
const pathname = url.pathname
|
|
1050
863
|
if (!pathname.startsWith(basePath)) return undefined
|
|
1051
|
-
const
|
|
864
|
+
const rest = pathname.slice(basePath.length)
|
|
865
|
+
const slash = rest.indexOf('/')
|
|
866
|
+
const bundle = byId.get(slash === -1 ? rest : rest.slice(0, slash))
|
|
1052
867
|
if (!bundle) return undefined
|
|
868
|
+
const requested = (slash === -1 ? '' : rest.slice(slash + 1)).replace(/\/$/, '')
|
|
1053
869
|
|
|
1054
870
|
// Authorisation is the host's, not the bundle's: every route is gated on
|
|
1055
871
|
// the declared section, and a bundle has no way to opt a route out.
|
|
1056
872
|
if (!hasSection(principal, bundle.section)) return new Response('Forbidden', { status: 403 })
|
|
1057
873
|
|
|
1058
|
-
const
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
const cors = options.site?.cors
|
|
1076
|
-
return cors ? withCors(cors, request, response) : response
|
|
874
|
+
for (const route of (bundle.routes ?? []).filter((candidate) => !onSite(candidate))) {
|
|
875
|
+
const params = matchRoute(route.path, requested)
|
|
876
|
+
if (!params) continue
|
|
877
|
+
if (options.isOn && !options.isOn(bundle.id)) return waitingResponse(bundle.id)
|
|
878
|
+
const caller: BundleCaller = Object.freeze({ kind: 'backoffice', principal })
|
|
879
|
+
return invoke(
|
|
880
|
+
{ route: route as SiteRoute, owner: `the bundle ${bundle.id}` },
|
|
881
|
+
request,
|
|
882
|
+
url,
|
|
883
|
+
params,
|
|
884
|
+
{
|
|
885
|
+
checks: false,
|
|
886
|
+
extra: { bundle: contextFor(bundle, caller), caller, principal },
|
|
887
|
+
},
|
|
888
|
+
)
|
|
889
|
+
}
|
|
890
|
+
return new Response('Not Found', { status: 404 })
|
|
1077
891
|
},
|
|
1078
892
|
}
|
|
1079
893
|
}
|