@smbcloud / smbcloud-ascapi Mirror · read-only / commits / eac2a13
Fork 0

Read-only mirror of github.com/smbcloudXYZ/smbcloud-ascapi.

Mirrored from https://github.com/smbcloudXYZ/smbcloud-ascapi.git

Synced Nov 25, 09:15 UTC

Add asc xiaomi for the GetApps developer interface

A new smbcloud-ascapi-xiaomi crate signs requests to Xiaomi GetApps (/third-api on global.developer.mi.com) the way Xiaomi's interface guide describes: HMAC-SHA1 over the method, the Base64 MD5 of the body, the AppId, PkgName, Timestamp and Nonce, and the path, keyed with the app's App Secret. The signer is tested against vectors computed in Python; Xiaomi's own sample can't be reproduced because its body was edited after the hash was taken. Two commands cover what Xiaomi documents publicly: - asc xiaomi orders: the order query, up to 30 days per call. Xiaomi has to allowlist the account first. - asc xiaomi upload-url: the APK upload address. It uploads nothing and works as a credentials and signature check. Signed URLs in the answer are cut to scheme, host and path. The upload and submit steps after that are on a private Xiaomi wiki, so the listing, the APK and the review submission stay in the console for now. Credentials come from --xiaomi-env, XIAOMI_ENV_PATH or the XIAOMI_* variables; the secret never appears in Debug output or errors, and --dry-run prints the signed request with the signature withheld. The crate is added to the CI solo-build loop and the crates.io publish list, and docs/xiaomi.md covers setup, the error codes and the PSV route for apps that are also on Google Play. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Seto Elkahfi committed Nov 19, 2026 at 10:35 UTC eac2a13f3b960c7cbefef15400b59e729f3c2b12
20 files changed +1080 -9
.github/workflows/ci.yml
+1 -1
@@ -69,7 +69,7 @@ jobs:
69 # core with the MCP server's dependencies already in the graph and
70 # tell us nothing.
71 run: |
72 - for crate in core aso pricing iap signing reports play appgallery msstore admob amazon; do
72 + for crate in core aso pricing iap signing reports play appgallery msstore admob amazon xiaomi; do
73 cargo check --package "smbcloud-ascapi-${crate}" --locked
74 done
75
.github/workflows/release-crates.yml
+4 -3
@@ -92,7 +92,7 @@ jobs:
92 - name: Check the lower crates build alone
93 shell: bash
94 run: |
95 - for crate in core aso pricing iap signing reports play appgallery msstore admob amazon; do
95 + for crate in core aso pricing iap signing reports play appgallery msstore admob amazon xiaomi; do
96 cargo check -p "smbcloud-ascapi-${crate}" --locked
97 done
98
@@ -135,8 +135,8 @@ jobs:
135
136 # Dependency order: a crate can only be published once everything it
137 # depends on is on crates.io. core first, then the domain crates
138 - # that only depend on core, then play, appgallery, msstore, admob
139 - # and amazon (which depend on no other workspace crate), then
138 + # that only depend on core, then play, appgallery, msstore, admob,
139 + # amazon and xiaomi (which depend on no other workspace crate), then
140 # frontend, mcp, and the CLI last.
141 crates=(
142 core
@@ -150,6 +150,7 @@ jobs:
150 msstore
151 admob
152 amazon
153 + xiaomi
154 frontend
155 mcp
156 cli
Cargo.lock
+38
@@ -501,6 +501,7 @@ dependencies = [
501 "block-buffer",
502 "const-oid",
503 "crypto-common",
504 + "subtle",
505 ]
506
507 [[package]]
@@ -701,6 +702,15 @@ version = "0.5.0"
702 source = "registry+https://github.com/rust-lang/crates.io-index"
703 checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
704
705 +[[package]]
706 +name = "hmac"
707 +version = "0.12.1"
708 +source = "registry+https://github.com/rust-lang/crates.io-index"
709 +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
710 +dependencies = [
711 + "digest",
712 +]
713 +
714 [[package]]
715 name = "http"
716 version = "1.5.0"
@@ -1746,6 +1756,17 @@ dependencies = [
1756 "serde",
1757 ]
1758
1759 +[[package]]
1760 +name = "sha1"
1761 +version = "0.10.7"
1762 +source = "registry+https://github.com/rust-lang/crates.io-index"
1763 +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
1764 +dependencies = [
1765 + "cfg-if",
1766 + "cpufeatures 0.2.17",
1767 + "digest",
1768 +]
1769 +
1770 [[package]]
1771 name = "sha2"
1772 version = "0.10.9"
@@ -1877,6 +1898,7 @@ dependencies = [
1898 "smbcloud-ascapi-pricing",
1899 "smbcloud-ascapi-reports",
1900 "smbcloud-ascapi-signing",
1901 + "smbcloud-ascapi-xiaomi",
1902 "tokio",
1903 ]
1904
@@ -1908,6 +1930,7 @@ dependencies = [
1930 "smbcloud-ascapi-msstore",
1931 "smbcloud-ascapi-play",
1932 "smbcloud-ascapi-signing",
1933 + "smbcloud-ascapi-xiaomi",
1934 "tokio",
1935 "zip",
1936 ]
@@ -1998,6 +2021,21 @@ dependencies = [
2021 "zeroize",
2022 ]
2023
2024 +[[package]]
2025 +name = "smbcloud-ascapi-xiaomi"
2026 +version = "0.3.0"
2027 +dependencies = [
2028 + "base64 0.22.1",
2029 + "hmac",
2030 + "md5",
2031 + "rand 0.8.8",
2032 + "reqwest",
2033 + "serde",
2034 + "serde_json",
2035 + "sha1",
2036 + "thiserror",
2037 +]
2038 +
2039 [[package]]
2040 name = "socket2"
2041 version = "0.6.5"
Cargo.toml
+2
@@ -8,6 +8,7 @@ members = [
8 "crates/appgallery",
9 "crates/amazon",
10 "crates/msstore",
11 + "crates/xiaomi",
12 "crates/signing",
13 "crates/pricing",
14 "crates/iap",
@@ -32,6 +33,7 @@ smbcloud-ascapi-admob = { version = "0.3.0", path = "crates/admob" }
33 smbcloud-ascapi-amazon = { version = "0.3.0", path = "crates/amazon" }
34 smbcloud-ascapi-appgallery = { version = "0.3.0", path = "crates/appgallery" }
35 smbcloud-ascapi-msstore = { version = "0.3.0", path = "crates/msstore" }
36 +smbcloud-ascapi-xiaomi = { version = "0.3.0", path = "crates/xiaomi" }
37 smbcloud-ascapi-signing = { version = "0.3.0", path = "crates/signing" }
38 smbcloud-ascapi-pricing = { version = "0.3.0", path = "crates/pricing" }
39 smbcloud-ascapi-iap = { version = "0.3.0", path = "crates/iap" }
README.md
+1 -1
@@ -35,7 +35,7 @@ Pre-built binaries are on [GitHub Releases](https://github.com/smbcloudXYZ/smbcl
35
36 ## Docs
37
38 -[Install](docs/install.md) · [Credentials](docs/credentials.md) · [AppGallery](docs/appgallery.md) · [Amazon](docs/amazon.md) · [AdMob](docs/admob.md) · [China compliance](docs/china-compliance.md) · [Architecture](docs/architecture.md)
38 +[Install](docs/install.md) · [Credentials](docs/credentials.md) · [AppGallery](docs/appgallery.md) · [Amazon](docs/amazon.md) · [Xiaomi GetApps](docs/xiaomi.md) · [AdMob](docs/admob.md) · [China compliance](docs/china-compliance.md) · [Architecture](docs/architecture.md)
39
40 ## Contributing
41
crates/cli/Cargo.toml
+1
@@ -25,6 +25,7 @@ smbcloud-ascapi-aso = { workspace = true }
25 smbcloud-ascapi-core = { workspace = true }
26 smbcloud-ascapi-appgallery = { workspace = true }
27 smbcloud-ascapi-msstore = { workspace = true }
28 +smbcloud-ascapi-xiaomi = { workspace = true }
29 smbcloud-ascapi-play = { workspace = true }
30 smbcloud-ascapi-pricing = { workspace = true }
31 smbcloud-ascapi-iap = { workspace = true }
crates/cli/src/main.rs
+93
@@ -884,6 +884,41 @@ enum AmazonTargetingCommand {
884 },
885 }
886
887 +#[derive(Subcommand)]
888 +enum XiaomiCommand {
889 + /// Orders in a window of up to 30 days (POST /third-api/order/v1/query).
890 + /// Xiaomi must allowlist the account first (overseas-dev@xiaomi.com);
891 + /// without it GetApps answers 999 "does not have … permission". At most
892 + /// one request a second. With `--dry-run` the signed request is printed
893 + /// instead of sent.
894 + Orders {
895 + /// Comma-separated package names; defaults to XIAOMI_PACKAGE.
896 + #[arg(long)]
897 + packages: Option<String>,
898 + /// Start: Unix seconds or YYYY-MM-DD (00:00 UTC).
899 + #[arg(long)]
900 + start: String,
901 + /// End: Unix seconds or YYYY-MM-DD (00:00 UTC). After the start.
902 + #[arg(long)]
903 + end: String,
904 + /// Comma-separated pricing regions, e.g. RO,ES.
905 + #[arg(long)]
906 + regions: Option<String>,
907 + /// Comma-separated payment states: 1 click to pay, 2 paid, 3 closed,
908 + /// 4 refund pending, 5 refund started, 6 refunded.
909 + #[arg(long)]
910 + pay_status: Option<String>,
911 + /// 0 normal, 1 test, 2 promotion, 3 incentive.
912 + #[arg(long)]
913 + pay_type: Option<i64>,
914 + },
915 + /// The APK upload address for XIAOMI_PACKAGE
916 + /// (GET /third-api/apk/v1/getUploadUrl). Uploads nothing. Useful as a
917 + /// credentials and signature check; signed URLs in the answer are cut to
918 + /// scheme, host and path.
919 + UploadUrl,
920 +}
921 +
922 #[derive(Subcommand)]
923 #[allow(clippy::large_enum_variant)]
924 enum MsStoreCommand {
@@ -1049,6 +1084,18 @@ enum Command {
1084 #[command(subcommand)]
1085 command: MsStoreCommand,
1086 },
1087 + /// Xiaomi GetApps: order queries and the APK upload address, through the
1088 + /// signed developer interface. Uses the app's App ID and App Secret from
1089 + /// the console, not the App Store Connect key. Listing, upload and
1090 + /// submission are done in the console.
1091 + Xiaomi {
1092 + /// Dotenv file with the XIAOMI_* credentials. Falls back to
1093 + /// `XIAOMI_ENV_PATH`, then to the XIAOMI_* variables themselves.
1094 + #[arg(long, global = true)]
1095 + xiaomi_env: Option<PathBuf>,
1096 + #[command(subcommand)]
1097 + command: XiaomiCommand,
1098 + },
1099 /// Look up apps by bundle ID, or a specific app by its ASC app ID.
1100 Apps {
1101 #[command(subcommand)]
@@ -1466,6 +1513,43 @@ async fn run_amazon(
1513 }
1514 }
1515
1516 +async fn run_xiaomi(
1517 + env_path: Option<&std::path::Path>,
1518 + command: XiaomiCommand,
1519 + dry_run: bool,
1520 +) -> Result<()> {
1521 + use smbcloud_ascapi_frontend::xiaomi;
1522 + let client = xiaomi::xiaomi_client(env_path).map_err(|e| anyhow::anyhow!(e))?;
1523 + let fail = |e: String| anyhow::anyhow!(e);
1524 + match command {
1525 + XiaomiCommand::Orders {
1526 + packages,
1527 + start,
1528 + end,
1529 + regions,
1530 + pay_status,
1531 + pay_type,
1532 + } => {
1533 + let query = smbcloud_ascapi_xiaomi::OrderQuery {
1534 + pkgs: packages.unwrap_or_else(|| client.package().to_string()),
1535 + regions,
1536 + pay_status,
1537 + pay_type,
1538 + start_timestamp: xiaomi::parse_time(&start).map_err(fail)?,
1539 + end_timestamp: xiaomi::parse_time(&end).map_err(fail)?,
1540 + };
1541 + print_json(
1542 + &xiaomi::orders(&client, &query, dry_run)
1543 + .await
1544 + .map_err(fail)?,
1545 + )
1546 + }
1547 + XiaomiCommand::UploadUrl => {
1548 + print_json(&xiaomi::upload_url(&client, dry_run).await.map_err(fail)?)
1549 + }
1550 + }
1551 +}
1552 +
1553 async fn run_msstore(
1554 env_path: Option<&std::path::Path>,
1555 command: MsStoreCommand,
@@ -3358,6 +3442,14 @@ async fn main() -> Result<()> {
3442 return run_msstore(msstore_env.as_deref(), command, cli.dry_run).await;
3443 }
3444
3445 + if let Some(Command::Xiaomi {
3446 + xiaomi_env,
3447 + command,
3448 + }) = cli.command
3449 + {
3450 + return run_xiaomi(xiaomi_env.as_deref(), command, cli.dry_run).await;
3451 + }
3452 +
3453 let key_id = cli
3454 .key_id
3455 .clone()
@@ -3392,6 +3484,7 @@ async fn main() -> Result<()> {
3484 Command::AppGallery { .. }
3485 | Command::Amazon { .. }
3486 | Command::Msstore { .. }
3487 + | Command::Xiaomi { .. }
3488 | Command::Play { .. }
3489 | Command::Admob { .. } => {
3490 unreachable!("handled before App Store Connect credentials")
crates/frontend/Cargo.toml
+1
@@ -22,6 +22,7 @@ smbcloud-ascapi-amazon = { workspace = true }
22 smbcloud-ascapi-appgallery = { workspace = true }
23 smbcloud-ascapi-aso = { workspace = true }
24 smbcloud-ascapi-msstore = { workspace = true }
25 +smbcloud-ascapi-xiaomi = { workspace = true }
26 smbcloud-ascapi-core = { workspace = true }
27 smbcloud-ascapi-play = { workspace = true }
28 smbcloud-ascapi-signing = { workspace = true }
crates/frontend/src/lib.rs
+1
@@ -37,6 +37,7 @@ pub mod release_controls;
37 pub mod review;
38 pub mod time;
39 pub mod upload;
40 +pub mod xiaomi;
41
42 pub use attach_build::{attach_build, AttachedBuild};
43 pub use await_processing::{
crates/frontend/src/xiaomi.rs new
+136
@@ -0,0 +1,136 @@
1 +//! Xiaomi GetApps operations shared by `asc xiaomi` and, later, MCP tools.
2 +//!
3 +//! Only what Xiaomi documents publicly: the order query and the APK upload
4 +//! address. A response can carry a signed upload URL, so URLs in it are cut
5 +//! to scheme, host and path before printing.
6 +
7 +use std::path::Path;
8 +
9 +use serde_json::{Map, Value};
10 +use smbcloud_ascapi_xiaomi::{Credentials, OrderQuery, Prepared, XiaomiClient};
11 +
12 +/// Resolve the client. `path` wins; then `XIAOMI_ENV_PATH`; then the
13 +/// `XIAOMI_*` variables set directly. The App Secret never appears in an
14 +/// error.
15 +pub fn xiaomi_client(path: Option<&Path>) -> Result<XiaomiClient, String> {
16 + let credentials = if let Some(path) = path {
17 + Credentials::from_env_file(path)
18 + } else if let Ok(path) = std::env::var("XIAOMI_ENV_PATH") {
19 + Credentials::from_env_file(path)
20 + } else if std::env::var_os("XIAOMI_APP_SECRET").is_some() {
21 + Credentials::from_process_env()
22 + } else {
23 + return Err("no Xiaomi GetApps credentials: pass --xiaomi-env, or set \
24 + XIAOMI_ENV_PATH (a dotenv file) or the XIAOMI_* variables"
25 + .to_string());
26 + };
27 + credentials
28 + .map(XiaomiClient::new)
29 + .map_err(|e| e.to_string())
30 +}
31 +
32 +/// Send `prepared`, or with `dry_run` describe it and send nothing. The
33 +/// response has its URLs redacted.
34 +async fn run(client: &XiaomiClient, prepared: Prepared, dry_run: bool) -> Result<Value, String> {
35 + if dry_run {
36 + return Ok(prepared.describe());
37 + }
38 + client
39 + .send(prepared)
40 + .await
41 + .map(|data| redact_urls(&data))
42 + .map_err(|e| e.to_string())
43 +}
44 +
45 +/// Orders for the query. Read-only, but `dry_run` still skips the request so
46 +/// a signature can be checked without spending the one-a-second budget.
47 +pub async fn orders(
48 + client: &XiaomiClient,
49 + query: &OrderQuery,
50 + dry_run: bool,
51 +) -> Result<Value, String> {
52 + query.validate()?;
53 + let prepared = client.orders_request(query).map_err(|e| e.to_string())?;
54 + run(client, prepared, dry_run).await
55 +}
56 +
57 +/// The APK upload address for the client's package. Fetching it uploads
58 +/// nothing.
59 +pub async fn upload_url(client: &XiaomiClient, dry_run: bool) -> Result<Value, String> {
60 + let prepared = client.upload_url_request().map_err(|e| e.to_string())?;
61 + run(client, prepared, dry_run).await
62 +}
63 +
64 +/// Copy of `value` with every `http(s)://` string reduced to scheme, host and
65 +/// path, so a signed query string is never printed.
66 +pub fn redact_urls(value: &Value) -> Value {
67 + match value {
68 + Value::String(s) if s.starts_with("http://") || s.starts_with("https://") => {
69 + let base = s.split(['?', '#']).next().unwrap_or(s);
70 + if base.len() < s.len() {
71 + Value::String(format!("{base}?<redacted>"))
72 + } else {
73 + value.clone()
74 + }
75 + }
76 + Value::Array(items) => Value::Array(items.iter().map(redact_urls).collect()),
77 + Value::Object(map) => Value::Object(
78 + map.iter()
79 + .map(|(k, v)| (k.clone(), redact_urls(v)))
80 + .collect::<Map<_, _>>(),
81 + ),
82 + _ => value.clone(),
83 + }
84 +}
85 +
86 +/// Parse a time argument: Unix seconds, or a `YYYY-MM-DD` date taken as
87 +/// 00:00 UTC.
88 +pub fn parse_time(arg: &str) -> Result<u64, String> {
89 + let arg = arg.trim();
90 + if !arg.is_empty() && arg.bytes().all(|b| b.is_ascii_digit()) {
91 + return arg.parse().map_err(|e| format!("{arg}: {e}"));
92 + }
93 + let parts: Vec<&str> = arg.split('-').collect();
94 + let [y, m, d] = parts.as_slice() else {
95 + return Err(format!("{arg}: expected Unix seconds or YYYY-MM-DD"));
96 + };
97 + let (y, m, d): (i64, i64, i64) = match (y.parse(), m.parse(), d.parse()) {
98 + (Ok(y), Ok(m), Ok(d)) if (1..=12).contains(&m) && (1..=31).contains(&d) => (y, m, d),
99 + _ => return Err(format!("{arg}: expected Unix seconds or YYYY-MM-DD")),
100 + };
101 + // Days from the civil date (Howard Hinnant's algorithm).
102 + let y = if m <= 2 { y - 1 } else { y };
103 + let era = y.div_euclid(400);
104 + let yoe = y - era * 400;
105 + let mp = (m + 9) % 12;
106 + let doy = (153 * mp + 2) / 5 + d - 1;
107 + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
108 + let days = era * 146_097 + doe - 719_468;
109 + u64::try_from(days * 86_400).map_err(|_| format!("{arg}: before 1970"))
110 +}
111 +
112 +#[cfg(test)]
113 +mod tests {
114 + use super::*;
115 + use serde_json::json;
116 +
117 + #[test]
118 + fn signed_query_strings_are_cut() {
119 + let v = json!({"data": {"uploadUrl": "https://bucket.example/k?Signature=abc&Expires=1",
120 + "plain": "https://example.com/a", "n": 1}});
121 + assert_eq!(
122 + redact_urls(&v),
123 + json!({"data": {"uploadUrl": "https://bucket.example/k?<redacted>",
124 + "plain": "https://example.com/a", "n": 1}})
125 + );
126 + }
127 +
128 + #[test]
129 + fn times_parse_as_seconds_or_dates() {
130 + assert_eq!(parse_time("1703134938").unwrap(), 1_703_134_938);
131 + assert_eq!(parse_time("1970-01-01").unwrap(), 0);
132 + assert_eq!(parse_time("2026-11-19").unwrap(), 1_795_046_400);
133 + assert!(parse_time("2026-13-01").is_err());
134 + assert!(parse_time("yesterday").is_err());
135 + }
136 +}
crates/xiaomi/Cargo.toml new
+23
@@ -0,0 +1,23 @@
1 +[package]
2 +name = "smbcloud-ascapi-xiaomi"
3 +version.workspace = true
4 +edition.workspace = true
5 +authors.workspace = true
6 +license.workspace = true
7 +repository.workspace = true
8 +description = "Xiaomi GetApps developer interface: HMAC-SHA1 signed requests, order queries and the APK upload address."
9 +readme = "README.md"
10 +
11 +[lib]
12 +path = "src/lib.rs"
13 +
14 +[dependencies]
15 +base64 = { workspace = true }
16 +hmac = "0.12"
17 +md5 = "0.7"
18 +rand = { workspace = true }
19 +reqwest = { workspace = true, features = ["json", "rustls-tls-native-roots"] }
20 +serde = { workspace = true, features = ["derive"] }
21 +serde_json = { workspace = true }
22 +sha1 = "0.10"
23 +thiserror = { workspace = true }
crates/xiaomi/README.md new
+17
@@ -0,0 +1,17 @@
1 +# smbcloud-ascapi-xiaomi
2 +
3 +The Xiaomi GetApps developer interface (`/third-api/…` on
4 +global.developer.mi.com): HMAC-SHA1 request signing, the order query, and the
5 +APK upload address. It shares nothing with `smbcloud-ascapi-core`.
6 +
7 +```rust
8 +use smbcloud_ascapi_xiaomi::{Credentials, XiaomiClient};
9 +
10 +let client = XiaomiClient::new(Credentials::from_env_file("xiaomi.env")?);
11 +let request = client.upload_url_request()?;
12 +let data = client.send(request).await?;
13 +```
14 +
15 +`XiaomiClient::prepare` signs a request without sending it, and
16 +`Prepared::describe` shows it with the signature withheld. The signer lives in
17 +`sign.rs` and is tested against vectors computed independently.
crates/xiaomi/src/auth.rs new
+183
@@ -0,0 +1,183 @@
1 +use std::collections::HashMap;
2 +use std::path::Path;
3 +
4 +use crate::error::{Error, Result};
5 +
6 +pub const KEY_APP_ID: &str = "XIAOMI_APP_ID";
7 +pub const KEY_APP_SECRET: &str = "XIAOMI_APP_SECRET";
8 +pub const KEY_PACKAGE: &str = "XIAOMI_PACKAGE";
9 +pub const KEY_EMAIL: &str = "XIAOMI_EMAIL";
10 +pub const KEY_DEVELOPER_ID: &str = "XIAOMI_DEVELOPER_ID";
11 +pub const KEY_USER_ID: &str = "XIAOMI_USER_ID";
12 +
13 +/// The App ID and App Secret are per app (the app's page in the console);
14 +/// the email, developer id and Xiaomi user id belong to the developer
15 +/// account. GetApps checks that all of them belong together.
16 +#[derive(Clone)]
17 +pub struct Credentials {
18 + pub app_id: String,
19 + app_secret: String,
20 + pub package: String,
21 + pub email: String,
22 + pub developer_id: String,
23 + pub user_id: String,
24 +}
25 +
26 +// Hand-written so `{:?}` can never print the App Secret.
27 +impl std::fmt::Debug for Credentials {
28 + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29 + f.debug_struct("Credentials")
30 + .field("app_id", &self.app_id)
31 + .field("app_secret", &"<redacted>")
32 + .field("package", &self.package)
33 + .field("email", &self.email)
34 + .field("developer_id", &self.developer_id)
35 + .field("user_id", &self.user_id)
36 + .finish()
37 + }
38 +}
39 +
40 +/// Parse a dotenv file: `KEY=VALUE` lines, `#` comments, an optional
41 +/// `export ` prefix, and one pair of matching quotes around a value.
42 +pub fn parse_dotenv(text: &str) -> HashMap<String, String> {
43 + let mut map = HashMap::new();
44 + for line in text.lines() {
45 + let line = line.trim();
46 + if line.is_empty() || line.starts_with('#') {
47 + continue;
48 + }
49 + let line = line.strip_prefix("export ").unwrap_or(line);
50 + let Some((key, value)) = line.split_once('=') else {
51 + continue;
52 + };
53 + let value = value.trim();
54 + let value = ['"', '\'']
55 + .iter()
56 + .find_map(|q| value.strip_prefix(*q).and_then(|v| v.strip_suffix(*q)))
57 + .unwrap_or(value);
58 + map.insert(key.trim().to_string(), value.to_string());
59 + }
60 + map
61 +}
62 +
63 +impl Credentials {
64 + pub fn new(
65 + app_id: impl Into<String>,
66 + app_secret: impl Into<String>,
67 + package: impl Into<String>,
68 + email: impl Into<String>,
69 + developer_id: impl Into<String>,
70 + user_id: impl Into<String>,
71 + ) -> Self {
72 + Self {
73 + app_id: app_id.into(),
74 + app_secret: app_secret.into(),
75 + package: package.into(),
76 + email: email.into(),
77 + developer_id: developer_id.into(),
78 + user_id: user_id.into(),
79 + }
80 + }
81 +
82 + /// Build from a key lookup. A key that is absent or empty is an error
83 + /// naming the key; so is a developer or user id that is not a number.
84 + pub fn from_lookup(get: impl Fn(&str) -> Option<String>) -> Result<Self> {
85 + let need = |key: &'static str| {
86 + get(key)
87 + .map(|v| v.trim().to_string())
88 + .filter(|v| !v.is_empty())
89 + .ok_or(Error::MissingCredential(key))
90 + };
91 + let numeric = |key: &'static str| {
92 + let value = need(key)?;
93 + if value.bytes().all(|b| b.is_ascii_digit()) {
94 + Ok(value)
95 + } else {
96 + Err(Error::NotNumeric(key))
97 + }
98 + };
99 + Ok(Self {
100 + app_id: need(KEY_APP_ID)?,
101 + app_secret: need(KEY_APP_SECRET)?,
102 + package: need(KEY_PACKAGE)?,
103 + email: need(KEY_EMAIL)?,
104 + developer_id: numeric(KEY_DEVELOPER_ID)?,
105 + user_id: numeric(KEY_USER_ID)?,
106 + })
107 + }
108 +
109 + pub fn from_env_file(path: impl AsRef<Path>) -> Result<Self> {
110 + let path = path.as_ref();
111 + let text = std::fs::read_to_string(path).map_err(|source| Error::EnvRead {
112 + path: path.display().to_string(),
113 + source,
114 + })?;
115 + let map = parse_dotenv(&text);
116 + Self::from_lookup(|key| map.get(key).cloned())
117 + }
118 +
119 + pub fn from_process_env() -> Result<Self> {
120 + Self::from_lookup(|key| std::env::var(key).ok())
121 + }
122 +
123 + pub(crate) fn app_secret(&self) -> &str {
124 + &self.app_secret
125 + }
126 +}
127 +
128 +#[cfg(test)]
129 +mod tests {
130 + use super::*;
131 +
132 + fn full() -> HashMap<&'static str, &'static str> {
133 + HashMap::from([
134 + (KEY_APP_ID, "2882303761521427725"),
135 + (KEY_APP_SECRET, "s3cret"),
136 + (KEY_PACKAGE, "com.example.app"),
137 + (KEY_EMAIL, "dev@example.com"),
138 + (KEY_DEVELOPER_ID, "1080405"),
139 + (KEY_USER_ID, "2410896325"),
140 + ])
141 + }
142 +
143 + #[test]
144 + fn reads_every_key() {
145 + let map = full();
146 + let c = Credentials::from_lookup(|k| map.get(k).map(|v| v.to_string())).unwrap();
147 + assert_eq!(c.app_id, "2882303761521427725");
148 + assert_eq!(c.package, "com.example.app");
149 + assert_eq!(c.app_secret(), "s3cret");
150 + }
151 +
152 + #[test]
153 + fn names_the_missing_key() {
154 + let mut map = full();
155 + map.insert(KEY_EMAIL, " ");
156 + let e = Credentials::from_lookup(|k| map.get(k).map(|v| v.to_string())).unwrap_err();
157 + assert!(matches!(e, Error::MissingCredential(KEY_EMAIL)));
158 + }
159 +
160 + #[test]
161 + fn rejects_a_non_numeric_user_id() {
162 + let mut map = full();
163 + map.insert(KEY_USER_ID, "2410896325xx");
164 + let e = Credentials::from_lookup(|k| map.get(k).map(|v| v.to_string())).unwrap_err();
165 + assert!(matches!(e, Error::NotNumeric(KEY_USER_ID)));
166 + }
167 +
168 + #[test]
169 + fn debug_hides_the_secret() {
170 + let map = full();
171 + let c = Credentials::from_lookup(|k| map.get(k).map(|v| v.to_string())).unwrap();
172 + let shown = format!("{c:?}");
173 + assert!(!shown.contains("s3cret"));
174 + assert!(shown.contains("<redacted>"));
175 + }
176 +
177 + #[test]
178 + fn dotenv_strips_quotes_and_export() {
179 + let map = parse_dotenv("# c\nexport XIAOMI_APP_ID=\"1\"\nXIAOMI_EMAIL='a@b'\n");
180 + assert_eq!(map["XIAOMI_APP_ID"], "1");
181 + assert_eq!(map["XIAOMI_EMAIL"], "a@b");
182 + }
183 +}
crates/xiaomi/src/client.rs new
+263
@@ -0,0 +1,263 @@
1 +use std::time::{SystemTime, UNIX_EPOCH};
2 +
3 +use reqwest::Method;
4 +use serde::Serialize;
5 +use serde_json::Value;
6 +
7 +use crate::auth::Credentials;
8 +use crate::error::{Error, Result};
9 +use crate::sign::{new_nonce, SignedHeaders};
10 +
11 +pub const API_ROOT: &str = "https://global.developer.mi.com";
12 +/// Order query. Needs allowlisting: email overseas-dev@xiaomi.com. At most one
13 +/// request a second and 30 days per query.
14 +pub const ORDER_QUERY_PATH: &str = "/third-api/order/v1/query";
15 +/// The APK upload address. Named in Xiaomi's header page as the GET example;
16 +/// its response shape is not public.
17 +pub const UPLOAD_URL_PATH: &str = "/third-api/apk/v1/getUploadUrl";
18 +
19 +/// Body of the order query. Lists are comma-separated, as the API takes them.
20 +#[derive(Debug, Clone, Serialize)]
21 +#[serde(rename_all = "camelCase")]
22 +pub struct OrderQuery {
23 + pub pkgs: String,
24 + #[serde(skip_serializing_if = "Option::is_none")]
25 + pub regions: Option<String>,
26 + /// 1 click to pay, 2 paid, 3 closed, 4 refund pending, 5 refund started,
27 + /// 6 refunded.
28 + #[serde(skip_serializing_if = "Option::is_none")]
29 + pub pay_status: Option<String>,
30 + /// 0 normal, 1 test, 2 promotion, 3 incentive.
31 + #[serde(skip_serializing_if = "Option::is_none")]
32 + pub pay_type: Option<i64>,
33 + pub start_timestamp: u64,
34 + pub end_timestamp: u64,
35 +}
36 +
37 +/// Longest window the order query accepts.
38 +pub const ORDER_QUERY_MAX_SECS: u64 = 30 * 24 * 60 * 60;
39 +
40 +impl OrderQuery {
41 + /// The checks GetApps would otherwise answer with a 400.
42 + pub fn validate(&self) -> std::result::Result<(), String> {
43 + if self.pkgs.trim().is_empty() {
44 + return Err("at least one package is required".into());
45 + }
46 + if self.end_timestamp <= self.start_timestamp {
47 + return Err("the end time must be after the start time".into());
48 + }
49 + if self.end_timestamp - self.start_timestamp > ORDER_QUERY_MAX_SECS {
50 + return Err("the window is longer than 30 days".into());
51 + }
52 + Ok(())
53 + }
54 +}
55 +
56 +/// A prepared request: what would be sent, for `--dry-run`. Holds the
57 +/// signature, never the secret.
58 +#[derive(Debug, Clone)]
59 +pub struct Prepared {
60 + pub method: Method,
61 + pub url: String,
62 + pub headers: SignedHeaders,
63 + pub body: Option<String>,
64 +}
65 +
66 +impl Prepared {
67 + /// What `--dry-run` prints: the method, URL, headers, canonical string
68 + /// and body. The `Authorization` value is withheld: it is valid for 30
69 + /// minutes.
70 + pub fn describe(&self) -> Value {
71 + let headers: serde_json::Map<String, Value> = self
72 + .headers
73 + .pairs()
74 + .iter()
75 + .map(|(name, value)| {
76 + let shown = if *name == "Authorization" {
77 + "<signature withheld>"
78 + } else {
79 + value
80 + };
81 + (name.to_string(), Value::String(shown.to_string()))
82 + })
83 + .collect();
84 + serde_json::json!({
85 + "method": self.method.as_str(),
86 + "url": self.url,
87 + "headers": headers,
88 + "canonical": self.headers.canonical,
89 + "body": self.body,
90 + })
91 + }
92 +}
93 +
94 +pub struct XiaomiClient {
95 + http: reqwest::Client,
96 + credentials: Credentials,
97 + root: String,
98 +}
99 +
100 +impl XiaomiClient {
101 + pub fn new(credentials: Credentials) -> Self {
102 + Self {
103 + http: reqwest::Client::new(),
104 + credentials,
105 + root: API_ROOT.to_string(),
106 + }
107 + }
108 +
109 + /// Point at another host, for tests against a local server.
110 + pub fn with_root(mut self, root: impl Into<String>) -> Self {
111 + self.root = root.into();
112 + self
113 + }
114 +
115 + pub fn package(&self) -> &str {
116 + &self.credentials.package
117 + }
118 +
119 + /// Sign a request without sending it. `body` is serialized once here, and
120 + /// those exact bytes are both hashed and sent.
121 + pub fn prepare(
122 + &self,
123 + method: Method,
124 + path: &str,
125 + body: Option<&impl Serialize>,
126 + ) -> Result<Prepared> {
127 + let body = body.map(serde_json::to_string).transpose()?;
128 + let timestamp = SystemTime::now()
129 + .duration_since(UNIX_EPOCH)
130 + .map(|d| d.as_secs())
131 + .unwrap_or_default();
132 + let headers = SignedHeaders::new(
133 + &self.credentials,
134 + method.as_str(),
135 + path,
136 + body.as_deref().map(str::as_bytes),
137 + timestamp,
138 + new_nonce(),
139 + );
140 + Ok(Prepared {
141 + method,
142 + url: format!("{}{path}", self.root),
143 + headers,
144 + body,
145 + })
146 + }
147 +
148 + /// Send a prepared request and return the envelope's `data`. An HTTP error
149 + /// or an envelope `code` other than 200 is an error carrying Xiaomi's
150 + /// message.
151 + pub async fn send(&self, prepared: Prepared) -> Result<Value> {
152 + let mut request = self
153 + .http
154 + .request(prepared.method, &prepared.url)
155 + .header("Content-Type", "application/json");
156 + for (name, value) in prepared.headers.pairs() {
157 + request = request.header(name, value);
158 + }
159 + if let Some(body) = prepared.body {
160 + request = request.body(body);
161 + }
162 + let response = request.send().await?;
163 + let status = response.status();
164 + let text = response.text().await.unwrap_or_default();
165 + if !status.is_success() {
166 + return Err(Error::Http2xx {
167 + status: status.as_u16(),
168 + detail: text,
169 + });
170 + }
171 + unwrap_envelope(serde_json::from_str(&text)?)
172 + }
173 +
174 + pub fn orders_request(&self, query: &OrderQuery) -> Result<Prepared> {
175 + self.prepare(Method::POST, ORDER_QUERY_PATH, Some(query))
176 + }
177 +
178 + pub fn upload_url_request(&self) -> Result<Prepared> {
179 + self.prepare(Method::GET, UPLOAD_URL_PATH, None::<&()>)
180 + }
181 +}
182 +
183 +/// `{"code": 200, "msg": …, "data": …}` → `data`. Any other code is an error.
184 +pub(crate) fn unwrap_envelope(envelope: Value) -> Result<Value> {
185 + let code = envelope.get("code").and_then(Value::as_i64).unwrap_or(-1);
186 + if code == 200 {
187 + return Ok(envelope.get("data").cloned().unwrap_or(Value::Null));
188 + }
189 + Err(Error::Api {
190 + code,
191 + msg: envelope
192 + .get("msg")
193 + .and_then(Value::as_str)
194 + .unwrap_or("no message")
195 + .to_string(),
196 + })
197 +}
198 +
199 +#[cfg(test)]
200 +mod tests {
201 + use super::*;
202 + use serde_json::json;
203 +
204 + fn query() -> OrderQuery {
205 + OrderQuery {
206 + pkgs: "com.example.app".into(),
207 + regions: None,
208 + pay_status: Some("2,6".into()),
209 + pay_type: None,
210 + start_timestamp: 1_701_084_799,
211 + end_timestamp: 1_702_684_799,
212 + }
213 + }
214 +
215 + #[test]
216 + fn order_body_is_camel_case_and_skips_unset() {
217 + let body = serde_json::to_value(query()).unwrap();
218 + assert_eq!(
219 + body,
220 + json!({"pkgs":"com.example.app","payStatus":"2,6",
221 + "startTimestamp":1_701_084_799u64,"endTimestamp":1_702_684_799u64})
222 + );
223 + }
224 +
225 + #[test]
226 + fn order_window_is_checked() {
227 + assert!(query().validate().is_ok());
228 + let mut q = query();
229 + q.end_timestamp = q.start_timestamp;
230 + assert!(q.validate().is_err());
231 + q.end_timestamp = q.start_timestamp + ORDER_QUERY_MAX_SECS + 1;
232 + assert!(q.validate().unwrap_err().contains("30 days"));
233 + }
234 +
235 + #[test]
236 + fn envelope_200_yields_data() {
237 + let data = unwrap_envelope(json!({"code":200,"msg":"ok","data":[1]})).unwrap();
238 + assert_eq!(data, json!([1]));
239 + }
240 +
241 + #[test]
242 + fn envelope_error_keeps_code_and_message() {
243 + let e = unwrap_envelope(json!({"code":1002,"msg":"Signature mismatch!"})).unwrap_err();
244 + assert!(matches!(e, Error::Api { code: 1002, ref msg } if msg == "Signature mismatch!"));
245 + }
246 +
247 + #[test]
248 + fn prepare_hashes_the_bytes_it_sends() {
249 + let credentials = Credentials::new("1", "secret", "com.example.app", "a@b", "2", "3");
250 + let client = XiaomiClient::new(credentials);
251 + let p = client
252 + .prepare(Method::POST, ORDER_QUERY_PATH, Some(&query()))
253 + .unwrap();
254 + let body = p.body.unwrap();
255 + let md5 = crate::sign::body_md5(body.as_bytes());
256 + assert!(p
257 + .headers
258 + .canonical
259 + .starts_with(&format!("POST{md5}AppId:1")));
260 + assert!(p.headers.canonical.ends_with(ORDER_QUERY_PATH));
261 + assert_eq!(p.url, format!("{API_ROOT}{ORDER_QUERY_PATH}"));
262 + }
263 +}
crates/xiaomi/src/error.rs new
+36
@@ -0,0 +1,36 @@
1 +use thiserror::Error;
2 +
3 +#[derive(Debug, Error)]
4 +pub enum Error {
5 + #[error("failed to read the credentials file {path}: {source}")]
6 + EnvRead {
7 + path: String,
8 + #[source]
9 + source: std::io::Error,
10 + },
11 +
12 + /// Names the key only, never a value.
13 + #[error("missing or empty credential {0}")]
14 + MissingCredential(&'static str),
15 +
16 + /// `DeveloperId` and `UserId` must be numbers; GetApps answers 999 otherwise.
17 + #[error("credential {0} must be a number")]
18 + NotNumeric(&'static str),
19 +
20 + #[error("http request failed: {0}")]
21 + Http(#[from] reqwest::Error),
22 +
23 + #[error("failed to decode JSON: {0}")]
24 + Json(#[from] serde_json::Error),
25 +
26 + /// A non-2xx HTTP status.
27 + #[error("GetApps returned HTTP {status}: {detail}")]
28 + Http2xx { status: u16, detail: String },
29 +
30 + /// HTTP 200 with a `code` other than 200 in the envelope. 999 is a header
31 + /// or permission problem, 1001/1002/3001/3002 are signature problems.
32 + #[error("GetApps returned code {code}: {msg}")]
33 + Api { code: i64, msg: String },
34 +}
35 +
36 +pub type Result<T> = std::result::Result<T, Error>;
crates/xiaomi/src/lib.rs new
+25
@@ -0,0 +1,25 @@
1 +//! Xiaomi GetApps developer interface (`/third-api/…` on
2 +//! global.developer.mi.com).
3 +//!
4 +//! Every request carries the same header set (`AppId`, `PkgName`, `Email`,
5 +//! `DeveloperId`, `UserId`, `Nonce`, `Timestamp`) and an `Authorization`
6 +//! header: an HMAC-SHA1 over a canonical string, keyed with the App Secret
7 +//! from the app's page in the console. See [`sign`] for the string.
8 +//!
9 +//! The public docs describe two endpoints: the order query, which needs
10 +//! allowlisting by Xiaomi, and the APK upload address. The upload and submit
11 +//! steps that follow are documented on a private Xiaomi wiki, so they are not
12 +//! here yet.
13 +
14 +pub mod auth;
15 +pub mod client;
16 +pub mod error;
17 +pub mod sign;
18 +
19 +pub use auth::{parse_dotenv, Credentials};
20 +pub use client::{
21 + OrderQuery, Prepared, XiaomiClient, API_ROOT, ORDER_QUERY_MAX_SECS, ORDER_QUERY_PATH,
22 + UPLOAD_URL_PATH,
23 +};
24 +pub use error::{Error, Result};
25 +pub use sign::{body_md5, canonical_string, signature, SignedHeaders};
crates/xiaomi/src/sign.rs new
+189
@@ -0,0 +1,189 @@
1 +//! The `Authorization` signature from Xiaomi's "GetApps Interface User
2 +//! Guide" and "Generic GetApps interface request header" pages.
3 +//!
4 +//! The canonical string is the method, then the Base64 MD5 of the body when
5 +//! there is one, then `AppId:…PkgName:…Timestamp:…Nonce:…`, then the request
6 +//! path without the domain, all concatenated with no separators. The
7 +//! signature is the standard (not URL-safe) Base64 of its HMAC-SHA1, keyed
8 +//! with the App Secret.
9 +//!
10 +//! The docs spell the timestamp label both `Timestamp:` and `TimeStamp:`.
11 +//! Both assembled examples use `Timestamp:`, so that is what is signed. If
12 +//! GetApps answers 1002 (signature mismatch), check this first.
13 +
14 +use base64::engine::general_purpose::STANDARD;
15 +use base64::Engine;
16 +use hmac::{Hmac, Mac};
17 +use sha1::Sha1;
18 +
19 +use crate::auth::Credentials;
20 +
21 +/// Base64 of the MD5 of the exact body bytes sent.
22 +pub fn body_md5(body: &[u8]) -> String {
23 + STANDARD.encode(md5::compute(body).0)
24 +}
25 +
26 +/// The string the HMAC is computed over.
27 +pub fn canonical_string(
28 + method: &str,
29 + body: Option<&[u8]>,
30 + app_id: &str,
31 + package: &str,
32 + timestamp: &str,
33 + nonce: &str,
34 + path: &str,
35 +) -> String {
36 + let md5 = body.map(body_md5).unwrap_or_default();
37 + format!(
38 + "{}{md5}AppId:{app_id}PkgName:{package}Timestamp:{timestamp}Nonce:{nonce}{path}",
39 + method.to_ascii_uppercase()
40 + )
41 +}
42 +
43 +/// Base64 (standard alphabet) of HMAC-SHA1(secret, canonical).
44 +pub fn signature(secret: &str, canonical: &str) -> String {
45 + let mut mac =
46 + Hmac::<Sha1>::new_from_slice(secret.as_bytes()).expect("HMAC accepts a key of any length");
47 + mac.update(canonical.as_bytes());
48 + STANDARD.encode(mac.finalize().into_bytes())
49 +}
50 +
51 +/// A fresh nonce: 32 lowercase hex characters, the shape of a UUID without
52 +/// dashes. GetApps refuses a nonce it has seen (3002).
53 +pub fn new_nonce() -> String {
54 + use rand::Rng;
55 + let bytes: [u8; 16] = rand::thread_rng().gen();
56 + bytes.iter().map(|b| format!("{b:02x}")).collect()
57 +}
58 +
59 +/// The full header set for one request. `Debug` and [`SignedHeaders::pairs`]
60 +/// carry the signature, never the secret.
61 +#[derive(Debug, Clone)]
62 +pub struct SignedHeaders {
63 + pub canonical: String,
64 + pub authorization: String,
65 + pub app_id: String,
66 + pub package: String,
67 + pub email: String,
68 + pub developer_id: String,
69 + pub user_id: String,
70 + pub nonce: String,
71 + pub timestamp: String,
72 +}
73 +
74 +impl SignedHeaders {
75 + pub fn new(
76 + credentials: &Credentials,
77 + method: &str,
78 + path: &str,
79 + body: Option<&[u8]>,
80 + timestamp: u64,
81 + nonce: String,
82 + ) -> Self {
83 + let timestamp = timestamp.to_string();
84 + let canonical = canonical_string(
85 + method,
86 + body,
87 + &credentials.app_id,
88 + &credentials.package,
89 + &timestamp,
90 + &nonce,
91 + path,
92 + );
93 + Self {
94 + authorization: signature(credentials.app_secret(), &canonical),
95 + canonical,
96 + app_id: credentials.app_id.clone(),
97 + package: credentials.package.clone(),
98 + email: credentials.email.clone(),
99 + developer_id: credentials.developer_id.clone(),
100 + user_id: credentials.user_id.clone(),
101 + nonce,
102 + timestamp,
103 + }
104 + }
105 +
106 + /// Header names exactly as GetApps wants them (initial capitals).
107 + pub fn pairs(&self) -> [(&'static str, &str); 8] {
108 + [
109 + ("Authorization", &self.authorization),
110 + ("AppId", &self.app_id),
111 + ("PkgName", &self.package),
112 + ("Email", &self.email),
113 + ("DeveloperId", &self.developer_id),
114 + ("UserId", &self.user_id),
115 + ("Nonce", &self.nonce),
116 + ("Timestamp", &self.timestamp),
117 + ]
118 + }
119 +}
120 +
121 +#[cfg(test)]
122 +mod tests {
123 + use super::*;
124 +
125 + // Vectors computed independently with Python's hmac, hashlib and base64.
126 + // Xiaomi's own sample cannot be reproduced: its body was edited after the
127 + // MD5 was taken.
128 + const BODY: &str =
129 + r#"{"pkgs":"com.example.app","startTimestamp":1701084799,"endTimestamp":1702684799}"#;
130 + const NONCE: &str = "8420674727e94e7cabff27ac66db5c5d";
131 +
132 + #[test]
133 + fn body_md5_is_base64_of_the_raw_digest() {
134 + assert_eq!(body_md5(BODY.as_bytes()), "FQgbNE045u5FQeSePz8Rbw==");
135 + }
136 +
137 + #[test]
138 + fn post_with_body() {
139 + let canonical = canonical_string(
140 + "post",
141 + Some(BODY.as_bytes()),
142 + "2882303761521427725",
143 + "com.example.app",
144 + "1703134938",
145 + NONCE,
146 + "/third-api/order/v1/query",
147 + );
148 + assert_eq!(
149 + canonical,
150 + "POSTFQgbNE045u5FQeSePz8Rbw==AppId:2882303761521427725PkgName:com.example.app\
151 + Timestamp:1703134938Nonce:8420674727e94e7cabff27ac66db5c5d/third-api/order/v1/query"
152 + );
153 + assert_eq!(
154 + signature("123456", &canonical),
155 + "chhSRb8ikmOSRWr60iEQPDziodI="
156 + );
157 + }
158 +
159 + #[test]
160 + fn get_without_body() {
161 + let credentials = Credentials::new(
162 + "2882303761521427725",
163 + "123456",
164 + "com.example.app",
165 + "dev@example.com",
166 + "1080405",
167 + "2410896325",
168 + );
169 + let headers = SignedHeaders::new(
170 + &credentials,
171 + "GET",
172 + "/third-api/apk/v1/getUploadUrl",
173 + None,
174 + 1703134938,
175 + NONCE.to_string(),
176 + );
177 + assert!(headers.canonical.starts_with("GETAppId:"));
178 + assert_eq!(headers.authorization, "dC0JlSQeQguwnve9J67o82nBPFQ=");
179 + assert!(!format!("{headers:?}").contains("123456"));
180 + }
181 +
182 + #[test]
183 + fn nonce_is_32_hex_and_fresh() {
184 + let a = new_nonce();
185 + assert_eq!(a.len(), 32);
186 + assert!(a.bytes().all(|b| b.is_ascii_hexdigit()));
187 + assert_ne!(a, new_nonce());
188 + }
189 +}
docs/README.md
+1 -1
@@ -1,3 +1,3 @@
1 # Docs
2
3 -[Install](install.md) · [Credentials](credentials.md) · [AppGallery](appgallery.md) · [Amazon](amazon.md) · [China compliance](china-compliance.md) · [New app on Google Play](google-play-new-app.md) · [Architecture](architecture.md)
3 +[Install](install.md) · [Credentials](credentials.md) · [AppGallery](appgallery.md) · [Amazon](amazon.md) · [Xiaomi GetApps](xiaomi.md) · [China compliance](china-compliance.md) · [New app on Google Play](google-play-new-app.md) · [Architecture](architecture.md)
docs/architecture.md
+4 -3
@@ -10,6 +10,7 @@ from the other:
10 | `smbcloud-ascapi-amazon` | Amazon Appstore App Submission API (Fire tablets, Fire TV): Login with Amazon client-credentials auth, the open edit, APK upload and replace (ETag), device targeting, validate; no commit, independent of `core` |
11 | `smbcloud-ascapi-appgallery` | Huawei AppGallery Connect Publishing API (Android): app info and listings, file and package upload, submit, phased release, release time, GMS flag, package list and status; Service Account auth (PS256 JWT), independent of `core` |
12 | `smbcloud-ascapi-msstore` | Microsoft Store submission API v1.0: listing text on an MSIX app's pending submission; Entra client-credentials auth, independent of `core` |
13 +| `smbcloud-ascapi-xiaomi` | Xiaomi GetApps developer interface: HMAC-SHA1 signed requests, the order query and the APK upload address; independent of `core` |
14 | `smbcloud-ascapi-admob` | Google AdMob Management API (v1beta): apps and ad units; user OAuth (installed-app PKCE flow, cached refresh token), independent of `core` |
15 | `smbcloud-ascapi-aso` | App Metadata: apps, app infos, versions, builds, pre-release versions, review submissions, bundle IDs, localizations, screenshots |
16 | `smbcloud-ascapi-pricing` | Pricing: app price schedules, and the per-territory prices joined with their price points and currencies |
@@ -20,8 +21,8 @@ from the other:
21 | `smbcloud-ascapi-mcp` | The MCP contract and stdio server |
22 | `smbcloud-ascapi-cli` | The `asc` binary: clap command tree, plus `--mcp` |
23
23 -`aso`, `play`, `appgallery`, `amazon`, `msstore`, `admob`, `pricing`, `iap`,
24 -`signing` and `reports` know nothing about each other, and none of them knows
24 +`aso`, `play`, `appgallery`, `amazon`, `msstore`, `xiaomi`, `admob`, `pricing`,
25 +`iap`, `signing` and `reports` know nothing about each other, and none of them knows
26 anything about the front ends.
27
28 `aso`, `pricing`, `iap`, `signing` and `reports` are the Apple-domain crates:
@@ -33,6 +34,6 @@ use smbcloud_ascapi_core::{ApiKey, Client};
34 use smbcloud_ascapi_aso::prelude::*; // or pricing::prelude, signing::prelude
35 ```
36
36 -The store backends `play`, `appgallery`, `amazon`, `msstore` and `admob` are
37 +The store backends `play`, `appgallery`, `amazon`, `msstore`, `xiaomi` and `admob` are
38 different: they authenticate their own way and have their own error envelopes,
39 so they do not depend on `core` and each defines its own client.
docs/xiaomi.md new
+61
@@ -0,0 +1,61 @@
1 +# Xiaomi GetApps
2 +
3 +`asc xiaomi` calls the GetApps developer interface on
4 +`global.developer.mi.com/third-api/…`. Each request is signed with HMAC-SHA1
5 +using the app's App Secret. Xiaomi documents two endpoints publicly: the
6 +order query and the APK upload address. The rest of the upload and the
7 +submission are documented on a private Xiaomi wiki, so the listing, the APK
8 +upload and the review submission still happen in the console.
9 +
10 +## Credentials
11 +
12 +The App ID and App Secret are per app: open the app in the console and click
13 +the eye icon next to them. The email, developer id and Xiaomi user id belong
14 +to the developer account, and GetApps checks that they all match. Put them in
15 +a dotenv file, pass it with `--xiaomi-env` or `XIAOMI_ENV_PATH`, or export
16 +the variables:
17 +
18 +```bash
19 +XIAOMI_APP_ID=...
20 +XIAOMI_APP_SECRET=...
21 +XIAOMI_PACKAGE=com.example.app
22 +XIAOMI_EMAIL=... # the developer account's email
23 +XIAOMI_DEVELOPER_ID=... # a number
24 +XIAOMI_USER_ID=... # the Xiaomi account id, a number
25 +```
26 +
27 +The App Secret is never printed, and `--dry-run` withholds the signature too.
28 +
29 +## Commands
30 +
31 +```bash
32 +asc xiaomi upload-url # credentials and signature check
33 +asc xiaomi orders --start 2026-11-01 --end 2026-11-19 # up to 30 days, UTC dates or Unix seconds
34 +asc xiaomi orders --start 2026-11-01 --end 2026-11-19 --pay-status 2,6 --regions ES,RO
35 +asc --dry-run xiaomi orders --start 2026-11-01 --end 2026-11-19 # print the signed request, send nothing
36 +```
37 +
38 +`upload-url` fetches the address and uploads nothing. Signed URLs in the answer
39 +are cut to scheme, host and path.
40 +
41 +`orders` only works once Xiaomi has allowlisted the account. Ask
42 +overseas-dev@xiaomi.com. Until then GetApps answers code 999 with "does not
43 +have /third-api/order/v1/query permission". The limit is one request a second.
44 +
45 +## Error codes
46 +
47 +| Code | Meaning |
48 +|---|---|
49 +| 999 | A header is missing or wrong, the ids don't belong together, or the account lacks permission for the endpoint |
50 +| 1001 | No App Secret found for the App ID |
51 +| 1002 | Signature mismatch. Xiaomi's docs spell the label both `Timestamp:` and `TimeStamp:`; `asc` signs `Timestamp:`, as both worked examples do |
52 +| 3001 | The timestamp is more than 30 minutes old: check the clock |
53 +| 3002 | Duplicate nonce |
54 +
55 +## Publishing without the API
56 +
57 +For an app that is also on Google Play, Xiaomi asks for a PSV build: the same
58 +package name, the same signing key as Play (Google's app signing key, not
59 +your upload key) and a higher versionCode than Play's. To get an APK signed
60 +with Google's key, upload the bundle to Play's internal testing track as a
61 +draft, then download the signed universal APK from the App bundle explorer.