-
-
Notifications
You must be signed in to change notification settings - Fork 829
Expand file tree
/
Copy pathauth.rs
More file actions
122 lines (98 loc) · 3.65 KB
/
Copy pathauth.rs
File metadata and controls
122 lines (98 loc) · 3.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
use std::thread::sleep;
use std::time::{Duration, Instant};
use anyhow::{Context, Result, anyhow, bail};
use reqwest::blocking::Client;
use serde::Deserialize;
use crate::cli::AuthOpts;
use crate::env;
#[derive(Debug, Deserialize)]
struct DeviceStartResponse {
device_code: String,
user_code: String,
verification_url: String,
expires_in: u64,
#[serde(default = "default_poll_interval")]
interval: u64,
}
fn default_poll_interval() -> u64 {
2
}
#[derive(Debug, Deserialize)]
struct DevicePollResponse {
status: String,
token: Option<String>,
}
pub fn run(opts: AuthOpts) -> Result<()> {
login(opts.api_url)
}
fn login(api_url_override: Option<String>) -> Result<()> {
let api_url = api_url_override
.or_else(|| env::load_ai_api_url().ok())
.unwrap_or_else(|| "https://myflow.sh".to_string());
let api_url = api_url.trim().trim_end_matches('/').to_string();
let client = Client::builder()
.timeout(Duration::from_secs(30))
.build()
.context("failed to create HTTP client for auth")?;
let start_url = format!("{}/api/auth/cli/start", api_url);
let response = client
.post(&start_url)
.json(&serde_json::json!({"client": "flow"}))
.send()
.context("failed to start device auth")?;
if !response.status().is_success() {
bail!("device auth start failed: HTTP {}", response.status());
}
let payload: DeviceStartResponse = response
.json()
.context("failed to parse device auth response")?;
println!("\nFlow auth with myflow");
println!("───────────────────────");
println!("Code: {}", payload.user_code);
println!("Open: {}\n", payload.verification_url);
open_in_browser(&payload.verification_url);
let expires_at = Instant::now() + Duration::from_secs(payload.expires_in);
let poll_url = format!("{}/api/auth/cli/poll", api_url);
println!("Waiting for approval...");
while Instant::now() < expires_at {
sleep(Duration::from_secs(payload.interval.max(1)));
let poll_response = client
.post(&poll_url)
.json(&serde_json::json!({"device_code": payload.device_code}))
.send()
.context("failed to poll device auth")?;
if !poll_response.status().is_success() {
bail!("device auth poll failed: HTTP {}", poll_response.status());
}
let poll: DevicePollResponse = poll_response
.json()
.context("failed to parse device auth poll response")?;
match poll.status.as_str() {
"approved" => {
let token = poll
.token
.ok_or_else(|| anyhow!("device auth approved without token"))?;
env::save_ai_auth_token(token, Some(api_url.clone()))?;
println!("✓ Auth complete. You're ready to use Flow AI.");
return Ok(());
}
"pending" => continue,
"expired" => bail!("device code expired. Run `f auth` again."),
"invalid" => bail!("device code invalid. Run `f auth` again."),
other => bail!("unexpected auth status: {}", other),
}
}
bail!("device code expired. Run `f auth` again.")
}
fn open_in_browser(url: &str) {
#[cfg(target_os = "macos")]
{
let _ = std::process::Command::new("open").arg(url).status();
}
#[cfg(target_os = "linux")]
{
let _ = std::process::Command::new("xdg-open").arg(url).status();
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
println!("Open this URL in your browser: {}", url);
}