1use std::sync::Arc;
35
36use serde::{Deserialize, Serialize};
37
38use crate::backend::rpc::engine::WshRpcEngine;
39
40use super::identity_auth_dirs::{caller_auth_dir, compute_and_ensure_account_dir, compute_and_ensure_bundle_dir};
41use super::identity_auth_spawn::spawn_auth_cli;
42use super::AppState;
43
44pub const COMMAND_AUTH_START: &str = "auth.start";
45pub const COMMAND_AUTH_POLL: &str = "auth.poll";
46pub const COMMAND_AUTH_SUBMIT_CALLBACK: &str = "auth.submitcallback";
47pub const COMMAND_AUTH_CANCEL: &str = "auth.cancel";
48pub const COMMAND_ENSURE_ACCOUNT_DIR: &str = "identity.ensureaccountdir";
59
60pub use crate::backend::rpc_types::StartProviderAuthReq;
61
62#[derive(Debug, Deserialize, Serialize, ts_rs::TS)]
63#[ts(export, export_to = "../../../frontend/types/rpc/")]
64#[serde(rename_all = "camelCase")]
65pub struct PollProviderAuthReq {
66 pub session_id: String,
67}
68
69#[derive(Debug, Deserialize, Serialize, ts_rs::TS)]
70#[ts(export, export_to = "../../../frontend/types/rpc/")]
71#[serde(rename_all = "camelCase")]
72pub struct SubmitAuthCallbackReq {
73 pub session_id: String,
74 pub callback_url: String,
77}
78
79#[derive(Debug, Deserialize, Serialize, ts_rs::TS)]
80#[ts(export, export_to = "../../../frontend/types/rpc/")]
81#[serde(rename_all = "camelCase")]
82pub struct CancelProviderAuthReq {
83 pub session_id: String,
84}
85
86#[derive(Debug, Serialize, Deserialize, ts_rs::TS)]
87#[ts(export, export_to = "../../../frontend/types/rpc/")]
88#[serde(rename_all = "camelCase")]
89pub struct AckResp {
90 pub success: bool,
91 #[serde(skip_serializing_if = "Option::is_none")]
92 #[ts(optional)]
93 pub error: Option<String>,
94}
95
96#[derive(Debug, Deserialize, Serialize, ts_rs::TS)]
97#[ts(export, export_to = "../../../frontend/types/rpc/")]
98#[serde(rename_all = "camelCase")]
99pub struct EnsureAccountDirReq {
100 pub provider_id: String,
101 #[serde(default)]
104 pub existing_account_id: String,
105}
106
107#[derive(Debug, Serialize, Deserialize, ts_rs::TS)]
108#[ts(export, export_to = "../../../frontend/types/rpc/")]
109#[serde(rename_all = "camelCase")]
110pub struct EnsureAccountDirResp {
111 pub account_id: String,
112 #[serde(skip_serializing_if = "Option::is_none")]
116 #[ts(optional)]
117 pub dir: Option<String>,
118}
119
120pub(crate) fn start_provider_auth(state: &AppState, req: StartProviderAuthReq) -> crate::identity::auth_session::StartSessionResult {
123 let mgr = state.auth_session_manager.clone();
124 let mstore = state.id_store.clone();
125 let identity_store = state.identity_store.clone();
126 let broker = state.broker.clone();
127 tracing::info!(
128 provider_id = %req.provider_id,
129 cli_path = %req.cli_path,
130 into_bundle_id = ?req.into_bundle_id,
131 direct_account = req.direct_account,
132 "auth.start"
133 );
134 let mut auth_env = req.auth_env;
152 let (account_id, bundle_dir) = if req.direct_account {
153 let (account_id, dir) = compute_and_ensure_account_dir(
154 &mstore,
155 &req.existing_account_id,
156 &req.provider_id,
157 &mut auth_env,
158 );
159 (account_id, dir)
160 } else {
161 let dir = compute_and_ensure_bundle_dir(
162 req.into_bundle_id.as_deref(),
163 &req.provider_id,
164 &mut auth_env,
165 );
166 (String::new(), dir)
167 };
168 let exclusive_key = bundle_dir
172 .clone()
173 .or_else(|| caller_auth_dir(&req.provider_id, &auth_env));
174 let r = mgr.start_session(req.provider_id.clone(), exclusive_key);
175 spawn_auth_cli(
176 mgr,
177 mstore,
178 identity_store,
179 broker,
180 r.session_id.clone(),
181 req.provider_id,
182 req.into_bundle_id,
183 bundle_dir,
184 req.direct_account,
185 account_id,
186 req.cli_path,
187 req.auth_login_args,
188 req.auth_check_args,
189 auth_env,
190 req.requires_tty,
191 );
192 r
193}
194
195pub fn register_identity_handlers(engine: &Arc<WshRpcEngine>, state: &AppState) {
196 let mstore_for_ensure_dir = state.id_store.clone();
197 let state_for_start = state.clone();
198 engine.register_typed(
199 COMMAND_AUTH_START,
200 move |req: StartProviderAuthReq, _ctx| {
201 let state = state_for_start.clone();
202 async move { Ok(start_provider_auth(&state, req)) }
203 },
204 );
205
206 let mgr = state.auth_session_manager.clone();
207 engine.register_typed(
208 COMMAND_AUTH_POLL,
209 move |req: PollProviderAuthReq, _ctx| {
210 let mgr = mgr.clone();
211 async move {
212 let snap = mgr
213 .poll_session(&req.session_id)
214 .ok_or_else(|| format!("auth.poll: unknown session {}", req.session_id))?;
215 Ok(snap)
216 }
217 },
218 );
219
220 let mgr = state.auth_session_manager.clone();
221 engine.register_typed(
222 COMMAND_AUTH_CANCEL,
223 move |req: CancelProviderAuthReq, _ctx| {
224 let mgr = mgr.clone();
225 async move {
226 let ok = mgr.cancel_session(&req.session_id);
227 Ok(AckResp {
228 success: ok,
229 error: if ok {
230 None
231 } else {
232 Some(format!("unknown or already-terminal session: {}", req.session_id))
233 },
234 })
235 }
236 },
237 );
238
239 let mgr = state.auth_session_manager.clone();
240 engine.register_typed(
241 COMMAND_AUTH_SUBMIT_CALLBACK,
242 move |req: SubmitAuthCallbackReq, _ctx| {
243 let mgr = mgr.clone();
244 async move {
245 let delivered = mgr
246 .send_to_stdin(&req.session_id, req.callback_url)
247 .await;
248 Ok(AckResp {
249 success: delivered,
250 error: if delivered {
251 None
252 } else {
253 Some(format!(
254 "no stdin sender for session {} (process exited or session unknown)",
255 req.session_id
256 ))
257 },
258 })
259 }
260 },
261 );
262
263 engine.register_typed(
264 COMMAND_ENSURE_ACCOUNT_DIR,
265 move |req: EnsureAccountDirReq, _ctx| {
266 let mstore = mstore_for_ensure_dir.clone();
267 async move {
268 let mut auth_env = std::collections::HashMap::new();
269 let (account_id, dir) = compute_and_ensure_account_dir(
270 &mstore,
271 &req.existing_account_id,
272 &req.provider_id,
273 &mut auth_env,
274 );
275 let resp = EnsureAccountDirResp { account_id, dir };
276 Ok(resp)
277 }
278 },
279 );
280}
281
282#[cfg(test)]
283mod tests {
284 use super::*;
285
286 #[test]
293 fn start_req_parses_minimal() {
294 let v = serde_json::json!({
295 "providerId": "claude",
296 "cliPath": "/usr/bin/claude",
297 "authLoginArgs": ["login"],
298 "authCheckArgs": ["whoami"]
299 });
300 let r: StartProviderAuthReq = serde_json::from_value(v).unwrap();
301 assert_eq!(r.provider_id, "claude");
302 assert_eq!(r.cli_path, "/usr/bin/claude");
303 assert_eq!(r.auth_login_args, vec!["login"]);
304 assert_eq!(r.auth_check_args, vec!["whoami"]);
305 assert!(r.into_bundle_id.is_none());
306 assert!(r.auth_env.is_empty());
307 }
308
309 #[test]
310 fn start_req_parses_with_bundle_id() {
311 let v = serde_json::json!({
312 "providerId": "codex",
313 "cliPath": "/usr/bin/codex",
314 "authLoginArgs": ["auth", "login"],
315 "authCheckArgs": ["auth", "status"],
316 "authEnv": { "FOO": "bar" },
317 "intoBundleId": "bundle-1"
318 });
319 let r: StartProviderAuthReq = serde_json::from_value(v).unwrap();
320 assert_eq!(r.provider_id, "codex");
321 assert_eq!(r.into_bundle_id.as_deref(), Some("bundle-1"));
322 assert_eq!(r.auth_env.get("FOO").map(String::as_str), Some("bar"));
323 }
324
325 #[test]
326 fn poll_req_round_trips() {
327 let v = serde_json::json!({ "sessionId": "auth-xyz" });
328 let r: PollProviderAuthReq = serde_json::from_value(v).unwrap();
329 assert_eq!(r.session_id, "auth-xyz");
330 }
331
332 #[test]
333 fn submit_callback_req_round_trips() {
334 let v = serde_json::json!({
335 "sessionId": "auth-xyz",
336 "callbackUrl": "https://example.com/cb?code=abc"
337 });
338 let r: SubmitAuthCallbackReq = serde_json::from_value(v).unwrap();
339 assert_eq!(r.session_id, "auth-xyz");
340 assert!(r.callback_url.contains("code=abc"));
341 }
342
343 #[test]
344 fn ack_resp_omits_error_when_success() {
345 let r = AckResp { success: true, error: None };
346 let v = serde_json::to_value(&r).unwrap();
347 assert_eq!(v, serde_json::json!({ "success": true }));
348 }
349
350 #[test]
351 fn ack_resp_includes_error_when_failure() {
352 let r = AckResp { success: false, error: Some("boom".into()) };
353 let v = serde_json::to_value(&r).unwrap();
354 assert_eq!(v, serde_json::json!({ "success": false, "error": "boom" }));
355 }
356
357 #[test]
360 fn start_req_parses_direct_account_fields() {
361 let v = serde_json::json!({
362 "providerId": "claude",
363 "cliPath": "/usr/bin/claude",
364 "authLoginArgs": ["login"],
365 "authCheckArgs": ["whoami"],
366 "directAccount": true,
367 "existingAccountId": "acc-1"
368 });
369 let r: StartProviderAuthReq = serde_json::from_value(v).unwrap();
370 assert!(r.direct_account);
371 assert_eq!(r.existing_account_id, "acc-1");
372 }
373
374 #[test]
375 fn start_req_direct_account_fields_default_when_absent() {
376 let v = serde_json::json!({
380 "providerId": "claude",
381 "cliPath": "/usr/bin/claude",
382 "authLoginArgs": ["login"],
383 "authCheckArgs": ["whoami"]
384 });
385 let r: StartProviderAuthReq = serde_json::from_value(v).unwrap();
386 assert!(!r.direct_account);
387 assert_eq!(r.existing_account_id, "");
388 }
389}
390
391#[cfg(test)]
393mod req_shape_tests {
394 use super::*;
395 use serde_json::json;
396
397 #[test]
403 fn auth_start_requires_only_four_fields() {
404 let minimal: StartProviderAuthReq = serde_json::from_value(json!({
405 "providerId": "claude",
406 "cliPath": "/usr/bin/claude",
407 "authLoginArgs": ["login"],
408 "authCheckArgs": ["whoami"],
409 }))
410 .expect("auth.start must accept just the four required fields");
411 assert!(minimal.into_bundle_id.is_none());
412 assert!(!minimal.direct_account);
413 assert_eq!(minimal.existing_account_id, "");
414 assert!(minimal.auth_env.is_empty());
415 assert!(!minimal.requires_tty);
416
417 assert!(
418 serde_json::from_value::<StartProviderAuthReq>(json!({"providerId": "c"})).is_err(),
419 "cliPath and the two arg lists have no defaults"
420 );
421 }
422
423 #[test]
424 fn the_session_id_commands_accept_their_payloads() {
425 serde_json::from_value::<PollProviderAuthReq>(json!({"sessionId": "s1"}))
426 .expect("auth.poll");
427 serde_json::from_value::<CancelProviderAuthReq>(json!({"sessionId": "s1"}))
428 .expect("auth.cancel");
429 serde_json::from_value::<SubmitAuthCallbackReq>(
430 json!({"sessionId": "s1", "callbackUrl": "http://localhost/cb"}),
431 )
432 .expect("auth.submitcallback");
433 serde_json::from_value::<EnsureAccountDirReq>(json!({"providerId": "claude"}))
434 .expect("identity.ensureaccountdir, existingAccountId omitted");
435
436 assert!(
437 serde_json::from_value::<PollProviderAuthReq>(json!({"session_id": "s1"})).is_err(),
438 "snake_case is not the wire format for these"
439 );
440 }
441
442 #[test]
450 fn the_ack_shapes_omit_their_optional_keys_rather_than_nulling_them() {
451 let ok = serde_json::to_value(AckResp { success: true, error: None }).expect("serializable");
452 assert_eq!(ok, json!({"success": true}));
453
454 let dir = serde_json::to_value(EnsureAccountDirResp {
455 account_id: "a1".to_string(),
456 dir: None,
457 })
458 .expect("serializable");
459 assert_eq!(dir, json!({"accountId": "a1"}));
460 }
461}