@greenmind/cli 0.0.0-stage → 0.9.40
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 +40 -4
- package/src/bin.ts +15 -0
- package/src/bundle.ts +100 -0
- package/src/client.ts +549 -0
- package/src/command.ts +1054 -0
- package/src/commands.ts +274 -0
- package/src/constants.ts +39 -0
- package/src/credentials.ts +159 -0
- package/src/environment-commands.ts +470 -0
- package/src/ext-config.ts +107 -0
- package/src/identity.ts +287 -0
- package/src/index.ts +58 -0
- package/src/json-read.ts +29 -0
- package/src/load.ts +127 -0
- package/src/org-commands.ts +579 -0
- package/src/protocol.ts +28 -0
- package/src/runner-command.ts +118 -0
- package/src/session.ts +278 -0
- package/README.md +0 -3
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { resolve } from 'node:path'
|
|
2
|
+
import { pathToFileURL } from 'node:url'
|
|
3
|
+
import { Command, type CommandUnknownOpts } from '@commander-js/extra-typings'
|
|
4
|
+
import { createRunner, type JobHandler, RunnerRefused } from '@greenmind/ext-sdk/src/runner'
|
|
5
|
+
import { CLI_VERSION, ENV_ORG } from './constants'
|
|
6
|
+
import { LoadError } from './load'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* `gm runner`: serves one of the org's pools from this machine, running the job handlers a
|
|
10
|
+
* module exports until it is stopped. The credential is an org key holding `run_jobs`, never a
|
|
11
|
+
* person's sign-in: a runner is left running unattended.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** Handlers by job type, or `handle(job, fn)` pairs. */
|
|
15
|
+
type HandlerExport = Readonly<Record<string, JobHandler>> | [string, JobHandler][]
|
|
16
|
+
|
|
17
|
+
/** What a handlers module exports. */
|
|
18
|
+
interface HandlerModule {
|
|
19
|
+
readonly handlers?: HandlerExport
|
|
20
|
+
readonly default?: HandlerExport
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const ENV_RUNNER_KEY = 'GM_RUNNER_KEY'
|
|
24
|
+
export const ENV_GATEWAY_URL = 'GM_GATEWAY_URL'
|
|
25
|
+
export const ENV_REALTIME_URL = 'GM_REALTIME_URL'
|
|
26
|
+
|
|
27
|
+
export const DEFAULT_GATEWAY_URL = 'https://api.publishing.greenmindmedia.com'
|
|
28
|
+
export const DEFAULT_REALTIME_URL = 'wss://rt.publishing.greenmindmedia.com'
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The handlers a module exports: `handlers`, or its default export, an object of handlers by job
|
|
32
|
+
* type (or a list of `handle(job, fn)` pairs).
|
|
33
|
+
*/
|
|
34
|
+
export async function loadHandlers(file: string): Promise<Record<string, JobHandler>> {
|
|
35
|
+
const exported: HandlerModule = await import(pathToFileURL(resolve(file)).href)
|
|
36
|
+
const found = exported.handlers ?? exported.default ?? {}
|
|
37
|
+
const handlers: Record<string, JobHandler> = Array.isArray(found)
|
|
38
|
+
? Object.fromEntries(found)
|
|
39
|
+
: { ...found }
|
|
40
|
+
const named = Object.values(handlers)
|
|
41
|
+
if (named.length === 0 || !named.every((each) => each instanceof Function)) {
|
|
42
|
+
throw new LoadError(
|
|
43
|
+
`${file} exports no handlers: export \`handlers\`, an object of functions by job type.`,
|
|
44
|
+
)
|
|
45
|
+
}
|
|
46
|
+
return handlers
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const positive = (value: string) => {
|
|
50
|
+
const parsed = Number(value)
|
|
51
|
+
if (!Number.isInteger(parsed) || parsed < 1)
|
|
52
|
+
throw new Error(`${value} is not a whole number of 1 or more.`)
|
|
53
|
+
return parsed
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function runnerCommand(): CommandUnknownOpts {
|
|
57
|
+
return new Command('runner')
|
|
58
|
+
.description(
|
|
59
|
+
"Serve one of your org's job pools from this machine, running the handlers a module exports",
|
|
60
|
+
)
|
|
61
|
+
.argument('<handlers>', 'A module exporting `handlers`: functions by job type')
|
|
62
|
+
.requiredOption('--pool <name>', 'The pool to serve')
|
|
63
|
+
.option('--org <handle>', `The org whose pool it is (or ${ENV_ORG})`)
|
|
64
|
+
.option('--key <key>', `An org key holding run_jobs (or ${ENV_RUNNER_KEY})`)
|
|
65
|
+
.option('--concurrency <n>', 'Jobs to run at once', positive, 1)
|
|
66
|
+
.option('--label <label...>', 'What this machine offers beyond the pool, such as gpu')
|
|
67
|
+
.option('--host <name>', "This machine's name, as the console lists it")
|
|
68
|
+
.option('--gateway-url <url>', `The HTTP gateway (or ${ENV_GATEWAY_URL})`)
|
|
69
|
+
.option('--realtime-url <url>', `The realtime gateway (or ${ENV_REALTIME_URL})`)
|
|
70
|
+
.option('--http-only', 'Never open a socket; every call is a request')
|
|
71
|
+
.action(async (file, options) => {
|
|
72
|
+
const org = options.org ?? process.env[ENV_ORG]
|
|
73
|
+
const key = options.key ?? process.env[ENV_RUNNER_KEY]
|
|
74
|
+
if (!org || !key) {
|
|
75
|
+
console.error(
|
|
76
|
+
`Name the org (--org or ${ENV_ORG}) and the key (--key or ${ENV_RUNNER_KEY}).`,
|
|
77
|
+
)
|
|
78
|
+
process.exitCode = 1
|
|
79
|
+
return
|
|
80
|
+
}
|
|
81
|
+
let handlers: Record<string, JobHandler>
|
|
82
|
+
try {
|
|
83
|
+
handlers = await loadHandlers(file)
|
|
84
|
+
} catch (error) {
|
|
85
|
+
console.error(error instanceof Error ? error.message : String(error))
|
|
86
|
+
process.exitCode = 1
|
|
87
|
+
return
|
|
88
|
+
}
|
|
89
|
+
const runner = createRunner({
|
|
90
|
+
httpUrl: options.gatewayUrl ?? process.env[ENV_GATEWAY_URL] ?? DEFAULT_GATEWAY_URL,
|
|
91
|
+
socketUrl: options.httpOnly
|
|
92
|
+
? undefined
|
|
93
|
+
: (options.realtimeUrl ?? process.env[ENV_REALTIME_URL] ?? DEFAULT_REALTIME_URL),
|
|
94
|
+
org,
|
|
95
|
+
pool: options.pool,
|
|
96
|
+
key,
|
|
97
|
+
handlers,
|
|
98
|
+
concurrency: options.concurrency,
|
|
99
|
+
labels: options.label ?? [],
|
|
100
|
+
host: options.host,
|
|
101
|
+
version: `gm/${CLI_VERSION}`,
|
|
102
|
+
print: (line) => console.log(line),
|
|
103
|
+
})
|
|
104
|
+
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
|
|
105
|
+
process.once(signal, () => {
|
|
106
|
+
console.log('Stopping: the jobs held go back to the queue.')
|
|
107
|
+
void runner.stop()
|
|
108
|
+
})
|
|
109
|
+
}
|
|
110
|
+
try {
|
|
111
|
+
await runner.run()
|
|
112
|
+
} catch (error) {
|
|
113
|
+
if (!(error instanceof RunnerRefused)) throw error
|
|
114
|
+
console.error(`The pool refused this runner: ${error.message}`)
|
|
115
|
+
process.exitCode = 1
|
|
116
|
+
}
|
|
117
|
+
})
|
|
118
|
+
}
|
package/src/session.ts
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import type { ExtToolDiscovery } from '@greenmind/ext-schema'
|
|
2
|
+
import { PlatformClient, readToolDiscovery, type TokenSource } from './client'
|
|
3
|
+
import type { Print } from './commands'
|
|
4
|
+
import {
|
|
5
|
+
BASE_SCOPES,
|
|
6
|
+
CLIENT_ID,
|
|
7
|
+
DEFAULT_PLATFORM_URL,
|
|
8
|
+
ENV_ISSUER,
|
|
9
|
+
ENV_KEY,
|
|
10
|
+
ENV_ORG,
|
|
11
|
+
ENV_URL,
|
|
12
|
+
} from './constants'
|
|
13
|
+
import {
|
|
14
|
+
credentialsDir,
|
|
15
|
+
loginKey,
|
|
16
|
+
readLogin,
|
|
17
|
+
type StoredLogin,
|
|
18
|
+
storedPlatforms,
|
|
19
|
+
withLock,
|
|
20
|
+
writeLogin,
|
|
21
|
+
} from './credentials'
|
|
22
|
+
import { deviceLogin, type IdentityOptions, refreshLogin, revokeLogin } from './identity'
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Choosing the credential a command calls the platform with, and the sign-in commands that make
|
|
26
|
+
* one. An org key, from `--key` or the environment, always wins and no stored login is read, so
|
|
27
|
+
* a build server never signs in; otherwise the stored login for the platform's address is used.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
export class SessionError extends Error {
|
|
31
|
+
override readonly name = 'SessionError'
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface SessionOptions {
|
|
35
|
+
readonly url?: string
|
|
36
|
+
readonly key?: string
|
|
37
|
+
/** The handle of the org whose environments the command names; `GM_ORG` when left out. */
|
|
38
|
+
readonly org?: string
|
|
39
|
+
readonly env?: NodeJS.ProcessEnv
|
|
40
|
+
/** The credentials directory; the user's own unless a test names one. */
|
|
41
|
+
readonly dir?: string
|
|
42
|
+
readonly identity?: IdentityOptions
|
|
43
|
+
readonly fetch?: typeof fetch
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* What a command accepts: `optional` runs without one (a check that stays offline), `any` takes a
|
|
48
|
+
* org key or a person, `person` only a person, since the routes it calls take no key.
|
|
49
|
+
*/
|
|
50
|
+
export type Need = 'optional' | 'any' | 'person'
|
|
51
|
+
|
|
52
|
+
class StoredTokens implements TokenSource {
|
|
53
|
+
constructor(
|
|
54
|
+
private readonly dir: string,
|
|
55
|
+
private readonly platformUrl: string,
|
|
56
|
+
private readonly identity: IdentityOptions,
|
|
57
|
+
) {}
|
|
58
|
+
|
|
59
|
+
async accessToken(): Promise<string> {
|
|
60
|
+
const held = readLogin(this.dir, this.platformUrl)
|
|
61
|
+
if (!held) throw notSignedIn(this.platformUrl)
|
|
62
|
+
const now = this.identity.now ?? Date.now
|
|
63
|
+
if (Date.parse(held.expiresAt) - now() > 30_000) return held.accessToken
|
|
64
|
+
const renewed = await refreshLogin(this.dir, this.platformUrl, undefined, this.identity)
|
|
65
|
+
// With nothing to renew it with, the server gets to say the token has ended.
|
|
66
|
+
return renewed?.accessToken ?? held.accessToken
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async refresh(rejected: string): Promise<string | undefined> {
|
|
70
|
+
return (await refreshLogin(this.dir, this.platformUrl, rejected, this.identity))?.accessToken
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function notSignedIn(platformUrl: string | undefined): SessionError {
|
|
75
|
+
return new SessionError(
|
|
76
|
+
platformUrl
|
|
77
|
+
? `You are not signed in to ${platformUrl}. Run \`gm login --url ${platformUrl}\`.`
|
|
78
|
+
: 'You are not signed in. Run `gm login`.',
|
|
79
|
+
)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function keyOf(options: SessionOptions): string | undefined {
|
|
83
|
+
return options.key ?? (options.env ?? process.env)[ENV_KEY] ?? undefined
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function urlOf(options: SessionOptions): string | undefined {
|
|
87
|
+
return options.url ?? (options.env ?? process.env)[ENV_URL] ?? undefined
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function orgOf(options: SessionOptions): string | undefined {
|
|
91
|
+
return options.org ?? ((options.env ?? process.env)[ENV_ORG] || undefined)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The client a command calls with, or none where the command may go without. `what` begins the
|
|
96
|
+
* message for a command that has nothing to call with, such as "Pushing".
|
|
97
|
+
*/
|
|
98
|
+
export function connect(
|
|
99
|
+
options: SessionOptions,
|
|
100
|
+
need: Exclude<Need, 'optional'>,
|
|
101
|
+
what: string,
|
|
102
|
+
): PlatformClient
|
|
103
|
+
export function connect(
|
|
104
|
+
options: SessionOptions,
|
|
105
|
+
need: Need,
|
|
106
|
+
what: string,
|
|
107
|
+
): PlatformClient | undefined
|
|
108
|
+
export function connect(
|
|
109
|
+
options: SessionOptions,
|
|
110
|
+
need: Need,
|
|
111
|
+
what: string,
|
|
112
|
+
): PlatformClient | undefined {
|
|
113
|
+
const key = keyOf(options)
|
|
114
|
+
const explicitUrl = urlOf(options)
|
|
115
|
+
if (key) {
|
|
116
|
+
if (need === 'person') {
|
|
117
|
+
throw new SessionError(
|
|
118
|
+
`${what} needs you signed in: an org key (--key or ${ENV_KEY}) cannot do it. Leave the key out and run \`gm login\`.`,
|
|
119
|
+
)
|
|
120
|
+
}
|
|
121
|
+
if (!explicitUrl) {
|
|
122
|
+
throw new SessionError(
|
|
123
|
+
`Both a platform address (--url or ${ENV_URL}) and an org key (--key or ${ENV_KEY}) are needed.`,
|
|
124
|
+
)
|
|
125
|
+
}
|
|
126
|
+
return new PlatformClient({
|
|
127
|
+
baseUrl: explicitUrl,
|
|
128
|
+
org: orgOf(options),
|
|
129
|
+
orgKey: key,
|
|
130
|
+
fetch: options.fetch,
|
|
131
|
+
})
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const dir = options.dir ?? credentialsDir(options.env)
|
|
135
|
+
if (!explicitUrl && need === 'optional') return undefined
|
|
136
|
+
let platformUrl = explicitUrl
|
|
137
|
+
if (!platformUrl) {
|
|
138
|
+
const stored = storedPlatforms(dir)
|
|
139
|
+
if (stored.length === 1) platformUrl = stored[0]
|
|
140
|
+
else if (need === 'person') throw notSignedIn(undefined)
|
|
141
|
+
}
|
|
142
|
+
if (!platformUrl) {
|
|
143
|
+
throw new SessionError(
|
|
144
|
+
`${what} needs a platform address (--url or ${ENV_URL}) and an org key (--key or ${ENV_KEY}), or a stored sign-in: run \`gm login\`.`,
|
|
145
|
+
)
|
|
146
|
+
}
|
|
147
|
+
if (!readLogin(dir, platformUrl)) {
|
|
148
|
+
if (need === 'person') throw notSignedIn(platformUrl)
|
|
149
|
+
throw new SessionError(
|
|
150
|
+
`Both a platform address (--url or ${ENV_URL}) and an org key (--key or ${ENV_KEY}) are needed, or sign in with \`gm login --url ${platformUrl}\`.`,
|
|
151
|
+
)
|
|
152
|
+
}
|
|
153
|
+
return new PlatformClient({
|
|
154
|
+
baseUrl: platformUrl,
|
|
155
|
+
org: orgOf(options),
|
|
156
|
+
tokens: new StoredTokens(dir, platformUrl, options.identity ?? {}),
|
|
157
|
+
fetch: options.fetch,
|
|
158
|
+
})
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** A stored sign-in and the platform address it is kept under. */
|
|
162
|
+
export interface SignedIn {
|
|
163
|
+
readonly platformUrl: string
|
|
164
|
+
readonly login: StoredLogin
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* The stored sign-in a command run with these options would use, and the platform it is for. A
|
|
169
|
+
* command that has to know what the sign-in carries (its scopes, say) reads it here.
|
|
170
|
+
*/
|
|
171
|
+
export function signedInAs(options: SessionOptions): SignedIn {
|
|
172
|
+
const dir = options.dir ?? credentialsDir(options.env)
|
|
173
|
+
const platformUrl = urlOf(options) ?? storedPlatforms(dir)[0]
|
|
174
|
+
const login = platformUrl ? readLogin(dir, platformUrl) : undefined
|
|
175
|
+
if (!platformUrl || !login) throw notSignedIn(platformUrl)
|
|
176
|
+
return { platformUrl: loginKey(platformUrl), login }
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export interface LoginOptions extends SessionOptions {
|
|
180
|
+
readonly issuer?: string
|
|
181
|
+
readonly clientId?: string
|
|
182
|
+
/** Asked for beside the scopes the platform names. */
|
|
183
|
+
readonly extraScopes?: readonly string[]
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Where and how to sign in to a platform: what the platform itself says (`readToolDiscovery`), each
|
|
188
|
+
* value overridden by a flag or the environment where one is given. With an issuer given by hand,
|
|
189
|
+
* a platform that cannot say is not asked at all, so a stage older than the discovery route can
|
|
190
|
+
* still be signed in to.
|
|
191
|
+
*/
|
|
192
|
+
async function signInPlan(options: LoginOptions, platformUrl: string) {
|
|
193
|
+
const env = options.env ?? process.env
|
|
194
|
+
const givenIssuer = options.issuer ?? env[ENV_ISSUER]
|
|
195
|
+
let told: ExtToolDiscovery | undefined
|
|
196
|
+
try {
|
|
197
|
+
told = await readToolDiscovery(platformUrl, options.fetch)
|
|
198
|
+
} catch (error) {
|
|
199
|
+
if (!givenIssuer) throw error
|
|
200
|
+
}
|
|
201
|
+
const scopes = told?.scopes ?? [...BASE_SCOPES]
|
|
202
|
+
return {
|
|
203
|
+
issuer: givenIssuer ?? told?.issuer ?? '',
|
|
204
|
+
clientId: options.clientId ?? told?.clientId ?? CLIENT_ID,
|
|
205
|
+
scopes: [...new Set([...scopes, ...(options.extraScopes ?? [])])],
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Signs in with the device flow and keeps the tokens under the platform's address. */
|
|
210
|
+
export async function runLogin(options: LoginOptions, print: Print): Promise<boolean> {
|
|
211
|
+
const platformUrl = loginKey(urlOf(options) ?? DEFAULT_PLATFORM_URL)
|
|
212
|
+
const dir = options.dir ?? credentialsDir(options.env)
|
|
213
|
+
const plan = await signInPlan(options, platformUrl)
|
|
214
|
+
const identity = options.identity ?? {}
|
|
215
|
+
const issued = await deviceLogin({
|
|
216
|
+
...identity,
|
|
217
|
+
issuer: plan.issuer,
|
|
218
|
+
clientId: plan.clientId,
|
|
219
|
+
scopes: plan.scopes,
|
|
220
|
+
prompt: ({ url, code, completeUrl }) => {
|
|
221
|
+
print(`Open ${completeUrl ?? url} and confirm this code: ${code}`)
|
|
222
|
+
if (completeUrl) print(`Or open ${url} and type it.`)
|
|
223
|
+
print('Waiting for you to approve it...')
|
|
224
|
+
},
|
|
225
|
+
})
|
|
226
|
+
await withLock(dir, async () => writeLogin(dir, platformUrl, issued))
|
|
227
|
+
print(`Signed in to ${platformUrl}${describeUser(issued.user)}.`)
|
|
228
|
+
return true
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function describeUser(user: StoredLogin['user']): string {
|
|
232
|
+
const who = user.name ?? user.email ?? user.subject
|
|
233
|
+
return who ? ` as ${who}` : ''
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Revokes the tokens at the identity server and forgets them. Forgetting happens regardless. */
|
|
237
|
+
export async function runLogout(options: SessionOptions, print: Print): Promise<boolean> {
|
|
238
|
+
const dir = options.dir ?? credentialsDir(options.env)
|
|
239
|
+
const platformUrl = urlOf(options) ?? storedPlatforms(dir)[0]
|
|
240
|
+
const login = platformUrl ? readLogin(dir, platformUrl) : undefined
|
|
241
|
+
if (!platformUrl || !login) {
|
|
242
|
+
print('You are not signed in.')
|
|
243
|
+
return true
|
|
244
|
+
}
|
|
245
|
+
const problem = await revokeLogin(login, options.identity ?? {})
|
|
246
|
+
await withLock(dir, async () => writeLogin(dir, platformUrl, undefined))
|
|
247
|
+
if (problem) {
|
|
248
|
+
print(`Signed out of ${platformUrl} here, but the tokens could not be revoked: ${problem}`)
|
|
249
|
+
return false
|
|
250
|
+
}
|
|
251
|
+
print(`Signed out of ${platformUrl}; its tokens are revoked.`)
|
|
252
|
+
return true
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Who is signed in to which platform. Never prints a token. */
|
|
256
|
+
export function runWhoami(options: SessionOptions, print: Print): boolean {
|
|
257
|
+
const dir = options.dir ?? credentialsDir(options.env)
|
|
258
|
+
const explicit = urlOf(options)
|
|
259
|
+
const platforms = explicit ? [loginKey(explicit)] : storedPlatforms(dir)
|
|
260
|
+
const found = platforms.flatMap((platform) => {
|
|
261
|
+
const login = readLogin(dir, platform)
|
|
262
|
+
return login ? [[platform, login] as const] : []
|
|
263
|
+
})
|
|
264
|
+
if (found.length === 0) {
|
|
265
|
+
print(explicit ? `You are not signed in to ${explicit}.` : 'You are not signed in.')
|
|
266
|
+
return false
|
|
267
|
+
}
|
|
268
|
+
for (const [platform, login] of found) {
|
|
269
|
+
const ends = Date.parse(login.expiresAt)
|
|
270
|
+
print(`${platform}${describeUser(login.user)}`)
|
|
271
|
+
print(` identity server ${login.issuer}`)
|
|
272
|
+
print(` scopes ${login.scope}`)
|
|
273
|
+
print(
|
|
274
|
+
` access token ${ends > Date.now() ? `valid until ${login.expiresAt}` : 'ended; renewed on next use'}`,
|
|
275
|
+
)
|
|
276
|
+
}
|
|
277
|
+
return true
|
|
278
|
+
}
|
package/README.md
DELETED