@fabrika/cli 0.9.0-dev.5 → 0.9.0-dev.50
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 +16 -13
- package/src/app-dev-seed.ts +2 -6
- package/src/app-dev-ui.ts +155 -24
- package/src/app-dev.ts +65 -24
- package/src/connect.ts +24 -8
- package/src/control-oauth.ts +463 -0
- package/src/control.ts +899 -105
- package/src/credential-origin.ts +54 -0
- package/src/data.ts +61 -24
- package/src/db.ts +35 -212
- package/src/index.ts +21 -5
- package/src/job.ts +2 -2
- package/src/operations.ts +737 -0
- package/types/src/app-dev-seed.d.ts +0 -2
- package/types/src/app-dev-ui.d.ts +22 -8
- package/types/src/connect.d.ts +4 -1
- package/types/src/control-oauth.d.ts +56 -0
- package/types/src/control.d.ts +86 -14
- package/types/src/credential-origin.d.ts +14 -0
- package/types/src/data.d.ts +3 -1
- package/types/src/db.d.ts +1 -3
- package/types/src/job.d.ts +1 -1
- package/types/src/operations.d.ts +23 -0
- package/src/junit.ts +0 -37
- package/types/src/junit.d.ts +0 -10
|
@@ -0,0 +1,463 @@
|
|
|
1
|
+
// The command-line client's OAuth half: `fabrika control auth device` asks IAM for an RFC 8628 device grant that a person
|
|
2
|
+
// approves in the browser, and every later Control call without FABRIKA_CONTROL_KEY refreshes an access token for the
|
|
3
|
+
// one console resource it calls (RFC 8707). The refresh token lives in the credential helper alone, never on stdout.
|
|
4
|
+
//
|
|
5
|
+
// IAM rotates the refresh token on every refresh and treats a second use of a spent one as a replay that revokes the
|
|
6
|
+
// grant. So a refresh runs under a per-origin file lock (lock, `get`, refresh, `store`, unlock), and neither a device
|
|
7
|
+
// code nor a refresh token is sent again after an answer that did not arrive: IAM may have spent it.
|
|
8
|
+
|
|
9
|
+
import type { RpcFetch } from '@fabrika/app'
|
|
10
|
+
import { OAUTH_CLI_CLIENT_ID } from '@fabrika/auth-core'
|
|
11
|
+
import {
|
|
12
|
+
CONTROL_CLI_PRESETS,
|
|
13
|
+
CONTROL_OPERATIONS_RPC_PATH,
|
|
14
|
+
CONTROL_RPC_PATH,
|
|
15
|
+
type ControlCliPreset,
|
|
16
|
+
controlCliPresetPaths,
|
|
17
|
+
} from '@fabrika/control-contract'
|
|
18
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
19
|
+
import { link, mkdir, open, readFile, stat, unlink, writeFile } from 'node:fs/promises'
|
|
20
|
+
import { homedir } from 'node:os'
|
|
21
|
+
import { isAbsolute, join } from 'node:path'
|
|
22
|
+
import { z } from 'zod'
|
|
23
|
+
import { credentialOriginOf } from './credential-origin.js'
|
|
24
|
+
|
|
25
|
+
export const CREDENTIAL_HELPER_VARIABLE = 'FABRIKA_CONTROL_CREDENTIAL_HELPER'
|
|
26
|
+
|
|
27
|
+
/** RFC 8628 §3.4. */
|
|
28
|
+
const DEVICE_CODE_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:device_code'
|
|
29
|
+
|
|
30
|
+
const RESTART = 'run `fabrika control auth device` again'
|
|
31
|
+
|
|
32
|
+
/** Where the refresh token lives between runs: a command with `get` and `store`, in the style of a git credential helper. */
|
|
33
|
+
export interface CredentialHelper {
|
|
34
|
+
/** The refresh token stored for `origin`, or null when none is. */
|
|
35
|
+
get(origin: string): Promise<string | null>
|
|
36
|
+
store(origin: string, refreshToken: string): Promise<void>
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Takes the one lock that serializes refresh-token rotation for `origin` on this machine; resolves to its release. */
|
|
40
|
+
export type CredentialLock = (origin: string) => Promise<() => Promise<void>>
|
|
41
|
+
|
|
42
|
+
export interface ControlOAuthDependencies {
|
|
43
|
+
readonly fetch: RpcFetch
|
|
44
|
+
readonly helper: CredentialHelper
|
|
45
|
+
readonly lock: CredentialLock
|
|
46
|
+
/** Milliseconds. */
|
|
47
|
+
readonly now: () => number
|
|
48
|
+
readonly sleep: (ms: number) => Promise<void>
|
|
49
|
+
/** Guidance for the person running the command; it goes to stderr. */
|
|
50
|
+
readonly note: (line: string) => void
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const errorCode = (error: unknown): unknown => typeof error === 'object' && error !== null ? Reflect.get(error, 'code') : undefined
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* `command` run by the shell with the action as its one argument, as git runs a credential helper. Its stdin carries
|
|
57
|
+
* `origin=<origin>` and, for `store`, `refresh_token=<token>`; `get` prints `refresh_token=<token>`, or nothing.
|
|
58
|
+
*/
|
|
59
|
+
export function commandCredentialHelper(command: string): CredentialHelper {
|
|
60
|
+
const run = async (action: 'get' | 'store', input: string): Promise<string> => {
|
|
61
|
+
const child = Bun.spawn(['sh', '-c', `${command} "$@"`, CREDENTIAL_HELPER_VARIABLE, action], {
|
|
62
|
+
stdin: new TextEncoder().encode(input),
|
|
63
|
+
stdout: 'pipe',
|
|
64
|
+
stderr: 'inherit',
|
|
65
|
+
})
|
|
66
|
+
const [output, code] = await Promise.all([new Response(child.stdout).text(), child.exited])
|
|
67
|
+
// The output may hold the token, so a failure reports the exit code alone.
|
|
68
|
+
if (code !== 0) throw new Error(`${CREDENTIAL_HELPER_VARIABLE} ${action} exited with ${code}`)
|
|
69
|
+
return output
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
get: async (origin) => {
|
|
73
|
+
for (const line of (await run('get', `origin=${origin}\n`)).split('\n')) {
|
|
74
|
+
const matched = /^refresh_token=(\S+)$/.exec(line.trim())
|
|
75
|
+
if (matched?.[1] !== undefined) return matched[1]
|
|
76
|
+
}
|
|
77
|
+
return null
|
|
78
|
+
},
|
|
79
|
+
store: async (origin, refreshToken) => {
|
|
80
|
+
await run('store', `origin=${origin}\nrefresh_token=${refreshToken}\n`)
|
|
81
|
+
},
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** A lock file's text (its holder's pid and a nonce that tells this holding from a later one) and whether that pid lives. */
|
|
86
|
+
interface LockHolder {
|
|
87
|
+
readonly text: string
|
|
88
|
+
readonly stale: boolean
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function lockHolder(path: string): Promise<LockHolder | null> {
|
|
92
|
+
const text = await readFile(path, 'utf8').catch(() => null)
|
|
93
|
+
if (text === null) return null
|
|
94
|
+
const pid = Number(text.split(' ')[0])
|
|
95
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return { text, stale: false }
|
|
96
|
+
try {
|
|
97
|
+
process.kill(pid, 0)
|
|
98
|
+
return { text, stale: false }
|
|
99
|
+
} catch (error) {
|
|
100
|
+
return { text, stale: errorCode(error) === 'ESRCH' }
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** A takeover guard older than this was left by a process that died while it took a lock over, which takes milliseconds. */
|
|
105
|
+
const TAKEOVER_GUARD_MS = 10_000
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Removes a dead holder's lock file. Only the holder of the `.takeover` guard may, and only while the file still holds
|
|
109
|
+
* the text it judged dead: that text names a dead process and a nonce, so no live holder's file matches it. Answers
|
|
110
|
+
* whether this caller took the guard, so it retries at once instead of waiting.
|
|
111
|
+
*/
|
|
112
|
+
async function removeStale(path: string, judged: string): Promise<boolean> {
|
|
113
|
+
const guard = `${path}.takeover`
|
|
114
|
+
try {
|
|
115
|
+
await (await open(guard, 'wx', 0o600)).close()
|
|
116
|
+
} catch (error) {
|
|
117
|
+
if (errorCode(error) !== 'EEXIST') throw error
|
|
118
|
+
const since = await stat(guard).then((file) => Date.now() - file.mtimeMs, () => 0)
|
|
119
|
+
if (since > TAKEOVER_GUARD_MS) await unlink(guard).catch(() => undefined)
|
|
120
|
+
return false
|
|
121
|
+
}
|
|
122
|
+
try {
|
|
123
|
+
if ((await readFile(path, 'utf8').catch(() => null)) === judged) await unlink(path).catch(() => undefined)
|
|
124
|
+
} finally {
|
|
125
|
+
await unlink(guard).catch(() => undefined)
|
|
126
|
+
}
|
|
127
|
+
return true
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* An exclusive lock file per origin under `directory`, created whole by `link` so it never exists empty, and naming its
|
|
132
|
+
* holder. A dead holder's file is taken over; release removes only this holding's own file.
|
|
133
|
+
*/
|
|
134
|
+
export function fileCredentialLock(directory: string, waitMs = 30_000): CredentialLock {
|
|
135
|
+
return async (origin) => {
|
|
136
|
+
await mkdir(directory, { recursive: true, mode: 0o700 })
|
|
137
|
+
const path = join(directory, `${createHash('sha256').update(origin).digest('hex').slice(0, 32)}.lock`)
|
|
138
|
+
const mine = `${process.pid} ${randomUUID()}\n`
|
|
139
|
+
const prepared = `${path}.${randomUUID()}.new`
|
|
140
|
+
await writeFile(prepared, mine, { mode: 0o600 })
|
|
141
|
+
const deadline = Date.now() + waitMs
|
|
142
|
+
try {
|
|
143
|
+
for (;;) {
|
|
144
|
+
try {
|
|
145
|
+
await link(prepared, path)
|
|
146
|
+
return async () => {
|
|
147
|
+
if ((await readFile(path, 'utf8').catch(() => null)) === mine) await unlink(path).catch(() => undefined)
|
|
148
|
+
}
|
|
149
|
+
} catch (error) {
|
|
150
|
+
if (errorCode(error) !== 'EEXIST') throw error
|
|
151
|
+
}
|
|
152
|
+
const holder = await lockHolder(path)
|
|
153
|
+
if (holder === null) continue
|
|
154
|
+
if (holder.stale) {
|
|
155
|
+
if (await removeStale(path, holder.text)) continue
|
|
156
|
+
} else if (Date.now() >= deadline) {
|
|
157
|
+
throw new Error(
|
|
158
|
+
`Another fabrika process holds ${path}; its refresh may be waiting on IAM. Remove the file only when no fabrika process runs`,
|
|
159
|
+
)
|
|
160
|
+
}
|
|
161
|
+
await Bun.sleep(50)
|
|
162
|
+
}
|
|
163
|
+
} finally {
|
|
164
|
+
await unlink(prepared).catch(() => undefined)
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** The helper `command` names, the lock under the user's cache directory, and the real clock. */
|
|
170
|
+
export function defaultControlOAuthDependencies(
|
|
171
|
+
command: string,
|
|
172
|
+
env: Readonly<Record<string, string | undefined>>,
|
|
173
|
+
send: RpcFetch,
|
|
174
|
+
): ControlOAuthDependencies {
|
|
175
|
+
const xdg = env['XDG_CACHE_HOME']?.trim()
|
|
176
|
+
const cache = xdg !== undefined && isAbsolute(xdg) ? xdg : join(homedir(), '.cache')
|
|
177
|
+
return {
|
|
178
|
+
fetch: send,
|
|
179
|
+
helper: commandCredentialHelper(command),
|
|
180
|
+
lock: fileCredentialLock(join(cache, 'fabrika', 'control-credentials')),
|
|
181
|
+
now: Date.now,
|
|
182
|
+
sleep: (ms) => Bun.sleep(ms),
|
|
183
|
+
note: (line) => console.warn(line),
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
interface AuthorizationServer {
|
|
188
|
+
readonly issuer: string
|
|
189
|
+
readonly tokenEndpoint: string
|
|
190
|
+
readonly deviceEndpoint: string
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const protectedResourceSchema = z.object({ resource: z.string(), authorization_servers: z.array(z.string()).min(1) })
|
|
194
|
+
const serverMetadataSchema = z.object({ issuer: z.string(), token_endpoint: z.string(), device_authorization_endpoint: z.string() })
|
|
195
|
+
const deviceStartSchema = z.object({
|
|
196
|
+
device_code: z.string().min(1).max(256),
|
|
197
|
+
user_code: z.string().regex(/^[A-Z0-9-]{4,16}$/),
|
|
198
|
+
verification_uri: z.string(),
|
|
199
|
+
verification_uri_complete: z.string().optional(),
|
|
200
|
+
expires_in: z.number().int().positive().max(3600),
|
|
201
|
+
interval: z.number().int().positive().max(60).optional(),
|
|
202
|
+
})
|
|
203
|
+
const tokensSchema = z.object({
|
|
204
|
+
access_token: z.string().min(1),
|
|
205
|
+
token_type: z.string().regex(/^bearer$/i),
|
|
206
|
+
expires_in: z.number().int().nonnegative(),
|
|
207
|
+
refresh_token: z.string().min(1).optional(),
|
|
208
|
+
})
|
|
209
|
+
/** What is left to keep of a 200 answer the CLI cannot otherwise read: IAM may have rotated the refresh token in it. */
|
|
210
|
+
const rotatedSchema = z.object({ refresh_token: z.string().min(1) })
|
|
211
|
+
type Tokens = z.infer<typeof tokensSchema>
|
|
212
|
+
/** Only an error code is ever repeated from IAM's answer. */
|
|
213
|
+
const errorSchema = z.object({ error: z.string().regex(/^[a-z_]{1,64}$/) })
|
|
214
|
+
|
|
215
|
+
const sameOrigin = (raw: string, origin: string): boolean => {
|
|
216
|
+
try {
|
|
217
|
+
return new URL(raw).origin === origin
|
|
218
|
+
} catch {
|
|
219
|
+
return false
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** A metadata document, or null for anything but a 200 JSON answer; a redirect is not followed. */
|
|
224
|
+
async function getJson(url: string, deps: ControlOAuthDependencies): Promise<unknown> {
|
|
225
|
+
let response: Response
|
|
226
|
+
try {
|
|
227
|
+
response = await deps.fetch(url, { headers: { accept: 'application/json' }, redirect: 'manual' })
|
|
228
|
+
} catch {
|
|
229
|
+
throw new Error(`${new URL(url).origin} could not be reached`)
|
|
230
|
+
}
|
|
231
|
+
if (response.status !== 200) {
|
|
232
|
+
await response.body?.cancel().catch(() => undefined)
|
|
233
|
+
return null
|
|
234
|
+
}
|
|
235
|
+
return await response.json().catch(() => null)
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* IAM's endpoints, found from Control's origin alone: the console's RPC resource names its authorization server
|
|
240
|
+
* (RFC 9728), whose metadata names the endpoints (RFC 8414). Both answers decide where a credential goes, so both are
|
|
241
|
+
* read without following a redirect, and every endpoint must be on the issuer's own origin.
|
|
242
|
+
*/
|
|
243
|
+
async function discover(origin: string, deps: ControlOAuthDependencies): Promise<AuthorizationServer> {
|
|
244
|
+
const resource = `${origin}${CONTROL_RPC_PATH}`
|
|
245
|
+
const published = protectedResourceSchema.safeParse(await getJson(`${origin}/.well-known/oauth-protected-resource${CONTROL_RPC_PATH}`, deps))
|
|
246
|
+
if (!published.success || published.data.resource !== resource) {
|
|
247
|
+
throw new Error(`${origin} publishes no OAuth resource for its RPC: this installation does not serve the command-line client's OAuth`)
|
|
248
|
+
}
|
|
249
|
+
const issuer = published.data.authorization_servers[0]
|
|
250
|
+
if (issuer === undefined || credentialOriginOf(issuer) !== issuer) {
|
|
251
|
+
throw new Error(`${origin} names an authorization server that is not an https origin`)
|
|
252
|
+
}
|
|
253
|
+
const server = serverMetadataSchema.safeParse(await getJson(`${issuer}/.well-known/oauth-authorization-server`, deps))
|
|
254
|
+
if (
|
|
255
|
+
!server.success || server.data.issuer !== issuer || !sameOrigin(server.data.token_endpoint, issuer)
|
|
256
|
+
|| !sameOrigin(server.data.device_authorization_endpoint, issuer)
|
|
257
|
+
) {
|
|
258
|
+
throw new Error(`${issuer} publishes no OAuth metadata this CLI can use`)
|
|
259
|
+
}
|
|
260
|
+
return { issuer, tokenEndpoint: server.data.token_endpoint, deviceEndpoint: server.data.device_authorization_endpoint }
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** One form POST, never redirected and never retried; `lost` is the whole message when no answer arrives. */
|
|
264
|
+
async function postForm(url: string, form: URLSearchParams, deps: ControlOAuthDependencies, lost: string): Promise<Response> {
|
|
265
|
+
try {
|
|
266
|
+
return await deps.fetch(url, {
|
|
267
|
+
method: 'POST',
|
|
268
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
|
|
269
|
+
body: form.toString(),
|
|
270
|
+
redirect: 'manual',
|
|
271
|
+
})
|
|
272
|
+
} catch {
|
|
273
|
+
throw new Error(lost)
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
type TokenAnswer =
|
|
278
|
+
| { readonly kind: 'tokens'; readonly tokens: Tokens }
|
|
279
|
+
| { readonly kind: 'error'; readonly error: string }
|
|
280
|
+
| { readonly kind: 'unreadable'; readonly refreshToken?: string }
|
|
281
|
+
|
|
282
|
+
/** The token endpoint's answer: tokens, an OAuth error this CLI can read, or neither (with a rotated token it held). */
|
|
283
|
+
async function tokenAnswer(response: Response): Promise<TokenAnswer> {
|
|
284
|
+
const body: unknown = await response.json().catch(() => null)
|
|
285
|
+
if (response.status === 200) {
|
|
286
|
+
const tokens = tokensSchema.safeParse(body)
|
|
287
|
+
if (tokens.success) return { kind: 'tokens', tokens: tokens.data }
|
|
288
|
+
const rotated = rotatedSchema.safeParse(body)
|
|
289
|
+
return rotated.success ? { kind: 'unreadable', refreshToken: rotated.data.refresh_token } : { kind: 'unreadable' }
|
|
290
|
+
}
|
|
291
|
+
if (response.status === 400 || response.status === 401) {
|
|
292
|
+
const error = errorSchema.safeParse(body)
|
|
293
|
+
if (error.success) return { kind: 'error', error: error.data.error }
|
|
294
|
+
}
|
|
295
|
+
return { kind: 'unreadable' }
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
export interface DeviceGrantRequest {
|
|
299
|
+
/** Control's origin, already checked. */
|
|
300
|
+
readonly origin: string
|
|
301
|
+
readonly preset: ControlCliPreset
|
|
302
|
+
/** The application every preset but `create` holds its actions at. */
|
|
303
|
+
readonly app?: string
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** The preset `raw` names, or null. */
|
|
307
|
+
export const parseControlCliPreset = (raw: string): ControlCliPreset | null => CONTROL_CLI_PRESETS.find((preset) => preset === raw) ?? null
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* The device grant: start it for the preset's resources, tell the person where to approve it, poll until they do, and
|
|
311
|
+
* store the refresh token through the helper. The access token of the first resource is dropped; a call refreshes its own.
|
|
312
|
+
*/
|
|
313
|
+
export async function authorizeDevice(request: DeviceGrantRequest, deps: ControlOAuthDependencies): Promise<void> {
|
|
314
|
+
const server = await discover(request.origin, deps)
|
|
315
|
+
const resources = controlCliPresetPaths(request.preset).map((path) => `${request.origin}${path}`)
|
|
316
|
+
const form = new URLSearchParams({
|
|
317
|
+
client_id: OAUTH_CLI_CLIENT_ID,
|
|
318
|
+
scope: request.app === undefined ? request.preset : `${request.preset}:${request.app}`,
|
|
319
|
+
})
|
|
320
|
+
for (const resource of resources) form.append('resource', resource)
|
|
321
|
+
const response = await postForm(server.deviceEndpoint, form, deps, `${server.issuer} could not be reached to start the device grant`)
|
|
322
|
+
if (response.status === 429) {
|
|
323
|
+
await response.body?.cancel().catch(() => undefined)
|
|
324
|
+
throw new Error('IAM refuses new device grants for a minute (HTTP 429); try again later')
|
|
325
|
+
}
|
|
326
|
+
const body: unknown = await response.json().catch(() => null)
|
|
327
|
+
if (response.status !== 200) {
|
|
328
|
+
const error = errorSchema.safeParse(body)
|
|
329
|
+
throw new Error(`IAM refused the device grant: ${error.success ? error.data.error : `HTTP ${response.status}`}`)
|
|
330
|
+
}
|
|
331
|
+
const started = deviceStartSchema.safeParse(body)
|
|
332
|
+
if (!started.success || !sameOrigin(started.data.verification_uri, server.issuer)) {
|
|
333
|
+
throw new Error('IAM answered the device grant with a body this CLI cannot read')
|
|
334
|
+
}
|
|
335
|
+
const page = started.data.verification_uri_complete !== undefined && sameOrigin(started.data.verification_uri_complete, server.issuer)
|
|
336
|
+
? started.data.verification_uri_complete
|
|
337
|
+
: started.data.verification_uri
|
|
338
|
+
deps.note(`Open ${page} and confirm the code ${started.data.user_code}.`)
|
|
339
|
+
deps.note(`The person who approves picks how long the grant lasts. The code expires in ${Math.ceil(started.data.expires_in / 60)} minutes.`)
|
|
340
|
+
const refreshToken = await pollDevice(server, started.data, resources[0] ?? `${request.origin}${CONTROL_RPC_PATH}`, deps)
|
|
341
|
+
const release = await deps.lock(request.origin)
|
|
342
|
+
try {
|
|
343
|
+
await deps.helper.store(request.origin, refreshToken)
|
|
344
|
+
} finally {
|
|
345
|
+
await release()
|
|
346
|
+
}
|
|
347
|
+
deps.note(`Approved. The refresh token is stored through ${CREDENTIAL_HELPER_VARIABLE}; Control calls without FABRIKA_CONTROL_KEY use it.`)
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
async function pollDevice(
|
|
351
|
+
server: AuthorizationServer,
|
|
352
|
+
started: z.infer<typeof deviceStartSchema>,
|
|
353
|
+
resource: string,
|
|
354
|
+
deps: ControlOAuthDependencies,
|
|
355
|
+
): Promise<string> {
|
|
356
|
+
const form = new URLSearchParams({ grant_type: DEVICE_CODE_GRANT_TYPE, client_id: OAUTH_CLI_CLIENT_ID, device_code: started.device_code, resource })
|
|
357
|
+
let interval = started.interval ?? 5
|
|
358
|
+
const deadline = deps.now() + started.expires_in * 1000
|
|
359
|
+
while (deps.now() < deadline) {
|
|
360
|
+
await deps.sleep(interval * 1000)
|
|
361
|
+
const response = await postForm(
|
|
362
|
+
server.tokenEndpoint,
|
|
363
|
+
form,
|
|
364
|
+
deps,
|
|
365
|
+
`${server.issuer} did not answer the device code. It is not sent again, because IAM may have redeemed it; ${RESTART}`,
|
|
366
|
+
)
|
|
367
|
+
const answer = await tokenAnswer(response)
|
|
368
|
+
// An answer this CLI cannot read still keeps the grant when it carries the refresh token.
|
|
369
|
+
if (answer.kind === 'unreadable' && answer.refreshToken !== undefined) return answer.refreshToken
|
|
370
|
+
if (answer.kind === 'unreadable') throw new Error(`IAM answered the device code with HTTP ${response.status}. It is not sent again; ${RESTART}`)
|
|
371
|
+
if (answer.kind === 'tokens') {
|
|
372
|
+
if (answer.tokens.refresh_token === undefined) throw new Error('IAM approved the grant but issued no refresh token')
|
|
373
|
+
return answer.tokens.refresh_token
|
|
374
|
+
}
|
|
375
|
+
if (answer.error === 'authorization_pending') continue
|
|
376
|
+
if (answer.error === 'slow_down') {
|
|
377
|
+
interval += 5
|
|
378
|
+
continue
|
|
379
|
+
}
|
|
380
|
+
if (answer.error === 'access_denied') throw new Error('The grant was denied in the browser')
|
|
381
|
+
if (answer.error === 'expired_token') break
|
|
382
|
+
throw new Error(`IAM refused the device code: ${answer.error}`)
|
|
383
|
+
}
|
|
384
|
+
throw new Error(`The code expired before anyone approved it; ${RESTART}`)
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** Why IAM refused a refresh, as the person can act on it. */
|
|
388
|
+
function refreshRefusal(origin: string, resource: string, error: string): string {
|
|
389
|
+
if (error === 'invalid_grant') return `The grant for ${origin} expired, was revoked, or its refresh token was used twice; ${RESTART}`
|
|
390
|
+
if (error === 'invalid_target') {
|
|
391
|
+
return `The grant for ${origin} does not cover ${resource}; approve a preset that does with \`fabrika control auth device\``
|
|
392
|
+
}
|
|
393
|
+
return `IAM refused the refresh: ${error}`
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** Stores the token IAM rotated; once it is lost, the stored one is spent. */
|
|
397
|
+
async function storeRotated(origin: string, refreshToken: string, deps: ControlOAuthDependencies): Promise<void> {
|
|
398
|
+
try {
|
|
399
|
+
await deps.helper.store(origin, refreshToken)
|
|
400
|
+
} catch (error) {
|
|
401
|
+
const reason = error instanceof Error ? error.message : 'it failed'
|
|
402
|
+
throw new Error(`IAM rotated the refresh token, but storing the new one failed (${reason}); the stored one is spent: ${RESTART}`)
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** A current access token for one of the console's resources. */
|
|
407
|
+
export type ControlBearer = (resource: string) => Promise<string>
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* Access tokens for `origin`'s resources, refreshed through the helper's grant as a call needs them and kept in this
|
|
411
|
+
* process's memory only. Concurrent calls for one resource share one refresh.
|
|
412
|
+
*/
|
|
413
|
+
export function controlOAuthBearer(origin: string, deps: ControlOAuthDependencies): ControlBearer {
|
|
414
|
+
let server: Promise<AuthorizationServer> | undefined
|
|
415
|
+
const held = new Map<string, { readonly token: string; readonly refreshAt: number }>()
|
|
416
|
+
const pending = new Map<string, Promise<string>>()
|
|
417
|
+
const refresh = async (resource: string): Promise<string> => {
|
|
418
|
+
server ??= discover(origin, deps)
|
|
419
|
+
const { issuer, tokenEndpoint } = await server
|
|
420
|
+
const release = await deps.lock(origin)
|
|
421
|
+
try {
|
|
422
|
+
const stored = await deps.helper.get(origin)
|
|
423
|
+
if (stored === null) throw new Error(`${CREDENTIAL_HELPER_VARIABLE} holds no grant for ${origin}; run \`fabrika control auth device\` first`)
|
|
424
|
+
const form = new URLSearchParams({ grant_type: 'refresh_token', client_id: OAUTH_CLI_CLIENT_ID, refresh_token: stored, resource })
|
|
425
|
+
const response = await postForm(
|
|
426
|
+
tokenEndpoint,
|
|
427
|
+
form,
|
|
428
|
+
deps,
|
|
429
|
+
`${issuer} did not answer the refresh. If it arrived there, the stored refresh token is spent and the next call fails; then ${RESTART}`,
|
|
430
|
+
)
|
|
431
|
+
const answer = await tokenAnswer(response)
|
|
432
|
+
if (answer.kind === 'unreadable') {
|
|
433
|
+
if (answer.refreshToken !== undefined) await storeRotated(origin, answer.refreshToken, deps)
|
|
434
|
+
throw new Error(`IAM answered the refresh with HTTP ${response.status}, in a shape this CLI cannot read`)
|
|
435
|
+
}
|
|
436
|
+
if (answer.kind === 'error') throw new Error(refreshRefusal(origin, resource, answer.error))
|
|
437
|
+
if (answer.tokens.refresh_token !== undefined) await storeRotated(origin, answer.tokens.refresh_token, deps)
|
|
438
|
+
// Refreshed 30 seconds early, so a token does not expire between this check and Control's.
|
|
439
|
+
held.set(resource, { token: answer.tokens.access_token, refreshAt: deps.now() + Math.max(0, answer.tokens.expires_in - 30) * 1000 })
|
|
440
|
+
return answer.tokens.access_token
|
|
441
|
+
} finally {
|
|
442
|
+
await release()
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
return (resource) => {
|
|
446
|
+
const token = held.get(resource)
|
|
447
|
+
if (token !== undefined && deps.now() < token.refreshAt) return Promise.resolve(token.token)
|
|
448
|
+
const running = pending.get(resource)
|
|
449
|
+
if (running !== undefined) return running
|
|
450
|
+
const started = refresh(resource).finally(() => pending.delete(resource))
|
|
451
|
+
pending.set(resource, started)
|
|
452
|
+
return started
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
const onPath = (pathname: string, path: string): boolean => pathname === path || pathname.startsWith(`${path}/`)
|
|
457
|
+
|
|
458
|
+
/** The console resource a request needs: the Operations RPC, or Control's own. A bearer never leaves Control's origin. */
|
|
459
|
+
export function controlResourceFor(origin: string, input: RequestInfo | URL): string {
|
|
460
|
+
const url = new URL(input instanceof Request ? input.url : input)
|
|
461
|
+
if (url.origin !== origin) throw new Error(`A Control credential is sent to ${origin} only`)
|
|
462
|
+
return `${origin}${onPath(url.pathname, CONTROL_OPERATIONS_RPC_PATH) ? CONTROL_OPERATIONS_RPC_PATH : CONTROL_RPC_PATH}`
|
|
463
|
+
}
|