|
| 1 | +/** |
| 2 | + * Self-contained Bailian console login: the plugin speaks the console's |
| 3 | + * callback protocol itself instead of shelling out to `bl auth login --console`. |
| 4 | + * |
| 5 | + * Why not the CLI: it hard-codes `needApiKey: !hasApiKey`, so once any api key |
| 6 | + * is stored it never asks the console to issue a fresh one — you end up pairing |
| 7 | + * an old account's key with a new account's workspace id, and nothing warns |
| 8 | + * you. Driving the flow here lets us always pass `needapikey=true`, so the key |
| 9 | + * and the workspace id both come from the account that just signed in, and the |
| 10 | + * values land straight in the dsh stores without transiting the CLI's |
| 11 | + * `~/.bailian/config.json`. |
| 12 | + * |
| 13 | + * Protocol (mirrors the CLI's implementation): bind a loopback-only port, open |
| 14 | + * `<console>/console-login?notice=127.0.0.1:<port>?state=<state>&needapikey=true`, |
| 15 | + * then accept one callback carrying the credentials as query parameters or a |
| 16 | + * JSON / form-encoded body. Note the URL shape: `state` is part of the `notice` |
| 17 | + * value (separated by `?`), not a sibling query parameter. |
| 18 | + */ |
| 19 | + |
| 20 | +import { execFile } from 'node:child_process' |
| 21 | +import { randomBytes } from 'node:crypto' |
| 22 | +import http from 'node:http' |
| 23 | + |
| 24 | +/** Console web origins by site, keyed as the CLI's `--console-site` values. */ |
| 25 | +const CONSOLE_ORIGINS: Record<string, string> = { |
| 26 | + domestic: 'https://bailian.console.aliyun.com', |
| 27 | + international: 'https://modelstudio.console.alibabacloud.com', |
| 28 | +} |
| 29 | + |
| 30 | +/** How long the loopback listener waits for the browser callback. */ |
| 31 | +const LOGIN_TIMEOUT_MS = 15 * 60 * 1000 |
| 32 | + |
| 33 | +/** Upper bound on a callback body, matching the CLI's limit. */ |
| 34 | +const MAX_CALLBACK_BODY = 65536 |
| 35 | + |
| 36 | +/** Credentials the console callback can carry. */ |
| 37 | +export interface ConsoleLoginCredentials { |
| 38 | + /** Freshly issued DashScope api key (`needapikey=true` asks for one). */ |
| 39 | + apiKey?: string |
| 40 | + /** Workspace id of the account that signed in. */ |
| 41 | + workspaceId?: string |
| 42 | +} |
| 43 | + |
| 44 | +/** |
| 45 | + * Where the login flow stands. Deliberately carries no secret: the plain key |
| 46 | + * is handed to the completion callback and never retained here, so polling |
| 47 | + * this state from the browser cannot leak it. |
| 48 | + */ |
| 49 | +export type ConsoleLoginState = |
| 50 | + | { phase: 'idle' } |
| 51 | + | { phase: 'waiting', loginUrl: string } |
| 52 | + | { phase: 'done', fields: string[] } |
| 53 | + | { phase: 'failed', reason: string } |
| 54 | + |
| 55 | +/** The single in-flight flow: one browser login at a time. */ |
| 56 | +let active: { server: http.Server } | undefined |
| 57 | +let state: ConsoleLoginState = { phase: 'idle' } |
| 58 | + |
| 59 | +/** Read the current flow state (safe to expose to the panel). */ |
| 60 | +export function consoleLoginState(): ConsoleLoginState { |
| 61 | + return state |
| 62 | +} |
| 63 | + |
| 64 | +/** Pick the first non-blank string among the given keys. */ |
| 65 | +function stringField(source: Record<string, unknown>, ...keys: string[]): string | undefined { |
| 66 | + for (const key of keys) { |
| 67 | + const value = source[key] |
| 68 | + if (typeof value === 'string' && value.trim() !== '') return value.trim() |
| 69 | + } |
| 70 | + return undefined |
| 71 | +} |
| 72 | + |
| 73 | +/** Read a bounded UTF-8 request body; an oversized body reads as empty. */ |
| 74 | +function readBody(req: http.IncomingMessage): Promise<string> { |
| 75 | + return new Promise((resolve) => { |
| 76 | + const chunks: Buffer[] = [] |
| 77 | + let size = 0 |
| 78 | + req.on('data', (chunk: Buffer) => { |
| 79 | + size += chunk.length |
| 80 | + if (size > MAX_CALLBACK_BODY) { req.destroy(); resolve(''); return } |
| 81 | + chunks.push(chunk) |
| 82 | + }) |
| 83 | + req.on('end', () => { resolve(Buffer.concat(chunks).toString('utf8')) }) |
| 84 | + req.on('error', () => { resolve('') }) |
| 85 | + }) |
| 86 | +} |
| 87 | + |
| 88 | +/** |
| 89 | + * Parse a callback body as JSON (optionally wrapped in `data`) or as form |
| 90 | + * encoding. Content-type is a hint only — the CLI falls back to trying both, |
| 91 | + * and so do we, because the console has shipped both shapes. |
| 92 | + * @param raw - the raw request body. |
| 93 | + * @returns the flattened fields; an unparseable body yields no fields. |
| 94 | + */ |
| 95 | +export function parseCallbackBody(raw: string): Record<string, unknown> { |
| 96 | + const text = raw.replace(/^\uFEFF/, '').trim() |
| 97 | + if (text === '') return {} |
| 98 | + let json: unknown |
| 99 | + let parsedAsJson = false |
| 100 | + try { |
| 101 | + json = JSON.parse(text) |
| 102 | + parsedAsJson = true |
| 103 | + } catch (_notJson) { /* fall through to form parsing */ } |
| 104 | + if (parsedAsJson) { |
| 105 | + // Valid JSON that is not an object carries no fields. Returning here rather |
| 106 | + // than falling through matters: form parsing would turn the whole payload |
| 107 | + // into one junk key. |
| 108 | + if (json === null || typeof json !== 'object' || Array.isArray(json)) return {} |
| 109 | + const record = json as Record<string, unknown> |
| 110 | + const inner = record.data |
| 111 | + if (inner !== null && typeof inner === 'object' && !Array.isArray(inner)) { |
| 112 | + // Merge the envelope's `data` under the top level, top level winning. |
| 113 | + return { ...inner as Record<string, unknown>, ...record } |
| 114 | + } |
| 115 | + return record |
| 116 | + } |
| 117 | + try { |
| 118 | + return Object.fromEntries(new URLSearchParams(text)) |
| 119 | + } catch (_notForm) { |
| 120 | + return {} |
| 121 | + } |
| 122 | +} |
| 123 | + |
| 124 | +/** |
| 125 | + * Pick the api key and workspace id out of a callback's fields, query |
| 126 | + * parameters taking priority over the body. |
| 127 | + * @param query - the callback URL's query parameters. |
| 128 | + * @param body - the parsed callback body. |
| 129 | + * @returns the credentials found; fields are absent rather than blank. |
| 130 | + */ |
| 131 | +export function pickCallbackCredentials( |
| 132 | + query: Record<string, unknown>, |
| 133 | + body: Record<string, unknown>, |
| 134 | +): ConsoleLoginCredentials { |
| 135 | + const apiKey = stringField(query, 'api_key', 'apiKey') ?? stringField(body, 'api_key', 'apiKey') |
| 136 | + const workspaceId = stringField(query, 'workspace_id', 'workspaceId') |
| 137 | + ?? stringField(body, 'workspace_id', 'workspaceId') |
| 138 | + return { |
| 139 | + ...(apiKey !== undefined ? { apiKey } : {}), |
| 140 | + ...(workspaceId !== undefined ? { workspaceId } : {}), |
| 141 | + } |
| 142 | +} |
| 143 | + |
| 144 | +/** Extract the credentials from a callback, query parameters taking priority. */ |
| 145 | +async function extractCredentials(req: http.IncomingMessage, url: URL): Promise<ConsoleLoginCredentials> { |
| 146 | + const method = req.method ?? 'GET' |
| 147 | + const body = (method === 'POST' || method === 'PUT' || method === 'PATCH') |
| 148 | + ? parseCallbackBody(await readBody(req)) |
| 149 | + : {} |
| 150 | + return pickCallbackCredentials(Object.fromEntries(url.searchParams), body) |
| 151 | +} |
| 152 | + |
| 153 | +/** Open a URL with the OS default handler; never routed through a shell. */ |
| 154 | +function openInBrowser(url: string): Promise<void> { |
| 155 | + const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open' |
| 156 | + const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url] |
| 157 | + return new Promise((resolve, reject) => { |
| 158 | + execFile(cmd, args, { windowsHide: true }, err => { err ? reject(err) : resolve() }) |
| 159 | + }) |
| 160 | +} |
| 161 | + |
| 162 | +/** Bind an http server to a loopback-only port chosen by the OS. */ |
| 163 | +function listenLoopback(server: http.Server): Promise<number> { |
| 164 | + return new Promise((resolve, reject) => { |
| 165 | + const onError = (err: Error): void => { reject(err) } |
| 166 | + server.once('error', onError) |
| 167 | + server.listen({ port: 0, host: '127.0.0.1', exclusive: true }, () => { |
| 168 | + server.off('error', onError) |
| 169 | + const address = server.address() |
| 170 | + if (address === null || typeof address === 'string') { |
| 171 | + reject(new Error('expected a TCP address')) |
| 172 | + return |
| 173 | + } |
| 174 | + resolve(address.port) |
| 175 | + }) |
| 176 | + }) |
| 177 | +} |
| 178 | + |
| 179 | +/** Outcome of asking the host to start a console login. */ |
| 180 | +export type ConsoleLoginStart = |
| 181 | + | { status: 'started', loginUrl: string } |
| 182 | + | { status: 'already-running', loginUrl: string } |
| 183 | + | { status: 'failed', reason: string } |
| 184 | + |
| 185 | +/** |
| 186 | + * Start a console login on the host: binds a loopback listener, opens the |
| 187 | + * console login page in the host's default browser, and hands the credentials |
| 188 | + * from the callback to `onComplete` (which persists them). Fire-and-forget — |
| 189 | + * this resolves once the browser has been opened; poll {@link consoleLoginState} |
| 190 | + * for the outcome. |
| 191 | + * @param opts.site - console site, `domestic` (default) or `international`. |
| 192 | + * @param opts.onComplete - persists the received credentials; its resolved |
| 193 | + * field names become the `done` state's `fields`. |
| 194 | + * @returns whether the flow started, plus the URL to open manually if needed. |
| 195 | + */ |
| 196 | +export async function startConsoleLogin(opts: { |
| 197 | + site?: string |
| 198 | + onComplete: (credentials: ConsoleLoginCredentials) => Promise<string[]> |
| 199 | +}): Promise<ConsoleLoginStart> { |
| 200 | + if (active !== undefined) { |
| 201 | + return { |
| 202 | + status: 'already-running', |
| 203 | + loginUrl: state.phase === 'waiting' ? state.loginUrl : '', |
| 204 | + } |
| 205 | + } |
| 206 | + const expectedState = randomBytes(16).toString('hex') |
| 207 | + let settled = false |
| 208 | + const server = http.createServer((req, res) => { |
| 209 | + void (async () => { |
| 210 | + if (req.method === 'OPTIONS') { |
| 211 | + // The console page posts cross-origin; answer its preflight. |
| 212 | + res.writeHead(204, { |
| 213 | + 'Access-Control-Allow-Origin': '*', |
| 214 | + 'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, OPTIONS', |
| 215 | + 'Access-Control-Allow-Headers': 'Content-Type', |
| 216 | + }) |
| 217 | + res.end() |
| 218 | + return |
| 219 | + } |
| 220 | + const url = new URL(req.url ?? '/', 'http://127.0.0.1') |
| 221 | + if (url.searchParams.get('state') !== expectedState) { |
| 222 | + // Not our callback (or a forged one): refuse without ending the flow. |
| 223 | + res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' }) |
| 224 | + res.end('bad state\n') |
| 225 | + return |
| 226 | + } |
| 227 | + const credentials = await extractCredentials(req, url) |
| 228 | + res.writeHead(200, { |
| 229 | + 'Content-Type': 'text/plain; charset=utf-8', |
| 230 | + 'Access-Control-Allow-Origin': '*', |
| 231 | + }) |
| 232 | + res.end('OK\n') |
| 233 | + if (credentials.apiKey === undefined && credentials.workspaceId === undefined) { |
| 234 | + // A callback with neither value (e.g. a bare probe): keep waiting. |
| 235 | + return |
| 236 | + } |
| 237 | + settled = true |
| 238 | + try { |
| 239 | + const fields = await opts.onComplete(credentials) |
| 240 | + state = { phase: 'done', fields } |
| 241 | + } catch (err) { |
| 242 | + state = { phase: 'failed', reason: err instanceof Error ? err.message : 'persist failed' } |
| 243 | + } |
| 244 | + server.close() |
| 245 | + })().catch(() => { |
| 246 | + res.statusCode = 500 |
| 247 | + res.end() |
| 248 | + }) |
| 249 | + }) |
| 250 | + |
| 251 | + let port: number |
| 252 | + try { |
| 253 | + port = await listenLoopback(server) |
| 254 | + } catch (err) { |
| 255 | + const reason = err instanceof Error ? err.message : 'could not bind a local port' |
| 256 | + state = { phase: 'failed', reason } |
| 257 | + return { status: 'failed', reason } |
| 258 | + } |
| 259 | + |
| 260 | + // `state` rides inside the `notice` value, and `needapikey=true` is the whole |
| 261 | + // point: it makes the console issue a key for the account signing in. |
| 262 | + const origin = (opts.site !== undefined ? CONSOLE_ORIGINS[opts.site] : undefined) ?? CONSOLE_ORIGINS.domestic! |
| 263 | + const loginUrl = `${origin}/console-login?notice=127.0.0.1:${port}` |
| 264 | + + `?state=${encodeURIComponent(expectedState)}&needapikey=true` |
| 265 | + |
| 266 | + active = { server } |
| 267 | + state = { phase: 'waiting', loginUrl } |
| 268 | + const timer = setTimeout(() => { server.close() }, LOGIN_TIMEOUT_MS) |
| 269 | + timer.unref?.() |
| 270 | + server.once('close', () => { |
| 271 | + clearTimeout(timer) |
| 272 | + active = undefined |
| 273 | + if (!settled && state.phase === 'waiting') { |
| 274 | + state = { phase: 'failed', reason: 'the login timed out before the console called back' } |
| 275 | + } |
| 276 | + }) |
| 277 | + |
| 278 | + try { |
| 279 | + await openInBrowser(loginUrl) |
| 280 | + } catch (_browserRefused) { |
| 281 | + // Headless or locked-down host: the panel shows `loginUrl` to open by hand. |
| 282 | + } |
| 283 | + return { status: 'started', loginUrl } |
| 284 | +} |
| 285 | + |
| 286 | +/** Abandon an in-flight login (closes the listener). */ |
| 287 | +export function cancelConsoleLogin(): void { |
| 288 | + active?.server.close() |
| 289 | + active = undefined |
| 290 | + state = { phase: 'idle' } |
| 291 | +} |
0 commit comments