@fabrika/iam 0.9.0-dev.33 → 0.9.0-dev.35

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/fabrika.config.ts CHANGED
@@ -6,10 +6,20 @@
6
6
  // them as plaintext. The Custom Domain route comes from `ctx.domain` (`FABRIKA_IAM_HOSTNAME` in the
7
7
  // standalone Oblaka adapter).
8
8
 
9
+ import { CONTROL_APP_ID, CONTROL_CLI_RESOURCES } from '@fabrika/control-contract'
9
10
  import { type EmailTransportConfig, readEmailTransportConfig } from '@fabrika/email'
10
11
  import { isHttpOrigin } from '@fabrika/email/platform'
11
12
  import { builtinEmailProviders } from '@fabrika/email/providers'
12
- import { D1Database, defineApp, platformNames, type ResourceContext, Worker } from '@fabrika/provider-cloudflare'
13
+ import type { OAuthResourceDto } from '@fabrika/iam-contract'
14
+ import {
15
+ D1Database,
16
+ defineApp,
17
+ NO_IMPORTABLE_ENV_FLAG,
18
+ NO_PROCESS_ENV_FLAG,
19
+ platformNames,
20
+ type ResourceContext,
21
+ Worker,
22
+ } from '@fabrika/provider-cloudflare'
13
23
 
14
24
  // Keep the legacy Oblaka namespace so the first fabrika deploy continues the existing cf-state.
15
25
  const IAM_APP_ID = 'propustka'
@@ -98,6 +108,26 @@ const controlUrl = (source: EnvironmentSource): string | undefined => {
98
108
  return raw
99
109
  }
100
110
 
111
+ /**
112
+ * IAM's `OAUTH_CONFIG` on a Cloudflare installation: the command-line client's resources on the console's origin,
113
+ * recomputed on every deploy so a release that changes the presets converges with no other step. No MCP client: a
114
+ * Worker console serves no `/mcp`. Without a console origin OAuth stays off.
115
+ */
116
+ const oauthConfig = (control: string | undefined): string => {
117
+ if (control === undefined) return ''
118
+ const resources: OAuthResourceDto[] = CONTROL_CLI_RESOURCES.map(({ path, grants }) => ({
119
+ app: CONTROL_APP_ID,
120
+ resource: `${control}${path}`,
121
+ scopeGrants: grants.map((grant) => ({
122
+ scope: grant.scope,
123
+ ...(grant.parameter === undefined ? {} : { parameter: grant.parameter }),
124
+ permissions: grant.actions.map((action) => ({ action })),
125
+ })),
126
+ client: 'cli',
127
+ }))
128
+ return JSON.stringify({ clients: [], resources })
129
+ }
130
+
101
131
  const remoteConfig = (env: string, domain: string | undefined, source: EnvironmentSource): RemoteConfig => {
102
132
  const authentication = authenticationConfig(source)
103
133
  const email = emailConfig(source)
@@ -161,7 +191,7 @@ const buildVars = (config: RemoteConfig | 'local', source: EnvironmentSource): R
161
191
 
162
192
  return {
163
193
  HUMAN_EMAIL_DOMAINS: config.humanEmailDomains,
164
- OAUTH_CONFIG: source['FABRIKA_IAM_OAUTH_CONFIG'] ?? '',
194
+ OAUTH_CONFIG: oauthConfig(config.controlUrl),
165
195
  // Only when named: an empty ADMIN_AUDIENCES means "no JWT may administer", so a `?? ''`
166
196
  // default would lock the console out of every install instead of falling back to its app id.
167
197
  ...(config.adminAudiences === undefined ? {} : { ADMIN_AUDIENCES: config.adminAudiences }),
@@ -200,7 +230,6 @@ export const iamPipelineVars = (source: EnvironmentSource): string[] => {
200
230
  const email = emailConfig(source)
201
231
  return [
202
232
  'FABRIKA_IAM_ADMIN_AUDIENCES',
203
- 'FABRIKA_IAM_OAUTH_CONFIG',
204
233
  'FABRIKA_IAM_AUTH_LOG_RETENTION_DAYS',
205
234
  'FABRIKA_IAM_AUDIT_RETENTION_DAYS',
206
235
  'FABRIKA_IAM_OIDC_SESSION_HOURS',
@@ -246,7 +275,10 @@ export const buildIamWorker = (ctx: ResourceContext, source: EnvironmentSource =
246
275
  dir: '.',
247
276
  name: names.iamWorker,
248
277
  main: './src/index.ts',
249
- compatibility_flags: ['nodejs_compat_v2'],
278
+ // `process.env` and the importable `env` of `cloudflare:workers` stay empty: otherwise each could hold every secret,
279
+ // the signing keys included, for any bundled module to read (`nodejs_compat_v2` alone already leaves `process.env`
280
+ // empty). IAM reads its configuration from the Worker's `env` only.
281
+ compatibility_flags: ['nodejs_compat_v2', NO_PROCESS_ENV_FLAG, NO_IMPORTABLE_ENV_FLAG],
250
282
  compatibility_date: '2025-10-01',
251
283
  // This is the public auth surface. Control reaches admin APIs over a service binding.
252
284
  routes: domain === undefined ? [] : [{ pattern: domain, custom_domain: true }],
@@ -0,0 +1,6 @@
1
+ -- An OAuth grant given for several resources of one app. SQLite/D1 dialect;
2
+ -- `../migrations-postgres/0033_oauth_grant_resources.sql` states the same outcome.
3
+ --
4
+ -- `resources` is a JSON array of every resource the grant covers; each token it mints names one of them. NULL keeps
5
+ -- the meaning every earlier grant has: `resource` is the only one.
6
+ ALTER TABLE oauth_grants ADD COLUMN resources TEXT;
@@ -0,0 +1,24 @@
1
+ -- RFC 8628 device authorization attempts of the OAuth server. SQLite/D1 dialect;
2
+ -- `../migrations-postgres/0034_oauth_device_authorizations.sql` states the same outcome.
3
+ --
4
+ -- Only hashes of the device code and the user code are stored. An attempt lives five minutes. A person approving it
5
+ -- binds it to their IAM session and picks the grant's end; the grant itself is written when the device redeems the
6
+ -- approval, and `grant_id` names it then, so a device code presented again revokes that grant.
7
+ CREATE TABLE oauth_device_authorizations (
8
+ device_code_hash TEXT PRIMARY KEY,
9
+ user_code_hash TEXT NOT NULL UNIQUE,
10
+ client_id TEXT NOT NULL,
11
+ app TEXT NOT NULL,
12
+ resources TEXT NOT NULL,
13
+ scopes TEXT NOT NULL,
14
+ interval_seconds INTEGER NOT NULL,
15
+ next_poll_at INTEGER NOT NULL,
16
+ created_at INTEGER NOT NULL,
17
+ expires_at INTEGER NOT NULL,
18
+ status TEXT NOT NULL CHECK (status IN ('pending', 'approved', 'denied', 'redeemed')),
19
+ principal_id TEXT REFERENCES principals(id) ON DELETE CASCADE,
20
+ session_id TEXT REFERENCES sessions(id) ON DELETE CASCADE,
21
+ grant_expires_at INTEGER,
22
+ grant_id TEXT
23
+ );
24
+ CREATE INDEX idx_oauth_device_authorizations_expires ON oauth_device_authorizations(expires_at);
@@ -0,0 +1,6 @@
1
+ -- An OAuth grant given for several resources of one app. Postgres dialect;
2
+ -- `../migrations/0033_oauth_grant_resources.sql` states the same outcome.
3
+ --
4
+ -- `resources` is a JSON array of every resource the grant covers; each token it mints names one of them. NULL keeps
5
+ -- the meaning every earlier grant has: `resource` is the only one.
6
+ ALTER TABLE oauth_grants ADD COLUMN resources TEXT;
@@ -0,0 +1,24 @@
1
+ -- RFC 8628 device authorization attempts of the OAuth server. Postgres dialect;
2
+ -- `../migrations/0034_oauth_device_authorizations.sql` states the same outcome.
3
+ --
4
+ -- Only hashes of the device code and the user code are stored. An attempt lives five minutes. A person approving it
5
+ -- binds it to their IAM session and picks the grant's end; the grant itself is written when the device redeems the
6
+ -- approval, and `grant_id` names it then, so a device code presented again revokes that grant.
7
+ CREATE TABLE oauth_device_authorizations (
8
+ device_code_hash TEXT PRIMARY KEY,
9
+ user_code_hash TEXT NOT NULL UNIQUE,
10
+ client_id TEXT NOT NULL,
11
+ app TEXT NOT NULL,
12
+ resources TEXT NOT NULL,
13
+ scopes TEXT NOT NULL,
14
+ interval_seconds INTEGER NOT NULL,
15
+ next_poll_at INTEGER NOT NULL,
16
+ created_at INTEGER NOT NULL,
17
+ expires_at INTEGER NOT NULL,
18
+ status TEXT NOT NULL CHECK (status IN ('pending', 'approved', 'denied', 'redeemed')),
19
+ principal_id TEXT REFERENCES principals(id) ON DELETE CASCADE,
20
+ session_id TEXT REFERENCES sessions(id) ON DELETE CASCADE,
21
+ grant_expires_at INTEGER,
22
+ grant_id TEXT
23
+ );
24
+ CREATE INDEX idx_oauth_device_authorizations_expires ON oauth_device_authorizations(expires_at);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/iam",
3
- "version": "0.9.0-dev.33",
3
+ "version": "0.9.0-dev.35",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/contember/fabrika-platform.git",
@@ -56,15 +56,16 @@
56
56
  "prune:auth-log": "bun src/node/prune.ts"
57
57
  },
58
58
  "dependencies": {
59
- "@fabrika/app": "0.9.0-dev.33",
60
- "@fabrika/auth": "0.9.0-dev.33",
61
- "@fabrika/auth-core": "0.9.0-dev.33",
62
- "@fabrika/email": "0.9.0-dev.33",
63
- "@fabrika/iam-contract": "0.9.0-dev.33",
64
- "@fabrika/platform": "0.9.0-dev.33",
65
- "@fabrika/platform-node": "0.9.0-dev.33",
66
- "@fabrika/provider-cloudflare": "0.9.0-dev.33",
67
- "@fabrika/proxy-core": "0.9.0-dev.33",
59
+ "@fabrika/app": "0.9.0-dev.35",
60
+ "@fabrika/auth": "0.9.0-dev.35",
61
+ "@fabrika/auth-core": "0.9.0-dev.35",
62
+ "@fabrika/control-contract": "0.9.0-dev.35",
63
+ "@fabrika/email": "0.9.0-dev.35",
64
+ "@fabrika/iam-contract": "0.9.0-dev.35",
65
+ "@fabrika/platform": "0.9.0-dev.35",
66
+ "@fabrika/platform-node": "0.9.0-dev.35",
67
+ "@fabrika/provider-cloudflare": "0.9.0-dev.35",
68
+ "@fabrika/proxy-core": "0.9.0-dev.35",
68
69
  "jose": "^5.9.0",
69
70
  "uqr": "^0.1.3",
70
71
  "zod": "^3.25.76"
package/src/app.ts CHANGED
@@ -96,7 +96,7 @@ export function createIamApp(options: IamAppOptions = {}): FetchService<Env> {
96
96
  const serve = (handle: (ctx: IamAppContext) => Response | Promise<Response>): ServiceHandler<Env> => async ({ request, env, exec }) =>
97
97
  handle(await context(request, env, exec))
98
98
  const auth = serve((ctx) => handleAuth(ctx.request, ctx.services, ctx.env, ctx.exec, ctx.clientAddress, ctx.requestId))
99
- const oauth = serve((ctx) => handleOAuth(ctx.request, ctx.services, ctx.env, ctx.requestId))
99
+ const oauth = serve((ctx) => handleOAuth(ctx.request, ctx.services, ctx.env, ctx.requestId, ctx.clientAddress))
100
100
  const admin = serve((ctx) => handleAdmin(ctx.request, ctx.services, ctx.env, ctx.exec, ctx.requestId))
101
101
  const mint = serve((ctx) => handleMintHttp(ctx.request, createIamRpc(ctx.env, ctx.exec), options.proxyKey ?? ''))
102
102
  const rpc = serve((ctx) => handleRpcHttp(ctx.request, createIamRpc(ctx.env, ctx.exec), options.rpcKey ?? ''))
package/src/env.ts CHANGED
@@ -38,8 +38,9 @@ export interface Env {
38
38
  */
39
39
  ADMIN_AUDIENCES?: string
40
40
  /**
41
- * JSON: the OAuth 2.1 authorization server for MCP clients (`src/oauth-config.ts`). Absent or empty
42
- * means OAuth is off and its routes 404. Deploy var `FABRIKA_IAM_OAUTH_CONFIG`. Malformed fails the boot.
41
+ * JSON: the OAuth 2.1 authorization server's clients and resources (`src/oauth-config.ts`). Absent or empty means
42
+ * OAuth is off and its routes 404. On Bun, `FABRIKA_IAM_OAUTH_CONFIG`; a Cloudflare deploy computes it in
43
+ * `fabrika.config.ts`. Malformed fails the boot.
43
44
  */
44
45
  OAUTH_CONFIG?: string
45
46
  /**
@@ -22,6 +22,7 @@ import { parseOAuthConfig } from '../oauth-config'
22
22
  import { parseOidcSessionSeconds } from '../oidc-session'
23
23
  import { BUN_PBKDF2_COST } from '../password-crypto'
24
24
  import { parseRetention } from '../retention'
25
+ import { parseAdminAudiences, platformAudiencesFor } from '../services'
25
26
 
26
27
  /** Config that exists ONLY off Workers — the process's own knobs, not part of the service's `Env`. */
27
28
  export interface ProcessConfig {
@@ -102,7 +103,7 @@ export async function createRuntime(source: Record<string, string | undefined> =
102
103
  const controlUrl = httpOrigin(source, 'FABRIKA_CONTROL_URL')
103
104
 
104
105
  // Parsed here as well as per request in `buildServices`, for the same readiness-probe reason as above.
105
- parseOAuthConfig(source['FABRIKA_IAM_OAUTH_CONFIG'])
106
+ parseOAuthConfig(source['FABRIKA_IAM_OAUTH_CONFIG'], platformAudiencesFor(parseAdminAudiences(source['FABRIKA_IAM_ADMIN_AUDIENCES'])))
106
107
  const authLogRetentionDays = source['FABRIKA_IAM_AUTH_LOG_RETENTION_DAYS']
107
108
  const auditRetentionDays = source['FABRIKA_IAM_AUDIT_RETENTION_DAYS']
108
109
  parseRetention(
@@ -1,3 +1,4 @@
1
+ import { OAUTH_CLI_CLIENT_ID } from '@fabrika/auth-core'
1
2
  import type { OAuthClientCredential, OAuthClientMetadataDocument } from '@fabrika/iam-contract'
2
3
  import { createLocalJWKSet, errors, type JSONWebKeySet, type JWTPayload, jwtVerify } from 'jose'
3
4
  import type { EstablishedClient } from './oauth'
@@ -24,14 +25,16 @@ export async function authenticateOAuthClient(
24
25
  config: OAuthConfig,
25
26
  input: { clientId: string; credential: OAuthClientCredential; audiences: string[] },
26
27
  ): Promise<EstablishedClient | null> {
28
+ // The CLI client is public: it holds no key, so it sends no assertion.
29
+ if (input.clientId === OAUTH_CLI_CLIENT_ID) return input.credential.method === 'none' ? { kind: 'cli', clientId: input.clientId } : null
27
30
  const registration = config.clients.find((client) => client.clientId === input.clientId)
28
31
  if (registration === undefined) return null
29
32
  const metadata = await clientMetadata(registration)
30
33
  if (metadata === null) return null
31
- if (metadata.token_endpoint_auth_method === 'none') return input.credential.method === 'none' ? { registration, metadata } : null
34
+ if (metadata.token_endpoint_auth_method === 'none') return input.credential.method === 'none' ? { kind: 'managed', registration, metadata } : null
32
35
  if (input.credential.method !== 'private_key_jwt') return null
33
36
  const accepted = await verifyClientAssertion(services, metadata, input.credential.assertion, input.audiences)
34
- return accepted ? { registration, metadata } : null
37
+ return accepted ? { kind: 'managed', registration, metadata } : null
35
38
  }
36
39
 
37
40
  /**
@@ -46,6 +49,7 @@ export async function authenticateRevokingClient(
46
49
  input: { clientId: string; credential: OAuthClientCredential; audiences: string[] },
47
50
  ): Promise<boolean> {
48
51
  if (input.credential.method !== 'none') return await authenticateOAuthClient(services, config, input) !== null
52
+ if (input.clientId === OAUTH_CLI_CLIENT_ID) return true
49
53
  const registration = config.clients.find((client) => client.clientId === input.clientId)
50
54
  if (registration === undefined) return false
51
55
  const metadata = await clientMetadata(registration)
@@ -15,21 +15,22 @@ export interface OAuthConfig {
15
15
  const MAX_CLIENTS = 16
16
16
  const MAX_RESOURCES = 32
17
17
  const CONFIG_KEYS = ['clients', 'resources']
18
- const CLIENT_KEYS = ['provider', 'clientId', 'redirectUris', 'metadataUrl']
19
- const RESOURCE_KEYS = ['app', 'resource', 'defaultScopes', 'scopeGrants']
18
+ const CLIENT_KEYS = ['provider', 'clientId', 'redirectUris', 'metadataUrl', 'identity']
19
+ const RESOURCE_KEYS = ['app', 'resource', 'defaultScopes', 'scopeGrants', 'client']
20
20
 
21
21
  /**
22
- * Parse `OAUTH_CONFIG`. Absent or empty disables OAuth; anything malformed THROWS, so a typo fails the
23
- * boot instead of quietly serving fewer clients or scopes than the operator wrote. Unknown keys are
24
- * refused for the same reason.
22
+ * Parse `OAUTH_CONFIG`. Absent or empty disables OAuth; anything malformed THROWS, so a typo fails the boot instead of
23
+ * quietly serving fewer clients or scopes than the operator wrote. Unknown keys are refused for the same reason.
24
+ * `clients` may be empty: the command-line client is IAM's own and never listed. A client's identity resource names
25
+ * neither a registered resource nor a `platformAudiences` app, so its token is never one an installation service accepts.
25
26
  */
26
- export function parseOAuthConfig(raw: string | undefined): OAuthConfig | null {
27
+ export function parseOAuthConfig(raw: string | undefined, platformAudiences: ReadonlySet<string>): OAuthConfig | null {
27
28
  if (raw === undefined || raw.trim() === '') return null
28
29
  const value = parseJsonOrNull(raw)
29
30
  const rawClients = prop(value, 'clients')
30
31
  const rawResources = prop(value, 'resources')
31
32
  if (
32
- !hasOnlyKeys(value, CONFIG_KEYS) || !Array.isArray(rawClients) || rawClients.length === 0 || rawClients.length > MAX_CLIENTS
33
+ !hasOnlyKeys(value, CONFIG_KEYS) || !Array.isArray(rawClients) || rawClients.length > MAX_CLIENTS
33
34
  || !Array.isArray(rawResources)
34
35
  || rawResources.length === 0 || rawResources.length > MAX_RESOURCES
35
36
  ) {
@@ -55,6 +56,14 @@ export function parseOAuthConfig(raw: string | undefined): OAuthConfig | null {
55
56
  }
56
57
  resources.push(resource)
57
58
  }
59
+ for (const [index, { identity }] of clients.entries()) {
60
+ if (
61
+ identity !== undefined
62
+ && (platformAudiences.has(identity.app) || resources.some((entry) => entry.resource === identity.resource || entry.app === identity.app))
63
+ ) {
64
+ throw new Error(`OAUTH_CONFIG.clients[${index}].identity names an installation service's app or resource`)
65
+ }
66
+ }
58
67
  return { clients, resources }
59
68
  }
60
69
 
@@ -0,0 +1,184 @@
1
+ import { DEFAULT_LOCALE, narrowPermissions, type PermissionEntry } from '@fabrika/auth-core'
2
+ import { CONTROL_APP_ID, CONTROL_CLI_RESOURCES } from '@fabrika/control-contract'
3
+ import { isOAuthDeviceGrantLifetime, OAUTH_DEVICE_GRANT_LIFETIMES_SECONDS, type OAuthResourceDto } from '@fabrika/iam-contract'
4
+ import { sessionEndsAt } from './auth'
5
+ import { readForm, redirectHeaders, sameOrigin } from './auth/http'
6
+ import { currentSession } from './auth/sessions'
7
+ import { type PrincipalRow, principalStatus } from './db'
8
+ import { escapeHtml } from './html'
9
+ import { installationBrand } from './installation-brand'
10
+ import { scopeCeiling, servesClient } from './oauth'
11
+ import type { OAuthConfig } from './oauth-config'
12
+ import { attemptRequest, enterUserCode, formatUserCode, normalizeUserCode, OAUTH_DEVICE_PATH, userCodeHash } from './oauth-device'
13
+ import { htmlPage } from './password-pages'
14
+ import type { OAuthDeviceAuthorizationRow } from './repositories/oauth'
15
+ import type { SignedInSessionRow } from './repositories/sessions'
16
+ import { unixNow } from './repositories/sql'
17
+ import { resolveAuthorityAt } from './resolve'
18
+ import type { Services } from './services'
19
+
20
+ const LIFETIME_LABELS: Record<(typeof OAUTH_DEVICE_GRANT_LIFETIMES_SECONDS)[number], string> = {
21
+ 3600: '1 hour',
22
+ 86_400: '24 hours',
23
+ 604_800: '7 days',
24
+ }
25
+
26
+ /**
27
+ * `/oauth/device`: a signed-in person enters the code a device shows, reads what it asks for and decides. GET only
28
+ * renders the entry form, so a link can neither decide nor spend the person's code-entry budget.
29
+ */
30
+ export async function handleDevicePage(request: Request, services: Services, config: OAuthConfig): Promise<Response> {
31
+ if (request.method !== 'GET' && request.method !== 'POST') {
32
+ return new Response(null, { status: 405, headers: { allow: 'GET, POST', 'cache-control': 'no-store' } })
33
+ }
34
+ if (request.method === 'POST' && !sameOrigin(request, services.config)) {
35
+ return page(services, 'Not allowed', '<p>The form was not submitted from this page.</p>', 403)
36
+ }
37
+ const signedIn = await signedInPerson(request, services)
38
+ if (signedIn === null) {
39
+ if (request.method === 'POST') return page(services, 'Signed out', '<p>Your sign-in has ended. Open the link from your terminal again.</p>', 401)
40
+ const back = `${services.config.issuer}${OAUTH_DEVICE_PATH}${new URL(request.url).search}`
41
+ return new Response(null, { status: 302, headers: redirectHeaders(`${services.config.issuer}/auth/login?redirect=${encodeURIComponent(back)}`) })
42
+ }
43
+ if (signedIn === 'refused') return page(services, 'Not allowed', '<p>This account cannot authorize devices.</p>', 403)
44
+ if (request.method === 'GET') {
45
+ const offered = new URL(request.url).searchParams.get('user_code')
46
+ const code = offered === null ? null : normalizeUserCode(offered)
47
+ return entryPage(services, signedIn.principal, code === null ? '' : formatUserCode(code), null)
48
+ }
49
+ const form = await readForm(request)
50
+ const rawCode = form?.get('user_code') ?? ''
51
+ const entry = await enterUserCode(services, signedIn.principal.id, rawCode)
52
+ if (entry.kind === 'throttled') return page(services, 'Too many attempts', '<p>Too many wrong codes. Wait ten minutes and try again.</p>', 429)
53
+ if (entry.kind === 'unknown') return entryPage(services, signedIn.principal, '', 'That code is not valid, or it has expired.')
54
+ const decision = form?.get('decision')
55
+ if (decision === null || decision === undefined) return consentPage(services, config, signedIn.principal, entry.attempt, entry.userCode)
56
+ const hash = await userCodeHash(entry.userCode)
57
+ const now = unixNow()
58
+ if (decision === 'deny') {
59
+ await services.repositories.oauth.denyDeviceAuthorization(hash, now)
60
+ return page(services, 'Access denied', '<p>The device was not given access. You can close this page.</p>')
61
+ }
62
+ const lifetime = Number(form?.get('lifetime'))
63
+ if (decision !== 'approve' || !isOAuthDeviceGrantLifetime(lifetime)) return page(services, 'Not allowed', '<p>The decision is missing.</p>', 400)
64
+ // The grant stays bound to this IAM session and ends with it, an OIDC login's cap included.
65
+ const grantExpiresAt = Math.min(now + lifetime, sessionEndsAt(signedIn.session, services.config))
66
+ const approved = await services.repositories.oauth.approveDeviceAuthorization(
67
+ hash,
68
+ { principalId: signedIn.principal.id, sessionId: signedIn.session.id, grantExpiresAt },
69
+ now,
70
+ )
71
+ if (!approved) return page(services, 'Expired', '<p>This request was decided already, or it has expired.</p>', 409)
72
+ return page(services, 'Access granted', '<p>The device has access. Return to your terminal; you can close this page.</p>')
73
+ }
74
+
75
+ async function signedInPerson(
76
+ request: Request,
77
+ services: Services,
78
+ ): Promise<{ session: SignedInSessionRow; principal: PrincipalRow } | 'refused' | null> {
79
+ const session = await currentSession(request, services)
80
+ if (session === null) return null
81
+ const principal = await services.repositories.principals.getPrincipalById(session.principal_id)
82
+ if (principal === null || principal.type !== 'user' || principalStatus(principal) !== 'active') return 'refused'
83
+ return { session, principal }
84
+ }
85
+
86
+ async function entryPage(services: Services, principal: PrincipalRow, code: string, problem: string | null): Promise<Response> {
87
+ return page(
88
+ services,
89
+ 'Connect a device',
90
+ `<h1>Connect a device</h1>
91
+ <p>Signed in as <strong>${escapeHtml(principal.label)}</strong>.</p>
92
+ ${problem === null ? '' : `<p role="alert">${escapeHtml(problem)}</p>`}
93
+ <p>Enter the code your terminal shows. Only enter a code you started yourself.</p>
94
+ <form method="post" action="${OAUTH_DEVICE_PATH}">
95
+ <label for="user_code">Code</label>
96
+ <input id="user_code" name="user_code" value="${escapeHtml(code)}" autocomplete="off" autocapitalize="characters" spellcheck="false" required>
97
+ <button>Continue</button></form>`,
98
+ problem === null ? 200 : 400,
99
+ )
100
+ }
101
+
102
+ async function consentPage(
103
+ services: Services,
104
+ config: OAuthConfig,
105
+ principal: PrincipalRow,
106
+ attempt: OAuthDeviceAuthorizationRow,
107
+ userCode: string,
108
+ ): Promise<Response> {
109
+ const request = attemptRequest(attempt)
110
+ const resources = request?.resources.map((uri) =>
111
+ config.resources.find((entry) => entry.resource === uri && entry.app === attempt.app && servesClient(entry, true))
112
+ )
113
+ if (request === null || resources === undefined || !resources.every((resource): resource is OAuthResourceDto => resource !== undefined)) {
114
+ return page(services, 'Not available', '<p>This request asks for something the server no longer offers.</p>', 409)
115
+ }
116
+ const authority = await resolveAuthorityAt(services, principal, attempt.app)
117
+ const sections = resources.map((resource) => {
118
+ const permissions = narrowPermissions(authority.permissions, scopeCeiling(resource, request.scopes) ?? [])
119
+ return `<h2>${escapeHtml(resourceLabel(resource))}</h2><p class="uri">${escapeHtml(resource.resource)}</p>${permissionList(permissions)}`
120
+ })
121
+ const unbounded = request.scopes.filter((token) => resources.some((resource) => isUnbounded(resource, token)))
122
+ const warning = unbounded.length === 0
123
+ ? ''
124
+ : `<p role="alert"><strong>Warning:</strong> ${
125
+ unbounded.map((token) => `<code>${escapeHtml(token)}</code>`).join(', ')
126
+ } is not limited to one scope value: it holds its actions everywhere you hold them.</p>`
127
+ const lifetimes = OAUTH_DEVICE_GRANT_LIFETIMES_SECONDS.map((seconds, index) =>
128
+ `<label class="choice"><input type="radio" name="lifetime" value="${seconds}"${index === 0 ? ' checked' : ''}> ${LIFETIME_LABELS[seconds]}</label>`
129
+ )
130
+ return page(
131
+ services,
132
+ 'Authorize device',
133
+ `<h1>Authorize the fabrika command-line client</h1>
134
+ <p>Signed in as <strong>${escapeHtml(principal.label)}</strong>.</p>
135
+ <p>A device asks to act as you in <strong>${escapeHtml(attempt.app)}</strong>. It started this request at
136
+ <strong>${new Date(attempt.created_at * 1000).toISOString()}</strong> with the code <code>${escapeHtml(formatUserCode(userCode))}</code>.
137
+ Allow it only if you started it yourself.</p>
138
+ <p>Scopes: ${request.scopes.map((token) => `<code>${escapeHtml(token)}</code>`).join(' ')}</p>
139
+ ${warning}
140
+ <p>At most these permissions, and only while you hold them yourself:</p>
141
+ ${sections.join('')}
142
+ <form method="post" action="${OAUTH_DEVICE_PATH}">
143
+ <input type="hidden" name="user_code" value="${escapeHtml(formatUserCode(userCode))}">
144
+ <fieldset><legend>Access lasts</legend>${lifetimes.join('')}</fieldset>
145
+ <p>Access also ends when this sign-in ends or when it is revoked.</p>
146
+ <div class="actions"><button name="decision" value="approve">Allow</button>
147
+ <button name="decision" value="deny">Deny</button></div></form>`,
148
+ )
149
+ }
150
+
151
+ /**
152
+ * What a person reads a resource as: the name the console gives its command-line resource (the device grant serves
153
+ * only those), else the resource's path, which tells two resources of one app apart. The full URI stays under it.
154
+ */
155
+ function resourceLabel(resource: OAuthResourceDto): string {
156
+ const path = new URL(resource.resource).pathname
157
+ const known = resource.app === CONTROL_APP_ID ? CONTROL_CLI_RESOURCES.find((entry) => entry.path === path) : undefined
158
+ return known?.label ?? path
159
+ }
160
+
161
+ /** A scope whose actions no parameter narrows and at least one of which names no scope of its own. */
162
+ function isUnbounded(resource: OAuthResourceDto, token: string): boolean {
163
+ const grant = resource.scopeGrants.find((entry) => entry.scope === token)
164
+ return grant !== undefined && grant.parameter === undefined && grant.permissions.some((permission) => permission.scope == null)
165
+ }
166
+
167
+ function permissionList(permissions: readonly PermissionEntry[]): string {
168
+ if (permissions.length === 0) return '<p>None: you hold none of these permissions yourself.</p>'
169
+ const items = permissions.map((permission) => {
170
+ const scope = permission.scope == null ? 'everywhere' : `${permission.scope.type} ${permission.scope.value}`
171
+ return `<li><code>${escapeHtml(permission.action)}</code> <span>${escapeHtml(scope)}</span></li>`
172
+ })
173
+ return `<ul class="rows">${items.join('')}</ul>`
174
+ }
175
+
176
+ async function page(services: Services, title: string, content: string, status = 200): Promise<Response> {
177
+ return htmlPage({
178
+ locale: DEFAULT_LOCALE,
179
+ brand: await installationBrand(services),
180
+ title,
181
+ content: content.startsWith('<h1>') ? content : `<h1>${escapeHtml(title)}</h1>${content}`,
182
+ status,
183
+ })
184
+ }