@crombolo/server 0.64.0 → 0.65.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/server",
3
- "version": "0.64.0",
3
+ "version": "0.65.1",
4
4
  "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. The crombolo HTTP server: routing, configuration, media stores and background jobs.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -31,19 +31,19 @@
31
31
  "access": "public"
32
32
  },
33
33
  "dependencies": {
34
- "@crombolo/api-delivery": "0.64.0",
35
- "@crombolo/api-management": "0.64.0",
36
- "@crombolo/auth": "0.64.0",
37
- "@crombolo/backoffice-host": "0.64.0",
38
- "@crombolo/common": "0.64.0",
39
- "@crombolo/content": "0.64.0",
40
- "@crombolo/contracts": "0.64.0",
41
- "@crombolo/core": "0.64.0",
42
- "@crombolo/data": "0.64.0",
43
- "@crombolo/extension": "0.64.0",
44
- "@crombolo/render": "0.64.0",
45
- "@crombolo/schema": "0.64.0",
46
- "@crombolo/transfer": "0.64.0",
34
+ "@crombolo/api-delivery": "0.65.1",
35
+ "@crombolo/api-management": "0.65.1",
36
+ "@crombolo/auth": "0.65.1",
37
+ "@crombolo/backoffice-host": "0.65.1",
38
+ "@crombolo/common": "0.65.1",
39
+ "@crombolo/content": "0.65.1",
40
+ "@crombolo/contracts": "0.65.1",
41
+ "@crombolo/core": "0.65.1",
42
+ "@crombolo/data": "0.65.1",
43
+ "@crombolo/extension": "0.65.1",
44
+ "@crombolo/render": "0.65.1",
45
+ "@crombolo/schema": "0.65.1",
46
+ "@crombolo/transfer": "0.65.1",
47
47
  "@logtape/logtape": "^2.3.8",
48
48
  "@opentelemetry/api": "1.10.0",
49
49
  "@opentelemetry/context-async-hooks": "3.0.0",
package/src/access.ts CHANGED
@@ -98,12 +98,16 @@ export function createNodeLookup(db: Db): NodeLookup {
98
98
  }
99
99
  }
100
100
 
101
- /** A user's languages, their groups' start nodes per tree (story 339), and group verbs. */
101
+ /**
102
+ * A user's languages, their groups' start nodes per tree (story 339), and group
103
+ * verbs; from the given groups instead while a session views as them (story 314).
104
+ */
102
105
  export async function loadAccess(
103
106
  db: Db,
104
107
  userId: number,
108
+ groupKeys?: readonly string[],
105
109
  ): Promise<Pick<Principal, 'languages' | 'startNodes' | 'groups'>> {
106
- const data = await new UserRepository(db).access(userId)
110
+ const data = await new UserRepository(db).access(userId, groupKeys)
107
111
  return {
108
112
  languages: data.languages,
109
113
  groups: data.groups,
package/src/approvals.ts CHANGED
@@ -441,6 +441,26 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
441
441
  })
442
442
  }
443
443
 
444
+ /** Whether the person who made the change is in one of these groups. */
445
+ const requesterIn = async (
446
+ request: ApprovalRequest,
447
+ approvers: readonly string[],
448
+ actor: Principal | undefined,
449
+ ): Promise<boolean> => {
450
+ // Story 314: the requester viewing as groups is in exactly those.
451
+ if (actor?.viewingAs && normaliseUuid(actor.id) === request.requestedBy)
452
+ return actor.groups.some((g) => approvers.includes(g.alias))
453
+ const member = await db.q
454
+ .selectFrom('user_group_member as m')
455
+ .innerJoin('user_group as g', 'g.id', 'm.user_group_id')
456
+ .innerJoin('user_account as u', 'u.id', 'm.user_id')
457
+ .select((eb) => eb.fn.countAll().as('n'))
458
+ .where('u.key', '=', request.requestedBy)
459
+ .where('g.alias', 'in', approvers.length > 0 ? approvers : [''])
460
+ .execute()
461
+ return Number(member[0]?.n ?? 0) > 0
462
+ }
463
+
444
464
  /**
445
465
  * Stages just reached count the person who made the change as approving
446
466
  * when the workflow says so and they are in the stage's groups.
@@ -449,20 +469,13 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
449
469
  repo: ApprovalRepositoryType,
450
470
  request: ApprovalRequest,
451
471
  stages: readonly string[],
472
+ actor: Principal | undefined,
452
473
  ): Promise<void> => {
453
474
  for (const stage of stages) {
454
475
  const stepId = await repo.addStep(request.id, stage)
455
476
  if (request.workflow.selfApproval !== 'automatic') continue
456
477
  const approvers = stageOf(request.workflow, stage)?.approvers ?? []
457
- const member = await db.q
458
- .selectFrom('user_group_member as m')
459
- .innerJoin('user_group as g', 'g.id', 'm.user_group_id')
460
- .innerJoin('user_account as u', 'u.id', 'm.user_id')
461
- .select((eb) => eb.fn.countAll().as('n'))
462
- .where('u.key', '=', request.requestedBy)
463
- .where('g.alias', 'in', approvers.length > 0 ? approvers : [''])
464
- .execute()
465
- if (Number(member[0]?.n ?? 0) > 0)
478
+ if (await requesterIn(request, approvers, actor))
466
479
  await repo.record(request.id, {
467
480
  kind: 'approved',
468
481
  stepId,
@@ -478,6 +491,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
478
491
  const settle = async (
479
492
  repo: ApprovalRepositoryType,
480
493
  request: ApprovalRequest,
494
+ actor: Principal | undefined,
481
495
  ): Promise<boolean> => {
482
496
  for (let round = 0; round < request.workflow.stages.length + 1; round++) {
483
497
  const steps = await repo.steps(request.id)
@@ -499,7 +513,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
499
513
  if (workflowComplete(request.workflow, approved)) return true
500
514
  const next = stagesNowWaiting(request.workflow, approved, reached)
501
515
  if (next.length > 0) {
502
- await reach(repo, request, next)
516
+ await reach(repo, request, next, actor)
503
517
  const facts = await page(request.nodeKey)
504
518
  await notify(
505
519
  'approvers',
@@ -912,7 +926,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
912
926
  comment: [comment?.trim(), when && `to be ${when}`].filter(Boolean).join('\n\n') || null,
913
927
  })
914
928
  const first = startStages(workflow)
915
- await reach(repo, request, first)
929
+ await reach(repo, request, first, principal)
916
930
  await notify(
917
931
  'approvers',
918
932
  request,
@@ -920,7 +934,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
920
934
  `Waiting for your approval: ${facts.name}`,
921
935
  `${principal.name} sent "${facts.name}" for approval through "${workflow.name}".${when ? ` It is to be ${when}.` : ''}${comment ? `\n\n${comment}` : ''}`,
922
936
  )
923
- const complete = await settle(repo, request)
937
+ const complete = await settle(repo, request, principal)
924
938
  await auditStep(
925
939
  principal,
926
940
  facts,
@@ -958,7 +972,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
958
972
  userKey: principal.id,
959
973
  comment: comment?.trim() || null,
960
974
  })
961
- const complete = await settle(repo, request)
975
+ const complete = await settle(repo, request, principal)
962
976
  await auditStep(
963
977
  principal,
964
978
  await page(request.nodeKey),
@@ -1011,7 +1025,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
1011
1025
  (s) => (s.state === 'waiting' || s.state === 'approved') && redo.has(s.stage),
1012
1026
  ))
1013
1027
  await repo.setStepState(step.id, step.stage === from ? 'sent-back' : 'discarded')
1014
- await reach(repo, request, [to])
1028
+ await reach(repo, request, [to], principal)
1015
1029
  await notify(
1016
1030
  'approvers',
1017
1031
  request,
@@ -1019,7 +1033,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
1019
1033
  `Back for your approval: ${facts?.name ?? 'a page'}`,
1020
1034
  `"${facts?.name}" was sent back to you${comment ? `:\n\n${comment}` : '.'}`,
1021
1035
  )
1022
- complete = await settle(repo, request)
1036
+ complete = await settle(repo, request, principal)
1023
1037
  }
1024
1038
  await auditStep(
1025
1039
  principal,
@@ -17,6 +17,7 @@ import {
17
17
  USER_DELEGATE,
18
18
  } from '@crombolo/backoffice-host/registry'
19
19
  import {
20
+ appendCacheInstruction,
20
21
  type Db,
21
22
  ExtensionSettingRepository,
22
23
  ownerTablesIn,
@@ -115,6 +116,8 @@ export interface SwitchOutcome {
115
116
  ok: boolean
116
117
  on?: boolean
117
118
  message: string
119
+ /** It is granted and on, and its server half could not start, saying why (story 346). */
120
+ couldNotStart?: string
118
121
  }
119
122
 
120
123
  export interface BundleAdmin {
@@ -172,8 +175,33 @@ export function createBundleAdmin(options: {
172
175
  failed?: () => readonly { id: string; reason: string }[]
173
176
  /** Stops an extension's running process, where this node runs one (story 328). */
174
177
  stopExtension?: (id: string) => Promise<void>
178
+ /**
179
+ * Brings an extension's server half to what its grant says now, on every node
180
+ * (story 346): started when granted and on, stopped when off, unmounted when
181
+ * removed. Answers whether it runs here, or why it could not start; nothing
182
+ * where no server runs here, as on the CLI.
183
+ */
184
+ changed?: (id: string) => Promise<{ running: boolean; reason?: string } | undefined>
175
185
  }): BundleAdmin {
176
186
  const { db, config, marketplace, extensions, bundleGrants } = options
187
+
188
+ /** Started, stopped or unmounted to match its grant; an answer that says when it could not start. */
189
+ const afterSwitch = async (
190
+ pkg: { id: string; name: string; carries: { server?: boolean } },
191
+ outcome: SwitchOutcome,
192
+ ): Promise<SwitchOutcome> => {
193
+ if (!outcome.ok || !pkg.carries.server) return outcome
194
+ const now = await options.changed?.(pkg.id).catch((error: unknown) => ({
195
+ running: false,
196
+ reason: error instanceof Error ? error.message : String(error),
197
+ }))
198
+ if (!outcome.on || now?.running !== false || !now.reason) return outcome
199
+ return {
200
+ ...outcome,
201
+ couldNotStart: now.reason,
202
+ message: `${outcome.message} It could not start: ${now.reason}`,
203
+ }
204
+ }
177
205
  const options_ = options
178
206
  /**
179
207
  * The data removed extensions left (story 328): an owner the tables ledger
@@ -459,6 +487,8 @@ export function createBundleAdmin(options: {
459
487
  .join(' '),
460
488
  }
461
489
  if (!before?.carries.server) return result
490
+ // One running in a process of its own is unmounted now; one the site's code imported waits.
491
+ if (id && (await options_.changed?.(id).catch(() => undefined))) return result
462
492
  markRestartPending(config.siteDir, `${name} removed`)
463
493
  return { ...result, restartPending: true }
464
494
  },
@@ -531,12 +561,12 @@ export function createBundleAdmin(options: {
531
561
  `granted ${LEVEL_WORDS[level].label}: ${asks.join(', ') || 'nothing'}${delegateKey ? `, acting for ${delegateKey} when nobody is using it` : ''}`,
532
562
  )
533
563
  const state = bundleGrants.state(pkg)
534
- return {
564
+ return afterSwitch(pkg, {
535
565
  status: 200,
536
566
  ok: true,
537
567
  on: state.on,
538
568
  message: `${pkg.name} is granted what it asks for.`,
539
- }
569
+ })
540
570
  },
541
571
 
542
572
  async setEnabled(actor, id, enabled) {
@@ -573,7 +603,7 @@ export function createBundleAdmin(options: {
573
603
  `${pkg.packageName}@${pkg.version}`,
574
604
  enabled ? 'enabled; it runs again' : 'disabled; it is off',
575
605
  )
576
- return {
606
+ const outcome = {
577
607
  status: 200,
578
608
  ok: true,
579
609
  on: state.on,
@@ -581,6 +611,7 @@ export function createBundleAdmin(options: {
581
611
  ? `${pkg.name} is turned on.`
582
612
  : `${pkg.name} is turned off until it is enabled again.`,
583
613
  }
614
+ return afterSwitch(pkg, outcome)
584
615
  },
585
616
  }
586
617
  }
@@ -643,5 +674,10 @@ export async function localBundleAdmin(
643
674
  marketplace,
644
675
  extensions,
645
676
  bundleGrants,
677
+ // A site running on this database starts or stops it when it hears (story 346).
678
+ changed: async (id) => {
679
+ await appendCacheInstruction(db, { kind: 'extensions', payload: { id } }).catch(() => null)
680
+ return undefined
681
+ },
646
682
  })
647
683
  }
@@ -2,7 +2,8 @@
2
2
  * A host installs a site's bundles itself and tells each node (story 181):
3
3
  * `reloadBundles()` reads the site's `package.json` and `node_modules` again,
4
4
  * so the back office serves what is there now. It never mounts a server half:
5
- * configured `bundles` are wired at boot only, and stay as they were.
5
+ * configured `bundles` are wired at boot only, and an installed extension starts
6
+ * when it is granted (story 346).
6
7
  */
7
8
  import type { BundlePackage, ExtensionRegistry } from '@crombolo/backoffice-host'
8
9
 
package/src/bundles.ts CHANGED
@@ -822,10 +822,20 @@ export interface ServerBundles {
822
822
  principal: Principal,
823
823
  invoke: RouteInvoker,
824
824
  ): Promise<Response | undefined>
825
- /** The bundles' site routes, for the server's route table, each given its bundle's capabilities. */
826
- siteRoutes(): DeclaredRoute[]
825
+ /**
826
+ * The bundles' site routes, for the server's route table, each given its
827
+ * bundle's capabilities; one bundle's when named.
828
+ */
829
+ siteRoutes(bundleId?: string): DeclaredRoute[]
827
830
  /** What a bundle's job is given: its capabilities for no caller, as on a public route (story 187). */
828
831
  jobContext(bundleId: string): Pick<BundleHost, BundleCapability> | undefined
832
+ /**
833
+ * Mounts one more bundle while the server runs (story 346), checked as boot
834
+ * checks them; answers why it cannot be, and mounts nothing then.
835
+ */
836
+ add(bundle: ServerBundle, pkg: BundlePackage): string[]
837
+ /** Unmounts a bundle: its routes answer nothing from now on. */
838
+ remove(bundleId: string): void
829
839
  }
830
840
 
831
841
  const JOB_CALLER: BundleCaller = Object.freeze({ kind: 'job' })
@@ -862,11 +872,12 @@ export function createServerBundles(options: ServerBundlesOptions): ServerBundle
862
872
  throw new Error(`The configured bundles cannot be mounted:\n- ${problems.join('\n- ')}`)
863
873
 
864
874
  const basePath = `${options.pluginApiPath}/${BUNDLE_API_SEGMENT}/`
865
- const byId = new Map(options.bundles.map((bundle) => [bundle.id, bundle]))
866
- const logs = new Map(options.bundles.map((bundle) => [bundle.id, options.log(bundle.id)]))
875
+ const live = [...options.bundles]
876
+ const byId = new Map(live.map((bundle) => [bundle.id, bundle]))
877
+ const logs = new Map(live.map((bundle) => [bundle.id, options.log(bundle.id)]))
867
878
 
868
879
  const owners = new Map(options.packages.map((pkg) => [pkg.id, pkg]))
869
- const mounted: MountedBundle[] = options.bundles.map((bundle) => {
880
+ const mountedOf = (bundle: ServerBundle): MountedBundle => {
870
881
  const owner = owners.get(bundle.id) as BundlePackage
871
882
  return {
872
883
  id: bundle.id,
@@ -881,7 +892,8 @@ export function createServerBundles(options: ServerBundlesOptions): ServerBundle
881
892
  audience: onSite(route) ? ('site' as const) : ('backoffice' as const),
882
893
  })),
883
894
  }
884
- })
895
+ }
896
+ const mounted: MountedBundle[] = live.map(mountedOf)
885
897
 
886
898
  // Made once per bundle, at its first request, each on its own tables alone.
887
899
  const databases = new Map<string, TablesDatabase>()
@@ -1031,25 +1043,48 @@ export function createServerBundles(options: ServerBundlesOptions): ServerBundle
1031
1043
  const bundle = byId.get(bundleId)
1032
1044
  return bundle ? contextFor(bundle, JOB_CALLER) : undefined
1033
1045
  },
1034
- siteRoutes() {
1035
- return options.bundles.flatMap((bundle) =>
1036
- (bundle.routes ?? []).filter(onSite).map(
1037
- (route): DeclaredRoute => ({
1038
- route: whileOn(bundle.id, route as SiteRoute),
1039
- owner: `the bundle ${bundle.id}`,
1040
- extra: ({ member, via }) => {
1041
- const caller: BundleCaller = member
1042
- ? Object.freeze({
1043
- kind: 'member',
1044
- member: freezeMember(member as RequestMember),
1045
- via,
1046
- })
1047
- : PUBLIC_CALLER
1048
- return { bundle: contextFor(bundle, caller), caller }
1049
- },
1050
- }),
1051
- ),
1052
- )
1046
+ add(bundle, pkg) {
1047
+ const problems = byId.has(bundle.id)
1048
+ ? [`Bundle "${bundle.id}" is already mounted.`]
1049
+ : validateServerBundles([bundle], [pkg], options.coreVersion)
1050
+ if (problems.length > 0) return problems
1051
+ owners.set(pkg.id, pkg)
1052
+ live.push(bundle)
1053
+ byId.set(bundle.id, bundle)
1054
+ logs.set(bundle.id, options.log(bundle.id))
1055
+ mounted.push(mountedOf(bundle))
1056
+ return []
1057
+ },
1058
+ remove(bundleId) {
1059
+ const at = live.findIndex((bundle) => bundle.id === bundleId)
1060
+ if (at >= 0) live.splice(at, 1)
1061
+ const shown = mounted.findIndex((bundle) => bundle.id === bundleId)
1062
+ if (shown >= 0) mounted.splice(shown, 1)
1063
+ byId.delete(bundleId)
1064
+ logs.delete(bundleId)
1065
+ databases.delete(bundleId)
1066
+ },
1067
+ siteRoutes(bundleId) {
1068
+ return live
1069
+ .filter((bundle) => bundleId === undefined || bundle.id === bundleId)
1070
+ .flatMap((bundle) =>
1071
+ (bundle.routes ?? []).filter(onSite).map(
1072
+ (route): DeclaredRoute => ({
1073
+ route: whileOn(bundle.id, route as SiteRoute),
1074
+ owner: `the bundle ${bundle.id}`,
1075
+ extra: ({ member, via }) => {
1076
+ const caller: BundleCaller = member
1077
+ ? Object.freeze({
1078
+ kind: 'member',
1079
+ member: freezeMember(member as RequestMember),
1080
+ via,
1081
+ })
1082
+ : PUBLIC_CALLER
1083
+ return { bundle: contextFor(bundle, caller), caller }
1084
+ },
1085
+ }),
1086
+ ),
1087
+ )
1053
1088
  },
1054
1089
  async handle(request, url, principal, invoke) {
1055
1090
  const pathname = url.pathname
package/src/config.ts CHANGED
@@ -106,6 +106,21 @@ function contentModeSetting(): ContentMode {
106
106
  return value
107
107
  }
108
108
 
109
+ /**
110
+ * Whether the Delivery API is public, from `CROMBOLO_DELIVERY_API_PRIVATE` (story 348):
111
+ * unset, it serves what the site publishes. The switch it replaced is refused, since
112
+ * ignoring `CROMBOLO_DELIVERY_API_PUBLIC=false` would quietly open a private API.
113
+ */
114
+ function deliveryApiPublic(): boolean | undefined {
115
+ // Read directly: it is no longer a setting, only a name to refuse.
116
+ if (Bun.env.CROMBOLO_DELIVERY_API_PUBLIC !== undefined)
117
+ throw new Error(
118
+ 'CROMBOLO_DELIVERY_API_PUBLIC has gone: set CROMBOLO_DELIVERY_API_PRIVATE=true to keep the Delivery API private, every request needing its key, or leave both unset for it to serve what the site publishes (story 348).',
119
+ )
120
+ const isPrivate = envFlag(setting('CROMBOLO_DELIVERY_API_PRIVATE'))
121
+ return isPrivate === undefined ? undefined : !isPrivate
122
+ }
123
+
109
124
  /** Whether the back office must leave templates, stylesheets and scripts alone. */
110
125
  export const contentFilesLocked = (config: Pick<CromboloConfig, 'contentMode'>) =>
111
126
  config.contentMode === 'production'
@@ -517,7 +532,7 @@ export interface CromboloConfig {
517
532
  /**
518
533
  * Umbraco's Delivery API (`docs/delivery-api.md`): off unless enabled.
519
534
  * `CROMBOLO_DELIVERY_API`, `CROMBOLO_DELIVERY_API_KEY`,
520
- * `CROMBOLO_DELIVERY_API_PUBLIC`, `CROMBOLO_DELIVERY_API_MEDIA`,
535
+ * `CROMBOLO_DELIVERY_API_PRIVATE`, `CROMBOLO_DELIVERY_API_MEDIA`,
521
536
  * `CROMBOLO_DELIVERY_API_CORS_ORIGINS`, `CROMBOLO_DELIVERY_API_PREVIEW_URL` and
522
537
  * `CROMBOLO_DELIVERY_API_PREVIEW_TOKEN_MINUTES`; member
523
538
  * sign-in is configured here, since its clients and secrets are a list.
@@ -1028,7 +1043,7 @@ export function loadConfig(
1028
1043
  deliveryApi: stripUndefined({
1029
1044
  enabled: envFlag(setting('CROMBOLO_DELIVERY_API')),
1030
1045
  apiKey: setting('CROMBOLO_DELIVERY_API_KEY') || undefined,
1031
- publicAccess: envFlag(setting('CROMBOLO_DELIVERY_API_PUBLIC')),
1046
+ publicAccess: deliveryApiPublic(),
1032
1047
  media:
1033
1048
  envFlag(setting('CROMBOLO_DELIVERY_API_MEDIA')) === undefined
1034
1049
  ? undefined
@@ -1224,7 +1239,7 @@ export function describeDatabase(
1224
1239
  }
1225
1240
  }
1226
1241
 
1227
- export const VERSION = '0.64.0'
1242
+ export const VERSION = '0.65.1'
1228
1243
 
1229
1244
  /** A whole number of seconds from the environment; undefined when unset or not one. */
1230
1245
  /** A positive number from a setting, else the default. */