@crombolo/server 0.66.0 → 0.67.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.66.0",
3
+ "version": "0.67.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.66.0",
36
- "@crombolo/api-management": "0.66.0",
37
- "@crombolo/auth": "0.66.0",
38
- "@crombolo/backoffice-host": "0.66.0",
39
- "@crombolo/common": "0.66.0",
40
- "@crombolo/content": "0.66.0",
41
- "@crombolo/contracts": "0.66.0",
42
- "@crombolo/core": "0.66.0",
43
- "@crombolo/data": "0.66.0",
44
- "@crombolo/extension": "0.66.0",
45
- "@crombolo/render": "0.66.0",
46
- "@crombolo/schema": "0.66.0",
47
- "@crombolo/transfer": "0.66.0",
35
+ "@crombolo/api-delivery": "0.67.0",
36
+ "@crombolo/api-management": "0.67.0",
37
+ "@crombolo/auth": "0.67.0",
38
+ "@crombolo/backoffice-host": "0.67.0",
39
+ "@crombolo/common": "0.67.0",
40
+ "@crombolo/content": "0.67.0",
41
+ "@crombolo/contracts": "0.67.0",
42
+ "@crombolo/core": "0.67.0",
43
+ "@crombolo/data": "0.67.0",
44
+ "@crombolo/extension": "0.67.0",
45
+ "@crombolo/render": "0.67.0",
46
+ "@crombolo/schema": "0.67.0",
47
+ "@crombolo/transfer": "0.67.0",
48
48
  "@logtape/logtape": "^2.3.8",
49
49
  "@opentelemetry/api": "1.10.0",
50
50
  "@opentelemetry/context-async-hooks": "3.0.0",
@@ -217,6 +217,20 @@ export function createMemberPort(db: Db, options: MemberPortOptions = {}): Membe
217
217
  return undefined
218
218
  }
219
219
 
220
+ /**
221
+ * A group that doesn't exist is refused rather than dropped, so a save never
222
+ * leaves a member out of a group it was asked to put them in.
223
+ */
224
+ const unknownGroups = async (groupKeys: readonly string[] | undefined) => {
225
+ const missing = await members.notGroups(groupKeys ?? [])
226
+ if (missing.length === 0) return undefined
227
+ return {
228
+ ok: false as const,
229
+ reason: `No member group has ${missing.length === 1 ? 'the key' : 'the keys'} ${missing.map((k) => `"${k}"`).join(', ')}.`,
230
+ status: 400,
231
+ }
232
+ }
233
+
220
234
  const failure = (error: unknown) => {
221
235
  if (error instanceof WriteRejectedError)
222
236
  return { ok: false as const, reason: error.message, status: 409 }
@@ -235,7 +249,7 @@ export function createMemberPort(db: Db, options: MemberPortOptions = {}): Membe
235
249
  const type = await memberTypes.byKey(input.memberTypeKey)
236
250
  if (!type)
237
251
  return { ok: false as const, reason: 'The member type could not be found.', status: 404 }
238
- const clash = await duplicate(input)
252
+ const clash = (await duplicate(input)) ?? (await unknownGroups(input.groupKeys))
239
253
  if (clash) return clash
240
254
  try {
241
255
  const created = await members.create(
@@ -259,7 +273,7 @@ export function createMemberPort(db: Db, options: MemberPortOptions = {}): Membe
259
273
  async update(key, input, principal) {
260
274
  const existing = await members.byKey(key)
261
275
  if (!existing) return notFound()
262
- const clash = await duplicate(input, key)
276
+ const clash = (await duplicate(input, key)) ?? (await unknownGroups(input.groupKeys))
263
277
  if (clash) return clash
264
278
  // Umbraco requires the current password only when the editor supplies one;
265
279
  // an administrator changing another member's password does not.
package/src/approvals.ts CHANGED
@@ -269,8 +269,9 @@ export function scheduleRefusal(
269
269
  }
270
270
 
271
271
  /**
272
- * CI and a command-line token never decide (stories 160, 351): a person
273
- * deciding, signed in, is the point of an approval.
272
+ * CI, a command-line token and a token exchanged through a provider never
273
+ * decide (stories 160, 351, 364): a person deciding, signed in, is the point
274
+ * of an approval.
274
275
  */
275
276
  function refuseUnattended(principal: Principal): void {
276
277
  if (principal.ci) throw new ApprovalRefused('CI cannot approve or send back a request.', 403)
@@ -279,6 +280,11 @@ function refuseUnattended(principal: Principal): void {
279
280
  'A command-line token cannot approve or send back a request. Decide it signed in as yourself.',
280
281
  403,
281
282
  )
283
+ if (principal.viaExchange)
284
+ throw new ApprovalRefused(
285
+ 'A sign-in through another service cannot approve or send back a request. Decide it signed in as yourself.',
286
+ 403,
287
+ )
282
288
  }
283
289
 
284
290
  export function createApprovals(options: ApprovalsOptions): Approvals {
@@ -96,6 +96,12 @@ export function createCliTokensApi(db: Db, tokens: CliTokens) {
96
96
  }
97
97
  if (!enabled) return refused(CLI_TOKEN_REFUSALS.off)
98
98
  if (request.method === 'POST' && rest === '') {
99
+ // Story 364: a sign-in through another service lasts minutes; a token it made would not.
100
+ if (principal.viaExchange)
101
+ return refused(
102
+ 'A sign-in through another service cannot make command-line tokens. Make one signed in as yourself.',
103
+ 403,
104
+ )
99
105
  const body = (await request.json().catch(() => ({}))) as { name?: unknown; days?: unknown }
100
106
  const issued = await tokens.issue(
101
107
  me.id,
package/src/config.ts CHANGED
@@ -27,6 +27,8 @@ import { type UnrestrictedFrom, unrestrictedFrom } from './grant-policy.ts'
27
27
  import { checkHost, type HostConfig } from './host-token.ts'
28
28
  import {
29
29
  checkIdentityProviders,
30
+ exchangeAudienceClashes,
31
+ exchangingProviders,
30
32
  type IdentityProvider,
31
33
  type LockedIdentityProviders,
32
34
  } from './identity-providers.ts'
@@ -238,6 +240,12 @@ export interface CromboloConfig {
238
240
  * them without the site's code. A provider's own `locked: true` does too.
239
241
  */
240
242
  lockedIdentityProviders: LockedIdentityProviders
243
+ /**
244
+ * Back-office identity providers whose tokens the remote exchanges for a
245
+ * sign-in as the person (story 364), by id, besides those the config opts
246
+ * in: `CROMBOLO_REMOTE_EXCHANGE_PROVIDERS`.
247
+ */
248
+ remoteExchangeProviders: readonly string[]
241
249
  /**
242
250
  * Whether the cache-busted asset path may be cached immutably. Defaults to
243
251
  * `!development`.
@@ -1064,6 +1072,10 @@ export function loadConfig(
1064
1072
  liveReload: envFlag(setting('CROMBOLO_LIVE_RELOAD')) ?? false,
1065
1073
  allowPrivateAddresses: envFlag(setting('CROMBOLO_ALLOW_PRIVATE_ADDRESSES')) ?? false,
1066
1074
  lockedIdentityProviders: lockedProviders(setting('CROMBOLO_LOCKED_IDENTITY_PROVIDERS')),
1075
+ remoteExchangeProviders: (setting('CROMBOLO_REMOTE_EXCHANGE_PROVIDERS') ?? '')
1076
+ .split(',')
1077
+ .map((id) => id.trim())
1078
+ .filter(Boolean),
1067
1079
  seo: stripUndefined({
1068
1080
  sitemap: envFlag(setting('CROMBOLO_SITEMAP')),
1069
1081
  indexable: envFlag(setting('CROMBOLO_INDEXABLE')),
@@ -1132,6 +1144,11 @@ export function loadConfig(
1132
1144
  )
1133
1145
  checkIdentityProviders(merged.memberIdentityProviders, 'member')
1134
1146
  checkIdentityProviders(merged.backofficeIdentityProviders, 'backoffice')
1147
+ for (const clash of exchangeAudienceClashes(
1148
+ exchangingProviders(merged.backofficeIdentityProviders, merged.remoteExchangeProviders),
1149
+ merged.backofficeIdentityProviders,
1150
+ ))
1151
+ throw new Error(clash)
1135
1152
  // Field by field, so a site setting its title suffix keeps the environment's switches.
1136
1153
  merged.seo = { ...fromEnv.seo, ...stripUndefined(overrides.seo ?? {}) }
1137
1154
  merged.remote = { ...fromEnv.remote, ...stripUndefined(overrides.remote ?? {}) }
@@ -1273,7 +1290,7 @@ export function describeDatabase(
1273
1290
  }
1274
1291
  }
1275
1292
 
1276
- export const VERSION = '0.66.0'
1293
+ export const VERSION = '0.67.0'
1277
1294
 
1278
1295
  /** A whole number of seconds from the environment; undefined when unset or not one. */
1279
1296
  /** A positive number from a setting, else the default. */
@@ -226,21 +226,27 @@ export function createExternalSignIn(
226
226
  identity,
227
227
  provider: { ...provider, name: provider.oidc.name },
228
228
  })
229
+ // Story 364: what the remote's exchange finds this person by, from this issuer.
230
+ const named = identity.identity
231
+ ? { value: identity.identity, issuer: provider.oidc.issuer }
232
+ : undefined
229
233
  let account: ExternalAccount
230
234
  switch (decision.kind) {
231
235
  case 'refuse':
232
236
  return back(decision.reason)
233
237
  case 'signIn':
234
238
  account = linkedAccount as ExternalAccount
239
+ if (named?.value !== linked?.identity?.value || named?.issuer !== linked?.identity?.issuer)
240
+ await logins.recordIdentity(loginProvider, identity.subject, named)
235
241
  break
236
242
  case 'link':
237
243
  account = sameEmail as ExternalAccount
238
- await logins.link(account.key, loginProvider, identity.subject)
244
+ await logins.link(account.key, loginProvider, identity.subject, named)
239
245
  break
240
246
  case 'create': {
241
247
  const groups = syncedGroups(provider.defaultGroups, identity.groups, provider.groupMap)
242
248
  account = await audience.create(identity, provider, groups)
243
- await logins.link(account.key, loginProvider, identity.subject)
249
+ await logins.link(account.key, loginProvider, identity.subject, named)
244
250
  break
245
251
  }
246
252
  }
@@ -48,6 +48,13 @@ export interface IdentityProviderOptions {
48
48
  * alone. `CROMBOLO_LOCKED_IDENTITY_PROVIDERS` locks it too.
49
49
  */
50
50
  locked?: boolean
51
+ /**
52
+ * Back-office providers only (story 364): lets the remote exchange this
53
+ * provider's tokens for a sign-in as the person they name. The token's `aud`
54
+ * must be `audience`, the site's origin by default, and never a sign-in
55
+ * client id. `CROMBOLO_REMOTE_EXCHANGE_PROVIDERS` turns it on too.
56
+ */
57
+ remoteExchange?: boolean | { audience?: string }
51
58
  }
52
59
 
53
60
  /** Which preset made a provider: what the Entra bundle looks for. */
@@ -67,6 +74,8 @@ export interface IdentityProvider {
67
74
  memberType: string | undefined
68
75
  /** Declared `locked: true`. */
69
76
  locked: boolean
77
+ /** Declared `remoteExchange`: the audience its exchanged tokens carry, when not the site's origin. */
78
+ remoteExchange: { audience?: string } | undefined
70
79
  /** Why it cannot sign anyone in as it stands, such as a new issuer with no secret of its own. */
71
80
  unavailable?: string
72
81
  }
@@ -125,6 +134,12 @@ function preset(
125
134
  defaultGroups: options.defaultGroups ?? [],
126
135
  memberType: options.memberType,
127
136
  locked: options.locked === true,
137
+ remoteExchange:
138
+ options.remoteExchange === true
139
+ ? {}
140
+ : typeof options.remoteExchange === 'object'
141
+ ? { ...options.remoteExchange }
142
+ : undefined,
128
143
  }
129
144
  }
130
145
 
@@ -145,7 +160,8 @@ export function entra(
145
160
  clientId: options.clientId,
146
161
  clientSecret: options.clientSecret,
147
162
  },
148
- { email: 'email', name: 'name', groups: 'groups' },
163
+ // Entra's `sub` differs for each app registration; `oid` is the person's in the tenant.
164
+ { email: 'email', name: 'name', groups: 'groups', identity: 'oid' },
149
165
  options,
150
166
  )
151
167
  return { ...provider, tenantId: options.tenantId }
@@ -206,3 +222,30 @@ export function checkIdentityProviders(
206
222
  }
207
223
  return list
208
224
  }
225
+
226
+ /** The back-office providers that exchange: those the config opts in, and those the server names. */
227
+ export function exchangingProviders(
228
+ providers: readonly IdentityProvider[],
229
+ fromServer: readonly string[],
230
+ ): IdentityProvider[] {
231
+ return providers.flatMap((provider) => {
232
+ if (provider.remoteExchange) return [provider]
233
+ return fromServer.includes(provider.oidc.id) ? [{ ...provider, remoteExchange: {} }] : []
234
+ })
235
+ }
236
+
237
+ /** Exchanging providers whose audience is a client id a sign-in uses, which the boot refuses. Pure. */
238
+ export function exchangeAudienceClashes(
239
+ exchanging: readonly IdentityProvider[],
240
+ backoffice: readonly IdentityProvider[],
241
+ ): string[] {
242
+ return exchanging.flatMap((provider) => {
243
+ const audience = provider.remoteExchange?.audience
244
+ const clash = audience ? backoffice.find((p) => p.oidc.clientId === audience) : undefined
245
+ return clash
246
+ ? [
247
+ `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.`,
248
+ ]
249
+ : []
250
+ })
251
+ }
package/src/principal.ts CHANGED
@@ -31,5 +31,6 @@ 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
35
  }
35
36
  }
package/src/remote-ci.ts CHANGED
@@ -30,6 +30,18 @@ export const CI_TOKEN_SECONDS = 15 * 60
30
30
  /** An identity token valid for longer than this is refused. */
31
31
  const MAX_IDENTITY_SECONDS = 60 * 60
32
32
 
33
+ /** The `iss` a JWT claims, unverified: only to choose who checks it. */
34
+ export function unverifiedIssuer(token: string): string | undefined {
35
+ try {
36
+ const body = token.split('.')[1]
37
+ if (!body) return undefined
38
+ const payload = JSON.parse(Buffer.from(body, 'base64url').toString('utf8')) as JWTPayload
39
+ return typeof payload.iss === 'string' ? payload.iss.replace(/\/+$/, '') : undefined
40
+ } catch {
41
+ return undefined
42
+ }
43
+ }
44
+
33
45
  /** The issuers a site trusts tokens from: GitHub's, gitlab.com's, and any it names. */
34
46
  export function trustedIssuers(extra: readonly string[] = []): string[] {
35
47
  return [...new Set([GITHUB_ISSUER, GITLAB_ISSUER, ...extra.map((i) => i.replace(/\/+$/, ''))])]
@@ -47,6 +59,27 @@ export function usableIssuer(issuer: string): boolean {
47
59
  }
48
60
  }
49
61
 
62
+ /**
63
+ * An issuer's signing keys, from its OIDC discovery: cached per issuer, and
64
+ * failing closed when the issuer or its key set is not one to fetch.
65
+ */
66
+ export function issuerKeys(): (issuer: string) => Promise<ReturnType<typeof createRemoteJWKSet>> {
67
+ const keySets = new Map<string, ReturnType<typeof createRemoteJWKSet>>()
68
+ return async (issuer) => {
69
+ const known = keySets.get(issuer)
70
+ if (known) return known
71
+ if (!usableIssuer(issuer)) throw new Error('the issuer is not reached over HTTPS')
72
+ const response = await fetch(`${issuer.replace(/\/+$/, '')}/.well-known/openid-configuration`)
73
+ if (!response.ok) throw new Error(`the issuer's discovery answered ${response.status}`)
74
+ const { jwks_uri: jwksUri } = (await response.json()) as { jwks_uri?: string }
75
+ if (!jwksUri || !usableIssuer(new URL(jwksUri).origin))
76
+ throw new Error('the issuer names no usable key set')
77
+ const set = createRemoteJWKSet(new URL(jwksUri))
78
+ keySets.set(issuer, set)
79
+ return set
80
+ }
81
+ }
82
+
50
83
  /** Where a CI run was, from its identity token, in the same words for either provider. */
51
84
  export interface RunClaims {
52
85
  repository: string
@@ -193,21 +226,7 @@ export function createCiSignIn(options: {
193
226
  const rules = new RemoteTrustRepository(options.db)
194
227
  const issuers = options.issuers.filter(usableIssuer)
195
228
  const limiter = new AttemptLimiter({ max: 10, maxAll: 200, windowMs: 15 * 60_000 })
196
- const keySets = new Map<string, ReturnType<typeof createRemoteJWKSet>>()
197
-
198
- /** The issuer's signing keys, from its OIDC discovery; cached, and failing closed. */
199
- const keysOf = async (issuer: string) => {
200
- const known = keySets.get(issuer)
201
- if (known) return known
202
- const response = await fetch(`${issuer}/.well-known/openid-configuration`)
203
- if (!response.ok) throw new Error(`the issuer's discovery answered ${response.status}`)
204
- const { jwks_uri: jwksUri } = (await response.json()) as { jwks_uri?: string }
205
- if (!jwksUri || !usableIssuer(new URL(jwksUri).origin))
206
- throw new Error('the issuer names no usable key set')
207
- const set = createRemoteJWKSet(new URL(jwksUri))
208
- keySets.set(issuer, set)
209
- return set
210
- }
229
+ const keysOf = issuerKeys()
211
230
 
212
231
  const refuse = async (request: Request, refusal: Refusal, ip: string | undefined) => {
213
232
  limiter.fail(`ip:${ip ?? 'unknown'}`)
@@ -220,17 +239,6 @@ export function createCiSignIn(options: {
220
239
  )
221
240
  }
222
241
 
223
- const unverifiedIssuer = (token: string): string | undefined => {
224
- try {
225
- const body = token.split('.')[1]
226
- if (!body) return undefined
227
- const payload = JSON.parse(Buffer.from(body, 'base64url').toString('utf8')) as JWTPayload
228
- return typeof payload.iss === 'string' ? payload.iss.replace(/\/+$/, '') : undefined
229
- } catch {
230
- return undefined
231
- }
232
- }
233
-
234
242
  return {
235
243
  issuers,
236
244
 
@@ -0,0 +1,269 @@
1
+ /**
2
+ * A person signed in through a provider reaches the remote (story 364): a token
3
+ * one of the site's own back-office providers issued for the remote, exchanged
4
+ * (RFC 8693) at the same endpoint as CI's for a fifteen-minute sign-in as the
5
+ * person it names. The provider must opt in from the config or the server, the
6
+ * token's `aud` must be the audience it names and never a sign-in client id,
7
+ * and the person is found by the claim that names them across the provider's
8
+ * apps, as their last sign-in recorded it. docs/remote-protocol.md, "Signing
9
+ * in as a person through a provider".
10
+ */
11
+ import {
12
+ type Db,
13
+ ExternalLoginRepository,
14
+ externalLoginProvider,
15
+ RemoteExchangeIds,
16
+ } from '@crombolo/data'
17
+ import { type JWTPayload, jwtVerify } from 'jose'
18
+ import { type ExternalAccount, syncedGroups } from './external-sign-in.ts'
19
+ import type { IdentityProvider } from './identity-providers.ts'
20
+ import {
21
+ ACCESS_TOKEN_TYPE,
22
+ issuerKeys,
23
+ JWT_TOKEN_TYPE,
24
+ overHttps,
25
+ TOKEN_EXCHANGE_GRANT,
26
+ unverifiedIssuer,
27
+ usableIssuer,
28
+ } from './remote-ci.ts'
29
+ import { AttemptLimiter } from './setup.ts'
30
+
31
+ /** How long an exchanged sign-in lasts. There is no refresh: the holder exchanges again. */
32
+ export const PERSON_TOKEN_SECONDS = 15 * 60
33
+ /** A provider's token valid for longer than this is refused; Entra's last 60 to 90 minutes. */
34
+ export const MAX_PROVIDER_TOKEN_SECONDS = 90 * 60
35
+
36
+ const ASYMMETRIC = ['RS256', 'RS384', 'RS512', 'PS256', 'PS384', 'PS512', 'ES256', 'ES384', 'ES512']
37
+
38
+ const text = (claims: JWTPayload, name: string | undefined): string | undefined => {
39
+ const value = name ? claims[name] : undefined
40
+ return typeof value === 'string' && value !== '' ? value : undefined
41
+ }
42
+
43
+ const list = (claims: JWTPayload, name: string | undefined): string[] => {
44
+ const value = name ? claims[name] : undefined
45
+ if (Array.isArray(value)) return value.filter((v): v is string => typeof v === 'string')
46
+ return typeof value === 'string' && value !== '' ? [value] : []
47
+ }
48
+
49
+ /** The person-side of the site the exchange needs: back-office users, as sign-in finds them. */
50
+ export interface ExchangeAccounts {
51
+ byKey(key: string): Promise<ExternalAccount | undefined>
52
+ byEmail(email: string): Promise<ExternalAccount | undefined>
53
+ setGroups(account: ExternalAccount, groups: string[]): Promise<void>
54
+ /** Why the person may not sign in now: locked out, disabled, or with no back-office section. */
55
+ refusal(key: string): Promise<string | undefined>
56
+ /** Signs them in as a device of their own, or says why not. */
57
+ signIn(
58
+ key: string,
59
+ provider: { id: string; name: string },
60
+ seconds: number,
61
+ ip: string | undefined,
62
+ ): Promise<{ accessToken: string } | { refused: string }>
63
+ }
64
+
65
+ export type PeopleExchangeOutcome =
66
+ | { ok: true; provider: IdentityProvider; account: ExternalAccount }
67
+ | { ok: false; reason: string; provider?: IdentityProvider }
68
+
69
+ export interface PeopleExchange {
70
+ /** What the discovery document says, when any provider exchanges. */
71
+ discovery(origin: string, api: string): Promise<Record<string, unknown> | undefined>
72
+ /** Whether a token's issuer is an exchanging provider's, so this exchange answers it. */
73
+ handles(issuer: string): Promise<boolean>
74
+ exchange(request: Request, url: URL, ip: string | undefined): Promise<Response>
75
+ }
76
+
77
+ export function createPeopleExchange(options: {
78
+ db: Db
79
+ /** The providers that exchange, as declared. */
80
+ providers: readonly IdentityProvider[]
81
+ /** Every back-office provider, as declared: none of their client ids is ever an audience. */
82
+ backoffice: readonly IdentityProvider[]
83
+ /** A provider as sign-in uses it, with an administrator's overrides (033). */
84
+ resolve(provider: IdentityProvider): Promise<IdentityProvider>
85
+ accounts: ExchangeAccounts
86
+ /** Told of each exchange, accepted or refused, for the audit log. */
87
+ onExchange(outcome: PeopleExchangeOutcome, request: Request): Promise<void>
88
+ }): PeopleExchange {
89
+ const logins = new ExternalLoginRepository(options.db)
90
+ const ids = new RemoteExchangeIds(options.db)
91
+ const keysOf = issuerKeys()
92
+ const limiter = new AttemptLimiter({ max: 10, maxAll: 200, windowMs: 15 * 60_000 })
93
+
94
+ const effective = () =>
95
+ Promise.all(
96
+ options.providers.map(async (declared) => {
97
+ const provider = await options.resolve(declared).catch(() => declared)
98
+ return { ...provider, remoteExchange: declared.remoteExchange }
99
+ }),
100
+ )
101
+ const issuerOf = (provider: IdentityProvider) => provider.oidc.issuer.replace(/\/+$/, '')
102
+ const audienceOf = (provider: IdentityProvider, origin: string) =>
103
+ provider.remoteExchange?.audience ?? origin
104
+ const usable = (provider: IdentityProvider) =>
105
+ !provider.unavailable && usableIssuer(issuerOf(provider))
106
+
107
+ const json = (body: unknown, status: number) =>
108
+ Response.json(body, { status, headers: { 'cache-control': 'no-store' } })
109
+
110
+ const refuse = async (
111
+ request: Request,
112
+ ip: string | undefined,
113
+ reason: string,
114
+ provider?: IdentityProvider,
115
+ ) => {
116
+ limiter.fail(`ip:${ip ?? 'unknown'}`)
117
+ if (provider) limiter.fail(`issuer:${issuerOf(provider)}`)
118
+ await options.onExchange({ ok: false, reason, provider }, request)
119
+ // The same answer whatever went wrong: the audit log has the reason, the caller does not.
120
+ return json(
121
+ { error: 'invalid_grant', error_description: 'The identity token was not accepted.' },
122
+ 400,
123
+ )
124
+ }
125
+
126
+ /** The account the token names: by its recorded identity, else by email where allowed. */
127
+ const accountFor = async (
128
+ provider: IdentityProvider,
129
+ issuer: string,
130
+ claims: JWTPayload,
131
+ ): Promise<ExternalAccount | string> => {
132
+ const loginProvider = externalLoginProvider('user', provider.oidc.id)
133
+ const value = text(claims, provider.oidc.claims.identity ?? 'sub')
134
+ if (!value) return 'the token names no person'
135
+ const linked = await logins.findByIdentity(loginProvider, { value, issuer })
136
+ if (linked) {
137
+ const account = await options.accounts.byKey(linked.ownerKey)
138
+ return account ?? 'the person it is linked to no longer exists'
139
+ }
140
+ // Story 364, D5: never an account made, and a link is only ever made by a sign-in.
141
+ const email = text(claims, provider.oidc.claims.email)?.toLowerCase()
142
+ const verified = claims.email_verified === true || claims.email_verified === 'true'
143
+ if (!provider.linkByEmail || !email || !(verified || provider.emailsVerified))
144
+ return 'nobody is linked to this person; they sign in to the back office once first'
145
+ const sameEmail = await options.accounts.byEmail(email)
146
+ if (!sameEmail) return 'nobody here has their email address, and an exchange makes no account'
147
+ const links = await logins.forOwner(sameEmail.key)
148
+ if (links.some((l) => l.loginProvider === loginProvider))
149
+ return 'the account with their email is linked to someone else at this provider'
150
+ return sameEmail
151
+ }
152
+
153
+ return {
154
+ async discovery(origin, api) {
155
+ const providers = (await effective()).filter(usable)
156
+ if (providers.length === 0) return undefined
157
+ return {
158
+ tokenExchange: `${api}/token`,
159
+ grantType: TOKEN_EXCHANGE_GRANT,
160
+ subjectTokenType: JWT_TOKEN_TYPE,
161
+ audience: origin,
162
+ providers: providers.map((p) => ({
163
+ id: p.oidc.id,
164
+ name: p.oidc.name,
165
+ issuer: issuerOf(p),
166
+ audience: audienceOf(p, origin),
167
+ })),
168
+ }
169
+ },
170
+
171
+ async handles(issuer) {
172
+ return (await effective()).some((p) => usable(p) && issuerOf(p) === issuer)
173
+ },
174
+
175
+ async exchange(request, url, ip) {
176
+ if (!overHttps(request, url))
177
+ return json(
178
+ { error: 'invalid_request', error_description: 'Signing in from elsewhere needs HTTPS.' },
179
+ 400,
180
+ )
181
+ if (limiter.blocked(`ip:${ip ?? 'unknown'}`))
182
+ return json({ error: 'slow_down', error_description: 'Too many refused tokens.' }, 429)
183
+ const form = new URLSearchParams(await request.text())
184
+ if (form.get('grant_type') !== TOKEN_EXCHANGE_GRANT)
185
+ return json({ error: 'unsupported_grant_type' }, 400)
186
+ if (form.get('subject_token_type') !== JWT_TOKEN_TYPE)
187
+ return json({ error: 'invalid_request', error_description: 'A JWT is expected.' }, 400)
188
+ const token = form.get('subject_token') ?? ''
189
+
190
+ const issuer = unverifiedIssuer(token)
191
+ const provider = (await effective()).find((p) => usable(p) && issuerOf(p) === issuer)
192
+ if (!issuer || !provider)
193
+ return refuse(request, ip, 'an issuer that is not an exchanging provider')
194
+ if (limiter.blocked(`issuer:${issuer}`))
195
+ return json({ error: 'slow_down', error_description: 'Too many refused tokens.' }, 429)
196
+
197
+ const audience = audienceOf(provider, url.origin)
198
+ const signInClients = await Promise.all(
199
+ options.backoffice.map(
200
+ async (p) => (await options.resolve(p).catch(() => p)).oidc.clientId,
201
+ ),
202
+ )
203
+ if (signInClients.includes(audience))
204
+ return refuse(request, ip, 'its audience is a sign-in client id', provider)
205
+
206
+ let claims: JWTPayload
207
+ try {
208
+ ;({ payload: claims } = await jwtVerify(token, await keysOf(issuer), {
209
+ issuer,
210
+ audience,
211
+ algorithms: ASYMMETRIC,
212
+ requiredClaims: ['exp', 'iat'],
213
+ }))
214
+ } catch (error) {
215
+ return refuse(
216
+ request,
217
+ ip,
218
+ `the token did not verify: ${error instanceof Error ? error.message : String(error)}`,
219
+ provider,
220
+ )
221
+ }
222
+ if (claims.nonce !== undefined)
223
+ return refuse(request, ip, 'it is a sign-in ID token, which carries a nonce', provider)
224
+ const exp = claims.exp as number
225
+ if (exp - (claims.iat as number) > MAX_PROVIDER_TOKEN_SECONDS)
226
+ return refuse(request, ip, 'the token is valid for too long', provider)
227
+ // Entra calls its one-time id `uti`.
228
+ const tokenId = text(claims, 'jti') ?? text(claims, 'uti')
229
+ if (!tokenId) return refuse(request, ip, 'the token has no one-time id', provider)
230
+ if (!(await ids.spend(issuer, tokenId, new Date(exp * 1000))))
231
+ return refuse(request, ip, 'the token was already used', provider)
232
+
233
+ const found = await accountFor(provider, issuer, claims)
234
+ if (typeof found === 'string') return refuse(request, ip, found, provider)
235
+ const refusal = await options.accounts.refusal(found.key)
236
+ if (refusal) return refuse(request, ip, refusal, provider)
237
+
238
+ let account = found
239
+ if (Object.keys(provider.groupMap).length > 0) {
240
+ const groups = syncedGroups(
241
+ account.groups,
242
+ list(claims, provider.oidc.claims.groups),
243
+ provider.groupMap,
244
+ )
245
+ if (groups.join('\n') !== account.groups.join('\n')) {
246
+ await options.accounts.setGroups(account, groups)
247
+ account = { ...account, groups }
248
+ }
249
+ }
250
+ const signedIn = await options.accounts.signIn(
251
+ account.key,
252
+ { id: provider.oidc.id, name: provider.oidc.name },
253
+ PERSON_TOKEN_SECONDS,
254
+ ip,
255
+ )
256
+ if ('refused' in signedIn) return refuse(request, ip, signedIn.refused, provider)
257
+ await options.onExchange({ ok: true, provider, account }, request)
258
+ return json(
259
+ {
260
+ access_token: signedIn.accessToken,
261
+ issued_token_type: ACCESS_TOKEN_TYPE,
262
+ token_type: 'Bearer',
263
+ expires_in: PERSON_TOKEN_SECONDS,
264
+ },
265
+ 200,
266
+ )
267
+ },
268
+ }
269
+ }
package/src/remote.ts CHANGED
@@ -71,10 +71,11 @@ import { type MediaStore, streamOf } from './media-store.ts'
71
71
  import { siteMemberPorts } from './member-admin.ts'
72
72
  import { describeProvenance, provenanceProblem, verifyProvenance } from './provenance.ts'
73
73
  import { createBackgroundJobRoutes } from './remote-background-jobs.ts'
74
- import { createCiSignIn, readRuleInput, trustedIssuers } from './remote-ci.ts'
74
+ import { createCiSignIn, readRuleInput, trustedIssuers, unverifiedIssuer } from './remote-ci.ts'
75
75
  import { createExtensionActivityRoutes } from './remote-extension-activity.ts'
76
76
  import { createMediaLibraryRoutes } from './remote-media-library.ts'
77
77
  import { createMemberRoutes } from './remote-members.ts'
78
+ import type { PeopleExchange } from './remote-people.ts'
78
79
  import { createUndoRoutes } from './remote-undo.ts'
79
80
  import { createUserRoutes } from './remote-users.ts'
80
81
  import { openSecret, sealSecret, usableSecretKey } from './secrets.ts'
@@ -102,6 +103,8 @@ export interface RemoteOptions {
102
103
  db: Db
103
104
  config: CromboloConfig
104
105
  authenticate(request: Request): Promise<Principal | undefined>
106
+ /** Story 364: a back-office provider's token exchanged for a sign-in as the person it names. */
107
+ people?: PeopleExchange
105
108
  /**
106
109
  * Told once a push has landed, so this node's published cache is rebuilt: the
107
110
  * import's cache instruction carries this node's id, and a node skips its own.
@@ -223,7 +226,7 @@ export function createRemote(options: RemoteOptions): Remote {
223
226
  // Under the back office, as the editor's own API calls are; a command line
224
227
  // follows these addresses rather than building its own.
225
228
  const managementApi = managementApiPath(config.backOfficePath.replace(/\/+$/, ''))
226
- const discovery = (origin: string) => ({
229
+ const discovery = async (origin: string) => ({
227
230
  protocol: 'crombolo-remote',
228
231
  versions: [REMOTE_PROTOCOL_VERSION],
229
232
  // The bundle formats this site reads, oldest and newest (story 306).
@@ -237,6 +240,11 @@ export function createRemote(options: RemoteOptions): Remote {
237
240
  grantType: DEVICE_CODE_GRANT,
238
241
  // Story 160: a CI job's identity token, exchanged for a token acting as a trust rule.
239
242
  ci: ci.discovery(origin, `${origin}${REMOTE_API_PATH}`),
243
+ // Story 364: a person's token from one of this site's own back-office providers.
244
+ ...(await (async () => {
245
+ const people = await options.people?.discovery(origin, `${origin}${REMOTE_API_PATH}`)
246
+ return people ? { people } : {}
247
+ })()),
240
248
  },
241
249
  capabilities: [
242
250
  ...(atLeast('content') ? ['bundle-apply'] : []),
@@ -1297,6 +1305,12 @@ export function createRemote(options: RemoteOptions): Remote {
1297
1305
  title: 'A command-line token cannot approve pushes',
1298
1306
  detail: 'Approve or decline it signed in as yourself.',
1299
1307
  })
1308
+ if (principal.viaExchange)
1309
+ return problem(403, {
1310
+ code: 'exchange-cannot-approve',
1311
+ title: 'A sign-in through another service cannot approve pushes',
1312
+ detail: 'Approve or decline it signed in as yourself.',
1313
+ })
1300
1314
  const job = await jobs.get(id)
1301
1315
  if (job?.kind !== 'push')
1302
1316
  return problem(404, { code: 'not-found', title: 'There is no such push' })
@@ -1513,16 +1527,28 @@ export function createRemote(options: RemoteOptions): Remote {
1513
1527
  if (pathname === REMOTE_DISCOVERY_PATH) {
1514
1528
  if (!settings.enabled) return undefined
1515
1529
  return request.method === 'GET'
1516
- ? Response.json(discovery(url.origin), { headers: { 'cache-control': 'no-store' } })
1530
+ ? Response.json(await discovery(url.origin), {
1531
+ headers: { 'cache-control': 'no-store' },
1532
+ })
1517
1533
  : new Response(null, { status: 405 })
1518
1534
  }
1519
1535
  if (!pathname.startsWith(`${REMOTE_API_PATH}/`)) return undefined
1520
1536
  if (!settings.enabled)
1521
1537
  return problem(404, { code: 'not-enabled', title: 'This site is not a remote' })
1522
- if (pathname === `${REMOTE_API_PATH}/token`)
1523
- return request.method === 'POST'
1524
- ? ci.exchange(request, url, request.headers.get('x-forwarded-for')?.split(',')[0]?.trim())
1525
- : new Response(null, { status: 405 })
1538
+ if (pathname === `${REMOTE_API_PATH}/token`) {
1539
+ if (request.method !== 'POST') return new Response(null, { status: 405 })
1540
+ const ip = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim()
1541
+ // One endpoint for both: the token's issuer says whether it is CI's or a person's.
1542
+ const people = options.people
1543
+ const issuer = people
1544
+ ? unverifiedIssuer(
1545
+ new URLSearchParams(await request.clone().text()).get('subject_token') ?? '',
1546
+ )
1547
+ : undefined
1548
+ return people && issuer && (await people.handles(issuer))
1549
+ ? people.exchange(request, url, ip)
1550
+ : ci.exchange(request, url, ip)
1551
+ }
1526
1552
  // A CI token is good here and nowhere else; a person's is the back office's own.
1527
1553
  const principal = (await ci.principalOf(request)) ?? (await options.authenticate(request))
1528
1554
  if (!principal)
package/src/server.ts CHANGED
@@ -108,6 +108,7 @@ import {
108
108
  readUrlOptions,
109
109
  searchProvidersOf,
110
110
  TransferRunRepository,
111
+ UserRepository,
111
112
  type WritesPaused,
112
113
  withAuditContext,
113
114
  } from '@crombolo/data'
@@ -247,6 +248,7 @@ import {
247
248
  import { principalOf } from './principal.ts'
248
249
  import { provenanceProblem } from './provenance.ts'
249
250
  import { createRemote, may, type RestartOutcome } from './remote.ts'
251
+ import { createPeopleExchange } from './remote-people.ts'
250
252
  import { createSchemaTransfer, UPLOAD_LIMITS } from './schema-transfer.ts'
251
253
  import { SiteAssets } from './site-assets.ts'
252
254
  import { unknownHostProvided } from './site-file.ts'
@@ -279,6 +281,7 @@ import { backofficeAudience } from './backoffice-external.ts'
279
281
  import { createCliTokensApi, tokenRefusal } from './cli-tokens-api.ts'
280
282
  import { createExternalSignIn } from './external-sign-in.ts'
281
283
  import { IdentityProviderOverrides } from './identity-provider-overrides.ts'
284
+ import { exchangingProviders } from './identity-providers.ts'
282
285
  import {
283
286
  builtIslandFile,
284
287
  devServerIslandManifest,
@@ -678,6 +681,14 @@ export async function createServer(
678
681
  const principal = await principalFrom(identity)
679
682
  // Story 314: what this session writes says whose groups it was seen as.
680
683
  const context = currentAuditContext()
684
+ // Story 364: and that it came by a token exchanged through a provider.
685
+ if (context && identity.exchangedThrough)
686
+ context.exchange = {
687
+ userKey: normaliseUuid(principal.id),
688
+ provider:
689
+ config.backofficeIdentityProviders.find((p) => p.oidc.id === identity.exchangedThrough)
690
+ ?.oidc.name ?? identity.exchangedThrough,
691
+ }
681
692
  if (context && principal.viewingAs)
682
693
  context.viewing = {
683
694
  userKey: normaliseUuid(principal.id),
@@ -919,10 +930,91 @@ export async function createServer(
919
930
  source: 'request',
920
931
  ...clientAddress(request),
921
932
  })
933
+ // Story 364: a back-office provider's token exchanged at the remote for a sign-in as the person.
934
+ const exchanging = exchangingProviders(
935
+ config.backofficeIdentityProviders,
936
+ config.remoteExchangeProviders,
937
+ )
938
+ for (const id of config.remoteExchangeProviders)
939
+ if (!config.backofficeIdentityProviders.some((p) => p.oidc.id === id))
940
+ log.warning(
941
+ 'CROMBOLO_REMOTE_EXCHANGE_PROVIDERS names {id}, which the config declares no back-office identity provider as.',
942
+ { id },
943
+ )
944
+ if (exchanging.length > 0)
945
+ log.info('The remote exchanges tokens from {providers}', {
946
+ providers: exchanging.map((p) => p.oidc.id).join(', '),
947
+ })
948
+ const people =
949
+ exchanging.length === 0
950
+ ? undefined
951
+ : (() => {
952
+ const users = new UserRepository(db)
953
+ const accounts = backofficeAudience(db, {
954
+ auth,
955
+ providers: exchanging,
956
+ backOfficePath: paths.backOfficePath,
957
+ sessionCookie: () => '',
958
+ })
959
+ const overrides = new IdentityProviderOverrides(
960
+ db,
961
+ config.secretKey,
962
+ config.lockedIdentityProviders,
963
+ )
964
+ return createPeopleExchange({
965
+ db,
966
+ providers: exchanging,
967
+ backoffice: config.backofficeIdentityProviders,
968
+ resolve: (provider) => overrides.apply('user', provider),
969
+ accounts: {
970
+ byKey: accounts.byKey,
971
+ byEmail: accounts.byEmail,
972
+ setGroups: accounts.setGroups,
973
+ refusal: async (key) => {
974
+ const user = await users.byKey(key)
975
+ if (!user) return 'the person no longer exists'
976
+ if (user.isLockedOut) return 'the person is locked out'
977
+ if (!user.isApproved) return 'the person is disabled or not yet approved'
978
+ const identity = await auth.identityOf(user.id)
979
+ return (identity?.allowedSections.length ?? 0) > 0
980
+ ? undefined
981
+ : 'the person has no access to the back office'
982
+ },
983
+ signIn: async (key, provider, seconds, ip) => {
984
+ const user = await users.byKey(key)
985
+ if (!user) return { refused: 'the person no longer exists' }
986
+ const result = await auth.signInByExchange(user.userName, provider, seconds, ip)
987
+ if (result.status === 'success') return { accessToken: result.accessToken }
988
+ return {
989
+ refused:
990
+ result.reason === 'lockedOut'
991
+ ? 'the person is locked out'
992
+ : 'the person is disabled or not yet approved',
993
+ }
994
+ },
995
+ },
996
+ onExchange: (outcome, request) =>
997
+ recordAudit(db, {
998
+ category: 'sign-in',
999
+ action: outcome.ok ? 'RemoteExchangeSignIn' : 'RemoteExchangeSignInRefused',
1000
+ source: 'request',
1001
+ userKey: outcome.ok ? outcome.account.key : null,
1002
+ userName: null,
1003
+ entityType: 'User',
1004
+ entityKey: outcome.ok ? outcome.account.key : null,
1005
+ entityName: outcome.ok ? outcome.account.email : null,
1006
+ detail: outcome.ok
1007
+ ? `Signed in through ${outcome.provider.oidc.name}, by exchange at the remote`
1008
+ : `Refused${outcome.provider ? ` through ${outcome.provider.oidc.name}` : ''}: ${outcome.reason}`,
1009
+ ...clientAddress(request),
1010
+ }),
1011
+ })
1012
+ })()
922
1013
  const remote = createRemote({
923
1014
  db,
924
1015
  config,
925
1016
  authenticate,
1017
+ people,
926
1018
  bundles: bundleAdmin,
927
1019
  operations: core.operations,
928
1020
  nodeState: schema.nodeState,
@@ -2628,6 +2720,8 @@ export async function createServer(
2628
2720
  if (pathname === viewAsPath) {
2629
2721
  const identity = await identify(request)
2630
2722
  if (!identity) return new Response('Unauthorized', { status: 401 })
2723
+ // Story 364: a token exchanged through a provider never sees as anyone else.
2724
+ if (identity.exchangedThrough) return new Response('Forbidden', { status: 403 })
2631
2725
  return viewAs.handle(request, identity, clientAddress(request))
2632
2726
  }
2633
2727
 
package/src/settings.ts CHANGED
@@ -284,6 +284,13 @@ const DECLARED = [
284
284
  description:
285
285
  "Identity providers nobody can change in the back office, by id, separated by commas, or `all`: they sign in by the site's configuration alone. A provider declared `locked: true` is locked too.",
286
286
  },
287
+ {
288
+ env: 'CROMBOLO_REMOTE_EXCHANGE_PROVIDERS',
289
+ kind: 'list',
290
+ section: 'Sign-in and secrets',
291
+ description:
292
+ "Back-office identity providers, by id, separated by commas, whose tokens the remote exchanges for a sign-in as the person they name, besides those the site's configuration opts in.",
293
+ },
287
294
  {
288
295
  env: 'CROMBOLO_SECRET_KEY',
289
296
  kind: 'string',