From 49f69f4d194ef7acc71225eb7f0cccc772ecbeaf Mon Sep 17 00:00:00 2001 From: DIYgod Date: Fri, 27 Feb 2026 16:51:58 +0800 Subject: [PATCH] feat(cli): support browser-based auth login (#4887) --- apps/cli/skill.md | 8 +- apps/cli/src/browser-login.test.ts | 48 +++++ apps/cli/src/browser-login.ts | 222 ++++++++++++++++++++++++ apps/cli/src/client.ts | 2 +- apps/cli/src/commands/auth.ts | 24 ++- apps/ssr/client/modules/login/index.tsx | 83 ++++++++- 6 files changed, 374 insertions(+), 13 deletions(-) create mode 100644 apps/cli/src/browser-login.test.ts create mode 100644 apps/cli/src/browser-login.ts diff --git a/apps/cli/skill.md b/apps/cli/skill.md index ca3eb16db..1aa187a64 100644 --- a/apps/cli/skill.md +++ b/apps/cli/skill.md @@ -16,7 +16,8 @@ Use this skill when a user asks to: 1. Folo CLI is installed and executable as `folo`. 2. Authentication is configured: - - `folo auth login --token ` + - `folo auth login` (recommended, opens browser and auto-logins) + - or `folo auth login --token ` - or set `FOLO_TOKEN=` ## Output Contract @@ -113,7 +114,7 @@ Loop until `hasNext` is `false`: ## Command Reference -- `folo auth login --token ` +- `folo auth login [--timeout ] [--token ]` - `folo auth logout` - `folo auth whoami` @@ -163,7 +164,8 @@ Loop until `hasNext` is `false`: ## Error Recovery - `UNAUTHORIZED` - - Re-login: `folo auth login --token ` + - Re-login: `folo auth login` + - or `folo auth login --token ` - Or set `FOLO_TOKEN` - `HTTP_4xx` / `HTTP_5xx` - Retry with `--verbose` for request details diff --git a/apps/cli/src/browser-login.test.ts b/apps/cli/src/browser-login.test.ts new file mode 100644 index 000000000..8718c70fa --- /dev/null +++ b/apps/cli/src/browser-login.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from "vitest" + +import { DEFAULT_VALUES } from "../../../packages/internal/shared/src/env.common" +import { resolveCLILoginUrl } from "./browser-login" + +describe("browser login helpers", () => { + it("maps production API URL using env.common", () => { + const url = resolveCLILoginUrl(DEFAULT_VALUES.PROD.API_URL, "http://127.0.0.1:12345/callback") + const parsed = new URL(url) + + expect(parsed.origin).toBe(new URL(DEFAULT_VALUES.PROD.WEB_URL).origin) + expect(parsed.pathname).toBe("/login") + expect(parsed.searchParams.get("cli_callback")).toBe("http://127.0.0.1:12345/callback") + }) + + it("maps dev API URL using env.common", () => { + const url = resolveCLILoginUrl(DEFAULT_VALUES.DEV.API_URL, "http://127.0.0.1:12345/callback") + const parsed = new URL(url) + + expect(parsed.origin).toBe(new URL(DEFAULT_VALUES.DEV.WEB_URL).origin) + expect(parsed.pathname).toBe("/login") + expect(parsed.searchParams.get("cli_callback")).toBe("http://127.0.0.1:12345/callback") + }) + + it("maps local API URL using env.common", () => { + const url = resolveCLILoginUrl(DEFAULT_VALUES.LOCAL.API_URL, "http://127.0.0.1:12345/callback") + const parsed = new URL(url) + + expect(parsed.origin).toBe(new URL(DEFAULT_VALUES.LOCAL.WEB_URL).origin) + expect(parsed.pathname).toBe("/login") + expect(parsed.searchParams.get("cli_callback")).toBe("http://127.0.0.1:12345/callback") + }) + + it("falls back to API origin when no mapping exists", () => { + const url = resolveCLILoginUrl("https://api.follow.is", "http://localhost:3456/callback") + const parsed = new URL(url) + + expect(parsed.origin).toBe("https://api.follow.is") + expect(parsed.pathname).toBe("/login") + expect(parsed.searchParams.get("cli_callback")).toBe("http://localhost:3456/callback") + }) + + it("throws for invalid api url", () => { + expect(() => resolveCLILoginUrl("not-a-url", "http://127.0.0.1:3333/callback")).toThrowError( + /Invalid API URL/, + ) + }) +}) diff --git a/apps/cli/src/browser-login.ts b/apps/cli/src/browser-login.ts new file mode 100644 index 000000000..2a14e232a --- /dev/null +++ b/apps/cli/src/browser-login.ts @@ -0,0 +1,222 @@ +import { spawnSync } from "node:child_process" +import { createServer } from "node:http" +import type { AddressInfo } from "node:net" + +import { DEFAULT_VALUES } from "../../../packages/internal/shared/src/env.common" +import { CLIError } from "./output" + +const LOCAL_CALLBACK_HOST = "127.0.0.1" +const LOCAL_CALLBACK_PATH = "/callback" +const DEFAULT_TIMEOUT_MS = 3 * 60 * 1000 + +const mappedWebOrigins: Array<{ apiOrigin: string; webOrigin: string }> = [ + { + apiOrigin: new URL(DEFAULT_VALUES.PROD.API_URL).origin, + webOrigin: new URL(DEFAULT_VALUES.PROD.WEB_URL).origin, + }, + { + apiOrigin: new URL(DEFAULT_VALUES.DEV.API_URL).origin, + webOrigin: new URL(DEFAULT_VALUES.DEV.WEB_URL).origin, + }, + { + apiOrigin: new URL(DEFAULT_VALUES.LOCAL.API_URL).origin, + webOrigin: new URL(DEFAULT_VALUES.LOCAL.WEB_URL).origin, + }, +] + +const successPageHtml = ` + + + + + Folo CLI Login + + +

Folo CLI login complete

+

You can close this window and return to your terminal.

+ + +` + +const failurePageHtml = ` + + + + + Folo CLI Login + + +

Folo CLI login failed

+

Missing token in callback URL. Please retry in terminal.

+ + +` + +const getOpenBrowserCommand = (url: string): { command: string; args: string[] } => { + if (process.platform === "darwin") { + return { command: "open", args: [url] } + } + + if (process.platform === "win32") { + return { command: "cmd", args: ["/c", "start", "", url] } + } + + return { command: "xdg-open", args: [url] } +} + +const openBrowser = (url: string) => { + const { command, args } = getOpenBrowserCommand(url) + const result = spawnSync(command, args, { + stdio: "ignore", + }) + + if (result.error || result.status !== 0) { + throw new CLIError( + "BROWSER_OPEN_FAILED", + `Failed to open browser automatically. Open this URL manually: ${url}`, + ) + } +} + +export const resolveCLILoginUrl = (apiUrl: string, callbackUrl: string): string => { + let api: URL + try { + api = new URL(apiUrl) + } catch { + throw new CLIError("INVALID_ARGUMENT", `Invalid API URL: ${apiUrl}`) + } + + const mappedWebOrigin = mappedWebOrigins.find((item) => item.apiOrigin === api.origin)?.webOrigin + const webUrl = new URL(mappedWebOrigin ?? api.origin) + + webUrl.pathname = "/login" + webUrl.search = "" + webUrl.hash = "" + webUrl.searchParams.set("cli_callback", callbackUrl) + + return webUrl.toString() +} + +export interface BrowserLoginOptions { + apiUrl: string + timeoutMs?: number + onStatus?: (message: string) => void +} + +export interface BrowserLoginResult { + token: string + callbackUrl: string + loginUrl: string +} + +export const loginWithBrowser = async ( + options: BrowserLoginOptions, +): Promise => { + const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS + const onStatus = options.onStatus ?? (() => {}) + + if (timeoutMs <= 0) { + throw new CLIError("INVALID_ARGUMENT", "Browser login timeout must be greater than 0.") + } + + const result = await new Promise((resolve, reject) => { + let settled = false + let timer: NodeJS.Timeout | undefined + + const settle = (handler: () => void) => { + if (settled) { + return + } + settled = true + if (timer) { + clearTimeout(timer) + } + server.close(() => { + handler() + }) + } + + const server = createServer((req, res) => { + const requestUrl = new URL( + req.url ?? "/", + `http://${req.headers.host ?? LOCAL_CALLBACK_HOST}`, + ) + + if (requestUrl.pathname !== LOCAL_CALLBACK_PATH) { + res.statusCode = 404 + res.end("Not Found") + return + } + + const token = requestUrl.searchParams.get("token") + if (!token) { + res.statusCode = 400 + res.setHeader("content-type", "text/html; charset=utf-8") + res.end(failurePageHtml) + return + } + + res.statusCode = 200 + res.setHeader("content-type", "text/html; charset=utf-8") + res.end(successPageHtml) + + const callbackAddress = server.address() as AddressInfo | null + const callbackUrl = callbackAddress + ? `http://${LOCAL_CALLBACK_HOST}:${callbackAddress.port}${LOCAL_CALLBACK_PATH}` + : "" + const loginUrl = resolveCLILoginUrl(options.apiUrl, callbackUrl) + + settle(() => { + resolve({ + token, + callbackUrl, + loginUrl, + }) + }) + }) + + server.once("error", (error) => { + settle(() => { + reject( + new CLIError("NETWORK_ERROR", `Failed to start local callback server: ${error.message}`), + ) + }) + }) + + server.listen(0, LOCAL_CALLBACK_HOST, () => { + const address = server.address() as AddressInfo | null + if (!address) { + settle(() => { + reject(new CLIError("NETWORK_ERROR", "Failed to bind local callback server.")) + }) + return + } + + const callbackUrl = `http://${LOCAL_CALLBACK_HOST}:${address.port}${LOCAL_CALLBACK_PATH}` + const loginUrl = resolveCLILoginUrl(options.apiUrl, callbackUrl) + + onStatus(`Open this URL to sign in: ${loginUrl}`) + + try { + openBrowser(loginUrl) + onStatus("Browser opened. Waiting for login confirmation...") + } catch (error) { + onStatus((error as Error).message) + onStatus("Waiting for login confirmation...") + } + + timer = setTimeout(() => { + settle(() => { + reject( + new CLIError( + "TIMEOUT", + "Timed out waiting for browser login. Please run `folo auth login` again.", + ), + ) + }) + }, timeoutMs) + }) + }) + + return result +} diff --git a/apps/cli/src/client.ts b/apps/cli/src/client.ts index 2d74ba18d..2f8cb7965 100644 --- a/apps/cli/src/client.ts +++ b/apps/cli/src/client.ts @@ -82,7 +82,7 @@ export const createCommandContext = async ( if (requireAuth && !token) { throw new CLIError( "UNAUTHORIZED", - "Missing token. Run `folo auth login --token ` or set FOLO_TOKEN.", + "Missing token. Run `folo auth login` (browser sign-in) or set FOLO_TOKEN.", ) } diff --git a/apps/cli/src/commands/auth.ts b/apps/cli/src/commands/auth.ts index c8503b8ec..872b88c81 100644 --- a/apps/cli/src/commands/auth.ts +++ b/apps/cli/src/commands/auth.ts @@ -1,12 +1,15 @@ import type { Command } from "commander" +import { parsePositiveInt } from "../args" +import { loginWithBrowser } from "../browser-login" import { getGlobalOptions } from "../client" import { runCommand } from "../command" import { clearToken, getConfigPath, updateConfig } from "../config" import { CLIError } from "../output" interface AuthLoginOptions { - token: string + token?: string + timeout?: number } export const registerAuthCommand = (program: Command) => { @@ -14,15 +17,28 @@ export const registerAuthCommand = (program: Command) => { authCommand .command("login") - .description("Save session token and verify authentication") + .description("Sign in via browser (or save a provided token) and verify authentication") .option("--token ", "Session token from Folo") + .option( + "--timeout ", + "Browser login timeout in seconds (default: 180)", + parsePositiveInt, + ) .action(async function (this: Command, options: AuthLoginOptions) { await runCommand( this, async ({ client, options: globalOptions }) => { - const token = options.token ?? getGlobalOptions(this).token + let token = options.token ?? getGlobalOptions(this).token if (!token) { - throw new CLIError("INVALID_ARGUMENT", "Missing token. Use --token .") + const timeoutMs = (options.timeout ?? 180) * 1000 + const browserLogin = await loginWithBrowser({ + apiUrl: globalOptions.apiUrl, + timeoutMs, + onStatus: (message) => { + console.error(`[auth] ${message}`) + }, + }) + token = browserLogin.token } client.setAuthToken(token) diff --git a/apps/ssr/client/modules/login/index.tsx b/apps/ssr/client/modules/login/index.tsx index e1952d44e..8aa0aba64 100644 --- a/apps/ssr/client/modules/login/index.tsx +++ b/apps/ssr/client/modules/login/index.tsx @@ -4,6 +4,7 @@ import { getLastUsedLoginMethod, loginHandler, oneTimeToken, + signIn, signOut, twoFactor, } from "@client/lib/auth" @@ -36,6 +37,37 @@ import { Link, useLocation, useNavigate } from "react-router" import { toast } from "sonner" import { z } from "zod" +const parseCliCallbackUrl = (search: string): URL | null => { + const params = new URLSearchParams(search) + const rawCliCallback = params.get("cli_callback") + if (!rawCliCallback) { + return null + } + + try { + const url = new URL(rawCliCallback) + const isAllowedProtocol = url.protocol === "http:" + const isAllowedHost = url.hostname === "127.0.0.1" || url.hostname === "localhost" + + if (!isAllowedProtocol || !isAllowedHost) { + return null + } + + return url + } catch { + return null + } +} + +const parseTokenFromDeepLinkPath = (path: string): string | null => { + try { + const url = new URL(path, window.location.origin) + return url.searchParams.get("token") + } catch { + return null + } +} + export function Login() { const { status, refetch } = useSession() @@ -47,17 +79,33 @@ export function Login() { const urlParams = new URLSearchParams(location.search) const provider = urlParams.get("provider") const isCredentialProvider = provider === "credential" + const cliCallbackUrl = useMemo(() => parseCliCallbackUrl(location.search), [location.search]) const isAuthenticated = status === "authenticated" const { t } = useTranslation() + const startSocialLogin = useCallback( + (providerName: string) => { + if (cliCallbackUrl) { + void signIn.social({ + provider: providerName as "google" | "github" | "apple", + callbackURL: window.location.href, + }) + return + } + + loginHandler(providerName, "app") + }, + [cliCallbackUrl], + ) + useEffect(() => { if (provider && !isCredentialProvider && status === "unauthenticated") { - loginHandler(provider, "app") + startSocialLogin(provider) setRedirecting(true) } - }, [isCredentialProvider, provider, status]) + }, [isCredentialProvider, provider, startSocialLogin, status]) const getCallbackUrl = useCallback(async () => { const { data } = await oneTimeToken.generate() @@ -94,13 +142,37 @@ export function Login() { }) }, [getCallbackUrl]) + const handleCliCallback = useCallback(async () => { + if (!cliCallbackUrl) { + return + } + + const callbackUrl = await getCallbackUrl() + if (!callbackUrl) { + return + } + + const token = parseTokenFromDeepLinkPath(callbackUrl.url) + if (!token) { + return + } + + const redirectUrl = new URL(cliCallbackUrl.toString()) + redirectUrl.searchParams.set("token", token) + window.location.replace(redirectUrl.toString()) + }, [cliCallbackUrl, getCallbackUrl]) + const onceRef = useRef(false) useEffect(() => { if (isAuthenticated && !onceRef.current) { - handleOpenApp() + if (cliCallbackUrl) { + void handleCliCallback() + } else { + void handleOpenApp() + } } onceRef.current = true - }, [handleOpenApp, isAuthenticated]) + }, [cliCallbackUrl, handleCliCallback, handleOpenApp, isAuthenticated]) const navigate = useNavigate() @@ -181,7 +253,7 @@ export function Login() { if (key === "credential") { setIsEmail(true) } else { - loginHandler(key, "app") + startSocialLogin(key) } }} className="center relative w-full gap-2 rounded-xl border py-3 pl-5 font-semibold duration-200 hover:bg-material-medium" @@ -232,6 +304,7 @@ export function Login() { }, [ authProviders, handleOpenApp, + startSocialLogin, isAuthenticated, refetch, t,