offline-mcp 0.4.0

Model Context Protocol server exposing the Offline Protocol registry to AI agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! An application's native signing identities, edited the way the developer
//! API stores them (`native_attestation` on the application): iOS bundle ID +
//! Apple App ID prefix (usually the Team ID), Android package name + signing
//! certificate SHA-256 fingerprints. Every edit is idempotent: adding what is
//! already registered changes nothing.
//!
//! The validation mirrors developer-service-api's `native_client.rs`, so a
//! typo is refused here with the fix, before a request is made.

use serde_json::{json, Map, Value};

/// An iOS bundle ID: two or more dot-separated segments of ASCII letters,
/// digits and hyphens. The signed case is kept (App Attest hashes it).
pub fn normalize_bundle_id(raw: &str) -> Option<String> {
    let id = raw.trim();
    if id.is_empty() || id.len() > 155 {
        return None;
    }
    let segments: Vec<&str> = id.split('.').collect();
    let ok = segments.len() >= 2
        && segments.iter().all(|s| {
            !s.is_empty()
                && !s.starts_with('-')
                && !s.ends_with('-')
                && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
        });
    ok.then(|| id.to_string())
}

/// Apple's App ID prefix (usually the 10-character Team ID), upper-case.
pub fn normalize_team_id(raw: &str) -> Option<String> {
    let id = raw.trim().to_ascii_uppercase();
    (id.len() == 10
        && id
            .bytes()
            .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit()))
    .then_some(id)
}

/// An Android package name (application ID); case is kept.
pub fn normalize_package(raw: &str) -> Option<String> {
    let name = raw.trim();
    if name.is_empty() || name.len() > 155 {
        return None;
    }
    let segments: Vec<&str> = name.split('.').collect();
    let ok = segments.len() >= 2
        && segments.iter().all(|s| {
            s.bytes().next().is_some_and(|b| b.is_ascii_alphabetic())
                && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
        });
    ok.then(|| name.to_string())
}

/// A certificate SHA-256 fingerprint as `keytool`, Gradle's `signingReport`
/// and Play Console print it, or plain hex: stored as `AB:CD:…`.
pub fn normalize_sha256(raw: &str) -> Option<String> {
    let hex: String = raw
        .trim()
        .chars()
        .filter(|c| *c != ':' && !c.is_whitespace())
        .collect();
    if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
        return None;
    }
    let hex = hex.to_ascii_uppercase();
    Some(
        hex.as_bytes()
            .chunks(2)
            .map(|p| std::str::from_utf8(p).unwrap_or_default())
            .collect::<Vec<_>>()
            .join(":"),
    )
}

pub const BUNDLE_ID_HELP: &str =
    "an iOS bundle ID looks like com.example.app (letters, digits, hyphens; the exact case of your signed build)";
pub const TEAM_ID_HELP: &str =
    "the Apple Team ID (App ID prefix) is 10 letters or digits, e.g. ABCDE12345 \
     (Apple Developer → Membership, or `ios.appleTeamId` in app.json)";
pub const PACKAGE_HELP: &str =
    "an Android package name looks like com.example.app (letters, digits, underscores)";
pub const SHA256_HELP: &str =
    "a signing certificate SHA-256 is 64 hex digits, e.g. AB:CD:…; get it from \
     Play Console → App integrity → App signing, `./gradlew signingReport`, or \
     `keytool -list -v -keystore <file>`";

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IosApp {
    pub bundle_id: String,
    pub team_id: String,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AndroidApp {
    pub package: String,
    pub sha256: Vec<String>,
}

/// The `native_attestation` object of an application plus its Android
/// package list, edited in place and sent back whole, so settings this CLI
/// does not touch (Play Integrity project number, the stored credential) are
/// kept.
#[derive(Debug, Clone, PartialEq)]
pub struct Native {
    attestation: Map<String, Value>,
    android_package_names: Vec<String>,
}

impl Native {
    /// From an application object as `GET /developers/applications/:id` returns it.
    pub fn from_application(app: &Value) -> Self {
        let mut attestation = app
            .get("native_attestation")
            .and_then(Value::as_object)
            .cloned()
            .unwrap_or_default();
        for key in ["ios_apps", "android_apps"] {
            if !attestation.get(key).is_some_and(Value::is_array) {
                attestation.insert(key.into(), json!([]));
            }
        }
        if !attestation
            .get("allow_development")
            .is_some_and(Value::is_boolean)
        {
            attestation.insert("allow_development".into(), json!(false));
        }
        let android_package_names = app
            .get("android_package_names")
            .and_then(Value::as_array)
            .map(|a| {
                a.iter()
                    .filter_map(Value::as_str)
                    .map(str::to_string)
                    .collect()
            })
            .unwrap_or_default();
        Self {
            attestation,
            android_package_names,
        }
    }

    pub fn ios_apps(&self) -> Vec<IosApp> {
        self.attestation["ios_apps"]
            .as_array()
            .map(|a| {
                a.iter()
                    .filter_map(|v| {
                        Some(IosApp {
                            bundle_id: v.get("bundle_id")?.as_str()?.to_string(),
                            team_id: v.get("app_id_prefix")?.as_str()?.to_string(),
                        })
                    })
                    .collect()
            })
            .unwrap_or_default()
    }

    pub fn android_apps(&self) -> Vec<AndroidApp> {
        self.attestation["android_apps"]
            .as_array()
            .map(|a| {
                a.iter()
                    .filter_map(|v| {
                        Some(AndroidApp {
                            package: v.get("package_name")?.as_str()?.to_string(),
                            sha256: v
                                .get("signing_cert_sha256")?
                                .as_array()?
                                .iter()
                                .filter_map(Value::as_str)
                                .map(str::to_string)
                                .collect(),
                        })
                    })
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Android packages registered without a signing certificate (older
    /// registrations): they cannot attest.
    pub fn android_packages_without_certificate(&self) -> Vec<String> {
        let paired: Vec<String> = self.android_apps().into_iter().map(|a| a.package).collect();
        self.android_package_names
            .iter()
            .filter(|p| !paired.contains(p))
            .cloned()
            .collect()
    }

    pub fn allow_development(&self) -> bool {
        self.attestation["allow_development"]
            .as_bool()
            .unwrap_or(false)
    }

    fn set_ios(&mut self, apps: Vec<IosApp>) {
        self.attestation.insert(
            "ios_apps".into(),
            Value::Array(
                apps.into_iter()
                    .map(|a| json!({ "bundle_id": a.bundle_id, "app_id_prefix": a.team_id }))
                    .collect(),
            ),
        );
    }

    fn set_android(&mut self, apps: Vec<AndroidApp>) {
        self.attestation.insert(
            "android_apps".into(),
            Value::Array(
                apps.into_iter()
                    .map(|a| json!({ "package_name": a.package, "signing_cert_sha256": a.sha256 }))
                    .collect(),
            ),
        );
    }

    /// Register an iOS signing identity. Returns whether anything changed.
    pub fn add_ios(&mut self, bundle_id: &str, team_id: &str) -> bool {
        let mut apps = self.ios_apps();
        let exists = apps
            .iter()
            .any(|a| a.bundle_id == bundle_id && a.team_id.eq_ignore_ascii_case(team_id));
        if exists {
            return false;
        }
        apps.push(IosApp {
            bundle_id: bundle_id.to_string(),
            team_id: team_id.to_ascii_uppercase(),
        });
        self.set_ios(apps);
        true
    }

    /// Remove an iOS bundle (every Team ID it is paired with, or just one).
    pub fn remove_ios(&mut self, bundle_id: &str, team_id: Option<&str>) -> bool {
        let apps = self.ios_apps();
        let kept: Vec<IosApp> = apps
            .iter()
            .filter(|a| {
                let team_matches = match team_id {
                    Some(t) => a.team_id.eq_ignore_ascii_case(t),
                    None => true,
                };
                !(a.bundle_id.eq_ignore_ascii_case(bundle_id) && team_matches)
            })
            .cloned()
            .collect();
        let changed = kept.len() != apps.len();
        if changed {
            self.set_ios(kept);
        }
        changed
    }

    /// Register signing certificates for an Android package (adding the
    /// package when new). Returns whether anything changed.
    pub fn add_android(&mut self, package: &str, certs: &[String]) -> bool {
        let mut apps = self.android_apps();
        let mut changed = false;
        match apps.iter_mut().find(|a| a.package == package) {
            Some(app) => {
                for cert in certs {
                    if !app.sha256.contains(cert) {
                        app.sha256.push(cert.clone());
                        changed = true;
                    }
                }
            }
            None => {
                apps.push(AndroidApp {
                    package: package.to_string(),
                    sha256: certs.to_vec(),
                });
                changed = true;
            }
        }
        if !self.android_package_names.iter().any(|p| p == package) {
            self.android_package_names.push(package.to_string());
            changed = true;
        }
        if changed {
            self.set_android(apps);
        }
        changed
    }

    /// Remove one certificate of a package, or the whole package.
    pub fn remove_android(&mut self, package: &str, cert: Option<&str>) -> bool {
        let mut apps = self.android_apps();
        let before = apps.clone();
        match cert {
            Some(cert) => {
                for app in apps.iter_mut().filter(|a| a.package == package) {
                    app.sha256.retain(|c| c != cert);
                }
                // A package with no certificate left is removed, not left
                // unable to attest.
                apps.retain(|a| !a.sha256.is_empty());
            }
            None => apps.retain(|a| a.package != package),
        }
        let package_gone = !apps.iter().any(|a| a.package == package);
        let mut changed = apps != before;
        if package_gone && self.android_package_names.iter().any(|p| p == package) {
            self.android_package_names.retain(|p| p != package);
            changed = true;
        }
        if changed {
            self.set_android(apps);
        }
        changed
    }

    /// The developer marked the application production.
    pub fn production(&self) -> bool {
        self.attestation
            .get("production")
            .and_then(Value::as_bool)
            .unwrap_or(false)
    }

    pub fn set_production(&mut self, on: bool) -> bool {
        if self.production() == on {
            return false;
        }
        self.attestation
            .insert("production".into(), Value::Bool(on));
        true
    }

    /// `allow` (default) or `refuse`: Android devices that cannot fully attest.
    pub fn android_degraded(&self) -> &str {
        match self
            .attestation
            .get("android_degraded")
            .and_then(Value::as_str)
        {
            Some("refuse") => "refuse",
            _ => "allow",
        }
    }

    pub fn set_android_degraded(&mut self, allow: bool) -> bool {
        let value = if allow { "allow" } else { "refuse" };
        if self.android_degraded() == value {
            return false;
        }
        self.attestation
            .insert("android_degraded".into(), Value::String(value.into()));
        true
    }

    /// Until when development mode is on (RFC 3339, UTC), if it is on now.
    pub fn development_until(&self) -> Option<String> {
        if self.production() {
            return None;
        }
        let until = self
            .attestation
            .get("development_mode")
            .and_then(|d| d.get("until"))
            .and_then(Value::as_str)?;
        (super::is_future(until)).then(|| until.to_string())
    }

    pub fn set_allow_development(&mut self, on: bool) -> bool {
        if self.allow_development() == on {
            return false;
        }
        self.attestation
            .insert("allow_development".into(), Value::Bool(on));
        true
    }

    /// The `PATCH /developers/applications/:id` body that stores this state.
    pub fn patch_body(&self) -> Value {
        let mut attestation = self.attestation.clone();
        // Derived by the server; never sent back as if the client knew better.
        attestation.remove("android_service_account_email");
        attestation.remove("android_credentials_configured");
        // Set only through its own endpoint (the server ignores it here).
        attestation.remove("development_mode");
        json!({
            "native_attestation": Value::Object(attestation),
            "android_package_names": self.android_package_names,
        })
    }
}

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

    const SHA: &str = "ab:cd:ef:01:23:45:67:89:ab:cd:ef:01:23:45:67:89:ab:cd:ef:01:23:45:67:89:ab:cd:ef:01:23:45:67:89";

    #[test]
    fn identifiers_are_validated_like_the_server() {
        assert_eq!(
            normalize_bundle_id(" Com.Example.App ").as_deref(),
            Some("Com.Example.App")
        );
        assert!(normalize_bundle_id("example").is_none());
        assert!(normalize_bundle_id("com.example.app_1").is_none());
        assert_eq!(
            normalize_team_id("abcde12345").as_deref(),
            Some("ABCDE12345")
        );
        assert!(normalize_team_id("ABC").is_none());
        assert_eq!(
            normalize_package("com.Example.my_app").as_deref(),
            Some("com.Example.my_app")
        );
        assert!(normalize_package("com.example-app").is_none());
        assert_eq!(
            normalize_sha256(&SHA.replace(':', "")).unwrap(),
            SHA.to_ascii_uppercase()
        );
        assert!(normalize_sha256("abcd").is_none());
    }

    #[test]
    fn edits_are_idempotent_and_keep_settings_this_cli_does_not_touch() {
        let app = json!({
            "native_attestation": { "mode": "off", "ios_apps": [], "android_apps": [],
                "allow_development": false, "android_cloud_project_number": "123",
                "android_credentials_configured": true, "android_service_account_email": "x@y.iam.gserviceaccount.com" },
            "android_package_names": ["com.legacy.app"]
        });
        let mut n = Native::from_application(&app);
        let cert = normalize_sha256(SHA).unwrap();
        assert!(n.add_ios("com.example.app", "ABCDE12345"));
        assert!(!n.add_ios("com.example.app", "abcde12345"));
        assert!(n.add_android("com.example.app", std::slice::from_ref(&cert)));
        assert!(!n.add_android("com.example.app", std::slice::from_ref(&cert)));
        assert!(n.set_allow_development(true));
        assert!(!n.set_allow_development(true));
        assert_eq!(
            n.android_packages_without_certificate(),
            vec!["com.legacy.app"]
        );
        let body = n.patch_body();
        assert_eq!(
            body["native_attestation"]["android_cloud_project_number"],
            "123"
        );
        assert!(body["native_attestation"]
            .get("android_credentials_configured")
            .is_none());
        assert_eq!(
            body["native_attestation"]["ios_apps"][0]["app_id_prefix"],
            "ABCDE12345"
        );
        assert_eq!(
            body["android_package_names"],
            json!(["com.legacy.app", "com.example.app"])
        );

        assert!(n.remove_android("com.example.app", Some(&cert)));
        assert!(n.android_apps().is_empty());
        assert_eq!(
            n.patch_body()["android_package_names"],
            json!(["com.legacy.app"])
        );
        assert!(n.remove_ios("COM.EXAMPLE.APP", None));
        assert!(!n.remove_ios("com.example.app", None));
    }

    #[test]
    fn an_application_without_settings_starts_empty() {
        let n = Native::from_application(&json!({ "native_attestation": null }));
        assert!(n.ios_apps().is_empty());
        assert!(!n.allow_development());
        assert_eq!(n.patch_body()["native_attestation"]["ios_apps"], json!([]));
    }
}