Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Major refactoring #1

Merged
merged 13 commits into from
Dec 20, 2023
3 changes: 1 addition & 2 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ jobs:
strategy:
fail-fast: false
matrix:
rust: [beta, stable, 1.56.0]
rust: [beta, stable, 1.70.0]

steps:
- uses: actions/checkout@v3
Expand All @@ -31,7 +31,6 @@ jobs:
clippy:
name: Clippy
runs-on: ubuntu-latest
if: github.event_name != 'pull_request'
steps:
- uses: actions/checkout@v3
- uses: dtolnay/rust-toolchain@nightly
Expand Down
22 changes: 20 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,20 @@
/target
/Cargo.lock
# Generated by Cargo
# will have compiled files and executables
debug/
target/

# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
Cargo.lock

# These are backup files generated by rustfmt
**/*.rs.bk

# MSVC Windows builds of rustc generate these, which store debugging information
*.pdb

# Temporary json files
*.json

# Environment file
env
31 changes: 30 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,10 +1,39 @@
[package]
name = "xal"
version = "0.1.0"
edition = "2021"
edition = "2018"
description = "Xbox Authentication library"
license = "MIT"
repository = "https://github.com/OpenXbox/xal-rs"
homepage = "https://openxbox.org"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
async-trait = "0.1.74"
reqwest = { version = "0.11", features = ["json"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
cvlib = "0.1.2"
chrono = "0.4"
uuid = { version = "1", features = ["v4", "serde"] }
thiserror = "1.0.37"
url = "2.3.1"
http = "0.2.9"
log = "0.4.20"
p256 = "0.13.2"
base64ct = { version = "1.6.0", features = ["std"] }
sha2 = "0.10.8"
rand = "0.8.5"
oauth2 = "4.4.2"
nt-time = { version = "0.6.5", features = ["chrono"] }

[dev-dependencies]
hex-literal = "0.3.4"
tokio = { version = "1", features = ["macros"] }
tokio-test = "0.4.3"

[workspace]
members = [
"examples"
]
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Team OpenXbox

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
16 changes: 11 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,18 @@

Authenticate with Xbox Live

## Quickstart
## Documentation

```rs
todo!("")
```
Find the documentation here: <https://docs.rs/xal>

## Examples

Documentation: <https://docs.rs/xal>
Check out [xal-examples](./examples/)

## Minimum supported Rust version

This crate requires at least Rust 1.70 (stable).

## Disclaimer

This is an unofficial library not endorsed by Microsoft. Use at your own risk!
34 changes: 34 additions & 0 deletions examples/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
[package]
name = "xal_examples"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
xal = { path = ".." }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
async-trait = "0.1.74"
env_logger = "0.10.1"
log = "0.4.20"
clap = { version = "4.4.8", features = ["derive"] }
chrono = "0.4.31"
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
reqwest = { version = "0.11", features = ["json"] }

# Optional dependencies
wry = { version = "0.34.2", optional = true }

[features]
webview = ["wry"]

[[bin]]
name = "auth_cli"

[[bin]]
name = "auth_azure"

[[bin]]
name = "auth_webview"
required-features = ["webview"]
83 changes: 83 additions & 0 deletions examples/src/bin/auth_azure.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
use std::str::from_utf8;

use async_trait::async_trait;
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::TcpListener,
};
use xal::{
client_params::CLIENT_ANDROID,
oauth2::{RedirectUrl, Scope},
url::Url,
AuthPromptCallback, AuthPromptData, Error, XalAppParameters,
};
use xal_examples::auth_main;

pub struct HttpCallbackHandler {
bind_host: String,
redirect_url_base: String,
}

#[async_trait]
impl AuthPromptCallback for HttpCallbackHandler {
async fn call(
&self,
cb_data: AuthPromptData,
) -> Result<Option<Url>, Box<dyn std::error::Error>> {
let prompt = cb_data.prompt();
println!("{prompt}\n");

let listener = TcpListener::bind(&self.bind_host).await?;
println!("HTTP Server listening, waiting for connection...");

let (mut socket, addr) = listener.accept().await?;
println!("Connection received from {addr:?}");

let mut buf = [0u8; 1024];

if socket.read(&mut buf).await? == 0 {
return Err("Failed reading http request".into());
}

socket.write_all(b"HTTP/1.1 200 OK\n\r\n\r").await?;

let http_req = from_utf8(&buf)?;
println!("HTTP REQ: {http_req}");

let path = http_req.split(' ').nth(1).unwrap();
println!("Path: {path}");

Ok(Some(Url::parse(&format!(
"{}{}",
self.redirect_url_base, path
))?))
}
}

#[tokio::main]
async fn main() -> Result<(), Error> {
auth_main(
XalAppParameters {
app_id: "388ea51c-0b25-4029-aae2-17df49d23905".into(),
title_id: None,
auth_scopes: vec![
Scope::new("Xboxlive.signin".into()),
Scope::new("Xboxlive.offline_access".into()),
],
redirect_uri: Some(
RedirectUrl::new("http://localhost:8080/auth/callback".into()).unwrap(),
),
},
CLIENT_ANDROID(),
"RETAIL".into(),
xal::AccessTokenPrefix::D,
HttpCallbackHandler {
bind_host: "127.0.0.1:8080".into(),
redirect_url_base: "http://localhost:8080".into(),
},
)
.await
.ok();

Ok(())
}
11 changes: 11 additions & 0 deletions examples/src/bin/auth_cli.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
use xal::{AccessTokenPrefix, CliCallbackHandler, Error};
use xal_examples::auth_main_default;

#[tokio::main]
async fn main() -> Result<(), Error> {
auth_main_default(AccessTokenPrefix::None, CliCallbackHandler)
.await
.ok();

Ok(())
}
67 changes: 67 additions & 0 deletions examples/src/bin/auth_minecraft.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
use serde_json::json;
use xal::{
extensions::JsonExDeserializeMiddleware, oauth2::TokenResponse, AccessTokenPrefix,
CliCallbackHandler, Error, XalAuthenticator,
};
use xal_examples::auth_main;

#[tokio::main]
async fn main() -> Result<(), Error> {
let app_params = xal::app_params::MC_BEDROCK_SWITCH();
let client_params = xal::client_params::CLIENT_NINTENDO();

let ts = auth_main(
app_params,
client_params,
"RETAIL".into(),
AccessTokenPrefix::None,
CliCallbackHandler,
)
.await?;

let mut authenticator = XalAuthenticator::from(ts.clone());
let xsts_mc_services = authenticator
.get_xsts_token(
ts.device_token.as_ref(),
ts.title_token.as_ref(),
ts.user_token.as_ref(),
"rp://api.minecraftservices.com/",
)
.await?;

let identity_token = xsts_mc_services.authorization_header_value();
println!("identityToken: {identity_token}");

/* Minecraft stuff */
// Fetch minecraft token
let mc_token = reqwest::Client::new()
.post("https://api.minecraftservices.com/authentication/login_with_xbox")
.json(&json!({"identityToken": identity_token}))
.send()
.await?
.json_ex::<xal::oauth2::basic::BasicTokenResponse>()
.await?;
println!("MC: {mc_token:?}");

// Get minecraft entitlements
let entitlements = reqwest::Client::new()
.get("https://api.minecraftservices.com/entitlements/mcstore")
.bearer_auth(mc_token.access_token().secret())
.send()
.await?
.text()
.await?;
println!("Entitlements: {entitlements}");

// Get minecraft profile
let profile = reqwest::Client::new()
.get("https://api.minecraftservices.com/minecraft/profile")
.bearer_auth(mc_token.access_token().secret())
.send()
.await?
.text()
.await?;
println!("Profile: {profile}");

Ok(())
}
Loading