@crombolo/server 0.43.1 → 0.44.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.43.1",
3
+ "version": "0.44.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",
@@ -31,18 +31,18 @@
31
31
  "access": "public"
32
32
  },
33
33
  "dependencies": {
34
- "@crombolo/api-delivery": "0.43.1",
35
- "@crombolo/api-management": "0.43.1",
36
- "@crombolo/auth": "0.43.1",
37
- "@crombolo/backoffice-host": "0.43.1",
38
- "@crombolo/common": "0.43.1",
39
- "@crombolo/content": "0.43.1",
40
- "@crombolo/contracts": "0.43.1",
41
- "@crombolo/core": "0.43.1",
42
- "@crombolo/data": "0.43.1",
43
- "@crombolo/render": "0.43.1",
44
- "@crombolo/schema": "0.43.1",
45
- "@crombolo/transfer": "0.43.1",
34
+ "@crombolo/api-delivery": "0.44.0",
35
+ "@crombolo/api-management": "0.44.0",
36
+ "@crombolo/auth": "0.44.0",
37
+ "@crombolo/backoffice-host": "0.44.0",
38
+ "@crombolo/common": "0.44.0",
39
+ "@crombolo/content": "0.44.0",
40
+ "@crombolo/contracts": "0.44.0",
41
+ "@crombolo/core": "0.44.0",
42
+ "@crombolo/data": "0.44.0",
43
+ "@crombolo/render": "0.44.0",
44
+ "@crombolo/schema": "0.44.0",
45
+ "@crombolo/transfer": "0.44.0",
46
46
  "@logtape/logtape": "^2.3.8",
47
47
  "jose": "^6.2.12"
48
48
  }
package/src/config.ts CHANGED
@@ -46,8 +46,20 @@ export type UserLinkSender = (message: {
46
46
  message: string | null
47
47
  }) => Promise<void>
48
48
 
49
+ /**
50
+ * How much a site takes from the remote protocol (story 167), each level the
51
+ * ones before it and more: `read` pulls, `content` applies bundles of content,
52
+ * `all` takes whole-site pushes and bundles that change structure and code.
53
+ */
54
+ export type RemoteAccess = 'off' | 'read' | 'content' | 'all'
55
+
56
+ export const REMOTE_ACCESS_LEVELS: readonly RemoteAccess[] = ['off', 'read', 'content', 'all']
57
+
49
58
  export interface RemoteSettings {
59
+ /** Whether the site answers the protocol at all: its access is not `off`. */
50
60
  enabled: boolean
61
+ /** `CROMBOLO_REMOTE_ACCESS`; `all` when only `enabled` is given, as a test does. */
62
+ access?: RemoteAccess
51
63
  /** The environment this server is, as the remote protocol names it. */
52
64
  environment: string
53
65
  /** A push here replaces something people rely on: it needs its own permission. */
@@ -60,6 +72,24 @@ export interface RemoteSettings {
60
72
  * the server's.
61
73
  */
62
74
  maxUploadBytes: number
75
+ /**
76
+ * Issuers of CI identity tokens trusted beside GitHub's and gitlab.com's (story
77
+ * 160): a self-managed GitLab, as `CROMBOLO_REMOTE_OIDC_ISSUERS`, comma separated.
78
+ */
79
+ oidcIssuers?: string[]
80
+ }
81
+
82
+ /** `CROMBOLO_REMOTE_ACCESS`, refusing the switch it replaced so a site does not quietly stop being a remote. */
83
+ function remoteAccessSetting(): RemoteAccess {
84
+ // Read directly: it is no longer a setting, only a name to refuse.
85
+ if (Bun.env.CROMBOLO_REMOTE_ENABLED !== undefined)
86
+ throw new Error(
87
+ 'CROMBOLO_REMOTE_ENABLED has gone: set CROMBOLO_REMOTE_ACCESS to read, content or all instead (story 167).',
88
+ )
89
+ const value = (setting('CROMBOLO_REMOTE_ACCESS') ?? 'off').trim().toLowerCase()
90
+ if (!REMOTE_ACCESS_LEVELS.includes(value as RemoteAccess))
91
+ throw new Error(`CROMBOLO_REMOTE_ACCESS is "${value}": it is off, read, content or all.`)
92
+ return value as RemoteAccess
63
93
  }
64
94
 
65
95
  /** The prefix every API client id carries, as the Management API requires. */
@@ -800,11 +830,16 @@ export function loadConfig(
800
830
  memberIdentityProviders: [],
801
831
  backofficeIdentityProviders: [],
802
832
  remote: {
803
- enabled: setting('CROMBOLO_REMOTE_ENABLED') === 'true',
833
+ enabled: remoteAccessSetting() !== 'off',
834
+ access: remoteAccessSetting(),
804
835
  environment: setting('CROMBOLO_REMOTE_ENVIRONMENT') || 'production',
805
836
  protected: setting('CROMBOLO_REMOTE_PROTECTED') !== 'false',
806
837
  approvals: setting('CROMBOLO_REMOTE_APPROVALS') === 'true',
807
838
  maxUploadBytes: Number(setting('CROMBOLO_REMOTE_MAX_UPLOAD_GB') ?? 50) * 1024 ** 3,
839
+ oidcIssuers: (setting('CROMBOLO_REMOTE_OIDC_ISSUERS') ?? '')
840
+ .split(',')
841
+ .map((issuer) => issuer.trim())
842
+ .filter(Boolean),
808
843
  },
809
844
  redirects: [],
810
845
  trackRedirects: setting('CROMBOLO_TRACK_REDIRECTS') !== 'false',
@@ -866,6 +901,11 @@ export function loadConfig(
866
901
  // Field by field, so a site setting its title suffix keeps the environment's switches.
867
902
  merged.seo = { ...fromEnv.seo, ...stripUndefined(overrides.seo ?? {}) }
868
903
  merged.remote = { ...fromEnv.remote, ...stripUndefined(overrides.remote ?? {}) }
904
+ // An override that says only `enabled` means everything, as before story 167.
905
+ if (overrides.remote?.enabled !== undefined && overrides.remote.access === undefined)
906
+ merged.remote.access = overrides.remote.enabled ? 'all' : 'off'
907
+ merged.remote.access ??= merged.remote.enabled ? 'all' : 'off'
908
+ merged.remote.enabled = merged.remote.access !== 'off'
869
909
  merged.errors = {
870
910
  showDetails:
871
911
  overrides.errors?.showDetails ??
@@ -982,7 +1022,7 @@ export function describeDatabase(
982
1022
  }
983
1023
  }
984
1024
 
985
- export const VERSION = '0.43.1'
1025
+ export const VERSION = '0.44.0'
986
1026
 
987
1027
  /** A whole number of seconds from the environment; undefined when unset or not one. */
988
1028
  /** A positive number from a setting, else the default. */
package/src/core.ts CHANGED
@@ -230,7 +230,11 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
230
230
  createMediaSource(db, { nodeState: schema.nodeState, nodeId: schema.nodeId }),
231
231
  { budgetBytes: (config.mediaCacheMegabytes ?? DEFAULT_MEDIA_CACHE_MEGABYTES) * 1024 * 1024 },
232
232
  )
233
- const cacheOptions = { form: (key: string) => forms.byKey(key), media: mediaCache }
233
+ const cacheOptions = {
234
+ form: (key: string) => forms.byKey(key),
235
+ forms: () => forms.all(),
236
+ media: mediaCache,
237
+ }
234
238
  if (config.errors.showDetails) enableComponentStack()
235
239
  const cache = new PublishedCache(publishedSource, {
236
240
  ...cacheOptions,
@@ -21,6 +21,7 @@ import {
21
21
  BUILT_IN_FORM_TYPES,
22
22
  DEFAULT_UPLOAD_SETTINGS,
23
23
  FORM_HONEYPOT_FIELD,
24
+ FORM_LIBRARY_FIELD,
24
25
  FORM_PAGE_FIELD,
25
26
  FORM_RENDERED_FIELD,
26
27
  FORM_RESERVED_FIELDS,
@@ -28,6 +29,7 @@ import {
28
29
  type FormFieldError,
29
30
  type FormSubmissionState,
30
31
  type FormTypes,
32
+ formTokenSubject,
31
33
  isUploadAllowed,
32
34
  type SchemaForm,
33
35
  type SubmittedValues,
@@ -215,6 +217,7 @@ export function readFlash(
215
217
  if (!parsed) return undefined
216
218
  return {
217
219
  formKey: parsed.formKey,
220
+ ...(parsed.libraryKey ? { libraryKey: parsed.libraryKey } : {}),
218
221
  formAlias: parsed.formAlias,
219
222
  values: parsed.values ?? {},
220
223
  errors: parsed.errors ?? [],
@@ -238,6 +241,8 @@ export interface FormSubmitDeps {
238
241
  urlOf?: (key: string) => Promise<string | undefined>
239
242
  /** Fills in the options of choices drawn from a source, as the page rendered them. */
240
243
  resolveForm?: (form: SchemaForm) => Promise<SchemaForm>
244
+ /** A published Library form's form, with its words (story 239). */
245
+ libraryForm?: (key: string) => Promise<SchemaForm | undefined>
241
246
  }
242
247
 
243
248
  export type FormSubmitOutcome =
@@ -289,9 +294,8 @@ export async function submitForm(
289
294
  formKey: string,
290
295
  options: { ip?: string; now?: number } = {},
291
296
  ): Promise<FormSubmitOutcome> {
292
- const definition = deps.forms.byKey(formKey)
293
- if (!definition) return { status: 'notFound' }
294
- const form = deps.resolveForm ? await deps.resolveForm(definition) : definition
297
+ const file = deps.forms.byKey(formKey)
298
+ if (!file) return { status: 'notFound' }
295
299
 
296
300
  const secret = await formSigningSecret(deps.db)
297
301
  const data = await request.formData()
@@ -299,9 +303,23 @@ export async function submitForm(
299
303
 
300
304
  const renderedAt = Number(data.get(FORM_RENDERED_FIELD) ?? 0)
301
305
  const token = String(data.get(FORM_TOKEN_FIELD) ?? '')
306
+ const libraryKey = String(data.get(FORM_LIBRARY_FIELD) ?? '').trim() || undefined
302
307
  // Always required: the renderer puts a token in every form it draws, so a
303
308
  // submission without a good one did not come from a page this site rendered.
304
- if (!verifyFormToken(secret, formKey, renderedAt, token)) return { status: 'badToken' }
309
+ // It covers the Library form too, so its words cannot be swapped for another's.
310
+ const subject = formTokenSubject(formKey, libraryKey)
311
+ if (!verifyFormToken(secret, subject, renderedAt, token)) return { status: 'badToken' }
312
+
313
+ // Shown through a Library form: its words, which must still be published
314
+ // and still be made from this form.
315
+ let definition = file
316
+ if (libraryKey) {
317
+ const library = await deps.libraryForm?.(libraryKey)
318
+ if (!library || (library.key ?? library.alias) !== (file.key ?? file.alias))
319
+ return { status: 'notFound' }
320
+ definition = library
321
+ }
322
+ const form = deps.resolveForm ? await deps.resolveForm(definition) : definition
305
323
 
306
324
  // A stepped form moving forward: this page's answers checked, and nothing else.
307
325
  const checking = data.get(FORM_PAGE_FIELD)
@@ -365,7 +383,13 @@ export async function submitForm(
365
383
  return {
366
384
  status: 'invalid',
367
385
  form,
368
- state: { formKey: key, formAlias: form.alias, values: submitted, errors: result.errors },
386
+ state: {
387
+ formKey: key,
388
+ ...(libraryKey ? { libraryKey } : {}),
389
+ formAlias: form.alias,
390
+ values: submitted,
391
+ errors: result.errors,
392
+ },
369
393
  }
370
394
 
371
395
  let entryId: string | undefined
@@ -375,6 +399,7 @@ export async function submitForm(
375
399
  formAlias: form.alias,
376
400
  culture: null,
377
401
  pageKey: null,
402
+ libraryKey: libraryKey ?? null,
378
403
  ipHash: hashIp(secret, options.ip),
379
404
  userAgent: request.headers.get('user-agent')?.slice(0, 500) ?? null,
380
405
  spam,
@@ -401,6 +426,7 @@ export async function submitForm(
401
426
  runOn: workflow.on,
402
427
  entryId: entryId ?? null,
403
428
  payload: result.values,
429
+ ...(form.library?.recipients ? { recipients: form.library.recipients } : {}),
404
430
  })),
405
431
  )
406
432
 
@@ -419,6 +445,7 @@ export async function submitForm(
419
445
  redirectTo,
420
446
  state: {
421
447
  formKey: key,
448
+ ...(libraryKey ? { libraryKey } : {}),
422
449
  formAlias: form.alias,
423
450
  values: {},
424
451
  errors: [],
@@ -45,6 +45,8 @@ export interface WorkflowContext {
45
45
  form: SchemaForm
46
46
  values: readonly FormValueToStore[]
47
47
  entryId: string | null
48
+ /** In place of a send-e-mail workflow's `to`: a Library form's recipients (story 239). */
49
+ recipients?: readonly string[]
48
50
  /** Which attempt this is, from 1. */
49
51
  attempt?: number
50
52
  /** When the run was queued; now when absent. */
@@ -232,7 +234,10 @@ async function sendEmail(
232
234
  // asks for them: an inbox is not covered by the sensitive-data permission.
233
235
  const leftOut = leftOutFields(context.form, workflow)
234
236
  const values = withoutLeftOut(context.values, leftOut)
235
- const to = asList(substitute(asString(settings.to) ?? '', values))
237
+ const to =
238
+ context.recipients && context.recipients.length > 0
239
+ ? [...context.recipients]
240
+ : asList(substitute(asString(settings.to) ?? '', values))
236
241
  if (to.length === 0) return { ok: false, retry: false, error: 'The workflow has no recipient.' }
237
242
  const subject = substitute(asString(settings.subject) ?? context.form.name, values).trim()
238
243
 
@@ -589,6 +594,7 @@ export function createWorkflowRunner(
589
594
  form,
590
595
  values: run.payload,
591
596
  entryId: run.entryId,
597
+ ...(run.recipients ? { recipients: run.recipients } : {}),
592
598
  attempt: run.attempts,
593
599
  submittedAt: run.createDate,
594
600
  }
package/src/index.ts CHANGED
@@ -90,6 +90,7 @@ export * from './ports.ts'
90
90
  export * from './rate-limit.ts'
91
91
  export * from './redirects.ts'
92
92
  export * from './remote.ts'
93
+ export * from './remote-ci.ts'
93
94
  export * from './remote-credentials.ts'
94
95
  export * from './remote-media.ts'
95
96
  export * from './routes.ts'
package/src/no-nodes.ts CHANGED
@@ -169,7 +169,7 @@ export default function Article({ model }: PageProps) {
169
169
  <table>
170
170
  <tr><td><code>schema/</code></td><td>content types, data types and languages, as TOML files</td></tr>
171
171
  <tr><td><code>components/</code></td><td>templates and the components they share, as <code>.tsx</code></td></tr>
172
- <tr><td><code>seed/</code></td><td>starting pages and media, as files</td></tr>
172
+ <tr><td><code>content/</code></td><td>starting pages and media, as files</td></tr>
173
173
  <tr><td><code>crombolo.config.ts</code></td><td>the site's settings: its name, its database, its addresses</td></tr>
174
174
  </table>
175
175
  </section>
@@ -0,0 +1,334 @@
1
+ /**
2
+ * Signing in to a remote from CI (story 160): a GitHub Actions or GitLab job's
3
+ * OIDC identity token, exchanged (RFC 8693) for a short-lived token that acts
4
+ * as the trust rule it matched. No secret is stored anywhere: the provider signs
5
+ * the identity token, and a rule an administrator made on this site says which
6
+ * repository and branch, tag or environment it must come from, and what it may
7
+ * do. docs/remote-protocol.md, "Signing in from CI".
8
+ */
9
+ import type { Principal } from '@crombolo/api-management/domain'
10
+ import { RemotePermissions } from '@crombolo/core'
11
+ import {
12
+ type CiToken,
13
+ type Db,
14
+ RemoteTrustRepository,
15
+ type TrustRefKind,
16
+ type TrustRule,
17
+ type TrustRuleInput,
18
+ } from '@crombolo/data'
19
+ import { createRemoteJWKSet, type JWTPayload, jwtVerify } from 'jose'
20
+ import { AttemptLimiter } from './setup.ts'
21
+
22
+ export const GITHUB_ISSUER = 'https://token.actions.githubusercontent.com'
23
+ export const GITLAB_ISSUER = 'https://gitlab.com'
24
+ export const TOKEN_EXCHANGE_GRANT = 'urn:ietf:params:oauth:grant-type:token-exchange'
25
+ export const JWT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:jwt'
26
+ export const ACCESS_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token'
27
+
28
+ /** How long a CI token lasts. There is no refresh: the job exchanges again. */
29
+ export const CI_TOKEN_SECONDS = 15 * 60
30
+ /** An identity token valid for longer than this is refused. */
31
+ const MAX_IDENTITY_SECONDS = 60 * 60
32
+
33
+ /** The issuers a site trusts tokens from: GitHub's, gitlab.com's, and any it names. */
34
+ export function trustedIssuers(extra: readonly string[] = []): string[] {
35
+ return [...new Set([GITHUB_ISSUER, GITLAB_ISSUER, ...extra.map((i) => i.replace(/\/+$/, ''))])]
36
+ }
37
+
38
+ const isLocal = (host: string) => host === 'localhost' || host === '127.0.0.1' || host === '[::1]'
39
+
40
+ /** An issuer is fetched over HTTPS; a local one only for a test or a developer's own GitLab. */
41
+ export function usableIssuer(issuer: string): boolean {
42
+ try {
43
+ const url = new URL(issuer)
44
+ return url.protocol === 'https:' || (url.protocol === 'http:' && isLocal(url.hostname))
45
+ } catch {
46
+ return false
47
+ }
48
+ }
49
+
50
+ /** Where a CI run was, from its identity token, in the same words for either provider. */
51
+ export interface RunClaims {
52
+ repository: string
53
+ refType: 'branch' | 'tag' | undefined
54
+ ref: string | undefined
55
+ environment: string | undefined
56
+ /** The run, for the audit log: GitHub's run id and attempt, GitLab's pipeline and job. */
57
+ run: string | undefined
58
+ }
59
+
60
+ const text = (value: unknown) => (typeof value === 'string' && value !== '' ? value : undefined)
61
+
62
+ /** A verified identity token's claims, as GitHub or GitLab put them. Pure. */
63
+ export function runClaims(issuer: string, payload: JWTPayload): RunClaims | undefined {
64
+ const refType = text(payload.ref_type)
65
+ const kind = refType === 'branch' || refType === 'tag' ? refType : undefined
66
+ if (issuer === GITHUB_ISSUER) {
67
+ const repository = text(payload.repository)
68
+ if (!repository) return undefined
69
+ const ref = text(payload.ref)
70
+ const prefix = kind === 'tag' ? 'refs/tags/' : 'refs/heads/'
71
+ const runId = text(payload.run_id)
72
+ return {
73
+ repository,
74
+ refType: kind,
75
+ ref: ref?.startsWith(prefix) ? ref.slice(prefix.length) : ref,
76
+ environment: text(payload.environment),
77
+ run: runId ? `${runId}/${text(payload.run_attempt) ?? '1'}` : undefined,
78
+ }
79
+ }
80
+ // GitLab, whether gitlab.com or a self-managed instance a site names.
81
+ const repository = text(payload.project_path)
82
+ if (!repository) return undefined
83
+ const pipeline = text(payload.pipeline_id)
84
+ const job = text(payload.job_id)
85
+ return {
86
+ repository,
87
+ refType: kind,
88
+ ref: text(payload.ref),
89
+ environment: text(payload.environment),
90
+ run: pipeline ? `${pipeline}${job ? `/${job}` : ''}` : undefined,
91
+ }
92
+ }
93
+
94
+ /** Whether a rule admits a run: its issuer, repository and ref exactly, no wildcards. Pure. */
95
+ export function ruleMatches(rule: TrustRule, issuer: string, claims: RunClaims): boolean {
96
+ if (rule.disabled || rule.issuer !== issuer) return false
97
+ // Owners and repositories are case-insensitive on both providers.
98
+ if (rule.repository.toLowerCase() !== claims.repository.toLowerCase()) return false
99
+ if (rule.refKind === 'environment') return claims.environment === rule.refValue
100
+ return claims.refType === rule.refKind && claims.ref === rule.refValue
101
+ }
102
+
103
+ /** The remote verbs a rule may hold. */
104
+ export const TRUSTABLE_PERMISSIONS: readonly string[] = Object.values(RemotePermissions)
105
+
106
+ const REF_KINDS: readonly TrustRefKind[] = ['branch', 'tag', 'environment']
107
+
108
+ /** A rule as posted, checked: undefined and the reasons when it cannot be one. Pure. */
109
+ export function readRuleInput(
110
+ body: unknown,
111
+ issuers: readonly string[],
112
+ ): { input?: TrustRuleInput; problems: string[] } {
113
+ const b = (body ?? {}) as Record<string, unknown>
114
+ const problems: string[] = []
115
+ const name = typeof b.name === 'string' ? b.name.trim() : ''
116
+ if (!name || name.length > 255) problems.push('Give it a name of up to 255 characters.')
117
+ const issuer = typeof b.issuer === 'string' ? b.issuer.trim().replace(/\/+$/, '') : ''
118
+ if (!issuers.includes(issuer))
119
+ problems.push(`The provider must be one of: ${issuers.join(', ')}.`)
120
+ const repository = typeof b.repository === 'string' ? b.repository.trim() : ''
121
+ if (!/^[\w.-]+(\/[\w.-]+)+$/.test(repository))
122
+ problems.push(
123
+ 'The repository is owner/name (GitHub) or group/project (GitLab), with no wildcards.',
124
+ )
125
+ const refKind = REF_KINDS.find((k) => k === b.refKind)
126
+ if (!refKind) problems.push('Say whether it matches a branch, a tag or an environment.')
127
+ const refValue = typeof b.refValue === 'string' ? b.refValue.trim() : ''
128
+ if (!refValue || /[*?[\]]/.test(refValue))
129
+ problems.push('Name the branch, tag or environment exactly, with no wildcards.')
130
+ const permissions = Array.isArray(b.permissions)
131
+ ? [...new Set(b.permissions.filter((p): p is string => typeof p === 'string'))]
132
+ : []
133
+ if (permissions.length === 0) problems.push('Choose what it may do.')
134
+ const unknown = permissions.filter((p) => !TRUSTABLE_PERMISSIONS.includes(p))
135
+ if (unknown.length > 0) problems.push(`Not remote permissions: ${unknown.join(', ')}.`)
136
+ if (problems.length > 0) return { problems }
137
+ return {
138
+ input: { name, issuer, repository, refKind: refKind as TrustRefKind, refValue, permissions },
139
+ problems,
140
+ }
141
+ }
142
+
143
+ /** The principal a CI token acts as: the rule, holding its remote permissions and nothing else. */
144
+ export function ciPrincipal(token: CiToken): Principal {
145
+ const none = { root: false, keys: [] }
146
+ return {
147
+ id: token.rule.key,
148
+ userName: token.rule.name,
149
+ name: `CI: ${token.rule.name}`,
150
+ email: '',
151
+ isAdmin: false,
152
+ languageIsoCode: undefined,
153
+ avatarUrls: [],
154
+ allowedSections: [],
155
+ permissions: token.rule.permissions.filter((p) => TRUSTABLE_PERMISSIONS.includes(p)),
156
+ groupKeys: [],
157
+ hasAccessToAllLanguages: false,
158
+ languages: [],
159
+ startNodes: { document: none, media: none, element: none },
160
+ groups: [],
161
+ ci: { rule: token.rule.key, claims: token.claims },
162
+ }
163
+ }
164
+
165
+ /** Whether a request came over HTTPS: directly, or through a proxy that says so. */
166
+ export function overHttps(request: Request, url: URL): boolean {
167
+ if (url.protocol === 'https:') return true
168
+ if (request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim() === 'https') return true
169
+ return isLocal(url.hostname)
170
+ }
171
+
172
+ export interface CiSignIn {
173
+ /** What the discovery document says about signing in from CI. */
174
+ discovery(origin: string, api: string): Record<string, unknown>
175
+ /** The exchange: an identity token in, a CI token out, or a refusal that says nothing more. */
176
+ exchange(request: Request, url: URL, ip: string | undefined): Promise<Response>
177
+ /** The principal a bearer token is, when it is a CI token. */
178
+ principalOf(request: Request): Promise<Principal | undefined>
179
+ readonly issuers: readonly string[]
180
+ }
181
+
182
+ type Refusal = { reason: string; issuer?: string; repository?: string }
183
+
184
+ export function createCiSignIn(options: {
185
+ db: Db
186
+ issuers: readonly string[]
187
+ /** Told of each exchange, accepted or refused, for the audit log. */
188
+ onExchange(
189
+ outcome: { ok: true; rule: TrustRule; claims: RunClaims } | ({ ok: false } & Refusal),
190
+ request: Request,
191
+ ): Promise<void>
192
+ }): CiSignIn {
193
+ const rules = new RemoteTrustRepository(options.db)
194
+ const issuers = options.issuers.filter(usableIssuer)
195
+ 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
+ }
211
+
212
+ const refuse = async (request: Request, refusal: Refusal, ip: string | undefined) => {
213
+ limiter.fail(`ip:${ip ?? 'unknown'}`)
214
+ if (refusal.issuer) limiter.fail(`issuer:${refusal.issuer}`)
215
+ await options.onExchange({ ok: false, ...refusal }, request)
216
+ // The same answer whatever went wrong: the audit log has the reason, the caller does not.
217
+ return Response.json(
218
+ { error: 'invalid_grant', error_description: 'The identity token was not accepted.' },
219
+ { status: 400, headers: { 'cache-control': 'no-store' } },
220
+ )
221
+ }
222
+
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
+ return {
235
+ issuers,
236
+
237
+ discovery(origin, api) {
238
+ return {
239
+ tokenExchange: `${api}/token`,
240
+ grantType: TOKEN_EXCHANGE_GRANT,
241
+ subjectTokenType: JWT_TOKEN_TYPE,
242
+ audience: origin,
243
+ issuers,
244
+ }
245
+ },
246
+
247
+ async exchange(request, url, ip) {
248
+ const json = (body: unknown, status: number) =>
249
+ Response.json(body, { status, headers: { 'cache-control': 'no-store' } })
250
+ if (!overHttps(request, url))
251
+ return json(
252
+ { error: 'invalid_request', error_description: 'Signing in from CI needs HTTPS.' },
253
+ 400,
254
+ )
255
+ if (limiter.blocked(`ip:${ip ?? 'unknown'}`))
256
+ return json({ error: 'slow_down', error_description: 'Too many refused tokens.' }, 429)
257
+ const form = new URLSearchParams(await request.text())
258
+ if (form.get('grant_type') !== TOKEN_EXCHANGE_GRANT)
259
+ return json({ error: 'unsupported_grant_type' }, 400)
260
+ if (form.get('subject_token_type') !== JWT_TOKEN_TYPE)
261
+ return json({ error: 'invalid_request', error_description: 'A JWT is expected.' }, 400)
262
+ const token = form.get('subject_token') ?? ''
263
+
264
+ const issuer = unverifiedIssuer(token)
265
+ if (!issuer || !issuers.includes(issuer))
266
+ return refuse(request, { reason: 'an issuer this site does not trust' }, ip)
267
+ if (limiter.blocked(`issuer:${issuer}`))
268
+ return json({ error: 'slow_down', error_description: 'Too many refused tokens.' }, 429)
269
+
270
+ let payload: JWTPayload
271
+ try {
272
+ const verified = await jwtVerify(token, await keysOf(issuer), {
273
+ issuer,
274
+ audience: url.origin,
275
+ requiredClaims: ['exp', 'iat', 'jti'],
276
+ })
277
+ payload = verified.payload
278
+ } catch (error) {
279
+ return refuse(
280
+ request,
281
+ {
282
+ reason: `the token did not verify: ${error instanceof Error ? error.message : String(error)}`,
283
+ issuer,
284
+ },
285
+ ip,
286
+ )
287
+ }
288
+ if ((payload.exp as number) - (payload.iat as number) > MAX_IDENTITY_SECONDS)
289
+ return refuse(request, { reason: 'the token is valid for too long', issuer }, ip)
290
+
291
+ const claims = runClaims(issuer, payload)
292
+ if (!claims) return refuse(request, { reason: 'the token names no repository', issuer }, ip)
293
+ const rule = (await rules.liveFor(issuer)).find((candidate) =>
294
+ ruleMatches(candidate, issuer, claims),
295
+ )
296
+ if (!rule)
297
+ return refuse(
298
+ request,
299
+ { reason: 'no trust rule matches', issuer, repository: claims.repository },
300
+ ip,
301
+ )
302
+
303
+ const recorded: Record<string, string> = { repository: claims.repository }
304
+ if (claims.refType) recorded.refType = claims.refType
305
+ if (claims.ref) recorded.ref = claims.ref
306
+ if (claims.environment) recorded.environment = claims.environment
307
+ if (claims.run) recorded.run = claims.run
308
+ const issued = await rules.issue(
309
+ rule,
310
+ { issuer, jti: payload.jti as string, claims: recorded },
311
+ CI_TOKEN_SECONDS,
312
+ )
313
+ if (!issued) return refuse(request, { reason: 'the token was already used', issuer }, ip)
314
+ await options.onExchange({ ok: true, rule, claims }, request)
315
+ return json(
316
+ {
317
+ access_token: issued.token,
318
+ issued_token_type: ACCESS_TOKEN_TYPE,
319
+ token_type: 'Bearer',
320
+ expires_in: CI_TOKEN_SECONDS,
321
+ },
322
+ 200,
323
+ )
324
+ },
325
+
326
+ async principalOf(request) {
327
+ const header = request.headers.get('authorization') ?? ''
328
+ const match = /^Bearer\s+(crci_\S+)$/i.exec(header)
329
+ if (!match) return undefined
330
+ const token = await rules.resolve(match[1] as string)
331
+ return token ? ciPrincipal(token) : undefined
332
+ },
333
+ }
334
+ }