@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.
@@ -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,15 +1,18 @@
1
- import { DEFAULT_LOCALE } from '@fabrika/auth-core'
1
+ import { DEFAULT_LOCALE, type KeyGrant } 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
- type OAuthResourceDto,
8
+ type OAuthIdentityResource,
8
9
  parseOAuthAuthorizationAttempt,
9
10
  parseOAuthClientCredential,
11
+ parseOAuthDeviceAuthorizationRequest,
10
12
  parseOAuthRevocationRequest,
11
13
  parseOAuthTokenRequest,
12
14
  resolveOAuthAuthorizationScopes,
15
+ resolveOAuthIdentityScopes,
13
16
  } from '@fabrika/iam-contract'
14
17
  import { decodeJwt } from 'jose'
15
18
  import { readForm, redirectHeaders, sameOrigin } from './auth/http'
@@ -18,9 +21,20 @@ import { principalStatus } from './db'
18
21
  import type { Env } from './env'
19
22
  import { escapeHtml } from './html'
20
23
  import { installationBrand } from './installation-brand'
21
- import { establishClient, type EstablishedClient, exchangeOAuthToken, grantAuthorization, revokeOAuthToken, scopeCeiling } from './oauth'
24
+ import {
25
+ type AuthorizationTarget,
26
+ establishClient,
27
+ exchangeOAuthToken,
28
+ grantAuthorization,
29
+ type ManagedClient,
30
+ revokeOAuthToken,
31
+ scopeCeiling,
32
+ servesClient,
33
+ } from './oauth'
22
34
  import { authenticateOAuthClient, authenticateRevokingClient } from './oauth-client-auth'
23
35
  import type { OAuthConfig } from './oauth-config'
36
+ import { OAUTH_DEVICE_PATH, redeemDeviceCode, startDeviceAuthorization } from './oauth-device'
37
+ import { handleDevicePage } from './oauth-device-page'
24
38
  import { normalizeOrigin } from './origin'
25
39
  import { htmlPage } from './password-pages'
26
40
  import type { Services } from './services'
@@ -29,11 +43,21 @@ export const OAUTH_METADATA_PATH = '/.well-known/oauth-authorization-server'
29
43
  const AUTHORIZE_PATH = '/oauth/authorize'
30
44
  const TOKEN_PATH = '/oauth/token'
31
45
  const REVOKE_PATH = '/oauth/revoke'
46
+ const DEVICE_AUTHORIZATION_PATH = '/oauth/device_authorization'
32
47
 
33
48
  type SigningEnv = Pick<Env, 'FABRIKA_IAM_SIGNING_KEYS' | 'ENVIRONMENT'>
34
49
 
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> {
50
+ /**
51
+ * The OAuth authorization server's public surface. With `OAUTH_CONFIG` unset every path is 404. `clientAddress` is the
52
+ * composition's client coordinate (`client-address.ts`), null where it names none.
53
+ */
54
+ export async function handleOAuth(
55
+ request: Request,
56
+ services: Services,
57
+ env: SigningEnv,
58
+ requestId: string,
59
+ clientAddress: string | null,
60
+ ): Promise<Response> {
37
61
  const config = services.config.oauth
38
62
  if (config === null) return new Response('not found', { status: 404 })
39
63
  const pathname = new URL(request.url).pathname
@@ -48,6 +72,10 @@ export async function handleOAuth(request: Request, services: Services, env: Sig
48
72
  return request.method === 'POST' ? token(request, services, env, config, requestId) : methodNotAllowed('POST')
49
73
  case REVOKE_PATH:
50
74
  return request.method === 'POST' ? revoke(request, services, env, config, requestId) : methodNotAllowed('POST')
75
+ case DEVICE_AUTHORIZATION_PATH:
76
+ return request.method === 'POST' ? deviceAuthorization(request, services, config, clientAddress) : methodNotAllowed('POST')
77
+ case OAUTH_DEVICE_PATH:
78
+ return handleDevicePage(request, services, config)
51
79
  default:
52
80
  return new Response('not found', { status: 404 })
53
81
  }
@@ -59,9 +87,10 @@ function authorizationServerMetadata(issuer: string): Response {
59
87
  authorization_endpoint: `${issuer}${AUTHORIZE_PATH}`,
60
88
  token_endpoint: `${issuer}${TOKEN_PATH}`,
61
89
  revocation_endpoint: `${issuer}${REVOKE_PATH}`,
90
+ device_authorization_endpoint: `${issuer}${DEVICE_AUTHORIZATION_PATH}`,
62
91
  jwks_uri: `${issuer}/.well-known/jwks.json`,
63
92
  response_types_supported: ['code'],
64
- grant_types_supported: ['authorization_code', 'refresh_token'],
93
+ grant_types_supported: ['authorization_code', 'refresh_token', OAUTH_DEVICE_CODE_GRANT_TYPE],
65
94
  code_challenge_methods_supported: ['S256'],
66
95
  token_endpoint_auth_methods_supported: ['none', 'private_key_jwt'],
67
96
  token_endpoint_auth_signing_alg_values_supported: [...OAUTH_CLIENT_ASSERTION_ALGORITHMS],
@@ -76,7 +105,7 @@ function authorizationServerMetadata(issuer: string): Response {
76
105
  type AuthorizationCheck =
77
106
  | { kind: 'refused'; message: string }
78
107
  | { kind: 'redirect'; response: Response }
79
- | { kind: 'valid'; request: OAuthAuthorizationRequest; client: EstablishedClient; resource: OAuthResourceDto; scopes: string[] }
108
+ | { kind: 'valid'; request: OAuthAuthorizationRequest; client: ManagedClient; resource: AuthorizationTarget; scopes: string[]; ceiling: KeyGrant[] }
80
109
 
81
110
  /**
82
111
  * Validate an authorization request in the order RFC 6749 §4.1.2.1 requires: until the client and its
@@ -89,11 +118,28 @@ async function checkAuthorization(issuer: string, config: OAuthConfig, input: Re
89
118
  const client = await establishClient(config, coordinates.client_id, coordinates.redirect_uri)
90
119
  if (client === null) return { kind: 'refused', message: 'The client or its redirect URI is not registered.' }
91
120
  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)
121
+ const identity = client.registration.identity
122
+ if (identity !== undefined) return checkIdentityAuthorization(issuer, attempt.request, client, identity)
123
+ // The command-line client's resources are served through the device grant only, never to a managed client.
124
+ const resource = config.resources.find((entry) => entry.resource === coordinates.resource && servesClient(entry, false))
93
125
  if (resource === undefined) return { kind: 'redirect', response: clientRedirect(issuer, coordinates, { error: 'invalid_target' }) }
94
126
  const scopes = resolveOAuthAuthorizationScopes(attempt.request.scope, resource)
95
- if (scopes === null) return { kind: 'redirect', response: clientRedirect(issuer, coordinates, { error: 'invalid_scope' }) }
96
- return { kind: 'valid', request: attempt.request, client, resource, scopes }
127
+ const ceiling = scopes === null ? null : scopeCeiling(resource, scopes)
128
+ if (scopes === null || ceiling === null) return { kind: 'redirect', response: clientRedirect(issuer, coordinates, { error: 'invalid_scope' }) }
129
+ return { kind: 'valid', request: attempt.request, client, resource, scopes, ceiling }
130
+ }
131
+
132
+ /** An identity-only client is served its own resource alone, with the `identity` scope and no permission. */
133
+ function checkIdentityAuthorization(
134
+ issuer: string,
135
+ request: OAuthAuthorizationRequest,
136
+ client: ManagedClient,
137
+ identity: OAuthIdentityResource,
138
+ ): AuthorizationCheck {
139
+ if (request.resource !== identity.resource) return { kind: 'redirect', response: clientRedirect(issuer, request, { error: 'invalid_target' }) }
140
+ const scopes = resolveOAuthIdentityScopes(request.scope)
141
+ if (scopes === null) return { kind: 'redirect', response: clientRedirect(issuer, request, { error: 'invalid_scope' }) }
142
+ return { kind: 'valid', request, client, resource: identity, scopes, ceiling: [] }
97
143
  }
98
144
 
99
145
  async function showConsent(request: Request, services: Services, config: OAuthConfig): Promise<Response> {
@@ -144,7 +190,9 @@ async function token(request: Request, services: Services, env: SigningEnv, conf
144
190
  audiences: [`${issuer}${TOKEN_PATH}`, issuer],
145
191
  })
146
192
  if (client === null) return protocolError('invalid_client', 401)
147
- const outcome = await exchangeOAuthToken(services, env, client, input, requestId)
193
+ const outcome = input.grant_type === OAUTH_DEVICE_CODE_GRANT_TYPE
194
+ ? await redeemDeviceCode(services, env, client, input, requestId)
195
+ : await exchangeOAuthToken(services, env, client, input, requestId)
148
196
  if (!outcome.ok) return protocolError(outcome.error, 400)
149
197
  return Response.json(outcome.body, { headers: { 'cache-control': 'no-store', pragma: 'no-cache' } })
150
198
  }
@@ -167,6 +215,30 @@ async function revoke(request: Request, services: Services, env: SigningEnv, con
167
215
  return new Response(null, { status: 200, headers: { 'cache-control': 'no-store' } })
168
216
  }
169
217
 
218
+ /** RFC 8628 §3.1: a public client starts a device authorization; a client that sends an assertion is refused. */
219
+ async function deviceAuthorization(request: Request, services: Services, config: OAuthConfig, clientAddress: string | null): Promise<Response> {
220
+ const form = await readForm(request)
221
+ const fields = form === null ? null : withRepeatedResource(form)
222
+ if (fields === null) return protocolError('invalid_request', 400)
223
+ if (parseOAuthClientCredential(fields.fields)?.method !== 'none') return protocolError('invalid_client', 401)
224
+ const input = parseOAuthDeviceAuthorizationRequest(fields)
225
+ if (input === null) return protocolError('invalid_request', 400)
226
+ const outcome = await startDeviceAuthorization(services, config, input, clientAddress)
227
+ if (!outcome.ok && outcome.error === 'temporarily_unavailable') {
228
+ return Response.json({ error: outcome.error }, { status: 429, headers: { 'retry-after': '60', 'cache-control': 'no-store', pragma: 'no-cache' } })
229
+ }
230
+ if (!outcome.ok) return protocolError(outcome.error, 400)
231
+ return Response.json(outcome.body, { headers: { 'cache-control': 'no-store', pragma: 'no-cache' } })
232
+ }
233
+
234
+ /** RFC 8707 §2: `resource` may repeat to name several resources; every other parameter still must not. */
235
+ function withRepeatedResource(params: URLSearchParams): { fields: Record<string, string>; resources: string[] } | null {
236
+ const resources = params.getAll('resource')
237
+ const rest = new URLSearchParams([...params].filter(([name]) => name !== 'resource'))
238
+ const fields = singleValued(rest)
239
+ return fields === null ? null : { fields, resources }
240
+ }
241
+
170
242
  /**
171
243
  * RFC 7521 §4.2 lets a client that authenticates with an assertion omit `client_id`; the assertion's
172
244
  * `sub` then names it. Nothing is trusted from it here: verification requires `iss` = `sub` = that id.
@@ -182,12 +254,19 @@ function withAssertedClientId(fields: Record<string, string> | null, credential:
182
254
  }
183
255
 
184
256
  async function consentPage(services: Services, check: Extract<AuthorizationCheck, { kind: 'valid' }>, signedInAs: string): Promise<Response> {
185
- const { request, client, resource, scopes } = check
257
+ const { request, client, resource, scopes, ceiling } = check
186
258
  const clientName = client.metadata.client_name ?? client.registration.clientId
187
- const permissions = (scopeCeiling(resource, scopes) ?? []).map((permission) => {
259
+ const permissions = ceiling.map((permission) => {
188
260
  const scope = permission.scope == null ? 'everywhere' : `${permission.scope.type} ${permission.scope.value}`
189
261
  return `<li><code>${escapeHtml(permission.action)}</code> — ${escapeHtml(scope)}</li>`
190
262
  })
263
+ const asks = client.registration.identity === undefined
264
+ ? `<p><strong>${escapeHtml(clientName)}</strong> asks to act as you in <strong>${escapeHtml(resource.app)}</strong>.</p>`
265
+ : `<p><strong>${escapeHtml(clientName)}</strong> asks to know who you are. It receives your account and name, and no permission.</p>`
266
+ const grants = client.registration.identity === undefined
267
+ ? `<p>At most these permissions, and only those you hold yourself:</p>
268
+ <ul>${permissions.join('')}</ul>`
269
+ : ''
191
270
  const fields: [string, string | undefined][] = [
192
271
  ['response_type', request.response_type],
193
272
  ['client_id', request.client_id],
@@ -205,12 +284,11 @@ async function consentPage(services: Services, check: Extract<AuthorizationCheck
205
284
  title: 'Authorize application',
206
285
  content: `<h1>Authorize ${escapeHtml(clientName)}</h1>
207
286
  <p>Signed in as <strong>${escapeHtml(signedInAs)}</strong>.</p>
208
- <p><strong>${escapeHtml(clientName)}</strong> asks to act as you in <strong>${escapeHtml(resource.app)}</strong>.</p>
287
+ ${asks}
209
288
  <p>Client: <code>${escapeHtml(client.registration.clientId)}</code></p>
210
289
  <p>Resource: <code>${escapeHtml(resource.resource)}</code></p>
211
290
  <p>Scopes: <code>${escapeHtml(scopes.join(' '))}</code></p>
212
- <p>At most these permissions, and only those you hold yourself:</p>
213
- <ul>${permissions.join('')}</ul>
291
+ ${grants}
214
292
  <p>Access ends when this sign-in ends or when it is revoked.</p>
215
293
  <form method="post" action="${AUTHORIZE_PATH}">${hidden.join('')}
216
294
  <button name="decision" value="approve">Allow</button>