@crombolo/server 0.44.0 → 0.46.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/src/remote.ts CHANGED
@@ -17,7 +17,12 @@ import { tmpdir } from 'node:os'
17
17
  import { join, sep } from 'node:path'
18
18
  import { hasSection, type Principal } from '@crombolo/api-management/domain'
19
19
  import { DEVICE_CODE_GRANT, REMOTE_CLIENT_ID } from '@crombolo/auth'
20
- import { managementApiPath, RemotePermissions, type RemoteVerb } from '@crombolo/core'
20
+ import {
21
+ EXPLICIT_PERMISSIONS,
22
+ managementApiPath,
23
+ RemotePermissions,
24
+ type RemoteVerb,
25
+ } from '@crombolo/core'
21
26
  import {
22
27
  AuditLog,
23
28
  auditRecord,
@@ -36,17 +41,20 @@ import {
36
41
  revertRun,
37
42
  } from '@crombolo/transfer'
38
43
  import { readAuditPageQuery, recordAudit } from './adapters/audit.ts'
44
+ import type { BundleAdmin } from './bundle-admin.ts'
45
+ import { codeChanges, installedCode, planCode } from './bundle-code-install.ts'
39
46
  import {
40
47
  checkBundleContent,
41
48
  installBundleContent,
42
49
  readBundle,
43
50
  revertSections,
44
51
  } from './bundle-install.ts'
45
- import { carriesSections, swappedSections } from './bundle-sections.ts'
52
+ import { carriesSections, type SectionFile, swappedSections } from './bundle-sections.ts'
46
53
  import { type CromboloConfig, REMOTE_ACCESS_LEVELS, type RemoteAccess } from './config.ts'
47
54
  import { answerContentQuery, contentQueryScope } from './content-query.ts'
48
55
  import { mediaStoreFor } from './media-files.ts'
49
56
  import { type MediaStore, streamOf } from './media-store.ts'
57
+ import { describeProvenance, provenanceProblem, verifyProvenance } from './provenance.ts'
50
58
  import { createCiSignIn, readRuleInput, trustedIssuers } from './remote-ci.ts'
51
59
  import { openSecret, sealSecret, usableSecretKey } from './secrets.ts'
52
60
  import { exportSite } from './site-file.ts'
@@ -76,6 +84,16 @@ export interface RemoteOptions {
76
84
  * import's cache instruction carries this node's id, and a node skips its own.
77
85
  */
78
86
  onApplied?(): void
87
+ /** A new server from the supervising `crombolo start`, once it is healthy (story 241). */
88
+ restart?: () => Promise<RestartOutcome>
89
+ /** Installed bundles (story 241); absent where this node does not manage them. */
90
+ bundles?: BundleAdmin
91
+ }
92
+
93
+ /** What a supervised restart came to: the new server serving, or why the old one still is. */
94
+ export interface RestartOutcome {
95
+ ok: boolean
96
+ reason?: string
79
97
  }
80
98
 
81
99
  export interface Remote {
@@ -103,8 +121,9 @@ const problem = (status: number, body: Problem) =>
103
121
  headers: { 'content-type': 'application/problem+json' },
104
122
  })
105
123
 
106
- const may = (principal: Principal, verb: RemoteVerb) =>
107
- principal.isAdmin || principal.permissions.includes(verb)
124
+ /** An administrator holds every remote permission but those a group has to name (story 241). */
125
+ export const may = (principal: Principal, verb: RemoteVerb) =>
126
+ (principal.isAdmin && !EXPLICIT_PERMISSIONS.has(verb)) || principal.permissions.includes(verb)
108
127
 
109
128
  /** Who may read the audit log: whoever has its dashboard, in Settings. */
110
129
  const mayReadAudit = (principal: Principal) => hasSection(principal, 'settings')
@@ -189,6 +208,8 @@ export function createRemote(options: RemoteOptions): Remote {
189
208
  'audit',
190
209
  'content-query',
191
210
  ...(settings.approvals ? ['approvals'] : []),
211
+ ...(options.bundles && atLeast('read') ? ['bundle-manage'] : []),
212
+ ...(options.restart && atLeast('all') ? ['restart'] : []),
192
213
  ],
193
214
  environments: [environment()],
194
215
  })
@@ -627,6 +648,7 @@ export function createRemote(options: RemoteOptions): Remote {
627
648
  return {
628
649
  dryRun: raw.dryRun === true,
629
650
  publish: raw.publish === true,
651
+ replaceFiles: raw.replaceFiles === true,
630
652
  label: typeof raw.label === 'string' ? raw.label.slice(0, 200) : undefined,
631
653
  resolutions,
632
654
  resolveAll,
@@ -671,8 +693,11 @@ export function createRemote(options: RemoteOptions): Remote {
671
693
  })
672
694
  await extractTarball(local, dir)
673
695
  let structural: boolean
696
+ let code: SectionFile[]
674
697
  try {
675
- structural = carriesSections(readBundle(dir, config.siteDir).carried)
698
+ const carried = readBundle(dir, config.siteDir).carried
699
+ structural = carriesSections(carried)
700
+ code = codeChanges(planCode(config, carried))
676
701
  } catch (error) {
677
702
  return problem(400, {
678
703
  code: 'not-a-bundle',
@@ -680,6 +705,15 @@ export function createRemote(options: RemoteOptions): Remote {
680
705
  detail: error instanceof Error ? error.message : String(error),
681
706
  })
682
707
  }
708
+ // Where it was built, before the rest is weighed (story 060).
709
+ const provenance = await verifyProvenance(dir)
710
+ const signatureRefused = provenanceProblem(provenance, config.bundlePolicy)
711
+ if (signatureRefused)
712
+ return problem(403, {
713
+ code: 'signature-refused',
714
+ title: 'This site does not take that bundle',
715
+ detail: `It is refused: ${signatureRefused}.`,
716
+ })
683
717
  if (structural && !atLeast('all'))
684
718
  return notAtLevel('all', 'bundles that change content types, views or code')
685
719
  if (structural && !may(principal, RemotePermissions.ApplyStructure))
@@ -689,9 +723,28 @@ export function createRemote(options: RemoteOptions): Remote {
689
723
  detail:
690
724
  'The bundle carries content types, views or code, which needs Crombolo.Remote.ApplyStructure.',
691
725
  })
726
+ // Code that would change this site's files (story 241): installed here, and
727
+ // only by someone a group has given InstallCode, administrators included.
728
+ if (code.length > 0 && !config.runtimeInstalls)
729
+ return problem(409, {
730
+ code: 'installs-elsewhere',
731
+ title: 'This site does not install code while it runs',
732
+ detail:
733
+ config.installsElsewhere?.message ??
734
+ "Add the bundle's code to the site and deploy it the way this site is deployed.",
735
+ })
736
+ if (code.length > 0 && !may(principal, RemotePermissions.InstallCode))
737
+ return problem(403, {
738
+ code: 'forbidden-code',
739
+ title: 'You may not install code on this site',
740
+ detail: `The bundle would change ${code.length} code file(s) here, which needs Crombolo.Remote.InstallCode, given by a group.`,
741
+ items: code.map((file) => file.path),
742
+ })
692
743
  const input = {
693
744
  bundle: dir,
694
745
  publish: asked.publish,
746
+ replaceFiles: asked.replaceFiles,
747
+ installCode: code.length > 0,
695
748
  resolutions: asked.resolutions,
696
749
  resolveAll: asked.resolveAll,
697
750
  by: principal.name,
@@ -715,6 +768,8 @@ export function createRemote(options: RemoteOptions): Remote {
715
768
  return Response.json({
716
769
  dryRun: true,
717
770
  structural,
771
+ provenance,
772
+ code: code.map((file) => ({ path: file.path, action: file.action })),
718
773
  bundle: checked.bundle,
719
774
  ...report(checked.check),
720
775
  clean: checked.clean,
@@ -733,7 +788,7 @@ export function createRemote(options: RemoteOptions): Remote {
733
788
  principal,
734
789
  request,
735
790
  'RemoteBundleApplied',
736
- `${result.bundle.id} as run ${result.runId}${structural ? ', with structure' : ''}`,
791
+ `${result.bundle.id} as run ${result.runId}${structural ? ', with structure' : ''}; ${describeProvenance(provenance)}`,
737
792
  )
738
793
  options.onApplied?.()
739
794
  }
@@ -741,6 +796,10 @@ export function createRemote(options: RemoteOptions): Remote {
741
796
  {
742
797
  dryRun: false,
743
798
  structural,
799
+ provenance,
800
+ code: result.code
801
+ ? { written: result.code.written.length, installed: result.code.installed, live: false }
802
+ : null,
744
803
  bundle: result.bundle,
745
804
  runId: result.runId ?? null,
746
805
  ...report(result.check),
@@ -780,6 +839,115 @@ export function createRemote(options: RemoteOptions): Remote {
780
839
  })
781
840
  }
782
841
 
842
+ /**
843
+ * Installed bundles (story 241), as Settings → Bundles manages them: listed
844
+ * at `read`; installed, removed, disabled and enabled at `all`. Installing or
845
+ * removing changes the code the server loads, so it also needs
846
+ * ApplyStructure and InstallCode, which an administrator holds only when a
847
+ * group gives it to them, and a site that installs at runtime.
848
+ */
849
+ async function manageBundles(
850
+ request: Request,
851
+ principal: Principal,
852
+ what: string,
853
+ ): Promise<Response> {
854
+ const bundles = options.bundles
855
+ if (!bundles)
856
+ return problem(404, { code: 'not-found', title: 'This remote does not manage bundles' })
857
+ const actor = {
858
+ id: principal.ci ? null : principal.id,
859
+ name: `${principal.name}${ciRun(principal)}`,
860
+ email: principal.ci ? null : principal.email,
861
+ source: 'request' as const,
862
+ ipAddress: null,
863
+ forwardedFor: request.headers.get('x-forwarded-for'),
864
+ }
865
+ if (what === 'installed' && request.method === 'GET') {
866
+ if (!atLeast('read')) return notAtLevel('read', 'reads')
867
+ if (!may(principal, RemotePermissions.Pull) && !mayChange(principal))
868
+ return problem(403, { code: 'forbidden', title: 'You may not read this environment' })
869
+ return Response.json(await bundles.installed())
870
+ }
871
+ if (!fromThisSiteOrBearer(request)) return new Response('Forbidden', { status: 403 })
872
+ if (!atLeast('all')) return notAtLevel('all', 'installing and switching bundles')
873
+ const switched = /^installed\/(.+)\/(disable|enable)$/.exec(what)
874
+ if (switched && request.method === 'POST') {
875
+ if (principal.ci ? !may(principal, RemotePermissions.ApplyStructure) : !principal.isAdmin)
876
+ return problem(403, {
877
+ code: 'forbidden',
878
+ title: 'Only an administrator turns bundles off and on',
879
+ })
880
+ const { status, ...outcome } = await bundles.setEnabled(
881
+ actor,
882
+ decodeURIComponent(switched[1] as string),
883
+ switched[2] === 'enable',
884
+ )
885
+ return status === 200
886
+ ? Response.json(outcome)
887
+ : problem(status, { code: 'not-found', title: outcome.message })
888
+ }
889
+ const installing = what === 'installed' && request.method === 'POST'
890
+ const removing = /^installed\/[^/]/.test(what) && request.method === 'DELETE'
891
+ if (!installing && !removing) return new Response(null, { status: 405 })
892
+ if (!mayChange(principal) || !may(principal, RemotePermissions.ApplyStructure))
893
+ return problem(403, {
894
+ code: 'forbidden-structure',
895
+ title: "You may not change this site's structure",
896
+ detail: 'Installing or removing a bundle needs Crombolo.Remote.ApplyStructure.',
897
+ })
898
+ if (!may(principal, RemotePermissions.InstallCode))
899
+ return problem(403, {
900
+ code: 'forbidden-code',
901
+ title: 'You may not install code on this site',
902
+ detail:
903
+ 'It needs "Install code on this site" (Crombolo.Remote.InstallCode), which only a group that names it gives, administrators included.',
904
+ })
905
+ if (!config.runtimeInstalls)
906
+ return problem(409, {
907
+ code: 'installs-elsewhere',
908
+ title: 'This site does not install bundles while it runs',
909
+ detail:
910
+ config.installsElsewhere?.message ??
911
+ "Add the bundle to the site's package.json and deploy it, so every server has it.",
912
+ })
913
+ if (removing) {
914
+ const name = decodeURIComponent(what.slice('installed/'.length))
915
+ const outcome = await bundles.uninstall(actor, name)
916
+ return outcome.ok
917
+ ? Response.json(outcome)
918
+ : problem(409, { code: 'uninstall-refused', title: outcome.message })
919
+ }
920
+ const body = (await request.json().catch(() => ({}))) as Record<string, unknown>
921
+ const name = typeof body.name === 'string' ? body.name : ''
922
+ const grant = Array.isArray(body.grant)
923
+ ? body.grant.filter((p): p is string => typeof p === 'string')
924
+ : []
925
+ const outcome = await bundles.install(actor, {
926
+ name,
927
+ version: typeof body.version === 'string' ? body.version : undefined,
928
+ applyContent: body.applyContent === true,
929
+ // Naming the grant is the consent: a script that names what it grants has said yes.
930
+ acceptServerCode: true,
931
+ grant,
932
+ })
933
+ if (outcome.ok) return Response.json(outcome)
934
+ if (outcome.needsServerConsent) {
935
+ const asked = (outcome.permissions ?? []).map((p) => p.permission)
936
+ const missing = asked.filter((p) => !grant.includes(p))
937
+ const extra = grant.filter((p) => !asked.includes(p))
938
+ return problem(409, {
939
+ code: 'grant-mismatch',
940
+ title: `${name} asks for other permissions than were granted`,
941
+ detail: outcome.message,
942
+ items: [
943
+ ...missing.map((p) => `not granted: ${p}`),
944
+ ...extra.map((p) => `not asked for: ${p}`),
945
+ ],
946
+ })
947
+ }
948
+ return problem(409, { code: 'install-refused', title: outcome.message })
949
+ }
950
+
783
951
  /** Undoes an apply (story 167), as `bundle revert` does here; files it replaced come back too. */
784
952
  async function revertBundleRun(
785
953
  request: Request,
@@ -791,6 +959,19 @@ export function createRemote(options: RemoteOptions): Remote {
791
959
  return problem(403, { code: 'forbidden', title: 'You may not change this environment' })
792
960
  if (!fromThisSiteOrBearer(request)) return new Response('Forbidden', { status: 403 })
793
961
  const body = (await request.json().catch(() => ({}))) as { force?: unknown }
962
+ // A run that installed code changes code back, which needs what it did.
963
+ if (
964
+ installedCode(config, runId) &&
965
+ (!atLeast('all') ||
966
+ !may(principal, RemotePermissions.ApplyStructure) ||
967
+ !may(principal, RemotePermissions.InstallCode))
968
+ )
969
+ return problem(403, {
970
+ code: 'forbidden-code',
971
+ title: "Reverting that run changes this site's code",
972
+ detail:
973
+ 'It needs CROMBOLO_REMOTE_ACCESS=all, Crombolo.Remote.ApplyStructure and Crombolo.Remote.InstallCode.',
974
+ })
794
975
  // A run that replaced files changes structure back, which needs the same as it did.
795
976
  const swapped = swappedSections(config, runId)
796
977
  if (
@@ -825,6 +1006,39 @@ export function createRemote(options: RemoteOptions): Remote {
825
1006
  })
826
1007
  }
827
1008
 
1009
+ /**
1010
+ * A new server, through the supervising `crombolo start` (story 241): any
1011
+ * administrator, or CI whose rule may install code, at the `all` level.
1012
+ */
1013
+ async function restartSite(request: Request, principal: Principal): Promise<Response> {
1014
+ if (!atLeast('all')) return notAtLevel('all', 'restarts')
1015
+ const allowed = principal.ci ? may(principal, RemotePermissions.InstallCode) : principal.isAdmin
1016
+ if (!allowed)
1017
+ return problem(403, { code: 'forbidden', title: 'Only an administrator restarts this site' })
1018
+ if (!fromThisSiteOrBearer(request)) return new Response('Forbidden', { status: 403 })
1019
+ if (!options.restart)
1020
+ return problem(409, {
1021
+ code: 'not-supervised',
1022
+ title: 'Nothing here can restart this site',
1023
+ detail:
1024
+ 'It was not started with `crombolo start`, which restarts it; restart it the way its host does.',
1025
+ })
1026
+ const outcome = await options.restart()
1027
+ await audit(
1028
+ principal,
1029
+ request,
1030
+ outcome.ok ? 'RemoteRestart' : 'RemoteRestartFailed',
1031
+ outcome.ok ? 'a new server is serving' : (outcome.reason ?? 'the new server did not start'),
1032
+ )
1033
+ if (!outcome.ok)
1034
+ return problem(502, {
1035
+ code: 'restart-failed',
1036
+ title: 'The new server did not start; the old one is still serving',
1037
+ detail: outcome.reason,
1038
+ })
1039
+ return Response.json({ restarted: true })
1040
+ }
1041
+
828
1042
  async function startPush(request: Request, url: URL, principal: Principal): Promise<Response> {
829
1043
  if (!may(principal, RemotePermissions.Push))
830
1044
  return problem(403, { code: 'forbidden', title: 'You may not push to this environment' })
@@ -1213,6 +1427,9 @@ export function createRemote(options: RemoteOptions): Remote {
1213
1427
  await request.json().catch(() => undefined),
1214
1428
  )
1215
1429
  }
1430
+ if (what === 'restart' && request.method === 'POST') return restartSite(request, principal)
1431
+ if (what === 'installed' || what.startsWith('installed/'))
1432
+ return manageBundles(request, principal, what)
1216
1433
  // Story 167: the site's level first, then the person's permissions.
1217
1434
  const pulling =
1218
1435
  what === 'pulls' ||
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Code installed but not yet running (story 241). Installing a bundle, or the
3
+ * code a bundle carries, changes the site's files; the server only loads code
4
+ * at boot, so the change is live after `crombolo restart`. Each install adds a
5
+ * reason here, and a server that boots clears it, since it now runs that code.
6
+ */
7
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
8
+ import { dirname, join } from 'node:path'
9
+
10
+ const FILE = join('.crombolo', 'restart-pending.json')
11
+
12
+ export interface RestartPending {
13
+ /** When the first change waiting for a restart was made. */
14
+ since: string
15
+ /** What is waiting, one line each, in the order it was installed. */
16
+ reasons: string[]
17
+ }
18
+
19
+ /** What is waiting for a restart on this site, or undefined when nothing is. */
20
+ export function restartPending(siteDir: string): RestartPending | undefined {
21
+ const file = join(siteDir, FILE)
22
+ if (!existsSync(file)) return undefined
23
+ try {
24
+ const read = JSON.parse(readFileSync(file, 'utf8')) as Partial<RestartPending>
25
+ return {
26
+ since: typeof read.since === 'string' ? read.since : new Date(0).toISOString(),
27
+ reasons: Array.isArray(read.reasons)
28
+ ? read.reasons.filter((r): r is string => typeof r === 'string')
29
+ : [],
30
+ }
31
+ } catch {
32
+ return undefined
33
+ }
34
+ }
35
+
36
+ /** Records that installed code waits for a restart. */
37
+ export function markRestartPending(siteDir: string, reason: string): RestartPending {
38
+ const now = restartPending(siteDir)
39
+ const next: RestartPending = {
40
+ since: now?.since ?? new Date().toISOString(),
41
+ reasons: [...(now?.reasons ?? []), reason],
42
+ }
43
+ const file = join(siteDir, FILE)
44
+ mkdirSync(dirname(file), { recursive: true })
45
+ writeFileSync(file, `${JSON.stringify(next, null, 2)}\n`)
46
+ return next
47
+ }
48
+
49
+ /** A server that booted runs the site's code as it is now. */
50
+ export function clearRestartPending(siteDir: string): void {
51
+ rmSync(join(siteDir, FILE), { force: true })
52
+ }