import { createServer } from "node:http" import type { AddressInfo } from "node:net" import { spawn } from "node:child_process" import { randomBytes } from "node:crypto" import { hostname } from "node:os" import { CliError, c, info, log } from "../cli" /* * Browser login (loopback OAuth-style flow, like `vercel`/`gh`): * 1. start a one-shot HTTP listener on 127.0.0.1: * 2. open the browser to /app/cli-auth?port&state&name * 3. the web page (user already signed in) mints a personal access token and redirects it back * to the local listener, which captures it and shows a success page. * `state` is a random nonce echoed back to prevent another local page from injecting a token. */ const SUCCESS_HTML = `lecodes

✓ Authorized

You can close this tab and return to your terminal.

` const errorHtml = (msg: string) => `lecodes

Authorization failed

${msg}

` /** Open a URL in the default browser (best-effort; the URL is also printed as a fallback). */ export const openBrowser = (url: string) => { let cmd: string let args: string[] if (process.platform === "win32") { cmd = "rundll32"; args = [ "url.dll,FileProtocolHandler", url ] } else if (process.platform === "darwin") { cmd = "open"; args = [ url ] } else { cmd = "xdg-open"; args = [ url ] } try { const child = spawn(cmd, args, { stdio: "ignore", detached: true }) child.on("error", () => {}) child.unref() } catch { /* fall back to the printed URL */ } } /** Run the browser login flow against `webBase` (the app origin) and resolve the access token. */ export const browserLogin = async ( webBase: string, timeoutMs = 5 * 60 * 1000, open: (url: string) => void = openBrowser, ): Promise => { const state = randomBytes(16).toString("hex") let resolve!: (token: string) => void let reject!: (err: Error) => void const tokenPromise = new Promise((res, rej) => { resolve = res; reject = rej }) const server = createServer((req, res) => { const url = new URL(req.url ?? "/", "http://127.0.0.1") if (url.pathname !== "/") { res.writeHead(404); res.end(); return } const token = url.searchParams.get("token") if (!token || url.searchParams.get("state") !== state) { res.writeHead(400, { "content-type": "text/html" }) res.end(errorHtml("Invalid or expired authorization.")) return } res.writeHead(200, { "content-type": "text/html" }) res.end(SUCCESS_HTML) resolve(token) }) await new Promise((res, rej) => { server.once("error", rej) server.listen(0, "127.0.0.1", res) }) const port = (server.address() as AddressInfo).port const timer = setTimeout(() => reject(new CliError("Timed out waiting for browser authorization.")), timeoutMs) const authUrl = `${webBase}/app/cli-auth?port=${port}&state=${state}&name=${encodeURIComponent(hostname())}` info("Opening your browser to authorize the CLI…") log(c.dim(" " + authUrl)) log(c.dim(" (waiting — finish in the browser, or press Ctrl+C to cancel)")) open(authUrl) try { return await tokenPromise } finally { clearTimeout(timer) server.close() } }