@fabrika/iam 0.9.0-dev.32 → 0.9.0-dev.34

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.
Files changed (81) hide show
  1. package/fabrika.config.ts +47 -7
  2. package/migrations/0032_second_factor.sql +29 -0
  3. package/migrations/0033_oauth_grant_resources.sql +6 -0
  4. package/migrations/0034_oauth_device_authorizations.sql +24 -0
  5. package/migrations-postgres/0032_second_factor.sql +29 -0
  6. package/migrations-postgres/0033_oauth_grant_resources.sql +6 -0
  7. package/migrations-postgres/0034_oauth_device_authorizations.sql +24 -0
  8. package/package.json +12 -10
  9. package/src/admin/api-keys.ts +15 -5
  10. package/src/admin/grant-support.ts +10 -0
  11. package/src/admin/grants.ts +5 -2
  12. package/src/admin/handlers.ts +3 -0
  13. package/src/admin/principals.ts +2 -5
  14. package/src/admin/rpc.ts +8 -0
  15. package/src/admin/second-factor.ts +39 -0
  16. package/src/admin/sessions.ts +4 -4
  17. package/src/app.ts +1 -1
  18. package/src/auth/failure.ts +5 -0
  19. package/src/auth/http.ts +1 -1
  20. package/src/auth/invitations.ts +11 -3
  21. package/src/auth/login.ts +3 -2
  22. package/src/auth/oidc.ts +1 -1
  23. package/src/auth/password.ts +6 -6
  24. package/src/auth/routes.ts +11 -3
  25. package/src/auth/second-factor-challenge.ts +114 -0
  26. package/src/auth/second-factor.ts +276 -0
  27. package/src/auth/sessions.ts +72 -21
  28. package/src/auth.ts +19 -4
  29. package/src/catalog/cs.ts +32 -0
  30. package/src/catalog/en.ts +33 -0
  31. package/src/catalog/index.ts +28 -0
  32. package/src/catalog/uk.ts +33 -0
  33. package/src/data-key.ts +92 -0
  34. package/src/db.ts +12 -1
  35. package/src/env.ts +15 -2
  36. package/src/node/runtime.ts +7 -0
  37. package/src/oauth-client-auth.ts +6 -2
  38. package/src/oauth-config.ts +5 -5
  39. package/src/oauth-device-page.ts +173 -0
  40. package/src/oauth-device.ts +265 -0
  41. package/src/oauth-http.ts +53 -7
  42. package/src/oauth.ts +105 -37
  43. package/src/oidc-session.ts +25 -0
  44. package/src/repositories/audit.ts +4 -2
  45. package/src/repositories/oauth.ts +171 -4
  46. package/src/repositories/second-factors.ts +165 -0
  47. package/src/repositories/sessions.ts +17 -9
  48. package/src/second-factor-pages.ts +129 -0
  49. package/src/services.ts +11 -2
  50. package/src/tokens.ts +3 -3
  51. package/src/totp.ts +132 -0
  52. package/types/src/admin/api-keys.d.ts +3 -3
  53. package/types/src/admin/grant-support.d.ts +2 -0
  54. package/types/src/admin/handlers.d.ts +3 -0
  55. package/types/src/admin/second-factor.d.ts +5 -0
  56. package/types/src/auth/failure.d.ts +10 -0
  57. package/types/src/auth/http.d.ts +1 -1
  58. package/types/src/auth/invitations.d.ts +2 -1
  59. package/types/src/auth/password.d.ts +1 -1
  60. package/types/src/auth/second-factor-challenge.d.ts +34 -0
  61. package/types/src/auth/second-factor.d.ts +19 -0
  62. package/types/src/auth/sessions.d.ts +22 -9
  63. package/types/src/auth.d.ts +9 -3
  64. package/types/src/catalog/index.d.ts +28 -0
  65. package/types/src/data-key.d.ts +19 -0
  66. package/types/src/db.d.ts +4 -1
  67. package/types/src/env.d.ts +15 -2
  68. package/types/src/oauth-config.d.ts +3 -3
  69. package/types/src/oauth-device-page.d.ts +7 -0
  70. package/types/src/oauth-device.d.ts +51 -0
  71. package/types/src/oauth-http.d.ts +5 -2
  72. package/types/src/oauth.d.ts +34 -8
  73. package/types/src/oidc-session.d.ts +12 -0
  74. package/types/src/repositories/audit.d.ts +2 -1
  75. package/types/src/repositories/oauth.d.ts +48 -1
  76. package/types/src/repositories/second-factors.d.ts +68 -0
  77. package/types/src/repositories/sessions.d.ts +7 -3
  78. package/types/src/rpc-inputs.d.ts +23 -23
  79. package/types/src/second-factor-pages.d.ts +42 -0
  80. package/types/src/services.d.ts +4 -0
  81. package/types/src/totp.d.ts +32 -0
@@ -0,0 +1,173 @@
1
+ import { DEFAULT_LOCALE, narrowPermissions, type PermissionEntry } from '@fabrika/auth-core'
2
+ import { isOAuthDeviceGrantLifetime, OAUTH_DEVICE_GRANT_LIFETIMES_SECONDS, type OAuthResourceDto } from '@fabrika/iam-contract'
3
+ import { sessionEndsAt } from './auth'
4
+ import { readForm, redirectHeaders, sameOrigin } from './auth/http'
5
+ import { currentSession } from './auth/sessions'
6
+ import { type PrincipalRow, principalStatus } from './db'
7
+ import { escapeHtml } from './html'
8
+ import { installationBrand } from './installation-brand'
9
+ import { scopeCeiling, servesClient } from './oauth'
10
+ import type { OAuthConfig } from './oauth-config'
11
+ import { attemptRequest, enterUserCode, formatUserCode, normalizeUserCode, OAUTH_DEVICE_PATH, userCodeHash } from './oauth-device'
12
+ import { htmlPage } from './password-pages'
13
+ import type { OAuthDeviceAuthorizationRow } from './repositories/oauth'
14
+ import type { SignedInSessionRow } from './repositories/sessions'
15
+ import { unixNow } from './repositories/sql'
16
+ import { resolveAuthorityAt } from './resolve'
17
+ import type { Services } from './services'
18
+
19
+ const LIFETIME_LABELS: Record<(typeof OAUTH_DEVICE_GRANT_LIFETIMES_SECONDS)[number], string> = {
20
+ 3600: '1 hour',
21
+ 86_400: '24 hours',
22
+ 604_800: '7 days',
23
+ }
24
+
25
+ /**
26
+ * `/oauth/device`: a signed-in person enters the code a device shows, reads what it asks for and decides. GET only
27
+ * renders the entry form, so a link can neither decide nor spend the person's code-entry budget.
28
+ */
29
+ export async function handleDevicePage(request: Request, services: Services, config: OAuthConfig): Promise<Response> {
30
+ if (request.method !== 'GET' && request.method !== 'POST') {
31
+ return new Response(null, { status: 405, headers: { allow: 'GET, POST', 'cache-control': 'no-store' } })
32
+ }
33
+ if (request.method === 'POST' && !sameOrigin(request, services.config)) {
34
+ return page(services, 'Not allowed', '<p>The form was not submitted from this page.</p>', 403)
35
+ }
36
+ const signedIn = await signedInPerson(request, services)
37
+ if (signedIn === null) {
38
+ if (request.method === 'POST') return page(services, 'Signed out', '<p>Your sign-in has ended. Open the link from your terminal again.</p>', 401)
39
+ const back = `${services.config.issuer}${OAUTH_DEVICE_PATH}${new URL(request.url).search}`
40
+ return new Response(null, { status: 302, headers: redirectHeaders(`${services.config.issuer}/auth/login?redirect=${encodeURIComponent(back)}`) })
41
+ }
42
+ if (signedIn === 'refused') return page(services, 'Not allowed', '<p>This account cannot authorize devices.</p>', 403)
43
+ if (request.method === 'GET') {
44
+ const offered = new URL(request.url).searchParams.get('user_code')
45
+ const code = offered === null ? null : normalizeUserCode(offered)
46
+ return entryPage(services, signedIn.principal, code === null ? '' : formatUserCode(code), null)
47
+ }
48
+ const form = await readForm(request)
49
+ const rawCode = form?.get('user_code') ?? ''
50
+ const entry = await enterUserCode(services, signedIn.principal.id, rawCode)
51
+ if (entry.kind === 'throttled') return page(services, 'Too many attempts', '<p>Too many wrong codes. Wait ten minutes and try again.</p>', 429)
52
+ if (entry.kind === 'unknown') return entryPage(services, signedIn.principal, '', 'That code is not valid, or it has expired.')
53
+ const decision = form?.get('decision')
54
+ if (decision === null || decision === undefined) return consentPage(services, config, signedIn.principal, entry.attempt, entry.userCode)
55
+ const hash = await userCodeHash(entry.userCode)
56
+ const now = unixNow()
57
+ if (decision === 'deny') {
58
+ await services.repositories.oauth.denyDeviceAuthorization(hash, now)
59
+ return page(services, 'Access denied', '<p>The device was not given access. You can close this page.</p>')
60
+ }
61
+ const lifetime = Number(form?.get('lifetime'))
62
+ if (decision !== 'approve' || !isOAuthDeviceGrantLifetime(lifetime)) return page(services, 'Not allowed', '<p>The decision is missing.</p>', 400)
63
+ // The grant stays bound to this IAM session and ends with it, an OIDC login's cap included.
64
+ const grantExpiresAt = Math.min(now + lifetime, sessionEndsAt(signedIn.session, services.config))
65
+ const approved = await services.repositories.oauth.approveDeviceAuthorization(
66
+ hash,
67
+ { principalId: signedIn.principal.id, sessionId: signedIn.session.id, grantExpiresAt },
68
+ now,
69
+ )
70
+ if (!approved) return page(services, 'Expired', '<p>This request was decided already, or it has expired.</p>', 409)
71
+ return page(services, 'Access granted', '<p>The device has access. Return to your terminal; you can close this page.</p>')
72
+ }
73
+
74
+ async function signedInPerson(
75
+ request: Request,
76
+ services: Services,
77
+ ): Promise<{ session: SignedInSessionRow; principal: PrincipalRow } | 'refused' | null> {
78
+ const session = await currentSession(request, services)
79
+ if (session === null) return null
80
+ const principal = await services.repositories.principals.getPrincipalById(session.principal_id)
81
+ if (principal === null || principal.type !== 'user' || principalStatus(principal) !== 'active') return 'refused'
82
+ return { session, principal }
83
+ }
84
+
85
+ async function entryPage(services: Services, principal: PrincipalRow, code: string, problem: string | null): Promise<Response> {
86
+ return page(
87
+ services,
88
+ 'Connect a device',
89
+ `<h1>Connect a device</h1>
90
+ <p>Signed in as <strong>${escapeHtml(principal.label)}</strong>.</p>
91
+ ${problem === null ? '' : `<p role="alert">${escapeHtml(problem)}</p>`}
92
+ <p>Enter the code your terminal shows. Only enter a code you started yourself.</p>
93
+ <form method="post" action="${OAUTH_DEVICE_PATH}">
94
+ <label for="user_code">Code</label>
95
+ <input id="user_code" name="user_code" value="${escapeHtml(code)}" autocomplete="off" autocapitalize="characters" spellcheck="false" required>
96
+ <button>Continue</button></form>`,
97
+ problem === null ? 200 : 400,
98
+ )
99
+ }
100
+
101
+ async function consentPage(
102
+ services: Services,
103
+ config: OAuthConfig,
104
+ principal: PrincipalRow,
105
+ attempt: OAuthDeviceAuthorizationRow,
106
+ userCode: string,
107
+ ): Promise<Response> {
108
+ const request = attemptRequest(attempt)
109
+ const resources = request?.resources.map((uri) =>
110
+ config.resources.find((entry) => entry.resource === uri && entry.app === attempt.app && servesClient(entry, true))
111
+ )
112
+ if (request === null || resources === undefined || !resources.every((resource): resource is OAuthResourceDto => resource !== undefined)) {
113
+ return page(services, 'Not available', '<p>This request asks for something the server no longer offers.</p>', 409)
114
+ }
115
+ const authority = await resolveAuthorityAt(services, principal, attempt.app)
116
+ const sections = resources.map((resource) => {
117
+ const permissions = narrowPermissions(authority.permissions, scopeCeiling(resource, request.scopes) ?? [])
118
+ return `<h2><code>${escapeHtml(resource.resource)}</code></h2>${permissionList(permissions)}`
119
+ })
120
+ const unbounded = request.scopes.filter((token) => resources.some((resource) => isUnbounded(resource, token)))
121
+ const warning = unbounded.length === 0
122
+ ? ''
123
+ : `<p role="alert"><strong>Warning:</strong> ${
124
+ unbounded.map((token) => `<code>${escapeHtml(token)}</code>`).join(', ')
125
+ } is not limited to one scope value: it holds its actions everywhere you hold them.</p>`
126
+ const lifetimes = OAUTH_DEVICE_GRANT_LIFETIMES_SECONDS.map((seconds, index) =>
127
+ `<label><input type="radio" name="lifetime" value="${seconds}"${index === 0 ? ' checked' : ''}> ${LIFETIME_LABELS[seconds]}</label>`
128
+ )
129
+ return page(
130
+ services,
131
+ 'Authorize device',
132
+ `<h1>Authorize the fabrika command-line client</h1>
133
+ <p>Signed in as <strong>${escapeHtml(principal.label)}</strong>.</p>
134
+ <p>A device asks to act as you in <strong>${escapeHtml(attempt.app)}</strong>. It started this request at
135
+ <strong>${new Date(attempt.created_at * 1000).toISOString()}</strong> with the code <code>${escapeHtml(formatUserCode(userCode))}</code>.
136
+ Allow it only if you started it yourself.</p>
137
+ <p>Scopes: <code>${escapeHtml(request.scopes.join(' '))}</code></p>
138
+ ${warning}
139
+ <p>At most these permissions, and only while you hold them yourself:</p>
140
+ ${sections.join('')}
141
+ <form method="post" action="${OAUTH_DEVICE_PATH}">
142
+ <input type="hidden" name="user_code" value="${escapeHtml(formatUserCode(userCode))}">
143
+ <fieldset><legend>Access lasts</legend>${lifetimes.join('')}</fieldset>
144
+ <p>Access also ends when this sign-in ends or when it is revoked.</p>
145
+ <button name="decision" value="approve">Allow</button>
146
+ <button name="decision" value="deny">Deny</button></form>`,
147
+ )
148
+ }
149
+
150
+ /** A scope whose actions no parameter narrows and at least one of which names no scope of its own. */
151
+ function isUnbounded(resource: OAuthResourceDto, token: string): boolean {
152
+ const grant = resource.scopeGrants.find((entry) => entry.scope === token)
153
+ return grant !== undefined && grant.parameter === undefined && grant.permissions.some((permission) => permission.scope == null)
154
+ }
155
+
156
+ function permissionList(permissions: readonly PermissionEntry[]): string {
157
+ if (permissions.length === 0) return '<p>None: you hold none of these permissions yourself.</p>'
158
+ const items = permissions.map((permission) => {
159
+ const scope = permission.scope == null ? 'everywhere' : `${permission.scope.type} ${permission.scope.value}`
160
+ return `<li><code>${escapeHtml(permission.action)}</code> — ${escapeHtml(scope)}</li>`
161
+ })
162
+ return `<ul>${items.join('')}</ul>`
163
+ }
164
+
165
+ async function page(services: Services, title: string, content: string, status = 200): Promise<Response> {
166
+ return htmlPage({
167
+ locale: DEFAULT_LOCALE,
168
+ brand: await installationBrand(services),
169
+ title,
170
+ content: content.startsWith('<h1>') ? content : `<h1>${escapeHtml(title)}</h1>${content}`,
171
+ status,
172
+ })
173
+ }
@@ -0,0 +1,265 @@
1
+ import { OAUTH_CLI_CLIENT_ID, parseOAuthScopes } from '@fabrika/auth-core'
2
+ import {
3
+ OAUTH_DEVICE_CODE_GRANT_TYPE,
4
+ type OAuthDeviceAuthorizationRequest,
5
+ type OAuthDeviceAuthorizationResponse,
6
+ type OAuthResourceDto,
7
+ type OAuthTokenRequest,
8
+ resolveOAuthScopeToken,
9
+ } from '@fabrika/iam-contract'
10
+ import { uuidv7 } from '@fabrika/platform'
11
+ import type { Env } from './env'
12
+ import { parseJsonOrNull } from './json'
13
+ import {
14
+ type EstablishedClient,
15
+ grantAuthority,
16
+ grantRevocation,
17
+ mintForGrant,
18
+ type OAuthTokenOutcome,
19
+ servesClient,
20
+ storedResourceList,
21
+ } from './oauth'
22
+ import type { OAuthConfig } from './oauth-config'
23
+ import type { OAuthDeviceAuthorizationRow, OAuthGrantRow } from './repositories/oauth'
24
+ import { unixNow } from './repositories/sql'
25
+ import { generateToken, hashToken } from './secret'
26
+ import type { Services } from './services'
27
+
28
+ type SigningEnv = Pick<Env, 'FABRIKA_IAM_SIGNING_KEYS' | 'ENVIRONMENT'>
29
+
30
+ export const OAUTH_DEVICE_PATH = '/oauth/device'
31
+ /** RFC 8628 §3.2 `expires_in`: a person has five minutes to enter the code and decide. */
32
+ export const OAUTH_DEVICE_ATTEMPT_TTL_SECONDS = 300
33
+ export const OAUTH_DEVICE_POLL_INTERVAL_SECONDS = 5
34
+
35
+ /** RFC 8628 §6.1: twenty consonants, eight of them (about 34 bits), typed without ambiguity. */
36
+ const USER_CODE_ALPHABET = 'BCDFGHJKLMNPQRSTVWXZ'
37
+ const USER_CODE_LENGTH = 8
38
+
39
+ const START_WINDOW_SECONDS = 600
40
+ /** Starts per client address in a window, only where the composition names one (`client-address.ts`). */
41
+ const STARTS_PER_ADDRESS = 30
42
+ /**
43
+ * Starts per client in a window. With one device client it is installation-wide, and on a composition that names no
44
+ * client address it is the only bound, so it bounds the attempt rows a flood writes (each expires in five minutes)
45
+ * rather than a person: keeping it full takes a sustained flood, and a full bucket refuses for one minute only.
46
+ */
47
+ const STARTS_PER_CLIENT = 10_000
48
+ const CLIENT_BLOCK_SECONDS = 60
49
+
50
+ /**
51
+ * RFC 8628 §5.1: code entries a signed-in person may make in a window, right or wrong, counted before the lookup so a
52
+ * burst cannot test more codes than this. Looking a code up and deciding it are two entries.
53
+ */
54
+ const CODE_ENTRY_WINDOW_SECONDS = 600
55
+ const CODE_ENTRIES_PER_PRINCIPAL = 20
56
+
57
+ export type DeviceStartOutcome =
58
+ | { ok: true; body: OAuthDeviceAuthorizationResponse }
59
+ | { ok: false; error: 'unauthorized_client' | 'invalid_target' | 'invalid_scope' | 'temporarily_unavailable' }
60
+
61
+ /** The user code as a person types it: upper case, without the separator or spaces. Null when it cannot be one. */
62
+ export function normalizeUserCode(raw: string): string | null {
63
+ if (raw.length > 32) return null
64
+ const code = raw.toUpperCase().replaceAll(/[\s-]/g, '')
65
+ return code.length === USER_CODE_LENGTH && [...code].every((letter) => USER_CODE_ALPHABET.includes(letter)) ? code : null
66
+ }
67
+
68
+ export function formatUserCode(code: string): string {
69
+ return `${code.slice(0, 4)}-${code.slice(4)}`
70
+ }
71
+
72
+ function generateUserCode(): string {
73
+ let code = ''
74
+ while (code.length < USER_CODE_LENGTH) {
75
+ for (const byte of crypto.getRandomValues(new Uint8Array(USER_CODE_LENGTH))) {
76
+ // 240 is the largest multiple of 20 below 256, so every letter is equally likely.
77
+ if (byte < 240 && code.length < USER_CODE_LENGTH) code += USER_CODE_ALPHABET.charAt(byte % USER_CODE_ALPHABET.length)
78
+ }
79
+ }
80
+ return code
81
+ }
82
+
83
+ export function userCodeHash(code: string): Promise<string> {
84
+ return hashToken(`oauth-device-user-code:${code}`)
85
+ }
86
+
87
+ /**
88
+ * Count one use of the bucket `key`, which admits `allowed` uses per window, and answer whether it is spent. Decided from
89
+ * the counting statement's own `RETURNING`, so a concurrent burst cannot pass it.
90
+ */
91
+ async function spentBucket(services: Services, key: string, allowed: number, blockSeconds: number): Promise<boolean> {
92
+ const throttle = await services.repositories.passwords.recordLoginFailure({
93
+ loginKeyHash: await hashToken(key),
94
+ windowSeconds: START_WINDOW_SECONDS,
95
+ // The row blocks on the use that reaches `maxAttempts`, so the allowed uses are one fewer.
96
+ maxAttempts: allowed + 1,
97
+ blockSeconds,
98
+ })
99
+ return throttle.blocked_until !== null && throttle.blocked_until > unixNow()
100
+ }
101
+
102
+ /** The resources a device request names, when the server serves every one of them for one app. */
103
+ function requestedResources(config: OAuthConfig, uris: readonly string[]): OAuthResourceDto[] | null {
104
+ const resources: OAuthResourceDto[] = []
105
+ for (const uri of uris) {
106
+ const resource = config.resources.find((entry) => entry.resource === uri && servesClient(entry, true))
107
+ const first = resources[0]
108
+ if (resource === undefined || (first !== undefined && resource.app !== first.app)) return null
109
+ resources.push(resource)
110
+ }
111
+ return resources
112
+ }
113
+
114
+ /** RFC 8628 §3.1–3.2: record an attempt for the CLI client and answer its codes. */
115
+ export async function startDeviceAuthorization(
116
+ services: Services,
117
+ config: OAuthConfig,
118
+ request: OAuthDeviceAuthorizationRequest,
119
+ clientAddress: string | null,
120
+ ): Promise<DeviceStartOutcome> {
121
+ if (request.client_id !== OAUTH_CLI_CLIENT_ID) return { ok: false, error: 'unauthorized_client' }
122
+ const resources = requestedResources(config, request.resources)
123
+ const app = resources?.[0]?.app
124
+ if (resources === null || app === undefined) return { ok: false, error: 'invalid_target' }
125
+ if (!resources.every((resource) => request.scope.every((token) => resolveOAuthScopeToken(token, resource) !== null))) {
126
+ return { ok: false, error: 'invalid_scope' }
127
+ }
128
+ // The address bucket first: a start it refuses must not count against the bucket every other client shares.
129
+ if (clientAddress !== null && await spentBucket(services, `oauth-device-start:address:${clientAddress}`, STARTS_PER_ADDRESS, START_WINDOW_SECONDS)) {
130
+ return { ok: false, error: 'temporarily_unavailable' }
131
+ }
132
+ if (await spentBucket(services, `oauth-device-start:client:${request.client_id}`, STARTS_PER_CLIENT, CLIENT_BLOCK_SECONDS)) {
133
+ return { ok: false, error: 'temporarily_unavailable' }
134
+ }
135
+ const now = unixNow()
136
+ // A collision of either code with a live attempt is improbable; drawing again settles it.
137
+ for (let attempt = 0; attempt < 3; attempt++) {
138
+ const deviceCode = generateToken()
139
+ const userCode = generateUserCode()
140
+ const started = await services.repositories.oauth.startDeviceAuthorization({
141
+ device_code_hash: await hashToken(deviceCode),
142
+ user_code_hash: await userCodeHash(userCode),
143
+ client_id: request.client_id,
144
+ app,
145
+ resources: JSON.stringify(request.resources),
146
+ scopes: JSON.stringify(request.scope),
147
+ interval_seconds: OAUTH_DEVICE_POLL_INTERVAL_SECONDS,
148
+ created_at: now,
149
+ expires_at: now + OAUTH_DEVICE_ATTEMPT_TTL_SECONDS,
150
+ })
151
+ if (!started) continue
152
+ const verificationUri = `${services.config.issuer}${OAUTH_DEVICE_PATH}`
153
+ return {
154
+ ok: true,
155
+ body: {
156
+ device_code: deviceCode,
157
+ user_code: formatUserCode(userCode),
158
+ verification_uri: verificationUri,
159
+ verification_uri_complete: `${verificationUri}?${new URLSearchParams({ user_code: formatUserCode(userCode) })}`,
160
+ expires_in: OAUTH_DEVICE_ATTEMPT_TTL_SECONDS,
161
+ interval: OAUTH_DEVICE_POLL_INTERVAL_SECONDS,
162
+ },
163
+ }
164
+ }
165
+ throw new Error('could not draw unused device codes')
166
+ }
167
+
168
+ export type CodeEntry =
169
+ | { kind: 'found'; attempt: OAuthDeviceAuthorizationRow; userCode: string }
170
+ | { kind: 'unknown' }
171
+ | { kind: 'throttled' }
172
+
173
+ /**
174
+ * The pending attempt a signed-in person's code names. Every entry counts against that person before the lookup, and
175
+ * once the budget is spent even a right code is refused until the block ends (RFC 8628 §5.1).
176
+ */
177
+ export async function enterUserCode(services: Services, principalId: string, raw: string): Promise<CodeEntry> {
178
+ const throttle = await services.repositories.passwords.recordLoginFailure({
179
+ loginKeyHash: await hashToken(`oauth-device-code:principal:${principalId}`),
180
+ windowSeconds: CODE_ENTRY_WINDOW_SECONDS,
181
+ maxAttempts: CODE_ENTRIES_PER_PRINCIPAL + 1,
182
+ blockSeconds: CODE_ENTRY_WINDOW_SECONDS,
183
+ })
184
+ const now = unixNow()
185
+ if (throttle.blocked_until !== null && throttle.blocked_until > now) return { kind: 'throttled' }
186
+ const userCode = normalizeUserCode(raw)
187
+ const attempt = userCode === null ? null : await services.repositories.oauth.pendingDeviceAuthorization(await userCodeHash(userCode), now)
188
+ return attempt !== null && userCode !== null ? { kind: 'found', attempt, userCode } : { kind: 'unknown' }
189
+ }
190
+
191
+ /** The attempt's stored scope tokens and resources, or null when either does not parse. */
192
+ export function attemptRequest(attempt: OAuthDeviceAuthorizationRow): { scopes: string[]; resources: string[] } | null {
193
+ const scopes = parseOAuthScopes(parseJsonOrNull(attempt.scopes))
194
+ const resources = storedResourceList(attempt.resources)
195
+ return scopes === null || resources === null ? null : { scopes, resources }
196
+ }
197
+
198
+ /**
199
+ * RFC 8628 §3.4–3.5: one poll of the token endpoint. An approved attempt is spent for a new grant, bound to the IAM
200
+ * session it was approved under, and answers a token for the requested resource and the grant's first refresh token.
201
+ */
202
+ export async function redeemDeviceCode(
203
+ services: Services,
204
+ env: SigningEnv,
205
+ client: EstablishedClient,
206
+ input: Extract<OAuthTokenRequest, { grant_type: typeof OAUTH_DEVICE_CODE_GRANT_TYPE }>,
207
+ requestId: string,
208
+ ): Promise<OAuthTokenOutcome> {
209
+ if (client.kind !== 'cli') return { ok: false, error: 'unauthorized_client' }
210
+ const repository = services.repositories.oauth
211
+ const now = unixNow()
212
+ const hash = await hashToken(input.device_code)
213
+ const attempt = await repository.deviceAuthorization(hash)
214
+ if (attempt === null || attempt.client_id !== input.client_id) return { ok: false, error: 'invalid_grant' }
215
+ if (attempt.status === 'redeemed') {
216
+ // A spent device code presented again may have leaked: revoke what it gave, as for a replayed authorization code.
217
+ if (attempt.grant_id !== null) {
218
+ await repository.revokeGrant(attempt.grant_id, now, grantRevocation(requestId, attempt.grant_id, input.client_id, 'device_code_replay'))
219
+ }
220
+ return { ok: false, error: 'invalid_grant' }
221
+ }
222
+ if (attempt.expires_at <= now) return { ok: false, error: 'expired_token' }
223
+ if (!await repository.admitDevicePoll(hash, now)) return { ok: false, error: 'slow_down' }
224
+ if (attempt.status === 'denied') return { ok: false, error: 'access_denied' }
225
+ if (attempt.status === 'pending') return { ok: false, error: 'authorization_pending' }
226
+ const request = attemptRequest(attempt)
227
+ const [first] = request?.resources ?? []
228
+ // Checked before the attempt is spent, so a wrong resource does not cost the approval.
229
+ if (
230
+ request === null || first === undefined || !request.resources.includes(input.resource) || attempt.principal_id === null
231
+ || attempt.session_id === null || attempt.grant_expires_at === null
232
+ ) {
233
+ return { ok: false, error: 'invalid_grant' }
234
+ }
235
+ const grant: OAuthGrantRow = {
236
+ id: uuidv7(),
237
+ principal_id: attempt.principal_id,
238
+ session_id: attempt.session_id,
239
+ client_id: attempt.client_id,
240
+ app: attempt.app,
241
+ resource: first,
242
+ resources: JSON.stringify(request.resources),
243
+ scopes: JSON.stringify(request.scopes),
244
+ created_at: now,
245
+ expires_at: attempt.grant_expires_at,
246
+ revoked_at: null,
247
+ }
248
+ // The grant's whole authority (session, principal, configuration) is checked before anything is written.
249
+ if (await grantAuthority(services, grant, now, input.resource) === null) return { ok: false, error: 'invalid_grant' }
250
+ const refreshToken = generateToken()
251
+ const claimed = await repository.redeemDeviceAuthorization(hash, grant, await hashToken(refreshToken), {
252
+ requestId,
253
+ principalId: grant.principal_id,
254
+ principalLabel: grant.principal_id,
255
+ app: 'propustka',
256
+ action: 'iam.oauth.grant.create',
257
+ resourceType: 'oauth_grant',
258
+ resourceId: grant.id,
259
+ metadata: { clientId: grant.client_id, app: grant.app, resources: request.resources, scopes: request.scopes, flow: 'device' },
260
+ }, now)
261
+ if (claimed === null) return { ok: false, error: 'invalid_grant' }
262
+ const access = await mintForGrant(services, env, grant, input.resource, now)
263
+ if (access === null) return { ok: false, error: 'invalid_grant' }
264
+ return { ok: true, body: { ...access, refresh_token: refreshToken } }
265
+ }
package/src/oauth-http.ts CHANGED
@@ -1,12 +1,14 @@
1
1
  import { DEFAULT_LOCALE } from '@fabrika/auth-core'
2
2
  import {
3
3
  OAUTH_CLIENT_ASSERTION_ALGORITHMS,
4
+ OAUTH_DEVICE_CODE_GRANT_TYPE,
4
5
  type OAuthAuthorizationRequest,
5
6
  type OAuthAuthorizationServerMetadata,
6
7
  type OAuthClientCredential,
7
8
  type OAuthResourceDto,
8
9
  parseOAuthAuthorizationAttempt,
9
10
  parseOAuthClientCredential,
11
+ parseOAuthDeviceAuthorizationRequest,
10
12
  parseOAuthRevocationRequest,
11
13
  parseOAuthTokenRequest,
12
14
  resolveOAuthAuthorizationScopes,
@@ -18,9 +20,11 @@ import { principalStatus } from './db'
18
20
  import type { Env } from './env'
19
21
  import { escapeHtml } from './html'
20
22
  import { installationBrand } from './installation-brand'
21
- import { establishClient, type EstablishedClient, exchangeOAuthToken, grantAuthorization, revokeOAuthToken, scopeCeiling } from './oauth'
23
+ import { establishClient, exchangeOAuthToken, grantAuthorization, type ManagedClient, revokeOAuthToken, scopeCeiling, servesClient } from './oauth'
22
24
  import { authenticateOAuthClient, authenticateRevokingClient } from './oauth-client-auth'
23
25
  import type { OAuthConfig } from './oauth-config'
26
+ import { OAUTH_DEVICE_PATH, redeemDeviceCode, startDeviceAuthorization } from './oauth-device'
27
+ import { handleDevicePage } from './oauth-device-page'
24
28
  import { normalizeOrigin } from './origin'
25
29
  import { htmlPage } from './password-pages'
26
30
  import type { Services } from './services'
@@ -29,11 +33,21 @@ export const OAUTH_METADATA_PATH = '/.well-known/oauth-authorization-server'
29
33
  const AUTHORIZE_PATH = '/oauth/authorize'
30
34
  const TOKEN_PATH = '/oauth/token'
31
35
  const REVOKE_PATH = '/oauth/revoke'
36
+ const DEVICE_AUTHORIZATION_PATH = '/oauth/device_authorization'
32
37
 
33
38
  type SigningEnv = Pick<Env, 'FABRIKA_IAM_SIGNING_KEYS' | 'ENVIRONMENT'>
34
39
 
35
- /** The OAuth authorization server's public surface. With `OAUTH_CONFIG` unset every path is 404. */
36
- export async function handleOAuth(request: Request, services: Services, env: SigningEnv, requestId: string): Promise<Response> {
40
+ /**
41
+ * The OAuth authorization server's public surface. With `OAUTH_CONFIG` unset every path is 404. `clientAddress` is the
42
+ * composition's client coordinate (`client-address.ts`), null where it names none.
43
+ */
44
+ export async function handleOAuth(
45
+ request: Request,
46
+ services: Services,
47
+ env: SigningEnv,
48
+ requestId: string,
49
+ clientAddress: string | null,
50
+ ): Promise<Response> {
37
51
  const config = services.config.oauth
38
52
  if (config === null) return new Response('not found', { status: 404 })
39
53
  const pathname = new URL(request.url).pathname
@@ -48,6 +62,10 @@ export async function handleOAuth(request: Request, services: Services, env: Sig
48
62
  return request.method === 'POST' ? token(request, services, env, config, requestId) : methodNotAllowed('POST')
49
63
  case REVOKE_PATH:
50
64
  return request.method === 'POST' ? revoke(request, services, env, config, requestId) : methodNotAllowed('POST')
65
+ case DEVICE_AUTHORIZATION_PATH:
66
+ return request.method === 'POST' ? deviceAuthorization(request, services, config, clientAddress) : methodNotAllowed('POST')
67
+ case OAUTH_DEVICE_PATH:
68
+ return handleDevicePage(request, services, config)
51
69
  default:
52
70
  return new Response('not found', { status: 404 })
53
71
  }
@@ -59,9 +77,10 @@ function authorizationServerMetadata(issuer: string): Response {
59
77
  authorization_endpoint: `${issuer}${AUTHORIZE_PATH}`,
60
78
  token_endpoint: `${issuer}${TOKEN_PATH}`,
61
79
  revocation_endpoint: `${issuer}${REVOKE_PATH}`,
80
+ device_authorization_endpoint: `${issuer}${DEVICE_AUTHORIZATION_PATH}`,
62
81
  jwks_uri: `${issuer}/.well-known/jwks.json`,
63
82
  response_types_supported: ['code'],
64
- grant_types_supported: ['authorization_code', 'refresh_token'],
83
+ grant_types_supported: ['authorization_code', 'refresh_token', OAUTH_DEVICE_CODE_GRANT_TYPE],
65
84
  code_challenge_methods_supported: ['S256'],
66
85
  token_endpoint_auth_methods_supported: ['none', 'private_key_jwt'],
67
86
  token_endpoint_auth_signing_alg_values_supported: [...OAUTH_CLIENT_ASSERTION_ALGORITHMS],
@@ -76,7 +95,7 @@ function authorizationServerMetadata(issuer: string): Response {
76
95
  type AuthorizationCheck =
77
96
  | { kind: 'refused'; message: string }
78
97
  | { kind: 'redirect'; response: Response }
79
- | { kind: 'valid'; request: OAuthAuthorizationRequest; client: EstablishedClient; resource: OAuthResourceDto; scopes: string[] }
98
+ | { kind: 'valid'; request: OAuthAuthorizationRequest; client: ManagedClient; resource: OAuthResourceDto; scopes: string[] }
80
99
 
81
100
  /**
82
101
  * Validate an authorization request in the order RFC 6749 §4.1.2.1 requires: until the client and its
@@ -89,7 +108,8 @@ async function checkAuthorization(issuer: string, config: OAuthConfig, input: Re
89
108
  const client = await establishClient(config, coordinates.client_id, coordinates.redirect_uri)
90
109
  if (client === null) return { kind: 'refused', message: 'The client or its redirect URI is not registered.' }
91
110
  if (attempt.kind === 'invalid_scope') return { kind: 'redirect', response: clientRedirect(issuer, coordinates, { error: 'invalid_scope' }) }
92
- const resource = config.resources.find((entry) => entry.resource === coordinates.resource)
111
+ // The command-line client's resources are served through the device grant only, never to a managed client.
112
+ const resource = config.resources.find((entry) => entry.resource === coordinates.resource && servesClient(entry, false))
93
113
  if (resource === undefined) return { kind: 'redirect', response: clientRedirect(issuer, coordinates, { error: 'invalid_target' }) }
94
114
  const scopes = resolveOAuthAuthorizationScopes(attempt.request.scope, resource)
95
115
  if (scopes === null) return { kind: 'redirect', response: clientRedirect(issuer, coordinates, { error: 'invalid_scope' }) }
@@ -144,7 +164,9 @@ async function token(request: Request, services: Services, env: SigningEnv, conf
144
164
  audiences: [`${issuer}${TOKEN_PATH}`, issuer],
145
165
  })
146
166
  if (client === null) return protocolError('invalid_client', 401)
147
- const outcome = await exchangeOAuthToken(services, env, client, input, requestId)
167
+ const outcome = input.grant_type === OAUTH_DEVICE_CODE_GRANT_TYPE
168
+ ? await redeemDeviceCode(services, env, client, input, requestId)
169
+ : await exchangeOAuthToken(services, env, client, input, requestId)
148
170
  if (!outcome.ok) return protocolError(outcome.error, 400)
149
171
  return Response.json(outcome.body, { headers: { 'cache-control': 'no-store', pragma: 'no-cache' } })
150
172
  }
@@ -167,6 +189,30 @@ async function revoke(request: Request, services: Services, env: SigningEnv, con
167
189
  return new Response(null, { status: 200, headers: { 'cache-control': 'no-store' } })
168
190
  }
169
191
 
192
+ /** RFC 8628 §3.1: a public client starts a device authorization; a client that sends an assertion is refused. */
193
+ async function deviceAuthorization(request: Request, services: Services, config: OAuthConfig, clientAddress: string | null): Promise<Response> {
194
+ const form = await readForm(request)
195
+ const fields = form === null ? null : withRepeatedResource(form)
196
+ if (fields === null) return protocolError('invalid_request', 400)
197
+ if (parseOAuthClientCredential(fields.fields)?.method !== 'none') return protocolError('invalid_client', 401)
198
+ const input = parseOAuthDeviceAuthorizationRequest(fields)
199
+ if (input === null) return protocolError('invalid_request', 400)
200
+ const outcome = await startDeviceAuthorization(services, config, input, clientAddress)
201
+ if (!outcome.ok && outcome.error === 'temporarily_unavailable') {
202
+ return Response.json({ error: outcome.error }, { status: 429, headers: { 'retry-after': '60', 'cache-control': 'no-store', pragma: 'no-cache' } })
203
+ }
204
+ if (!outcome.ok) return protocolError(outcome.error, 400)
205
+ return Response.json(outcome.body, { headers: { 'cache-control': 'no-store', pragma: 'no-cache' } })
206
+ }
207
+
208
+ /** RFC 8707 §2: `resource` may repeat to name several resources; every other parameter still must not. */
209
+ function withRepeatedResource(params: URLSearchParams): { fields: Record<string, string>; resources: string[] } | null {
210
+ const resources = params.getAll('resource')
211
+ const rest = new URLSearchParams([...params].filter(([name]) => name !== 'resource'))
212
+ const fields = singleValued(rest)
213
+ return fields === null ? null : { fields, resources }
214
+ }
215
+
170
216
  /**
171
217
  * RFC 7521 §4.2 lets a client that authenticates with an assertion omit `client_id`; the assertion's
172
218
  * `sub` then names it. Nothing is trusted from it here: verification requires `iss` = `sub` = that id.