xjp-oidc 1.1.0

OIDC/OAuth2 SDK for Rust - Server and WASM support
Documentation
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! Server-Sent Events (SSE) support for login flows
//!
//! This module provides support for real-time login status updates via SSE,
//! commonly used for QR code login flows where the status needs to be
//! monitored in real-time.

#[cfg(not(target_arch = "wasm32"))]
use crate::{
    errors::{Error, Result},
    http::HttpClient,
};

#[cfg(not(target_arch = "wasm32"))]
use serde::{Deserialize, Serialize};

/// Login status enum matching the backend implementation
#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum LoginStatus {
    /// Waiting for user action (e.g., QR code scan)
    Pending,
    /// User has scanned but not yet authorized
    Scanned,
    /// User has authorized the login
    Authorized,
    /// Login completed successfully
    Success,
    /// Login failed
    Failed,
    /// Login session expired
    Expired,
}

/// Login state information
#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoginState {
    /// Current status of the login session
    pub status: LoginStatus,
    /// OAuth authorization code (present when status is Success)
    pub code: Option<String>,
    /// Error message (present when status is Failed)
    pub error: Option<String>,
    /// Creation timestamp (Unix timestamp)
    pub created_at: i64,
}

/// SSE event types
#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug, Clone)]
pub enum LoginEvent {
    /// Status update event
    StatusUpdate(LoginState),
    /// Heartbeat event (no data)
    Heartbeat,
    /// Stream closed event
    Close,
    /// Error event
    Error(String),
}

/// Start a login session and get a login ID for monitoring
///
/// This creates a new login session on the server and returns a login ID
/// that can be used to monitor the login status via SSE.
///
/// # Example
/// ```no_run
/// # #[cfg(not(target_arch = "wasm32"))]
/// # use xjp_oidc::{sse::start_login_session, http::ReqwestHttpClient};
/// # #[cfg(not(target_arch = "wasm32"))]
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let http = ReqwestHttpClient::default();
///
/// let (login_id, qr_url) = start_login_session(
///     "https://auth.example.com",
///     "my-client-id",
///     "https://app.example.com/callback",
///     &http
/// ).await?;
///
/// println!("Login ID: {}", login_id);
/// println!("QR Code URL: {}", qr_url);
/// # Ok(())
/// # }
/// ```
#[cfg(not(target_arch = "wasm32"))]
pub async fn start_login_session(
    issuer: &str,
    client_id: &str,
    redirect_uri: &str,
    http: &dyn HttpClient,
) -> Result<(String, String)> {
    // Validate parameters
    if issuer.is_empty() {
        return Err(Error::InvalidParam("issuer cannot be empty"));
    }
    if client_id.is_empty() {
        return Err(Error::InvalidParam("client_id cannot be empty"));
    }
    if redirect_uri.is_empty() {
        return Err(Error::InvalidParam("redirect_uri cannot be empty"));
    }

    // Build the login session endpoint URL
    let session_endpoint = format!("{}/auth/wechat/qr", issuer.trim_end_matches('/'));

    // Prepare request body
    let body = serde_json::json!({
        "client_id": client_id,
        "redirect_uri": redirect_uri,
    });

    // Make the request
    let response = http
        .post_json_value(&session_endpoint, &body, None)
        .await
        .map_err(|e| Error::Network(format!("Failed to start login session: {}", e)))?;

    // Extract login_id and qr_url from response
    let login_id = response["login_id"]
        .as_str()
        .ok_or_else(|| Error::InvalidState("Missing login_id in response".to_string()))?
        .to_string();

    let qr_url = response["wechat_qr_url"]
        .as_str()
        .ok_or_else(|| Error::InvalidState("Missing wechat_qr_url in response".to_string()))?
        .to_string();

    Ok((login_id, qr_url))
}

/// Configuration for SSE login monitoring
#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug, Clone)]
pub struct LoginMonitorConfig {
    /// The issuer URL
    pub issuer: String,
    /// The login ID to monitor
    pub login_id: String,
    /// Optional timeout in seconds (default: 300)
    pub timeout_secs: Option<u64>,
    /// Optional reconnect attempts (default: 3)
    pub max_reconnects: Option<u32>,
}

/// Subscribe to login status updates via SSE
///
/// This function returns a stream of login events that can be consumed
/// to track the login progress in real-time.
///
/// # Example
/// ```no_run
/// # #[cfg(not(target_arch = "wasm32"))]
/// # use xjp_oidc::sse::{subscribe_login_events, LoginMonitorConfig, LoginEvent, LoginStatus};
/// # #[cfg(not(target_arch = "wasm32"))]
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// use futures_util::StreamExt;
///
/// let config = LoginMonitorConfig {
///     issuer: "https://auth.example.com".to_string(),
///     login_id: "login-123".to_string(),
///     timeout_secs: Some(300),
///     max_reconnects: Some(3),
/// };
///
/// let mut event_stream = subscribe_login_events(config).await?;
///
/// while let Some(event) = event_stream.next().await {
///     match event {
///         Ok(LoginEvent::StatusUpdate(state)) => {
///             println!("Status: {:?}", state.status);
///             if state.status == LoginStatus::Success {
///                 println!("Login successful! Code: {:?}", state.code);
///                 break;
///             }
///         }
///         Ok(LoginEvent::Heartbeat) => {
///             println!("Heartbeat received");
///         }
///         Ok(LoginEvent::Close) => {
///             println!("Stream closed");
///             break;
///         }
///         Err(e) => {
///             eprintln!("Error: {}", e);
///             break;
///         }
///     }
/// }
/// # Ok(())
/// # }
/// ```
#[cfg(all(not(target_arch = "wasm32"), feature = "sse"))]
pub async fn subscribe_login_events(
    config: LoginMonitorConfig,
) -> Result<impl futures_util::Stream<Item = Result<LoginEvent>>> {
    use eventsource_client::{Client, ClientBuilder, ReconnectOptions, SSE};
    use futures_util::StreamExt;

    // Build SSE endpoint URL
    let sse_url = format!(
        "{}/auth/login-stream?login_id={}",
        config.issuer.trim_end_matches('/'),
        urlencoding::encode(&config.login_id)
    );

    // Create reconnect options with available methods
    let reconnect = ReconnectOptions::reconnect(true)
        .retry_initial(false)
        .delay(std::time::Duration::from_secs(1))
        .delay_max(std::time::Duration::from_secs(5))
        .build();

    // Create SSE client
    let client = ClientBuilder::for_url(&sse_url)
        .map_err(|e| Error::Network(format!("Failed to create SSE client: {}", e)))?
        .reconnect(reconnect)
        .build();

    // Convert the event stream to our LoginEvent type
    let event_stream = client.stream().map(|result| {
        match result {
            Ok(SSE::Event(e)) => {
                match e.event_type.as_str() {
                    "pending" | "scanned" | "authorized" | "success" | "failed" | "expired" => {
                        // Parse login state from event data - handle both direct and nested formats
                        let parse_result: Result<LoginState> = {
                            // First try to parse as direct LoginState
                            if let Ok(state) = serde_json::from_str::<LoginState>(&e.data) {
                                Ok(state)
                            } else {
                                // Try to parse as nested format and extract state field
                                if let Ok(response) = serde_json::from_str::<serde_json::Value>(&e.data) {
                                    if let Some(nested_state) = response.get("state") {
                                        serde_json::from_value(nested_state.clone())
                                            .map_err(|e| Error::Verification(format!("Failed to parse login state from nested SSE format: {}", e)))
                                    } else {
                                        Err(Error::Verification("SSE data is not valid LoginState and has no 'state' field".to_string()))
                                    }
                                } else {
                                    Err(Error::Verification("Failed to parse SSE data as JSON".to_string()))
                                }
                            }
                        };
                        
                        match parse_result {
                            Ok(state) => Ok(LoginEvent::StatusUpdate(state)),
                            Err(e) => Err(e),
                        }
                    }
                    "close" => Ok(LoginEvent::Close),
                    "heartbeat" | "" => Ok(LoginEvent::Heartbeat),
                    _ => Ok(LoginEvent::Heartbeat), // Treat unknown events as heartbeat
                }
            }
            Ok(SSE::Comment(_)) => Ok(LoginEvent::Heartbeat),
            Err(e) => Err(Error::Network(format!("SSE error: {}", e))),
        }
    });

    // Apply timeout if specified
    if let Some(timeout_secs) = config.timeout_secs {
        let timeout_stream = tokio_stream::StreamExt::timeout(
            event_stream,
            std::time::Duration::from_secs(timeout_secs),
        )
        .map(move |result| {
            result
                .map_err(|_| Error::Network("SSE stream timeout".to_string()))
                .and_then(|inner| inner)
        });

        Ok(Box::pin(timeout_stream) as std::pin::Pin<Box<dyn futures_util::Stream<Item = Result<LoginEvent>> + Send>>)
    } else {
        Ok(Box::pin(event_stream) as std::pin::Pin<Box<dyn futures_util::Stream<Item = Result<LoginEvent>> + Send>>)
    }
}

/// Check login status once (non-streaming)
///
/// This is useful for polling the login status without using SSE,
/// or as a fallback when SSE is not available.
///
/// # Example
/// ```no_run
/// # #[cfg(not(target_arch = "wasm32"))]
/// # use xjp_oidc::{sse::check_login_status, http::ReqwestHttpClient};
/// # #[cfg(not(target_arch = "wasm32"))]
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let http = ReqwestHttpClient::default();
///
/// let state = check_login_status(
///     "https://auth.example.com",
///     "login-123",
///     &http
/// ).await?;
///
/// println!("Current status: {:?}", state.status);
/// # Ok(())
/// # }
/// ```
#[cfg(not(target_arch = "wasm32"))]
pub async fn check_login_status(
    issuer: &str,
    login_id: &str,
    http: &dyn HttpClient,
) -> Result<LoginState> {
    // Validate parameters
    if issuer.is_empty() {
        return Err(Error::InvalidParam("issuer cannot be empty"));
    }
    if login_id.is_empty() {
        return Err(Error::InvalidParam("login_id cannot be empty"));
    }

    // Build status check endpoint URL
    let status_endpoint = format!(
        "{}/auth/login-status/{}",
        issuer.trim_end_matches('/'),
        urlencoding::encode(login_id)
    );

    // Make the request
    let response = http
        .get_value(&status_endpoint)
        .await
        .map_err(|e| Error::Network(format!("Failed to check login status: {}", e)))?;

    // Parse response - handle both direct and nested formats
    let state: LoginState = if let Some(nested_state) = response.get("state") {
        // New format: { "loginId": "...", "state": { ... } }
        serde_json::from_value(nested_state.clone())
            .map_err(|e| Error::Verification(format!("Failed to parse login state from nested format: {}", e)))?
    } else {
        // Legacy format: direct LoginState object
        serde_json::from_value(response)
            .map_err(|e| Error::Verification(format!("Failed to parse login state from direct format: {}", e)))?
    };

    Ok(state)
}

// WASM stub implementations
#[cfg(target_arch = "wasm32")]
use crate::errors::{Error, Result};

#[cfg(target_arch = "wasm32")]
pub async fn start_login_session(
    _issuer: &str,
    _client_id: &str,
    _redirect_uri: &str,
    _http: &dyn crate::http::HttpClient,
) -> Result<(String, String)> {
    Err(Error::ServerOnly("SSE login sessions"))
}

#[cfg(target_arch = "wasm32")]
pub async fn check_login_status(
    _issuer: &str,
    _login_id: &str,
    _http: &dyn crate::http::HttpClient,
) -> Result<()> {
    Err(Error::ServerOnly("SSE login status"))
}

#[cfg(test)]
#[cfg(not(target_arch = "wasm32"))]
mod tests {
    use super::*;

    #[test]
    fn test_login_state_parsing() {
        let json = serde_json::json!({
            "status": "SUCCESS",
            "code": "auth_code_123",
            "error": null,
            "created_at": 1234567890
        });

        let state: LoginState = serde_json::from_value(json).unwrap();
        assert_eq!(state.status, LoginStatus::Success);
        assert_eq!(state.code, Some("auth_code_123".to_string()));
        assert!(state.error.is_none());
        assert_eq!(state.created_at, 1234567890);
    }

    #[test]
    fn test_login_status_serialization() {
        let status = LoginStatus::Pending;
        let json = serde_json::to_string(&status).unwrap();
        assert_eq!(json, r#""PENDING""#);

        let status = LoginStatus::Success;
        let json = serde_json::to_string(&status).unwrap();
        assert_eq!(json, r#""SUCCESS""#);
    }

    #[test]
    fn test_nested_login_state_parsing() {
        // Test new nested format from server
        let nested_json = serde_json::json!({
            "loginId": "login_123",
            "state": {
                "status": "PENDING",
                "code": null,
                "error": null,
                "created_at": 1234567890
            }
        });

        // Simulate the parsing logic from check_login_status
        let state: LoginState = if let Some(nested_state) = nested_json.get("state") {
            serde_json::from_value(nested_state.clone()).unwrap()
        } else {
            serde_json::from_value(nested_json).unwrap()
        };

        assert_eq!(state.status, LoginStatus::Pending);
        assert!(state.code.is_none());
        assert!(state.error.is_none());
        assert_eq!(state.created_at, 1234567890);
    }

    #[test]
    fn test_sse_event_data_parsing() {
        // Test SSE event data parsing with direct format
        let direct_data = r#"{"status":"SUCCESS","code":"auth_123","error":null,"created_at":1234567890}"#;
        let state: LoginState = serde_json::from_str(direct_data).unwrap();
        assert_eq!(state.status, LoginStatus::Success);
        assert_eq!(state.code, Some("auth_123".to_string()));

        // Test SSE event data parsing with nested format
        let nested_data = r#"{"loginId":"login_123","state":{"status":"FAILED","code":null,"error":"Auth failed","created_at":1234567890}}"#;
        
        // Simulate the parsing logic from SSE event handler
        let parse_result: Result<LoginState> = {
            if let Ok(state) = serde_json::from_str::<LoginState>(nested_data) {
                Ok(state)
            } else {
                if let Ok(response) = serde_json::from_str::<serde_json::Value>(nested_data) {
                    if let Some(nested_state) = response.get("state") {
                        serde_json::from_value(nested_state.clone())
                            .map_err(|e| Error::Verification(format!("Failed to parse: {}", e)))
                    } else {
                        Err(Error::Verification("No state field".to_string()))
                    }
                } else {
                    Err(Error::Verification("Invalid JSON".to_string()))
                }
            }
        };
        
        let state = parse_result.unwrap();
        assert_eq!(state.status, LoginStatus::Failed);
        assert!(state.code.is_none());
        assert_eq!(state.error, Some("Auth failed".to_string()));
    }
}