use std::sync::Arc;
use crate::desktop::{offline_only, refresh_ownership_via_desktop, OFFLINE_ONLY_ENV};
use crate::device::{device_hash, now_unix};
use crate::error::{OwnershipStatus, SdkError};
use crate::paths::{load_cached_drm_flag, load_session, SessionState};
use crate::session::{Session, SessionSnapshot, TrackingState};
use crate::ticket::{check_ownership_offline, OwnershipCheck};
pub const MAX_PUBLIC_KEY_LEN: usize = 256;
pub(crate) fn validate_public_key(public_key: &str) -> Result<(), SdkError> {
if public_key.is_empty() {
return Err(SdkError::invalid_public_key("The public key is empty.")
.with_hint("Pass the public key generated for this title in the Arcane portal."));
}
if public_key.len() > MAX_PUBLIC_KEY_LEN {
return Err(SdkError::invalid_public_key("The public key is too long.")
.with_hint("Pass the public key from the Arcane portal, not a file path or a token.")
.with_context("length", public_key.len())
.with_context("max_length", MAX_PUBLIC_KEY_LEN));
}
if let Some((index, bad)) = public_key
.char_indices()
.find(|(_, c)| !(c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.')))
{
return Err(SdkError::invalid_public_key(
"The public key 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(())
}
#[derive(Debug, Clone)]
pub struct ArcaneClient {
public_key: String,
game_id: Option<String>,
user_id: Option<String>,
device_hash: String,
ownership: OwnershipStatus,
ticket_expires_at: Option<i64>,
checked_at: i64,
session: Arc<Session>,
}
impl ArcaneClient {
pub fn init(public_key: &str) -> Result<Self, SdkError> {
validate_public_key(public_key)?;
let client = Self::resolve_ownership(public_key)?;
client.session.begin(client.tracking_state());
Ok(client)
}
fn resolve_ownership(public_key: &str) -> Result<Self, SdkError> {
if let Some(false) = load_cached_drm_flag(public_key) {
return Self::drm_disabled(public_key);
}
match check_ownership_offline(public_key) {
Ok(check) => Ok(Self::from_check(public_key, check)),
Err(err) if err.should_refresh_via_desktop() && !offline_only() => {
let outcome = refresh_ownership_via_desktop(public_key)?;
match check_ownership_offline(public_key) {
Ok(check) => {
let mut client = Self::from_check(public_key, check);
client.user_id = client.user_id.or(outcome.user_id);
client.game_id = client.game_id.or(outcome.game_id);
Ok(client)
}
Err(retry_err)
if !outcome.drm_enabled && retry_err.should_refresh_via_desktop() =>
{
let mut client = Self::drm_disabled(public_key)?;
client.user_id = client.user_id.or(outcome.user_id);
client.game_id = client.game_id.or(outcome.game_id);
Ok(client)
}
Err(retry_err) => Err(retry_err),
}
}
Err(err) => Err(err),
}
}
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
}
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.public_key)?;
let mut next = match check_ownership_offline(&self.public_key) {
Ok(check) => Self::from_check(&self.public_key, check),
Err(err) if !outcome.drm_enabled && err.should_refresh_via_desktop() => {
Self::drm_disabled(&self.public_key)?
}
Err(err) => return Err(err),
};
next.user_id = next.user_id.or(outcome.user_id).or(self.user_id.clone());
next.game_id = next.game_id.or(outcome.game_id).or(self.game_id.clone());
next.session = Arc::clone(&self.session);
let status = next.ownership.clone();
*self = next;
Ok(status)
}
pub fn public_key(&self) -> &str {
&self.public_key
}
pub fn game_id(&self) -> Option<&str> {
self.game_id.as_deref()
}
pub fn user_id(&self) -> Option<&str> {
self.user_id.as_deref()
}
pub fn device_hash(&self) -> &str {
&self.device_hash
}
pub fn ownership(&self) -> OwnershipStatus {
self.ownership.clone()
}
pub fn is_owned(&self) -> bool {
self.ownership == OwnershipStatus::Owned
}
pub fn ticket_expires_at(&self) -> Option<i64> {
self.ticket_expires_at
}
pub fn checked_at(&self) -> i64 {
self.checked_at
}
pub fn frame(&self) {
self.session.frame();
}
pub fn set_graphics(&self, resolution: &str, preset: &str) {
self.session.set_graphics(resolution, preset);
}
pub fn session(&self) -> SessionSnapshot {
self.session.snapshot()
}
pub fn shutdown(self) {
self.session.end();
}
fn from_check(public_key: &str, check: OwnershipCheck) -> Self {
Self {
public_key: public_key.to_string(),
game_id: check.game_id,
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(public_key)),
}
}
fn drm_disabled(public_key: &str) -> Result<Self, SdkError> {
Ok(Self {
public_key: public_key.to_string(),
game_id: None,
user_id: match load_session() {
SessionState::SignedIn(user_id) => Some(user_id),
_ => None,
},
device_hash: device_hash()?,
ownership: OwnershipStatus::DrmDisabled,
ticket_expires_at: None,
checked_at: now_unix(),
session: Arc::new(Session::dormant(public_key)),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_portal_shaped_keys() {
for key in ["pk_live_abc123", "pk-test.01", "ABC", "0"] {
assert!(validate_public_key(key).is_ok(), "rejected {key}");
}
}
#[test]
fn rejects_empty_key() {
let err = validate_public_key("").unwrap_err();
assert_eq!(err.code(), "invalid_public_key");
assert!(err.hint().is_some());
}
#[test]
fn rejects_oversized_key() {
let err = validate_public_key(&"a".repeat(MAX_PUBLIC_KEY_LEN + 1)).unwrap_err();
assert_eq!(err.code(), "invalid_public_key");
assert!(err
.context()
.iter()
.any(|(k, v)| k == "length" && v == &(MAX_PUBLIC_KEY_LEN + 1).to_string()));
}
#[test]
fn rejects_characters_that_would_escape_a_url_or_path() {
for key in [
"pk_abc/../evil",
"pk abc",
"pk_abc?x=1",
"pk_abc#frag",
"pk_abc\n",
" pk_abc",
"pk_abc ",
"pk_é",
] {
let err = validate_public_key(key).unwrap_err();
assert_eq!(err.code(), "invalid_public_key", "accepted {key:?}");
}
}
#[test]
fn reports_where_the_bad_character_is() {
let err = validate_public_key("pk_ab/cd").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", "'/'")));
}
}