@fabrika/cli 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/package.json +13 -13
- package/src/connect.ts +24 -8
- package/src/control-oauth.ts +463 -0
- package/src/control.ts +100 -47
- package/src/credential-origin.ts +54 -0
- package/src/data.ts +3 -2
- package/src/operations.ts +23 -8
- package/types/src/connect.d.ts +4 -1
- package/types/src/control-oauth.d.ts +56 -0
- package/types/src/control.d.ts +11 -18
- package/types/src/credential-origin.d.ts +14 -0
- package/types/src/data.d.ts +1 -1
- package/types/src/operations.d.ts +4 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fabrika/cli",
|
|
3
|
-
"version": "0.9.0-dev.
|
|
3
|
+
"version": "0.9.0-dev.35",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -31,20 +31,20 @@
|
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
33
|
"zod": "^3.25.76",
|
|
34
|
-
"@fabrika/app": "0.9.0-dev.
|
|
35
|
-
"@fabrika/auth-core": "0.9.0-dev.
|
|
36
|
-
"@fabrika/control-contract": "0.9.0-dev.
|
|
37
|
-
"@fabrika/operations-contract": "0.9.0-dev.
|
|
38
|
-
"@fabrika/provider-contract": "0.9.0-dev.
|
|
39
|
-
"@fabrika/db": "0.9.0-dev.
|
|
40
|
-
"@fabrika/platform": "0.9.0-dev.
|
|
41
|
-
"@fabrika/platform-node": "0.9.0-dev.
|
|
42
|
-
"@fabrika/check": "0.9.0-dev.
|
|
34
|
+
"@fabrika/app": "0.9.0-dev.35",
|
|
35
|
+
"@fabrika/auth-core": "0.9.0-dev.35",
|
|
36
|
+
"@fabrika/control-contract": "0.9.0-dev.35",
|
|
37
|
+
"@fabrika/operations-contract": "0.9.0-dev.35",
|
|
38
|
+
"@fabrika/provider-contract": "0.9.0-dev.35",
|
|
39
|
+
"@fabrika/db": "0.9.0-dev.35",
|
|
40
|
+
"@fabrika/platform": "0.9.0-dev.35",
|
|
41
|
+
"@fabrika/platform-node": "0.9.0-dev.35",
|
|
42
|
+
"@fabrika/check": "0.9.0-dev.35"
|
|
43
43
|
},
|
|
44
44
|
"peerDependencies": {
|
|
45
|
-
"@fabrika/builder": "0.9.0-dev.
|
|
46
|
-
"@fabrika/provider-cloudflare": "0.9.0-dev.
|
|
47
|
-
"@fabrika/provider-zerops": "0.9.0-dev.
|
|
45
|
+
"@fabrika/builder": "0.9.0-dev.35",
|
|
46
|
+
"@fabrika/provider-cloudflare": "0.9.0-dev.35",
|
|
47
|
+
"@fabrika/provider-zerops": "0.9.0-dev.35"
|
|
48
48
|
},
|
|
49
49
|
"peerDependenciesMeta": {
|
|
50
50
|
"@fabrika/builder": {
|
package/src/connect.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { CONNECT_LIMITS, ContractError, parseExportDescription, snapshotNames, snapshotSource } from '@fabrika/app/contract'
|
|
2
2
|
import { isJsonMediaType, readBoundedBytes } from '@fabrika/app/implement'
|
|
3
3
|
import { API_KEY_PREFIX, type ExportDescription } from '@fabrika/auth-core'
|
|
4
|
+
import { CONTROL_RPC_PATH } from '@fabrika/control-contract'
|
|
4
5
|
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
|
5
6
|
import { dirname, join } from 'node:path'
|
|
7
|
+
import { controlOAuthBearer, type ControlOAuthDependencies, CREDENTIAL_HELPER_VARIABLE, defaultControlOAuthDependencies } from './control-oauth.js'
|
|
6
8
|
|
|
7
9
|
const KEY_VARIABLE = 'FABRIKA_CONTROL_KEY'
|
|
8
10
|
const URL_VARIABLE = 'FABRIKA_CONTROL_URL'
|
|
@@ -21,7 +23,8 @@ Usage:
|
|
|
21
23
|
|
|
22
24
|
Run from the application root. Both read the export the owner's environment <env> approved for the consumer from
|
|
23
25
|
Control (${URL_VARIABLE} or --url), with a machine key that holds deploy.read on the consumer, read from
|
|
24
|
-
${KEY_VARIABLE} in the environment only
|
|
26
|
+
${KEY_VARIABLE} in the environment only, or with the grant \`fabrika control auth device\` stored through
|
|
27
|
+
${CREDENTIAL_HELPER_VARIABLE}. The origin is https; plain http only for localhost. \`add\` refuses an
|
|
25
28
|
existing snapshot and prints what to add to src/app-kit.ts and to the endpoints that call it; \`pull\` refuses a missing one
|
|
26
29
|
and says whether the digest changed. The platform writes each import's address and key when it deploys the consumer.
|
|
27
30
|
`
|
|
@@ -35,6 +38,8 @@ export interface ConnectCommandDependencies {
|
|
|
35
38
|
readonly write: (line: string) => void
|
|
36
39
|
/** Guidance for the person running it. */
|
|
37
40
|
readonly note: (line: string) => void
|
|
41
|
+
/** Replaces the credential helper, its lock and the clock; only a test passes it. */
|
|
42
|
+
readonly oauth?: ControlOAuthDependencies
|
|
38
43
|
}
|
|
39
44
|
|
|
40
45
|
interface Target {
|
|
@@ -85,12 +90,23 @@ function parseTarget(command: string, argv: readonly string[], source: ConnectCo
|
|
|
85
90
|
return { app, export: name, version: Number(version), consumer, env, control: url.origin }
|
|
86
91
|
}
|
|
87
92
|
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
93
|
+
/** The key when it is set, else an access token for Control's RPC from the grant the credential helper holds. */
|
|
94
|
+
async function controlBearer(target: Target, deps: ConnectCommandDependencies): Promise<string> {
|
|
95
|
+
const key = deps.source[KEY_VARIABLE]?.trim() ?? ''
|
|
96
|
+
if (key !== '') {
|
|
97
|
+
if (!key.startsWith(API_KEY_PREFIX)) {
|
|
98
|
+
throw new Error(`${KEY_VARIABLE} must hold a ${API_KEY_PREFIX} machine key that holds deploy.read on the consumer`)
|
|
99
|
+
}
|
|
100
|
+
return key
|
|
101
|
+
}
|
|
102
|
+
const helper = deps.source[CREDENTIAL_HELPER_VARIABLE]?.trim() ?? ''
|
|
103
|
+
if (helper === '') {
|
|
104
|
+
throw new Error(
|
|
105
|
+
`${KEY_VARIABLE} must hold a ${API_KEY_PREFIX} machine key that holds deploy.read on the consumer, or ${CREDENTIAL_HELPER_VARIABLE} the helper a \`fabrika control auth device\` grant is stored through`,
|
|
106
|
+
)
|
|
92
107
|
}
|
|
93
|
-
|
|
108
|
+
const oauth = deps.oauth ?? defaultControlOAuthDependencies(helper, deps.source, (input, init) => deps.fetch(new Request(input, init)))
|
|
109
|
+
return await controlOAuthBearer(target.control, oauth)(`${target.control}${CONTROL_RPC_PATH}`)
|
|
94
110
|
}
|
|
95
111
|
|
|
96
112
|
/**
|
|
@@ -188,7 +204,7 @@ function contractHint(description: ExportDescription): string[] {
|
|
|
188
204
|
|
|
189
205
|
async function add(argv: readonly string[], deps: ConnectCommandDependencies): Promise<void> {
|
|
190
206
|
const target = parseTarget('add', argv, deps.source)
|
|
191
|
-
const description = await fetchDescription(target,
|
|
207
|
+
const description = await fetchDescription(target, await controlBearer(target, deps), deps)
|
|
192
208
|
const { file } = snapshotNames(target.app, target.export, target.version)
|
|
193
209
|
const path = join(deps.cwd, file)
|
|
194
210
|
await mkdir(dirname(path), { recursive: true })
|
|
@@ -211,7 +227,7 @@ async function pull(argv: readonly string[], deps: ConnectCommandDependencies):
|
|
|
211
227
|
if (previous === null) {
|
|
212
228
|
throw new Error(`connect pull: ${file} does not exist; run fabrika connect add first`)
|
|
213
229
|
}
|
|
214
|
-
const description = await fetchDescription(target,
|
|
230
|
+
const description = await fetchDescription(target, await controlBearer(target, deps), deps)
|
|
215
231
|
const source = snapshotSource(description)
|
|
216
232
|
await writeFile(path, source)
|
|
217
233
|
deps.write(`${file}\n`)
|
|
@@ -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
|
+
}
|
package/src/control.ts
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
|
|
12
12
|
import { createRpcClient, type InferRpcClient, RpcError, type RpcFetch } from '@fabrika/app'
|
|
13
13
|
import { type IssueKeyInput, type IssueKeyResult, MAX_KEY_LIFETIME_SECONDS } from '@fabrika/auth-core'
|
|
14
|
-
import { APP_ENV_KINDS } from '@fabrika/control-contract'
|
|
14
|
+
import { APP_ENV_KINDS, CONTROL_CLI_PRESETS } from '@fabrika/control-contract'
|
|
15
15
|
import type {
|
|
16
16
|
AppDto,
|
|
17
17
|
AppEnvDto,
|
|
@@ -31,6 +31,16 @@ import type {
|
|
|
31
31
|
RunDto,
|
|
32
32
|
} from '@fabrika/control-contract'
|
|
33
33
|
import { z } from 'zod'
|
|
34
|
+
import {
|
|
35
|
+
authorizeDevice,
|
|
36
|
+
controlOAuthBearer,
|
|
37
|
+
type ControlOAuthDependencies,
|
|
38
|
+
controlResourceFor,
|
|
39
|
+
CREDENTIAL_HELPER_VARIABLE,
|
|
40
|
+
defaultControlOAuthDependencies,
|
|
41
|
+
parseControlCliPreset,
|
|
42
|
+
} from './control-oauth.js'
|
|
43
|
+
import { credentialOrigin, type OriginSource } from './credential-origin.js'
|
|
34
44
|
|
|
35
45
|
const jsonValueSchema: z.ZodType<JsonValue> = z.lazy(() =>
|
|
36
46
|
z.union([z.null(), z.string(), z.number(), z.boolean(), z.array(jsonValueSchema), z.record(jsonValueSchema)])
|
|
@@ -52,6 +62,7 @@ const issueKeyResultSchema = z.union([
|
|
|
52
62
|
const USAGE = `fabrika control — operate the Delivery control plane
|
|
53
63
|
|
|
54
64
|
Usage:
|
|
65
|
+
fabrika control auth device --preset=<read|deploy|operate|create> [--app=<id>]
|
|
55
66
|
fabrika control key issue --label=<name> --permissions=<a,b,c> --expires-in=<seconds> [--iam-url=<origin>]
|
|
56
67
|
fabrika control apps list
|
|
57
68
|
fabrika control apps get --app=<id>
|
|
@@ -169,9 +180,27 @@ The control origin is not a credential and takes either form:
|
|
|
169
180
|
--url=<origin> FABRIKA_CONTROL_URL
|
|
170
181
|
|
|
171
182
|
Credentials are read from the ENVIRONMENT ONLY and have no flag, so they cannot reach a CI log or a
|
|
172
|
-
process listing:
|
|
183
|
+
process listing. One of:
|
|
173
184
|
|
|
174
|
-
FABRIKA_CONTROL_KEY
|
|
185
|
+
FABRIKA_CONTROL_KEY a machine \`px_\` credential for the control app; it wins when both are set
|
|
186
|
+
FABRIKA_CONTROL_CREDENTIAL_HELPER a command with \`get\` and \`store\` that holds the refresh token of a
|
|
187
|
+
\`control auth device\` grant (below)
|
|
188
|
+
|
|
189
|
+
\`auth device\` asks IAM for a grant a person approves in the browser (RFC 8628). It prints the page and the
|
|
190
|
+
code on stderr and waits; the person signs in, checks the code, and picks how long the grant lasts (an hour, a
|
|
191
|
+
day or a week). The grant holds the preset's actions at one application, never more than that person may:
|
|
192
|
+
|
|
193
|
+
read deploy.read, data.read, operations.read
|
|
194
|
+
deploy read, and deploy.trigger
|
|
195
|
+
operate deploy, secret.manage, app.manage and operations.triage
|
|
196
|
+
create app.manage wherever the person holds it, with no --app: it also changes and deletes apps
|
|
197
|
+
|
|
198
|
+
The refresh token goes to the helper and nowhere else: the helper runs as \`sh -c '<helper> get|store'\`,
|
|
199
|
+
reads \`origin=<console origin>\` (and, for \`store\`, \`refresh_token=<token>\`) on stdin, and \`get\` prints
|
|
200
|
+
\`refresh_token=<token>\`, or nothing. Every call then trades it for a short-lived access token, and IAM
|
|
201
|
+
rotates it each time; a lock under $XDG_CACHE_HOME/fabrika (~/.cache/fabrika when unset) serializes that
|
|
202
|
+
between processes on this machine. If a refresh's answer is lost, the stored token is spent and the next
|
|
203
|
+
call says to run \`auth device\` again.
|
|
175
204
|
|
|
176
205
|
\`key issue\` mints that credential and therefore authenticates differently — it presents the
|
|
177
206
|
installation's IAM RPC key as transport authentication and its provisioning key as the ISSUING
|
|
@@ -278,17 +307,6 @@ const secret = (variable: string, env: Readonly<Record<string, string | undefine
|
|
|
278
307
|
/** The console's client with a bearer instead of a cookie, and no SSO bounce: there is no browser to send. */
|
|
279
308
|
export type ControlClient = InferRpcClient<ControlRpcContract>
|
|
280
309
|
|
|
281
|
-
/** Plain http may carry the key to loopback only: 127.0.0.0/8, [::1], and the names RFC 6761 reserves for it, `localhost` and `*.localhost`. */
|
|
282
|
-
const LOOPBACK_HOST = /^(?:localhost|.+\.localhost|127\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[::1\])$/
|
|
283
|
-
|
|
284
|
-
/** Which origin a check reads, so its refusals name the right flag and variable. `hint` follows a refusal of the value. */
|
|
285
|
-
interface OriginSource {
|
|
286
|
-
readonly label: string
|
|
287
|
-
readonly flag: string
|
|
288
|
-
readonly variable: string
|
|
289
|
-
readonly hint?: string
|
|
290
|
-
}
|
|
291
|
-
|
|
292
310
|
const CONTROL_ORIGIN: OriginSource = { label: 'Control', flag: 'url', variable: 'FABRIKA_CONTROL_URL' }
|
|
293
311
|
|
|
294
312
|
const IAM_ORIGIN: OriginSource = {
|
|
@@ -299,31 +317,6 @@ const IAM_ORIGIN: OriginSource = {
|
|
|
299
317
|
+ "inside the provider's project, never from this machine.",
|
|
300
318
|
}
|
|
301
319
|
|
|
302
|
-
/**
|
|
303
|
-
* An origin a credential is sent to, checked before the credential goes anywhere: https, or http to a loopback host for
|
|
304
|
-
* local development, and nothing but scheme, host and port. A refusal never repeats the value, which may hold userinfo.
|
|
305
|
-
*/
|
|
306
|
-
export const credentialOrigin = (raw: string | undefined, source: OriginSource): string => {
|
|
307
|
-
const { label, flag, variable } = source
|
|
308
|
-
if (raw === undefined || raw.trim() === '') {
|
|
309
|
-
throw new Error(`${label} origin is required. Pass --${flag}=<origin> or set ${variable}.`)
|
|
310
|
-
}
|
|
311
|
-
const refuse = (reason: string): Error => new Error(source.hint === undefined ? reason : `${reason}. ${source.hint}`)
|
|
312
|
-
let url: URL
|
|
313
|
-
try {
|
|
314
|
-
url = new URL(raw.trim())
|
|
315
|
-
} catch {
|
|
316
|
-
throw refuse(`--${flag} or ${variable} is not a URL`)
|
|
317
|
-
}
|
|
318
|
-
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && LOOPBACK_HOST.test(url.hostname))) {
|
|
319
|
-
throw refuse(`--${flag} or ${variable} must be https; plain http only to localhost, *.localhost, 127.0.0.0/8 or [::1]`)
|
|
320
|
-
}
|
|
321
|
-
if (url.username !== '' || url.password !== '' || url.pathname !== '/' || url.search !== '' || url.hash !== '' || /[?#]/.test(raw)) {
|
|
322
|
-
throw refuse(`--${flag} or ${variable} must be an origin only: no credentials, path, query or fragment`)
|
|
323
|
-
}
|
|
324
|
-
return url.origin
|
|
325
|
-
}
|
|
326
|
-
|
|
327
320
|
const KEY_LABEL = '[FABRIKA_CONTROL_KEY]'
|
|
328
321
|
|
|
329
322
|
/** `text` with the control key cut out: every diagnostic of an area that holds the key passes through it. */
|
|
@@ -355,37 +348,75 @@ const withoutEchoedKey = async (response: Response, key: string): Promise<Respon
|
|
|
355
348
|
return new Response(text, { status: response.status, statusText: response.statusText, headers: response.headers })
|
|
356
349
|
}
|
|
357
350
|
|
|
358
|
-
/** Control's origin and the fetch that carries
|
|
351
|
+
/** Control's origin and the fetch that carries the Control credential to it. */
|
|
359
352
|
export interface ControlTransport {
|
|
360
353
|
readonly origin: string
|
|
361
354
|
readonly fetch: RpcFetch
|
|
355
|
+
/** The credential is a person's device grant, not FABRIKA_CONTROL_KEY. */
|
|
356
|
+
readonly grant: boolean
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** Neither credential is set; both are read from the environment only. */
|
|
360
|
+
export const MISSING_CONTROL_CREDENTIAL = `FABRIKA_CONTROL_KEY is required (environment only — it has no flag), or ${CREDENTIAL_HELPER_VARIABLE} `
|
|
361
|
+
+ 'after `fabrika control auth device`.'
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* The bearer for one request: FABRIKA_CONTROL_KEY when it is set, else an access token for the resource the request
|
|
365
|
+
* calls, refreshed through the grant the credential helper holds.
|
|
366
|
+
*/
|
|
367
|
+
const controlBearer = (
|
|
368
|
+
origin: string,
|
|
369
|
+
env: Readonly<Record<string, string | undefined>>,
|
|
370
|
+
send: RpcFetch,
|
|
371
|
+
oauth: ControlOAuthDependencies | undefined,
|
|
372
|
+
): (input: RequestInfo | URL) => Promise<string> => {
|
|
373
|
+
const key = env['FABRIKA_CONTROL_KEY']?.trim()
|
|
374
|
+
if (key !== undefined && key !== '') return () => Promise.resolve(key)
|
|
375
|
+
const helper = env[CREDENTIAL_HELPER_VARIABLE]?.trim()
|
|
376
|
+
if (helper === undefined || helper === '') throw new Error(MISSING_CONTROL_CREDENTIAL)
|
|
377
|
+
const bearer = controlOAuthBearer(origin, oauth ?? defaultControlOAuthDependencies(helper, env, send))
|
|
378
|
+
return (input) => bearer(controlResourceFor(origin, input))
|
|
362
379
|
}
|
|
363
380
|
|
|
364
381
|
/**
|
|
365
|
-
* The origin from `url` or FABRIKA_CONTROL_URL, the
|
|
366
|
-
*
|
|
382
|
+
* The origin from `url` or FABRIKA_CONTROL_URL, the credential from the environment only, no redirect followed. Every
|
|
383
|
+
* client of the console's origin is built on it.
|
|
367
384
|
*/
|
|
368
385
|
export const controlTransport = (
|
|
369
386
|
url: string | undefined,
|
|
370
387
|
env: Readonly<Record<string, string | undefined>>,
|
|
371
388
|
send: RpcFetch = fetch,
|
|
389
|
+
oauth?: ControlOAuthDependencies,
|
|
372
390
|
): ControlTransport => {
|
|
373
391
|
const origin = credentialOrigin(url ?? env['FABRIKA_CONTROL_URL'], CONTROL_ORIGIN)
|
|
374
|
-
const
|
|
392
|
+
const bearer = controlBearer(origin, env, send, oauth)
|
|
375
393
|
return {
|
|
376
394
|
origin,
|
|
395
|
+
grant: (env['FABRIKA_CONTROL_KEY']?.trim() ?? '') === '',
|
|
377
396
|
fetch: async (input, init) => {
|
|
397
|
+
let token: string
|
|
398
|
+
try {
|
|
399
|
+
token = await bearer(input)
|
|
400
|
+
} catch (error) {
|
|
401
|
+
// The RPC client reads a rejected fetch as "Network request failed"; this answer keeps the reason.
|
|
402
|
+
const message = error instanceof Error ? error.message : 'the Control credential could not be obtained'
|
|
403
|
+
return Response.json({ error: { type: 'credential', message } }, { status: 401 })
|
|
404
|
+
}
|
|
378
405
|
const headers = new Headers(init?.headers)
|
|
379
|
-
headers.set('authorization', `Bearer ${
|
|
406
|
+
headers.set('authorization', `Bearer ${token}`)
|
|
380
407
|
// A redirect would carry the bearer to wherever it points.
|
|
381
|
-
return await withoutEchoedKey(await send(input, { ...init, headers, redirect: 'manual' }),
|
|
408
|
+
return await withoutEchoedKey(await send(input, { ...init, headers, redirect: 'manual' }), token)
|
|
382
409
|
},
|
|
383
410
|
}
|
|
384
411
|
}
|
|
385
412
|
|
|
386
413
|
/** The one client of Control that `fabrika control`, `fabrika env` and `fabrika operations` share. */
|
|
387
|
-
export const connectControl = (
|
|
388
|
-
|
|
414
|
+
export const connectControl = (
|
|
415
|
+
url: string | undefined,
|
|
416
|
+
env: Readonly<Record<string, string | undefined>>,
|
|
417
|
+
oauth?: ControlOAuthDependencies,
|
|
418
|
+
): ControlClient => {
|
|
419
|
+
const transport = controlTransport(url, env, fetch, oauth)
|
|
389
420
|
return createRpcClient<ControlRpcContract>({ baseUrl: `${transport.origin}/api/rpc`, fetch: transport.fetch })
|
|
390
421
|
}
|
|
391
422
|
|
|
@@ -494,6 +525,24 @@ const runKeyIssue = async (flags: Flags, env: Readonly<Record<string, string | u
|
|
|
494
525
|
console.info(flags.json ? JSON.stringify(outcome, null, 2) : outcome.token)
|
|
495
526
|
}
|
|
496
527
|
|
|
528
|
+
const APP_ID = /^[a-z0-9][a-z0-9-]*$/
|
|
529
|
+
|
|
530
|
+
/** `auth device`: the device grant for one preset, stored through the credential helper; nothing goes to stdout. */
|
|
531
|
+
const runAuthDevice = async (flags: Flags, env: Readonly<Record<string, string | undefined>>): Promise<void> => {
|
|
532
|
+
const origin = credentialOrigin(flags.values.get('url') ?? env['FABRIKA_CONTROL_URL'], CONTROL_ORIGIN)
|
|
533
|
+
const raw = required(flags, 'preset')
|
|
534
|
+
const preset = parseControlCliPreset(raw)
|
|
535
|
+
if (preset === null) throw new Error(`--preset must be one of ${CONTROL_CLI_PRESETS.join(', ')}`)
|
|
536
|
+
const app = optional(flags, 'app')
|
|
537
|
+
if (preset === 'create' && app !== undefined) throw new Error('--preset=create holds its action wherever you may, and takes no --app')
|
|
538
|
+
if (preset !== 'create' && (app === undefined || !APP_ID.test(app))) throw new Error(`--preset=${preset} needs --app=<application id>`)
|
|
539
|
+
const helper = env[CREDENTIAL_HELPER_VARIABLE]?.trim()
|
|
540
|
+
if (helper === undefined || helper === '') {
|
|
541
|
+
throw new Error(`${CREDENTIAL_HELPER_VARIABLE} is required: the refresh token is stored through it and never printed`)
|
|
542
|
+
}
|
|
543
|
+
await authorizeDevice({ origin, preset, ...(app === undefined ? {} : { app }) }, defaultControlOAuthDependencies(helper, env, fetch))
|
|
544
|
+
}
|
|
545
|
+
|
|
497
546
|
const decodeIssueKeyResult = (value: unknown): IssueKeyResult => {
|
|
498
547
|
const result = issueKeyResultSchema.safeParse(value)
|
|
499
548
|
if (!result.success) {
|
|
@@ -1068,6 +1117,10 @@ export const runControlCli = async (
|
|
|
1068
1117
|
case undefined:
|
|
1069
1118
|
console.info(USAGE)
|
|
1070
1119
|
return
|
|
1120
|
+
case 'auth':
|
|
1121
|
+
if (verb !== 'device') throw new Error(`Unknown \`control auth\` verb: ${verb ?? '(missing)'}`)
|
|
1122
|
+
await runAuthDevice(flags, env)
|
|
1123
|
+
return
|
|
1071
1124
|
case 'key':
|
|
1072
1125
|
if (verb !== 'issue') throw new Error(`Unknown \`control key\` verb: ${verb ?? '(missing)'}`)
|
|
1073
1126
|
await runKeyIssue(flags, env)
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// The origin check every credential the CLI sends passes before it goes anywhere.
|
|
2
|
+
|
|
3
|
+
/** Plain http may carry a credential to loopback only: 127.0.0.0/8, [::1], and the names RFC 6761 reserves for it, `localhost` and `*.localhost`. */
|
|
4
|
+
const LOOPBACK_HOST = /^(?:localhost|.+\.localhost|127\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[::1\])$/
|
|
5
|
+
|
|
6
|
+
/** Which origin a check reads, so its refusals name the right flag and variable. `hint` follows a refusal of the value. */
|
|
7
|
+
export interface OriginSource {
|
|
8
|
+
readonly label: string
|
|
9
|
+
readonly flag: string
|
|
10
|
+
readonly variable: string
|
|
11
|
+
readonly hint?: string
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
type OriginCheck = { readonly origin: string } | { readonly refusal: 'not_url' | 'scheme' | 'not_origin' }
|
|
15
|
+
|
|
16
|
+
/** `raw`'s origin when it may carry a credential: https, or http to a loopback host, and nothing but scheme, host and port. */
|
|
17
|
+
function checkOrigin(raw: string): OriginCheck {
|
|
18
|
+
let url: URL
|
|
19
|
+
try {
|
|
20
|
+
url = new URL(raw.trim())
|
|
21
|
+
} catch {
|
|
22
|
+
return { refusal: 'not_url' }
|
|
23
|
+
}
|
|
24
|
+
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && LOOPBACK_HOST.test(url.hostname))) return { refusal: 'scheme' }
|
|
25
|
+
if (url.username !== '' || url.password !== '' || url.pathname !== '/' || url.search !== '' || url.hash !== '' || /[?#]/.test(raw)) {
|
|
26
|
+
return { refusal: 'not_origin' }
|
|
27
|
+
}
|
|
28
|
+
return { origin: url.origin }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The origin of a value another party published (an authorization server), or null when no credential may go there. */
|
|
32
|
+
export const credentialOriginOf = (raw: string): string | null => {
|
|
33
|
+
const checked = checkOrigin(raw)
|
|
34
|
+
return 'origin' in checked ? checked.origin : null
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* An origin a credential is sent to, checked before the credential goes anywhere. A refusal never repeats the value,
|
|
39
|
+
* which may hold userinfo.
|
|
40
|
+
*/
|
|
41
|
+
export const credentialOrigin = (raw: string | undefined, source: OriginSource): string => {
|
|
42
|
+
const { label, flag, variable } = source
|
|
43
|
+
if (raw === undefined || raw.trim() === '') {
|
|
44
|
+
throw new Error(`${label} origin is required. Pass --${flag}=<origin> or set ${variable}.`)
|
|
45
|
+
}
|
|
46
|
+
const checked = checkOrigin(raw)
|
|
47
|
+
if ('origin' in checked) return checked.origin
|
|
48
|
+
const reason = {
|
|
49
|
+
not_url: `--${flag} or ${variable} is not a URL`,
|
|
50
|
+
scheme: `--${flag} or ${variable} must be https; plain http only to localhost, *.localhost, 127.0.0.0/8 or [::1]`,
|
|
51
|
+
not_origin: `--${flag} or ${variable} must be an origin only: no credentials, path, query or fragment`,
|
|
52
|
+
}[checked.refusal]
|
|
53
|
+
throw new Error(source.hint === undefined ? reason : `${reason}. ${source.hint}`)
|
|
54
|
+
}
|
package/src/data.ts
CHANGED
|
@@ -66,9 +66,10 @@ The control origin takes either form:
|
|
|
66
66
|
|
|
67
67
|
--url=<origin> FABRIKA_CONTROL_URL
|
|
68
68
|
|
|
69
|
-
The credential is read from the ENVIRONMENT ONLY and has no flag:
|
|
69
|
+
The credential is read from the ENVIRONMENT ONLY and has no flag; one of:
|
|
70
70
|
|
|
71
|
-
FABRIKA_CONTROL_KEY
|
|
71
|
+
FABRIKA_CONTROL_KEY a machine \`px_\` credential for the control app
|
|
72
|
+
FABRIKA_CONTROL_CREDENTIAL_HELPER the helper a \`fabrika control auth device\` grant is stored through
|
|
72
73
|
`
|
|
73
74
|
|
|
74
75
|
type Environment = Readonly<Record<string, string | undefined>>
|
package/src/operations.ts
CHANGED
|
@@ -22,7 +22,8 @@ import type {
|
|
|
22
22
|
} from '@fabrika/operations-contract/operator-api'
|
|
23
23
|
import type { OperationsIssueQuery, OperationsReleaseQuery, OperationsRpcContract } from '@fabrika/operations-contract/rpc'
|
|
24
24
|
import { z } from 'zod'
|
|
25
|
-
import {
|
|
25
|
+
import { type ControlOAuthDependencies, CREDENTIAL_HELPER_VARIABLE } from './control-oauth.js'
|
|
26
|
+
import { controlTransport, MISSING_CONTROL_CREDENTIAL, withoutControlKey } from './control.js'
|
|
26
27
|
import { printable } from './data.js'
|
|
27
28
|
|
|
28
29
|
const USAGE = `fabrika operations — read Operations (errors, releases, health) from the command line
|
|
@@ -71,16 +72,20 @@ Exit codes:
|
|
|
71
72
|
1 the call failed: Control or Operations unreachable, a server error, an unreadable answer, or a procedure this
|
|
72
73
|
installation's release does not offer
|
|
73
74
|
2 usage: an unknown command or option, a bad value, or a selection that matches several sources
|
|
74
|
-
3 the
|
|
75
|
+
3 the credential: neither FABRIKA_CONTROL_KEY nor FABRIKA_CONTROL_CREDENTIAL_HELPER is set, or it was refused,
|
|
76
|
+
or it does not hold \`operations.read\`
|
|
75
77
|
4 not found: no such issue, event or source, or one the key may not read
|
|
76
78
|
|
|
77
79
|
The console origin takes either form:
|
|
78
80
|
|
|
79
81
|
--url=<origin> FABRIKA_CONTROL_URL
|
|
80
82
|
|
|
81
|
-
The credential is read from the ENVIRONMENT ONLY and has no flag:
|
|
83
|
+
The credential is read from the ENVIRONMENT ONLY and has no flag; one of:
|
|
82
84
|
|
|
83
|
-
FABRIKA_CONTROL_KEY
|
|
85
|
+
FABRIKA_CONTROL_KEY a \`px_\` key of the console app holding \`operations.read\`
|
|
86
|
+
FABRIKA_CONTROL_CREDENTIAL_HELPER the helper a \`fabrika control auth device\` grant is stored through
|
|
87
|
+
(any preset but \`create\` reads Operations; a list is empty where the
|
|
88
|
+
person who approved it holds no \`operations.read\`)
|
|
84
89
|
|
|
85
90
|
Mint a key narrowed to \`operations.read\` alone, with a short expiry: docs/reference/operations-errors.md,
|
|
86
91
|
"Reading Operations from the command line".
|
|
@@ -102,6 +107,8 @@ type Environment = Readonly<Record<string, string | undefined>>
|
|
|
102
107
|
export interface OperationsIo {
|
|
103
108
|
readonly env: Environment
|
|
104
109
|
readonly fetch: RpcFetch
|
|
110
|
+
/** Replaces the credential helper, its lock and the clock; only a test passes it. */
|
|
111
|
+
readonly oauth?: ControlOAuthDependencies
|
|
105
112
|
readonly out: (text: string) => void
|
|
106
113
|
readonly err: (text: string) => void
|
|
107
114
|
}
|
|
@@ -513,22 +520,25 @@ const issueLines = (detail: OperationsIssueDetailResponseDto, event: OperationsE
|
|
|
513
520
|
interface Clients {
|
|
514
521
|
readonly operations: InferRpcClient<OperationsRpcContract>
|
|
515
522
|
readonly control: InferRpcClient<ControlRpcContract>
|
|
523
|
+
/** The credential is a person's device grant, whose Operations token is its own. */
|
|
524
|
+
readonly grant: boolean
|
|
516
525
|
}
|
|
517
526
|
|
|
518
527
|
const connect = (args: Args, io: OperationsIo): Clients => {
|
|
519
|
-
const
|
|
520
|
-
if (
|
|
521
|
-
throw new OperationsCliError(OPERATIONS_EXIT.credential,
|
|
528
|
+
const given = (name: string): boolean => (io.env[name]?.trim() ?? '') !== ''
|
|
529
|
+
if (!given('FABRIKA_CONTROL_KEY') && !given(CREDENTIAL_HELPER_VARIABLE)) {
|
|
530
|
+
throw new OperationsCliError(OPERATIONS_EXIT.credential, MISSING_CONTROL_CREDENTIAL)
|
|
522
531
|
}
|
|
523
532
|
let transport: ReturnType<typeof controlTransport>
|
|
524
533
|
try {
|
|
525
|
-
transport = controlTransport(args.url, io.env, io.fetch)
|
|
534
|
+
transport = controlTransport(args.url, io.env, io.fetch, io.oauth)
|
|
526
535
|
} catch (error) {
|
|
527
536
|
throw usageError(error instanceof Error ? error.message : String(error))
|
|
528
537
|
}
|
|
529
538
|
return {
|
|
530
539
|
operations: createRpcClient<OperationsRpcContract>({ baseUrl: `${transport.origin}/operations/api/rpc`, fetch: transport.fetch }),
|
|
531
540
|
control: createRpcClient<ControlRpcContract>({ baseUrl: `${transport.origin}/api/rpc`, fetch: transport.fetch }),
|
|
541
|
+
grant: transport.grant,
|
|
532
542
|
}
|
|
533
543
|
}
|
|
534
544
|
|
|
@@ -537,6 +547,9 @@ const connect = (args: Args, io: OperationsIo): Clients => {
|
|
|
537
547
|
* console's own navigation asks Control which actions the caller holds; so does this, to tell the two apart.
|
|
538
548
|
*/
|
|
539
549
|
const requireRead = async (clients: Clients): Promise<void> => {
|
|
550
|
+
// A grant's token for Control holds no Operations action, so Control's answer cannot tell. Its Operations token holds
|
|
551
|
+
// `operations.read` where the person does; elsewhere a list is empty, as the help says.
|
|
552
|
+
if (clients.grant) return
|
|
540
553
|
const access = parse(consoleAccessSchema, await clients.control.consoleAccess(), 'console access')
|
|
541
554
|
const read = OPERATIONS_ACTIONS.READ
|
|
542
555
|
if (access.global.includes(read) || access.scopes.some((scope) => scope.actions.includes(read))) return
|
|
@@ -686,6 +699,8 @@ const rpcFailure = (error: RpcError): OperationsCliError => {
|
|
|
686
699
|
`This installation's release does not offer the call; retrying will not change that — ${said}`,
|
|
687
700
|
)
|
|
688
701
|
}
|
|
702
|
+
// The device grant's own refusal (no grant stored, expired, not covering Operations): its message says what to do.
|
|
703
|
+
if (error.type === 'credential') return new OperationsCliError(OPERATIONS_EXIT.credential, error.message)
|
|
689
704
|
if (error.httpStatus === 401) {
|
|
690
705
|
return new OperationsCliError(OPERATIONS_EXIT.credential, `The console refused FABRIKA_CONTROL_KEY (unknown, expired or revoked) — ${said}`)
|
|
691
706
|
}
|
package/types/src/connect.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
|
|
1
|
+
import { type ControlOAuthDependencies } from './control-oauth.js';
|
|
2
|
+
export declare const CONNECT_USAGE = "fabrika connect \u2014 vendor another application's export\n\nUsage:\n fabrika connect add <app>/<export>@<version> --consumer=<this app's id> --env=<env> [--url=<control origin>]\n Write fabrika/connect/<app>.<export>.v<version>.ts.\n fabrika connect pull <app>/<export>@<version> --consumer=<this app's id> --env=<env> [--url=<control origin>]\n Rewrite that snapshot from what the owner's environment approved now.\n\nRun from the application root. Both read the export the owner's environment <env> approved for the consumer from\nControl (FABRIKA_CONTROL_URL or --url), with a machine key that holds deploy.read on the consumer, read from\nFABRIKA_CONTROL_KEY in the environment only, or with the grant `fabrika control auth device` stored through\nFABRIKA_CONTROL_CREDENTIAL_HELPER. The origin is https; plain http only for localhost. `add` refuses an\nexisting snapshot and prints what to add to src/app-kit.ts and to the endpoints that call it; `pull` refuses a missing one\nand says whether the digest changed. The platform writes each import's address and key when it deploys the consumer.\n";
|
|
2
3
|
export interface ConnectCommandDependencies {
|
|
3
4
|
/** The application root. */
|
|
4
5
|
readonly cwd: string;
|
|
@@ -8,6 +9,8 @@ export interface ConnectCommandDependencies {
|
|
|
8
9
|
readonly write: (line: string) => void;
|
|
9
10
|
/** Guidance for the person running it. */
|
|
10
11
|
readonly note: (line: string) => void;
|
|
12
|
+
/** Replaces the credential helper, its lock and the clock; only a test passes it. */
|
|
13
|
+
readonly oauth?: ControlOAuthDependencies;
|
|
11
14
|
}
|
|
12
15
|
/**
|
|
13
16
|
* Every line and error leaves with the Control key cut out. No diagnostic quotes the answer; this is defence in depth
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { RpcFetch } from '@fabrika/app';
|
|
2
|
+
import { type ControlCliPreset } from '@fabrika/control-contract';
|
|
3
|
+
export declare const CREDENTIAL_HELPER_VARIABLE = "FABRIKA_CONTROL_CREDENTIAL_HELPER";
|
|
4
|
+
/** Where the refresh token lives between runs: a command with `get` and `store`, in the style of a git credential helper. */
|
|
5
|
+
export interface CredentialHelper {
|
|
6
|
+
/** The refresh token stored for `origin`, or null when none is. */
|
|
7
|
+
get(origin: string): Promise<string | null>;
|
|
8
|
+
store(origin: string, refreshToken: string): Promise<void>;
|
|
9
|
+
}
|
|
10
|
+
/** Takes the one lock that serializes refresh-token rotation for `origin` on this machine; resolves to its release. */
|
|
11
|
+
export type CredentialLock = (origin: string) => Promise<() => Promise<void>>;
|
|
12
|
+
export interface ControlOAuthDependencies {
|
|
13
|
+
readonly fetch: RpcFetch;
|
|
14
|
+
readonly helper: CredentialHelper;
|
|
15
|
+
readonly lock: CredentialLock;
|
|
16
|
+
/** Milliseconds. */
|
|
17
|
+
readonly now: () => number;
|
|
18
|
+
readonly sleep: (ms: number) => Promise<void>;
|
|
19
|
+
/** Guidance for the person running the command; it goes to stderr. */
|
|
20
|
+
readonly note: (line: string) => void;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* `command` run by the shell with the action as its one argument, as git runs a credential helper. Its stdin carries
|
|
24
|
+
* `origin=<origin>` and, for `store`, `refresh_token=<token>`; `get` prints `refresh_token=<token>`, or nothing.
|
|
25
|
+
*/
|
|
26
|
+
export declare function commandCredentialHelper(command: string): CredentialHelper;
|
|
27
|
+
/**
|
|
28
|
+
* An exclusive lock file per origin under `directory`, created whole by `link` so it never exists empty, and naming its
|
|
29
|
+
* holder. A dead holder's file is taken over; release removes only this holding's own file.
|
|
30
|
+
*/
|
|
31
|
+
export declare function fileCredentialLock(directory: string, waitMs?: number): CredentialLock;
|
|
32
|
+
/** The helper `command` names, the lock under the user's cache directory, and the real clock. */
|
|
33
|
+
export declare function defaultControlOAuthDependencies(command: string, env: Readonly<Record<string, string | undefined>>, send: RpcFetch): ControlOAuthDependencies;
|
|
34
|
+
export interface DeviceGrantRequest {
|
|
35
|
+
/** Control's origin, already checked. */
|
|
36
|
+
readonly origin: string;
|
|
37
|
+
readonly preset: ControlCliPreset;
|
|
38
|
+
/** The application every preset but `create` holds its actions at. */
|
|
39
|
+
readonly app?: string;
|
|
40
|
+
}
|
|
41
|
+
/** The preset `raw` names, or null. */
|
|
42
|
+
export declare const parseControlCliPreset: (raw: string) => ControlCliPreset | null;
|
|
43
|
+
/**
|
|
44
|
+
* The device grant: start it for the preset's resources, tell the person where to approve it, poll until they do, and
|
|
45
|
+
* store the refresh token through the helper. The access token of the first resource is dropped; a call refreshes its own.
|
|
46
|
+
*/
|
|
47
|
+
export declare function authorizeDevice(request: DeviceGrantRequest, deps: ControlOAuthDependencies): Promise<void>;
|
|
48
|
+
/** A current access token for one of the console's resources. */
|
|
49
|
+
export type ControlBearer = (resource: string) => Promise<string>;
|
|
50
|
+
/**
|
|
51
|
+
* Access tokens for `origin`'s resources, refreshed through the helper's grant as a call needs them and kept in this
|
|
52
|
+
* process's memory only. Concurrent calls for one resource share one refresh.
|
|
53
|
+
*/
|
|
54
|
+
export declare function controlOAuthBearer(origin: string, deps: ControlOAuthDependencies): ControlBearer;
|
|
55
|
+
/** The console resource a request needs: the Operations RPC, or Control's own. A bearer never leaves Control's origin. */
|
|
56
|
+
export declare function controlResourceFor(origin: string, input: RequestInfo | URL): string;
|
package/types/src/control.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type InferRpcClient, type RpcFetch } from '@fabrika/app';
|
|
2
2
|
import type { AppEnvDto, ControlRpcContract, DeploymentNamespaceDto, PlanDeploymentNamespaceResponse } from '@fabrika/control-contract';
|
|
3
|
-
declare const USAGE = "fabrika control \u2014 operate the Delivery control plane\n\nUsage:\n fabrika control key issue --label=<name> --permissions=<a,b,c> --expires-in=<seconds> [--iam-url=<origin>]\n fabrika control apps list\n fabrika control apps get --app=<id>\n fabrika control apps environments list --app=<id>\n fabrika control apps environments put --provider=<name> --app=<id> --env=<name> --manifest=<path>\n [--domain=<host>] [--public-origin=<url>] [--trigger-ref=<ref>] [--namespace=<id>]\n [--cross-origin=<origin> ...] [--kind=standard|dev]\n fabrika control apps environments suspend --app=<id> --env=<name>\n fabrika control apps environments resume --app=<id> --env=<name>\n fabrika control apps variables list --app=<id>\n fabrika control apps variables put --app=<id> --name=<name> --value=<text> [--env=<name>] [--not-secret]\n fabrika control apps variables delete --app=<id> --name=<name> [--env=<name>]\n fabrika control apps secrets list --app=<id>\n fabrika control apps secrets put --app=<id> --name=<name> [--env=<name>] (the value on stdin)\n fabrika control apps secrets delete --app=<id> --name=<name> [--env=<name>]\n fabrika control register --provider=<name> --app=<id> --repo=<url> --env=<name> --manifest=<path>\n [--domain=<host>] [--public-origin=<url>] [--trigger-ref=<ref>]\n [--namespace=<id>] [--installation-id=<n|none>] [--cross-origin=<origin> ...]\n fabrika control namespaces list\n fabrika control namespaces get --namespace=<id>\n fabrika control namespaces plan --namespace=<id> --env=<name> --preset=<cheap|mid|full> [placement]\n fabrika control namespaces create --namespace=<id> --env=<name> --preset=<cheap|mid|full> [placement]\n fabrika control namespaces reconcile --namespace=<id>\n fabrika control namespaces update --namespace=<id> --proxy-source=current\n fabrika control namespaces remove --namespace=<id>\n fabrika control namespaces release-claims --namespace=<id> --app=<id> --env=<name>\n fabrika control deploy --app=<id> --env=<name> [--ref=<ref>]\n fabrika control runs list [--app=<id>] [--env=<name>] [--limit=<n>]\n fabrika control runs get --run=<id>\n fabrika control runs log --run=<id>\n\n`register` CREATES an app and refuses a second one with the same id. Re-registering a changed\nmanifest \u2014 a new import document, or a new `zerops.yaml` of an app without a contract \u2014 is\n`apps environments put`, which replaces one environment's envelopes and leaves the app row alone. A\ncontract app's deploy registers the `zerops.yaml` of its commit itself.\n\nA manifest that publishes the app through the namespace proxy is routed by HOST, so `--domain` is\nREQUIRED for it \u2014 on `register` and on `apps environments put` alike \u2014 and a registration without one is\nrefused before anything is created. `namespaces get` lists the hosts a `zerops-subdomain` namespace\nserves and which of them are still free; a custom-domain namespace serves the domain you bound to its\nproxy. A manifest with no proxy target needs no domain.\n\n`apps environments suspend` takes an environment offline in an incident, such as a compromised or leaked application.\nBehind a Zerops namespace proxy every request to it answers 503 once the republished proxy is live, which takes the\nminutes of a proxy build; `namespaces get` follows it. A namespace pinned to an older proxy source is refused with the\nre-pin to run first. On Cloudflare the environment's object goes into maintenance `closed`. `resume` restores the\nrouting it had, or on Cloudflare the maintenance mode it was in. Neither stops the application's service, nor\nrevokes a key. Repeating either is a retry.\n\nA variable's value is stored and printed in clear, so `apps variables put` refuses one that looks like a\ncredential (by its name, such as `*_TOKEN` or `*_PASSWORD`, or by its value) and names `apps secrets put` instead.\n`--not-secret` stores it anyway, for a value you have checked is not one. A secret's value is write-only: `apps secrets put`\nreads it from STDIN, never from a flag, so it reaches neither shell history nor a process listing, and\none trailing newline is dropped. No command prints it back; `apps secrets list` shows names, scope and\nstorage only. Generate one in the pipe:\n\n openssl rand -base64 32 | fabrika control apps secrets put --app=<id> --name=<name>\n\n`--public-origin` is where IAM may return a signed-in person: without one, sign-in to the environment is\nrefused. When `register` is given none and the namespace lists `--domain` among its hosts, it sets\n`https://<domain>` and says so on stderr. A custom domain needs the flag.\n\n`--cross-origin` names an origin whose pages may call the environment's cross-origin endpoints (ADR-0022), and\nrepeats: the flags given are the environment's whole list. Each is an exact origin with a literal host\n(`https://app.example.com`; `http://` only for a local one), never the environment's own domain, at most 16.\n`apps environments put` without the flag keeps the stored list, and a lone empty `--cross-origin=` clears it.\nOn Zerops the change reaches the namespace proxy at once; on Cloudflare the next deploy of the environment\napplies it.\n\n`--installation-id` has three states: omitted resolves the installation from the repository owner's\nconnected GitHub App, `none` registers an anonymous PUBLIC repository source, and a number names one\ninstallation outright. With `none`, control reads the repository once without a token and refuses one\nGitHub hides: a private repository needs the GitHub App connected in the console first.\n\n`--trigger-ref` is the git ref whose push deploys the environment; without it the environment deploys only\non `deploy`. A bare name is a branch: `--trigger-ref=deploy/prod` is stored as `refs/heads/deploy/prod`.\nA full ref is kept as given: `refs/heads/<branch>`, `refs/tags/<tag>`, or a `*` glob such as\n`refs/tags/v*`, which deploys every matching tag. A tag always needs the `refs/tags/` form. Each\nenvironment of an app needs its own trigger ref. Branches named `fabrika/\u2026` are reserved for MCP\nworkspaces and are never a trigger ref.\n\nNamespace placement options, each defaulting to what the preset would choose:\n\n --project=<name> the provider project the namespace owns; on Zerops the default is\n fabrika-<env>-<namespace id>, beside the installation's fabrika-<env>\n --core-package=<LIGHT|SERIOUS> defaults to LIGHT on every environment, `prod` included (ADR-0038).\n SERIOUS is a deliberate choice: a project cannot be downgraded again\n --public-access=<custom-domain|zerops-subdomain>\n --exclusive-app=<id> required by, and only by, the `full` preset\n --postgres-type=<type> the `cheap` preset's shared PostgreSQL; on Zerops postgresql:single@18\n (default) or postgresql:ha@18, which keeps its data through a node loss.\n Fixed once created\n --postgres-profile=<profile> its profile, given together with --postgres-type: oltp-hobby for single,\n oltp-staging (about $11) or oltp-production (about $72) for HA\n\n`namespaces plan` is a preview and changes nothing. It prints one `<path>\\t<value>` row per field of\nthe plan, keyed by its path in `--json`; a multi-line value such as the proxy's descriptor file is shown\nby size only. `namespaces create` commits that exact plan \u2014 the\nsame two steps the console's form takes \u2014 and returns as soon as the placement is recorded: provisioning\nruns behind the control queue and takes minutes, so the state comes back `pending`. Follow it with\n`namespaces get` or `namespaces list`; nothing needs to stay connected. `namespaces remove` frees the id\nof a placement no application is registered in. It deletes nothing at the provider and prints, on stderr,\nthe provider resources it stopped tracking. `namespaces update --proxy-source=current` re-pins a placement's\nproxy to the source this control plane deploys new placements from \u2014 a placement keeps the one it was created\nwith until you do \u2014 and queues the reconcile that rebuilds the proxy from it; a `failed` placement accepts it.\n\n`namespaces release-claims` frees the resource names one app environment holds in a placement, which an\nenvironment or app delete otherwise refuses over. Delete those resources at the provider first: the release\nreads each one back and refuses, naming it, while any still exists. It prints one released key per line.\n\nEvery command accepts --json, which prints the procedure's result verbatim.\n\nThe control origin is not a credential and takes either form:\n\n --url=<origin> FABRIKA_CONTROL_URL\n\nCredentials are read from the ENVIRONMENT ONLY and have no flag, so they cannot reach a CI log or a\nprocess listing:\n\n FABRIKA_CONTROL_KEY required a machine `px_` credential for the control app\n\n`key issue` mints that credential and therefore authenticates differently \u2014 it presents the\ninstallation's IAM RPC key as transport authentication and its provisioning key as the ISSUING\ncredential. Every key expires: `--expires-in` is required and at most 2592000 (30 days). Both\ncredentials are read from the environment only:\n\n FABRIKA_IAM_RPC_URL required IAM's PUBLIC origin, or --iam-url\n FABRIKA_IAM_RPC_KEY required the installation's IAM RPC key\n FABRIKA_IAM_PROVISIONING_KEY required the installation's seeded `px_` provisioning key\n FABRIKA_CONTROL_APP_ID optional the control app's IAM id (default `vozka`)\n\nThe PUBLIC origin is the `https://` address the installation answers on \u2014 the one `platform admin`\nand `platform init` print in their closing block, and the value `FABRIKA_IAM_ISSUER` holds on the\ncontrol service. It is NOT the private hostname the services use between themselves: `http://iam:3000`\nresolves inside the provider's project and nowhere else, so from here it only ever fails to connect.\n\nConnecting a GitHub source is NOT here and will not be: App creation is a browser flow whose\nauthorization requires a human principal (ADR-0029). Use Settings \u2192 Source in the console.\n";
|
|
3
|
+
import { type ControlOAuthDependencies } from './control-oauth.js';
|
|
4
|
+
declare const USAGE = "fabrika control \u2014 operate the Delivery control plane\n\nUsage:\n fabrika control auth device --preset=<read|deploy|operate|create> [--app=<id>]\n fabrika control key issue --label=<name> --permissions=<a,b,c> --expires-in=<seconds> [--iam-url=<origin>]\n fabrika control apps list\n fabrika control apps get --app=<id>\n fabrika control apps environments list --app=<id>\n fabrika control apps environments put --provider=<name> --app=<id> --env=<name> --manifest=<path>\n [--domain=<host>] [--public-origin=<url>] [--trigger-ref=<ref>] [--namespace=<id>]\n [--cross-origin=<origin> ...] [--kind=standard|dev]\n fabrika control apps environments suspend --app=<id> --env=<name>\n fabrika control apps environments resume --app=<id> --env=<name>\n fabrika control apps variables list --app=<id>\n fabrika control apps variables put --app=<id> --name=<name> --value=<text> [--env=<name>] [--not-secret]\n fabrika control apps variables delete --app=<id> --name=<name> [--env=<name>]\n fabrika control apps secrets list --app=<id>\n fabrika control apps secrets put --app=<id> --name=<name> [--env=<name>] (the value on stdin)\n fabrika control apps secrets delete --app=<id> --name=<name> [--env=<name>]\n fabrika control register --provider=<name> --app=<id> --repo=<url> --env=<name> --manifest=<path>\n [--domain=<host>] [--public-origin=<url>] [--trigger-ref=<ref>]\n [--namespace=<id>] [--installation-id=<n|none>] [--cross-origin=<origin> ...]\n fabrika control namespaces list\n fabrika control namespaces get --namespace=<id>\n fabrika control namespaces plan --namespace=<id> --env=<name> --preset=<cheap|mid|full> [placement]\n fabrika control namespaces create --namespace=<id> --env=<name> --preset=<cheap|mid|full> [placement]\n fabrika control namespaces reconcile --namespace=<id>\n fabrika control namespaces update --namespace=<id> --proxy-source=current\n fabrika control namespaces remove --namespace=<id>\n fabrika control namespaces release-claims --namespace=<id> --app=<id> --env=<name>\n fabrika control deploy --app=<id> --env=<name> [--ref=<ref>]\n fabrika control runs list [--app=<id>] [--env=<name>] [--limit=<n>]\n fabrika control runs get --run=<id>\n fabrika control runs log --run=<id>\n\n`register` CREATES an app and refuses a second one with the same id. Re-registering a changed\nmanifest \u2014 a new import document, or a new `zerops.yaml` of an app without a contract \u2014 is\n`apps environments put`, which replaces one environment's envelopes and leaves the app row alone. A\ncontract app's deploy registers the `zerops.yaml` of its commit itself.\n\nA manifest that publishes the app through the namespace proxy is routed by HOST, so `--domain` is\nREQUIRED for it \u2014 on `register` and on `apps environments put` alike \u2014 and a registration without one is\nrefused before anything is created. `namespaces get` lists the hosts a `zerops-subdomain` namespace\nserves and which of them are still free; a custom-domain namespace serves the domain you bound to its\nproxy. A manifest with no proxy target needs no domain.\n\n`apps environments suspend` takes an environment offline in an incident, such as a compromised or leaked application.\nBehind a Zerops namespace proxy every request to it answers 503 once the republished proxy is live, which takes the\nminutes of a proxy build; `namespaces get` follows it. A namespace pinned to an older proxy source is refused with the\nre-pin to run first. On Cloudflare the environment's object goes into maintenance `closed`. `resume` restores the\nrouting it had, or on Cloudflare the maintenance mode it was in. Neither stops the application's service, nor\nrevokes a key. Repeating either is a retry.\n\nA variable's value is stored and printed in clear, so `apps variables put` refuses one that looks like a\ncredential (by its name, such as `*_TOKEN` or `*_PASSWORD`, or by its value) and names `apps secrets put` instead.\n`--not-secret` stores it anyway, for a value you have checked is not one. A secret's value is write-only: `apps secrets put`\nreads it from STDIN, never from a flag, so it reaches neither shell history nor a process listing, and\none trailing newline is dropped. No command prints it back; `apps secrets list` shows names, scope and\nstorage only. Generate one in the pipe:\n\n openssl rand -base64 32 | fabrika control apps secrets put --app=<id> --name=<name>\n\n`--public-origin` is where IAM may return a signed-in person: without one, sign-in to the environment is\nrefused. When `register` is given none and the namespace lists `--domain` among its hosts, it sets\n`https://<domain>` and says so on stderr. A custom domain needs the flag.\n\n`--cross-origin` names an origin whose pages may call the environment's cross-origin endpoints (ADR-0022), and\nrepeats: the flags given are the environment's whole list. Each is an exact origin with a literal host\n(`https://app.example.com`; `http://` only for a local one), never the environment's own domain, at most 16.\n`apps environments put` without the flag keeps the stored list, and a lone empty `--cross-origin=` clears it.\nOn Zerops the change reaches the namespace proxy at once; on Cloudflare the next deploy of the environment\napplies it.\n\n`--installation-id` has three states: omitted resolves the installation from the repository owner's\nconnected GitHub App, `none` registers an anonymous PUBLIC repository source, and a number names one\ninstallation outright. With `none`, control reads the repository once without a token and refuses one\nGitHub hides: a private repository needs the GitHub App connected in the console first.\n\n`--trigger-ref` is the git ref whose push deploys the environment; without it the environment deploys only\non `deploy`. A bare name is a branch: `--trigger-ref=deploy/prod` is stored as `refs/heads/deploy/prod`.\nA full ref is kept as given: `refs/heads/<branch>`, `refs/tags/<tag>`, or a `*` glob such as\n`refs/tags/v*`, which deploys every matching tag. A tag always needs the `refs/tags/` form. Each\nenvironment of an app needs its own trigger ref. Branches named `fabrika/\u2026` are reserved for MCP\nworkspaces and are never a trigger ref.\n\nNamespace placement options, each defaulting to what the preset would choose:\n\n --project=<name> the provider project the namespace owns; on Zerops the default is\n fabrika-<env>-<namespace id>, beside the installation's fabrika-<env>\n --core-package=<LIGHT|SERIOUS> defaults to LIGHT on every environment, `prod` included (ADR-0038).\n SERIOUS is a deliberate choice: a project cannot be downgraded again\n --public-access=<custom-domain|zerops-subdomain>\n --exclusive-app=<id> required by, and only by, the `full` preset\n --postgres-type=<type> the `cheap` preset's shared PostgreSQL; on Zerops postgresql:single@18\n (default) or postgresql:ha@18, which keeps its data through a node loss.\n Fixed once created\n --postgres-profile=<profile> its profile, given together with --postgres-type: oltp-hobby for single,\n oltp-staging (about $11) or oltp-production (about $72) for HA\n\n`namespaces plan` is a preview and changes nothing. It prints one `<path>\\t<value>` row per field of\nthe plan, keyed by its path in `--json`; a multi-line value such as the proxy's descriptor file is shown\nby size only. `namespaces create` commits that exact plan \u2014 the\nsame two steps the console's form takes \u2014 and returns as soon as the placement is recorded: provisioning\nruns behind the control queue and takes minutes, so the state comes back `pending`. Follow it with\n`namespaces get` or `namespaces list`; nothing needs to stay connected. `namespaces remove` frees the id\nof a placement no application is registered in. It deletes nothing at the provider and prints, on stderr,\nthe provider resources it stopped tracking. `namespaces update --proxy-source=current` re-pins a placement's\nproxy to the source this control plane deploys new placements from \u2014 a placement keeps the one it was created\nwith until you do \u2014 and queues the reconcile that rebuilds the proxy from it; a `failed` placement accepts it.\n\n`namespaces release-claims` frees the resource names one app environment holds in a placement, which an\nenvironment or app delete otherwise refuses over. Delete those resources at the provider first: the release\nreads each one back and refuses, naming it, while any still exists. It prints one released key per line.\n\nEvery command accepts --json, which prints the procedure's result verbatim.\n\nThe control origin is not a credential and takes either form:\n\n --url=<origin> FABRIKA_CONTROL_URL\n\nCredentials are read from the ENVIRONMENT ONLY and have no flag, so they cannot reach a CI log or a\nprocess listing. One of:\n\n FABRIKA_CONTROL_KEY a machine `px_` credential for the control app; it wins when both are set\n FABRIKA_CONTROL_CREDENTIAL_HELPER a command with `get` and `store` that holds the refresh token of a\n `control auth device` grant (below)\n\n`auth device` asks IAM for a grant a person approves in the browser (RFC 8628). It prints the page and the\ncode on stderr and waits; the person signs in, checks the code, and picks how long the grant lasts (an hour, a\nday or a week). The grant holds the preset's actions at one application, never more than that person may:\n\n read deploy.read, data.read, operations.read\n deploy read, and deploy.trigger\n operate deploy, secret.manage, app.manage and operations.triage\n create app.manage wherever the person holds it, with no --app: it also changes and deletes apps\n\nThe refresh token goes to the helper and nowhere else: the helper runs as `sh -c '<helper> get|store'`,\nreads `origin=<console origin>` (and, for `store`, `refresh_token=<token>`) on stdin, and `get` prints\n`refresh_token=<token>`, or nothing. Every call then trades it for a short-lived access token, and IAM\nrotates it each time; a lock under $XDG_CACHE_HOME/fabrika (~/.cache/fabrika when unset) serializes that\nbetween processes on this machine. If a refresh's answer is lost, the stored token is spent and the next\ncall says to run `auth device` again.\n\n`key issue` mints that credential and therefore authenticates differently \u2014 it presents the\ninstallation's IAM RPC key as transport authentication and its provisioning key as the ISSUING\ncredential. Every key expires: `--expires-in` is required and at most 2592000 (30 days). Both\ncredentials are read from the environment only:\n\n FABRIKA_IAM_RPC_URL required IAM's PUBLIC origin, or --iam-url\n FABRIKA_IAM_RPC_KEY required the installation's IAM RPC key\n FABRIKA_IAM_PROVISIONING_KEY required the installation's seeded `px_` provisioning key\n FABRIKA_CONTROL_APP_ID optional the control app's IAM id (default `vozka`)\n\nThe PUBLIC origin is the `https://` address the installation answers on \u2014 the one `platform admin`\nand `platform init` print in their closing block, and the value `FABRIKA_IAM_ISSUER` holds on the\ncontrol service. It is NOT the private hostname the services use between themselves: `http://iam:3000`\nresolves inside the provider's project and nowhere else, so from here it only ever fails to connect.\n\nConnecting a GitHub source is NOT here and will not be: App creation is a browser flow whose\nauthorization requires a human principal (ADR-0029). Use Settings \u2192 Source in the console.\n";
|
|
4
5
|
interface Flags {
|
|
5
6
|
readonly values: ReadonlyMap<string, string>;
|
|
6
7
|
/** Every value of every option, in order; `values` keeps the last. Only a repeatable option reads it. */
|
|
@@ -14,32 +15,24 @@ interface Flags {
|
|
|
14
15
|
export declare const parseControlFlags: (argv: readonly string[]) => Flags;
|
|
15
16
|
/** The console's client with a bearer instead of a cookie, and no SSO bounce: there is no browser to send. */
|
|
16
17
|
export type ControlClient = InferRpcClient<ControlRpcContract>;
|
|
17
|
-
/** Which origin a check reads, so its refusals name the right flag and variable. `hint` follows a refusal of the value. */
|
|
18
|
-
interface OriginSource {
|
|
19
|
-
readonly label: string;
|
|
20
|
-
readonly flag: string;
|
|
21
|
-
readonly variable: string;
|
|
22
|
-
readonly hint?: string;
|
|
23
|
-
}
|
|
24
|
-
/**
|
|
25
|
-
* An origin a credential is sent to, checked before the credential goes anywhere: https, or http to a loopback host for
|
|
26
|
-
* local development, and nothing but scheme, host and port. A refusal never repeats the value, which may hold userinfo.
|
|
27
|
-
*/
|
|
28
|
-
export declare const credentialOrigin: (raw: string | undefined, source: OriginSource) => string;
|
|
29
18
|
/** `text` with the control key cut out: every diagnostic of an area that holds the key passes through it. */
|
|
30
19
|
export declare const withoutControlKey: (text: string, env: Readonly<Record<string, string | undefined>>) => string;
|
|
31
|
-
/** Control's origin and the fetch that carries
|
|
20
|
+
/** Control's origin and the fetch that carries the Control credential to it. */
|
|
32
21
|
export interface ControlTransport {
|
|
33
22
|
readonly origin: string;
|
|
34
23
|
readonly fetch: RpcFetch;
|
|
24
|
+
/** The credential is a person's device grant, not FABRIKA_CONTROL_KEY. */
|
|
25
|
+
readonly grant: boolean;
|
|
35
26
|
}
|
|
27
|
+
/** Neither credential is set; both are read from the environment only. */
|
|
28
|
+
export declare const MISSING_CONTROL_CREDENTIAL: string;
|
|
36
29
|
/**
|
|
37
|
-
* The origin from `url` or FABRIKA_CONTROL_URL, the
|
|
38
|
-
*
|
|
30
|
+
* The origin from `url` or FABRIKA_CONTROL_URL, the credential from the environment only, no redirect followed. Every
|
|
31
|
+
* client of the console's origin is built on it.
|
|
39
32
|
*/
|
|
40
|
-
export declare const controlTransport: (url: string | undefined, env: Readonly<Record<string, string | undefined>>, send?: RpcFetch) => ControlTransport;
|
|
33
|
+
export declare const controlTransport: (url: string | undefined, env: Readonly<Record<string, string | undefined>>, send?: RpcFetch, oauth?: ControlOAuthDependencies) => ControlTransport;
|
|
41
34
|
/** The one client of Control that `fabrika control`, `fabrika env` and `fabrika operations` share. */
|
|
42
|
-
export declare const connectControl: (url: string | undefined, env: Readonly<Record<string, string | undefined
|
|
35
|
+
export declare const connectControl: (url: string | undefined, env: Readonly<Record<string, string | undefined>>, oauth?: ControlOAuthDependencies) => ControlClient;
|
|
43
36
|
/** The exact text `app build` would write, and the provider whose envelope carries it. */
|
|
44
37
|
export interface CompiledManifest {
|
|
45
38
|
readonly provider: string;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Which origin a check reads, so its refusals name the right flag and variable. `hint` follows a refusal of the value. */
|
|
2
|
+
export interface OriginSource {
|
|
3
|
+
readonly label: string;
|
|
4
|
+
readonly flag: string;
|
|
5
|
+
readonly variable: string;
|
|
6
|
+
readonly hint?: string;
|
|
7
|
+
}
|
|
8
|
+
/** The origin of a value another party published (an authorization server), or null when no credential may go there. */
|
|
9
|
+
export declare const credentialOriginOf: (raw: string) => string | null;
|
|
10
|
+
/**
|
|
11
|
+
* An origin a credential is sent to, checked before the credential goes anywhere. A refusal never repeats the value,
|
|
12
|
+
* which may hold userinfo.
|
|
13
|
+
*/
|
|
14
|
+
export declare const credentialOrigin: (raw: string | undefined, source: OriginSource) => string;
|
package/types/src/data.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
declare const USAGE = "fabrika env \u2014 an application environment's data, through the control plane\n\nUsage:\n fabrika env inspect <app> <env> [--content] [--json]\n fabrika env maintenance <app> <env> <open|read-only|closed> [--json]\n fabrika env operations <app> <env> [--json]\n fabrika env recover <app> <env> <operationId> <resume|open> [--json]\n fabrika env backups <app> <env> [--json]\n fabrika env backups schedule <app> <env> [on|off] [--json]\n fabrika env restore <app> <env> --at=<time> [--json]\n\n`inspect` prints the environment's data view: the object's maintenance mode and generation, the database size and\neach table's row count (a count at 100000 reads `100000+`: it is capped), the applied migrations,\nthe scheduler's alarm, each job's last run, file and webhook counts, and when the application last failed to boot.\nIt needs `data.read`. `--content` adds the boot failure's message and stack, which are the application's own text,\nand needs `data.content.read` granted globally.\n\n`maintenance` puts the environment into a mode: `read-only` refuses writes, `closed` refuses every request, and\n`open` serves again. It starts a data operation and prints it; `operations` follows it. It needs `data.manage`.\n\n`operations` lists the environment's data operations, newest first, one row each:\n<id> <kind> <state> <step> <target mode> <generation> <error code> <created at>.\n\n`recover` fences an environment whose operation is stuck in `closed` at a fresh generation, then `resume`s that\noperation from its recorded step, or `open`s the environment. A failed operation can only be opened past. It needs\n`data.manage`.\n\n`backups` lists the environment's consistent backups, newest first, one row each:\n<id> <object> <state> <created at> <size bytes> <parts> <tables> <rehearsal> <rehearsal code> <error code> <expired>\n<pre-migration>.\nA backup counts as `succeeded` only once its rehearsal, an import into a scratch object, passed. One older than 30\ndays is `expired` and never offered for a restore. The last column is `pre-migration` for the backup a migration\ntakes before its deploy, and `-` for any other, such as a daily backup or a restore's. It needs `data.read`.\n\n`backups schedule` prints whether the environment takes a daily backup; `on` or `off` sets it, which needs\n`data.manage`. Turning it off stops the daily backup only: the backup before a migration still runs.\n\n`restore` brings back the environment's data as it was at `--at`, an ISO 8601 time with an offset in the past. It\nis a side restore: the serving object is frozen read-only and backed up, the backup is imported into a new clone\nobject, ordinary traffic is pointed at the clone, which serves the current data from then on, and the original is\nrewound to that time and kept in `inspect`, serving nothing, for inspection. It starts a data operation and prints\nit; `operations` follows it. It needs `data.manage`.\n\nA release of the control plane that does not offer a command answers that it is not available; retrying does not\nchange that. An environment the caller may not see answers `not_found`, as one that does not exist.\n\nstdout carries data only; progress and follow-up commands go to stderr. `--json` prints the result as JSON.\n\nThe control origin takes either form:\n\n --url=<origin> FABRIKA_CONTROL_URL\n\nThe credential is read from the ENVIRONMENT ONLY and has no flag:\n\n FABRIKA_CONTROL_KEY
|
|
1
|
+
declare const USAGE = "fabrika env \u2014 an application environment's data, through the control plane\n\nUsage:\n fabrika env inspect <app> <env> [--content] [--json]\n fabrika env maintenance <app> <env> <open|read-only|closed> [--json]\n fabrika env operations <app> <env> [--json]\n fabrika env recover <app> <env> <operationId> <resume|open> [--json]\n fabrika env backups <app> <env> [--json]\n fabrika env backups schedule <app> <env> [on|off] [--json]\n fabrika env restore <app> <env> --at=<time> [--json]\n\n`inspect` prints the environment's data view: the object's maintenance mode and generation, the database size and\neach table's row count (a count at 100000 reads `100000+`: it is capped), the applied migrations,\nthe scheduler's alarm, each job's last run, file and webhook counts, and when the application last failed to boot.\nIt needs `data.read`. `--content` adds the boot failure's message and stack, which are the application's own text,\nand needs `data.content.read` granted globally.\n\n`maintenance` puts the environment into a mode: `read-only` refuses writes, `closed` refuses every request, and\n`open` serves again. It starts a data operation and prints it; `operations` follows it. It needs `data.manage`.\n\n`operations` lists the environment's data operations, newest first, one row each:\n<id> <kind> <state> <step> <target mode> <generation> <error code> <created at>.\n\n`recover` fences an environment whose operation is stuck in `closed` at a fresh generation, then `resume`s that\noperation from its recorded step, or `open`s the environment. A failed operation can only be opened past. It needs\n`data.manage`.\n\n`backups` lists the environment's consistent backups, newest first, one row each:\n<id> <object> <state> <created at> <size bytes> <parts> <tables> <rehearsal> <rehearsal code> <error code> <expired>\n<pre-migration>.\nA backup counts as `succeeded` only once its rehearsal, an import into a scratch object, passed. One older than 30\ndays is `expired` and never offered for a restore. The last column is `pre-migration` for the backup a migration\ntakes before its deploy, and `-` for any other, such as a daily backup or a restore's. It needs `data.read`.\n\n`backups schedule` prints whether the environment takes a daily backup; `on` or `off` sets it, which needs\n`data.manage`. Turning it off stops the daily backup only: the backup before a migration still runs.\n\n`restore` brings back the environment's data as it was at `--at`, an ISO 8601 time with an offset in the past. It\nis a side restore: the serving object is frozen read-only and backed up, the backup is imported into a new clone\nobject, ordinary traffic is pointed at the clone, which serves the current data from then on, and the original is\nrewound to that time and kept in `inspect`, serving nothing, for inspection. It starts a data operation and prints\nit; `operations` follows it. It needs `data.manage`.\n\nA release of the control plane that does not offer a command answers that it is not available; retrying does not\nchange that. An environment the caller may not see answers `not_found`, as one that does not exist.\n\nstdout carries data only; progress and follow-up commands go to stderr. `--json` prints the result as JSON.\n\nThe control origin takes either form:\n\n --url=<origin> FABRIKA_CONTROL_URL\n\nThe credential is read from the ENVIRONMENT ONLY and has no flag; one of:\n\n FABRIKA_CONTROL_KEY a machine `px_` credential for the control app\n FABRIKA_CONTROL_CREDENTIAL_HELPER the helper a `fabrika control auth device` grant is stored through\n";
|
|
2
2
|
type Environment = Readonly<Record<string, string | undefined>>;
|
|
3
3
|
/** Every control character but tab and line feed: an answer must not drive the operator's terminal. */
|
|
4
4
|
export declare const printable: (text: string) => string;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type RpcFetch } from '@fabrika/app';
|
|
2
|
-
|
|
2
|
+
import { type ControlOAuthDependencies } from './control-oauth.js';
|
|
3
|
+
declare const USAGE = "fabrika operations \u2014 read Operations (errors, releases, health) from the command line\n\nUsage:\n fabrika operations issues [--app=<id>] [--env=<env>] [--service=<key>] [--status=<open|resolved|ignored>]\n [--level=<fatal|error|warning|info>] [--since=<24h|7d|30d|all>] [--search=<text>]\n [--sort=<recent|new|frequency>] [--limit=<1-100>] [--cursor=<cursor>] [--json]\n fabrika operations issue <issueId> [--event=<occurrenceId>] [--json]\n fabrika operations releases [--app=<id>] [--env=<env>] [--service=<key>] [--limit=<1-100>] [--cursor=<cursor>] [--json]\n fabrika operations health [--app=<id>] [--env=<env>] [--service=<key>] [--json]\n\nEvery command is read-only. It reads what the console's Operations pages show, through the same API, with the\nkey's rights: a source (one service of an application environment) the key may not read is not listed, and an\nissue of one answers `not_found`.\n\n`issues` lists issues, the most recently seen first (`--sort` changes that), one row each:\n<id> <status> <level> <events> <last seen> <app> <env> <service> <title>.\nstderr carries the selection's counts by status (whatever `--status` says) and, when more issues match, the\n`--cursor` that reads the next page with the same options.\n\n`issue` prints one issue: its fields, its activity, its recent events (`occurrence` rows), and the latest\nevent in full: request, user, tags, each exception with its stack frames, and the breadcrumbs. `--event` shows\nthe event of another occurrence instead. The raw event is in `--json` only.\n\n`releases` lists releases, newest first, one row each:\n<id> <state> <artifacts> <release> <commit> <created at> <finished at> <new issues> <regressions> <app> <env> <service>.\n\n`health` prints each source's telemetry health and its HTTP checks:\nsource <app> <env> <service> <telemetry state>\ncheck <app> <env> <service> <path> <state> <observed at> <latency ms> <detail code> <consecutive failures>\n\n`--app`, `--env` and `--service` select sources. On `issues` and `releases` they must select exactly one;\nwhen they match several, the error lists them. Without them every source the key may read is included.\n\nIssue titles, exception messages, breadcrumbs, tags and the raw event are text the application's users and code\nwrote. They are printed as data with control characters removed; `--json` escapes them, C1 controls included,\nas JSON strings.\n\nstdout carries data only; notes and errors go to stderr. Times are ISO 8601 UTC, except a breadcrumb time the event\nwrote as text. `--json` prints the parsed answer: of the procedure, or for `issue` `{ issue, event }`, the\nissue and the event shown (`null` when none is stored).\n\nExit codes:\n 0 the answer was printed (an empty list included)\n 1 the call failed: Control or Operations unreachable, a server error, an unreadable answer, or a procedure this\n installation's release does not offer\n 2 usage: an unknown command or option, a bad value, or a selection that matches several sources\n 3 the credential: neither FABRIKA_CONTROL_KEY nor FABRIKA_CONTROL_CREDENTIAL_HELPER is set, or it was refused,\n or it does not hold `operations.read`\n 4 not found: no such issue, event or source, or one the key may not read\n\nThe console origin takes either form:\n\n --url=<origin> FABRIKA_CONTROL_URL\n\nThe credential is read from the ENVIRONMENT ONLY and has no flag; one of:\n\n FABRIKA_CONTROL_KEY a `px_` key of the console app holding `operations.read`\n FABRIKA_CONTROL_CREDENTIAL_HELPER the helper a `fabrika control auth device` grant is stored through\n (any preset but `create` reads Operations; a list is empty where the\n person who approved it holds no `operations.read`)\n\nMint a key narrowed to `operations.read` alone, with a short expiry: docs/reference/operations-errors.md,\n\"Reading Operations from the command line\".\n";
|
|
3
4
|
export declare const OPERATIONS_EXIT: {
|
|
4
5
|
readonly ok: 0;
|
|
5
6
|
readonly failed: 1;
|
|
@@ -12,6 +13,8 @@ type Environment = Readonly<Record<string, string | undefined>>;
|
|
|
12
13
|
export interface OperationsIo {
|
|
13
14
|
readonly env: Environment;
|
|
14
15
|
readonly fetch: RpcFetch;
|
|
16
|
+
/** Replaces the credential helper, its lock and the clock; only a test passes it. */
|
|
17
|
+
readonly oauth?: ControlOAuthDependencies;
|
|
15
18
|
readonly out: (text: string) => void;
|
|
16
19
|
readonly err: (text: string) => void;
|
|
17
20
|
}
|