arcane-sdk 0.15.0

Arcane Powered game SDK core (ownership tickets, DRM checks)
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
//! The SDK client: initialise once at launch, then read state from memory.

use std::sync::Arc;

use crate::achievements::{AchievementCache, Achievements};
use crate::desktop::{offline_only, refresh_ownership_via_desktop, RefreshOutcome, OFFLINE_ONLY_ENV};
use crate::device::{now_unix, primary_device_hash};
use crate::error::{OwnershipStatus, SdkError};
use crate::friends::Friends;
use crate::net::{Net, NetState};
use crate::p2p::{P2p, P2pState};
use crate::paths::{launch_user_id, load_cached_drm_flag, load_session, SessionState};
use crate::session::{Session, SessionSnapshot, TrackingState};
use crate::ticket::{check_ownership_offline, OwnershipCheck};

/// Longest game id the SDK will accept, in bytes.
pub const MAX_GAME_ID_LEN: usize = 256;

/// Reject a malformed game id before any filesystem or network work happens, so
/// a typo in the launch environment surfaces as `invalid_game_id` instead of a
/// confusing `ticket_missing` several layers down.
///
/// The charset is also what makes it safe to interpolate the id straight into
/// the loopback URL and the `arcane-powered://` deep link.
pub(crate) fn validate_game_id(game_id: &str) -> Result<(), SdkError> {
    if game_id.is_empty() {
        return Err(SdkError::invalid_game_id("The game id is empty.")
            .with_hint("Set ARCANE_GAME_ID to the game id shown for this title in the Arcane portal."));
    }
    if game_id.len() > MAX_GAME_ID_LEN {
        return Err(SdkError::invalid_game_id("The game id is too long.")
            .with_hint("Set ARCANE_GAME_ID to the game id from the Arcane portal, not a file path or a token.")
            .with_context("length", game_id.len())
            .with_context("max_length", MAX_GAME_ID_LEN));
    }
    if let Some((index, bad)) = game_id
        .char_indices()
        .find(|(_, c)| !(c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.')))
    {
        return Err(SdkError::invalid_game_id(
            "The game id contains a character that is not allowed.",
        )
        .with_hint(
            "Allowed characters are ASCII letters, digits, and `_`, `-`, `.`. \
             Check for stray whitespace or quotes around the value.",
        )
        .with_context("index", index)
        .with_context("character", format!("{bad:?}")));
    }
    Ok(())
}

/// The handle a game holds for its whole session.
///
/// Create it once at launch with [`ArcaneClient::init`]. It caches the ownership
/// result, the signed-in `user_id` and the device fingerprint, alongside the
/// `game_id` Arcane Powered launched it with, so nothing downstream has to pass
/// the id around.
///
/// Ownership is never revalidated on its own: it reflects the state as of the
/// last [`init`](ArcaneClient::init) or [`refresh`](ArcaneClient::refresh). The
/// client does run one background thread for the play session — playtime and
/// FPS sampling — described in [`SessionSnapshot`].
///
/// Cloning shares that session, the achievement cache filled by
/// [`Achievements::list`], and the lobby state behind [`P2p`]. The session ends
/// when the last clone is dropped, or on [`shutdown`](ArcaneClient::shutdown).
#[derive(Debug, Clone)]
pub struct ArcaneClient {
    game_id: String,
    user_id: Option<String>,
    device_hash: String,
    ownership: OwnershipStatus,
    ticket_expires_at: Option<i64>,
    checked_at: i64,
    session: Arc<Session>,
    achievements: Arc<AchievementCache>,
    p2p: Arc<P2pState>,
    net: Arc<NetState>,
}

impl ArcaneClient {
    /// Verify ownership and build the client. Call once, at launch.
    ///
    /// You pass nothing: Arcane Powered puts the game id of your title in
    /// `ARCANE_GAME_ID` and the signed-in account in `ARCANE_USER_ID` when it
    /// launches the game, and the SDK reads both. For local development you set
    /// them yourself. [`ArcaneClient::game_id`] reports that game id for the
    /// rest of the session.
    ///
    /// 1. Reads and validates `ARCANE_GAME_ID`.
    /// 2. If the cached `drm_enabled` flag is `false`, returns immediately with
    ///    [`OwnershipStatus::DrmDisabled`] — no ticket required.
    /// 3. Otherwise verifies the cached ownership ticket offline.
    /// 4. If the ticket is missing or expired, asks Arcane desktop to refresh
    ///    (opening the app via deep link when needed), then re-verifies.
    /// 5. Opens the play session and starts the `arcane-session` thread.
    ///
    /// The session never blocks or fails init: if the Arcane desktop app cannot
    /// be reached, tracking stays [`TrackingState::Pending`] and the thread
    /// retries every 60 seconds. It never opens the deep link.
    ///
    /// # Errors
    ///
    /// `missing_game_id`, `invalid_game_id`, `ticket_missing`, `ticket_expired`,
    /// `ticket_invalid`, `device_mismatch`, `clock_rollback`, `not_owned`,
    /// `network_required`, `not_authenticated`, `arcane_unavailable`,
    /// `ambiguous_session`, `internal`.
    pub fn init() -> Result<Self, SdkError> {
        let game_id = crate::paths::launch_game_id()?;
        let client = Self::resolve_ownership(&game_id)?;
        client.session.begin(client.tracking_state());
        Ok(client)
    }

    /// Ownership at launch: ask the desktop app first, fall back to the cached
    /// ticket only when *it* says the cloud is out of reach.
    ///
    /// A game is started by the Arcane desktop app, and minting a fresh ticket
    /// is what that launch is for — so the desktop is a precondition here, not a
    /// fallback. Only once it has answered does the online/offline fork matter.
    ///
    /// This is deliberately not cache-first. A cached ticket that still parses
    /// would otherwise outlive the thing it attests: an account key rotated
    /// since it was minted leaves it bound to a fingerprint the machine can no
    /// longer present, and `device_mismatch` does not ask for a refresh — the
    /// player would be locked out of a title they own with no way back.
    fn resolve_ownership(game_id: &str) -> Result<Self, SdkError> {
        // The developer/QA escape hatch, and the only path that never speaks to
        // the desktop app.
        if offline_only() {
            return Self::from_cached_ticket(game_id);
        }

        match refresh_ownership_via_desktop(game_id) {
            Ok(outcome) => Self::after_refresh(game_id, outcome),
            // The desktop is running and answered; it simply could not reach the
            // cloud. This is the case the cache exists for.
            Err(err) if err.is_cloud_unreachable() => Self::from_cached_ticket(game_id)
                .map_err(|cache_err| cache_err.with_context("desktop_refresh", err.message())),
            Err(err) => Err(err),
        }
    }

    /// Read what the desktop just wrote.
    fn after_refresh(game_id: &str, outcome: RefreshOutcome) -> Result<Self, SdkError> {
        match check_ownership_offline(game_id) {
            Ok(check) => {
                let mut client = Self::from_check(game_id, check);
                client.user_id = client.user_id.or(outcome.user_id);
                Ok(client)
            }
            // The desktop confirmed DRM is off for this title, so there is no
            // ticket to find and the missing file is not a failure.
            Err(err) if !outcome.drm_enabled && err.should_refresh_via_desktop() => {
                let mut client = Self::drm_disabled(game_id)?;
                client.user_id = client.user_id.or(outcome.user_id);
                Ok(client)
            }
            Err(err) => Err(err),
        }
    }

    /// The offline path: whatever the last launch left on disk.
    ///
    /// The cached DRM-off marker is honoured only here. Online, the desktop's
    /// answer is what decides, so a title that has since had DRM switched on
    /// cannot keep starting on a stale flag.
    fn from_cached_ticket(game_id: &str) -> Result<Self, SdkError> {
        if let Some(false) = load_cached_drm_flag(game_id) {
            return Self::drm_disabled(game_id);
        }
        check_ownership_offline(game_id).map(|check| Self::from_check(game_id, check))
    }

    fn tracking_state(&self) -> TrackingState {
        if offline_only() {
            return TrackingState::Disabled;
        }
        if self.ownership == OwnershipStatus::DrmDisabled && self.user_id.is_none() {
            return TrackingState::Disabled;
        }
        TrackingState::Pending
    }

    /// Re-run the ownership check, contacting Arcane desktop, and update the
    /// cached state in place.
    ///
    /// Use this when a long-running session needs to re-confirm ownership — the
    /// client never does it on its own. Returns the same error codes as
    /// [`ArcaneClient::init`]. On failure the client keeps its previous state.
    pub fn refresh(&mut self) -> Result<OwnershipStatus, SdkError> {
        if offline_only() {
            return Err(SdkError::network_required(
                "Ownership refresh is disabled because the SDK is running in offline-only mode.",
            )
            .with_hint(format!(
                "Unset {OFFLINE_ONLY_ENV} to let the SDK contact the Arcane desktop app."
            ))
            .with_context("env", OFFLINE_ONLY_ENV));
        }

        let outcome = refresh_ownership_via_desktop(&self.game_id)?;

        let mut next = match check_ownership_offline(&self.game_id) {
            Ok(check) => Self::from_check(&self.game_id, check),
            Err(err) if !outcome.drm_enabled && err.should_refresh_via_desktop() => {
                Self::drm_disabled(&self.game_id)?
            }
            Err(err) => return Err(err),
        };
        next.user_id = next.user_id.or(outcome.user_id).or(self.user_id.clone());
        next.session = Arc::clone(&self.session);
        next.achievements = Arc::clone(&self.achievements);
        next.p2p = Arc::clone(&self.p2p);
        next.net = Arc::clone(&self.net);

        let status = next.ownership.clone();
        *self = next;
        Ok(status)
    }

    /// The game id Arcane Powered launched this process with.
    pub fn game_id(&self) -> &str {
        &self.game_id
    }

    /// The signed-in Arcane account, when one is known.
    pub fn user_id(&self) -> Option<&str> {
        self.user_id.as_deref()
    }

    /// The fingerprint this ticket is bound to: this machine *and* this account.
    ///
    /// It is derived from the account key, not from the hardware, so the same
    /// machine reports a different value for a different signed-in account.
    /// Empty when DRM is off for the title and no fingerprint is on disk yet.
    pub fn device_hash(&self) -> &str {
        &self.device_hash
    }

    /// Ownership as of the last check.
    pub fn ownership(&self) -> OwnershipStatus {
        self.ownership.clone()
    }

    /// Whether a valid ownership ticket backed the last check. `false` when DRM
    /// is disabled for the title — the game should still run in that case.
    pub fn is_owned(&self) -> bool {
        self.ownership == OwnershipStatus::Owned
    }

    /// Unix timestamp of the ticket's `exp` claim, when a ticket was verified.
    pub fn ticket_expires_at(&self) -> Option<i64> {
        self.ticket_expires_at
    }

    /// Unix timestamp of the last successful check.
    pub fn checked_at(&self) -> i64 {
        self.checked_at
    }

    /// Count one rendered frame. Call it once per frame, from the render loop.
    ///
    /// Outside an FPS sampling window this is a single relaxed atomic load;
    /// inside one it adds a relaxed increment. No lock, no allocation, no clock
    /// read — safe to call thousands of times a second. A game that never calls
    /// it simply reports no FPS samples.
    pub fn frame(&self) {
        self.session.frame();
    }

    /// Record the current display settings, attached to the FPS samples that
    /// follow. Call it at startup and whenever the player changes them — never
    /// from the render loop, it takes a short lock.
    ///
    /// Both values are free-form and only travel to Arcane, for example
    /// `"2560x1440"` and `"high"`. Empty strings clear them.
    pub fn set_graphics(&self, resolution: &str, preset: &str) {
        self.session.set_graphics(resolution, preset);
    }

    /// Achievements for this title: list them, unlock one, read the cache.
    ///
    /// [`Achievements::list`] and [`Achievements::unlock`] each make one
    /// synchronous loopback call, so call them off the render thread — never per
    /// frame. [`Achievements::is_unlocked`] only reads memory.
    ///
    /// ```no_run
    /// # let client = arcane_sdk::ArcaneClient::init()?;
    /// client.achievements().unlock("first_blood")?;
    /// # Ok::<(), arcane_sdk::SdkError>(())
    /// ```
    pub fn achievements(&self) -> Achievements<'_> {
        Achievements::new(&self.game_id, &self.achievements)
    }

    /// This player's friends on Arcane, with `online` and `in_game` for this
    /// title.
    ///
    /// [`Friends::list`] makes one synchronous loopback call, so call it when a
    /// menu opens or on a timer of your own — never per frame. The SDK holds no
    /// list of its own: the Arcane desktop app caches it and flags a stale
    /// answer.
    ///
    /// ```no_run
    /// # let client = arcane_sdk::ArcaneClient::init()?;
    /// client.friends().list()?;
    /// # Ok::<(), arcane_sdk::SdkError>(())
    /// ```
    pub fn friends(&self) -> Friends<'_> {
        Friends::new(&self.game_id, self.user_id.as_deref())
    }

    /// P2P lobbies for this title: create one, join by code or by id, invite a
    /// friend, and read what happened.
    ///
    /// Arcane hosts the lobby and carries each member's opaque connection
    /// blob; your game keeps its own netcode. Every call but
    /// [`P2p::poll_events`] and [`P2p::launch_join_code`] makes one synchronous
    /// loopback round trip — call them off the render thread.
    ///
    /// **Calling this arms lobby event polling** on the `arcane-session`
    /// thread: from here on it asks the Arcane desktop app for events on every
    /// tick, and every 5 seconds while this client is in an open lobby. A game
    /// that never calls `p2p()` pays nothing for any of it.
    ///
    /// ```no_run
    /// # use arcane_sdk::Visibility;
    /// # let client = arcane_sdk::ArcaneClient::init()?;
    /// # let my_endpoint = b"udp://203.0.113.7:7777";
    /// let lobby = client.p2p().create_lobby(4, Visibility::FriendsAndCode, my_endpoint)?;
    /// # Ok::<(), arcane_sdk::SdkError>(())
    /// ```
    pub fn p2p(&self) -> P2p<'_> {
        P2p::new(&self.game_id, &self.p2p)
    }

    /// The coop network: reliable and unreliable messages between the members
    /// of a lobby, with no port to open.
    ///
    /// The Arcane desktop app runs the links — direct when it can, through
    /// Arcane's relay otherwise — and the game reads and writes local sockets.
    /// [`Net::open`] and [`Net::close`] make one loopback round trip;
    /// [`Net::send`], [`Net::receive`] and [`Net::poll_events`] never block on
    /// the network.
    ///
    /// ```no_run
    /// # use arcane_sdk::{Channel, NetOptions, Peer};
    /// # let client = arcane_sdk::ArcaneClient::init()?;
    /// # let lobby_id = "3f2b9c1e-0d4a-4e7b-9a61-5c8e2f7d1b40";
    /// client.net().open(lobby_id, NetOptions::default())?;
    /// client.net().send(Peer::Host, Channel::Unreliable, b"pos 12 4")?;
    /// while let Some(message) = client.net().receive() { /* … */ }
    /// # Ok::<(), arcane_sdk::SdkError>(())
    /// ```
    pub fn net(&self) -> Net<'_> {
        Net::new(&self.game_id, &self.net)
    }

    /// A copy of the current play session state: tracking, playtime, FPS
    /// samples. Reads memory only.
    pub fn session(&self) -> SessionSnapshot {
        self.session.snapshot()
    }

    /// End the play session now, reporting the final playtime, and drop the
    /// client.
    ///
    /// This is the one blocking call of the lifecycle: it posts to the Arcane
    /// desktop app with a 2-second timeout. Dropping the last clone of a client
    /// does the same thing, best-effort, so calling this is optional — it just
    /// makes the moment explicit.
    pub fn shutdown(self) {
        self.net().close();
        self.session.end();
    }

    fn from_check(game_id: &str, check: OwnershipCheck) -> Self {
        let p2p = Arc::new(P2pState::new());
        Self {
            game_id: game_id.to_string(),
            user_id: check.user_id,
            device_hash: check.device_hash,
            ownership: check.status,
            ticket_expires_at: check.ticket_expires_at,
            checked_at: now_unix(),
            session: Arc::new(Session::dormant(game_id, Arc::clone(&p2p))),
            achievements: Arc::new(AchievementCache::new()),
            p2p,
            net: Arc::new(NetState::new()),
        }
    }

    fn drm_disabled(game_id: &str) -> Result<Self, SdkError> {
        let p2p = Arc::new(P2pState::new());
        let user_id = launch_user_id().or_else(|| match load_session() {
            SessionState::SignedIn(user_id) => Some(user_id),
            _ => None,
        });
        // No ticket was verified here, so the fingerprint is informational and
        // best-effort: DRM is off, nothing depends on it.
        let device_hash = user_id
            .as_deref()
            .and_then(primary_device_hash)
            .unwrap_or_default();
        Ok(Self {
            game_id: game_id.to_string(),
            user_id,
            device_hash,
            ownership: OwnershipStatus::DrmDisabled,
            ticket_expires_at: None,
            checked_at: now_unix(),
            session: Arc::new(Session::dormant(game_id, Arc::clone(&p2p))),
            achievements: Arc::new(AchievementCache::new()),
            p2p,
            net: Arc::new(NetState::new()),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn accepts_portal_shaped_ids() {
        for id in [
            "9a1f8c3e-4b27-4d1a-9f6e-2c8b5d70a413",
            "game.01_beta",
            "ABC",
            "0",
        ] {
            assert!(validate_game_id(id).is_ok(), "rejected {id}");
        }
    }

    #[test]
    fn rejects_an_empty_id() {
        let err = validate_game_id("").unwrap_err();
        assert_eq!(err.code(), "invalid_game_id");
        assert!(err.hint().is_some());
    }

    #[test]
    fn rejects_an_oversized_id() {
        let err = validate_game_id(&"a".repeat(MAX_GAME_ID_LEN + 1)).unwrap_err();
        assert_eq!(err.code(), "invalid_game_id");
        assert!(err
            .context()
            .iter()
            .any(|(k, v)| k == "length" && v == &(MAX_GAME_ID_LEN + 1).to_string()));
    }

    #[test]
    fn rejects_characters_that_would_escape_a_url_or_path() {
        for id in [
            "9a1f8c3e/../evil",
            "9a1f8c3e 4b27",
            "9a1f8c3e?x=1",
            "9a1f8c3e#frag",
            "9a1f8c3e\n",
            " 9a1f8c3e",
            "9a1f8c3e ",
            "9a1f8c3é",
        ] {
            let err = validate_game_id(id).unwrap_err();
            assert_eq!(err.code(), "invalid_game_id", "accepted {id:?}");
        }
    }

    #[test]
    fn reports_where_the_bad_character_is() {
        let err = validate_game_id("9a1f8/c3e").unwrap_err();
        let context: Vec<_> = err
            .context()
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect();
        assert!(context.contains(&("index", "5")));
        assert!(context.contains(&("character", "'/'")));
    }
}