|
| 1 | +import { createServer } from "node:http"; |
| 2 | +import { randomUUID } from "node:crypto"; |
| 3 | + |
| 4 | +/** |
| 5 | + * `omniroute login antigravity` — local OAuth helper for remote installs. |
| 6 | + * |
| 7 | + * Why this exists: Google's `firstparty/nativeapp` consent for the embedded |
| 8 | + * Antigravity desktop client only releases the authorization code when the |
| 9 | + * loopback redirect (127.0.0.1:<port>) is REACHABLE. On a remote VPS install the |
| 10 | + * loopback is unreachable, so the consent hangs forever and never emits a code — |
| 11 | + * the dashboard's "paste the callback URL" fallback has nothing to paste. (The |
| 12 | + * same flow works locally and over an SSH tunnel, where the loopback IS reachable.) |
| 13 | + * |
| 14 | + * This command runs the OAuth on the user's OWN machine — where 127.0.0.1 works — |
| 15 | + * captures the code on a local loopback server, exchanges it for tokens, and |
| 16 | + * prints a single-line credential blob. The user pastes that blob into the remote |
| 17 | + * dashboard (Antigravity → "Paste credentials"), which decodes it, finalizes the |
| 18 | + * onboarding server-side, and persists the connection. |
| 19 | + * |
| 20 | + * It talks ONLY to Google (no OmniRoute server needed locally), so it works even |
| 21 | + * if the remote VPS is firewalled from the user's machine. |
| 22 | + */ |
| 23 | + |
| 24 | +const PROVIDER = "antigravity"; |
| 25 | + |
| 26 | +/** Open the system browser; no-op if the optional `open` dependency is missing. */ |
| 27 | +async function defaultOpenBrowser(url) { |
| 28 | + try { |
| 29 | + const { default: open } = await import("open"); |
| 30 | + await open(url); |
| 31 | + } catch { |
| 32 | + // `open` not available — the caller already printed the URL to paste manually. |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +/** |
| 37 | + * Start a loopback HTTP server bound to 127.0.0.1 (NOT 0.0.0.0 — we never want to |
| 38 | + * expose the callback to the LAN). Resolves to { port, waitForCallback, close }. |
| 39 | + */ |
| 40 | +function defaultStartServer(preferredPort) { |
| 41 | + return new Promise((resolve, reject) => { |
| 42 | + let resolveCallback; |
| 43 | + const callbackPromise = new Promise((r) => { |
| 44 | + resolveCallback = r; |
| 45 | + }); |
| 46 | + |
| 47 | + const server = createServer((req, res) => { |
| 48 | + const url = new URL(req.url, "http://127.0.0.1"); |
| 49 | + if (url.pathname !== "/callback" && url.pathname !== "/auth/callback") { |
| 50 | + res.writeHead(404).end(); |
| 51 | + return; |
| 52 | + } |
| 53 | + const params = Object.fromEntries(url.searchParams.entries()); |
| 54 | + res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); |
| 55 | + res.end( |
| 56 | + "<!doctype html><meta charset=utf-8><title>OmniRoute</title>" + |
| 57 | + "<body style=\"font-family:system-ui;padding:2rem\">" + |
| 58 | + "<h2>✅ Authorization received</h2>" + |
| 59 | + "<p>Return to your terminal — you can close this tab.</p></body>" |
| 60 | + ); |
| 61 | + resolveCallback(params); |
| 62 | + }); |
| 63 | + |
| 64 | + server.on("error", reject); |
| 65 | + server.listen(preferredPort || 0, "127.0.0.1", () => { |
| 66 | + const { port } = server.address(); |
| 67 | + resolve({ |
| 68 | + port, |
| 69 | + waitForCallback: () => callbackPromise, |
| 70 | + close: () => new Promise((r) => server.close(() => r())), |
| 71 | + }); |
| 72 | + }); |
| 73 | + }); |
| 74 | +} |
| 75 | + |
| 76 | +/** Lazy-load the antigravity provider + blob codec (TS source via tsx). */ |
| 77 | +async function loadDeps() { |
| 78 | + const { antigravity } = await import("../../../src/lib/oauth/providers/antigravity.ts"); |
| 79 | + const { encodeCredentialBlob } = await import("../../../src/lib/oauth/credentialBlob.ts"); |
| 80 | + return { antigravity, encodeCredentialBlob }; |
| 81 | +} |
| 82 | + |
| 83 | +/** |
| 84 | + * Build the Google authorization request for a given loopback port. Uses a plain |
| 85 | + * authorization_code grant (NO PKCE code_challenge) — matching the working flow: |
| 86 | + * a code_challenge here would force the exchange to require a code_verifier. |
| 87 | + */ |
| 88 | +export async function buildAntigravityAuthRequest(port, makeState = randomUUID) { |
| 89 | + const { antigravity } = await loadDeps(); |
| 90 | + const redirectUri = `http://127.0.0.1:${port}/callback`; |
| 91 | + const state = makeState(); |
| 92 | + const authUrl = antigravity.buildAuthUrl(antigravity.config, redirectUri, state); |
| 93 | + return { redirectUri, state, authUrl }; |
| 94 | +} |
| 95 | + |
| 96 | +/** Exchange the captured code for raw Google tokens (no code_verifier — no PKCE). */ |
| 97 | +export async function exchangeAntigravityCode(code, redirectUri) { |
| 98 | + const { antigravity } = await loadDeps(); |
| 99 | + return antigravity.exchangeToken(antigravity.config, code, redirectUri); |
| 100 | +} |
| 101 | + |
| 102 | +/** |
| 103 | + * Orchestrate the local login. Dependencies are injectable for testing; the real |
| 104 | + * path uses a 127.0.0.1 loopback server, the system browser, and a live token |
| 105 | + * exchange against Google. Returns the credential blob string. |
| 106 | + */ |
| 107 | +export async function runAntigravityLogin(opts = {}, deps = {}) { |
| 108 | + const startServer = deps.startServer ?? defaultStartServer; |
| 109 | + const openBrowser = deps.openBrowser ?? defaultOpenBrowser; |
| 110 | + const exchange = deps.exchange ?? exchangeAntigravityCode; |
| 111 | + const makeState = deps.makeState ?? randomUUID; |
| 112 | + const print = deps.print ?? ((s) => process.stdout.write(s)); |
| 113 | + const log = deps.log ?? ((s) => process.stderr.write(s)); |
| 114 | + const { encodeCredentialBlob } = await loadDeps(); |
| 115 | + |
| 116 | + const server = await startServer(opts.port); |
| 117 | + const { redirectUri, state, authUrl } = await buildAntigravityAuthRequest(server.port, makeState); |
| 118 | + |
| 119 | + log(`\nOpen this URL to authorize Antigravity (it will open automatically):\n\n ${authUrl}\n\n`); |
| 120 | + if (opts.browser !== false) await openBrowser(authUrl); |
| 121 | + log("Waiting for Google to redirect back to the local loopback...\n"); |
| 122 | + |
| 123 | + const timeoutMs = opts.timeout ?? 300000; |
| 124 | + let timer; |
| 125 | + let params; |
| 126 | + try { |
| 127 | + params = await Promise.race([ |
| 128 | + server.waitForCallback(), |
| 129 | + new Promise((_, reject) => { |
| 130 | + timer = setTimeout( |
| 131 | + () => reject(new Error("Timed out waiting for the OAuth callback")), |
| 132 | + timeoutMs |
| 133 | + ); |
| 134 | + // Don't keep the event loop alive solely for this timer. |
| 135 | + if (typeof timer.unref === "function") timer.unref(); |
| 136 | + }), |
| 137 | + ]); |
| 138 | + } finally { |
| 139 | + clearTimeout(timer); |
| 140 | + await server.close(); |
| 141 | + } |
| 142 | + |
| 143 | + if (params.error) { |
| 144 | + throw new Error(`Authorization failed: ${params.error_description || params.error}`); |
| 145 | + } |
| 146 | + if (params.state !== state) { |
| 147 | + throw new Error("State mismatch — aborting (possible CSRF). Please retry the login."); |
| 148 | + } |
| 149 | + if (!params.code) { |
| 150 | + throw new Error("No authorization code returned by Google."); |
| 151 | + } |
| 152 | + |
| 153 | + const tokens = await exchange(params.code, redirectUri); |
| 154 | + const blob = encodeCredentialBlob({ provider: PROVIDER, tokens }); |
| 155 | + |
| 156 | + print( |
| 157 | + "\n" + |
| 158 | + "Antigravity authorized. Copy the line below and paste it into your remote\n" + |
| 159 | + "OmniRoute dashboard: Providers → Antigravity → Connect → \"Paste credentials\".\n" + |
| 160 | + "(This contains a refresh token — treat it like a password.)\n\n" + |
| 161 | + blob + |
| 162 | + "\n\n" |
| 163 | + ); |
| 164 | + return blob; |
| 165 | +} |
| 166 | + |
| 167 | +async function runLoginAntigravity(opts) { |
| 168 | + try { |
| 169 | + await runAntigravityLogin({ |
| 170 | + browser: opts.browser, |
| 171 | + timeout: opts.timeout, |
| 172 | + port: opts.port, |
| 173 | + }); |
| 174 | + } catch (err) { |
| 175 | + process.stderr.write(`\nLogin failed: ${err?.message || err}\n`); |
| 176 | + process.exit(1); |
| 177 | + } |
| 178 | +} |
| 179 | + |
| 180 | +export function registerLogin(program) { |
| 181 | + const login = program |
| 182 | + .command("login") |
| 183 | + .description("Local OAuth helpers for remote OmniRoute installs (run on your own machine)"); |
| 184 | + |
| 185 | + login |
| 186 | + .command("antigravity") |
| 187 | + .description("Authorize Antigravity locally and print a credential blob to paste remotely") |
| 188 | + .option("--no-browser", "Do not auto-open the browser; print the URL instead") |
| 189 | + .option("--port <n>", "Fixed loopback port (default: OS-assigned)", (v) => parseInt(v, 10)) |
| 190 | + .option("--timeout <ms>", "How long to wait for the callback", (v) => parseInt(v, 10), 300000) |
| 191 | + .action(runLoginAntigravity); |
| 192 | +} |
0 commit comments