|
| 1 | +import { createHash, randomBytes } from "node:crypto"; |
| 2 | +import { createServer } from "node:http"; |
| 3 | +import { isWSL2Sync } from "../../src/infra/wsl.js"; |
| 4 | +import { resolveOAuthClientConfig } from "./oauth.credentials.js"; |
| 5 | +import { AUTH_URL, REDIRECT_URI, SCOPES } from "./oauth.shared.js"; |
| 6 | + |
| 7 | +export function shouldUseManualOAuthFlow(isRemote: boolean): boolean { |
| 8 | + return isRemote || isWSL2Sync(); |
| 9 | +} |
| 10 | + |
| 11 | +export function generatePkce(): { verifier: string; challenge: string } { |
| 12 | + const verifier = randomBytes(32).toString("hex"); |
| 13 | + const challenge = createHash("sha256").update(verifier).digest("base64url"); |
| 14 | + return { verifier, challenge }; |
| 15 | +} |
| 16 | + |
| 17 | +export function buildAuthUrl(challenge: string, verifier: string): string { |
| 18 | + const { clientId } = resolveOAuthClientConfig(); |
| 19 | + const params = new URLSearchParams({ |
| 20 | + client_id: clientId, |
| 21 | + response_type: "code", |
| 22 | + redirect_uri: REDIRECT_URI, |
| 23 | + scope: SCOPES.join(" "), |
| 24 | + code_challenge: challenge, |
| 25 | + code_challenge_method: "S256", |
| 26 | + state: verifier, |
| 27 | + access_type: "offline", |
| 28 | + prompt: "consent", |
| 29 | + }); |
| 30 | + return `${AUTH_URL}?${params.toString()}`; |
| 31 | +} |
| 32 | + |
| 33 | +export function parseCallbackInput( |
| 34 | + input: string, |
| 35 | + expectedState: string, |
| 36 | +): { code: string; state: string } | { error: string } { |
| 37 | + const trimmed = input.trim(); |
| 38 | + if (!trimmed) { |
| 39 | + return { error: "No input provided" }; |
| 40 | + } |
| 41 | + |
| 42 | + try { |
| 43 | + const url = new URL(trimmed); |
| 44 | + const code = url.searchParams.get("code"); |
| 45 | + const state = url.searchParams.get("state") ?? expectedState; |
| 46 | + if (!code) { |
| 47 | + return { error: "Missing 'code' parameter in URL" }; |
| 48 | + } |
| 49 | + if (!state) { |
| 50 | + return { error: "Missing 'state' parameter. Paste the full URL." }; |
| 51 | + } |
| 52 | + return { code, state }; |
| 53 | + } catch { |
| 54 | + if (!expectedState) { |
| 55 | + return { error: "Paste the full redirect URL, not just the code." }; |
| 56 | + } |
| 57 | + return { code: trimmed, state: expectedState }; |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +export async function waitForLocalCallback(params: { |
| 62 | + expectedState: string; |
| 63 | + timeoutMs: number; |
| 64 | + onProgress?: (message: string) => void; |
| 65 | +}): Promise<{ code: string; state: string }> { |
| 66 | + const port = 8085; |
| 67 | + const hostname = "localhost"; |
| 68 | + const expectedPath = "/oauth2callback"; |
| 69 | + |
| 70 | + return new Promise<{ code: string; state: string }>((resolve, reject) => { |
| 71 | + let timeout: NodeJS.Timeout | null = null; |
| 72 | + const server = createServer((req, res) => { |
| 73 | + try { |
| 74 | + const requestUrl = new URL(req.url ?? "/", `http://${hostname}:${port}`); |
| 75 | + if (requestUrl.pathname !== expectedPath) { |
| 76 | + res.statusCode = 404; |
| 77 | + res.setHeader("Content-Type", "text/plain"); |
| 78 | + res.end("Not found"); |
| 79 | + return; |
| 80 | + } |
| 81 | + |
| 82 | + const error = requestUrl.searchParams.get("error"); |
| 83 | + const code = requestUrl.searchParams.get("code")?.trim(); |
| 84 | + const state = requestUrl.searchParams.get("state")?.trim(); |
| 85 | + |
| 86 | + if (error) { |
| 87 | + res.statusCode = 400; |
| 88 | + res.setHeader("Content-Type", "text/plain"); |
| 89 | + res.end(`Authentication failed: ${error}`); |
| 90 | + finish(new Error(`OAuth error: ${error}`)); |
| 91 | + return; |
| 92 | + } |
| 93 | + |
| 94 | + if (!code || !state) { |
| 95 | + res.statusCode = 400; |
| 96 | + res.setHeader("Content-Type", "text/plain"); |
| 97 | + res.end("Missing code or state"); |
| 98 | + finish(new Error("Missing OAuth code or state")); |
| 99 | + return; |
| 100 | + } |
| 101 | + |
| 102 | + if (state !== params.expectedState) { |
| 103 | + res.statusCode = 400; |
| 104 | + res.setHeader("Content-Type", "text/plain"); |
| 105 | + res.end("Invalid state"); |
| 106 | + finish(new Error("OAuth state mismatch")); |
| 107 | + return; |
| 108 | + } |
| 109 | + |
| 110 | + res.statusCode = 200; |
| 111 | + res.setHeader("Content-Type", "text/html; charset=utf-8"); |
| 112 | + res.end( |
| 113 | + "<!doctype html><html><head><meta charset='utf-8'/></head>" + |
| 114 | + "<body><h2>Gemini CLI OAuth complete</h2>" + |
| 115 | + "<p>You can close this window and return to OpenClaw.</p></body></html>", |
| 116 | + ); |
| 117 | + |
| 118 | + finish(undefined, { code, state }); |
| 119 | + } catch (err) { |
| 120 | + finish(err instanceof Error ? err : new Error("OAuth callback failed")); |
| 121 | + } |
| 122 | + }); |
| 123 | + |
| 124 | + const finish = (err?: Error, result?: { code: string; state: string }) => { |
| 125 | + if (timeout) { |
| 126 | + clearTimeout(timeout); |
| 127 | + } |
| 128 | + try { |
| 129 | + server.close(); |
| 130 | + } catch { |
| 131 | + // ignore close errors |
| 132 | + } |
| 133 | + if (err) { |
| 134 | + reject(err); |
| 135 | + } else if (result) { |
| 136 | + resolve(result); |
| 137 | + } |
| 138 | + }; |
| 139 | + |
| 140 | + server.once("error", (err) => { |
| 141 | + finish(err instanceof Error ? err : new Error("OAuth callback server error")); |
| 142 | + }); |
| 143 | + |
| 144 | + server.listen(port, hostname, () => { |
| 145 | + params.onProgress?.(`Waiting for OAuth callback on ${REDIRECT_URI}…`); |
| 146 | + }); |
| 147 | + |
| 148 | + timeout = setTimeout(() => { |
| 149 | + finish(new Error("OAuth callback timeout")); |
| 150 | + }, params.timeoutMs); |
| 151 | + }); |
| 152 | +} |
0 commit comments