feat(cli): support browser-based auth login (#4887)

This commit is contained in:
DIYgod
2026-02-27 16:51:58 +08:00
committed by GitHub
parent 5950542845
commit 49f69f4d19
6 changed files with 374 additions and 13 deletions
+5 -3
View File
@@ -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 <session-token>`
- `folo auth login` (recommended, opens browser and auto-logins)
- or `folo auth login --token <session-token>`
- or set `FOLO_TOKEN=<token>`
## Output Contract
@@ -113,7 +114,7 @@ Loop until `hasNext` is `false`:
## Command Reference
- `folo auth login --token <token>`
- `folo auth login [--timeout <seconds>] [--token <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 <token>`
- Re-login: `folo auth login`
- or `folo auth login --token <token>`
- Or set `FOLO_TOKEN`
- `HTTP_4xx` / `HTTP_5xx`
- Retry with `--verbose` for request details
+48
View File
@@ -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/,
)
})
})
+222
View File
@@ -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 = `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Folo CLI Login</title>
</head>
<body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; padding: 20px; line-height: 1.5;">
<h1>Folo CLI login complete</h1>
<p>You can close this window and return to your terminal.</p>
</body>
</html>
`
const failurePageHtml = `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Folo CLI Login</title>
</head>
<body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; padding: 20px; line-height: 1.5;">
<h1>Folo CLI login failed</h1>
<p>Missing token in callback URL. Please retry in terminal.</p>
</body>
</html>
`
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<BrowserLoginResult> => {
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<BrowserLoginResult>((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
}
+1 -1
View File
@@ -82,7 +82,7 @@ export const createCommandContext = async (
if (requireAuth && !token) {
throw new CLIError(
"UNAUTHORIZED",
"Missing token. Run `folo auth login --token <token>` or set FOLO_TOKEN.",
"Missing token. Run `folo auth login` (browser sign-in) or set FOLO_TOKEN.",
)
}
+20 -4
View File
@@ -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 <token>", "Session token from Folo")
.option(
"--timeout <seconds>",
"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 <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)
+78 -5
View File
@@ -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,