Repository navigation
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 2 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,97 @@ | ||
| 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"; | ||
|
|
||
| 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 cmd = | ||
| platform() === "darwin" ? "open" : | ||
| platform() === "win32" ? "cmd" : | ||
| "xdg-open"; | ||
| const args = platform() === "win32" ? ["/c", "start", url] : [url]; | ||
| try { | ||
| spawn(cmd, args, { detached: true, stdio: "ignore" }).unref(); | ||
| } catch { | ||
| // Fallback: just print the URL | ||
| } | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| async function postJson<T>(url: string, body: unknown): Promise<T> { | ||
| const resp = await fetch(url, { | ||
| method: "POST", | ||
| headers: { "Content-Type": "application/json" }, | ||
| body: JSON.stringify(body), | ||
| }); | ||
| 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,45 @@ | ||
| import { readTokens, clearTokens } from "./token-store"; | ||
| import { stopRelay } from "../relay/pid"; | ||
|
|
||
| export async function logout(): Promise<void> { | ||
| const tokens = readTokens(); | ||
| if (!tokens) { | ||
| console.log("Not logged in."); | ||
| return; | ||
| } | ||
|
|
||
| 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 }), | ||
| }); | ||
| } catch { | ||
| // Best-effort server revoke | ||
| } | ||
|
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,43 @@ | ||
| import { readFileSync, writeFileSync, existsSync, mkdirSync, unlinkSync, chmodSync } 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"); | ||
|
|
||
| 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; | ||
| } | ||
| } | ||
|
|
||
| export function writeTokens(tokens: AuthTokens): void { | ||
| if (!existsSync(AUTH_DIR)) mkdirSync(AUTH_DIR, { recursive: true }); | ||
| writeFileSync(AUTH_FILE, JSON.stringify(tokens, null, 2)); | ||
| try { | ||
| chmodSync(AUTH_FILE, 0o600); | ||
| } catch { | ||
| // Windows doesn't support chmod; ignore | ||
| } | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| export function clearTokens(): void { | ||
| if (existsSync(AUTH_FILE)) unlinkSync(AUTH_FILE); | ||
| } | ||
|
|
||
| export function isLoggedIn(): boolean { | ||
| return readTokens() !== null; | ||
| } | ||
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
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.