@crombolo/server 0.61.0 → 0.63.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.
@@ -6,7 +6,13 @@
6
6
  * sign-in, so a change reaches every node with nothing to invalidate.
7
7
  */
8
8
  import { type Db, type ExternalLoginAudience, now } from '@crombolo/data'
9
- import { entraIssuer, type IdentityProvider } from './identity-providers.ts'
9
+ import {
10
+ entraIssuer,
11
+ type IdentityProvider,
12
+ type LockedIdentityProviders,
13
+ lockOf,
14
+ } from './identity-providers.ts'
15
+ import { type OutboundOptions, OutboundRefused, pinnedFetch } from './outbound-address.ts'
10
16
  import { openSecret, SECRET_KEY_VARIABLE, sealSecret, usableSecretKey } from './secrets.ts'
11
17
 
12
18
  /** The fields an override may change. */
@@ -27,8 +33,15 @@ export interface ProviderOverrideInput extends ProviderOverrides {
27
33
  clientSecret?: string | null
28
34
  }
29
35
 
36
+ /** The issuer and client id a kept secret was set for (story 305): it goes nowhere else. */
37
+ interface SecretFor {
38
+ issuer: string
39
+ clientId: string
40
+ }
41
+
30
42
  interface Stored extends ProviderOverrides {
31
43
  clientSecretSealed?: string
44
+ secretFor?: SecretFor
32
45
  }
33
46
 
34
47
  const OVERRIDABLE: readonly (keyof ProviderOverrides)[] = [
@@ -46,26 +59,56 @@ const OVERRIDABLE: readonly (keyof ProviderOverrides)[] = [
46
59
  const keyOf = (audience: ExternalLoginAudience, id: string) =>
47
60
  `crombolo:identity-provider:${audience}:${id}`
48
61
 
49
- /** The provider the config declares, with an administrator's changes on top. Pure. */
62
+ /** Where a provider sends its sign-ins with these changes: its issuer and client id. Pure. */
63
+ function targetOf(code: IdentityProvider, overrides: ProviderOverrides): SecretFor {
64
+ return {
65
+ issuer:
66
+ overrides.issuer ??
67
+ (code.kind === 'entra' && overrides.tenantId
68
+ ? entraIssuer(overrides.tenantId)
69
+ : code.oidc.issuer),
70
+ clientId: overrides.clientId ?? code.oidc.clientId,
71
+ }
72
+ }
73
+
74
+ const sameTarget = (a: SecretFor, b: SecretFor) =>
75
+ a.issuer === b.issuer && a.clientId === b.clientId
76
+
77
+ /**
78
+ * The provider the config declares, with an administrator's changes on top.
79
+ * A kept secret goes only to the issuer and client id it was set for, and the
80
+ * config's only to the config's own (story 305); left with neither when the
81
+ * config gave one, the provider is unavailable rather than signing in without.
82
+ * A kept secret from before 305, with nothing to say where it was set for, is
83
+ * taken as set for where the provider now sends. Pure.
84
+ */
50
85
  export function effectiveProvider(
51
86
  code: IdentityProvider,
52
- overrides: ProviderOverrides & { clientSecret?: string },
87
+ overrides: ProviderOverrides & { clientSecret?: string; secretFor?: SecretFor },
53
88
  ): IdentityProvider {
54
89
  const tenantId = overrides.tenantId ?? code.tenantId
55
- const issuer =
56
- overrides.issuer ??
57
- (code.kind === 'entra' && overrides.tenantId
58
- ? entraIssuer(overrides.tenantId)
59
- : code.oidc.issuer)
90
+ const target = targetOf(code, overrides)
91
+ const kept =
92
+ overrides.clientSecret && (!overrides.secretFor || sameTarget(overrides.secretFor, target))
93
+ ? overrides.clientSecret
94
+ : undefined
95
+ const ownTarget = sameTarget(target, { issuer: code.oidc.issuer, clientId: code.oidc.clientId })
96
+ const clientSecret = kept ?? (ownTarget ? code.oidc.clientSecret : undefined)
97
+ const name = overrides.name ?? code.oidc.name
60
98
  return {
61
99
  ...code,
62
100
  ...(tenantId ? { tenantId } : {}),
101
+ ...(code.oidc.clientSecret && !clientSecret
102
+ ? {
103
+ unavailable: `${name} sends to ${target.issuer}, which the config did not name, and has no client secret of its own for it: set one in its settings.`,
104
+ }
105
+ : {}),
63
106
  oidc: {
64
107
  ...code.oidc,
65
- name: overrides.name ?? code.oidc.name,
66
- issuer,
67
- clientId: overrides.clientId ?? code.oidc.clientId,
68
- clientSecret: overrides.clientSecret ?? code.oidc.clientSecret,
108
+ name,
109
+ issuer: target.issuer,
110
+ clientId: target.clientId,
111
+ clientSecret,
69
112
  },
70
113
  autoCreate: overrides.autoCreate ?? code.autoCreate,
71
114
  linkByEmail: overrides.linkByEmail ?? code.linkByEmail,
@@ -78,10 +121,17 @@ export function effectiveProvider(
78
121
  export class IdentityProviderOverrides {
79
122
  #db: Db
80
123
  #secretKey: string | undefined
124
+ #locked: LockedIdentityProviders
81
125
 
82
- constructor(db: Db, secretKey: string | undefined) {
126
+ constructor(db: Db, secretKey: string | undefined, locked: LockedIdentityProviders = []) {
83
127
  this.#db = db
84
128
  this.#secretKey = usableSecretKey(secretKey)
129
+ this.#locked = locked
130
+ }
131
+
132
+ /** Who locked a provider against changes here, if anyone (story 305). */
133
+ lockOf(code: IdentityProvider): 'config' | 'environment' | undefined {
134
+ return lockOf(code, this.#locked)
85
135
  }
86
136
 
87
137
  async #read(audience: ExternalLoginAudience, id: string): Promise<Stored> {
@@ -102,13 +152,15 @@ export class IdentityProviderOverrides {
102
152
  audience: ExternalLoginAudience,
103
153
  id: string,
104
154
  ): Promise<{ overrides: ProviderOverrides; hasClientSecret: boolean }> {
105
- const { clientSecretSealed, ...overrides } = await this.#read(audience, id)
155
+ const { clientSecretSealed, secretFor: _, ...overrides } = await this.#read(audience, id)
106
156
  return { overrides, hasClientSecret: Boolean(clientSecretSealed) }
107
157
  }
108
158
 
109
159
  /** A provider as a sign-in uses it: the config's, with the changes and a kept secret on top. */
110
160
  async apply(audience: ExternalLoginAudience, code: IdentityProvider): Promise<IdentityProvider> {
111
- const { clientSecretSealed, ...overrides } = await this.#read(audience, code.oidc.id)
161
+ // A locked provider is the config's, whatever was stored before it was locked.
162
+ if (this.lockOf(code)) return code
163
+ const { clientSecretSealed, secretFor, ...overrides } = await this.#read(audience, code.oidc.id)
112
164
  if (Object.keys(overrides).length === 0 && !clientSecretSealed) return code
113
165
  let clientSecret: string | undefined
114
166
  if (clientSecretSealed && this.#secretKey) {
@@ -118,33 +170,71 @@ export class IdentityProviderOverrides {
118
170
  clientSecret = undefined
119
171
  }
120
172
  }
121
- return effectiveProvider(code, { ...overrides, clientSecret })
173
+ return effectiveProvider(code, { ...overrides, clientSecret, secretFor })
122
174
  }
123
175
 
124
- /** Changes some fields. An empty string or an empty value clears a field back to the config's. */
176
+ /**
177
+ * Changes some fields. An empty string or an empty value clears a field back
178
+ * to the config's. A locked provider takes none (story 305), and a change of
179
+ * where it signs in comes with a secret of its own, or goes back to the
180
+ * config's issuer, whose secret then applies. Answers the fields changed.
181
+ */
125
182
  async update(
126
183
  audience: ExternalLoginAudience,
127
- id: string,
184
+ code: IdentityProvider,
128
185
  input: ProviderOverrideInput,
129
- ): Promise<{ ok: true } | { ok: false; error: string }> {
186
+ ): Promise<{ ok: true; changed: string[] } | { ok: false; error: string }> {
187
+ const lock = this.lockOf(code)
188
+ if (lock)
189
+ return {
190
+ ok: false,
191
+ error:
192
+ lock === 'config'
193
+ ? `${code.oidc.name} is locked by the site's configuration, so it cannot be changed here.`
194
+ : `${code.oidc.name} is locked by the server's CROMBOLO_LOCKED_IDENTITY_PROVIDERS, so it cannot be changed here.`,
195
+ }
196
+ const id = code.oidc.id
130
197
  const stored = await this.#read(audience, id)
198
+ const before = stored.secretFor ?? targetOf(code, stored)
199
+ const changed: string[] = []
131
200
  for (const field of OVERRIDABLE) {
132
201
  if (!(field in input)) continue
133
202
  const value = input[field]
203
+ if (JSON.stringify(value ?? '') !== JSON.stringify(stored[field] ?? '')) changed.push(field)
134
204
  if (value === undefined || value === null || value === '') delete stored[field]
135
205
  else (stored as Record<string, unknown>)[field] = value
136
206
  }
137
- if (input.clientSecret === null || input.clientSecret === '') delete stored.clientSecretSealed
138
- else if (typeof input.clientSecret === 'string') {
207
+ const after = targetOf(code, stored)
208
+ const own = sameTarget(after, { issuer: code.oidc.issuer, clientId: code.oidc.clientId })
209
+ const newSecret = typeof input.clientSecret === 'string' && input.clientSecret !== ''
210
+ if (!sameTarget(before, after) && !newSecret) {
211
+ if (!own && (code.oidc.clientSecret || stored.clientSecretSealed))
212
+ return {
213
+ ok: false,
214
+ error: `A new issuer needs its own secret: give ${code.oidc.name} the client secret for ${after.issuer} in the same save.`,
215
+ }
216
+ if (own && stored.clientSecretSealed) {
217
+ delete stored.clientSecretSealed
218
+ delete stored.secretFor
219
+ changed.push('clientSecret')
220
+ }
221
+ }
222
+ if (input.clientSecret === null || input.clientSecret === '') {
223
+ if (stored.clientSecretSealed) changed.push('clientSecret')
224
+ delete stored.clientSecretSealed
225
+ delete stored.secretFor
226
+ } else if (newSecret) {
139
227
  if (!this.#secretKey)
140
228
  return {
141
229
  ok: false,
142
230
  error: `Keeping a client secret here needs ${SECRET_KEY_VARIABLE} set on the server.`,
143
231
  }
144
- stored.clientSecretSealed = sealSecret(input.clientSecret, this.#secretKey)
145
- }
232
+ stored.clientSecretSealed = sealSecret(input.clientSecret as string, this.#secretKey)
233
+ stored.secretFor = after
234
+ changed.push('clientSecret')
235
+ } else if (stored.clientSecretSealed && !stored.secretFor) stored.secretFor = after
146
236
  await this.#write(audience, id, stored)
147
- return { ok: true }
237
+ return { ok: true, changed: [...new Set(changed)] }
148
238
  }
149
239
 
150
240
  /** Puts a provider back to what the config says. */
@@ -193,6 +283,12 @@ export interface BundleIdentityProvider {
193
283
  overridden: string[]
194
284
  /** The path to register with the provider as the redirect URL, after the site's address. */
195
285
  callbackPath: string
286
+ /** Who locked it against changes here (story 305), or null. */
287
+ locked: 'config' | 'environment' | null
288
+ /** Changes stored before it was locked, which it now ignores. */
289
+ ignored: string[]
290
+ /** It sends somewhere the config did not name with no secret of its own, so it signs nobody in. */
291
+ missingSecret: boolean
196
292
  }
197
293
 
198
294
  /** The `identityProviders` bundle capability (story 033): edit, never declare. */
@@ -203,6 +299,7 @@ export interface BundleIdentityProviders {
203
299
  id: string,
204
300
  input: ProviderOverrideInput,
205
301
  ): Promise<{ ok: true } | { ok: false; error: string }>
302
+ /** Back to the config, a locked provider included: how its ignored changes are cleared. */
206
303
  reset(audience: ExternalLoginAudience, id: string): Promise<boolean>
207
304
  /** Whether the provider's discovery document answers, with what it says if not. */
208
305
  test(audience: ExternalLoginAudience, id: string): Promise<{ ok: boolean; message: string }>
@@ -217,6 +314,14 @@ export function createBundleIdentityProviders(options: {
217
314
  memberCallbackPath: string
218
315
  backofficeCallbackPath: string
219
316
  groups(audience: ExternalLoginAudience): Promise<Array<{ value: string; name: string }>>
317
+ /** Where the test may reach (story 304). */
318
+ outbound?: OutboundOptions
319
+ /** Records a change for the audit log (story 305): never a secret. */
320
+ audit?: (
321
+ action: 'identity provider changed' | 'identity provider reset',
322
+ provider: { audience: ExternalLoginAudience; id: string; name: string },
323
+ detail: string | null,
324
+ ) => Promise<void>
220
325
  }): BundleIdentityProviders {
221
326
  const declared = (audience: ExternalLoginAudience, id: string) =>
222
327
  (audience === 'member' ? options.members : options.backoffice).find((p) => p.oidc.id === id)
@@ -227,6 +332,8 @@ export function createBundleIdentityProviders(options: {
227
332
  ): Promise<BundleIdentityProvider> => {
228
333
  const effective = await options.overrides.apply(audience, code)
229
334
  const { overrides, hasClientSecret } = await options.overrides.get(audience, code.oidc.id)
335
+ const stored = [...Object.keys(overrides), ...(hasClientSecret ? ['clientSecret'] : [])]
336
+ const locked = options.overrides.lockOf(code) ?? null
230
337
  const base = audience === 'member' ? options.memberCallbackPath : options.backofficeCallbackPath
231
338
  return {
232
339
  audience,
@@ -242,8 +349,11 @@ export function createBundleIdentityProviders(options: {
242
349
  emailsVerified: effective.emailsVerified,
243
350
  groupMap: { ...effective.groupMap },
244
351
  defaultGroups: [...effective.defaultGroups],
245
- overridden: [...Object.keys(overrides), ...(hasClientSecret ? ['clientSecret'] : [])],
352
+ overridden: locked ? [] : stored,
246
353
  callbackPath: `${base}/${code.oidc.id}/callback`,
354
+ locked,
355
+ ignored: locked ? stored : [],
356
+ missingSecret: Boolean(effective.unavailable),
247
357
  }
248
358
  }
249
359
 
@@ -255,13 +365,31 @@ export function createBundleIdentityProviders(options: {
255
365
  ])
256
366
  },
257
367
  async update(audience, id, input) {
258
- if (!declared(audience, id))
259
- return { ok: false, error: 'The config declares no such identity provider.' }
260
- return options.overrides.update(audience, id, input)
368
+ const code = declared(audience, id)
369
+ if (!code) return { ok: false, error: 'The config declares no such identity provider.' }
370
+ const outcome = await options.overrides.update(audience, code, input)
371
+ if (!outcome.ok) return outcome
372
+ if (outcome.changed.length > 0)
373
+ await options.audit?.(
374
+ 'identity provider changed',
375
+ { audience, id, name: code.oidc.name },
376
+ outcome.changed
377
+ .map((field) =>
378
+ field === 'clientSecret'
379
+ ? typeof input.clientSecret === 'string' && input.clientSecret !== ''
380
+ ? 'client secret set'
381
+ : 'client secret cleared'
382
+ : field,
383
+ )
384
+ .join(', '),
385
+ )
386
+ return { ok: true }
261
387
  },
262
388
  async reset(audience, id) {
263
- if (!declared(audience, id)) return false
389
+ const code = declared(audience, id)
390
+ if (!code) return false
264
391
  await options.overrides.reset(audience, id)
392
+ await options.audit?.('identity provider reset', { audience, id, name: code.oidc.name }, null)
265
393
  return true
266
394
  },
267
395
  groups: (audience) => options.groups(audience),
@@ -269,16 +397,38 @@ export function createBundleIdentityProviders(options: {
269
397
  const code = declared(audience, id)
270
398
  if (!code) return { ok: false, message: 'The config declares no such identity provider.' }
271
399
  const effective = await options.overrides.apply(audience, code)
272
- const url = `${effective.oidc.issuer.replace(/\/$/, '')}/.well-known/openid-configuration`
400
+ const issuer = effective.oidc.issuer
401
+ const url = `${issuer.replace(/\/$/, '')}/.well-known/openid-configuration`
402
+ // Story 304: only whether it answered, never its status or what it said,
403
+ // so the test cannot read back a page from wherever the issuer points.
404
+ const notDiscovery = {
405
+ ok: false,
406
+ message: `${issuer} did not answer with an OpenID Connect discovery document.`,
407
+ }
408
+ let response: Response
409
+ try {
410
+ response = await pinnedFetch(
411
+ url,
412
+ { headers: { accept: 'application/json' } },
413
+ options.outbound,
414
+ )
415
+ } catch (error) {
416
+ return {
417
+ ok: false,
418
+ message:
419
+ error instanceof OutboundRefused
420
+ ? `${issuer} could not be reached: ${error.message}`
421
+ : `${issuer} could not be reached.`,
422
+ }
423
+ }
424
+ if (!response.ok) return notDiscovery
273
425
  try {
274
- const response = await fetch(url, { headers: { accept: 'application/json' } })
275
- if (!response.ok) return { ok: false, message: `${url} answered ${response.status}.` }
276
426
  const document = (await response.json()) as { authorization_endpoint?: unknown }
277
427
  return typeof document.authorization_endpoint === 'string'
278
- ? { ok: true, message: `${effective.oidc.name} answered at ${effective.oidc.issuer}.` }
279
- : { ok: false, message: `${url} is not an OpenID Connect discovery document.` }
280
- } catch (error) {
281
- return { ok: false, message: `${url} could not be reached: ${(error as Error).message}` }
428
+ ? { ok: true, message: `${effective.oidc.name} answered at ${issuer}.` }
429
+ : notDiscovery
430
+ } catch {
431
+ return notDiscovery
282
432
  }
283
433
  },
284
434
  }
@@ -43,6 +43,11 @@ export interface IdentityProviderOptions {
43
43
  defaultGroups?: readonly string[]
44
44
  /** Members only: the member type a new member is created as, by alias; `Member` by default. */
45
45
  memberType?: string
46
+ /**
47
+ * Takes no change from the back office (story 305): signs in by the config
48
+ * alone. `CROMBOLO_LOCKED_IDENTITY_PROVIDERS` locks it too.
49
+ */
50
+ locked?: boolean
46
51
  }
47
52
 
48
53
  /** Which preset made a provider: what the Entra bundle looks for. */
@@ -60,6 +65,23 @@ export interface IdentityProvider {
60
65
  groupMap: Readonly<Record<string, string>>
61
66
  defaultGroups: readonly string[]
62
67
  memberType: string | undefined
68
+ /** Declared `locked: true`. */
69
+ locked: boolean
70
+ /** Why it cannot sign anyone in as it stands, such as a new issuer with no secret of its own. */
71
+ unavailable?: string
72
+ }
73
+
74
+ /** What locks providers from the server's environment: their ids, or all of them. */
75
+ export type LockedIdentityProviders = readonly string[] | 'all'
76
+
77
+ /** Who locked a provider, if anyone: the site's config or the server's environment. Pure. */
78
+ export function lockOf(
79
+ provider: IdentityProvider,
80
+ locked: LockedIdentityProviders = [],
81
+ ): 'config' | 'environment' | undefined {
82
+ if (provider.locked) return 'config'
83
+ if (locked === 'all' || locked.includes(provider.oidc.id)) return 'environment'
84
+ return undefined
63
85
  }
64
86
 
65
87
  const ID = /^[a-z0-9][a-z0-9-]*$/
@@ -102,6 +124,7 @@ function preset(
102
124
  groupMap: options.groups?.map ?? {},
103
125
  defaultGroups: options.defaultGroups ?? [],
104
126
  memberType: options.memberType,
127
+ locked: options.locked === true,
105
128
  }
106
129
  }
107
130
 
package/src/index.ts CHANGED
@@ -73,6 +73,12 @@ export {
73
73
  extensionEntryProblems,
74
74
  settingsOf,
75
75
  } from './extension-discovery.ts'
76
+ export {
77
+ type InstallExtensionOptions,
78
+ type InstallExtensionResult,
79
+ installExtension,
80
+ removeExtension,
81
+ } from './extension-install.ts'
76
82
  export { denoArguments, netHosts, processReads } from './extension-process.ts'
77
83
  export { normaliseScreenResult, safeScreenHref, screenValues } from './extension-screens.ts'
78
84
  export { extensionSqlProblem } from './extension-sql.ts'
@@ -89,6 +95,7 @@ export * from './git.ts'
89
95
  export * from './git-github.ts'
90
96
  export * from './git-routes.ts'
91
97
  export * from './grant-policy.ts'
98
+ export * from './grant-trust.ts'
92
99
  export * from './host-token.ts'
93
100
  export * from './identity-provider-overrides.ts'
94
101
  export * from './identity-providers.ts'