@crombolo/server 0.60.0 → 0.62.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.
@@ -265,6 +265,16 @@ export function createExternalSignIn(
265
265
  if (!declared || rest.length > 0) return undefined
266
266
  if (request.method !== 'GET') return new Response(null, { status: 405 })
267
267
  const provider = options.resolve ? await options.resolve(declared) : declared
268
+ // Story 305: never a sign-in to an issuer without the secret meant for it.
269
+ if (provider.unavailable) {
270
+ options.log?.(provider.unavailable)
271
+ return redirect(
272
+ audience.failed(
273
+ localReturnUrl(new URL(request.url).searchParams.get('returnUrl')) ?? '/',
274
+ `${provider.oidc.name} sign-in is not available right now. Ask an administrator.`,
275
+ ),
276
+ )
277
+ }
268
278
  const client = clientFor(provider)
269
279
  if (step === undefined || step === '') return start(request, provider, client)
270
280
  if (step === 'callback') return finish(request, provider, client)
@@ -25,6 +25,7 @@ import {
25
25
  DocumentRepository,
26
26
  FormWorkflowRepository,
27
27
  type FormWorkflowRun,
28
+ FormWorkflowSecretRepository,
28
29
  type NodeSchemaState,
29
30
  } from '@crombolo/data'
30
31
  import type { EmailField, EmailProps, EmailRenderResult } from '@crombolo/render'
@@ -33,6 +34,13 @@ import { htmlToText } from './email-text.ts'
33
34
  import type { FormWorkflowTypeDefinition } from './form-types.ts'
34
35
  import { logger } from './logging.ts'
35
36
  import type { MediaFileStore } from './media-files.ts'
37
+ import {
38
+ checkedAddress,
39
+ type OutboundOptions,
40
+ OutboundRefused,
41
+ pinnedFetch,
42
+ } from './outbound-address.ts'
43
+ import { openSecret, usableSecretKey } from './secrets.ts'
36
44
 
37
45
  const log = logger('forms')
38
46
 
@@ -65,6 +73,10 @@ export interface WorkflowDeps {
65
73
  email?: EmailPort
66
74
  mediaFiles?: MediaFileStore
67
75
  fetch?: typeof fetch
76
+ /** Where a send-to-URL workflow may go (story 304); a test's own lookup. */
77
+ outbound?: Omit<OutboundOptions, 'fetch'>
78
+ /** Opens a send-to-URL workflow's secret headers. */
79
+ secretKey?: string
68
80
  nodeState?: NodeSchemaState
69
81
  nodeId?: string
70
82
  /** Told when a workflow published something, so the cache is dropped. */
@@ -436,6 +448,84 @@ async function saveAsContent(
436
448
 
437
449
  // ------------------------------------------------------------------ send to url
438
450
 
451
+ /** A header the form names as secret, its value kept sealed in the database (story 304). */
452
+ export const isSecretHeader = (value: unknown): value is { secret: true } =>
453
+ Boolean(value && typeof value === 'object' && (value as { secret?: unknown }).secret === true)
454
+
455
+ /** What a log keeps of a refusal: a short text answer, nothing of any other. */
456
+ async function answerText(response: Response): Promise<string> {
457
+ const type = response.headers.get('content-type') ?? ''
458
+ if (!/^text\/|json|xml/i.test(type)) return ''
459
+ return (await response.text().catch(() => '')).trim().slice(0, 300)
460
+ }
461
+
462
+ /** The headers to send: those written in the form, and its secrets, opened for this URL. */
463
+ async function sendHeaders(
464
+ workflow: SchemaFormWorkflow,
465
+ context: WorkflowContext,
466
+ deps: WorkflowDeps,
467
+ url: string,
468
+ ): Promise<{ headers: Record<string, string> } | { error: string }> {
469
+ const settings = workflow.settings.headers
470
+ const written =
471
+ settings && typeof settings === 'object' && !Array.isArray(settings)
472
+ ? (settings as Record<string, unknown>)
473
+ : {}
474
+ const headers: Record<string, string> = {}
475
+ const secret: string[] = []
476
+ for (const [name, value] of Object.entries(written)) {
477
+ if (isSecretHeader(value)) secret.push(name)
478
+ else if (typeof value === 'string') headers[name] = value
479
+ }
480
+ if (secret.length === 0) return { headers }
481
+ const key = usableSecretKey(deps.secretKey)
482
+ const kept =
483
+ context.form.key && workflow.key
484
+ ? await new FormWorkflowSecretRepository(deps.db).of(context.form.key, workflow.key)
485
+ : new Map()
486
+ for (const name of secret) {
487
+ const stored = kept.get(name)
488
+ if (!stored) return { error: `The secret header "${name}" has not been set.` }
489
+ if (stored.url !== url)
490
+ return {
491
+ error: `The secret header "${name}" was set for another address; set it again for this one.`,
492
+ }
493
+ try {
494
+ if (!key) throw new Error('no key')
495
+ headers[name] = openSecret(stored.sealed, key)
496
+ } catch {
497
+ return {
498
+ error: `The secret header "${name}" cannot be read with this server's CROMBOLO_SECRET_KEY; set it again.`,
499
+ }
500
+ }
501
+ }
502
+ return { headers }
503
+ }
504
+
505
+ /**
506
+ * Why a form may not be saved sending where it says: a send-to-URL workflow's
507
+ * address, where its host already resolves, that the site does not send to. A
508
+ * host that does not resolve yet is checked at each send instead.
509
+ */
510
+ export async function refusedSendAddresses(
511
+ form: SchemaForm,
512
+ allowPrivateAddresses: boolean,
513
+ lookup?: OutboundOptions['lookup'],
514
+ ): Promise<{ path: string; message: string }[]> {
515
+ const problems: { path: string; message: string }[] = []
516
+ for (const [index, workflow] of form.workflows.entries()) {
517
+ const url = workflow.type === 'sendToUrl' ? asString(workflow.settings.url) : undefined
518
+ if (!url || !URL.canParse(url)) continue
519
+ try {
520
+ await checkedAddress(new URL(url), { allowPrivateAddresses, lookup })
521
+ } catch (error) {
522
+ if (error instanceof OutboundRefused && !error.message.endsWith('has no address.'))
523
+ problems.push({ path: `workflow[${index}].settings.url`, message: error.message })
524
+ }
525
+ }
526
+ return problems
527
+ }
528
+
439
529
  async function sendToUrl(
440
530
  workflow: SchemaFormWorkflow,
441
531
  context: WorkflowContext,
@@ -445,10 +535,8 @@ async function sendToUrl(
445
535
  const url = asString(settings.url)
446
536
  if (!url) return { ok: false, retry: false, error: 'The workflow names no URL.' }
447
537
  const method = settings.method === 'PUT' ? 'PUT' : 'POST'
448
- const headers =
449
- settings.headers && typeof settings.headers === 'object' && !Array.isArray(settings.headers)
450
- ? (settings.headers as Record<string, string>)
451
- : {}
538
+ const headers = await sendHeaders(workflow, context, deps, url)
539
+ if ('error' in headers) return { ok: false, retry: false, error: headers.error }
452
540
 
453
541
  const fields: Record<string, string | string[]> = {}
454
542
  for (const value of context.values)
@@ -463,15 +551,25 @@ async function sendToUrl(
463
551
  body.submittedAt = new Date().toISOString()
464
552
  }
465
553
 
466
- const call = deps.fetch ?? fetch
467
554
  try {
468
- const response = await call(url, {
469
- method,
470
- headers: { 'content-type': 'application/json', ...headers },
471
- body: JSON.stringify(body),
472
- })
555
+ const response = await pinnedFetch(
556
+ url,
557
+ {
558
+ method,
559
+ headers: { 'content-type': 'application/json', ...headers.headers },
560
+ body: JSON.stringify(body),
561
+ },
562
+ { ...deps.outbound, fetch: deps.fetch },
563
+ )
473
564
  if (response.ok) return { ok: true, detail: String(response.status) }
474
- const detail = (await response.text().catch(() => '')).trim().slice(0, 300)
565
+ // Story 304: a redirect is the receiver's answer, never followed.
566
+ if (response.status >= 300 && response.status < 400)
567
+ return {
568
+ ok: false,
569
+ retry: false,
570
+ error: `the endpoint answered ${response.status}, a redirect, which is not followed`,
571
+ }
572
+ const detail = await answerText(response)
475
573
  // A 4xx will not fix itself; a 5xx might.
476
574
  return {
477
575
  ok: false,
@@ -481,7 +579,7 @@ async function sendToUrl(
481
579
  } catch (error) {
482
580
  return {
483
581
  ok: false,
484
- retry: true,
582
+ retry: !(error instanceof OutboundRefused),
485
583
  error: error instanceof Error ? error.message : String(error),
486
584
  }
487
585
  }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Who may grant what (story 324): an administrator grants an extension what it
3
+ * asks for, at any level; Acts as you and Unrestricted also need a package
4
+ * someone has vouched for; a host may keep Unrestricted to the site's config.
5
+ * One that asks for nothing needs no grant, so Settings access installs it.
6
+ * One function, so the panel, the API, the command line and a remote all refuse
7
+ * alike. docs/bundles.md, "Levels".
8
+ */
9
+ import { type AccessLevel, isUpperLevel } from '@crombolo/backoffice-host/registry'
10
+ import type { ProvenanceResult } from './provenance.ts'
11
+
12
+ /** Where Unrestricted may be granted from: the back office, or only the site's config. */
13
+ export type UnrestrictedFrom = 'backoffice' | 'config'
14
+
15
+ /** What a host's `CROMBOLO_UNRESTRICTED_EXTENSIONS` says, `backoffice` unless it says `config`. */
16
+ export const unrestrictedFrom = (value: string | undefined): UnrestrictedFrom =>
17
+ value?.trim().toLowerCase() === 'config' ? 'config' : 'backoffice'
18
+
19
+ /** A package someone has vouched for: signed, vouched for by the host, or built here. */
20
+ export const vouchedFor = (provenance: ProvenanceResult | undefined): boolean =>
21
+ provenance?.state === 'signed' || provenance?.state === 'vouched' || provenance?.state === 'local'
22
+
23
+ export const ADMINISTRATOR_GRANTS = 'An administrator can turn this on.'
24
+ export const NOBODY_VOUCHED =
25
+ "Nobody has vouched for who built this, so it can't be turned on here."
26
+ export const CONFIG_GRANTS =
27
+ 'This site turns on Unrestricted extensions only in its configuration, which your developers change.'
28
+
29
+ /** What the person may do about one level, as the panel shows it. */
30
+ export type MayGrant = 'yes' | 'administrator' | 'config'
31
+
32
+ /** What a person may grant at each level here. */
33
+ export function mayGrant(isAdmin: boolean, from: UnrestrictedFrom): Record<AccessLevel, MayGrant> {
34
+ return {
35
+ limited: isAdmin ? 'yes' : 'administrator',
36
+ 'acts-as-you': isAdmin ? 'yes' : 'administrator',
37
+ unrestricted: from === 'config' ? 'config' : isAdmin ? 'yes' : 'administrator',
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Why this person may not grant this level of this package here, or undefined
43
+ * when they may. `grants` is whether it asks for anything at all. Pure.
44
+ */
45
+ export function grantRefusal(options: {
46
+ level: AccessLevel
47
+ grants: boolean
48
+ isAdmin: boolean
49
+ provenance: ProvenanceResult | undefined
50
+ from: UnrestrictedFrom
51
+ }): string | undefined {
52
+ if (!options.grants) return undefined
53
+ if (options.level === 'unrestricted' && options.from === 'config') return CONFIG_GRANTS
54
+ if (!options.isAdmin) return ADMINISTRATOR_GRANTS
55
+ if (isUpperLevel(options.level) && !vouchedFor(options.provenance)) return NOBODY_VOUCHED
56
+ return undefined
57
+ }
@@ -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