@crombolo/server 0.70.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.70.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.70.0",
36
- "@crombolo/api-management": "0.70.0",
37
- "@crombolo/auth": "0.70.0",
38
- "@crombolo/backoffice-host": "0.70.0",
39
- "@crombolo/common": "0.70.0",
40
- "@crombolo/content": "0.70.0",
41
- "@crombolo/contracts": "0.70.0",
42
- "@crombolo/core": "0.70.0",
43
- "@crombolo/data": "0.70.0",
44
- "@crombolo/extension": "0.70.0",
45
- "@crombolo/render": "0.70.0",
46
- "@crombolo/schema": "0.70.0",
47
- "@crombolo/transfer": "0.70.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",
@@ -53,7 +53,8 @@ import {
53
53
  } from '@crombolo/data'
54
54
  import type { SchemaUserGroup } from '@crombolo/schema'
55
55
  import { loadAccess } from '../access.ts'
56
- import type { CromboloConfig } from '../config.ts'
56
+ import type { CromboloConfig, UsersSetting } from '../config.ts'
57
+ import { managedUserPorts } from '../managed-users.ts'
57
58
  import type { MediaFileStore } from '../media-files.ts'
58
59
 
59
60
  const INVITE_HOURS = 72
@@ -113,7 +114,7 @@ export interface UserPortOptions {
113
114
  | 'allowPasswordReset'
114
115
  | 'backOfficePath'
115
116
  | 'backofficeIdentityProviders'
116
- >
117
+ > & { users?: UsersSetting }
117
118
  mediaFiles: MediaFileStore
118
119
  nodes: NodeLookup
119
120
  /** The groups the site's files declare (story 228). */
@@ -645,16 +646,20 @@ export function createUserPorts(
645
646
  },
646
647
  }
647
648
 
648
- return {
649
- users: userPort,
650
- groups: createUserGroupPort(db, {
651
- adminKey,
652
- nodes,
653
- onPagePermissionsChanged: options.onPagePermissionsChanged,
654
- declared: options.declaredGroups,
655
- }),
656
- userData: createUserDataPort(db),
657
- }
649
+ const managed = managedUserPorts(
650
+ db,
651
+ {
652
+ users: userPort,
653
+ groups: createUserGroupPort(db, {
654
+ adminKey,
655
+ nodes,
656
+ onPagePermissionsChanged: options.onPagePermissionsChanged,
657
+ declared: options.declaredGroups,
658
+ }),
659
+ },
660
+ config.users?.managedBy ?? [],
661
+ )
662
+ return { ...managed, userData: createUserDataPort(db) }
658
663
  }
659
664
 
660
665
  function toPermissions(rows: readonly GranularPermission[]): UserGroupResponse['permissions'] {
package/src/config.ts CHANGED
@@ -193,6 +193,17 @@ export const contentFilesLocked = (config: Pick<CromboloConfig, 'code' | 'conten
193
193
  export const workspacesOn = (config: Pick<CromboloConfig, 'workspaces' | 'contentEditing'>) =>
194
194
  config.workspaces || config.contentEditing === 'locked'
195
195
 
196
+ /** Who looks after the site's back-office people (story 389). */
197
+ export interface UsersSetting {
198
+ /** The API clients a directory signs in as; none leaves users to the site. */
199
+ managedBy: readonly string[]
200
+ managedAt?: string | undefined
201
+ }
202
+
203
+ /** Whether users come only from a directory outside the site (story 389). */
204
+ export const usersManaged = (config: { users?: UsersSetting }) =>
205
+ (config.users?.managedBy.length ?? 0) > 0
206
+
196
207
  /** Whether the site takes its pages, media, types and code only by a change (story 388). */
197
208
  export const contentLocked = (config: Pick<CromboloConfig, 'contentEditing'>) =>
198
209
  config.contentEditing === 'locked'
@@ -246,9 +257,9 @@ export function runsOnLocalhost(config: CromboloConfig): boolean {
246
257
  }
247
258
  }
248
259
 
249
- /** 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. */
250
261
  export function listeningBodyLimit(config: CromboloConfig): number {
251
- return config.remote.enabled
262
+ return config.remote.enabled || workspacesOn(config)
252
263
  ? Math.max(config.maxRequestBodyBytes, config.remote.maxUploadBytes)
253
264
  : config.maxRequestBodyBytes
254
265
  }
@@ -492,6 +503,13 @@ export interface CromboloConfig {
492
503
  * `CROMBOLO_CLI_TOKENS`, off unless set.
493
504
  */
494
505
  cliTokens: boolean
506
+ /**
507
+ * Story 389: back-office people kept in a directory outside the site. With `managedBy`
508
+ * naming API clients, only they create, change, disable or delete a user, or change
509
+ * whom a group holds; `managedAt` is the directory's address for one user, with
510
+ * `{email}`, `{key}` or `{userName}`. `CROMBOLO_USERS_MANAGED_BY`, `CROMBOLO_USERS_MANAGED_AT`.
511
+ */
512
+ users: UsersSetting
495
513
  /** The most days a command-line token may last. `CROMBOLO_CLI_TOKEN_MAX_DAYS`, 90. */
496
514
  cliTokenMaxDays: number
497
515
  /**
@@ -505,6 +523,11 @@ export interface CromboloConfig {
505
523
  * needs workspaces on.
506
524
  */
507
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'
508
531
  /**
509
532
  * How many workspaces with changed views render at once on a node, each in a
510
533
  * process of its own (story 378); past it the least recently used is stopped.
@@ -1100,9 +1123,17 @@ export function loadConfig(
1100
1123
  // Resolved again below, once it is known whether this is development.
1101
1124
  cliAccess: cliAccessSetting() as CliAccess,
1102
1125
  cliTokens: setting('CROMBOLO_CLI_TOKENS') === 'true',
1126
+ users: {
1127
+ managedBy: (setting('CROMBOLO_USERS_MANAGED_BY') ?? '')
1128
+ .split(',')
1129
+ .map((id) => id.trim())
1130
+ .filter(Boolean),
1131
+ managedAt: setting('CROMBOLO_USERS_MANAGED_AT') || undefined,
1132
+ },
1103
1133
  cliTokenMaxDays: Math.floor(positiveNumber(setting('CROMBOLO_CLI_TOKEN_MAX_DAYS'), 90)),
1104
1134
  workspaces: setting('CROMBOLO_WORKSPACES') === 'true',
1105
1135
  workspacesRequired: setting('CROMBOLO_WORKSPACES_REQUIRED') === 'true',
1136
+ applyChangesBy: (setting('CROMBOLO_APPLY_CHANGES_BY') || 'any') as 'any' | 'exchange',
1106
1137
  purgeAfterDays: Math.floor(nonNegativeNumber(setting('CROMBOLO_PURGE_AFTER_DAYS'), 0)),
1107
1138
  workspacesHost: setting('CROMBOLO_WORKSPACES_HOST') || undefined,
1108
1139
  workspaceLinkMaxDays: Math.floor(
@@ -1292,6 +1323,19 @@ export function loadConfig(
1292
1323
  throw new Error(
1293
1324
  `cliAccess is "${String(merged.cliAccess)}" in crombolo.config.ts: it is open or sign-in.`,
1294
1325
  )
1326
+ if (
1327
+ !Array.isArray(merged.users?.managedBy) ||
1328
+ merged.users.managedBy.some((id) => typeof id !== 'string' || !id.trim())
1329
+ )
1330
+ throw new Error('users.managedBy in crombolo.config.ts is a list of API client ids.')
1331
+ if (merged.users.managedAt !== undefined && !/^https?:\/\//.test(merged.users.managedAt))
1332
+ throw new Error(
1333
+ `users.managedAt is "${merged.users.managedAt}": it is an http or https address, with {email}, {key} or {userName}.`,
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
+ )
1295
1339
  if (merged.workspacesRequired && !merged.workspaces)
1296
1340
  throw new Error(
1297
1341
  'Workspaces are required (CROMBOLO_WORKSPACES_REQUIRED) but not turned on: set CROMBOLO_WORKSPACES=true as well.',
@@ -1448,7 +1492,7 @@ export function describeDatabase(
1448
1492
  }
1449
1493
  }
1450
1494
 
1451
- export const VERSION = '0.70.0'
1495
+ export const VERSION = '0.72.0'
1452
1496
 
1453
1497
  /** A whole number of seconds from the environment; undefined when unset or not one. */
1454
1498
  /** A positive number from a setting, else the default. */
@@ -134,6 +134,8 @@ export function createExternalSignIn(
134
134
  log?: (message: string) => void
135
135
  /** The provider as a sign-in uses it, with an administrator's overrides on top (story 033). */
136
136
  resolve?: (provider: IdentityProvider) => Promise<IdentityProvider>
137
+ /** Accounts come from a directory outside the site (story 389): none is made, no groups follow. */
138
+ managed?: () => boolean
137
139
  },
138
140
  ): ExternalSignIn {
139
141
  const logins = new ExternalLoginRepository(db)
@@ -215,6 +217,7 @@ export function createExternalSignIn(
215
217
  }
216
218
 
217
219
  const loginProvider = externalLoginProvider(audience.audience, provider.oidc.id)
220
+ const managed = options.managed?.() === true
218
221
  const linked = await logins.find(loginProvider, identity.subject)
219
222
  // A link to an account that has since been deleted counts for nothing.
220
223
  const linkedAccount = linked ? await audience.byKey(linked.ownerKey) : undefined
@@ -224,7 +227,11 @@ export function createExternalSignIn(
224
227
  linked: linkedAccount?.key,
225
228
  sameEmail: sameEmail?.key,
226
229
  identity,
227
- provider: { ...provider, name: provider.oidc.name },
230
+ provider: {
231
+ ...provider,
232
+ name: provider.oidc.name,
233
+ ...(managed ? { autoCreate: false } : {}),
234
+ },
228
235
  })
229
236
  // Story 364: what the remote's exchange finds this person by, from this issuer.
230
237
  const named = identity.identity
@@ -250,7 +257,7 @@ export function createExternalSignIn(
250
257
  break
251
258
  }
252
259
  }
253
- if (decision.kind !== 'create' && Object.keys(provider.groupMap).length > 0) {
260
+ if (!managed && decision.kind !== 'create' && Object.keys(provider.groupMap).length > 0) {
254
261
  const groups = syncedGroups(account.groups, identity.groups, provider.groupMap)
255
262
  if (groups.join('\n') !== account.groups.join('\n')) await audience.setGroups(account, groups)
256
263
  }
@@ -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/index.ts CHANGED
@@ -118,6 +118,7 @@ export * from './live-reload.ts'
118
118
  export * from './log-expressions.ts'
119
119
  export * from './log-viewer.ts'
120
120
  export * from './logging.ts'
121
+ export { MANAGED_OUTSIDE, managedHref } from './managed-users.ts'
121
122
  export * from './marketplace.ts'
122
123
  export * from './media-files.ts'
123
124
  export * from './media-folders.ts'
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Story 389: a site whose back-office people come from a directory outside it. Only
3
+ * the API clients `users.managedBy` names create, change, disable or delete a person,
4
+ * or change whom a group holds; everyone else is refused, administrators included.
5
+ * A person's own language, avatar, password and two-factor stay theirs, and API users
6
+ * stay the administrator's. docs/configuration.md, "Users managed from outside".
7
+ */
8
+ import type {
9
+ Principal,
10
+ UserGroupPort,
11
+ UserGroupStatus,
12
+ UserPort,
13
+ } from '@crombolo/api-management/domain'
14
+ import { normaliseUuid } from '@crombolo/core'
15
+ import { type Db, UserRepository } from '@crombolo/data'
16
+
17
+ /** What a refused change says, wherever it was asked. */
18
+ export const MANAGED_OUTSIDE =
19
+ "This site's people come from a directory outside it: add, change or remove them there."
20
+
21
+ /** The ports, with every change to a person kept for the directory's clients. */
22
+ export function managedUserPorts(
23
+ db: Db,
24
+ ports: { users: UserPort; groups: UserGroupPort },
25
+ managedBy: readonly string[],
26
+ ): { users: UserPort; groups: UserGroupPort } {
27
+ if (managedBy.length === 0) return ports
28
+ const clients = new Set(managedBy)
29
+ const repository = new UserRepository(db)
30
+ const isDirectory = (principal: Principal) =>
31
+ principal.viaClient !== undefined && clients.has(principal.viaClient)
32
+ const self = (principal: Principal, key: string) =>
33
+ normaliseUuid(principal.id) === normaliseUuid(key)
34
+ /** Whether the change is refused: someone else's, to a person rather than an API user. */
35
+ const refused = async (principal: Principal, keys: readonly string[]): Promise<boolean> => {
36
+ if (isDirectory(principal)) return false
37
+ const found = await repository.byKeys(keys)
38
+ return found.some((user) => user.kind !== 'Api')
39
+ }
40
+ const others = (principal: Principal, key: string) =>
41
+ self(principal, key) ? Promise.resolve(false) : refused(principal, [key])
42
+ const { users, groups } = ports
43
+ return {
44
+ users: {
45
+ ...users,
46
+ async create(principal, input) {
47
+ if (input.kind !== 'Api' && !isDirectory(principal))
48
+ return { status: 'ManagedOutside' as const }
49
+ return users.create(principal, input)
50
+ },
51
+ async invite(principal, input, message) {
52
+ if (!isDirectory(principal)) return { status: 'ManagedOutside' as const }
53
+ return users.invite(principal, input, message)
54
+ },
55
+ async resendInvite(principal, key, message) {
56
+ if (await refused(principal, [key])) return 'ManagedOutside'
57
+ return users.resendInvite(principal, key, message)
58
+ },
59
+ async update(principal, key, input) {
60
+ if (await refused(principal, [key])) return 'ManagedOutside'
61
+ return users.update(principal, key, input)
62
+ },
63
+ async delete(principal, keys) {
64
+ if (await refused(principal, keys)) return 'ManagedOutside'
65
+ return users.delete(principal, keys)
66
+ },
67
+ async setApproved(principal, keys, approved) {
68
+ if (await refused(principal, keys)) return 'ManagedOutside'
69
+ return users.setApproved(principal, keys, approved)
70
+ },
71
+ async unlock(principal, keys) {
72
+ if (await refused(principal, keys)) return 'ManagedOutside'
73
+ return users.unlock(principal, keys)
74
+ },
75
+ async setGroups(principal, keys, groupKeys) {
76
+ if (await refused(principal, keys)) return 'ManagedOutside'
77
+ return users.setGroups(principal, keys, groupKeys)
78
+ },
79
+ async changePassword(principal, key, password, old) {
80
+ if (await others(principal, key)) return 'ManagedOutside'
81
+ return users.changePassword(principal, key, password, old)
82
+ },
83
+ async resetPassword(principal, key) {
84
+ if (await others(principal, key)) return { status: 'ManagedOutside' as const }
85
+ return users.resetPassword(principal, key)
86
+ },
87
+ async setAvatar(principal, key, file) {
88
+ if (await others(principal, key)) return 'ManagedOutside'
89
+ return users.setAvatar(principal, key, file)
90
+ },
91
+ async removeAvatar(principal, key) {
92
+ if (await others(principal, key)) return 'ManagedOutside'
93
+ return users.removeAvatar(principal, key)
94
+ },
95
+ async mayManage(principal, key) {
96
+ if (await others(principal, key)) return 'ManagedOutside'
97
+ return users.mayManage ? users.mayManage(principal, key) : 'Success'
98
+ },
99
+ },
100
+ groups: {
101
+ ...groups,
102
+ async addUsers(principal, key, userKeys): Promise<UserGroupStatus> {
103
+ if (await refused(principal, userKeys)) return 'ManagedOutside'
104
+ return groups.addUsers(principal, key, userKeys)
105
+ },
106
+ async removeUsers(principal, key, userKeys): Promise<UserGroupStatus> {
107
+ if (await refused(principal, userKeys)) return 'ManagedOutside'
108
+ return groups.removeUsers(principal, key, userKeys)
109
+ },
110
+ },
111
+ }
112
+ }
113
+
114
+ /** The directory's address for one user, `{email}`, `{key}` and `{userName}` filled in. */
115
+ export const managedHref = (
116
+ template: string,
117
+ user: { key: string; email: string; userName: string },
118
+ ): string =>
119
+ template
120
+ .replaceAll('{email}', encodeURIComponent(user.email))
121
+ .replaceAll('{key}', encodeURIComponent(user.key))
122
+ .replaceAll('{userName}', encodeURIComponent(user.userName))
package/src/principal.ts CHANGED
@@ -31,6 +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
+ : {}),
42
+ ...(identity.viaClient ? { viaClient: identity.viaClient } : {}),
35
43
  }
36
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
@@ -199,6 +199,7 @@ import {
199
199
  listeningBodyLimit,
200
200
  loadConfig,
201
201
  type ServerRole,
202
+ usersManaged,
202
203
  VERSION,
203
204
  workspacesOn,
204
205
  } from './config.ts'
@@ -270,6 +271,7 @@ import {
270
271
  import { principalOf } from './principal.ts'
271
272
  import { provenanceProblem } from './provenance.ts'
272
273
  import { createRemote, may, type RestartOutcome } from './remote.ts'
274
+ import { createChangeRoutes, mayApplyChanges, streamBody } from './remote-changes.ts'
273
275
  import { createPeopleExchange } from './remote-people.ts'
274
276
  import { createSchemaTransfer, UPLOAD_LIMITS } from './schema-transfer.ts'
275
277
  import { SiteAssets } from './site-assets.ts'
@@ -314,6 +316,7 @@ import {
314
316
  viteIslandManifest,
315
317
  viteOutDir,
316
318
  } from './islands.ts'
319
+ import { managedHref } from './managed-users.ts'
317
320
  import {
318
321
  hasMiddleware,
319
322
  isSitePath,
@@ -737,6 +740,7 @@ export async function createServer(
737
740
  applicationUrl: config.applicationUrl,
738
741
  secureCookies: config.secureCookies,
739
742
  log: (message) => log.warning('Backoffice sign-in: {message}', { message }),
743
+ managed: () => usersManaged(config),
740
744
  resolve: (provider) =>
741
745
  new IdentityProviderOverrides(
742
746
  db,
@@ -1064,7 +1068,7 @@ export async function createServer(
1064
1068
  ? undefined
1065
1069
  : 'the person has no access to the back office'
1066
1070
  },
1067
- signIn: async (key, provider, seconds, ip, actor) => {
1071
+ signIn: async (key, provider, seconds, ip, actor, forApplying) => {
1068
1072
  const user = await users.byKey(key)
1069
1073
  if (!user) return { refused: 'the person no longer exists' }
1070
1074
  const result = await auth.signInByExchange(
@@ -1073,6 +1077,7 @@ export async function createServer(
1073
1077
  seconds,
1074
1078
  ip,
1075
1079
  actor,
1080
+ forApplying,
1076
1081
  )
1077
1082
  if (result.status === 'success') return { accessToken: result.accessToken }
1078
1083
  return {
@@ -1813,6 +1818,7 @@ export async function createServer(
1813
1818
  const contentQueryPath = `${paths.pluginPath}/api/content-query`
1814
1819
  const viewAsPath = `${paths.pluginPath}/api/view-as`
1815
1820
  const cliTokensPath = `${paths.pluginPath}/api/cli-tokens`
1821
+ const usersManagedPath = `${paths.pluginPath}/api/users-managed`
1816
1822
  const workspacesPath = `${paths.pluginPath}/api/workspaces`
1817
1823
  const changesPath = `${paths.pluginPath}/api/changes`
1818
1824
  const environmentValuesPath = `${paths.pluginPath}/api/environment-values`
@@ -1893,6 +1899,45 @@ export async function createServer(
1893
1899
  schema: () => workspaceSchema,
1894
1900
  merge: () => core.operations.merge,
1895
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
+
1896
1941
  // Story 379: each workspace's site, kept on this node while it is looked at.
1897
1942
  const workspaceSites = createWorkspaceSites({
1898
1943
  db,
@@ -3335,6 +3380,19 @@ export async function createServer(
3335
3380
  : Response.json(outcome, { status: outcome.status })
3336
3381
  }
3337
3382
 
3383
+ // Story 389: whether the Users section is the directory's, and where it links each user.
3384
+ if (pathname === usersManagedPath && request.method === 'GET') {
3385
+ const principal = await authenticate(request)
3386
+ if (!principal) return new Response('Unauthorized', { status: 401 })
3387
+ const managed = usersManaged(config)
3388
+ const template = managed ? config.users.managedAt : undefined
3389
+ const key = new URL(request.url).searchParams.get('user')
3390
+ if (!key) return Response.json({ managed, linked: template !== undefined })
3391
+ if (!template || !hasSection(principal, 'users')) return Response.json({ href: null })
3392
+ const user = await new UserRepository(db).byKey(key).catch(() => undefined)
3393
+ return Response.json({ href: user ? managedHref(template, user) : null })
3394
+ }
3395
+
3338
3396
  // Story 351: a person's command-line tokens, and an administrator's view of anyone's.
3339
3397
  if (pathname === cliTokensPath || pathname.startsWith(`${cliTokensPath}/`)) {
3340
3398
  const principal = await authenticate(request)
@@ -3353,6 +3411,22 @@ export async function createServer(
3353
3411
  )
3354
3412
  }
3355
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
+
3356
3430
  // Story 375: workspaces, opened, listed, shared and discarded.
3357
3431
  if (pathname === workspacesPath || pathname.startsWith(`${workspacesPath}/`)) {
3358
3432
  const principal = await authenticate(request)
@@ -5226,7 +5300,8 @@ export async function createServer(
5226
5300
  // request is held to the usual one here.
5227
5301
  if (
5228
5302
  listeningBodyLimit(config) > config.maxRequestBodyBytes &&
5229
- !remote.isUpload(request, requestUrl)
5303
+ !remote.isUpload(request, requestUrl) &&
5304
+ managementChange(pathname, request.method) !== 'changes'
5230
5305
  ) {
5231
5306
  const length = Number(request.headers.get('content-length') ?? 0)
5232
5307
  if (length > config.maxRequestBodyBytes)
package/src/settings.ts CHANGED
@@ -306,6 +306,20 @@ const DECLARED = [
306
306
  section: 'Sign-in and secrets',
307
307
  description: "A back office user's login is their e-mail address.",
308
308
  },
309
+ {
310
+ env: 'CROMBOLO_USERS_MANAGED_BY',
311
+ kind: 'list',
312
+ section: 'Sign-in and secrets',
313
+ description:
314
+ 'The API clients a directory outside the site signs in as. Set, only they add, change, disable or remove back office users or change whom a group holds; each person keeps their own language, avatar, password and two-factor.',
315
+ },
316
+ {
317
+ env: 'CROMBOLO_USERS_MANAGED_AT',
318
+ kind: 'string',
319
+ section: 'Sign-in and secrets',
320
+ description:
321
+ "The directory's address for one user, with `{email}`, `{key}` or `{userName}` filled in: the Users section links each person there.",
322
+ },
309
323
 
310
324
  // Back office and bundles
311
325
  {
@@ -576,6 +590,15 @@ const DECLARED = [
576
590
  description:
577
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`.',
578
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
+ },
579
602
  {
580
603
  env: 'CROMBOLO_SYNC_SCHEMA_AT_BOOT',
581
604
  kind: 'boolean',
package/src/user-admin.ts CHANGED
@@ -27,6 +27,7 @@ import {
27
27
  UserRepository,
28
28
  userState,
29
29
  } from '@crombolo/data'
30
+ import { MANAGED_OUTSIDE } from './managed-users.ts'
30
31
 
31
32
  export type UserAdminKind = 'not_found' | 'refused' | 'usage' | 'conflict'
32
33
 
@@ -61,6 +62,7 @@ export interface UserSummary {
61
62
 
62
63
  const REFUSALS: Partial<Record<UserStatus | UserGroupStatus, [UserAdminKind, string]>> = {
63
64
  UserNotFound: ['not_found', 'There is no such user.'],
65
+ ManagedOutside: ['refused', MANAGED_OUTSIDE],
64
66
  NotFound: ['not_found', 'There is no such user group.'],
65
67
  MissingUserGroup: ['not_found', 'There is no group with that alias.'],
66
68
  DuplicateUserName: ['conflict', 'Another user has that username.'],