@crombolo/server 0.70.0 → 0.71.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.71.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.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",
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'
@@ -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
  /**
@@ -1100,6 +1118,13 @@ export function loadConfig(
1100
1118
  // Resolved again below, once it is known whether this is development.
1101
1119
  cliAccess: cliAccessSetting() as CliAccess,
1102
1120
  cliTokens: setting('CROMBOLO_CLI_TOKENS') === 'true',
1121
+ users: {
1122
+ managedBy: (setting('CROMBOLO_USERS_MANAGED_BY') ?? '')
1123
+ .split(',')
1124
+ .map((id) => id.trim())
1125
+ .filter(Boolean),
1126
+ managedAt: setting('CROMBOLO_USERS_MANAGED_AT') || undefined,
1127
+ },
1103
1128
  cliTokenMaxDays: Math.floor(positiveNumber(setting('CROMBOLO_CLI_TOKEN_MAX_DAYS'), 90)),
1104
1129
  workspaces: setting('CROMBOLO_WORKSPACES') === 'true',
1105
1130
  workspacesRequired: setting('CROMBOLO_WORKSPACES_REQUIRED') === 'true',
@@ -1292,6 +1317,15 @@ export function loadConfig(
1292
1317
  throw new Error(
1293
1318
  `cliAccess is "${String(merged.cliAccess)}" in crombolo.config.ts: it is open or sign-in.`,
1294
1319
  )
1320
+ if (
1321
+ !Array.isArray(merged.users?.managedBy) ||
1322
+ merged.users.managedBy.some((id) => typeof id !== 'string' || !id.trim())
1323
+ )
1324
+ throw new Error('users.managedBy in crombolo.config.ts is a list of API client ids.')
1325
+ if (merged.users.managedAt !== undefined && !/^https?:\/\//.test(merged.users.managedAt))
1326
+ throw new Error(
1327
+ `users.managedAt is "${merged.users.managedAt}": it is an http or https address, with {email}, {key} or {userName}.`,
1328
+ )
1295
1329
  if (merged.workspacesRequired && !merged.workspaces)
1296
1330
  throw new Error(
1297
1331
  'Workspaces are required (CROMBOLO_WORKSPACES_REQUIRED) but not turned on: set CROMBOLO_WORKSPACES=true as well.',
@@ -1448,7 +1482,7 @@ export function describeDatabase(
1448
1482
  }
1449
1483
  }
1450
1484
 
1451
- export const VERSION = '0.70.0'
1485
+ export const VERSION = '0.71.0'
1452
1486
 
1453
1487
  /** A whole number of seconds from the environment; undefined when unset or not one. */
1454
1488
  /** 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
  }
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
@@ -32,5 +32,6 @@ export async function principalOf(
32
32
  ...(identity.viewingAs ? { viewingAs: identity.viewingAs } : {}),
33
33
  ...(viaToken ? { viaToken } : {}),
34
34
  ...(identity.exchangedThrough ? { viaExchange: { provider: identity.exchangedThrough } } : {}),
35
+ ...(identity.viaClient ? { viaClient: identity.viaClient } : {}),
35
36
  }
36
37
  }
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'
@@ -314,6 +315,7 @@ import {
314
315
  viteIslandManifest,
315
316
  viteOutDir,
316
317
  } from './islands.ts'
318
+ import { managedHref } from './managed-users.ts'
317
319
  import {
318
320
  hasMiddleware,
319
321
  isSitePath,
@@ -737,6 +739,7 @@ export async function createServer(
737
739
  applicationUrl: config.applicationUrl,
738
740
  secureCookies: config.secureCookies,
739
741
  log: (message) => log.warning('Backoffice sign-in: {message}', { message }),
742
+ managed: () => usersManaged(config),
740
743
  resolve: (provider) =>
741
744
  new IdentityProviderOverrides(
742
745
  db,
@@ -1813,6 +1816,7 @@ export async function createServer(
1813
1816
  const contentQueryPath = `${paths.pluginPath}/api/content-query`
1814
1817
  const viewAsPath = `${paths.pluginPath}/api/view-as`
1815
1818
  const cliTokensPath = `${paths.pluginPath}/api/cli-tokens`
1819
+ const usersManagedPath = `${paths.pluginPath}/api/users-managed`
1816
1820
  const workspacesPath = `${paths.pluginPath}/api/workspaces`
1817
1821
  const changesPath = `${paths.pluginPath}/api/changes`
1818
1822
  const environmentValuesPath = `${paths.pluginPath}/api/environment-values`
@@ -3335,6 +3339,19 @@ export async function createServer(
3335
3339
  : Response.json(outcome, { status: outcome.status })
3336
3340
  }
3337
3341
 
3342
+ // Story 389: whether the Users section is the directory's, and where it links each user.
3343
+ if (pathname === usersManagedPath && request.method === 'GET') {
3344
+ const principal = await authenticate(request)
3345
+ if (!principal) return new Response('Unauthorized', { status: 401 })
3346
+ const managed = usersManaged(config)
3347
+ const template = managed ? config.users.managedAt : undefined
3348
+ const key = new URL(request.url).searchParams.get('user')
3349
+ if (!key) return Response.json({ managed, linked: template !== undefined })
3350
+ if (!template || !hasSection(principal, 'users')) return Response.json({ href: null })
3351
+ const user = await new UserRepository(db).byKey(key).catch(() => undefined)
3352
+ return Response.json({ href: user ? managedHref(template, user) : null })
3353
+ }
3354
+
3338
3355
  // Story 351: a person's command-line tokens, and an administrator's view of anyone's.
3339
3356
  if (pathname === cliTokensPath || pathname.startsWith(`${cliTokensPath}/`)) {
3340
3357
  const principal = await authenticate(request)
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
  {
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.'],