|
| 1 | +import { createServer } from "node:http" |
| 2 | +import type { AddressInfo } from "node:net" |
| 3 | +import type { OpenSeaOAuth } from "@opensea/sdk" |
| 4 | + |
| 5 | +/** |
| 6 | + * Loopback IP the CLI binds for the OAuth redirect (RFC 8252 §7.3). Using the |
| 7 | + * literal `127.0.0.1` (not `localhost`) avoids DNS rebinding and matches the |
| 8 | + * loopback redirect URIs pre-registered on the public client. |
| 9 | + */ |
| 10 | +const LOOPBACK_HOST = "127.0.0.1" |
| 11 | + |
| 12 | +const CALLBACK_PATH = "/callback" |
| 13 | + |
| 14 | +/** |
| 15 | + * Run the authorization-code + PKCE flow over a temporary loopback HTTP server. |
| 16 | + * |
| 17 | + * Spins up `http://127.0.0.1:<random-port>/callback`, opens the browser to the |
| 18 | + * authorization endpoint, waits for the redirect, validates `state`, and |
| 19 | + * exchanges the code for tokens. No client secret, no private key. |
| 20 | + */ |
| 21 | +export async function loginWithLoopback( |
| 22 | + oauth: OpenSeaOAuth, |
| 23 | + options: { |
| 24 | + scopes: string[] |
| 25 | + openBrowser: (url: string) => void | Promise<void> |
| 26 | + timeoutMs?: number |
| 27 | + }, |
| 28 | +): Promise<import("@opensea/sdk").OAuthToken> { |
| 29 | + const { server, port } = await startServer() |
| 30 | + const redirectUri = `http://${LOOPBACK_HOST}:${port}${CALLBACK_PATH}` |
| 31 | + |
| 32 | + try { |
| 33 | + const request = await oauth.createAuthorizationRequest({ |
| 34 | + redirectUri, |
| 35 | + scopes: options.scopes, |
| 36 | + }) |
| 37 | + |
| 38 | + const codePromise = waitForCode(server, request.state, options.timeoutMs) |
| 39 | + await options.openBrowser(request.url) |
| 40 | + const code = await codePromise |
| 41 | + |
| 42 | + return await oauth.exchangeCode({ |
| 43 | + code, |
| 44 | + codeVerifier: request.codeVerifier, |
| 45 | + redirectUri, |
| 46 | + }) |
| 47 | + } finally { |
| 48 | + server.close() |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +function startServer(): Promise<{ |
| 53 | + server: import("node:http").Server |
| 54 | + port: number |
| 55 | +}> { |
| 56 | + return new Promise((resolve, reject) => { |
| 57 | + const server = createServer() |
| 58 | + server.on("error", reject) |
| 59 | + server.listen(0, LOOPBACK_HOST, () => { |
| 60 | + const address = server.address() as AddressInfo |
| 61 | + resolve({ server, port: address.port }) |
| 62 | + }) |
| 63 | + }) |
| 64 | +} |
| 65 | + |
| 66 | +/** Default time to wait for the browser redirect before giving up. */ |
| 67 | +const DEFAULT_TIMEOUT_MS = 5 * 60_000 |
| 68 | + |
| 69 | +function waitForCode( |
| 70 | + server: import("node:http").Server, |
| 71 | + expectedState: string, |
| 72 | + timeoutMs = DEFAULT_TIMEOUT_MS, |
| 73 | +): Promise<string> { |
| 74 | + return new Promise((resolve, reject) => { |
| 75 | + // Guard against a late or duplicate callback settling the promise twice |
| 76 | + // and against handling requests after we've already resolved/rejected. |
| 77 | + let settled = false |
| 78 | + const timer = setTimeout(() => { |
| 79 | + if (settled) return |
| 80 | + settled = true |
| 81 | + server.removeAllListeners("request") |
| 82 | + reject(new Error("Timed out waiting for authorization redirect")) |
| 83 | + }, timeoutMs) |
| 84 | + |
| 85 | + server.on("request", (req, res) => { |
| 86 | + const url = new URL(req.url ?? "/", `http://${LOOPBACK_HOST}`) |
| 87 | + if (url.pathname !== CALLBACK_PATH) { |
| 88 | + res.writeHead(404).end() |
| 89 | + return |
| 90 | + } |
| 91 | + if (settled) { |
| 92 | + res.writeHead(404).end() |
| 93 | + return |
| 94 | + } |
| 95 | + |
| 96 | + const error = url.searchParams.get("error") |
| 97 | + const code = url.searchParams.get("code") |
| 98 | + const state = url.searchParams.get("state") |
| 99 | + |
| 100 | + const finish = (message: string, ok: boolean) => { |
| 101 | + res.writeHead(ok ? 200 : 400, { "Content-Type": "text/html" }) |
| 102 | + res.end(renderResultPage(message, ok)) |
| 103 | + } |
| 104 | + const settle = () => { |
| 105 | + settled = true |
| 106 | + clearTimeout(timer) |
| 107 | + } |
| 108 | + |
| 109 | + if (error) { |
| 110 | + finish(`Authorization failed: ${error}`, false) |
| 111 | + settle() |
| 112 | + reject(new Error(`Authorization failed: ${error}`)) |
| 113 | + return |
| 114 | + } |
| 115 | + if (state !== expectedState) { |
| 116 | + finish("Authorization failed: state mismatch", false) |
| 117 | + settle() |
| 118 | + reject(new Error("State mismatch in authorization response")) |
| 119 | + return |
| 120 | + } |
| 121 | + if (!code) { |
| 122 | + finish("Authorization failed: missing code", false) |
| 123 | + settle() |
| 124 | + reject(new Error("No authorization code in redirect")) |
| 125 | + return |
| 126 | + } |
| 127 | + |
| 128 | + finish( |
| 129 | + "Login successful. You can close this tab and return to the CLI.", |
| 130 | + true, |
| 131 | + ) |
| 132 | + settle() |
| 133 | + resolve(code) |
| 134 | + }) |
| 135 | + }) |
| 136 | +} |
| 137 | + |
| 138 | +function renderResultPage(message: string, ok: boolean): string { |
| 139 | + const color = ok ? "#2081e2" : "#e23b2b" |
| 140 | + return `<!doctype html><html><head><meta charset="utf-8"><title>OpenSea CLI</title></head><body style="font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;background:#f5f7fb"><div style="text-align:center"><h2 style="color:${color}">OpenSea</h2><p>${escapeHtml(message)}</p></div></body></html>` |
| 141 | +} |
| 142 | + |
| 143 | +/** |
| 144 | + * Escape a string for safe interpolation into HTML text content. The OAuth |
| 145 | + * `error` param is attacker-influenced (it comes from the redirect query |
| 146 | + * string), so it must be encoded before it reaches the result page. |
| 147 | + */ |
| 148 | +function escapeHtml(value: string): string { |
| 149 | + return value |
| 150 | + .replace(/&/g, "&") |
| 151 | + .replace(/</g, "<") |
| 152 | + .replace(/>/g, ">") |
| 153 | + .replace(/"/g, """) |
| 154 | + .replace(/'/g, "'") |
| 155 | +} |
0 commit comments