@crombolo/server 0.71.0 → 0.72.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/server",
3
- "version": "0.71.0",
3
+ "version": "0.72.0",
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",
@@ -32,19 +32,19 @@
32
32
  "access": "public"
33
33
  },
34
34
  "dependencies": {
35
- "@crombolo/api-delivery": "0.71.0",
36
- "@crombolo/api-management": "0.71.0",
37
- "@crombolo/auth": "0.71.0",
38
- "@crombolo/backoffice-host": "0.71.0",
39
- "@crombolo/common": "0.71.0",
40
- "@crombolo/content": "0.71.0",
41
- "@crombolo/contracts": "0.71.0",
42
- "@crombolo/core": "0.71.0",
43
- "@crombolo/data": "0.71.0",
44
- "@crombolo/extension": "0.71.0",
45
- "@crombolo/render": "0.71.0",
46
- "@crombolo/schema": "0.71.0",
47
- "@crombolo/transfer": "0.71.0",
35
+ "@crombolo/api-delivery": "0.72.0",
36
+ "@crombolo/api-management": "0.72.0",
37
+ "@crombolo/auth": "0.72.0",
38
+ "@crombolo/backoffice-host": "0.72.0",
39
+ "@crombolo/common": "0.72.0",
40
+ "@crombolo/content": "0.72.0",
41
+ "@crombolo/contracts": "0.72.0",
42
+ "@crombolo/core": "0.72.0",
43
+ "@crombolo/data": "0.72.0",
44
+ "@crombolo/extension": "0.72.0",
45
+ "@crombolo/render": "0.72.0",
46
+ "@crombolo/schema": "0.72.0",
47
+ "@crombolo/transfer": "0.72.0",
48
48
  "@logtape/logtape": "^2.3.8",
49
49
  "@opentelemetry/api": "1.10.0",
50
50
  "@opentelemetry/context-async-hooks": "3.0.0",
package/src/config.ts CHANGED
@@ -257,9 +257,9 @@ export function runsOnLocalhost(config: CromboloConfig): boolean {
257
257
  }
258
258
  }
259
259
 
260
- /** The body limit to listen with: raised for remote uploads when the remote is on. */
260
+ /** The body limit to listen with: raised for uploads when the remote or workspaces are on. */
261
261
  export function listeningBodyLimit(config: CromboloConfig): number {
262
- return config.remote.enabled
262
+ return config.remote.enabled || workspacesOn(config)
263
263
  ? Math.max(config.maxRequestBodyBytes, config.remote.maxUploadBytes)
264
264
  : config.maxRequestBodyBytes
265
265
  }
@@ -523,6 +523,11 @@ export interface CromboloConfig {
523
523
  * needs workspaces on.
524
524
  */
525
525
  workspacesRequired: boolean
526
+ /**
527
+ * Who may stage or apply a change (story 394): `exchange` honours Apply changes only
528
+ * for a sign-in exchanged for applying one. `CROMBOLO_APPLY_CHANGES_BY`, any unless set.
529
+ */
530
+ applyChangesBy: 'any' | 'exchange'
526
531
  /**
527
532
  * How many workspaces with changed views render at once on a node, each in a
528
533
  * process of its own (story 378); past it the least recently used is stopped.
@@ -1128,6 +1133,7 @@ export function loadConfig(
1128
1133
  cliTokenMaxDays: Math.floor(positiveNumber(setting('CROMBOLO_CLI_TOKEN_MAX_DAYS'), 90)),
1129
1134
  workspaces: setting('CROMBOLO_WORKSPACES') === 'true',
1130
1135
  workspacesRequired: setting('CROMBOLO_WORKSPACES_REQUIRED') === 'true',
1136
+ applyChangesBy: (setting('CROMBOLO_APPLY_CHANGES_BY') || 'any') as 'any' | 'exchange',
1131
1137
  purgeAfterDays: Math.floor(nonNegativeNumber(setting('CROMBOLO_PURGE_AFTER_DAYS'), 0)),
1132
1138
  workspacesHost: setting('CROMBOLO_WORKSPACES_HOST') || undefined,
1133
1139
  workspaceLinkMaxDays: Math.floor(
@@ -1326,6 +1332,10 @@ export function loadConfig(
1326
1332
  throw new Error(
1327
1333
  `users.managedAt is "${merged.users.managedAt}": it is an http or https address, with {email}, {key} or {userName}.`,
1328
1334
  )
1335
+ if (merged.applyChangesBy !== 'any' && merged.applyChangesBy !== 'exchange')
1336
+ throw new Error(
1337
+ `applyChangesBy is "${String(merged.applyChangesBy)}": it is any or exchange (CROMBOLO_APPLY_CHANGES_BY).`,
1338
+ )
1329
1339
  if (merged.workspacesRequired && !merged.workspaces)
1330
1340
  throw new Error(
1331
1341
  'Workspaces are required (CROMBOLO_WORKSPACES_REQUIRED) but not turned on: set CROMBOLO_WORKSPACES=true as well.',
@@ -1482,7 +1492,7 @@ export function describeDatabase(
1482
1492
  }
1483
1493
  }
1484
1494
 
1485
- export const VERSION = '0.71.0'
1495
+ export const VERSION = '0.72.0'
1486
1496
 
1487
1497
  /** A whole number of seconds from the environment; undefined when unset or not one. */
1488
1498
  /** A positive number from a setting, else the default. */
@@ -62,6 +62,8 @@ export interface IdentityProviderOptions {
62
62
  /** How a provider's tokens are exchanged at the remote (stories 364 and 366). */
63
63
  export interface RemoteExchangeOptions {
64
64
  audience?: string
65
+ /** The audience of a token exchanged for applying a change (story 394). */
66
+ applyAudience?: string
65
67
  actors?: Readonly<Record<string, string>>
66
68
  }
67
69
 
@@ -248,12 +250,27 @@ export function exchangeAudienceClashes(
248
250
  backoffice: readonly IdentityProvider[],
249
251
  ): string[] {
250
252
  return exchanging.flatMap((provider) => {
251
- const audience = provider.remoteExchange?.audience
253
+ const { audience, applyAudience } = provider.remoteExchange ?? {}
252
254
  const clash = audience ? backoffice.find((p) => p.oidc.clientId === audience) : undefined
253
- return clash
254
- ? [
255
- `The ${provider.oidc.name} identity provider's remoteExchange audience is the client id ${clash.oidc.name} signs in with. Name the audience of an app used only for the remote, so a sign-in token can never be exchanged.`,
256
- ]
257
- : []
255
+ const applyClash = applyAudience
256
+ ? backoffice.find((p) => p.oidc.clientId === applyAudience)
257
+ : undefined
258
+ return [
259
+ ...(clash
260
+ ? [
261
+ `The ${provider.oidc.name} identity provider's remoteExchange audience is the client id ${clash.oidc.name} signs in with. Name the audience of an app used only for the remote, so a sign-in token can never be exchanged.`,
262
+ ]
263
+ : []),
264
+ ...(applyClash
265
+ ? [
266
+ `The ${provider.oidc.name} identity provider's remoteExchange applyAudience is the client id ${applyClash.oidc.name} signs in with. Name the audience of an app used only for applying changes.`,
267
+ ]
268
+ : []),
269
+ ...(applyAudience !== undefined && applyAudience === audience
270
+ ? [
271
+ `The ${provider.oidc.name} identity provider's remoteExchange applyAudience is its audience. Name another, so a token for applying changes is told apart from any other.`,
272
+ ]
273
+ : []),
274
+ ]
258
275
  })
259
276
  }
package/src/principal.ts CHANGED
@@ -31,7 +31,14 @@ export async function principalOf(
31
31
  )),
32
32
  ...(identity.viewingAs ? { viewingAs: identity.viewingAs } : {}),
33
33
  ...(viaToken ? { viaToken } : {}),
34
- ...(identity.exchangedThrough ? { viaExchange: { provider: identity.exchangedThrough } } : {}),
34
+ ...(identity.exchangedThrough
35
+ ? {
36
+ viaExchange: {
37
+ provider: identity.exchangedThrough,
38
+ ...(identity.exchangedForApplying ? { forApplying: true as const } : {}),
39
+ },
40
+ }
41
+ : {}),
35
42
  ...(identity.viaClient ? { viaClient: identity.viaClient } : {}),
36
43
  }
37
44
  }
@@ -6,7 +6,8 @@
6
6
  * Install code too when the change carries templates or the site's own code.
7
7
  * docs/changes.md.
8
8
  */
9
- import { mkdtempSync, rmSync } from 'node:fs'
9
+ import { createHash } from 'node:crypto'
10
+ import { createWriteStream, mkdtempSync, rmSync } from 'node:fs'
10
11
  import { tmpdir } from 'node:os'
11
12
  import { join } from 'node:path'
12
13
  import type { Principal } from '@crombolo/api-management/domain'
@@ -47,6 +48,44 @@ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
47
48
  const ONE = /^changes\/([0-9a-f-]{36})\/bundle$/i
48
49
  const WORKSPACE = /^workspaces\/([0-9a-f-]{36})\/change$/i
49
50
 
51
+ /**
52
+ * Whether the principal may stage or apply a change (story 394): Apply changes, and
53
+ * under `exchange` only for a sign-in exchanged for applying one.
54
+ */
55
+ export const mayApplyChanges = (
56
+ principal: Principal,
57
+ by: 'any' | 'exchange',
58
+ may: (principal: Principal, verb: RemoteVerb) => boolean,
59
+ ) =>
60
+ may(principal, RemotePermissions.ApplyChanges) &&
61
+ (by === 'any' || principal.viaExchange?.forApplying === true)
62
+
63
+ /** Streams a request body to a file, hashing it as it goes; undefined when it carried none. */
64
+ export async function streamBody(
65
+ request: Request,
66
+ path: string,
67
+ maxBytes: number,
68
+ ): Promise<{ sha256: string; size: number } | undefined> {
69
+ if (!request.body) return undefined
70
+ const hasher = createHash('sha256')
71
+ let size = 0
72
+ const sink = createWriteStream(path)
73
+ const reader = request.body.getReader()
74
+ try {
75
+ for (;;) {
76
+ const { done, value } = await reader.read()
77
+ if (done) break
78
+ size += value.length
79
+ if (size > maxBytes) throw new Error('too large')
80
+ hasher.update(value)
81
+ if (!sink.write(value)) await new Promise((r) => sink.once('drain', r))
82
+ }
83
+ } finally {
84
+ await new Promise<void>((resolve) => sink.end(() => resolve()))
85
+ }
86
+ return { sha256: hasher.digest('hex'), size }
87
+ }
88
+
50
89
  /** A change bundle packed as a tarball, as it travels. */
51
90
  export function packChange(change: ChangeBundle, media: ReadonlyMap<string, Uint8Array>) {
52
91
  const encoder = new TextEncoder()
@@ -100,6 +100,8 @@ export interface ExchangeAccounts {
100
100
  seconds: number,
101
101
  ip: string | undefined,
102
102
  actor: ExchangeActor | undefined,
103
+ /** Exchanged for applying a change (story 394), by the provider's apply audience. */
104
+ forApplying?: boolean,
103
105
  ): Promise<{ accessToken: string } | { refused: string }>
104
106
  }
105
107
 
@@ -261,6 +263,7 @@ export function createPeopleExchange(options: {
261
263
  )
262
264
 
263
265
  const audience = audienceOf(provider, url.origin)
266
+ const applyAudience = provider.remoteExchange?.applyAudience
264
267
  const signInClients = await Promise.all(
265
268
  options.backoffice.map(
266
269
  async (p) => (await options.resolve(p).catch(() => p)).oidc.clientId,
@@ -268,12 +271,14 @@ export function createPeopleExchange(options: {
268
271
  )
269
272
  if (signInClients.includes(audience))
270
273
  return refuse(request, ip, 'its audience is a sign-in client id', provider)
274
+ if (applyAudience && (applyAudience === audience || signInClients.includes(applyAudience)))
275
+ return refuse(request, ip, 'its audience for applying changes is not its own', provider)
271
276
 
272
277
  let claims: JWTPayload
273
278
  try {
274
279
  ;({ payload: claims } = await jwtVerify(token, await keysOf(issuer), {
275
280
  issuer,
276
- audience,
281
+ audience: applyAudience ? [audience, applyAudience] : audience,
277
282
  algorithms: ASYMMETRIC,
278
283
  requiredClaims: ['exp', 'iat'],
279
284
  }))
@@ -285,6 +290,10 @@ export function createPeopleExchange(options: {
285
290
  provider,
286
291
  )
287
292
  }
293
+ const audiences = typeof claims.aud === 'string' ? [claims.aud] : (claims.aud ?? [])
294
+ const forApplying = applyAudience !== undefined && audiences.includes(applyAudience)
295
+ if (forApplying && audiences.includes(audience))
296
+ return refuse(request, ip, 'it names both of its audiences', provider)
288
297
  if (claims.nonce !== undefined)
289
298
  return refuse(request, ip, 'it is a sign-in ID token, which carries a nonce', provider)
290
299
  const exp = claims.exp as number
@@ -322,6 +331,7 @@ export function createPeopleExchange(options: {
322
331
  PERSON_TOKEN_SECONDS,
323
332
  ip,
324
333
  actor,
334
+ forApplying,
325
335
  )
326
336
  if ('refused' in signedIn) return refuse(request, ip, signedIn.refused, provider)
327
337
  await options.onExchange({ ok: true, provider, account, actor }, request)
package/src/remote.ts CHANGED
@@ -78,7 +78,12 @@ import { type MediaStore, streamOf } from './media-store.ts'
78
78
  import { siteMemberPorts } from './member-admin.ts'
79
79
  import { describeProvenance, provenanceProblem, verifyProvenance } from './provenance.ts'
80
80
  import { createBackgroundJobRoutes } from './remote-background-jobs.ts'
81
- import { type ChangeRouteOptions, createChangeRoutes } from './remote-changes.ts'
81
+ import {
82
+ type ChangeRouteOptions,
83
+ createChangeRoutes,
84
+ mayApplyChanges,
85
+ streamBody,
86
+ } from './remote-changes.ts'
82
87
  import { createCiSignIn, readRuleInput, trustedIssuers, unverifiedIssuer } from './remote-ci.ts'
83
88
  import { createExtensionActivityRoutes } from './remote-extension-activity.ts'
84
89
  import { createMediaLibraryRoutes } from './remote-media-library.ts'
@@ -359,7 +364,10 @@ export function createRemote(options: RemoteOptions): Remote {
359
364
  problem,
360
365
  atLeast,
361
366
  notAtLevel,
362
- may,
367
+ may: (principal, verb) =>
368
+ verb === RemotePermissions.ApplyChanges
369
+ ? mayApplyChanges(principal, config.applyChangesBy, may)
370
+ : may(principal, verb),
363
371
  receive: (request, path) => receive(request, path),
364
372
  })
365
373
  : undefined
@@ -789,28 +797,11 @@ export function createRemote(options: RemoteOptions): Remote {
789
797
  }
790
798
 
791
799
  /** Streams a request body to a file, hashing it as it goes; undefined when it is not what it claimed. */
792
- async function receive(
800
+ function receive(
793
801
  request: Request,
794
802
  path: string,
795
803
  ): Promise<{ sha256: string; size: number } | undefined> {
796
- if (!request.body) return undefined
797
- const hasher = createHash('sha256')
798
- let size = 0
799
- const sink = createWriteStream(path)
800
- const reader = request.body.getReader()
801
- try {
802
- for (;;) {
803
- const { done, value } = await reader.read()
804
- if (done) break
805
- size += value.length
806
- if (size > settings.maxUploadBytes) throw new Error('too large')
807
- hasher.update(value)
808
- if (!sink.write(value)) await new Promise((r) => sink.once('drain', r))
809
- }
810
- } finally {
811
- await new Promise<void>((resolve) => sink.end(() => resolve()))
812
- }
813
- return { sha256: hasher.digest('hex'), size }
804
+ return streamBody(request, path, settings.maxUploadBytes)
814
805
  }
815
806
 
816
807
  /** The options a site apply was sent with, in `Crombolo-Options` (story 167). */
@@ -1628,7 +1619,7 @@ export function createRemote(options: RemoteOptions): Remote {
1628
1619
  applyChanges:
1629
1620
  Boolean(changeRoutes?.capabilities().length) &&
1630
1621
  atLeast('content') &&
1631
- may(principal, RemotePermissions.ApplyChanges),
1622
+ mayApplyChanges(principal, config.applyChangesBy, may),
1632
1623
  },
1633
1624
  },
1634
1625
  ])
@@ -1811,6 +1802,7 @@ export function createRemote(options: RemoteOptions): Remote {
1811
1802
  return (
1812
1803
  url.pathname === `${prefix}pushes` ||
1813
1804
  url.pathname === `${prefix}bundles` ||
1805
+ url.pathname === `${prefix}changes` ||
1814
1806
  url.pathname.startsWith(`${prefix}media/`) ||
1815
1807
  (mediaLibraryRoutes?.isUpload(url.pathname.slice(prefix.length), request.method) ?? false)
1816
1808
  )
package/src/server.ts CHANGED
@@ -271,6 +271,7 @@ import {
271
271
  import { principalOf } from './principal.ts'
272
272
  import { provenanceProblem } from './provenance.ts'
273
273
  import { createRemote, may, type RestartOutcome } from './remote.ts'
274
+ import { createChangeRoutes, mayApplyChanges, streamBody } from './remote-changes.ts'
274
275
  import { createPeopleExchange } from './remote-people.ts'
275
276
  import { createSchemaTransfer, UPLOAD_LIMITS } from './schema-transfer.ts'
276
277
  import { SiteAssets } from './site-assets.ts'
@@ -1067,7 +1068,7 @@ export async function createServer(
1067
1068
  ? undefined
1068
1069
  : 'the person has no access to the back office'
1069
1070
  },
1070
- signIn: async (key, provider, seconds, ip, actor) => {
1071
+ signIn: async (key, provider, seconds, ip, actor, forApplying) => {
1071
1072
  const user = await users.byKey(key)
1072
1073
  if (!user) return { refused: 'the person no longer exists' }
1073
1074
  const result = await auth.signInByExchange(
@@ -1076,6 +1077,7 @@ export async function createServer(
1076
1077
  seconds,
1077
1078
  ip,
1078
1079
  actor,
1080
+ forApplying,
1079
1081
  )
1080
1082
  if (result.status === 'success') return { accessToken: result.accessToken }
1081
1083
  return {
@@ -1897,6 +1899,45 @@ export async function createServer(
1897
1899
  schema: () => workspaceSchema,
1898
1900
  merge: () => core.operations.merge,
1899
1901
  })
1902
+ // Story 394: the remote's change routes, on the Management API for a bearer token.
1903
+ const managementChanges = createChangeRoutes({
1904
+ db,
1905
+ changes: () => (workspacesOn(config) ? changeTransfer : undefined),
1906
+ problem: (status, body) =>
1907
+ Response.json(
1908
+ {
1909
+ message: body.title,
1910
+ ...(body.detail ? { detail: body.detail } : {}),
1911
+ ...(body.items ? { refusals: body.items } : {}),
1912
+ },
1913
+ { status },
1914
+ ),
1915
+ atLeast: () => true,
1916
+ notAtLevel: () => new Response(null, { status: 403 }),
1917
+ may: (principal, verb) =>
1918
+ verb === RemotePermissions.ApplyChanges
1919
+ ? mayApplyChanges(principal, config.applyChangesBy, may)
1920
+ : may(principal, verb),
1921
+ receive: (request, path) => streamBody(request, path, config.remote.maxUploadBytes),
1922
+ })
1923
+ /** The remote's route a Management API change request is, if it is one. */
1924
+ const managementChange = (pathname: string, method: string): string | undefined => {
1925
+ if (pathname === changesPath) return method === 'PUT' ? 'changes' : undefined
1926
+ const bundle = /^\/([0-9a-f-]{36})\/bundle$/i.exec(pathname.slice(changesPath.length))
1927
+ if (pathname.startsWith(`${changesPath}/`) && bundle && method === 'GET')
1928
+ return `changes/${bundle[1]}/bundle`
1929
+ const open = /^\/([0-9a-f-]{36})\/change$/i.exec(pathname.slice(workspacesPath.length))
1930
+ if (pathname.startsWith(`${workspacesPath}/`) && open && method === 'GET')
1931
+ return `workspaces/${open[1]}/change`
1932
+ return undefined
1933
+ }
1934
+ /** A token the caller set in `Authorization`, never the back office's cookie. */
1935
+ const carriesBearer = (request: Request) => {
1936
+ const header = request.headers.get('authorization')
1937
+ const bearer = header?.toLowerCase().startsWith('bearer ') ? header.slice(7).trim() : ''
1938
+ return bearer !== '' && bearer !== REDACTED
1939
+ }
1940
+
1900
1941
  // Story 379: each workspace's site, kept on this node while it is looked at.
1901
1942
  const workspaceSites = createWorkspaceSites({
1902
1943
  db,
@@ -3370,6 +3411,22 @@ export async function createServer(
3370
3411
  )
3371
3412
  }
3372
3413
 
3414
+ // Story 394: a change exported or taken, for a token in Authorization alone.
3415
+ const moving = managementChange(pathname, request.method)
3416
+ if (moving) {
3417
+ if (!carriesBearer(request))
3418
+ return Response.json(
3419
+ { message: 'Moving a change needs a sign-in token in Authorization, not a cookie.' },
3420
+ { status: 401 },
3421
+ )
3422
+ const principal = await authenticate(request)
3423
+ if (!principal) return new Response('Unauthorized', { status: 401 })
3424
+ return (
3425
+ (await managementChanges.handle(request, new URL(request.url), principal, moving)) ??
3426
+ new Response(null, { status: 404 })
3427
+ )
3428
+ }
3429
+
3373
3430
  // Story 375: workspaces, opened, listed, shared and discarded.
3374
3431
  if (pathname === workspacesPath || pathname.startsWith(`${workspacesPath}/`)) {
3375
3432
  const principal = await authenticate(request)
@@ -5243,7 +5300,8 @@ export async function createServer(
5243
5300
  // request is held to the usual one here.
5244
5301
  if (
5245
5302
  listeningBodyLimit(config) > config.maxRequestBodyBytes &&
5246
- !remote.isUpload(request, requestUrl)
5303
+ !remote.isUpload(request, requestUrl) &&
5304
+ managementChange(pathname, request.method) !== 'changes'
5247
5305
  ) {
5248
5306
  const length = Number(request.headers.get('content-length') ?? 0)
5249
5307
  if (length > config.maxRequestBodyBytes)
package/src/settings.ts CHANGED
@@ -590,6 +590,15 @@ const DECLARED = [
590
590
  description:
591
591
  'Whether every change to a page is made in a workspace. What everyone sees then changes only when a workspace is merged; someone who edits without choosing one works in their own. Needs `CROMBOLO_WORKSPACES=true`.',
592
592
  },
593
+ {
594
+ env: 'CROMBOLO_APPLY_CHANGES_BY',
595
+ kind: 'enum',
596
+ values: ['any', 'exchange'],
597
+ default: 'any',
598
+ section: 'Schema',
599
+ description:
600
+ "Who may stage or apply a change from another copy of the site. `exchange`: only a sign-in exchanged through an identity provider's `applyAudience`, so a person's own sign-in never can.",
601
+ },
593
602
  {
594
603
  env: 'CROMBOLO_SYNC_SCHEMA_AT_BOOT',
595
604
  kind: 'boolean',