|
| 1 | +/** |
| 2 | + * Login Command |
| 3 | + * |
| 4 | + * Opens the browser to EffectTalk.dev for authentication and captures |
| 5 | + * the API key via a local callback server. |
| 6 | + */ |
| 7 | + |
| 8 | +import { Command } from "@effect/cli"; |
| 9 | +import { Console, Duration, Effect } from "effect"; |
| 10 | +import { randomBytes } from "node:crypto"; |
| 11 | +import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; |
| 12 | +import { writeConfig } from "../services/config/writer.js"; |
| 13 | + |
| 14 | +const AUTH_BASE_URL = "https://effecttalk.dev/cli/auth"; |
| 15 | +const PRIMARY_PORT = 4567; |
| 16 | +const FALLBACK_PORT = 4568; |
| 17 | +const TIMEOUT = Duration.minutes(5); |
| 18 | + |
| 19 | +interface AuthResult { |
| 20 | + readonly apiKey: string; |
| 21 | + readonly email: string; |
| 22 | +} |
| 23 | + |
| 24 | +/** |
| 25 | + * Try to start an HTTP server on the given port. |
| 26 | + * Returns an Effect that fails if the port is busy. |
| 27 | + */ |
| 28 | +const tryListen = (server: Server, port: number): Effect.Effect<number, Error> => |
| 29 | + Effect.async<number, Error>((resume) => { |
| 30 | + server.once("error", (err: NodeJS.ErrnoException) => { |
| 31 | + resume(Effect.fail(new Error(`Port ${port} unavailable: ${err.code}`))); |
| 32 | + }); |
| 33 | + server.listen(port, "127.0.0.1", () => { |
| 34 | + resume(Effect.succeed(port)); |
| 35 | + }); |
| 36 | + }); |
| 37 | + |
| 38 | +/** |
| 39 | + * Open a URL in the user's default browser. |
| 40 | + */ |
| 41 | +const openBrowser = (url: string): Effect.Effect<void, Error> => |
| 42 | + Effect.try({ |
| 43 | + try: () => { |
| 44 | + const { exec } = require("node:child_process") as typeof import("node:child_process"); |
| 45 | + const cmd = |
| 46 | + process.platform === "darwin" |
| 47 | + ? "open" |
| 48 | + : process.platform === "win32" |
| 49 | + ? "start" |
| 50 | + : "xdg-open"; |
| 51 | + exec(`${cmd} "${url}"`); |
| 52 | + }, |
| 53 | + catch: (error) => |
| 54 | + error instanceof Error ? error : new Error(`Failed to open browser: ${String(error)}`), |
| 55 | + }); |
| 56 | + |
| 57 | +/** |
| 58 | + * Wait for the authentication callback on the local server. |
| 59 | + */ |
| 60 | +const waitForCallback = ( |
| 61 | + server: Server, |
| 62 | + port: number, |
| 63 | + expectedState: string, |
| 64 | +): Effect.Effect<AuthResult, Error> => |
| 65 | + Effect.async<AuthResult, Error>((resume) => { |
| 66 | + server.on("request", (req: IncomingMessage, res: ServerResponse) => { |
| 67 | + const url = new URL(req.url ?? "/", `http://127.0.0.1:${port}`); |
| 68 | + |
| 69 | + if (url.pathname !== "/callback") { |
| 70 | + res.writeHead(404, { "Content-Type": "text/plain" }); |
| 71 | + res.end("Not Found"); |
| 72 | + return; |
| 73 | + } |
| 74 | + |
| 75 | + const state = url.searchParams.get("state"); |
| 76 | + if (state !== expectedState) { |
| 77 | + res.writeHead(403, { "Content-Type": "text/plain" }); |
| 78 | + res.end("Invalid state parameter"); |
| 79 | + return; |
| 80 | + } |
| 81 | + |
| 82 | + const apiKey = url.searchParams.get("apiKey") ?? ""; |
| 83 | + const email = url.searchParams.get("email") ?? ""; |
| 84 | + |
| 85 | + if (!apiKey) { |
| 86 | + res.writeHead(400, { "Content-Type": "text/plain" }); |
| 87 | + res.end("Missing apiKey parameter"); |
| 88 | + resume(Effect.fail(new Error("Callback received without apiKey"))); |
| 89 | + return; |
| 90 | + } |
| 91 | + |
| 92 | + res.writeHead(200, { "Content-Type": "text/html" }); |
| 93 | + res.end( |
| 94 | + "<html><body style=\"font-family:system-ui;text-align:center;padding:2em\">" + |
| 95 | + "<h1>Success!</h1><p>You can close this tab and return to the terminal.</p>" + |
| 96 | + "</body></html>" |
| 97 | + ); |
| 98 | + |
| 99 | + resume(Effect.succeed({ apiKey, email })); |
| 100 | + }); |
| 101 | + }); |
| 102 | + |
| 103 | +/** |
| 104 | + * Shut down the HTTP server. |
| 105 | + */ |
| 106 | +const closeServer = (server: Server): Effect.Effect<void> => |
| 107 | + Effect.async<void>((resume) => { |
| 108 | + server.close(() => { |
| 109 | + resume(Effect.succeed(void 0)); |
| 110 | + }); |
| 111 | + }); |
| 112 | + |
| 113 | +export const loginCommand = Command.make("login").pipe( |
| 114 | + Command.withDescription("Authenticate with EffectTalk.dev"), |
| 115 | + Command.withHandler(() => |
| 116 | + Effect.gen(function* () { |
| 117 | + const state = randomBytes(32).toString("hex"); |
| 118 | + const server = createServer(); |
| 119 | + |
| 120 | + // Try primary port, fall back to secondary |
| 121 | + const port = yield* tryListen(server, PRIMARY_PORT).pipe( |
| 122 | + Effect.orElse(() => tryListen(server, FALLBACK_PORT)), |
| 123 | + Effect.mapError(() => new Error( |
| 124 | + `Could not start local server on port ${PRIMARY_PORT} or ${FALLBACK_PORT}. ` + |
| 125 | + "Please free one of these ports and try again." |
| 126 | + )), |
| 127 | + ); |
| 128 | + |
| 129 | + const authUrl = `${AUTH_BASE_URL}?state=${state}&port=${port}`; |
| 130 | + |
| 131 | + yield* Console.log("\nAuthenticating with EffectTalk..."); |
| 132 | + yield* Console.log("Your browser should open automatically.\n"); |
| 133 | + yield* Console.log(`If it doesn't, open this URL manually:`); |
| 134 | + yield* Console.log(` ${authUrl}\n`); |
| 135 | + yield* Console.log("Waiting for authentication... (timeout: 5 minutes)\n"); |
| 136 | + |
| 137 | + // Open browser (best-effort — don't fail if it can't open) |
| 138 | + yield* openBrowser(authUrl).pipe(Effect.catchAll(() => Effect.void)); |
| 139 | + |
| 140 | + // Wait for callback with timeout |
| 141 | + const result = yield* waitForCallback(server, port, state).pipe( |
| 142 | + Effect.timeout(TIMEOUT), |
| 143 | + Effect.catchTag("TimeoutException", () => |
| 144 | + Effect.fail(new Error( |
| 145 | + "Authentication timed out after 5 minutes.\n" + |
| 146 | + "Run `ep login` again to retry." |
| 147 | + )) |
| 148 | + ), |
| 149 | + Effect.ensuring(closeServer(server)), |
| 150 | + ); |
| 151 | + |
| 152 | + // Write credentials to config file |
| 153 | + const configPath = yield* writeConfig({ |
| 154 | + apiKey: result.apiKey, |
| 155 | + email: result.email, |
| 156 | + }); |
| 157 | + |
| 158 | + const displayEmail = result.email || "unknown"; |
| 159 | + yield* Console.log(`Success! Authenticated as ${displayEmail}.`); |
| 160 | + yield* Console.log(` API key saved to ${configPath}`); |
| 161 | + }) |
| 162 | + ) |
| 163 | +); |
0 commit comments