-
Notifications
You must be signed in to change notification settings - Fork 19
feat: cloud platform client (login, relay, queue) #132
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| import { spawn } from "node:child_process"; | ||
| import { platform } from "node:os"; | ||
| import { writeTokens, type AuthTokens } from "./token-store"; | ||
|
|
||
| const DEFAULT_SERVER_URL = process.env.FAILPROOFAI_SERVER_URL ?? "https://api.befailproof.ai"; | ||
| const HTTP_TIMEOUT_MS = 10_000; | ||
|
|
||
| interface DeviceCodeResponse { | ||
| device_code: string; | ||
| user_code: string; | ||
| verification_url: string; | ||
| expires_in: number; | ||
| interval: number; | ||
| } | ||
|
|
||
| interface TokenResponse { | ||
| access_token: string; | ||
| refresh_token: string; | ||
| expires_in: number; | ||
| user: { id: string; email: string; name?: string }; | ||
| } | ||
|
|
||
| function openBrowser(url: string): void { | ||
| const os = platform(); | ||
| try { | ||
| if (os === "darwin") { | ||
| spawn("open", [url], { detached: true, stdio: "ignore" }).unref(); | ||
| } else if (os === "win32") { | ||
| // On cmd's `start`, the first quoted token is treated as a window | ||
| // title. Pass an empty title so URLs containing "&" or spaces are | ||
| // interpreted as the target, not the title. | ||
| spawn("cmd", ["/c", "start", "", url], { detached: true, stdio: "ignore" }).unref(); | ||
| } else { | ||
| spawn("xdg-open", [url], { detached: true, stdio: "ignore" }).unref(); | ||
| } | ||
| } catch { | ||
| // Fallback: the URL is already printed above. | ||
| } | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| async function postJson<T>(url: string, body: unknown, timeoutMs = HTTP_TIMEOUT_MS): Promise<T> { | ||
| const resp = await fetch(url, { | ||
| method: "POST", | ||
| headers: { "Content-Type": "application/json" }, | ||
| body: JSON.stringify(body), | ||
| signal: AbortSignal.timeout(timeoutMs), | ||
| }); | ||
| if (!resp.ok) { | ||
| throw new Error(`${url} → ${resp.status} ${resp.statusText}`); | ||
| } | ||
| return (await resp.json()) as T; | ||
| } | ||
|
|
||
| export async function login(): Promise<void> { | ||
| const serverUrl = DEFAULT_SERVER_URL; | ||
|
|
||
| console.log("Requesting device code..."); | ||
| const dc = await postJson<DeviceCodeResponse>(`${serverUrl}/api/v1/auth/device-code`, {}); | ||
|
|
||
| console.log(`\n Open this URL in your browser (will be opened automatically):`); | ||
| console.log(` ${dc.verification_url}\n`); | ||
| console.log(` Your code: ${dc.user_code}\n`); | ||
|
|
||
| openBrowser(dc.verification_url); | ||
|
|
||
| const deadline = Date.now() + dc.expires_in * 1000; | ||
| const intervalMs = dc.interval * 1000; | ||
|
|
||
| while (Date.now() < deadline) { | ||
| await new Promise((r) => setTimeout(r, intervalMs)); | ||
| try { | ||
| const result = await postJson<TokenResponse | { status: string }>( | ||
| `${serverUrl}/api/v1/auth/device-token`, | ||
| { device_code: dc.device_code }, | ||
| ); | ||
| if ("access_token" in result) { | ||
| const tokens: AuthTokens = { | ||
| access_token: result.access_token, | ||
| refresh_token: result.refresh_token, | ||
| expires_at: Math.floor(Date.now() / 1000) + result.expires_in, | ||
| user_email: result.user.email, | ||
| user_id: result.user.id, | ||
| server_url: serverUrl, | ||
| }; | ||
| writeTokens(tokens); | ||
| console.log(`Logged in as ${result.user.email}`); | ||
|
|
||
| // Auto-start relay daemon | ||
| try { | ||
| const { ensureRelayRunning } = await import("../relay/daemon"); | ||
| ensureRelayRunning(); | ||
| console.log("Relay daemon started."); | ||
| } catch (e) { | ||
| console.warn("Failed to auto-start relay daemon:", e); | ||
| } | ||
| return; | ||
| } | ||
| } catch { | ||
| // Pending or transient error — keep polling | ||
| } | ||
| } | ||
|
|
||
| throw new Error("Login timed out. Run `failproofai login` again."); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| import { readTokens, clearTokens } from "./token-store"; | ||
| import { stopRelay } from "../relay/pid"; | ||
|
|
||
| const LOGOUT_TIMEOUT_MS = 3_000; | ||
|
|
||
| export async function logout(): Promise<void> { | ||
| const tokens = readTokens(); | ||
| if (!tokens) { | ||
| console.log("Not logged in."); | ||
| return; | ||
| } | ||
|
|
||
| // Best-effort server revoke with a short timeout — the local logout | ||
| // must not block on a slow network. | ||
| try { | ||
| await fetch(`${tokens.server_url}/api/v1/auth/logout`, { | ||
| method: "POST", | ||
| headers: { "Content-Type": "application/json" }, | ||
| body: JSON.stringify({ refresh_token: tokens.refresh_token }), | ||
| signal: AbortSignal.timeout(LOGOUT_TIMEOUT_MS), | ||
| }); | ||
| } catch { | ||
| // Network or timeout — proceed to local clear anyway | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| try { | ||
| stopRelay(); | ||
| } catch { | ||
| // Best-effort daemon stop | ||
| } | ||
|
|
||
| clearTokens(); | ||
| console.log("Logged out."); | ||
| } | ||
|
|
||
| export function whoami(): void { | ||
| const tokens = readTokens(); | ||
| if (!tokens) { | ||
| console.log("Not logged in. Run `failproofai login` to authenticate."); | ||
| process.exit(1); | ||
| } | ||
| console.log(`Logged in as ${tokens.user_email}`); | ||
| console.log(`Server: ${tokens.server_url}`); | ||
| const expiresIn = tokens.expires_at - Math.floor(Date.now() / 1000); | ||
| if (expiresIn > 0) { | ||
| console.log(`Access token expires in ${Math.floor(expiresIn / 60)} minutes`); | ||
| } else { | ||
| console.log(`Access token expired (will refresh on next use)`); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| import { | ||
| readFileSync, | ||
| writeFileSync, | ||
| existsSync, | ||
| mkdirSync, | ||
| unlinkSync, | ||
| renameSync, | ||
| openSync, | ||
| closeSync, | ||
| } from "node:fs"; | ||
| import { join } from "node:path"; | ||
| import { homedir } from "node:os"; | ||
|
|
||
| export interface AuthTokens { | ||
| access_token: string; | ||
| refresh_token: string; | ||
| expires_at: number; | ||
| user_email: string; | ||
| user_id: string; | ||
| server_url: string; | ||
| } | ||
|
|
||
| const AUTH_DIR = join(homedir(), ".failproofai"); | ||
| const AUTH_FILE = join(AUTH_DIR, "auth.json"); | ||
|
|
||
| function ensureAuthDir(): void { | ||
| if (!existsSync(AUTH_DIR)) mkdirSync(AUTH_DIR, { recursive: true, mode: 0o700 }); | ||
| } | ||
|
|
||
| export function readTokens(): AuthTokens | null { | ||
| if (!existsSync(AUTH_FILE)) return null; | ||
| try { | ||
| const raw = readFileSync(AUTH_FILE, "utf8"); | ||
| return JSON.parse(raw) as AuthTokens; | ||
| } catch { | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Write tokens atomically with 0600 permissions *from creation*. | ||
| * We open with O_WRONLY|O_CREAT|O_TRUNC and explicit mode 0600 so the | ||
| * file is never world-readable, not even briefly during the write. | ||
| * Then rename into place (atomic on POSIX). | ||
| */ | ||
| export function writeTokens(tokens: AuthTokens): void { | ||
| ensureAuthDir(); | ||
| const tmpPath = `${AUTH_FILE}.tmp`; | ||
| const fd = openSync(tmpPath, "w", 0o600); | ||
| try { | ||
| writeFileSync(fd, JSON.stringify(tokens, null, 2)); | ||
| } finally { | ||
| closeSync(fd); | ||
| } | ||
| renameSync(tmpPath, AUTH_FILE); | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| export function clearTokens(): void { | ||
| if (existsSync(AUTH_FILE)) unlinkSync(AUTH_FILE); | ||
| } | ||
|
|
||
| export function isLoggedIn(): boolean { | ||
| return existsSync(AUTH_FILE); | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.