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 admob: accounts, apps and ad units
AdMob accepts user OAuth only, so sign-in is a one-time browser flow with PKCE and a loopback redirect. The refresh token is cached at ~/.config/asc/admob-token.json with mode 0600. Commands: login, accounts, apps list, adunits list, adunits create (rewarded, with reward amount and item). create honors --dry-run and reads the units back to confirm. A 403 on create maps to a limited-access error that points at the console and `adunits list`. MCP gets the two read-only list tools. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Seto Elkahfi committed
Nov 9, 2026 at 21:10 UTC
75d9fccf760a9ea989851943704b3e3b7c23f15b
20 files changed
+1393
-4
.agents/AGENTS.md
+21
-1
@@ -165,7 +165,7 @@ cargo fmt --all -- --check
165
cargo clippy --workspace --all-targets --locked -- -D warnings
166
cargo test --workspace --locked
167
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --workspace --locked
168
-cargo check -p smbcloud-ascapi-core --locked # also -aso, -play, -msstore, -signing: each lower crate must build alone
168
+cargo check -p smbcloud-ascapi-core --locked # also -aso, -play, -admob, -msstore, -signing: each lower crate must build alone
169
```
170
171
Single test: `cargo test -p smbcloud-ascapi-aso build::tests::<name>`.
@@ -366,6 +366,26 @@ flags; send the release from Console. `products create` also needs an uploaded b
366
declares `com.android.vending.BILLING`. The full order is in
367
[`docs/google-play-new-app.md`](../docs/google-play-new-app.md).
368
369
+## AdMob (CLI)
370
+
371
+`crates/admob` is a sibling of `crates/play` and does not depend on `core`. AdMob takes user OAuth
372
+only: `auth.rs` runs the installed-app flow (PKCE, loopback redirect) and caches a refresh token at
373
+`~/.config/asc/admob-token.json` (0600). The client JSON comes from `--admob-oauth-client` or
374
+`ADMOB_OAUTH_CLIENT_JSON_PATH`. `Debug` impls redact secrets; keep it that way.
375
+
376
+```bash
377
+asc admob login
378
+asc admob accounts
379
+asc admob apps list
380
+asc admob adunits list [--app ca-app-pub-...~...]
381
+asc admob adunits create --app ... --name ... --format rewarded --reward-amount 50 --reward-item Semitones
382
+```
383
+
384
+`adunits create` (v1beta) is limited access and answers 403 without a grant; the client maps that to a
385
+clear error. `create` reads the units back to confirm. MCP exposes only `admob_apps_list` and
386
+`admob_adunits_list`. The SSV callback URL and GDPR messages are console-only. Setup and limits:
387
+[`docs/admob.md`](../docs/admob.md). Shared code: `crates/frontend/src/admob.rs`.
388
+
389
## Microsoft Store (CLI)
390
391
`crates/msstore` is a sibling of `crates/play` and does not depend on `core`.
Cargo.lock
+16
@@ -1803,6 +1803,20 @@ version = "1.16.1"
1803
source = "registry+https://github.com/rust-lang/crates.io-index"
1804
checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891"
1805
1806
+[[package]]
1807
+name = "smbcloud-ascapi-admob"
1808
+version = "0.3.0"
1809
+dependencies = [
1810
+ "base64 0.22.1",
1811
+ "rand 0.8.8",
1812
+ "reqwest",
1813
+ "serde",
1814
+ "serde_json",
1815
+ "sha2",
1816
+ "thiserror",
1817
+ "tokio",
1818
+]
1819
+
1820
[[package]]
1821
name = "smbcloud-ascapi-appgallery"
1822
version = "0.3.0"
@@ -1840,6 +1854,7 @@ dependencies = [
1854
"flate2",
1855
"serde",
1856
"serde_json",
1857
+ "smbcloud-ascapi-admob",
1858
"smbcloud-ascapi-appgallery",
1859
"smbcloud-ascapi-aso",
1860
"smbcloud-ascapi-core",
@@ -1874,6 +1889,7 @@ dependencies = [
1889
"serde",
1890
"serde_json",
1891
"sha2",
1892
+ "smbcloud-ascapi-admob",
1893
"smbcloud-ascapi-appgallery",
1894
"smbcloud-ascapi-aso",
1895
"smbcloud-ascapi-core",
Cargo.toml
+2
@@ -4,6 +4,7 @@ members = [
4
"crates/core",
5
"crates/aso",
6
"crates/play",
7
+ "crates/admob",
8
"crates/appgallery",
9
"crates/msstore",
10
"crates/signing",
@@ -26,6 +27,7 @@ repository = "https://github.com/smbcloudXYZ/smbcloud-ascapi"
27
smbcloud-ascapi-core = { version = "0.3.0", path = "crates/core" }
28
smbcloud-ascapi-aso = { version = "0.3.0", path = "crates/aso" }
29
smbcloud-ascapi-play = { version = "0.3.0", path = "crates/play" }
30
+smbcloud-ascapi-admob = { version = "0.3.0", path = "crates/admob" }
31
smbcloud-ascapi-appgallery = { version = "0.3.0", path = "crates/appgallery" }
32
smbcloud-ascapi-msstore = { version = "0.3.0", path = "crates/msstore" }
33
smbcloud-ascapi-signing = { version = "0.3.0", path = "crates/signing" }
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) · [Architecture](docs/architecture.md)
38
+[Install](docs/install.md) · [Credentials](docs/credentials.md) · [AppGallery](docs/appgallery.md) · [AdMob](docs/admob.md) · [Architecture](docs/architecture.md)
39
40
## Contributing
41
crates/admob/Cargo.toml
new
+22
@@ -0,0 +1,22 @@
1
+[package]
2
+name = "smbcloud-ascapi-admob"
3
+version.workspace = true
4
+edition.workspace = true
5
+authors.workspace = true
6
+license.workspace = true
7
+repository.workspace = true
8
+description = "AdMob API: list accounts, apps and ad units, and create rewarded ad units where Google has granted write access. Authenticated with a user OAuth refresh token."
9
+readme = "README.md"
10
+
11
+[lib]
12
+path = "src/lib.rs"
13
+
14
+[dependencies]
15
+base64 = { workspace = true }
16
+rand = { workspace = true }
17
+reqwest = { workspace = true, features = ["json", "rustls-tls-native-roots"] }
18
+serde = { workspace = true, features = ["derive"] }
19
+serde_json = { workspace = true }
20
+sha2 = "0.10"
21
+thiserror = { workspace = true }
22
+tokio = { workspace = true, features = ["sync", "time", "net", "io-util"] }
crates/admob/README.md
new
+9
@@ -0,0 +1,9 @@
1
+# smbcloud-ascapi-admob
2
+
3
+AdMob API client behind `asc admob`: accounts, apps, ad units, and rewarded
4
+ad unit creation. AdMob accepts user OAuth only (no service accounts), so
5
+sign-in is an installed-app flow with PKCE and a loopback redirect. The
6
+refresh token is cached at `~/.config/asc/admob-token.json` (mode 0600).
7
+
8
+See [`docs/admob.md`](../../docs/admob.md) for the OAuth client setup and the
9
+limited-access note on `adUnits.create`.
crates/admob/src/auth.rs
new
+501
@@ -0,0 +1,501 @@
1
+//! Installed-app OAuth for AdMob: PKCE, a loopback redirect, and a cached
2
+//! refresh token. Nothing here prints a token or a secret.
3
+
4
+use std::path::{Path, PathBuf};
5
+use std::time::{Duration, Instant};
6
+
7
+use base64::engine::general_purpose::URL_SAFE_NO_PAD;
8
+use base64::Engine;
9
+use rand::distributions::Alphanumeric;
10
+use rand::Rng;
11
+use serde::{Deserialize, Serialize};
12
+use sha2::{Digest, Sha256};
13
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
14
+use tokio::net::TcpListener;
15
+use tokio::sync::Mutex;
16
+
17
+use crate::error::{Error, Result};
18
+
19
+/// `admob.readonly` covers the lists; `admob.monetization` is what
20
+/// `adUnits.create` needs.
21
+pub const SCOPES: &str = "https://www.googleapis.com/auth/admob.readonly \
22
+ https://www.googleapis.com/auth/admob.monetization";
23
+const DEFAULT_AUTH_URI: &str = "https://accounts.google.com/o/oauth2/v2/auth";
24
+const DEFAULT_TOKEN_URI: &str = "https://oauth2.googleapis.com/token";
25
+const REFRESH_MARGIN: Duration = Duration::from_secs(60);
26
+const LOGIN_TIMEOUT: Duration = Duration::from_secs(300);
27
+
28
+/// A Desktop-app OAuth client, as downloaded from Google Cloud Console.
29
+#[derive(Clone)]
30
+pub struct OAuthClient {
31
+ pub client_id: String,
32
+ client_secret: String,
33
+ auth_uri: String,
34
+ token_uri: String,
35
+}
36
+
37
+// Hand-written so `{:?}` can never print the secret.
38
+impl std::fmt::Debug for OAuthClient {
39
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40
+ f.debug_struct("OAuthClient")
41
+ .field("client_id", &self.client_id)
42
+ .field("client_secret", &"<redacted>")
43
+ .finish()
44
+ }
45
+}
46
+
47
+#[derive(Deserialize)]
48
+struct ClientFile {
49
+ installed: Option<RawClient>,
50
+ web: Option<RawClient>,
51
+}
52
+
53
+#[derive(Deserialize)]
54
+struct RawClient {
55
+ client_id: String,
56
+ client_secret: String,
57
+ #[serde(default)]
58
+ auth_uri: Option<String>,
59
+ #[serde(default)]
60
+ token_uri: Option<String>,
61
+}
62
+
63
+impl OAuthClient {
64
+ pub fn from_json(json: &str) -> Result<Self> {
65
+ let file: ClientFile = serde_json::from_str(json).map_err(|_| Error::ClientInvalid)?;
66
+ let raw = file.installed.or(file.web).ok_or(Error::ClientInvalid)?;
67
+ if raw.client_id.is_empty() || raw.client_secret.is_empty() {
68
+ return Err(Error::ClientInvalid);
69
+ }
70
+ Ok(Self {
71
+ client_id: raw.client_id,
72
+ client_secret: raw.client_secret,
73
+ auth_uri: raw.auth_uri.unwrap_or_else(|| DEFAULT_AUTH_URI.to_string()),
74
+ token_uri: raw
75
+ .token_uri
76
+ .unwrap_or_else(|| DEFAULT_TOKEN_URI.to_string()),
77
+ })
78
+ }
79
+
80
+ pub fn from_json_file(path: impl AsRef<Path>) -> Result<Self> {
81
+ let path = path.as_ref();
82
+ let json = std::fs::read_to_string(path).map_err(|source| Error::ClientRead {
83
+ path: path.display().to_string(),
84
+ source,
85
+ })?;
86
+ Self::from_json(&json)
87
+ }
88
+}
89
+
90
+/// A PKCE verifier and its S256 challenge (RFC 7636).
91
+#[derive(Clone)]
92
+pub struct Pkce {
93
+ pub verifier: String,
94
+ pub challenge: String,
95
+}
96
+
97
+impl std::fmt::Debug for Pkce {
98
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99
+ f.debug_struct("Pkce")
100
+ .field("verifier", &"<redacted>")
101
+ .field("challenge", &self.challenge)
102
+ .finish()
103
+ }
104
+}
105
+
106
+impl Pkce {
107
+ pub fn generate() -> Self {
108
+ Self::from_verifier(random_string(64))
109
+ }
110
+
111
+ pub fn from_verifier(verifier: String) -> Self {
112
+ let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()));
113
+ Self {
114
+ verifier,
115
+ challenge,
116
+ }
117
+ }
118
+}
119
+
120
+fn random_string(len: usize) -> String {
121
+ rand::thread_rng()
122
+ .sample_iter(Alphanumeric)
123
+ .take(len)
124
+ .map(char::from)
125
+ .collect()
126
+}
127
+
128
+/// What is cached on disk: the refresh token, nothing else.
129
+#[derive(Clone, Serialize, Deserialize)]
130
+pub struct StoredToken {
131
+ pub refresh_token: String,
132
+}
133
+
134
+impl std::fmt::Debug for StoredToken {
135
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
136
+ f.debug_struct("StoredToken")
137
+ .field("refresh_token", &"<redacted>")
138
+ .finish()
139
+ }
140
+}
141
+
142
+impl StoredToken {
143
+ /// `~/.config/asc/admob-token.json`.
144
+ pub fn default_path() -> PathBuf {
145
+ let home = std::env::var_os("HOME")
146
+ .map(PathBuf::from)
147
+ .unwrap_or_default();
148
+ home.join(".config").join("asc").join("admob-token.json")
149
+ }
150
+
151
+ pub fn save(&self, path: &Path) -> Result<()> {
152
+ let io = |source| Error::TokenCache {
153
+ path: path.display().to_string(),
154
+ source,
155
+ };
156
+ if let Some(dir) = path.parent() {
157
+ std::fs::create_dir_all(dir).map_err(io)?;
158
+ }
159
+ let json = serde_json::to_vec_pretty(self)?;
160
+ write_private(path, &json).map_err(io)
161
+ }
162
+
163
+ pub fn load(path: &Path) -> Result<Self> {
164
+ let json = std::fs::read_to_string(path).map_err(|source| {
165
+ if source.kind() == std::io::ErrorKind::NotFound {
166
+ Error::NotSignedIn {
167
+ path: path.display().to_string(),
168
+ }
169
+ } else {
170
+ Error::TokenCache {
171
+ path: path.display().to_string(),
172
+ source,
173
+ }
174
+ }
175
+ })?;
176
+ serde_json::from_str(&json).map_err(|_| Error::TokenCacheInvalid {
177
+ path: path.display().to_string(),
178
+ })
179
+ }
180
+}
181
+
182
+#[cfg(unix)]
183
+fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
184
+ use std::io::Write;
185
+ use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
186
+ let mut file = std::fs::OpenOptions::new()
187
+ .write(true)
188
+ .create(true)
189
+ .truncate(true)
190
+ .mode(0o600)
191
+ .open(path)?;
192
+ // `mode` only applies on creation; tighten a pre-existing file too.
193
+ file.set_permissions(std::fs::Permissions::from_mode(0o600))?;
194
+ file.write_all(bytes)
195
+}
196
+
197
+#[cfg(not(unix))]
198
+fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
199
+ std::fs::write(path, bytes)
200
+}
201
+
202
+#[derive(Deserialize)]
203
+struct TokenResponse {
204
+ access_token: String,
205
+ #[serde(default)]
206
+ expires_in: Option<u64>,
207
+ #[serde(default)]
208
+ refresh_token: Option<String>,
209
+}
210
+
211
+/// The consent URL for one login attempt.
212
+pub fn authorization_url(
213
+ client: &OAuthClient,
214
+ redirect_uri: &str,
215
+ pkce: &Pkce,
216
+ state: &str,
217
+) -> String {
218
+ reqwest::Url::parse_with_params(
219
+ &client.auth_uri,
220
+ &[
221
+ ("client_id", client.client_id.as_str()),
222
+ ("redirect_uri", redirect_uri),
223
+ ("response_type", "code"),
224
+ ("scope", SCOPES),
225
+ ("code_challenge", pkce.challenge.as_str()),
226
+ ("code_challenge_method", "S256"),
227
+ ("state", state),
228
+ // Without these Google may omit the refresh token.
229
+ ("access_type", "offline"),
230
+ ("prompt", "consent"),
231
+ ],
232
+ )
233
+ .map(|url| url.to_string())
234
+ .unwrap_or_default()
235
+}
236
+
237
+/// Pull the authorization code out of the loopback request line
238
+/// (`GET /?code=…&state=… HTTP/1.1`), checking `state`.
239
+pub fn parse_callback(request_line: &str, expected_state: &str) -> Result<String> {
240
+ let target = request_line
241
+ .split_whitespace()
242
+ .nth(1)
243
+ .ok_or_else(|| Error::Authorization("malformed redirect request".to_string()))?;
244
+ let url = reqwest::Url::parse(&format!("http://127.0.0.1{target}"))
245
+ .map_err(|_| Error::Authorization("malformed redirect request".to_string()))?;
246
+ let mut code = None;
247
+ let mut state = None;
248
+ let mut error = None;
249
+ for (key, value) in url.query_pairs() {
250
+ match key.as_ref() {
251
+ "code" => code = Some(value.into_owned()),
252
+ "state" => state = Some(value.into_owned()),
253
+ "error" => error = Some(value.into_owned()),
254
+ _ => {}
255
+ }
256
+ }
257
+ if let Some(error) = error {
258
+ return Err(Error::Authorization(format!("Google returned {error}")));
259
+ }
260
+ if state.as_deref() != Some(expected_state) {
261
+ return Err(Error::Authorization(
262
+ "the redirect's state did not match; start the login again".to_string(),
263
+ ));
264
+ }
265
+ code.ok_or_else(|| Error::Authorization("the redirect carried no code".to_string()))
266
+}
267
+
268
+fn open_browser(url: &str) {
269
+ let program = if cfg!(target_os = "macos") {
270
+ "open"
271
+ } else if cfg!(target_os = "windows") {
272
+ "explorer"
273
+ } else {
274
+ "xdg-open"
275
+ };
276
+ let _ = std::process::Command::new(program).arg(url).spawn();
277
+}
278
+
279
+/// Run the browser sign-in once and cache the refresh token at `token_path`.
280
+pub async fn login(client: &OAuthClient, token_path: &Path) -> Result<()> {
281
+ let http = reqwest::Client::new();
282
+ let listener = TcpListener::bind("127.0.0.1:0")
283
+ .await
284
+ .map_err(|e| Error::Authorization(format!("cannot open a loopback port: {e}")))?;
285
+ let port = listener
286
+ .local_addr()
287
+ .map_err(|e| Error::Authorization(e.to_string()))?
288
+ .port();
289
+ let redirect_uri = format!("http://127.0.0.1:{port}");
290
+ let pkce = Pkce::generate();
291
+ let state = random_string(32);
292
+ let url = authorization_url(client, &redirect_uri, &pkce, &state);
293
+
294
+ eprintln!("Opening the browser to sign in to AdMob. If it does not open, visit:\n{url}");
295
+ open_browser(&url);
296
+
297
+ let code = tokio::time::timeout(LOGIN_TIMEOUT, async {
298
+ let (mut socket, _) = listener
299
+ .accept()
300
+ .await
301
+ .map_err(|e| Error::Authorization(e.to_string()))?;
302
+ let mut buf = vec![0u8; 8192];
303
+ let n = socket
304
+ .read(&mut buf)
305
+ .await
306
+ .map_err(|e| Error::Authorization(e.to_string()))?;
307
+ let request = String::from_utf8_lossy(&buf[..n]).into_owned();
308
+ let line = request.lines().next().unwrap_or_default();
309
+ let parsed = parse_callback(line, &state);
310
+ let body = if parsed.is_ok() {
311
+ "Signed in. You can close this tab and return to the terminal."
312
+ } else {
313
+ "Sign-in failed. Return to the terminal for details."
314
+ };
315
+ let reply = format!(
316
+ "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
317
+ body.len()
318
+ );
319
+ let _ = socket.write_all(reply.as_bytes()).await;
320
+ parsed
321
+ })
322
+ .await
323
+ .map_err(|_| Error::Authorization("timed out waiting for the browser sign-in".to_string()))??;
324
+
325
+ let response = http
326
+ .post(&client.token_uri)
327
+ .form(&[
328
+ ("grant_type", "authorization_code"),
329
+ ("code", code.as_str()),
330
+ ("redirect_uri", redirect_uri.as_str()),
331
+ ("client_id", client.client_id.as_str()),
332
+ ("client_secret", client.client_secret.as_str()),
333
+ ("code_verifier", pkce.verifier.as_str()),
334
+ ])
335
+ .send()
336
+ .await?;
337
+ let status = response.status();
338
+ if !status.is_success() {
339
+ return Err(Error::Token {
340
+ status: status.as_u16(),
341
+ detail: response.text().await.unwrap_or_default(),
342
+ });
343
+ }
344
+ let body: TokenResponse = response.json().await?;
345
+ let refresh_token = body.refresh_token.ok_or_else(|| {
346
+ Error::Authorization(
347
+ "Google returned no refresh token; revoke the app's access in your Google account and log in again"
348
+ .to_string(),
349
+ )
350
+ })?;
351
+ StoredToken { refresh_token }.save(token_path)
352
+}
353
+
354
+/// Turns the cached refresh token into short-lived access tokens.
355
+pub(crate) struct Authenticator {
356
+ client: OAuthClient,
357
+ token_path: PathBuf,
358
+ cached: Mutex<Option<(String, Instant)>>,
359
+}
360
+
361
+impl Authenticator {
362
+ pub(crate) fn new(client: OAuthClient, token_path: PathBuf) -> Self {
363
+ Self {
364
+ client,
365
+ token_path,
366
+ cached: Mutex::new(None),
367
+ }
368
+ }
369
+
370
+ pub(crate) async fn access_token(&self, http: &reqwest::Client) -> Result<String> {
371
+ let mut cached = self.cached.lock().await;
372
+ if let Some((token, expires)) = cached.as_ref() {
373
+ if Instant::now() < *expires {
374
+ return Ok(token.clone());
375
+ }
376
+ }
377
+ let stored = StoredToken::load(&self.token_path)?;
378
+ let response = http
379
+ .post(&self.client.token_uri)
380
+ .form(&[
381
+ ("grant_type", "refresh_token"),
382
+ ("refresh_token", stored.refresh_token.as_str()),
383
+ ("client_id", self.client.client_id.as_str()),
384
+ ("client_secret", self.client.client_secret.as_str()),
385
+ ])
386
+ .send()
387
+ .await?;
388
+ let status = response.status();
389
+ if !status.is_success() {
390
+ return Err(Error::Token {
391
+ status: status.as_u16(),
392
+ detail: response.text().await.unwrap_or_default(),
393
+ });
394
+ }
395
+ let body: TokenResponse = response.json().await?;
396
+ let lifetime = Duration::from_secs(body.expires_in.unwrap_or(3600));
397
+ let expires = Instant::now() + lifetime.saturating_sub(REFRESH_MARGIN);
398
+ *cached = Some((body.access_token.clone(), expires));
399
+ Ok(body.access_token)
400
+ }
401
+}
402
+
403
+#[cfg(test)]
404
+mod tests {
405
+ use super::*;
406
+
407
+ const CLIENT_JSON: &str =
408
+ r#"{"installed":{"client_id":"cid.apps.googleusercontent.com","client_secret":"SECRET"}}"#;
409
+
410
+ #[test]
411
+ fn pkce_challenge_matches_the_rfc_7636_vector() {
412
+ let pkce = Pkce::from_verifier("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk".to_string());
413
+ assert_eq!(
414
+ pkce.challenge,
415
+ "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
416
+ );
417
+ }
418
+
419
+ #[test]
420
+ fn generated_pkce_pairs_are_unique_and_in_range() {
421
+ let a = Pkce::generate();
422
+ let b = Pkce::generate();
423
+ assert_ne!(a.verifier, b.verifier);
424
+ assert!((43..=128).contains(&a.verifier.len()));
425
+ assert_eq!(
426
+ a.challenge,
427
+ Pkce::from_verifier(a.verifier.clone()).challenge
428
+ );
429
+ }
430
+
431
+ #[test]
432
+ fn token_cache_round_trips_with_owner_only_permissions() {
433
+ let dir = std::env::temp_dir().join(format!("asc-admob-test-{}", random_string(8)));
434
+ let path = dir.join("nested").join("admob-token.json");
435
+ StoredToken {
436
+ refresh_token: "r-1".to_string(),
437
+ }
438
+ .save(&path)
439
+ .unwrap();
440
+ assert_eq!(StoredToken::load(&path).unwrap().refresh_token, "r-1");
441
+ #[cfg(unix)]
442
+ {
443
+ use std::os::unix::fs::PermissionsExt;
444
+ let mode = std::fs::metadata(&path).unwrap().permissions().mode();
445
+ assert_eq!(mode & 0o777, 0o600);
446
+ }
447
+ std::fs::remove_dir_all(&dir).unwrap();
448
+ }
449
+
450
+ #[test]
451
+ fn a_missing_cache_says_to_log_in() {
452
+ let err = StoredToken::load(Path::new("/nonexistent/admob-token.json")).unwrap_err();
453
+ assert!(err.to_string().contains("asc admob login"));
454
+ }
455
+
456
+ #[test]
457
+ fn debug_output_redacts_secrets() {
458
+ let client = OAuthClient::from_json(CLIENT_JSON).unwrap();
459
+ assert!(!format!("{client:?}").contains("SECRET"));
460
+ let token = StoredToken {
461
+ refresh_token: "REFRESH".to_string(),
462
+ };
463
+ assert!(!format!("{token:?}").contains("REFRESH"));
464
+ let pkce = Pkce::from_verifier("VERIFIER".to_string());
465
+ assert!(!format!("{pkce:?}").contains("VERIFIER"));
466
+ }
467
+
468
+ #[test]
469
+ fn an_invalid_client_file_is_rejected_without_echoing_it() {
470
+ let err = OAuthClient::from_json(r#"{"installed":{"client_id":"a","client_secret":""}}"#)
471
+ .unwrap_err()
472
+ .to_string();
473
+ assert!(!err.contains("\"a\""));
474
+ assert!(OAuthClient::from_json("nope").is_err());
475
+ assert!(OAuthClient::from_json("{}").is_err());
476
+ }
477
+
478
+ #[test]
479
+ fn authorization_url_carries_pkce_scopes_and_offline_access() {
480
+ let client = OAuthClient::from_json(CLIENT_JSON).unwrap();
481
+ let pkce = Pkce::from_verifier("v".repeat(43));
482
+ let url = authorization_url(&client, "http://127.0.0.1:5000", &pkce, "st");
483
+ assert!(url.starts_with("https://accounts.google.com/o/oauth2/v2/auth?"));
484
+ assert!(url.contains("code_challenge_method=S256"));
485
+ assert!(url.contains("access_type=offline"));
486
+ assert!(url.contains("admob.monetization"));
487
+ assert!(url.contains("state=st"));
488
+ assert!(!url.contains("SECRET"));
489
+ }
490
+
491
+ #[test]
492
+ fn callback_yields_the_code_and_rejects_a_wrong_state() {
493
+ assert_eq!(
494
+ parse_callback("GET /?code=abc%2F1&state=st HTTP/1.1", "st").unwrap(),
495
+ "abc/1"
496
+ );
497
+ assert!(parse_callback("GET /?code=abc&state=other HTTP/1.1", "st").is_err());
498
+ assert!(parse_callback("GET /?error=access_denied&state=st HTTP/1.1", "st").is_err());
499
+ assert!(parse_callback("garbage", "st").is_err());
500
+ }
501
+}
crates/admob/src/client.rs
new
+169
@@ -0,0 +1,169 @@
1
+use std::path::PathBuf;
2
+
3
+use reqwest::Method;
4
+use serde::de::DeserializeOwned;
5
+use serde::{Deserialize, Serialize};
6
+
7
+use crate::auth::{Authenticator, OAuthClient, StoredToken};
8
+use crate::error::{Error, Result};
9
+use crate::types::{Account, AdUnit, App, CreateAdUnit};
10
+
11
+const API_ROOT: &str = "https://admob.googleapis.com";
12
+
13
+/// `accounts/pub-123` from either `pub-123` or `accounts/pub-123`.
14
+pub(crate) fn account_name(account: &str) -> String {
15
+ if account.starts_with("accounts/") {
16
+ account.to_string()
17
+ } else {
18
+ format!("accounts/{account}")
19
+ }
20
+}
21
+
22
+/// A 403 on create means limited access has not been granted; every other
23
+/// failure stays a plain API error.
24
+pub(crate) fn map_create_error(error: Error) -> Error {
25
+ match error {
26
+ Error::Api {
27
+ status: 403,
28
+ detail,
29
+ } => Error::CreateNotPermitted { detail },
30
+ other => other,
31
+ }
32
+}
33
+
34
+#[derive(Deserialize)]
35
+#[serde(rename_all = "camelCase")]
36
+struct Page<T> {
37
+ #[serde(default = "Vec::new")]
38
+ items: Vec<T>,
39
+ #[serde(default)]
40
+ next_page_token: Option<String>,
41
+}
42
+
43
+pub struct AdmobClient {
44
+ http: reqwest::Client,
45
+ auth: Authenticator,
46
+ root: String,
47
+}
48
+
49
+impl AdmobClient {
50
+ /// `token_path` defaults to `~/.config/asc/admob-token.json`.
51
+ pub fn new(oauth: OAuthClient, token_path: Option<PathBuf>) -> Self {
52
+ Self {
53
+ http: reqwest::Client::new(),
54
+ auth: Authenticator::new(oauth, token_path.unwrap_or_else(StoredToken::default_path)),
55
+ root: API_ROOT.to_string(),
56
+ }
57
+ }
58
+
59
+ async fn request<T: DeserializeOwned>(
60
+ &self,
61
+ method: Method,
62
+ path_and_query: &str,
63
+ body: Option<&impl Serialize>,
64
+ ) -> Result<T> {
65
+ let token = self.auth.access_token(&self.http).await?;
66
+ let mut request = self
67
+ .http
68
+ .request(method, format!("{}{path_and_query}", self.root))
69
+ .bearer_auth(token);
70
+ if let Some(body) = body {
71
+ request = request.json(body);
72
+ }
73
+ let response = request.send().await?;
74
+ let status = response.status();
75
+ if status.is_success() {
76
+ Ok(response.json().await?)
77
+ } else {
78
+ Err(Error::Api {
79
+ status: status.as_u16(),
80
+ detail: response.text().await.unwrap_or_default(),
81
+ })
82
+ }
83
+ }
84
+
85
+ /// Follow `nextPageToken` until the list ends. `key` is the response
86
+ /// field holding the items.
87
+ async fn list_all<T: DeserializeOwned>(&self, path: &str, key: &str) -> Result<Vec<T>> {
88
+ let mut out = Vec::new();
89
+ let mut token: Option<String> = None;
90
+ loop {
91
+ let mut url = reqwest::Url::parse("https://x.invalid").expect("static url");
92
+ url.set_path(path);
93
+ if let Some(t) = &token {
94
+ url.query_pairs_mut().append_pair("pageToken", t);
95
+ }
96
+ let target = match url.query() {
97
+ Some(q) => format!("{}?{q}", url.path()),
98
+ None => url.path().to_string(),
99
+ };
100
+ let value: serde_json::Value = self.request(Method::GET, &target, None::<&()>).await?;
101
+ let mut shaped = serde_json::Map::new();
102
+ shaped.insert("items".into(), value.get(key).cloned().unwrap_or_default());
103
+ if let Some(next) = value.get("nextPageToken") {
104
+ shaped.insert("nextPageToken".into(), next.clone());
105
+ }
106
+ let page: Page<T> = serde_json::from_value(serde_json::Value::Object(shaped))?;
107
+ out.extend(page.items);
108
+ match page.next_page_token {
109
+ Some(next) if !next.is_empty() => token = Some(next),
110
+ _ => return Ok(out),
111
+ }
112
+ }
113
+ }
114
+
115
+ pub async fn list_accounts(&self) -> Result<Vec<Account>> {
116
+ self.list_all("/v1/accounts", "account").await
117
+ }
118
+
119
+ pub async fn list_apps(&self, account: &str) -> Result<Vec<App>> {
120
+ let path = format!("/v1/{}/apps", account_name(account));
121
+ self.list_all(&path, "apps").await
122
+ }
123
+
124
+ pub async fn list_ad_units(&self, account: &str) -> Result<Vec<AdUnit>> {
125
+ let path = format!("/v1/{}/adUnits", account_name(account));
126
+ self.list_all(&path, "adUnits").await
127
+ }
128
+
129
+ /// `accounts.adUnits.create` (v1beta). Limited access: see
130
+ /// [`Error::CreateNotPermitted`].
131
+ pub async fn create_ad_unit(&self, account: &str, body: &CreateAdUnit) -> Result<AdUnit> {
132
+ let path = format!("/v1beta/{}/adUnits", account_name(account));
133
+ self.request(Method::POST, &path, Some(body))
134
+ .await
135
+ .map_err(map_create_error)
136
+ }
137
+}
138
+
139
+#[cfg(test)]
140
+mod tests {
141
+ use super::*;
142
+
143
+ #[test]
144
+ fn a_403_on_create_maps_to_the_limited_access_error() {
145
+ let mapped = map_create_error(Error::Api {
146
+ status: 403,
147
+ detail: "denied".to_string(),
148
+ });
149
+ let text = mapped.to_string();
150
+ assert!(matches!(mapped, Error::CreateNotPermitted { .. }));
151
+ assert!(text.contains("limited access"));
152
+ assert!(text.contains("asc admob adunits list"));
153
+ }
154
+
155
+ #[test]
156
+ fn other_create_failures_pass_through() {
157
+ let mapped = map_create_error(Error::Api {
158
+ status: 400,
159
+ detail: "bad".to_string(),
160
+ });
161
+ assert!(matches!(mapped, Error::Api { status: 400, .. }));
162
+ }
163
+
164
+ #[test]
165
+ fn account_names_accept_both_forms() {
166
+ assert_eq!(account_name("pub-1"), "accounts/pub-1");
167
+ assert_eq!(account_name("accounts/pub-1"), "accounts/pub-1");
168
+ }
169
+}
crates/admob/src/error.rs
new
+53
@@ -0,0 +1,53 @@
1
+use thiserror::Error;
2
+
3
+#[derive(Debug, Error)]
4
+pub enum Error {
5
+ #[error("failed to read the OAuth client file {path}: {source}")]
6
+ ClientRead {
7
+ path: String,
8
+ #[source]
9
+ source: std::io::Error,
10
+ },
11
+
12
+ /// Deliberately carries no part of the file: a parse error could
13
+ /// otherwise quote the client secret.
14
+ #[error("the OAuth client JSON is not valid or lacks client_id/client_secret (use a Desktop app client)")]
15
+ ClientInvalid,
16
+
17
+ #[error("no cached AdMob sign-in at {path}: run `asc admob login` first")]
18
+ NotSignedIn { path: String },
19
+
20
+ #[error("failed to read or write the token cache {path}: {source}")]
21
+ TokenCache {
22
+ path: String,
23
+ #[source]
24
+ source: std::io::Error,
25
+ },
26
+
27
+ #[error("the token cache {path} is not valid JSON; delete it and run `asc admob login`")]
28
+ TokenCacheInvalid { path: String },
29
+
30
+ #[error("sign-in failed: {0}")]
31
+ Authorization(String),
32
+
33
+ #[error("http request failed: {0}")]
34
+ Http(#[from] reqwest::Error),
35
+
36
+ #[error("failed to decode JSON response: {0}")]
37
+ Json(#[from] serde_json::Error),
38
+
39
+ #[error("Google OAuth token exchange returned {status}: {detail}")]
40
+ Token { status: u16, detail: String },
41
+
42
+ #[error("AdMob API returned {status}: {detail}")]
43
+ Api { status: u16, detail: String },
44
+
45
+ #[error(
46
+ "AdMob refused to create the ad unit (403). adUnits.create is limited access: Google must \
47
+ grant it to your AdMob account. Create the unit in the console instead, then run \
48
+ `asc admob adunits list` to read its ID. API detail: {detail}"
49
+ )]
50
+ CreateNotPermitted { detail: String },
51
+}
52
+
53
+pub type Result<T> = std::result::Result<T, Error>;
crates/admob/src/lib.rs
new
+18
@@ -0,0 +1,18 @@
1
+//! AdMob API: accounts, apps, ad units, and rewarded ad unit creation.
2
+//!
3
+//! AdMob takes user OAuth only. [`auth::login`] runs the installed-app flow
4
+//! once (browser, loopback redirect, PKCE) and caches a refresh token;
5
+//! [`AdmobClient`] then refreshes access tokens silently. Creating an ad unit
6
+//! (`accounts.adUnits.create`, v1beta) is limited access and answers 403
7
+//! without a grant from Google; that case maps to
8
+//! [`Error::CreateNotPermitted`].
9
+
10
+pub mod auth;
11
+pub mod client;
12
+pub mod error;
13
+pub mod types;
14
+
15
+pub use auth::{OAuthClient, Pkce, StoredToken};
16
+pub use client::AdmobClient;
17
+pub use error::{Error, Result};
18
+pub use types::{Account, AdFormat, AdUnit, App, CreateAdUnit, RewardSettings};
crates/admob/src/types.rs
new
+129
@@ -0,0 +1,129 @@
1
+use serde::{Deserialize, Serialize};
2
+
3
+#[derive(Debug, Clone, Serialize, Deserialize)]
4
+#[serde(rename_all = "camelCase")]
5
+pub struct Account {
6
+ pub name: String,
7
+ #[serde(default)]
8
+ pub publisher_id: Option<String>,
9
+ #[serde(default)]
10
+ pub reporting_time_zone: Option<String>,
11
+ #[serde(default)]
12
+ pub currency_code: Option<String>,
13
+}
14
+
15
+#[derive(Debug, Clone, Serialize, Deserialize)]
16
+#[serde(rename_all = "camelCase")]
17
+pub struct App {
18
+ pub name: String,
19
+ #[serde(default)]
20
+ pub app_id: Option<String>,
21
+ #[serde(default)]
22
+ pub platform: Option<String>,
23
+ #[serde(default)]
24
+ pub manual_app_info: Option<serde_json::Value>,
25
+ #[serde(default)]
26
+ pub linked_app_info: Option<serde_json::Value>,
27
+}
28
+
29
+#[derive(Debug, Clone, Serialize, Deserialize)]
30
+#[serde(rename_all = "camelCase")]
31
+pub struct AdUnit {
32
+ pub name: String,
33
+ #[serde(default)]
34
+ pub ad_unit_id: Option<String>,
35
+ #[serde(default)]
36
+ pub app_id: Option<String>,
37
+ #[serde(default)]
38
+ pub display_name: Option<String>,
39
+ #[serde(default)]
40
+ pub ad_format: Option<String>,
41
+ #[serde(default)]
42
+ pub ad_types: Vec<String>,
43
+ #[serde(default)]
44
+ pub reward_settings: Option<serde_json::Value>,
45
+}
46
+
47
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48
+pub enum AdFormat {
49
+ Rewarded,
50
+}
51
+
52
+impl AdFormat {
53
+ pub fn api_name(self) -> &'static str {
54
+ match self {
55
+ AdFormat::Rewarded => "REWARDED",
56
+ }
57
+ }
58
+
59
+ pub fn parse(value: &str) -> Result<Self, String> {
60
+ match value.to_ascii_lowercase().as_str() {
61
+ "rewarded" => Ok(AdFormat::Rewarded),
62
+ other => Err(format!(
63
+ "unsupported ad format {other:?}; only rewarded is supported"
64
+ )),
65
+ }
66
+ }
67
+}
68
+
69
+/// `unitAmount` is an int64, which proto3 JSON writes as a string.
70
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
71
+#[serde(rename_all = "camelCase")]
72
+pub struct RewardSettings {
73
+ pub unit_amount: String,
74
+ pub unit_type: String,
75
+}
76
+
77
+/// Body of `accounts.adUnits.create` (v1beta).
78
+#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
79
+#[serde(rename_all = "camelCase")]
80
+pub struct CreateAdUnit {
81
+ pub display_name: String,
82
+ pub app_id: String,
83
+ pub ad_format: String,
84
+ pub reward_settings: RewardSettings,
85
+}
86
+
87
+impl CreateAdUnit {
88
+ pub fn rewarded(
89
+ app_id: &str,
90
+ display_name: &str,
91
+ reward_amount: u64,
92
+ reward_item: &str,
93
+ ) -> Self {
94
+ Self {
95
+ display_name: display_name.to_string(),
96
+ app_id: app_id.to_string(),
97
+ ad_format: AdFormat::Rewarded.api_name().to_string(),
98
+ reward_settings: RewardSettings {
99
+ unit_amount: reward_amount.to_string(),
100
+ unit_type: reward_item.to_string(),
101
+ },
102
+ }
103
+ }
104
+}
105
+
106
+#[cfg(test)]
107
+mod tests {
108
+ use super::*;
109
+
110
+ #[test]
111
+ fn create_body_serializes_in_camel_case_with_a_string_amount() {
112
+ let body = CreateAdUnit::rewarded("ca-app-pub-1~2", "Karaoke rewarded", 50, "Semitones");
113
+ assert_eq!(
114
+ serde_json::to_value(&body).unwrap(),
115
+ serde_json::json!({
116
+ "displayName": "Karaoke rewarded",
117
+ "appId": "ca-app-pub-1~2",
118
+ "adFormat": "REWARDED",
119
+ "rewardSettings": {"unitAmount": "50", "unitType": "Semitones"}
120
+ })
121
+ );
122
+ }
123
+
124
+ #[test]
125
+ fn only_rewarded_parses() {
126
+ assert_eq!(AdFormat::parse("Rewarded"), Ok(AdFormat::Rewarded));
127
+ assert!(AdFormat::parse("banner").is_err());
128
+ }
129
+}
crates/cli/Cargo.toml
+1
@@ -20,6 +20,7 @@ csv = { workspace = true }
20
flate2 = { workspace = true }
21
serde = { workspace = true }
22
serde_json = { workspace = true }
23
+smbcloud-ascapi-admob = { workspace = true }
24
smbcloud-ascapi-aso = { workspace = true }
25
smbcloud-ascapi-core = { workspace = true }
26
smbcloud-ascapi-appgallery = { workspace = true }
crates/cli/src/main.rs
+147
-1
@@ -96,6 +96,58 @@ struct Cli {
96
command: Option<Command>,
97
}
98
99
+#[derive(Subcommand)]
100
+enum AdmobCommand {
101
+ /// Sign in with a browser once and cache the refresh token at
102
+ /// ~/.config/asc/admob-token.json.
103
+ Login,
104
+ /// AdMob accounts the signed-in Google user can see.
105
+ Accounts,
106
+ /// Apps in the account.
107
+ Apps {
108
+ #[command(subcommand)]
109
+ command: AdmobAppsCommand,
110
+ },
111
+ /// Ad units: list, or create a rewarded unit (limited access).
112
+ Adunits {
113
+ #[command(subcommand)]
114
+ command: AdmobAdunitsCommand,
115
+ },
116
+}
117
+
118
+#[derive(Subcommand)]
119
+enum AdmobAppsCommand {
120
+ /// List the account's apps with their `ca-app-pub-…~…` app IDs.
121
+ List,
122
+}
123
+
124
+#[derive(Subcommand)]
125
+enum AdmobAdunitsCommand {
126
+ /// List ad units, optionally for one app.
127
+ List {
128
+ /// Only units of this app ID (`ca-app-pub-…~…`).
129
+ #[arg(long)]
130
+ app: Option<String>,
131
+ },
132
+ /// Create a rewarded ad unit. adUnits.create is limited access: without
133
+ /// a grant from Google it answers 403, and the unit has to be created in
134
+ /// the AdMob console. Honors --dry-run.
135
+ Create {
136
+ /// App ID (`ca-app-pub-…~…`), from `asc admob apps list`.
137
+ #[arg(long)]
138
+ app: String,
139
+ #[arg(long)]
140
+ name: String,
141
+ /// Only `rewarded` is supported.
142
+ #[arg(long, default_value = "rewarded")]
143
+ format: String,
144
+ #[arg(long)]
145
+ reward_amount: u64,
146
+ #[arg(long)]
147
+ reward_item: String,
148
+ },
149
+}
150
+
151
#[derive(Subcommand)]
152
enum PlayDetailsCommand {
153
/// Contact website, email, phone and default language.
@@ -887,6 +939,19 @@ enum Command {
939
#[command(subcommand)]
940
command: AppGalleryCommand,
941
},
942
+ /// AdMob accounts, apps and ad units. Uses a Google user OAuth sign-in
943
+ /// (AdMob has no service accounts), not the App Store Connect key.
944
+ Admob {
945
+ /// Path to a Desktop-app OAuth client JSON. Falls back to
946
+ /// `ADMOB_OAUTH_CLIENT_JSON_PATH`.
947
+ #[arg(long, global = true)]
948
+ admob_oauth_client: Option<PathBuf>,
949
+ /// AdMob account (`pub-…`). Defaults to the only account the user has.
950
+ #[arg(long, global = true)]
951
+ account: Option<String>,
952
+ #[command(subcommand)]
953
+ command: AdmobCommand,
954
+ },
955
/// Google Play store listings: text, images, and release notes. Uses a
956
/// Play service account, not the App Store Connect key.
957
Play {
@@ -1357,6 +1422,69 @@ async fn run_msstore(
1422
}
1423
}
1424
1425
+async fn run_admob(
1426
+ oauth_client: Option<&std::path::Path>,
1427
+ account: Option<&str>,
1428
+ command: AdmobCommand,
1429
+ dry_run: bool,
1430
+) -> Result<()> {
1431
+ use smbcloud_ascapi_frontend::admob;
1432
+ let fail = |e: String| anyhow::anyhow!(e);
1433
+ // Sign-in and the dry run need no API call, so no cached token either.
1434
+ if let AdmobCommand::Login = command {
1435
+ println!("{}", admob::login(oauth_client).await.map_err(fail)?);
1436
+ return Ok(());
1437
+ }
1438
+ if let AdmobCommand::Adunits {
1439
+ command:
1440
+ AdmobAdunitsCommand::Create {
1441
+ app,
1442
+ name,
1443
+ format,
1444
+ reward_amount,
1445
+ reward_item,
1446
+ },
1447
+ } = &command
1448
+ {
1449
+ let body =
1450
+ admob::plan_create(app, name, format, *reward_amount, reward_item).map_err(fail)?;
1451
+ if dry_run {
1452
+ println!("# dry run: nothing was sent; body that would be POSTed to adUnits.create:");
1453
+ return print_json(&body);
1454
+ }
1455
+ }
1456
+ let client = admob::admob_client(oauth_client).map_err(fail)?;
1457
+ match command {
1458
+ AdmobCommand::Login => unreachable!("handled above"),
1459
+ AdmobCommand::Accounts => print_json(&admob::list_accounts(&client).await.map_err(fail)?),
1460
+ AdmobCommand::Apps {
1461
+ command: AdmobAppsCommand::List,
1462
+ } => print_json(&admob::list_apps(&client, account).await.map_err(fail)?),
1463
+ AdmobCommand::Adunits { command } => match command {
1464
+ AdmobAdunitsCommand::List { app } => print_json(
1465
+ &admob::list_ad_units(&client, account, app.as_deref())
1466
+ .await
1467
+ .map_err(fail)?,
1468
+ ),
1469
+ AdmobAdunitsCommand::Create {
1470
+ app,
1471
+ name,
1472
+ format,
1473
+ reward_amount,
1474
+ reward_item,
1475
+ } => {
1476
+ let body = admob::plan_create(&app, &name, &format, reward_amount, &reward_item)
1477
+ .map_err(fail)?;
1478
+ print_json(
1479
+ &admob::create_ad_unit(&client, account, &body)
1480
+ .await
1481
+ .map_err(fail)?,
1482
+ )
1483
+ }
1484
+ },
1485
+ }
1486
+}
1487
+
1488
async fn run_play(
1489
service_account: Option<&std::path::Path>,
1490
command: PlayCommand,
@@ -3042,6 +3170,21 @@ async fn main() -> Result<()> {
3170
.await;
3171
}
3172
3173
+ if let Some(Command::Admob {
3174
+ admob_oauth_client,
3175
+ account,
3176
+ command,
3177
+ }) = cli.command
3178
+ {
3179
+ return run_admob(
3180
+ admob_oauth_client.as_deref(),
3181
+ account.as_deref(),
3182
+ command,
3183
+ cli.dry_run,
3184
+ )
3185
+ .await;
3186
+ }
3187
+
3188
if let Some(Command::Play {
3189
play_service_account,
3190
command,
@@ -3089,7 +3232,10 @@ async fn main() -> Result<()> {
3232
};
3233
3234
match command {
3092
- Command::AppGallery { .. } | Command::Msstore { .. } | Command::Play { .. } => {
3235
+ Command::AppGallery { .. }
3236
+ | Command::Msstore { .. }
3237
+ | Command::Play { .. }
3238
+ | Command::Admob { .. } => {
3239
unreachable!("handled before App Store Connect credentials")
3240
}
3241
Command::Apps { command } => run_apps(&client, &altool_auth, command, cli.dry_run).await,
crates/frontend/Cargo.toml
+1
@@ -17,6 +17,7 @@ schemars = { workspace = true }
17
serde = { workspace = true, features = ["derive"] }
18
serde_json = { workspace = true }
19
sha2 = "0.10"
20
+smbcloud-ascapi-admob = { workspace = true }
21
smbcloud-ascapi-appgallery = { workspace = true }
22
smbcloud-ascapi-aso = { workspace = true }
23
smbcloud-ascapi-msstore = { workspace = true }
crates/frontend/src/admob.rs
new
+168
@@ -0,0 +1,168 @@
1
+//! AdMob operations shared by `asc admob` and the MCP tools.
2
+//!
3
+//! Sign-in is a one-time browser flow (`asc admob login`); every other call
4
+//! uses the cached refresh token. The MCP tools are read-only and never start
5
+//! a browser: with no cached token they fail with a message that says to run
6
+//! `asc admob login`.
7
+
8
+use std::path::{Path, PathBuf};
9
+
10
+use serde::Serialize;
11
+use smbcloud_ascapi_admob::{
12
+ auth, Account, AdFormat, AdUnit, AdmobClient, App, CreateAdUnit, OAuthClient, StoredToken,
13
+};
14
+
15
+fn err(error: impl std::fmt::Display) -> String {
16
+ error.to_string()
17
+}
18
+
19
+fn oauth_client(path: Option<&Path>) -> Result<OAuthClient, String> {
20
+ let path = match path {
21
+ Some(path) => path.to_path_buf(),
22
+ None => std::env::var("ADMOB_OAUTH_CLIENT_JSON_PATH")
23
+ .map(PathBuf::from)
24
+ .map_err(|_| {
25
+ "no AdMob OAuth client: pass --admob-oauth-client, or set \
26
+ ADMOB_OAUTH_CLIENT_JSON_PATH to a Desktop-app client JSON (see docs/admob.md)"
27
+ .to_string()
28
+ })?,
29
+ };
30
+ OAuthClient::from_json_file(path).map_err(err)
31
+}
32
+
33
+/// Resolve the AdMob client. `path` wins; then `ADMOB_OAUTH_CLIENT_JSON_PATH`.
34
+/// Per call, so an unconfigured MCP server still lists its tools.
35
+pub fn admob_client(path: Option<&Path>) -> Result<AdmobClient, String> {
36
+ Ok(AdmobClient::new(oauth_client(path)?, None))
37
+}
38
+
39
+/// Run the browser sign-in and cache the refresh token.
40
+pub async fn login(path: Option<&Path>) -> Result<String, String> {
41
+ let client = oauth_client(path)?;
42
+ let token_path = StoredToken::default_path();
43
+ auth::login(&client, &token_path).await.map_err(err)?;
44
+ Ok(format!(
45
+ "signed in; token cached at {}",
46
+ token_path.display()
47
+ ))
48
+}
49
+
50
+pub async fn list_accounts(client: &AdmobClient) -> Result<Vec<Account>, String> {
51
+ client.list_accounts().await.map_err(err)
52
+}
53
+
54
+/// The account to use: `account` when given, else the only one the user has.
55
+pub async fn resolve_account(
56
+ client: &AdmobClient,
57
+ account: Option<&str>,
58
+) -> Result<String, String> {
59
+ if let Some(account) = account {
60
+ return Ok(account.to_string());
61
+ }
62
+ let accounts = list_accounts(client).await?;
63
+ match accounts.as_slice() {
64
+ [only] => Ok(only.name.clone()),
65
+ [] => Err("this Google user has no AdMob account".to_string()),
66
+ many => Err(format!(
67
+ "several AdMob accounts ({}); pass --account",
68
+ many.iter()
69
+ .map(|a| a.name.as_str())
70
+ .collect::<Vec<_>>()
71
+ .join(", ")
72
+ )),
73
+ }
74
+}
75
+
76
+pub async fn list_apps(client: &AdmobClient, account: Option<&str>) -> Result<Vec<App>, String> {
77
+ let account = resolve_account(client, account).await?;
78
+ client.list_apps(&account).await.map_err(err)
79
+}
80
+
81
+/// Ad units, optionally limited to one app id (`ca-app-pub-…~…`).
82
+pub async fn list_ad_units(
83
+ client: &AdmobClient,
84
+ account: Option<&str>,
85
+ app: Option<&str>,
86
+) -> Result<Vec<AdUnit>, String> {
87
+ let account = resolve_account(client, account).await?;
88
+ let units = client.list_ad_units(&account).await.map_err(err)?;
89
+ Ok(match app {
90
+ Some(app) => units
91
+ .into_iter()
92
+ .filter(|u| u.app_id.as_deref() == Some(app))
93
+ .collect(),
94
+ None => units,
95
+ })
96
+}
97
+
98
+/// The request body for a rewarded unit. Pure, so `--dry-run` needs no
99
+/// credentials.
100
+pub fn plan_create(
101
+ app: &str,
102
+ name: &str,
103
+ format: &str,
104
+ reward_amount: u64,
105
+ reward_item: &str,
106
+) -> Result<CreateAdUnit, String> {
107
+ match AdFormat::parse(format)? {
108
+ AdFormat::Rewarded => Ok(CreateAdUnit::rewarded(
109
+ app,
110
+ name,
111
+ reward_amount,
112
+ reward_item,
113
+ )),
114
+ }
115
+}
116
+
117
+#[derive(Debug, Serialize)]
118
+pub struct CreatedAdUnit {
119
+ pub created: AdUnit,
120
+ /// Set after reading the units back with `adunits list`.
121
+ pub confirmed_in_list: bool,
122
+}
123
+
124
+/// Create the unit, then read the list back and confirm it is there.
125
+pub async fn create_ad_unit(
126
+ client: &AdmobClient,
127
+ account: Option<&str>,
128
+ body: &CreateAdUnit,
129
+) -> Result<CreatedAdUnit, String> {
130
+ let account = resolve_account(client, account).await?;
131
+ let created = client.create_ad_unit(&account, body).await.map_err(err)?;
132
+ let listed = client.list_ad_units(&account).await.map_err(err)?;
133
+ let confirmed_in_list = listed.iter().any(|u| u.name == created.name);
134
+ if !confirmed_in_list {
135
+ return Err(format!(
136
+ "AdMob accepted the create ({}) but the unit is not in the list yet; run `asc admob adunits list`",
137
+ created.name
138
+ ));
139
+ }
140
+ Ok(CreatedAdUnit {
141
+ created,
142
+ confirmed_in_list,
143
+ })
144
+}
145
+
146
+#[cfg(test)]
147
+mod tests {
148
+ use super::*;
149
+
150
+ #[test]
151
+ fn plan_builds_the_rewarded_body() {
152
+ let body = plan_create(
153
+ "ca-app-pub-1~2",
154
+ "Karaoke rewarded",
155
+ "rewarded",
156
+ 50,
157
+ "Semitones",
158
+ )
159
+ .unwrap();
160
+ assert_eq!(body.ad_format, "REWARDED");
161
+ assert_eq!(body.reward_settings.unit_amount, "50");
162
+ }
163
+
164
+ #[test]
165
+ fn plan_rejects_other_formats() {
166
+ assert!(plan_create("a", "n", "banner", 1, "x").is_err());
167
+ }
168
+}
crates/frontend/src/lib.rs
+1
@@ -20,6 +20,7 @@
20
//! `profileContent`, and [`profiles::download_profile`] returns the path
21
//! it wrote instead.
22
23
+pub mod admob;
24
pub mod appgallery;
25
pub mod attach_build;
26
pub mod await_processing;
crates/mcp/src/lib.rs
+50
@@ -73,6 +73,8 @@ macro_rules! ascapi_mcp_tools {
73
$play_listing_list_name:literal,
74
$play_images_list_name:literal,
75
$play_track_get_name:literal,
76
+ $admob_apps_list_name:literal,
77
+ $admob_adunits_list_name:literal,
78
$appgallery_app_info_get_name:literal,
79
$appgallery_package_list_name:literal,
80
$appgallery_package_status_name:literal,
@@ -1048,6 +1050,54 @@ macro_rules! ascapi_mcp_tools {
1050
]))
1051
}
1052
1053
+ #[::rmcp::tool(
1054
+ name = $admob_apps_list_name,
1055
+ title = "List AdMob apps",
1056
+ annotations(title = "List AdMob apps", read_only_hint = true, idempotent_hint = true),
1057
+ description = "Purpose: list the apps of an AdMob account with their ca-app-pub app IDs. When to use vs siblings: use this to find an app ID; admob_adunits_list lists the ad units. Behavior: reads accounts.apps.list, nothing changes. Prerequisites: a Desktop-app OAuth client JSON at ADMOB_OAUTH_CLIENT_JSON_PATH and a cached sign-in made once with the asc admob login command. Failure modes: missing client or sign-in returns an invalid-request error naming what is absent; AdMob errors are returned verbatim with their status. Limitations: read-only; creating ad units is available only through the asc admob adunits create command."
1058
+ )]
1059
+ async fn admob_apps_list(
1060
+ &self,
1061
+ parameters: ::rmcp::handler::server::wrapper::Parameters<$crate::AdmobAppsListRequest>,
1062
+ ) -> ::std::result::Result<::rmcp::model::CallToolResult, ::rmcp::model::ErrorData> {
1063
+ use ::smbcloud_ascapi_frontend::admob;
1064
+ let client = admob::admob_client(None)
1065
+ .map_err(|error| ::rmcp::model::ErrorData::invalid_request(error, None))?;
1066
+ let request = parameters.0;
1067
+ let value = admob::list_apps(&client, request.account.as_deref())
1068
+ .await
1069
+ .map_err(|error| ::rmcp::model::ErrorData::internal_error(error, None))?;
1070
+ Ok(::rmcp::model::CallToolResult::success(vec![
1071
+ ::rmcp::model::ContentBlock::json(&value)?,
1072
+ ]))
1073
+ }
1074
+
1075
+ #[::rmcp::tool(
1076
+ name = $admob_adunits_list_name,
1077
+ title = "List AdMob ad units",
1078
+ annotations(title = "List AdMob ad units", read_only_hint = true, idempotent_hint = true),
1079
+ description = "Purpose: list the ad units of an AdMob account (ID, format, app, reward settings), optionally for one app. When to use vs siblings: use this to read a unit's ca-app-pub ad unit ID after creating it in the console; admob_apps_list finds app IDs. Behavior: reads accounts.adUnits.list, nothing changes. Prerequisites: a Desktop-app OAuth client JSON at ADMOB_OAUTH_CLIENT_JSON_PATH and a cached sign-in made once with the asc admob login command. Failure modes: missing client or sign-in returns an invalid-request error naming what is absent; AdMob errors are returned verbatim with their status. Limitations: read-only; creating ad units is available only through the asc admob adunits create command."
1080
+ )]
1081
+ async fn admob_adunits_list(
1082
+ &self,
1083
+ parameters: ::rmcp::handler::server::wrapper::Parameters<$crate::AdmobAdunitsListRequest>,
1084
+ ) -> ::std::result::Result<::rmcp::model::CallToolResult, ::rmcp::model::ErrorData> {
1085
+ use ::smbcloud_ascapi_frontend::admob;
1086
+ let client = admob::admob_client(None)
1087
+ .map_err(|error| ::rmcp::model::ErrorData::invalid_request(error, None))?;
1088
+ let request = parameters.0;
1089
+ let value = admob::list_ad_units(
1090
+ &client,
1091
+ request.account.as_deref(),
1092
+ request.app.as_deref(),
1093
+ )
1094
+ .await
1095
+ .map_err(|error| ::rmcp::model::ErrorData::internal_error(error, None))?;
1096
+ Ok(::rmcp::model::CallToolResult::success(vec![
1097
+ ::rmcp::model::ContentBlock::json(&value)?,
1098
+ ]))
1099
+ }
1100
+
1101
#[::rmcp::tool(
1102
name = $appgallery_app_info_get_name,
1103
title = "Get AppGallery app info",
crates/mcp/src/requests.rs
+17
@@ -276,6 +276,23 @@ pub struct BetaAppReviewDetailGetRequest {
276
pub app_id: String,
277
}
278
279
+#[derive(Debug, Clone, Deserialize, schemars::JsonSchema)]
280
+pub struct AdmobAppsListRequest {
281
+ /// AdMob account, `pub-…`. Defaults to the only account the user has.
282
+ #[serde(default)]
283
+ pub account: Option<String>,
284
+}
285
+
286
+#[derive(Debug, Clone, Deserialize, schemars::JsonSchema)]
287
+pub struct AdmobAdunitsListRequest {
288
+ /// AdMob account, `pub-…`. Defaults to the only account the user has.
289
+ #[serde(default)]
290
+ pub account: Option<String>,
291
+ /// Only units of this app ID, `ca-app-pub-…~…`.
292
+ #[serde(default)]
293
+ pub app: Option<String>,
294
+}
295
+
296
#[derive(Debug, Clone, Deserialize, schemars::JsonSchema)]
297
pub struct PlayPackageRequest {
298
/// Android application id, e.g. xyz.smbcloud.SiGit.
crates/mcp/src/server.rs
+5
-1
@@ -63,6 +63,8 @@ ascapi_mcp_tools!(
63
"play_listing_list",
64
"play_images_list",
65
"play_track_get",
66
+ "admob_apps_list",
67
+ "admob_adunits_list",
68
"appgallery_app_info_get",
69
"appgallery_package_list",
70
"appgallery_package_status",
@@ -117,7 +119,7 @@ mod tests {
119
/// The canonical tool names. Adding or renaming one is a
120
/// public-contract change, and this list is what makes that
121
/// deliberate rather than accidental.
120
- const CANONICAL_TOOL_NAMES: [&str; 40] = [
122
+ const CANONICAL_TOOL_NAMES: [&str; 42] = [
123
"app_list",
124
"app_get",
125
"app_update",
@@ -152,6 +154,8 @@ mod tests {
154
"play_listing_list",
155
"play_images_list",
156
"play_track_get",
157
+ "admob_apps_list",
158
+ "admob_adunits_list",
159
"appgallery_app_info_get",
160
"appgallery_package_list",
161
"appgallery_package_status",
docs/admob.md
new
+62
@@ -0,0 +1,62 @@
1
+# AdMob (`asc admob`)
2
+
3
+`asc admob` reads AdMob accounts, apps and ad units, and can create a rewarded
4
+ad unit. It uses the AdMob API, which accepts user OAuth only. There are no
5
+service accounts, so this is a one-time browser sign-in.
6
+
7
+## One-time setup
8
+
9
+1. In Google Cloud Console, pick a project and enable the **AdMob API**.
10
+2. Create an OAuth client of type **Desktop app** (APIs & Services, Credentials).
11
+ Configure the consent screen if asked; add yourself as a test user while
12
+ the screen is in testing.
13
+3. Download the client JSON and keep it outside any repo.
14
+4. Sign in as the Google user that owns the AdMob publisher account:
15
+
16
+```bash
17
+export ADMOB_OAUTH_CLIENT_JSON_PATH=~/path/to/client.json # or --admob-oauth-client
18
+asc admob login
19
+```
20
+
21
+The browser opens, Google redirects to a loopback port on `127.0.0.1`, and the
22
+code is exchanged with PKCE. Only the refresh token is stored, at
23
+`~/.config/asc/admob-token.json` with mode 0600. Later calls refresh access
24
+tokens silently. Delete the file to sign out. Tokens and the client secret are
25
+never printed.
26
+
27
+## Commands
28
+
29
+```bash
30
+asc admob accounts
31
+asc admob apps list [--account pub-...]
32
+asc admob adunits list [--app ca-app-pub-...~...] [--account pub-...]
33
+asc admob adunits create --app ca-app-pub-...~... --name "Karaoke rewarded" \
34
+ --format rewarded --reward-amount 50 --reward-item Semitones
35
+```
36
+
37
+`--account` defaults to the only account the user has. `--dry-run` on `create`
38
+prints the request body and needs neither credentials nor a sign-in. After a
39
+real create, `asc` reads the units back and fails if the new one is missing.
40
+
41
+The MCP server exposes `admob_apps_list` and `admob_adunits_list`, both
42
+read-only. They never open a browser; without a cached sign-in they say to run
43
+`asc admob login`.
44
+
45
+## Limited access on create
46
+
47
+`accounts.adUnits.create` (v1beta, scope `admob.monetization`) is limited
48
+access. Without a grant from your AdMob account manager it answers **403**, and
49
+`asc` reports that as a limited-access error. When that happens:
50
+
51
+1. Create the unit in the console at
52
+ `https://admob.google.com/v2/apps/<numeric app id>/adunits/create`.
53
+2. Run `asc admob adunits list --app <appId>` to read its ID.
54
+
55
+## What the API cannot do
56
+
57
+These stay manual console steps:
58
+
59
+- the server-side verification (SSV) callback URL on a rewarded unit
60
+- GDPR / consent messages
61
+- app-ads.txt verification
62
+- Google Play's "Contains ads" and Data safety forms (those are Play Console)