flintbase 0.3.1

Google / Firebase API key analyzer and APK secret scanner — tests keys against 20+ endpoints and extracts hardcoded credentials from Android apps
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
use std::path::{Path, PathBuf};
use std::process::Command;

use colored::Colorize;
use regex::Regex;

/// Sources we can try downloading from, in priority order.
const DOWNLOAD_SOURCES: &[&str] = &["apk-pure", "f-droid", "huawei-app-gallery"];

/// Parse a Play Store URL or raw package name into one or more package identifiers.
///
/// Supported inputs:
///   - Direct package name: `com.example.app`
///   - Single-app URL:      `https://play.google.com/store/apps/details?id=com.example.app`
///   - Developer URL:       `https://play.google.com/store/apps/developer?id=Developer+Name`
///                          (attempts to scrape app links; may not work without JS rendering)
pub fn parse_store_input(input: &str) -> anyhow::Result<Vec<String>> {
    let input = input.trim();

    // Case 1: Single app URL — extract `id=` parameter
    if input.contains("play.google.com/store/apps/details") {
        if let Some(pkg) = extract_id_param(input) {
            println!(
                "  {} Extracted package: {}",
                "".cyan(),
                pkg.bold()
            );
            return Ok(vec![pkg]);
        }
        anyhow::bail!("Could not extract package ID from URL: {}", input);
    }

    // Case 2: Developer URL — try to scrape app links
    if input.contains("play.google.com/store/apps/dev") {
        println!(
            "  {} Detected developer page, attempting to enumerate apps...",
            "".cyan()
        );
        return scrape_developer_apps(input);
    }

    // Case 3: Assume it's a raw package name
    let pkg_re = Regex::new(r"^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z][a-zA-Z0-9_]*)+$").unwrap();
    if pkg_re.is_match(input) {
        println!(
            "  {} Using package: {}",
            "".cyan(),
            input.bold()
        );
        return Ok(vec![input.to_string()]);
    }

    anyhow::bail!(
        "Unrecognized input: '{}'\n\
         Expected a Play Store URL or a package name like com.example.app",
        input
    );
}

/// Download an APK using apkeep, trying multiple sources as fallbacks.
/// Returns the path to the downloaded APK file.
#[allow(unused_assignments)]
pub fn download_apk(package: &str, output_dir: &Path, verbose: bool) -> anyhow::Result<PathBuf> {
    std::fs::create_dir_all(output_dir)?;

    let mut last_error = String::new();

    for (i, source) in DOWNLOAD_SOURCES.iter().enumerate() {
        let is_primary = i == 0;
        let label = if is_primary {
            format!("apkeep (source: {})", source)
        } else {
            format!("apkeep fallback (source: {})", source)
        };

        if !is_primary {
            println!(
                "  {} Trying fallback source: {}",
                "".yellow(),
                source.bold()
            );
        } else {
            println!(
                "  {} Downloading {} via {}...",
                "".cyan(),
                package.bold(),
                label.dimmed()
            );
        }

        match try_apkeep_download(package, source, output_dir, verbose) {
            Ok(apk_path) => {
                return Ok(apk_path);
            }
            Err(e) => {
                let msg = format!("{}: {}", source, e);
                if verbose {
                    println!("  {} {}", "verbose".dimmed(), msg.dimmed());
                }
                if !is_primary {
                    println!(
                        "  {} {} source failed: {}",
                        "".yellow(),
                        source,
                        short_error(&e.to_string())
                    );
                }
                last_error = msg;
            }
        }
    }

    // All sources exhausted — try direct APKPure web scrape as last resort
    println!(
        "  {} All apkeep sources exhausted, trying direct APKPure web download...",
        "".yellow()
    );

    match try_direct_apkpure_download(package, output_dir, verbose) {
        Ok(apk_path) => return Ok(apk_path),
        Err(e) => {
            if verbose {
                println!(
                    "  {} Direct APKPure: {}",
                    "verbose".dimmed(),
                    e.to_string().dimmed()
                );
            }
            last_error = format!("direct APKPure: {}", e);
        }
    }

    anyhow::bail!(
        "Failed to download {} from all sources.\n  Last error: {}\n  \
         The app may not be available on any supported mirror.\n  \
         Tip: You can manually place an APK at {}/{}.apk and re-run.",
        package,
        last_error,
        output_dir.display(),
        package
    )
}

/// Attempt to download with apkeep from a specific source.
fn try_apkeep_download(
    package: &str,
    source: &str,
    output_dir: &Path,
    verbose: bool,
) -> anyhow::Result<PathBuf> {
    let output = Command::new("apkeep")
        .arg("-a")
        .arg(package)
        .arg("-d")
        .arg(source)
        .arg(output_dir)
        .output()?;

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    if verbose {
        if !stdout.is_empty() {
            for line in stdout.lines() {
                println!("    {}", line.dimmed());
            }
        }
        if !stderr.is_empty() {
            for line in stderr.lines() {
                println!("    {}", line.dimmed());
            }
        }
    }

    // Check exit code
    if !output.status.success() {
        let err_text = if !stderr.is_empty() {
            stderr.trim().to_string()
        } else if !stdout.is_empty() {
            stdout.trim().to_string()
        } else {
            format!("exit code {}", output.status.code().unwrap_or(-1))
        };
        anyhow::bail!("apkeep exited with error: {}", short_error(&err_text));
    }

    // apkeep can exit 0 but not actually download anything — check for files
    match find_apk_in_dir(output_dir, package) {
        Ok(path) => {
            // Verify file is non-empty
            let size = std::fs::metadata(&path)
                .map(|m| m.len())
                .unwrap_or(0);
            if size == 0 {
                let _ = std::fs::remove_file(&path);
                anyhow::bail!("Downloaded file is empty (0 bytes)");
            }
            // Print download confirmation from apkeep stdout if present
            if stdout.contains("downloaded successfully") {
                // Already printed by apkeep
            }
            Ok(path)
        }
        Err(_) => {
            // Silent failure: apkeep exited 0 but produced no file
            let hint = if stdout.contains("not found") || stderr.contains("not found") {
                "app not found on this source"
            } else if stdout.is_empty() && stderr.is_empty() {
                "no output from apkeep (app likely not available on this source)"
            } else {
                "no APK file produced"
            };
            anyhow::bail!("{}", hint);
        }
    }
}

/// Last-resort: try downloading directly from APKPure's website.
/// Fetches the app page, extracts the download link, and downloads.
fn try_direct_apkpure_download(
    package: &str,
    output_dir: &Path,
    verbose: bool,
) -> anyhow::Result<PathBuf> {
    let client = reqwest::blocking::Client::builder()
        .user_agent(
            "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 \
             Chrome/120.0.0.0 Mobile Safari/537.36",
        )
        .timeout(std::time::Duration::from_secs(30))
        .redirect(reqwest::redirect::Policy::limited(10))
        .build()?;

    // Step 1: Fetch the APKPure page for this package
    // APKPure URLs: https://apkpure.com/<name>/<package>/download
    // We don't know the name slug, but APKPure redirects /<package>/download too
    let page_url = format!("https://apkpure.com/search?q={}", package);

    if verbose {
        println!(
            "    {} Fetching APKPure search: {}",
            "verbose".dimmed(),
            page_url.dimmed()
        );
    }

    let resp = client.get(&page_url).send()?;
    let body = resp.text()?;

    // Find the app page link for our exact package
    let link_re = Regex::new(&format!(
        r#"href="(https://apkpure\.com/[^"]+/{})"#,
        regex::escape(package)
    ))?;

    let app_page_url = link_re
        .captures(&body)
        .and_then(|c| c.get(1))
        .map(|m| m.as_str().to_string())
        .ok_or_else(|| anyhow::anyhow!("Package not found on APKPure search results"))?;

    if verbose {
        println!(
            "    {} Found app page: {}",
            "verbose".dimmed(),
            app_page_url.dimmed()
        );
    }

    // Step 2: Fetch app page and look for download link
    let download_page_url = format!("{}/download", app_page_url);
    let resp = client.get(&download_page_url).send()?;
    let body = resp.text()?;

    // Look for direct download link patterns
    let dl_re = Regex::new(r#"href="(https://d\.apkpure\.net/[^"]+\.apk[^"]*)"#)?;
    let download_url = dl_re
        .captures(&body)
        .and_then(|c| c.get(1))
        .map(|m| m.as_str().to_string());

    // Alternative: look for download button data attributes
    let download_url = download_url.or_else(|| {
        let alt_re = Regex::new(r#"data-dt-url="(https?://[^"]+\.apk[^"]*)"#).ok()?;
        alt_re
            .captures(&body)
            .and_then(|c| c.get(1))
            .map(|m| m.as_str().to_string())
    });

    let download_url = match download_url {
        Some(url) => url,
        None => {
            anyhow::bail!(
                "Could not extract download URL from APKPure page (site may require JS)"
            );
        }
    };

    if verbose {
        println!(
            "    {} Download URL: {}",
            "verbose".dimmed(),
            short_error(&download_url).dimmed()
        );
    }

    // Step 3: Download the APK
    println!(
        "  {} Downloading from APKPure direct...",
        "".cyan()
    );

    let resp = client.get(&download_url).send()?;
    if !resp.status().is_success() {
        anyhow::bail!("APKPure download returned HTTP {}", resp.status());
    }

    let bytes = resp.bytes()?;
    if bytes.len() < 1000 {
        anyhow::bail!(
            "Downloaded file too small ({} bytes) — likely not a real APK",
            bytes.len()
        );
    }

    let dest = output_dir.join(format!("{}.apk", package));
    std::fs::write(&dest, &bytes)?;

    println!(
        "  {} Downloaded {} ({:.1} MB)",
        "".green(),
        package,
        bytes.len() as f64 / 1_048_576.0
    );

    Ok(dest)
}

// ── Internal helpers ─────────────────────────────────────────────────────────

fn extract_id_param(url: &str) -> Option<String> {
    let re = Regex::new(r"[?&]id=([a-zA-Z0-9_.]+)").ok()?;
    re.captures(url).map(|c| c[1].to_string())
}

fn scrape_developer_apps(url: &str) -> anyhow::Result<Vec<String>> {
    let client = reqwest::blocking::Client::builder()
        .user_agent(
            "Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 \
             Chrome/120.0.0.0 Mobile Safari/537.36",
        )
        .timeout(std::time::Duration::from_secs(15))
        .build()?;

    let resp = client.get(url).send()?;
    let body = resp.text()?;

    let re = Regex::new(r"details\?id=([a-zA-Z0-9_.]+)").unwrap();
    let mut packages: Vec<String> = re
        .captures_iter(&body)
        .map(|c| c[1].to_string())
        .collect();

    packages.sort();
    packages.dedup();

    if packages.is_empty() {
        anyhow::bail!(
            "Could not extract any app packages from the developer page.\n\
             Google Play developer pages often require JavaScript rendering.\n\
             Please provide individual app URLs or package names instead."
        );
    }

    println!(
        "  {} Found {} app(s) on developer page:",
        "".green(),
        packages.len()
    );
    for pkg in &packages {
        println!("{}", pkg.bold());
    }

    Ok(packages)
}

fn find_apk_in_dir(dir: &Path, package: &str) -> anyhow::Result<PathBuf> {
    let entries = std::fs::read_dir(dir)?;
    let mut candidates: Vec<PathBuf> = Vec::new();

    for entry in entries.flatten() {
        let path = entry.path();
        if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
            if name.starts_with(package)
                && (name.ends_with(".apk") || name.ends_with(".xapk"))
            {
                candidates.push(path);
            }
        }
    }

    // Also check for any .apk file if we didn't find one matching the package name
    if candidates.is_empty() {
        let entries = std::fs::read_dir(dir)?;
        for entry in entries.flatten() {
            let path = entry.path();
            if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
                if name.ends_with(".apk") || name.ends_with(".xapk") {
                    candidates.push(path);
                }
            }
        }
    }

    // Sort by modification time (newest first)
    candidates.sort_by(|a, b| {
        let ma = a.metadata().and_then(|m| m.modified()).ok();
        let mb = b.metadata().and_then(|m| m.modified()).ok();
        mb.cmp(&ma)
    });

    candidates.into_iter().next().ok_or_else(|| {
        anyhow::anyhow!("No APK file found in {}", dir.display())
    })
}

/// Truncate long error messages for display.
fn short_error(msg: &str) -> String {
    let first_line = msg.lines().next().unwrap_or(msg);
    if first_line.len() > 120 {
        format!("{}...", &first_line[..120])
    } else {
        first_line.to_string()
    }
}