openrtc 1.0.4

OpenRTC: a Rust-first P2P runtime for device discovery, signaling, and iroh/QUIC networking.
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//! Parity Tests for pluto-rtc Rust native package
//!
//! These tests verify that the Rust native Client produces output
//! compatible with the TypeScript npm package. They cover:
//!
//! 1. Client creation – init without panic, correct node_id handling
//! 2. Device discovery – search_devices returns correct Device shapes
//! 3. Online/offline – update_presence / set_offline lifecycle
//! 4. Signaling – session creation / subscription
//! 5. Cross-package – serialization parity with TS types
//!
//! Tests use real Firebase auth to prove end-to-end correctness
//! (no sidecar process, no mocks for the signaling backend).

use anyhow::Result;
use openrtc::{
    client::Client,
    signaling::{Device, DeviceEvent, SessionEvent, SignalingSession},
};
use serde_json::json;

const PROJECT_ID: &str = "pluto-rtc-prod";
const API_KEY: &str = "AIzaSyAxyDE1xSYNAk5Ohe8VvKWi3xHOxB4cNV8";

// ---------------------------------------------------------------------------
// Auth Helpers
// ---------------------------------------------------------------------------

async fn get_test_token() -> Result<(String, String)> {
    let url = format!(
        "https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key={}",
        API_KEY
    );

    let client = reqwest::Client::new();
    let res = client
        .post(&url)
        .json(&json!({
            "email": "test@gmail.com",
            "password": "testing",
            "returnSecureToken": true
        }))
        .send()
        .await?;

    if !res.status().is_success() {
        let err = res.text().await?;
        return Err(anyhow::anyhow!("Firebase auth failed: {}", err));
    }

    let json: serde_json::Value = res.json().await?;
    let token = json["idToken"].as_str().unwrap().to_string();
    let uid = json["localId"].as_str().unwrap().to_string();
    Ok((token, uid))
}

fn init_crypto() {
    rustls::crypto::ring::default_provider()
        .install_default()
        .ok();
}

fn live_enabled() -> bool {
    std::env::var("OPENRTC_LIVE_TESTS")
        .map(|value| value == "1" || value.eq_ignore_ascii_case("true"))
        .unwrap_or(false)
}

fn make_client(token: String, api_key: &str) -> Client {
    Client::new(
        PROJECT_ID.into(),
        api_key.into(),
        Box::new(move || Some(token.clone())),
    )
}

// ===========================================================================
// 1. Client creation
// ===========================================================================

#[tokio::test]
async fn test_client_creation_without_panic() {
    init_crypto();
    let client = make_client(
        "test-token".to_string(),
        "pk_test_1111111111111111111111111111111111111111",
    );

    // Node ID starts as None
    assert!(client.current_node_id().await.is_none());
}

#[tokio::test]
async fn test_client_set_node_id() {
    init_crypto();
    let client = make_client("test-token".to_string(), "parity-test");

    client.set_node_id("test-node-001".into()).await;
    assert_eq!(client.current_node_id().await, Some("test-node-001".into()));
}

#[tokio::test]
async fn test_client_connection_manager_exists() {
    init_crypto();
    let client = make_client("test-token".to_string(), "parity-test");

    // ConnectionManager should be available
    let active = client.connection_manager.list_active().await;
    assert_eq!(active.len(), 0);
}

// ===========================================================================
// 2. Device discovery
// ===========================================================================

#[tokio::test]
async fn test_device_discovery_returns_devices() -> Result<()> {
    if !live_enabled() {
        eprintln!("skipping live test: set OPENRTC_LIVE_TESTS=1 to run");
        return Ok(());
    }

    init_crypto();
    let (token, uid) = get_test_token().await?;
    let client = make_client(token, "parity-test");
    client.set_node_id("parity-node-disc".into()).await;
    client.init_iroh(None, vec![]).await?;
    let ticket = client.endpoint_ticket().await?;

    // Register our presence first
    client
        .update_presence(&uid, "Parity Test Node", &ticket, None)
        .await?;

    // Small delay for Firestore propagation
    tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;

    let devices = client.search_devices(&uid).await?;

    // Should find at least our own device
    assert!(!devices.is_empty(), "Should find at least 1 device");

    // Verify Device struct has the expected fields
    for d in &devices {
        assert!(!d.device_id.is_empty());
        assert!(!d.device_name.is_empty());
        // online should be true for our registered device
    }

    // Find our specific device
    let ours = devices.iter().find(|d| d.device_name == "Parity Test Node");
    assert!(ours.is_some(), "Should find our own device");
    let ours = ours.unwrap();
    assert!(ours.online);

    Ok(())
}

// ===========================================================================
// 3. Online/offline changes
// ===========================================================================

#[tokio::test]
async fn test_presence_update_and_offline() -> Result<()> {
    if !live_enabled() {
        eprintln!("skipping live test: set OPENRTC_LIVE_TESTS=1 to run");
        return Ok(());
    }

    init_crypto();
    let (token, uid) = get_test_token().await?;
    let client = make_client(token, "parity-test");
    client.set_node_id("parity-node-presence".into()).await;
    client.init_iroh(None, vec![]).await?;
    let ticket = client.endpoint_ticket().await?;

    // Go online
    client
        .update_presence(&uid, "Presence Test", &ticket, Some("{\"test\":true}"))
        .await?;

    tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;

    // Verify we're discoverable
    let devices = client.search_devices(&uid).await?;
    let ours = devices.iter().find(|d| d.device_name == "Presence Test");
    assert!(ours.is_some(), "Device should be online");
    assert!(ours.unwrap().online);

    // Go offline
    client.set_offline(&uid).await?;

    // Note: offline status may take a moment to propagate;
    // the key test is that the call succeeds without error.

    Ok(())
}

#[tokio::test]
async fn test_presence_with_ttl() -> Result<()> {
    if !live_enabled() {
        eprintln!("skipping live test: set OPENRTC_LIVE_TESTS=1 to run");
        return Ok(());
    }

    init_crypto();
    let (token, uid) = get_test_token().await?;
    let client = make_client(token, "parity-test");
    client.set_node_id("parity-node-ttl".into()).await;
    client.init_iroh(None, vec![]).await?;
    let ticket = client.endpoint_ticket().await?;

    // Update presence with custom TTL
    client
        .update_presence_with_ttl(&uid, "TTL Test", &ticket, 120_000, None)
        .await?;

    // Should not error
    Ok(())
}

// ===========================================================================
// 4. Signaling session lifecycle
// ===========================================================================

#[tokio::test]
async fn test_signaling_session_creation() -> Result<()> {
    if !live_enabled() {
        eprintln!("skipping live test: set OPENRTC_LIVE_TESTS=1 to run");
        return Ok(());
    }

    init_crypto();
    let (token, _uid) = get_test_token().await?;
    let client = make_client(token, "parity-test");
    client.set_node_id("parity-sig-node".into()).await;

    // Send a signaling message
    let doc_id = client
        .send_message("target-node-id", "test-payload", Some("offer"), None)
        .await?;

    assert!(!doc_id.is_empty(), "Should return a document ID");

    Ok(())
}

#[tokio::test]
async fn test_signaling_session_struct_creation() {
    // Verify SignalingSession can be constructed with all required fields
    let session = SignalingSession {
        connection_id: "conn-test-1".into(),
        initiator: "node-a".into(),
        target: "node-b".into(),
        initiator_device_id: "dev-a".into(),
        target_device_id: "dev-b".into(),
        connection_type: Some("iroh".into()),
        offer: None,
        offer_e2ee: None,
        answer: None,
        answer_e2ee: None,
        ice_candidates: vec![],
        initiator_node_id: Some("node-a".into()),
        target_node_id: Some("node-b".into()),
        initiator_endpoint_addr: Some("{\"nodeId\":\"node-a\"}".into()),
        target_endpoint_addr: None,
        intent: Some("file-transfer".into()),
        app_tag: Some("plutonium-app".into()),
        created_at: Some(1700000000000),
        expires_at: Some(1700060000000),
        state: "pending".into(),
    };

    assert_eq!(session.connection_id, "conn-test-1");
    assert_eq!(session.state, "pending");
    assert_eq!(session.connection_type, Some("iroh".into()));
}

// ===========================================================================
// 5. Cross-package serialization parity
// ===========================================================================

#[tokio::test]
async fn test_device_serialization_matches_ts_shape() {
    let device = Device {
        app_tag: Some("plutonium-app".into()),
        device_id: "dev-rust-01".into(),
        user_id: Some("uid-r".into()),
        device_name: "Rust Node".into(),
        kind: Some("device".into()),
        platform_type: Some("desktop".into()),
        capabilities: Some(openrtc::signaling::DeviceCapabilities {
            can_host: true,
            can_sync: true,
            read_only: false,
        }),
        session_id: Some("sess-r".into()),
        node_id: Some("node-rust".into()),
        tag: Some("plutonium-app".into()),
        metadata: None,
        online: true,
        ticket: Some("ticket-rust".into()),
        last_seen_at: None,
        expires_at: None,
        created_at: None,
        updated_at: None,
        excluded_peers: vec![],
    };

    let json = serde_json::to_value(&device).unwrap();

    // Verify all TS-expected camelCase field names are present
    assert_eq!(json["deviceId"], "dev-rust-01");
    assert_eq!(json["deviceName"], "Rust Node");
    assert_eq!(json["platformType"], "desktop");
    assert_eq!(json["online"], true);
    assert_eq!(json["nodeId"], "node-rust");
    assert_eq!(json["ticket"], "ticket-rust");
    assert_eq!(json["tag"], "plutonium-app");

    // Capabilities should use camelCase
    let caps = &json["capabilities"];
    assert_eq!(caps["canHost"], true);
    assert_eq!(caps["canSync"], true);
    assert_eq!(caps["readOnly"], false);
}

#[tokio::test]
async fn test_session_serialization_matches_ts_shape() {
    let session = SignalingSession {
        connection_id: "conn-rs-1".into(),
        initiator: "node-a".into(),
        target: "node-b".into(),
        initiator_device_id: "dev-a".into(),
        target_device_id: "dev-b".into(),
        connection_type: Some("iroh".into()),
        offer: None,
        offer_e2ee: None,
        answer: None,
        answer_e2ee: None,
        ice_candidates: vec![],
        initiator_node_id: Some("node-a".into()),
        target_node_id: Some("node-b".into()),
        initiator_endpoint_addr: Some("{\"nodeId\":\"node-a\"}".into()),
        target_endpoint_addr: None,
        intent: Some("sync".into()),
        app_tag: Some("plutonium-app".into()),
        created_at: Some(1700000000000),
        expires_at: Some(1700060000000),
        state: "pending".into(),
    };

    let json = serde_json::to_value(&session).unwrap();

    // Verify TS-expected camelCase fields
    assert_eq!(json["connectionId"], "conn-rs-1");
    assert_eq!(json["initiator"], "node-a");
    assert_eq!(json["target"], "node-b");
    assert_eq!(json["initiatorDeviceId"], "dev-a");
    assert_eq!(json["targetDeviceId"], "dev-b");
    assert_eq!(json["connectionType"], "iroh");
    assert_eq!(json["state"], "pending");
    assert_eq!(json["initiatorNodeId"], "node-a");
    assert_eq!(json["targetNodeId"], "node-b");
    assert_eq!(json["initiatorEndpointAddr"], "{\"nodeId\":\"node-a\"}");
    assert_eq!(json["intent"], "sync");
    assert_eq!(json["appTag"], "plutonium-app");
    assert_eq!(json["iceCandidates"], json!([]));
}

#[tokio::test]
async fn test_device_event_serialization() {
    // Verify DeviceEvent enum serializes with correct tag
    let event = DeviceEvent::Added {
        device: Device {
            app_tag: None,
            device_id: "dev-1".into(),
            user_id: None,
            device_name: "Test".into(),
            kind: None,
            platform_type: None,
            capabilities: None,
            session_id: None,
            node_id: None,
            tag: None,
            metadata: None,
            online: true,
            ticket: None,
            last_seen_at: None,
            expires_at: None,
            created_at: None,
            updated_at: None,
            excluded_peers: vec![],
        },
    };

    let json = serde_json::to_value(&event).unwrap();
    // TS expects { type: "added", device: {...} }
    assert_eq!(json["type"], "added");
    assert!(json["device"].is_object());
}

#[tokio::test]
async fn test_session_event_serialization() {
    let event = SessionEvent::Added {
        session: SignalingSession {
            connection_id: "conn-evt".into(),
            initiator: "a".into(),
            target: "b".into(),
            initiator_device_id: "da".into(),
            target_device_id: "db".into(),
            connection_type: None,
            offer: None,
            offer_e2ee: None,
            answer: None,
            answer_e2ee: None,
            ice_candidates: vec![],
            initiator_node_id: None,
            target_node_id: None,
            initiator_endpoint_addr: None,
            target_endpoint_addr: None,
            intent: None,
            app_tag: None,
            created_at: None,
            expires_at: None,
            state: "pending".into(),
        },
    };

    let json = serde_json::to_value(&event).unwrap();
    // TS expects { type: "added", session: {...} }
    assert_eq!(json["type"], "added");
    assert!(json["session"].is_object());
    assert_eq!(json["session"]["connectionId"], "conn-evt");
}

#[tokio::test]
async fn test_ts_device_json_deserializes_into_rust() {
    // Simulated TS-generated Device JSON (camelCase)
    let ts_json = r#"{
        "deviceId": "dev-ts-01",
        "userId": "uid-ts",
        "deviceName": "Web Browser",
        "platformType": "web",
        "capabilities": { "canHost": false, "canSync": true, "readOnly": true },
        "sessionId": "sess-ts",
        "nodeId": "node-ts",
        "tag": "plutonium-app",
        "metadata": "{\"browser\":\"chrome\"}",
        "online": true,
        "ticket": "ticket-ts",
        "lastSeenAt": null,
        "expiresAt": null,
        "createdAt": null,
        "updatedAt": null
    }"#;

    let device: Device = serde_json::from_str(ts_json).unwrap();
    assert_eq!(device.device_id, "dev-ts-01");
    assert_eq!(device.device_name, "Web Browser");
    assert_eq!(device.platform_type, Some("web".into()));
    assert!(device.online);
    assert_eq!(device.capabilities.as_ref().unwrap().can_host, false);
    assert_eq!(device.capabilities.as_ref().unwrap().can_sync, true);
    assert_eq!(device.capabilities.as_ref().unwrap().read_only, true);
}

#[tokio::test]
async fn test_ts_session_json_deserializes_into_rust() {
    let ts_json = r#"{
        "connectionId": "conn-ts-1",
        "initiator": "node-ts-a",
        "target": "node-ts-b",
        "initiatorDeviceId": "dev-ts-a",
        "targetDeviceId": "dev-ts-b",
        "connectionType": "iroh",
        "offer": null,
        "offerE2ee": null,
        "answer": null,
        "answerE2ee": null,
        "iceCandidates": [],
        "initiatorNodeId": "node-ts-a",
        "targetNodeId": "node-ts-b",
        "initiatorEndpointAddr": "{\"nodeId\":\"node-ts-a\"}",
        "targetEndpointAddr": null,
        "intent": "file-transfer",
        "appTag": "plutonium-app",
        "createdAt": 1700000000000,
        "expiresAt": 1700060000000,
        "state": "pending"
    }"#;

    let session: SignalingSession = serde_json::from_str(ts_json).unwrap();
    assert_eq!(session.connection_id, "conn-ts-1");
    assert_eq!(session.initiator_device_id, "dev-ts-a");
    assert_eq!(session.connection_type, Some("iroh".into()));
    assert_eq!(session.state, "pending");
    assert_eq!(session.intent, Some("file-transfer".into()));
}