diff --git a/CHANGELOG.md b/CHANGELOG.md index d01836dc..270835fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,26 @@ ## Unreleased +- `storebound scan` on Google Play now matches the App Store side: rejections, blocked updates, suspensions and + policy strikes that the project files can prove, each verified against the live Play Policy Center / Play Console + Help page (cited with the date in `cli/lib/scan/play-rules.ts`). New rules: the restricted permissions and their + Console declarations (background location, READ_MEDIA_IMAGES / READ_MEDIA_VIDEO, MANAGE_EXTERNAL_STORAGE, + AccessibilityService with or without isAccessibilityTool, REQUEST_INSTALL_PACKAGES, Health Connect, + USE_FULL_SCREEN_INTENT, VpnService), prominent disclosure and the in-app privacy policy (User Data), Data safety + answers narrower than the SDKs' disclosures, Families (`play.targetAges`: ad SDKs not on Google's self-certified list + or older than their certified version, AD_ID and location in child-only apps, mixed audiences), the AD_ID permission + on targetSdk 33+, 16 KB page sizes (Unity before 6000.0.38f1 / 2022.3.56f1 / 2021.3.48f1, React Native before 0.77, + NDK before r28 without the flags, AGP before 8.5.1 with uncompressed libraries, prebuilt .so files; updates blocked + from 2027-02-01), the closed-testing requirement of new personal accounts (`play.accountType`, + `play.accountCreated`: 12 testers for 14 days), Play metadata (title over 30 characters, emoji, ALL CAPS, rank / + price / promotion terms, other apps, repeated keywords and keyword lists), interstitials shown from the launcher + activity's onCreate, card / PayPal SDKs or "buy on our website" next to in-app products (`play.billingPrograms`), + and brand names in the package or app name (low). Detection reads activities, services and receivers with their + intent filters, accessibility-service configs, strings.xml, the NDK / AGP versions, CMake / ndk-build files, + extractNativeLibs, useLegacyPackaging, Unity ProjectVersion.txt, .so files, and the merged manifest under + build/intermediates when the project was built locally. Device admin has no Play policy page and gets no rule. The + App Store rules are unchanged. New fixtures (play-android, play-native, play-families, play-listing) and Android parts + in the clean fixture; the README rule table has a column per store. - `storebound scan` (MCP tool `scan`, desktop Checks tab): an offline, read-only scan of the project itself for App Store and Google Play rejection risks before you submit. Detects the stack (native iOS / Android, React Native, Expo, Capacitor, Cordova, Flutter, Unity, Godot) and the SDKs from a maintained table (`cli/lib/scan/sdks.ts`: ads, diff --git a/README.md b/README.md index 456a4c04..a239119e 100644 --- a/README.md +++ b/README.md @@ -91,9 +91,11 @@ New personal Play developer accounts also need a closed test with 12+ testers fo ## Catch rejections before you submit App Store rejections cost days: you wait for review, read one sentence in the Resolution Center, fix it, and wait -again. Most of the usual ones are visible in the project long before that. `storebound scan` reads the project itself, -offline and read-only (Xcode project, Info.plist and build settings, entitlements, PrivacyInfo.xcprivacy, -Podfile.lock, Package.resolved, Cartfile, Gradle files and version catalogs, AndroidManifest.xml, package.json, +again. On Google Play a policy problem can mean a blocked update, a removal or a strike on the account. Most of the +usual ones are visible in the project long before that. `storebound scan` reads the project itself, offline and +read-only (Xcode project, Info.plist and build settings, entitlements, PrivacyInfo.xcprivacy, Podfile.lock, +Package.resolved, Cartfile, Gradle files and version catalogs, AndroidManifest.xml (and the merged manifest of a local +build), res/xml and strings.xml, CMake / ndk-build files, Unity ProjectVersion.txt, package.json, Expo app.json, capacitor.config, Cordova config.xml, pubspec, Unity Packages/manifest.json, ProjectSettings and External Dependency Manager files, Godot export presets), plus your config and listing files. It works out the stack and the SDKs (ads, analytics, attribution, crash, sign-in, payments, push, with versions and the file:line they come @@ -129,39 +131,55 @@ questions). The MCP tool `scan` is read-only and cannot write; `validate` includ app shows them on the Checks tab. A finding you decided is fine goes into the config with its reason: `scan: { ignore: [{ rule: 'demo-account', reason: '...' }] }`. -| rule | App Store guideline / Play policy | what scan proves | -|---|---|---| -| `demo-account`, `play-app-access` | 2.1(a), Play App access | a sign-in (config, auth SDKs, sign-in code) without `reviewAccess` or without the demo account in `.storebound/` | -| `account-deletion`, `play-deletion-url` | 5.1.1(v), Play account deletion | sign-up or social login without a deletion path in code or `accounts.inApp`; no `accounts.deletionUrl` | -| `login-services` | 4.8 | Google / Facebook / other third-party login without Sign in with Apple or another equivalent option | -| `restore-purchases`, `external-purchase` | 3.1.1 | non-consumables or subscriptions without a restore path; card / PayPal SDKs next to IAP; "buy on our website" | -| `subscription-info` | 3.1.2(c), 3.1.2 | no Terms of Use URL, no Terms link or renewal wording in the description, no legal links or "Manage subscription" in the app | -| `att` | 5.1.2(i) | tracking-capable SDKs or IDFA without ATT; the prompt without its purpose string; the string without a prompt | -| `purpose-strings`, `unused-permission` | 5.1.1(ii), 5.1.1(iv), ITMS-90683 | a used permission without its NS*UsageDescription; empty or vague strings; declared but unused | -| `privacy-manifest` | ITMS-91053 / 91061 | no PrivacyInfo.xcprivacy, required-reason APIs not declared, SDKs older than their first manifest version | -| `privacy-policy-link`, `privacy-labels` | 5.1.1(i), 5.1.2, Play Data safety | data collection without a privacy link in the app; SDK data types missing from `dataSafety` | -| `other-platforms` | 2.3.10 | "Android", "Google Play" and other stores in the App Store text or screenshot captions | -| `metadata-keywords`, `kids-terms` | 2.3.7, 2.3.8 | other apps' names, prices and "best / #1" in name, subtitle or keywords; keyword lists; "For Kids" outside the Kids Category | -| `placeholder-text` | 2.1(a), Play Metadata | lorem ipsum, TODO, template lines in the listings | -| `min-functionality` | 4.2 | Capacitor `server.url` / Cordova `` on a remote site; a few native files around a remote WKWebView | -| `deprecated-api`, `private-api` | 2.5.1 (ITMS-90809) | UIWebView; `App-Prefs:` / `prefs:root` URL schemes | -| `ipv6`, `ats` | 2.5.5, App Transport Security | IPv4 literals in server URLs; NSAllowsArbitraryLoads | -| `export-compliance` | export compliance | no ITSAppUsesNonExemptEncryption and no `apple.usesNonExemptEncryption`, or the two disagree (never guessed) | -| `kids-ads` | 1.3, Play Families | a Kids Category age band with third-party ads or analytics SDKs | -| `review-prompt` | 5.6.1, 3.2.2(x) / 5.6.3 | a custom "rate us" prompt without the system API; rewards for ratings | -| `play-target-sdk` | Play target API level | below API 36 (Wear OS / Automotive 35, TV / XR 34) for new apps and updates since 2026-08-31 | -| `play-fgs`, `play-exact-alarm`, `play-query-all-packages`, `play-sms-call-log` | Play permissions policies | foreground services without a type or its permission (and the Console declaration); USE_EXACT_ALARM; QUERY_ALL_PACKAGES; SMS and call log permissions | -| `play-package-name` | Play Console upload | the reserved `com.example` prefix | +| rule | App Store | Google Play | what scan proves | +|---|---|---|---| +| `demo-account`, `play-app-access` | 2.1(a) | App access | a sign-in (config, auth SDKs, sign-in code) without `reviewAccess` or without the demo account in `.storebound/` | +| `account-deletion`, `play-deletion-url` | 5.1.1(v) | User Data: account deletion | sign-up or social login without a deletion path in code or `accounts.inApp`; no `accounts.deletionUrl` | +| `login-services` | 4.8 | | Google / Facebook / other third-party login without Sign in with Apple or another equivalent option | +| `restore-purchases`, `external-purchase`, `play-payments` | 3.1.1 | Payments | non-consumables or subscriptions without a restore path; card / PayPal SDKs next to in-app products; "buy on our website" (Play: unless `play.billingPrograms` lists user choice billing or external offers) | +| `subscription-info` | 3.1.2(c), 3.1.2 | | no Terms of Use URL, no Terms link or renewal wording in the description, no legal links or "Manage subscription" in the app | +| `att` | 5.1.2(i) | | tracking-capable SDKs or IDFA without ATT; the prompt without its purpose string; the string without a prompt | +| `purpose-strings`, `unused-permission` | 5.1.1(ii), 5.1.1(iv), ITMS-90683 | | a used permission without its NS*UsageDescription; empty or vague strings; declared but unused | +| `privacy-manifest` | ITMS-91053 / 91061 | | no PrivacyInfo.xcprivacy, required-reason APIs not declared, SDKs older than their first manifest version | +| `privacy-policy-link`, `play-privacy-policy` | 5.1.1(i) | User Data: privacy policy | no privacy link in the app's sources (Play: every app; medium when it collects data), an `http://` link | +| `privacy-labels` | 5.1.2 | User Data: Data safety | SDK data types missing from `dataSafety`; Play also: an answer narrower than the SDK's disclosure (purposes, sharing), SDKs with no `dataSafety` at all | +| `play-prominent-disclosure` | | User Data: prominent disclosure, Location permissions | background location without a disclosure that says "location" and "background"; location, contacts, calendar or phone number access without any disclosure or rationale text in sources or `strings.xml` | +| `play-background-location`, `play-photo-video`, `play-all-files-access`, `play-accessibility`, `play-install-packages`, `play-health-connect`, `play-full-screen-intent`, `play-vpn` | | Location permissions, Photo and Video Permissions, All files access, AccessibilityService API, REQUEST_INSTALL_PACKAGES, Health Connect, Full-screen intent, VpnService | the restricted permission or service in the manifest (or the merged manifest of a local build), each with the core-use test and the Play Console declaration it needs; `isAccessibilityTool` lowers the accessibility finding to medium | +| `play-fgs`, `play-exact-alarm`, `play-query-all-packages`, `play-sms-call-log` | | Foreground service types, exact alarms, package visibility, SMS and Call Log | foreground services without a type or its permission (and the Console declaration); USE_EXACT_ALARM; QUERY_ALL_PACKAGES; SMS and call log permissions | +| `kids-ads`, `play-families-ads`, `play-families-ad-id`, `play-families-location` | 1.3 | Families | a Kids Category age band with third-party ads or analytics SDKs; `play.targetAges` under 13 with an ad SDK that is not Families self-certified (or older than its certified version), the AD_ID permission in a child-only app (mixed audience: ad / attribution SDKs need child-directed treatment), location in a child-only app | +| `play-ad-id` | | Advertising ID | targetSdk 33+ with ad / attribution SDKs and no AD_ID permission (medium when the merged manifest proves it is missing; Google Mobile Ads adds it itself) | +| `play-16kb` | | 16 KB page sizes (updates blocked from 2027-02-01) | Unity before 6000.0.38f1 / 2022.3.56f1 / 2021.3.48f1, React Native before 0.77, NDK before r28 for the app's own C/C++ without the 16 KB flags, AGP before 8.5.1 with uncompressed native libraries; else prebuilt `.so` files to check | +| `play-ads-launch` | | Ads, Better Ads Experiences | an interstitial shown from `onCreate` of the launcher activity (Android native; other engines: review-only) | +| `play-testing-requirement` | | Testing for new personal accounts | `play.accountType: 'personal'` created after 2023-11-13 (12 testers, 14 days of closed testing before production); low when the account type is not set | +| `other-platforms` | 2.3.10 | | "Android", "Google Play" and other stores in the App Store text or screenshot captions | +| `metadata-keywords`, `kids-terms`, `play-metadata` | 2.3.7, 2.3.8 | Metadata | other apps' names, prices and "best / #1" in name, subtitle or keywords; keyword lists; "For Kids" outside the Kids Category. Play title over 30 characters, emoji, ALL CAPS, rank / price / promotion terms; other apps in the title or short description; repeated keywords or keyword lists in the full description | +| `play-impersonation` | | Impersonation | a well-known brand in the package name or app name (low: a check, not a verdict) | +| `placeholder-text` | 2.1(a) | Metadata | lorem ipsum, TODO, template lines in the listings | +| `min-functionality` | 4.2 | | Capacitor `server.url` / Cordova `` on a remote site; a few native files around a remote WKWebView | +| `deprecated-api`, `private-api` | 2.5.1 (ITMS-90809) | | UIWebView; `App-Prefs:` / `prefs:root` URL schemes | +| `ipv6`, `ats` | 2.5.5, App Transport Security | | IPv4 literals in server URLs; NSAllowsArbitraryLoads | +| `export-compliance` | export compliance | | no ITSAppUsesNonExemptEncryption and no `apple.usesNonExemptEncryption`, or the two disagree (never guessed) | +| `review-prompt` | 5.6.1, 3.2.2(x) / 5.6.3 | | a custom "rate us" prompt without the system API; rewards for ratings | +| `play-target-sdk` | | Target API level | below API 36 (Wear OS / Automotive 35, TV / XR 34) for new apps and updates since 2026-08-31 | +| `play-package-name` | | Play Console upload | the reserved `com.example` prefix | -Rules cite Apple's App Review Guidelines and the Play policy pages they come from (checked 2026-10-11, in the code -comments of `cli/lib/scan/rules.ts`); the SDK table with each vendor's data disclosure page is `cli/lib/scan/sdks.ts`. -Merged-manifest permissions that libraries add at build time are outside the scan (it says so). +Rules cite Apple's App Review Guidelines and the Play Policy Center / Play Console Help pages they come from (checked +2026-10-11, in the code comments of `cli/lib/scan/rules.ts` and `cli/lib/scan/play-rules.ts`); the SDK table with each +vendor's data disclosure page and Google's Families self-certified ads SDK list is `cli/lib/scan/sdks.ts`. Play config +the rules read: `play.targetAges` (Target audience age groups), `play.accountType` / `play.accountCreated`, and +`play.billingPrograms`. When the project was built locally, scan also reads the merged manifest under +`build/intermediates` (the permissions libraries add); otherwise it says that it could not. Not a rule because no Play +policy page covers it: device admin apps (BIND_DEVICE_ADMIN); not a policy at all: Play Integrity / anti-tamper. **Checked at review, not by scan** (no file shows them): crashes and hangs on the reviewer's device (2.1, `store-health`), links that are dead at review time (`validate` checks the configured URLs), screenshots and descriptions that do not match the app (2.3, `store-screenshots`), unfinished UI (4.0), "too simple" and spam / template apps (4.2, 4.3, `portfolio-originality`), IAPs that fail in the sandbox (2.1(b), `store-iap-setup`), the content of the privacy policy -(`privacy-policy`), local law (5.2). The `review-rejections` skill covers what to do when one of these comes back. +(`privacy-policy`), local law (5.2). On Google Play: whether a restricted permission really serves the app's core +purpose (the Console declaration and its video decide), the wording and timing of a prominent disclosure, ad +placements in Unity, Flutter or React Native code, the Health apps declaration answers, and the alignment inside a +prebuilt `.so` (scan lists them; `zipalign -c -P 16` and `check_elf_alignment.sh` check the built app). The +`review-rejections` skill covers what to do when one of these comes back. ## 5-minute quick start diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts index dab9d1b5..da1ded03 100644 --- a/apps/desktop/src/i18n/en.ts +++ b/apps/desktop/src/i18n/en.ts @@ -400,7 +400,7 @@ export const en = { 'checks.scanSub': 'Offline scan of the project files: guideline, evidence, fix', 'checks.scanAgain': 'Scan again', 'checks.scanClean': 'No rejection risks found', - 'checks.scanCleanText': 'Nothing in the project files, config or listings matches a known App Store or Google Play rejection.', + 'checks.scanCleanText': 'Nothing in the project files, config or listings matches a known App Store rejection or Google Play policy issue.', 'checks.scanSdks': 'SDKs: {list}', 'checks.scanAsk': '{count} declaration answers only you can give', 'checks.scanAsk_one': '1 declaration answer only you can give', diff --git a/apps/desktop/src/i18n/tr.ts b/apps/desktop/src/i18n/tr.ts index f52e84a4..8bf2f36d 100644 --- a/apps/desktop/src/i18n/tr.ts +++ b/apps/desktop/src/i18n/tr.ts @@ -402,7 +402,7 @@ export const tr: Record = { 'checks.scanSub': 'Proje dosyalarının çevrimdışı taraması: kural, kanıt, çözüm', 'checks.scanAgain': 'Yeniden tara', 'checks.scanClean': 'Ret riski bulunmadı', - 'checks.scanCleanText': 'Proje dosyalarında, ayarda ve mağaza metinlerinde bilinen bir App Store veya Google Play reddine uyan bir şey yok.', + 'checks.scanCleanText': 'Proje dosyalarında, ayarda ve mağaza metinlerinde bilinen bir App Store reddine veya Google Play politika sorununa uyan bir şey yok.', 'checks.scanSdks': 'SDK\'lar: {list}', 'checks.scanAsk': 'Yalnızca senin cevaplayabileceğin {count} beyan sorusu', 'checks.scanAsk_one': 'Yalnızca senin cevaplayabileceğin 1 beyan sorusu', diff --git a/cli/lib/config.ts b/cli/lib/config.ts index 37793fdd..e8fe3153 100644 --- a/cli/lib/config.ts +++ b/cli/lib/config.ts @@ -414,6 +414,11 @@ export interface SubscriptionGroup { subscriptions: Subscription[]; } +/** Play target audience age groups (App content > Target audience and content). */ +export type PlayAgeGroup = '0-5' | '6-8' | '9-12' | '13-15' | '16-17' | '18+'; +export const PLAY_AGE_GROUPS: readonly PlayAgeGroup[] = ['0-5', '6-8', '9-12', '13-15', '16-17', '18+']; +export const PLAY_BILLING_PROGRAMS = ['user-choice-billing', 'alternative-billing', 'external-offers', 'external-content-links'] as const; + export interface ShipConfig { app: { name: string; @@ -444,6 +449,17 @@ export interface ShipConfig { /** Cloud Storage bucket of the Play Console report exports, e.g. "pubsite_prod_rev_" (Play Console > * Download reports > Statistics > Copy Cloud Storage URI). Used by `storebound analytics snapshot`. */ reportsBucket?: string; + /** Play Console > App content > Target audience and content: the age groups you select. Any group under 13 puts + * the app under the Families policy (`storebound scan` checks ad SDKs, the advertising ID and location for it). */ + targetAges?: PlayAgeGroup[]; + /** Developer account type. New personal accounts (created after 2023-11-13) must run a closed test with at least + * 12 opted-in testers for 14 days before they can apply for production (`storebound scan` reminds you). */ + accountType?: 'personal' | 'organization'; + /** When the Play developer account was created (YYYY-MM-DD), for the personal-account testing requirement. */ + accountCreated?: string; + /** Play billing programs the app is enrolled in that allow another payment method next to Play Billing for + * digital goods (user choice billing, alternative billing only, external offers / external content links). */ + billingPrograms?: ('user-choice-billing' | 'alternative-billing' | 'external-offers' | 'external-content-links')[]; }; apple?: { bundleId: string; appId?: string; primaryLocale?: string; listing?: string; info?: AppleAppInfo; reviewShots?: string; @@ -554,6 +570,12 @@ export function validateConfig(c: unknown): string[] { e.push('play.video: a plain YouTube video URL (https://www.youtube.com/watch?v=... or https://youtu.be/...), no playlist, channel or extra parameters'); if (cfg.play?.reportsBucket && !/^(gs:\/\/)?pubsite_prod(_rev)?_\d+\/?$/.test(cfg.play.reportsBucket)) e.push('play.reportsBucket: the Play reports bucket, e.g. "pubsite_prod_rev_" (Play Console > Download reports > Copy Cloud Storage URI)'); + if (cfg.play?.targetAges !== undefined && !(Array.isArray(cfg.play.targetAges) && cfg.play.targetAges.length && cfg.play.targetAges.every(a => PLAY_AGE_GROUPS.includes(a)))) + e.push(`play.targetAges: a list of ${PLAY_AGE_GROUPS.join(' | ')}`); + if (cfg.play?.accountType !== undefined && cfg.play.accountType !== 'personal' && cfg.play.accountType !== 'organization') e.push('play.accountType: personal | organization'); + if (cfg.play?.accountCreated !== undefined && !/^\d{4}-\d{2}-\d{2}$/.test(cfg.play.accountCreated)) e.push('play.accountCreated: a date, YYYY-MM-DD'); + if (cfg.play?.billingPrograms !== undefined && !(Array.isArray(cfg.play.billingPrograms) && cfg.play.billingPrograms.every(b => (PLAY_BILLING_PROGRAMS as readonly string[]).includes(b)))) + e.push(`play.billingPrograms: a list of ${PLAY_BILLING_PROGRAMS.join(' | ')}`); if (cfg.apple) { if (!ID_RE.test(cfg.apple.bundleId ?? '')) e.push('apple.bundleId: not a bundle id (com.example.game)'); if (cfg.apple.appId && !/^\d+$/.test(cfg.apple.appId)) e.push('apple.appId: numeric Apple ID of the app (App Store Connect > App Information)'); diff --git a/cli/lib/scan/index.ts b/cli/lib/scan/index.ts index 894b715a..f20d8470 100644 --- a/cli/lib/scan/index.ts +++ b/cli/lib/scan/index.ts @@ -51,11 +51,18 @@ export async function runScan(dir: string, o: { config?: string } = {}): Promise }; const configFile = configPath ? { path: rel(configPath), text: readFileSync(configPath, 'utf8') } : null; const declarations = proposeDeclarations(facts, config, configFile); - const findings = scanRules({ facts, config, configFile, listings, demoAccount: !!reviewDemoAccount(dir), labelGaps: declarations.labelGaps }); + const dataMerges = config?.dataSafety ? declarations.diff.filter(d => d.change === 'merge' && d.before).map(d => { + const b = d.before!; + const missing = [...d.after.collect.filter(x => !b.collect.includes(x)).map(x => `collected for ${x}`), ...(d.after.shared && !b.shared ? ['shared'] : []), + ...(d.after.share ?? []).filter(x => !(b.share ?? []).includes(x)).map(x => `shared for ${x}`)]; + return { type: d.type, missing: [...new Set(missing)].join(', '), evidence: d.evidence }; + }).filter(d => d.missing) : []; + const findings = scanRules({ facts, config, configFile, listings, demoAccount: !!reviewDemoAccount(dir), labelGaps: declarations.labelGaps, dataMerges }); const counts = { blocker: 0, high: 0, medium: 0, low: 0, accepted: 0 }; for (const f of findings) { if (f.accepted) counts.accepted++; else counts[f.severity]++; } const notes: string[] = []; - if (facts.android && facts.androidInfo.manifests.length) notes.push('Android: libraries add permissions when the manifest is merged; check the merged manifest (Android Studio > Merged Manifest, or the AAB) too.'); + if (facts.android && facts.androidInfo.mergedManifest) notes.push(`Android: permissions include the merged manifest of the last local build (${facts.androidInfo.mergedManifest}); rebuild after dependency changes.`); + else if (facts.android && facts.androidInfo.manifests.length) notes.push('Android: libraries add permissions when the manifest is merged and no local build output (build/intermediates) was found; check the merged manifest (Android Studio > Merged Manifest, or the AAB) too.'); if (facts.ios && !facts.plistSources.length) notes.push('iOS: no Info.plist settings found (generated at build time?): purpose string, ATS and export compliance checks were skipped.'); if (!facts.sources.length) notes.push('No app source files found: code checks (sign-in, deletion, restore, ATT prompt) could not run.'); const report: ScanReport = { diff --git a/cli/lib/scan/play-rules.ts b/cli/lib/scan/play-rules.ts new file mode 100644 index 00000000..56aaa4d5 --- /dev/null +++ b/cli/lib/scan/play-rules.ts @@ -0,0 +1,429 @@ +// Google Play policy rules for `storebound scan` (rejections, update blocks, suspensions and policy strikes), next to +// the App Store rules in rules.ts. Pure, like rules.ts: project facts + config + listings in, findings out. A rule only +// reports what a file or the config proves; where the policy turns on something no file shows (the app's core purpose, +// what happens at runtime) the finding says what to check and which Play Console declaration it needs. +// +// Sources, each fetched live and checked 2026-10-11 (Play Console Help / Policy Center, developer.android.com): +// - Permissions and APIs that Access Sensitive Information: support.google.com/googleplay/android-developer/answer/9888170 +// (index of the restricted permissions below). +// - Background location: answer/9799150 "Understanding location in the background permissions": core feature only, +// App content > Sensitive app permissions > Location permissions declaration with a video (30 s or less), a +// prominent disclosure before the runtime prompt that says "location" and "background" / "when the app is closed". +// - Photo and video permissions: answer/14115180: READ_MEDIA_IMAGES / READ_MEDIA_VIDEO only when the system photo +// picker is not enough for the app's core purpose (gallery-type apps), with a declaration; enforced since 2025-05-28. +// - All files access: answer/10467955: MANAGE_EXTERNAL_STORAGE only for file managers, backup and restore, +// anti-virus, document management, on-device search, disk encryption, device migration; declaration form. +// - AccessibilityService API: answer/10964491: isAccessibilityTool only for tools for people with disabilities; every +// other use needs an in-app disclosure, affirmative consent and the declaration (with a video). +// - REQUEST_INSTALL_PACKAGES: answer/12085295: core function must be sending / receiving packages and user-initiated +// installs; Permissions Declaration Form. +// - Health Connect: answer/12991134 (android.permission.health.*: each permission justified, permitted use cases, +// privacy policy) and the Health apps declaration every app completes: answer/14738291. +// - Full-screen intent: answer/13392821: on Android 14+ granted by default only to calling and alarm apps; App +// content declaration since 2024-05-31; other apps ask the user and handle a denial. +// - VpnService: answer/12564964: VPN as the core function (or the listed exceptions), disclosure + consent, declaration. +// - Device admin (BIND_DEVICE_ADMIN): no Play policy page covers it (checked the pages above, Device and Network Abuse +// answer/9888379 and User Data answer/10144311): no rule, nothing invented. +// - User Data: answer/10144311: prominent disclosure in the app, during normal use, right before the runtime request, +// describing the data and its use (not only in the privacy policy); a privacy policy for every app, in Play Console +// and inside the app; Data safety must include what SDKs collect. +// - Families: answer/9893335 (only Families Self-Certified Ads SDKs for children; child-only apps do not transmit the +// advertising ID and should not request AD_ID on API 33+; child-only apps may not request location) and the +// certified list answer/9859768 (in sdks.ts `families`; AppLovin left the program, Meta Audience Network is not on it). +// - Advertising ID: answer/6048248: apps targeting Android 13+ that use the advertising ID declare +// com.google.android.gms.permission.AD_ID (Google Mobile Ads merges it from its own manifest). +// - 16 KB page sizes: developer.android.com/guide/practices/page-sizes: apps targeting Android 15+ must support 16 KB +// pages on 64-bit devices; from 2027-02-01 updates that don't cannot be released. AGP 8.5.1+ zip-aligns uncompressed +// .so files (older: useLegacyPackaging), NDK r28+ aligns by default (r27 and older: flags). Unity: 6000.0.38f1, +// 2022.3.56f1, 2021.3.48f1, 6000.1+ (discussions.unity.com/t/info-unity-engine-support-for-16-kb-memory-page-sizes-android-15/1589588). +// React Native: 0.77 (reactnative.dev/blog/2025/01/21/version-0.77). Flutter: no official version found, not checked. +// - Testing for new personal developer accounts: answer/14151465: accounts created after 2023-11-13 run a closed test +// with at least 12 opted-in testers for 14 days in a row before applying for production. +// - Metadata: answer/9898842: title 30 characters or less; no emoji, emoticons or repeated special characters; no +// rank / performance / price / promotion / Play program terms ("#1", "best", "top", "popular", "free", "new", "sale", +// "% off") in the title, icon or developer name; avoid ALL CAPS unless it is the brand; no repeated or unrelated +// keywords, no comparisons with other apps, no other brands without permission. +// - Ads: answer/9857753 (no interstitials that show unexpectedly, before the splash screen or while the user does +// something else) and Better Ads Experiences answer/12271244 (apps without a splash screen wait for the home screen). +// Statically visible: an interstitial shown from the launcher activity's onCreate (Android native). Unity Start(), +// Flutter and React Native launch paths are not reliable from files: review-only. +// - Payments: answer/9858738 (Play Billing for digital goods; physical goods and services exempt; no steering outside +// user choice billing answer/13821247, external offers answer/14372887, US external content links answer/16470497). +// - Impersonation: answer/9888374 (don't imply a relation with someone you are not, e.g. in the title or developer +// name). The brand list below is storebound's own short list of well-known app brands, reported as low "check". +// Play Integrity / anti-tamper is not a policy: no rule. +import { PLAY_AGE_GROUPS } from '../config'; +import { allSubscriptions } from '../subscriptions'; +import { grep, type Hit, type ProjectFacts } from './project'; +import type { ScanFinding, ScanInput } from './rules'; +import { versionAtLeast } from './sdks'; + +const PLAY = 'https://support.google.com/googleplay/android-developer/answer/'; +export const PLAY_REFS = { + sensitive: `${PLAY}9888170`, backgroundLocation: `${PLAY}9799150`, photoVideo: `${PLAY}14115180`, allFiles: `${PLAY}10467955`, + accessibility: `${PLAY}10964491`, installPackages: `${PLAY}12085295`, healthConnect: `${PLAY}12991134`, healthDeclaration: `${PLAY}14738291`, + fullScreenIntent: `${PLAY}13392821`, vpn: `${PLAY}12564964`, userData: `${PLAY}10144311`, families: `${PLAY}9893335`, familiesSdks: `${PLAY}9859768`, + adId: `${PLAY}6048248`, pageSize: 'https://developer.android.com/guide/practices/page-sizes', testing: `${PLAY}14151465`, metadata: `${PLAY}9898842`, + ads: `${PLAY}9857753`, betterAds: `${PLAY}12271244`, payments: `${PLAY}9858738`, impersonation: `${PLAY}9888374`, +} as const; +/** From this date Play refuses updates that don't support 16 KB pages (developer.android.com/guide/practices/page-sizes). */ +export const PAGE_SIZE_DEADLINE = '2027-02-01'; +/** Personal accounts created after this date have the closed-testing requirement (answer/14151465). */ +export const PERSONAL_TESTING_SINCE = '2023-11-13'; +export const PERSONAL_TESTING = { testers: 12, days: 14 } as const; +/** First Unity version of each stream with 16 KB page size support (Unity forum post above); older streams have none. */ +export const UNITY_16KB: Record = { '2021.3': '2021.3.48f1', '2022.3': '2022.3.56f1', '6000.0': '6000.0.38f1' }; +const AD_ID = 'com.google.android.gms.permission.AD_ID'; +const BRANDS = ['instagram', 'tiktok', 'whatsapp', 'facebook', 'snapchat', 'youtube', 'netflix', 'spotify', 'telegram', 'pinterest', 'chatgpt', 'openai', + 'minecraft', 'roblox', 'fortnite', 'pubg', 'pokemon', 'duolingo', 'gmail', 'google', 'playstation', 'xbox', 'nintendo']; +const OTHER_APPS = ['instagram', 'tiktok', 'whatsapp', 'facebook', 'snapchat', 'youtube', 'netflix', 'spotify', 'telegram', 'messenger', 'pinterest', 'uber', 'airbnb', + 'chatgpt', 'openai', 'minecraft', 'roblox', 'fortnite', 'pubg', 'candy crush', 'clash of clans', 'pokemon', 'pokémon', 'among us', 'subway surfers', 'temple run', + 'angry birds', 'tetris', 'wordle', 'duolingo', 'gmail', 'google maps', 'waze', 'shazam', 'tinder', 'evernote', 'photoshop', 'capcut']; +const CLAIMS = /#\s?1\b|\bno\.? ?1\b|\bnumber one\b|\bbest\b|\btop\b|\bpopular\b|app of the year|game of the year|best of play|editor'?s'? choice|\bsale\b|\bdiscount\b|\d+\s?% off|cash ?back|limited time|\$\d/i; +/** "free" and "new" are only examples in the policy as promotion ("free for limited time only") and Play program + * ("New") terms; a plain "free" or "new" can be part of a real name, so they are a low "check". */ +const SOFT_CLAIMS = /\bfree\b|\bnew\b/i; +const EMOJI = /\p{Extended_Pictographic}|[:;]-?[)(DP]|\(\s*[╯°□・ω^]+|([!?*★☆♥✓✔•~_=+|-])\1{1,}/u; +const DISCLOSURE = /shouldShowRequestPermissionRationale|PermissionRationale|prominent[_ ]?disclosure|data[_ ]?disclosure|\b(collects?|transmits?|syncs?|stores?|shares?|uses?)\b[^"<\n]{0,80}\b(location|contacts?|calendar|phone numbers?)\b|\b(location|contacts?|calendar)\b[^"<\n]{0,80}\b(collected|transmitted|synced|stored|shared|used)\b/i; +const BACKGROUND_DISCLOSURE = /location[^"<\n]{0,160}(background|when the app is closed|not in use|always in use)|(background|when the app is closed|not in use|always in use)[^"<\n]{0,160}location/i; +const EXTERNAL_BUY = /\b(buy|subscribe|purchase|upgrade|pay)\b[^.\n]{0,40}\b(on|at|via|from) (our )?(website|web ?site|web|site)\b/i; +const SENSITIVE_DATA: Record = { + ACCESS_FINE_LOCATION: 'location', ACCESS_COARSE_LOCATION: 'location', ACCESS_BACKGROUND_LOCATION: 'location', READ_CONTACTS: 'contacts', + READ_CALENDAR: 'calendar', READ_PHONE_NUMBERS: 'phone numbers', +}; + +type Add = (f: Omit & { ref: string }) => void; +export interface PlayCtx { + add: Add; + cfg: (needle: string | RegExp, text?: string) => Hit[]; + sdkHits: (pred: (s: ProjectFacts['sdks'][number]) => boolean) => Hit[]; + listingHits: (file: { path: string; text: string } | undefined, re: RegExp, o?: { fenced?: boolean; field?: RegExp }) => Hit[]; + /** Account creation evidence (rules.ts), restorable products / subscriptions, payment SDKs. */ + creates: Hit[]; + restorable: Hit[]; + paySdk: Hit[]; +} + +const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +const permName = (n: string) => n.replace(/^android\.permission\./, ''); +const ev = (x: { at: { file: string; line: number } }, text: string): Hit => ({ ...x.at, text }); + +/** Text of the first fenced block under every heading matching `field`. */ +function fieldBlocks(file: { path: string; text: string } | undefined, field: RegExp): { at: Hit; text: string }[] { + if (!file) return []; + const out: { at: Hit; text: string }[] = []; + const lines = file.text.split('\n'); + for (let i = 0; i < lines.length; i++) { + if (!/^###\s/.test(lines[i]!) || !field.test(lines[i]!.slice(4))) continue; + let j = i + 1; + while (j < lines.length && !/^```/.test(lines[j]!) && !/^##/.test(lines[j]!)) j++; + if (j >= lines.length || !/^```/.test(lines[j]!)) continue; + let k = j + 1; + while (k < lines.length && !/^```/.test(lines[k]!)) k++; + out.push({ at: { file: file.path, line: j + 2, text: (lines[j + 1] ?? '').trim().slice(0, 160) }, text: lines.slice(j + 1, k).join('\n') }); + } + return out; +} + +const STOP = new Set(['app', 'apps', 'game', 'games', 'the', 'and', 'for', 'with', 'your', 'you', 'that', 'this', 'from', 'have', 'are', 'will', 'can', 'all', 'more', 'just', 'into', 'every', 'each', 'one', 'when', 'what', 'they', 'them', 'their', 'our', 'out', 'not', 'any', 'also']); + +export function playRules(inp: ScanInput, x: PlayCtx): void { + const { facts: p, config: c } = inp; + const { add, cfg, sdkHits } = x; + const a = p.androidInfo; + const android = p.android; + const perms = new Map(a.permissions.map(q => [permName(q.name), q] as const)); + const removed = new Map(a.removedPermissions.map(q => [permName(q.name), q] as const)); + const target = a.targetSdk?.value ?? null; + const ages = c?.play?.targetAges ?? []; + const kidsAges = ages.filter(g => PLAY_AGE_GROUPS.indexOf(g) < 3); + const childOnly = ages.length > 0 && kidsAges.length === ages.length; + const mixed = kidsAges.length > 0 && !childOnly; + const textSources = [...p.sources, ...a.strings]; + + // ---- sensitive permissions and APIs (each needs a Play Console declaration) ---- + if (android) { + const bg = perms.get('ACCESS_BACKGROUND_LOCATION'); + if (bg) + add({ rule: 'play-background-location', guideline: 'Play: Location permissions', severity: 'high', title: 'ACCESS_BACKGROUND_LOCATION needs a core feature that uses location in the background, the Location permissions declaration and a video', + evidence: [ev(bg, bg.name)], ref: PLAY_REFS.backgroundLocation, skill: 'store-declarations', + fix: 'Keep it only for one core, user-visible feature (never for ads or analytics alone); fill App content > Sensitive app permissions > Location permissions (one feature, a video of 30 s or less showing the prominent disclosure, the runtime prompt and the feature working in the background), and name the feature in the store description. Otherwise remove it (tools:node="remove" if a library adds it).' }); + const media = ['READ_MEDIA_IMAGES', 'READ_MEDIA_VIDEO'].map(n => perms.get(n)).filter(q => !!q); + if (media.length) + add({ rule: 'play-photo-video', guideline: 'Play: Photo and Video Permissions', severity: 'high', title: `${media.map(q => permName(q.name)).join(' / ')}: only for apps whose core purpose needs broad photo / video access; others use the photo picker`, + evidence: media.map(q => ev(q, q.name)), ref: PLAY_REFS.photoVideo, skill: 'store-declarations', + fix: 'Use the Android photo picker (androidx.activity 1.7.0+ PickVisualMedia, no permission) for one-time or occasional picks and remove the permissions; keep them only for gallery-type core features and fill the Photo and video permissions declaration.' }); + const mes = perms.get('MANAGE_EXTERNAL_STORAGE'); + if (mes) + add({ rule: 'play-all-files-access', guideline: 'Play: All files access', severity: 'high', title: 'MANAGE_EXTERNAL_STORAGE (All files access) is only for file managers, backup, anti-virus, document management, search and similar apps', + evidence: [ev(mes, mes.name)], ref: PLAY_REFS.allFiles, skill: 'store-declarations', + fix: 'Use the Storage Access Framework or MediaStore and remove the permission; apps whose core function needs it fill the All files access declaration and explain why those APIs are not enough.' }); + const acc = a.components.filter(q => q.kind === 'service' && (q.permission === 'android.permission.BIND_ACCESSIBILITY_SERVICE' || q.actions.includes('android.accessibilityservice.AccessibilityService'))); + if (acc.length) { + const tool = a.accessibilityConfigs.find(q => q.isTool); + add({ rule: 'play-accessibility', guideline: 'Play: AccessibilityService API', severity: tool ? 'medium' : 'high', + title: tool ? 'AccessibilityService marked isAccessibilityTool: only for tools whose primary purpose is helping people with disabilities' : `AccessibilityService ${acc[0]!.name} needs an in-app disclosure, affirmative consent and the AccessibilityService declaration`, + evidence: [...acc.slice(0, 2).map(q => ev(q, `service ${q.name}`)), ...(tool ? [ev(tool, 'android:isAccessibilityTool="true"')] : a.accessibilityConfigs.slice(0, 1).map(q => ev(q, 'accessibility-service')))], ref: PLAY_REFS.accessibility, skill: 'store-declarations', + fix: tool ? 'Keep isAccessibilityTool only for screen readers, switch, voice or braille input and similar tools (not automation, antivirus, launchers, cleaners, password managers); otherwise remove it and add the disclosure and consent. Fill the AccessibilityService declaration either way.' + : 'Show a disclosure during normal use that says what the service accesses and why, get an affirmative "accept", keep it separate from other disclosures, and fill the AccessibilityService declaration with a video (open the app, disclosure, accept and decline, the feature). Autonomous AI-style actions through the API are not allowed.' }); + } + const rip = perms.get('REQUEST_INSTALL_PACKAGES'); + if (rip) + add({ rule: 'play-install-packages', guideline: 'Play: REQUEST_INSTALL_PACKAGES', severity: 'high', title: 'REQUEST_INSTALL_PACKAGES is only for apps whose core function is sending or receiving app packages for user-initiated installs', + evidence: [ev(rip, rip.name)], ref: PLAY_REFS.installPackages, skill: 'store-declarations', + fix: 'Remove it (self-updates must go through Play); browsers, file managers, messengers with attachments, backup and enterprise apps keep it and fill the Permissions Declaration Form.' }); + const health = a.permissions.filter(q => /^android\.permission\.health\./.test(q.name)); + if (health.length) + add({ rule: 'play-health-connect', guideline: 'Play: Health Connect permissions', severity: 'high', title: `Health Connect permissions (${health.slice(0, 3).map(q => permName(q.name).replace(/^health\./, '')).join(', ')}${health.length > 3 ? ', ...' : ''}) need a justification for each one and a permitted use case`, + evidence: health.slice(0, 3).map(q => ev(q, q.name)), ref: PLAY_REFS.healthConnect, skill: 'store-declarations', + fix: 'Request only the data types a feature uses, justify each permission in the Health Connect declaration, show the privacy policy in the app, and answer App content > Health apps (answer/14738291). Ads, data sales and child-only apps are not allowed to use it.' }); + const fsi = perms.get('USE_FULL_SCREEN_INTENT'); + if (fsi && (target === null || target >= 34)) + add({ rule: 'play-full-screen-intent', guideline: 'Play: Full-screen intent', severity: 'high', title: 'USE_FULL_SCREEN_INTENT: on Android 14+ only calling and alarm apps get it by default, and every app declares it in Play Console', + evidence: [ev(fsi, fsi.name)], ref: PLAY_REFS.fullScreenIntent, skill: 'store-declarations', + fix: 'Remove it unless the core function is alarms or phone / video calls (an SDK may add it: check the merged manifest); otherwise fill App content > Full-screen intent, ask the user with ACTION_MANAGE_APP_USE_FULL_SCREEN_INTENT and handle a denial. Never for ads.' }); + const vpn = a.components.filter(q => q.kind === 'service' && (q.permission === 'android.permission.BIND_VPN_SERVICE' || q.actions.includes('android.net.VpnService'))); + if (vpn.length) + add({ rule: 'play-vpn', guideline: 'Play: VpnService', severity: 'high', title: `VpnService ${vpn[0]!.name}: only for VPN apps and the listed exceptions, with a disclosure, consent and the VpnService declaration`, + evidence: vpn.slice(0, 2).map(q => ev(q, `service ${q.name}`)), ref: PLAY_REFS.vpn, skill: 'store-declarations', + fix: 'Use VpnService only when it is the core function (or parental control, enterprise, app usage tracking, device security, network tools, browsers); describe it in the listing, encrypt traffic to the tunnel, show an in-app disclosure with affirmative consent, and fill the VpnService declaration (videos of 90 s or less).' }); + } + + // ---- prominent disclosure (User Data) ---- + if (android && (p.sources.length || a.strings.length)) { + const bg = perms.get('ACCESS_BACKGROUND_LOCATION'); + const own = (q: { at: { file: string } }) => !a.mergedManifest || q.at.file !== a.mergedManifest; + if (bg && own(bg) && !grep(textSources, BACKGROUND_DISCLOSURE, 1).length) + add({ rule: 'play-prominent-disclosure', guideline: 'Play: User Data (prominent disclosure)', severity: 'high', title: 'Background location without a prominent disclosure that says "location" and "background" / "when the app is closed"', + evidence: [ev(bg, bg.name)], ref: PLAY_REFS.backgroundLocation, skill: 'store-declarations', + fix: 'Before the runtime prompt, show a dialog during normal use, e.g. " collects location data to enable even when the app is closed or not in use." List every feature that uses it (and ads, if they do). It cannot live only in the privacy policy.' }); + const sensitive = [...perms.entries()].filter(([n, q]) => SENSITIVE_DATA[n] && own(q) && n !== 'ACCESS_BACKGROUND_LOCATION'); + if (sensitive.length && !grep(textSources, DISCLOSURE, 1).length) + add({ rule: 'play-prominent-disclosure', guideline: 'Play: User Data (prominent disclosure)', severity: 'medium', + title: `${[...new Set(sensitive.map(([n]) => SENSITIVE_DATA[n]))].join(', ')} access without a disclosure or rationale text in the app's sources or strings`, + evidence: sensitive.slice(0, 3).map(([, q]) => ev(q, q.name)), ref: PLAY_REFS.userData, skill: 'store-declarations', + fix: 'When people would not expect the collection, show an in-app disclosure right before the permission request that says which data is collected and how it is used or shared (" collects to enable , ."), and ask for an affirmative accept; the privacy policy alone is not enough.' }); + } + + // ---- Data safety: SDK disclosures the config's answers miss (additions are the privacy-labels rule in rules.ts) ---- + for (const g of inp.dataMerges ?? []) + add({ rule: 'privacy-labels', guideline: 'Play: User Data (Data safety)', severity: 'medium', title: `Data safety answer for ${g.type} is narrower than what is detected: ${g.missing}`, evidence: g.evidence.slice(0, 2), + ref: 'https://support.google.com/googleplay/android-developer/answer/10787469', skill: 'store-declarations', + fix: 'Check the SDK\'s Data safety guidance (sdks.ts names the page), widen the answer with `storebound scan --write`, then `storebound play data-safety`.' }); + if (c?.play && !c.dataSafety && p.sdks.some(s => s.sdk.data.length)) + add({ rule: 'privacy-labels', guideline: 'Play: User Data (Data safety)', severity: 'medium', title: 'SDKs that collect data, but the config has no dataSafety answers', evidence: sdkHits(s => s.sdk.data.length > 0).slice(0, 3), + ref: 'https://support.google.com/googleplay/android-developer/answer/10787469', skill: 'store-declarations', + fix: 'Run `storebound scan` and read the declarations proposal, confirm it with each SDK\'s disclosure page, `storebound scan --write`, then `storebound play data-safety`.' }); + + // ---- privacy policy in the app ---- + if (p.sources.length && android) { + const link = grep(textSources, /privacy|gizlilik|datenschutz|confidentialit|privacidad/i, 1); + const url = c?.app.privacyPolicyUrl ? grep(textSources, new RegExp(esc(c.app.privacyPolicyUrl)), 1) : []; + if (!link.length && !url.length) { + const collects = p.sdks.length > 0 || x.creates.length > 0 || [...perms.keys()].some(n => SENSITIVE_DATA[n]); + add({ rule: 'play-privacy-policy', guideline: 'Play: User Data (privacy policy)', severity: collects ? 'medium' : 'low', title: 'No privacy policy link found in the app\'s sources (Play wants it in Play Console and inside the app)', + evidence: [...cfg('privacyPolicyUrl'), ...sdkHits(() => true)].slice(0, 2).concat(p.sources.slice(0, 1).map(s => ({ file: s.path, line: 1, text: 'app sources' }))).slice(0, 3), + ref: PLAY_REFS.userData, skill: 'privacy-policy', + fix: 'Link app.privacyPolicyUrl from inside the app (e.g. Settings > Privacy policy, and the sign-up screen). It must be a public, non-geofenced https page, not a PDF, labelled as a privacy policy.' }); + } + const insecure = grep(textSources, /["'>]http:\/\/[^"'<\s]*privacy/i, 1); + if (insecure.length) + add({ rule: 'play-privacy-policy', guideline: 'Play: User Data (privacy policy)', severity: 'medium', title: 'The in-app privacy policy link uses http://', evidence: insecure, + ref: PLAY_REFS.userData, skill: 'privacy-policy', fix: 'Use the https URL (the same as app.privacyPolicyUrl).' }); + } + + // ---- Families ---- + const adSdks = p.sdks.filter(s => s.sdk.category === 'ads'); + if (kidsAges.length) { + const agesEv = cfg('targetAges'); + for (const s of adSdks) { + const fam = s.sdk.families; + const gradleDep = s.deps.find(d => d.eco === 'gradle' && d.version); + const old = fam?.certified && fam.since && gradleDep ? versionAtLeast(gradleDep.version!, fam.since) === false : false; + if (fam?.certified && !old) continue; + add({ rule: 'play-families-ads', guideline: 'Play: Families policy', severity: 'high', + title: old ? `${s.sdk.name} ${gradleDep!.version} is older than ${fam!.since}, the first Families self-certified version` : `${s.sdk.name} is not a Families Self-Certified Ads SDK (${fam?.note ?? 'not on the list'}), but the target audience includes children`, + evidence: [...sdkHits(q => q.sdk.id === s.sdk.id), ...agesEv].slice(0, 3), ref: PLAY_REFS.familiesSdks, skill: 'ads-mediation-checks', + fix: old ? `Update to ${fam!.since} or newer and turn on child-directed treatment.` : 'Ads shown to children (or users of unknown age) may only come from Families Self-Certified Ads SDKs (AdMob, ironSource / LevelPlay, Unity Ads and others on answer/9859768): remove this SDK and its mediation adapters, or take children out of the target audience.' }); + } + const adIdFromSdk = p.sdks.filter(s => s.sdk.mergesAdId); + const adId = perms.get(AD_ID); + if (childOnly && (target === null || target >= 33) && !removed.has(AD_ID) && (adId || adIdFromSdk.length)) + add({ rule: 'play-families-ad-id', guideline: 'Play: Families policy', severity: 'high', title: 'App only for children with the advertising ID permission (AD_ID): child-only apps must not transmit the advertising ID', + evidence: [...(adId ? [ev(adId, AD_ID)] : sdkHits(s => !!s.sdk.mergesAdId)), ...agesEv].slice(0, 3), ref: PLAY_REFS.families, skill: 'store-declarations', + fix: 'Remove it from the merged manifest: , turn on child-directed treatment in every ad SDK, and answer the Advertising ID declaration accordingly.' }); + else if (mixed && p.sdks.some(s => s.sdk.tracking && (s.sdk.category === 'ads' || s.sdk.category === 'attribution'))) + add({ rule: 'play-families-ad-id', guideline: 'Play: Families policy', severity: 'medium', title: 'Mixed audience with ad / attribution SDKs: no advertising ID or interest-based ads for children or users of unknown age', + evidence: [...sdkHits(s => s.sdk.tracking && (s.sdk.category === 'ads' || s.sdk.category === 'attribution')), ...agesEv].slice(0, 3), ref: PLAY_REFS.families, skill: 'ads-mediation-checks', + fix: 'Add a neutral age screen; for children and unknown ages turn on child-directed treatment (no advertising ID, no personalized ads or remarketing) in every SDK before it starts.' }); + const loc = ['ACCESS_FINE_LOCATION', 'ACCESS_COARSE_LOCATION', 'ACCESS_BACKGROUND_LOCATION'].map(n => perms.get(n)).filter(q => !!q); + if (childOnly && loc.length) + add({ rule: 'play-families-location', guideline: 'Play: Families policy', severity: 'high', title: 'App only for children requests location', evidence: [...loc.slice(0, 2).map(q => ev(q, q.name)), ...agesEv].slice(0, 3), + ref: PLAY_REFS.families, skill: 'store-declarations', fix: 'Remove the location permissions (tools:node="remove" for ones an SDK adds); apps only for children may not request location.' }); + } + + // ---- advertising ID permission (Android 13+) ---- + if (android && !childOnly && (target === null || target >= 33)) { + const users = p.sdks.filter(s => s.sdk.tracking && (s.sdk.category === 'ads' || s.sdk.category === 'attribution')); + if (users.length && !perms.has(AD_ID) && !removed.has(AD_ID) && !users.some(s => s.sdk.mergesAdId)) { + const merged = !!a.mergedManifest; + add({ rule: 'play-ad-id', guideline: 'Play: Advertising ID', severity: merged ? 'medium' : 'low', + title: merged ? `The merged manifest has no AD_ID permission, but ${users.map(s => s.sdk.name).join(', ')} ${users.length > 1 ? 'use' : 'uses'} the advertising ID` : `${users.map(s => s.sdk.name).join(', ')} ${users.length > 1 ? 'use' : 'uses'} the advertising ID: check that the merged manifest declares AD_ID (targetSdk 33+)`, + evidence: [...sdkHits(s => users.includes(s)), ...(merged ? [{ file: a.mergedManifest!, line: 1, text: 'merged AndroidManifest.xml' }] : [])].slice(0, 3), ref: PLAY_REFS.adId, skill: 'store-declarations', + fix: 'Apps targeting Android 13+ that use the advertising ID declare (without it the ID reads as zeros); answer the Advertising ID question in App content the same way.' }); + } + } + + // ---- 16 KB page sizes ---- + if (android) { + const n = p.native; + const ps: { title: string; evidence: Hit[]; fix: string; severity?: 'medium' }[] = []; + if (n.unityVersion) { + const v = n.unityVersion.value; + const stream = /^(\d+\.\d+)/.exec(v)?.[1] ?? ''; + const min = UNITY_16KB[stream]; + const ok = min ? unityPatch(v) >= unityPatch(min) : Number(stream.split('.')[0]) >= 6000; + if (!ok) + ps.push({ title: `Unity ${v} builds without 16 KB page size support (needs ${min ?? '6000.0.38f1, 2022.3.56f1 or 2021.3.48f1 (Extended LTS)'} or newer)`, evidence: [{ ...n.unityVersion.at, text: `m_EditorVersion: ${v}` }], + fix: `Update the editor to ${min ?? 'a supported LTS (6000.0.38f1+, 2022.3.56f1+)'} or newer and rebuild; plugins with their own .so files need 16 KB aligned builds too.` }); + } + const rn = p.deps.find(d => d.eco === 'npm' && d.name === 'react-native' && d.version); + if (rn && versionAtLeast(rn.version!, '0.77') === false) + ps.push({ title: `React Native ${rn.version} is older than 0.77, the first version with full 16 KB page size support`, evidence: [{ file: rn.file, line: rn.line, text: `react-native ${rn.version}` }], + fix: 'Upgrade React Native to 0.77 or newer (and native modules with their own .so files to aligned builds).' }); + const ndkMajor = n.ndkVersion ? Number(/^\d+/.exec(n.ndkVersion.value)?.[0]) : null; + if (n.nativeBuild && ndkMajor !== null && ndkMajor < 28 && !n.flexiblePageSizes) + ps.push({ title: `NDK ${n.ndkVersion!.value} (r${ndkMajor}) does not build 16 KB aligned libraries by default`, evidence: [{ ...n.ndkVersion!.at, text: `ndkVersion ${n.ndkVersion!.value}` }, { ...n.nativeBuild, text: 'native build' }], + fix: `Use NDK r28 or newer, or ${ndkMajor === 27 ? 'set -DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON' : 'add -Wl,-z,max-page-size=16384 -Wl,-z,common-page-size=16384 to the linker flags (and link libc++ statically on r26 and older)'}.` }); + const hasNative = n.libs.length > 0 || !!n.nativeBuild || p.stacks.some(s => s === 'flutter' || s === 'react-native' || s === 'godot'); + const compressed = n.legacyPackaging || (a.extractNativeLibs?.value ? a.extractNativeLibs.at : null); + if (hasNative && n.agp && versionAtLeast(n.agp.value, '8.5.1') === false && !compressed) + ps.push({ title: `Android Gradle Plugin ${n.agp.value} does not 16 KB zip-align uncompressed native libraries (needs 8.5.1+)`, + evidence: [{ ...n.agp.at, text: `AGP ${n.agp.value}` }, ...(a.extractNativeLibs ? [{ ...a.extractNativeLibs.at, text: `android:extractNativeLibs="${a.extractNativeLibs.value}"` }] : [])], + fix: 'Update AGP to 8.5.1 or newer; until then set packaging { jniLibs { useLegacyPackaging = true } } (compressed libraries, bigger install; on AGP 8.0 or lower also android.bundle.enableUncompressedNativeLibs=false in gradle.properties).' }); + const own = n.libs.filter(f => !/(^|\/)(armeabi-v7a|armeabi|x86)\//.test(f)); + if (!ps.length && own.length) + ps.push({ title: `${own.length} prebuilt native librar${own.length === 1 ? 'y' : 'ies'} (.so) in the project: check they are 16 KB aligned`, evidence: own.slice(0, 3).map(f => ({ file: f, line: 1, text: f.split('/').pop()! })), + severity: 'medium', fix: 'Check the built app: zipalign -v -c -P 16 4 app.apk and check_elf_alignment.sh (LOAD segments align 2**14), or APK Analyzer; ask the vendor for an aligned build of any library that fails.' }); + for (const q of ps) + add({ rule: 'play-16kb', guideline: 'Play: 16 KB page sizes', severity: q.severity ?? 'high', + title: `${q.title}; from ${PAGE_SIZE_DEADLINE} Play blocks updates without 16 KB support (apps targeting Android 15+)`, evidence: q.evidence, fix: q.fix, ref: PLAY_REFS.pageSize, skill: 'play-first-release' }); + } + + // ---- new personal developer accounts: closed testing before production ---- + if (c?.play) { + const t = c.play.accountType; + const created = c.play.accountCreated; + if (t === 'personal' && (!created || created > PERSONAL_TESTING_SINCE)) + add({ rule: 'play-testing-requirement', guideline: 'Play: Testing for new personal accounts', severity: 'medium', + title: `Personal developer account${created ? ` created ${created}` : ''}: production needs a closed test with at least ${PERSONAL_TESTING.testers} opted-in testers for ${PERSONAL_TESTING.days} days in a row first`, + evidence: cfg('accountType'), ref: PLAY_REFS.testing, skill: 'play-first-release', + fix: `Start the closed test early (testers opted in for ${PERSONAL_TESTING.days} continuous days), then apply for production access on the Dashboard; accounts created on or before ${PERSONAL_TESTING_SINCE} and organization accounts are exempt. Ignore this when production access is already granted.` }); + else if (!t) + add({ rule: 'play-testing-requirement', guideline: 'Play: Testing for new personal accounts', severity: 'low', + title: `Play account type unknown: new personal accounts need ${PERSONAL_TESTING.testers} testers for ${PERSONAL_TESTING.days} days in a closed test before production`, + evidence: cfg(/play\s*:/), ref: PLAY_REFS.testing, skill: 'play-first-release', + fix: `Set play.accountType ('personal' | 'organization') and play.accountCreated (YYYY-MM-DD) so scan can tell; personal accounts created after ${PERSONAL_TESTING_SINCE} need the closed test.` }); + } + + // ---- Play listing metadata ---- + if (c?.play || inp.listings.play) { + const listing = inp.listings.play; + const titles: Hit[] = fieldBlocks(listing, /\btitle\b/i).map(b => ({ ...b.at, text: b.text.trim() })); + if (!titles.length && c?.app.name) titles.push(...cfg(/\bname\s*:/, c.app.name).map(h => ({ ...h, text: c.app.name }))); + const long = titles.filter(t => [...t.text].length > 30); + if (long.length) + add({ rule: 'play-metadata', guideline: 'Play: Metadata', severity: 'high', title: `Play title longer than 30 characters: "${long[0]!.text}" (${[...long[0]!.text].length})`, evidence: long.slice(0, 2), + ref: PLAY_REFS.metadata, skill: 'aso-basics', fix: 'Shorten the title to 30 characters or less (a "### title" block in store/listing.md, else app.name).' }); + const emoji = titles.filter(t => EMOJI.test(t.text)); + if (emoji.length) + add({ rule: 'play-metadata', guideline: 'Play: Metadata', severity: 'high', title: 'Emoji, emoticons or repeated special characters in the Play title', evidence: emoji.slice(0, 2), + ref: PLAY_REFS.metadata, skill: 'aso-basics', fix: 'Use plain words in the title (and the developer name and icon).' }); + const caps = titles.filter(t => /[A-Z]{4,}/.test(t.text) && t.text === t.text.toUpperCase()); + if (caps.length) + add({ rule: 'play-metadata', guideline: 'Play: Metadata', severity: 'medium', title: `ALL CAPS Play title: "${caps[0]!.text}"`, evidence: caps.slice(0, 2), + ref: PLAY_REFS.metadata, skill: 'aso-basics', fix: 'Write the title in normal case unless the capitals are your registered brand.' }); + const claims = titles.filter(t => CLAIMS.test(t.text)); + if (claims.length) + add({ rule: 'play-metadata', guideline: 'Play: Metadata', severity: 'high', title: 'Rank, performance, price or promotion terms in the Play title ("#1", "best", "top", "popular", "sale", "% off")', evidence: claims.slice(0, 2), + ref: PLAY_REFS.metadata, skill: 'aso-basics', fix: 'Remove claims and promotions from the title (and the icon and developer name); describe what the app does instead.' }); + const soft = titles.filter(t => !CLAIMS.test(t.text) && SOFT_CLAIMS.test(t.text)); + if (soft.length) + add({ rule: 'play-metadata', guideline: 'Play: Metadata', severity: 'low', title: `"Free" or "New" in the Play title: "${soft[0]!.text}"`, evidence: soft.slice(0, 2), + ref: PLAY_REFS.metadata, skill: 'aso-basics', fix: 'Keep it only when it is part of the real name; as a price, promotion or "New" label it is not allowed in the title.' }); + const others = new RegExp(`(^|[^\\p{L}])(${OTHER_APPS.map(esc).join('|')})(?=$|[^\\p{L}])`, 'iu'); + const named = [...titles.filter(t => others.test(t.text)), ...fieldBlocks(listing, /\bshort\b/i).filter(b => others.test(b.text)).map(b => b.at)]; + if (named.length) + add({ rule: 'play-metadata', guideline: 'Play: Metadata', severity: 'medium', title: 'Other apps or brands named in the Play title or short description', evidence: named.slice(0, 2), + ref: PLAY_REFS.metadata, skill: 'aso-basics', fix: 'Remove other apps\' names and comparisons; name a brand only for a real integration you are allowed to mention, and never in a way that implies an endorsement.' }); + for (const b of fieldBlocks(listing, /\bfull\b/i)) { + const words = b.text.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean); + const counts = new Map(); + for (const w of words) if (w.length > 3 && !STOP.has(w)) counts.set(w, (counts.get(w) ?? 0) + 1); + const rep = words.length >= 80 ? [...counts].filter(([, k]) => k >= 6 && k / words.length > 0.03).sort((q, r) => r[1] - q[1]) : []; + const lists = b.text.split('\n').map((l, i) => ({ l, i })).filter(({ l }) => l.split(/[,|]/).length >= 8 && l.split(/[,|]/).every(s => s.trim().split(/\s+/).length <= 3)); + if (rep.length || lists.length) + add({ rule: 'play-metadata', guideline: 'Play: Metadata', severity: 'medium', + title: [rep.length ? `repeated keywords (${rep.slice(0, 3).map(([w, k]) => `"${w}" ${k}x`).join(', ')})` : '', lists.length ? 'a keyword list' : ''].filter(Boolean).join(' and ').replace(/^./, s => s.toUpperCase()) + ' in the full description', + evidence: [...(rep.length ? [b.at] : []), ...(lists.length ? [{ file: b.at.file, line: b.at.line + lists[0]!.i, text: lists[0]!.l.trim().slice(0, 160) }] : [])], ref: PLAY_REFS.metadata, skill: 'aso-basics', + fix: 'Write the description for people: say each thing once, no keyword lists or repeated terms (Play treats them as spam).' }); + } + } + + // ---- ads at app launch (Android native: the launcher activity) ---- + if (android) { + const launcher = a.components.find(q => q.kind === 'activity' && q.categories.includes('android.intent.category.LAUNCHER') && (!a.mergedManifest || q.at.file !== a.mergedManifest)); + const cls = launcher?.name.split('.').pop(); + const file = cls ? p.sources.find(s => /\.(kt|java)$/.test(s.path) && new RegExp(`\\bclass\\s+${esc(cls)}\\b`).test(s.text)) : undefined; + if (file) { + const lines = file.text.split('\n'); + const start = lines.findIndex(l => /\bonCreate\s*\(/.test(l) && !/^\s*(\/\/|\*)/.test(l)); + if (start >= 0) { + const indent = /^\s*/.exec(lines[start]!)![0].length; + let end = start + 1; + while (end < lines.length && !(/\S/.test(lines[end]!) && /^\s*/.exec(lines[end]!)![0].length <= indent && /^\s*(override\s+|public\s+|protected\s+|private\s+|fun\s|void\s|@)/.test(lines[end]!))) end++; + const body = lines.slice(start, end); + const show = body.findIndex(l => /interstitial\w*\??\.show(?:Ad)?\s*\(|showInterstitial\s*\(|IronSource\.showInterstitial|UnityAds\.show\s*\(|\bad\??\.show\s*\(\s*(this|this@\w+|activity|requireActivity\(\))/i.test(l) && !/^\s*(\/\/|\*)/.test(l)); + if (show >= 0 && body.some(l => /interstitial/i.test(l))) + add({ rule: 'play-ads-launch', guideline: 'Play: Ads (Better Ads Experiences)', severity: 'medium', title: `An interstitial is shown from ${cls}.onCreate, the launcher activity (an ad before the app has loaded)`, + evidence: [{ file: file.path, line: start + show + 1, text: body[show]!.trim().slice(0, 160) }, ev(launcher!, `launcher ${launcher!.name}`)], ref: PLAY_REFS.betterAds, skill: 'ads-mediation-checks', + fix: 'Show interstitials only at natural breaks after the app has loaded (after a level or a finished task), never at launch before the home screen or while people are doing something else.' }); + } + } + } + + // ---- payments outside Play Billing ---- + const programs = c?.play?.billingPrograms ?? []; + if (c?.play || android) { + const extPay = sdkHits(s => s.sdk.category === 'external-payments'); + const digital = x.restorable.length || x.paySdk.length || (c?.products?.length ?? 0) > 0 || (c ? allSubscriptions(c.subscriptions).length > 0 : false); + if (extPay.length && digital && !programs.length) + add({ rule: 'play-payments', guideline: 'Play: Payments', severity: 'medium', title: 'A card / PayPal payment SDK next to in-app products: digital goods on Play must use Play Billing', evidence: [...extPay, ...x.restorable].slice(0, 3), + ref: PLAY_REFS.payments, skill: 'store-iap-setup', + fix: 'Sell unlocks, coins, subscriptions and ad removal through Play Billing; keep Stripe / PayPal for physical goods and services. Enrolled in user choice billing, external offers or US external content links? Set play.billingPrograms.' }); + const nonApple = (q: string) => !/\.(swift|m|mm|h)$/.test(q); + const steer = programs.length ? [] : [...x.listingHits(inp.listings.play, EXTERNAL_BUY), ...grep(p.sources, EXTERNAL_BUY, 2, nonApple)]; + if (steer.length && (c?.play || android)) + add({ rule: 'play-payments', guideline: 'Play: Payments', severity: 'medium', title: 'A call to action to buy outside the app (website) in the Play listing or the app', evidence: steer.slice(0, 3), + ref: PLAY_REFS.payments, skill: 'review-rejections', fix: 'Outside the alternative billing and external offers programs, do not lead people to pay for digital content elsewhere; remove the text or enroll and set play.billingPrograms.' }); + } + + // ---- impersonation ---- + if (c?.play) { + const pkg = c.play.packageName.toLowerCase(); + const segs = pkg.split('.'); + const brandIn = (s: string) => BRANDS.find(b => s.split(/[_\d]+/).includes(b) || (b.length >= 6 && s.includes(b))); + const owner = segs[1] ?? ''; + const hitPkg = segs.slice(1).map(brandIn).find(b => b && b !== owner); + const nameRe = new RegExp(`(^|[^\\p{L}])(${BRANDS.map(esc).join('|')})(?=$|[^\\p{L}])`, 'iu'); + const hitName = nameRe.exec(c.app.name)?.[2]; + if ((hitPkg && !brandIn(owner)) || hitName) + add({ rule: 'play-impersonation', guideline: 'Play: Impersonation', severity: 'low', title: `${hitPkg ? `Package name ${c.play.packageName}` : `App name "${c.app.name}"`} contains "${hitPkg ?? hitName}": check that it does not suggest a relation with that brand`, + evidence: [...(hitPkg ? cfg('packageName') : []), ...(hitName ? cfg(/\bname\s*:/) : [])].slice(0, 2), ref: PLAY_REFS.impersonation, skill: 'review-rejections', + fix: 'Don\'t imply that the app is made or endorsed by another company: remove the brand from the name and package (it can\'t change after the first upload), or have written permission ready for an appeal.' }); + } +} + +/** Unity patch number for comparison inside one stream ("2022.3.56f1" -> 56). */ +function unityPatch(v: string): number { return Number(/^\d+\.\d+\.(\d+)/.exec(v)?.[1] ?? 0); } + diff --git a/cli/lib/scan/project.ts b/cli/lib/scan/project.ts index 7a610179..99874b78 100644 --- a/cli/lib/scan/project.ts +++ b/cli/lib/scan/project.ts @@ -16,6 +16,18 @@ export type Stack = 'ios-native' | 'android-native' | 'react-native' | 'expo' | export interface DetectedSdk { sdk: SdkDef; deps: DepRef[] } +export interface AndroidComponent { + kind: 'activity' | 'service' | 'receiver'; + name: string; + /** android:permission (e.g. BIND_ACCESSIBILITY_SERVICE, BIND_VPN_SERVICE, BIND_DEVICE_ADMIN). */ + permission: string | null; + fgsType: string | null; + actions: string[]; + categories: string[]; + meta: string[]; + at: Loc; +} + export interface ProjectFacts { root: string; stacks: Stack[]; @@ -38,6 +50,36 @@ export interface ProjectFacts { /** targetSdk is set by a tool we cannot read (Flutter SDK, Expo SDK, Unity "automatic"). */ targetSdkFrom: string | null; formFactor: 'phone' | 'wear' | 'tv' | 'automotive'; + /** : permissions the app strips from the merged manifest (e.g. AD_ID). */ + removedPermissions: { name: string; at: Loc }[]; + /** Activities, services and receivers with their android:permission, intent-filter actions and meta-data names. */ + components: AndroidComponent[]; + /** */ + extractNativeLibs: { value: boolean; at: Loc } | null; + /** A merged manifest from a local build (build/intermediates), read for the permissions libraries add. */ + mergedManifest: string | null; + /** res/xml accessibility-service configs (android:isAccessibilityTool). */ + accessibilityConfigs: { at: Loc; isTool: boolean }[]; + /** res/values*\/strings.xml (for disclosure texts). */ + strings: { path: string; text: string }[]; + }; + /** Native code and the toolchain versions that decide 16 KB page size support. */ + native: { + /** Prebuilt .so files in the project (jniLibs, Unity Plugins/Android, ...). */ + libs: string[]; + ndkVersion: { value: string; at: Loc } | null; + /** The NDK version is set by a tool (flutter.ndkVersion). */ + ndkFrom: string | null; + /** Android Gradle Plugin version. */ + agp: { value: string; at: Loc } | null; + /** The project builds C / C++ itself (externalNativeBuild, CMakeLists.txt, Android.mk). */ + nativeBuild: Loc | null; + /** ANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON or -Wl,-z,max-page-size=16384 in the native build. */ + flexiblePageSizes: Loc | null; + /** jniLibs.useLegacyPackaging = true (compressed native libraries). */ + legacyPackaging: Loc | null; + /** ProjectSettings/ProjectVersion.txt m_EditorVersion. */ + unityVersion: { value: string; at: Loc } | null; }; /** Capacitor server.url / Cordova pointing at a remote site. */ remoteStart: { url: string; at: Loc } | null; @@ -49,13 +91,14 @@ export interface ProjectFacts { const SKIP_DIRS = new Set(['.git', 'node_modules', 'Pods', 'build', 'Build', 'DerivedData', '.gradle', '.dart_tool', '.build', 'Library', 'Temp', 'Logs', 'obj', 'UserSettings', '.storebound', 'renders', '.idea', '.vscode', '.expo', 'vendor', 'xcuserdata', 'Carthage', '.next', 'coverage', '.godot', - 'intermediates', 'generated', 'outputs', 'tmp', '.cxx', 'fastlane', 'dist', 'www', 'public', 'clips', 'frames', 'fonts']); + 'intermediates', 'generated', 'outputs', 'tmp', '.cxx', 'fastlane', 'dist', 'www', 'public', 'clips', 'frames', 'fonts', '.fvm']); const SRC_EXT = new Set(['.swift', '.m', '.mm', '.h', '.kt', '.java', '.dart', '.js', '.jsx', '.ts', '.tsx', '.cs', '.gd', '.html', '.vue', '.svelte']); const MAX_FILES = 25_000; const MAX_TEXT = 1_500_000; -/** Every file under root (relative paths), skipping build output, dependency folders and VCS data. */ -export function listFiles(root: string): string[] { +/** Every file under root (relative paths), skipping build output, dependency folders and VCS data. Native libraries + * (.so) of any size also go into `bins` when given (they are not read, only listed). */ +export function listFiles(root: string, bins?: string[]): string[] { const out: string[] = []; const walk = (dir: string, depth: number) => { if (depth > 14 || out.length >= MAX_FILES) return; @@ -70,7 +113,10 @@ export function listFiles(root: string): string[] { // compiled frameworks are SDK binaries, not app code if (/\.(xc)?framework$|\.xcassets$|\.bundle$|\.app$|\.dSYM$/.test(n)) continue; walk(p, depth + 1); - } else if (st.size <= MAX_TEXT) out.push(relative(root, p).split(sep).join('/')); + } else { + if (bins && n.endsWith('.so')) bins.push(relative(root, p).split(sep).join('/')); + if (st.size <= MAX_TEXT) out.push(relative(root, p).split(sep).join('/')); + } if (out.length >= MAX_FILES) return; } }; @@ -186,7 +232,8 @@ function versionCatalog(file: string, text: string): DepRef[] { const body = m[1]!; const mod = /module\s*=\s*"([^":]+):([^"]+)"/.exec(body); const grp = /group\s*=\s*"([^"]+)"/.exec(body), nm = /name\s*=\s*"([^"]+)"/.exec(body); - const name = mod ? `${mod[1]}:${mod[2]}` : grp && nm ? `${grp[1]}:${nm[1]}` : null; + const plugin = /\bid\s*=\s*"(com\.android\.(?:application|library))"/.exec(body); + const name = mod ? `${mod[1]}:${mod[2]}` : grp && nm ? `${grp[1]}:${nm[1]}` : plugin ? 'com.android.application' : null; if (!name) continue; const ver = /version\.ref\s*=\s*"([^"]+)"/.exec(body)?.[1]; out.push({ eco: 'gradle', name, version: ver ? versions.get(ver) ?? null : /version\s*=\s*"([^"]+)"/.exec(body)?.[1] ?? null, file, line: lineAt(text, m.index!) }); @@ -238,7 +285,8 @@ const GODOT_KEYS: Record = { }; export function detectProject(root: string): ProjectFacts { - const files = listFiles(root); + const bins: string[] = []; + const files = listFiles(root, bins); const cache = new Map(); const read = (f: string): string => { if (!cache.has(f)) { try { cache.set(f, readFileSync(join(root, f), 'utf8')); } catch { cache.set(f, ''); } } @@ -251,7 +299,9 @@ export function detectProject(root: string): ProjectFacts { const entitlements = new Map(); const privacyManifests: Manifest[] = []; const setKey = (m: Map, key: string, value: unknown, at: Loc) => { if (!m.has(key)) m.set(key, { key, value, at }); }; - const android: ProjectFacts['androidInfo'] = { manifests: [], permissions: [], services: [], targetSdk: null, targetSdkFrom: null, formFactor: 'phone' }; + const android: ProjectFacts['androidInfo'] = { manifests: [], permissions: [], services: [], targetSdk: null, targetSdkFrom: null, formFactor: 'phone', + removedPermissions: [], components: [], extractNativeLibs: null, mergedManifest: null, accessibilityConfigs: [], strings: [] }; + const native: ProjectFacts['native'] = { libs: bins, ndkVersion: null, ndkFrom: null, agp: null, nativeBuild: null, flexiblePageSizes: null, legacyPackaging: null, unityVersion: null }; const sdkHits: { value: number; at: Loc; prio: number }[] = []; let remoteStart: ProjectFacts['remoteStart'] = null; const sources: { path: string; text: string }[] = []; @@ -288,24 +338,31 @@ export function detectProject(root: string): ProjectFacts { for (const m of t.matchAll(/\btargetSdk(?:Version)?\s*(?:=|\s)\s*\(?\s*(\d{2})\b/g)) sdkHits.push({ value: Number(m[1]), at: { file: f, line: lineAt(t, m.index!) }, prio: /(^|\/)app\/|variables\.gradle/.test(f) ? 0 : 1 }); if (/targetSdk(?:Version)?\s*(?:=|\s)\s*flutter\.targetSdkVersion/.test(t)) android.targetSdkFrom = 'the Flutter SDK (flutter.targetSdkVersion)'; + gradleNative(f, t, native, deps); } else if (n === 'libs.versions.toml') { const t = read(f); deps.push(...versionCatalog(f, t)); for (const m of t.matchAll(/^\s*(?:target-?sdk|targetSdk|android-?target-?sdk)\w*\s*=\s*"(\d{2})"/gim)) sdkHits.push({ value: Number(m[1]), at: { file: f, line: lineAt(t, m.index!) }, prio: 0 }); + const nd = /^\s*ndk(?:-?version)?\s*=\s*"(\d+\.[\d.]+)"/im.exec(t); + if (nd && !native.ndkVersion) native.ndkVersion = { value: nd[1]!, at: { file: f, line: lineAt(t, nd.index) } }; } else if (n === 'AndroidManifest.xml' && /(^|\/)src\/main\/AndroidManifest\.xml$|^AndroidManifest\.xml$|Plugins\/Android\/AndroidManifest\.xml$/.test(f) && !testy) { - const t = read(f); android.manifests.push(f); - for (const m of t.matchAll(/]*?)\/?>/g)) { - const name = /android:name="([^"]+)"/.exec(m[1]!)?.[1]; - if (name && !/tools:node="remove"/.test(m[1]!)) android.permissions.push({ name, at: { file: f, line: lineAt(t, m.index!) } }); - } - for (const m of t.matchAll(/]*?)(\/>|>)/g)) { - const name = /android:name="([^"]+)"/.exec(m[1]!)?.[1] ?? '?'; - android.services.push({ name, fgsType: /android:foregroundServiceType="([^"]+)"/.exec(m[1]!)?.[1] ?? null, at: { file: f, line: lineAt(t, m.index!) } }); - } - if (/android\.hardware\.type\.watch/.test(t)) android.formFactor = 'wear'; - else if (/android\.software\.leanback"[^>]*android:required="true"|android:required="true"[^>]*android\.software\.leanback/.test(t)) android.formFactor = 'tv'; - else if (/android\.hardware\.type\.automotive/.test(t)) android.formFactor = 'automotive'; + readManifest(f, read(f), android); + } else if (/\/res\/xml\/[^/]+\.xml$/.test(f) && read(f).includes(']*/.exec(t)!; + android.accessibilityConfigs.push({ at: { file: f, line: lineAt(t, m.index) }, isTool: /android:isAccessibilityTool="true"/.test(m[0]) }); + } else if (n === 'strings.xml' && /(^|\/)res\/values[^/]*\/strings\.xml$/.test(f) && !testy) { + android.strings.push({ path: f, text: read(f) }); + } else if (n === 'CMakeLists.txt' || n === 'Android.mk' || n === 'Application.mk') { + const t = read(f); + if (!native.nativeBuild) native.nativeBuild = { file: f, line: 1 }; + const fl = FLEXIBLE_PAGES.exec(t); + if (fl && !native.flexiblePageSizes) native.flexiblePageSizes = { file: f, line: lineAt(t, fl.index) }; + } else if (n === 'ProjectVersion.txt' && /(^|\/)ProjectSettings\//.test(f)) { + const t = read(f); + const m = /^m_EditorVersion:\s*(\S+)/m.exec(t); + if (m) native.unityVersion = { value: m[1]!, at: { file: f, line: lineAt(t, m.index) } }; } else if (n === 'package.json' && !f.includes('/node_modules/')) { const t = read(f); const d = packageJson(f, t); @@ -402,7 +459,101 @@ export function detectProject(root: string): ProjectFacts { const hits = deps.filter(d => matchesSdk(d, s)); if (hits.length) sdks.push({ sdk: s, deps: hits }); } - return { root, stacks: [...stacks], ios, android: isAndroid, deps, sdks, plist, plistSources, entitlements, privacyManifests, androidInfo: android, remoteStart, sources, scanned: files.length }; + // the Android Gradle Plugin: buildscript classpath, plugins { id(...) version }, or the version catalog + const agp = deps.find(d => (d.name === 'com.android.tools.build:gradle' || d.name === 'com.android.application') && d.version && /^\d/.test(d.version)); + if (agp) native.agp = { value: agp.version!, at: { file: agp.file, line: agp.line } }; + // the merged manifest of a local build, when there is one (libraries add permissions there: AD_ID, location, ...) + if (isAndroid) { + const merged = findMergedManifest(root, android.manifests, stacks.has('flutter')); + let t = ''; + if (merged) { try { t = readFileSync(join(root, merged), 'utf8'); } catch { /* unreadable */ } } + if (merged && t) { + android.mergedManifest = merged; + const extra: ProjectFacts['androidInfo'] = { ...android, permissions: [], services: [], components: [], removedPermissions: [], extractNativeLibs: null }; + readManifest(merged, t, extra); + const removed = new Set(android.removedPermissions.map(x => x.name)); + const have = new Set(android.permissions.map(x => x.name)); + for (const x of extra.permissions) if (!have.has(x.name) && !removed.has(x.name)) { android.permissions.push(x); have.add(x.name); } + const key = (k: string, n: string) => `${k}:${n.split('.').pop()}`; + const comps = new Set(android.components.map(x => key(x.kind, x.name))); + for (const x of extra.components) if (!comps.has(key(x.kind, x.name))) android.components.push(x); + const svc = new Set(android.services.map(x => key('service', x.name))); + for (const x of extra.services) if (!svc.has(key('service', x.name))) android.services.push(x); + } + } + return { root, stacks: [...stacks], ios, android: isAndroid, deps, sdks, plist, plistSources, entitlements, privacyManifests, androidInfo: android, native, remoteStart, sources, scanned: files.length }; +} + +/** NDK r27 flag and the linker flag of older NDKs that make native libraries 16 KB aligned. */ +const FLEXIBLE_PAGES = /ANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES\s*=?\s*ON|max-page-size=16384/; + +/** Permissions, components and settings of one AndroidManifest.xml, added to `a`. */ +function readManifest(f: string, t: string, a: ProjectFacts['androidInfo']): void { + for (const m of t.matchAll(/]*?)\/?>/g)) { + const name = /android:name="([^"]+)"/.exec(m[1]!)?.[1]; + if (!name) continue; + const at = { file: f, line: lineAt(t, m.index!) }; + if (/tools:node="remove"/.test(m[1]!)) a.removedPermissions.push({ name, at }); + else a.permissions.push({ name, at }); + } + for (const kind of ['activity', 'activity-alias', 'service', 'receiver'] as const) { + for (const m of t.matchAll(new RegExp(`<${kind}\\b([^>]*?)(/>|>([\\s\\S]*?))`, 'g'))) { + const attrs = m[1]!, body = m[3] ?? ''; + if (/tools:node="remove"/.test(attrs)) continue; + const c: AndroidComponent = { + kind: kind === 'activity-alias' ? 'activity' : kind, + name: /android:name="([^"]+)"/.exec(attrs)?.[1] ?? '?', + permission: /android:permission="([^"]+)"/.exec(attrs)?.[1] ?? null, + fgsType: /android:foregroundServiceType="([^"]+)"/.exec(attrs)?.[1] ?? null, + actions: [...body.matchAll(/ x[1]!), + categories: [...body.matchAll(/ x[1]!), + meta: [...body.matchAll(/ x[1]!), + at: { file: f, line: lineAt(t, m.index!) }, + }; + a.components.push(c); + if (c.kind === 'service') a.services.push({ name: c.name, fgsType: c.fgsType, at: c.at }); + } + } + const app = /]*/.exec(t); + const ex = app ? /android:extractNativeLibs="(true|false)"/.exec(app[0]) : null; + if (app && ex && !a.extractNativeLibs) a.extractNativeLibs = { value: ex[1] === 'true', at: { file: f, line: lineAt(t, app.index + ex.index) } }; + if (/android\.hardware\.type\.watch/.test(t)) a.formFactor = 'wear'; + else if (/android\.software\.leanback"[^>]*android:required="true"|android:required="true"[^>]*android\.software\.leanback/.test(t)) a.formFactor = 'tv'; + else if (/android\.hardware\.type\.automotive/.test(t)) a.formFactor = 'automotive'; +} + +/** NDK version, AGP plugin version, native build and packaging settings in one Gradle file. */ +function gradleNative(f: string, t: string, n: ProjectFacts['native'], deps: DepRef[]): void { + const nd = /\bndkVersion\s*=?\s*\(?\s*["'](\d+\.[\d.]+)["']/.exec(t); + if (nd && !n.ndkVersion) n.ndkVersion = { value: nd[1]!, at: { file: f, line: lineAt(t, nd.index) } }; + if (/\bndkVersion\s*=?\s*flutter\.ndkVersion/.test(t)) n.ndkFrom = 'the Flutter SDK (flutter.ndkVersion)'; + const ext = /\bexternalNativeBuild\s*\{/.exec(t); + if (ext && !n.nativeBuild) n.nativeBuild = { file: f, line: lineAt(t, ext.index) }; + const fl = FLEXIBLE_PAGES.exec(t); + if (fl && !n.flexiblePageSizes) n.flexiblePageSizes = { file: f, line: lineAt(t, fl.index) }; + const lp = /\buseLegacyPackaging\s*(?:=\s*)?true\b/.exec(t); + if (lp && !n.legacyPackaging) n.legacyPackaging = { file: f, line: lineAt(t, lp.index) }; + for (const m of t.matchAll(/\bid\s*\(?\s*["']com\.android\.(?:application|library)["']\s*\)?\s*version\s*["']([^"']+)["']/g)) + deps.push({ eco: 'gradle', name: 'com.android.application', version: m[1]!, file: f, line: lineAt(t, m.index!) }); +} + +/** A merged AndroidManifest.xml of a local build under /build/intermediates (release first), relative to + * root; Flutter builds into build/app/ at the project root. null when the project was not built here. */ +function findMergedManifest(root: string, manifests: string[], flutter: boolean): string | null { + const modules = new Set(manifests.filter(m => m.endsWith('src/main/AndroidManifest.xml')).map(m => `${m.slice(0, -'src/main/AndroidManifest.xml'.length)}build/`)); + if (flutter) modules.add('build/app/'); + const found: string[] = []; + const walk = (dir: string, depth: number) => { + if (depth > 4) return; + let names: string[]; + try { names = readdirSync(join(root, dir)); } catch { return; } + for (const n of names.sort()) { + if (n === 'AndroidManifest.xml') found.push(`${dir}/${n}`); + else if (!n.includes('.')) walk(`${dir}/${n}`, depth + 1); + } + }; + for (const m of modules) for (const sub of ['merged_manifest', 'merged_manifests', 'packaged_manifests']) walk(`${m}intermediates/${sub}`, 0); + return found.find(f => /release/i.test(f)) ?? found[0] ?? null; } const COMMENT = /^\s*(\/\/|#|\*|\/\*| +### title +``` +Clean Notes: Scan & Organize +``` + ### short ``` Notes that stay tidy, and paper notes turned into text. diff --git a/tests/fixtures/scan/clean/storebound.config.ts b/tests/fixtures/scan/clean/storebound.config.ts index 378a33f9..d72f16a6 100644 --- a/tests/fixtures/scan/clean/storebound.config.ts +++ b/tests/fixtures/scan/clean/storebound.config.ts @@ -12,7 +12,7 @@ export default { accounts: { enabled: true, deletionUrl: 'https://example.com/delete-account', inApp: 'Settings > Account > Delete account' }, reviewAccess: { signInRequired: true, instructions: 'Sign in with the demo account.' }, languages: [{ id: 'en', play: 'en-US', apple: 'en-US' }], - play: { packageName: 'org.example.cleannotes' }, + play: { packageName: 'org.example.cleannotes', accountType: 'organization', targetAges: ['13-15', '16-17', '18+'] }, apple: { bundleId: 'org.example.cleannotes', usesNonExemptEncryption: false }, appPrivacy: { tracking: true, trackingDomains: ['ads.example.com'] }, products: [ diff --git a/tests/fixtures/scan/play-android/README.md b/tests/fixtures/scan/play-android/README.md new file mode 100644 index 00000000..f24fdca7 --- /dev/null +++ b/tests/fixtures/scan/play-android/README.md @@ -0,0 +1,9 @@ +# play-android fixture + +A made-up Kotlin hiking app with planted Google Play policy problems for `storebound scan` tests: background +location without a prominent disclosure, READ_MEDIA_IMAGES / READ_MEDIA_VIDEO, MANAGE_EXTERNAL_STORAGE, +REQUEST_INSTALL_PACKAGES, Health Connect permissions, an AccessibilityService without isAccessibilityTool, a +VpnService, USE_FULL_SCREEN_INTENT added by a library (only in the committed merged manifest under +app/build/intermediates), AppLovin without AD_ID in the merged manifest, an interstitial shown from the launcher +activity's onCreate, Stripe next to an in-app product, no privacy policy link in the app, and a personal developer +account created after 2023-11-13. Not a buildable project. diff --git a/tests/fixtures/scan/play-android/app/build.gradle.kts b/tests/fixtures/scan/play-android/app/build.gradle.kts new file mode 100644 index 00000000..d9cb7009 --- /dev/null +++ b/tests/fixtures/scan/play-android/app/build.gradle.kts @@ -0,0 +1,23 @@ +plugins { + id("com.android.application") + id("org.jetbrains.kotlin.android") +} + +android { + namespace = "org.example.trailmate" + compileSdk = 36 + defaultConfig { + applicationId = "org.example.trailmate" + minSdk = 26 + targetSdk = 36 + versionCode = 3 + versionName = "1.2.0" + } +} + +dependencies { + implementation("com.applovin:applovin-sdk:13.0.1") + implementation("com.stripe:stripe-android:21.2.0") + implementation("com.android.billingclient:billing:7.1.1") + implementation("androidx.health.connect:connect-client:1.1.0-rc01") +} diff --git a/tests/fixtures/scan/play-android/app/build/intermediates/merged_manifest/release/processReleaseMainManifest/AndroidManifest.xml b/tests/fixtures/scan/play-android/app/build/intermediates/merged_manifest/release/processReleaseMainManifest/AndroidManifest.xml new file mode 100644 index 00000000..9a32d3e6 --- /dev/null +++ b/tests/fixtures/scan/play-android/app/build/intermediates/merged_manifest/release/processReleaseMainManifest/AndroidManifest.xml @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/fixtures/scan/play-android/app/src/main/AndroidManifest.xml b/tests/fixtures/scan/play-android/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000..2ca9bd29 --- /dev/null +++ b/tests/fixtures/scan/play-android/app/src/main/AndroidManifest.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/fixtures/scan/play-android/app/src/main/java/org/example/trailmate/MainActivity.kt b/tests/fixtures/scan/play-android/app/src/main/java/org/example/trailmate/MainActivity.kt new file mode 100644 index 00000000..26f18273 --- /dev/null +++ b/tests/fixtures/scan/play-android/app/src/main/java/org/example/trailmate/MainActivity.kt @@ -0,0 +1,21 @@ +package org.example.trailmate + +import android.os.Bundle +import androidx.appcompat.app.AppCompatActivity +import com.applovin.mediation.ads.MaxInterstitialAd + +class MainActivity : AppCompatActivity() { + private lateinit var interstitialAd: MaxInterstitialAd + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + interstitialAd = MaxInterstitialAd("launch-unit", this) + interstitialAd.loadAd() + if (interstitialAd.isReady) interstitialAd.showAd() + } + + override fun onResume() { + super.onResume() + } +} diff --git a/tests/fixtures/scan/play-android/app/src/main/res/values/strings.xml b/tests/fixtures/scan/play-android/app/src/main/res/values/strings.xml new file mode 100644 index 00000000..5c3788a1 --- /dev/null +++ b/tests/fixtures/scan/play-android/app/src/main/res/values/strings.xml @@ -0,0 +1,4 @@ + + Trail Mate + Start hike + diff --git a/tests/fixtures/scan/play-android/app/src/main/res/xml/accessibility_service_config.xml b/tests/fixtures/scan/play-android/app/src/main/res/xml/accessibility_service_config.xml new file mode 100644 index 00000000..588eed4e --- /dev/null +++ b/tests/fixtures/scan/play-android/app/src/main/res/xml/accessibility_service_config.xml @@ -0,0 +1,4 @@ + + diff --git a/tests/fixtures/scan/play-android/settings.gradle.kts b/tests/fixtures/scan/play-android/settings.gradle.kts new file mode 100644 index 00000000..8ee97160 --- /dev/null +++ b/tests/fixtures/scan/play-android/settings.gradle.kts @@ -0,0 +1,8 @@ +pluginManagement { + plugins { + id("com.android.application") version "8.7.3" + id("org.jetbrains.kotlin.android") version "2.0.21" + } +} +rootProject.name = "TrailMate" +include(":app") diff --git a/tests/fixtures/scan/play-android/storebound.config.ts b/tests/fixtures/scan/play-android/storebound.config.ts new file mode 100644 index 00000000..7065805e --- /dev/null +++ b/tests/fixtures/scan/play-android/storebound.config.ts @@ -0,0 +1,24 @@ +// Fixture config (made up, example.com placeholders only). +export default { + app: { + name: 'Trail Mate', + profile: 'app', + privacyPolicyUrl: 'https://example.com/privacy', + supportUrl: 'https://example.com/support', + website: 'https://example.com', + contactEmail: 'support@example.com', + }, + languages: [{ id: 'en', play: 'en-US' }], + play: { packageName: 'org.example.trailmate', accountType: 'personal', accountCreated: '2025-03-01' }, + products: [ + { id: 'org.example.trailmate.pro', type: 'non_consumable', usd: 4.99, listings: { en: { title: 'Pro', description: 'Offline maps' } } }, + ], + dataSafety: { + collectsData: true, + encryptedInTransit: true, + deletionRequest: false, + data: { + PSL_DEVICE_ID: { shared: false, collect: ['analytics'] }, + }, + }, +}; diff --git a/tests/fixtures/scan/play-families/Assets/GoogleMobileAds/Editor/GoogleMobileAdsDependencies.xml b/tests/fixtures/scan/play-families/Assets/GoogleMobileAds/Editor/GoogleMobileAdsDependencies.xml new file mode 100644 index 00000000..027ac2ec --- /dev/null +++ b/tests/fixtures/scan/play-families/Assets/GoogleMobileAds/Editor/GoogleMobileAdsDependencies.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/tests/fixtures/scan/play-families/Assets/Plugins/Android/AndroidManifest.xml b/tests/fixtures/scan/play-families/Assets/Plugins/Android/AndroidManifest.xml new file mode 100644 index 00000000..710c3aff --- /dev/null +++ b/tests/fixtures/scan/play-families/Assets/Plugins/Android/AndroidManifest.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/tests/fixtures/scan/play-families/Packages/manifest.json b/tests/fixtures/scan/play-families/Packages/manifest.json new file mode 100644 index 00000000..19bd687f --- /dev/null +++ b/tests/fixtures/scan/play-families/Packages/manifest.json @@ -0,0 +1,6 @@ +{ + "dependencies": { + "com.applovin.mediation.ads": "8.0.1", + "com.unity.ugui": "1.0.0" + } +} diff --git a/tests/fixtures/scan/play-families/ProjectSettings/ProjectSettings.asset b/tests/fixtures/scan/play-families/ProjectSettings/ProjectSettings.asset new file mode 100644 index 00000000..6e43b49a --- /dev/null +++ b/tests/fixtures/scan/play-families/ProjectSettings/ProjectSettings.asset @@ -0,0 +1,8 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!129 &1 +PlayerSettings: + productName: Puzzle Pals + companyName: Example Studio + AndroidMinSdkVersion: 23 + AndroidTargetSdkVersion: 36 diff --git a/tests/fixtures/scan/play-families/ProjectSettings/ProjectVersion.txt b/tests/fixtures/scan/play-families/ProjectSettings/ProjectVersion.txt new file mode 100644 index 00000000..10a392d4 --- /dev/null +++ b/tests/fixtures/scan/play-families/ProjectSettings/ProjectVersion.txt @@ -0,0 +1,2 @@ +m_EditorVersion: 2022.3.20f1 +m_EditorVersionWithRevision: 2022.3.20f1 (000000000000) diff --git a/tests/fixtures/scan/play-families/README.md b/tests/fixtures/scan/play-families/README.md new file mode 100644 index 00000000..d4337687 --- /dev/null +++ b/tests/fixtures/scan/play-families/README.md @@ -0,0 +1,6 @@ +# play-families fixture + +A made-up Unity game for children (Play target audience 0-12 only) with planted Families policy problems for +`storebound scan` tests: AppLovin MAX (not a Families Self-Certified Ads SDK), Google Mobile Ads 18.3.0 (older than +the first certified version), the AD_ID permission and a location permission in the Android plugin manifest, and +Unity 2022.3.20f1 (before 16 KB page size support). Not a buildable project. diff --git a/tests/fixtures/scan/play-families/storebound.config.ts b/tests/fixtures/scan/play-families/storebound.config.ts new file mode 100644 index 00000000..2dc33c2d --- /dev/null +++ b/tests/fixtures/scan/play-families/storebound.config.ts @@ -0,0 +1,24 @@ +// Fixture config (made up, example.com placeholders only). +export default { + app: { + name: 'Puzzle Pals', + profile: 'game', + privacyPolicyUrl: 'https://example.com/privacy', + supportUrl: 'https://example.com/support', + website: 'https://example.com', + contactEmail: 'support@example.com', + }, + languages: [{ id: 'en', play: 'en-US' }], + play: { packageName: 'org.example.puzzlepals', accountType: 'organization', targetAges: ['0-5', '6-8', '9-12'] }, + dataSafety: { + collectsData: true, + encryptedInTransit: true, + deletionRequest: false, + data: { + PSL_DEVICE_ID: { shared: true, collect: ['advertising', 'analytics', 'fraud'], share: ['advertising'] }, + PSL_APPROX_LOCATION: { shared: true, collect: ['advertising', 'analytics', 'fraud'], share: ['advertising'] }, + PSL_USER_INTERACTION: { shared: true, collect: ['advertising', 'analytics'], share: ['advertising'] }, + PSL_PERFORMANCE_DIAGNOSTICS: { shared: false, collect: ['analytics'] }, + }, + }, +}; diff --git a/tests/fixtures/scan/play-listing/README.md b/tests/fixtures/scan/play-listing/README.md new file mode 100644 index 00000000..b1e103dc --- /dev/null +++ b/tests/fixtures/scan/play-listing/README.md @@ -0,0 +1,6 @@ +# play-listing fixture + +A made-up photo app whose Google Play listing breaks the Metadata policy for `storebound scan` tests: a title longer +than 30 characters with an emoji, "#1", "best" and "free", an ALL CAPS title in a second language, another app named +in the short description, a repeated keyword and a keyword list in the full description, a "buy on our website" call +to action, and a package name that contains a well-known brand. Config and listing only. diff --git a/tests/fixtures/scan/play-listing/store/listing.md b/tests/fixtures/scan/play-listing/store/listing.md new file mode 100644 index 00000000..135efaee --- /dev/null +++ b/tests/fixtures/scan/play-listing/store/listing.md @@ -0,0 +1,43 @@ +# Snap Saver · Google Play listing copy (fixture with planted Metadata policy problems) + +## English + + +### title +``` +🔥 #1 Best Free Photo Saver App Pro +``` + +### short +``` +Save photos faster than Instagram and keep every album tidy. +``` + +### full +``` +Snap Saver keeps your photo library tidy. Save a photo, sort a photo, share a photo. + +Photo albums, photo backup, photo sorting and photo sharing in one place. Every photo stays on your phone, and every +photo album can be locked. Find any photo by date or place, and move a photo between albums with one tap. +Unlock Pro: buy the Pro version on our website for the lowest price. + +photo, gallery, album, saver, backup, cleaner, editor, collage, picture, camera +``` + +## Deutsch + + +### title +``` +FOTO SPEICHER +``` + +### short +``` +Fotos sichern und Alben ordnen. +``` + +### full +``` +Snap Saver ordnet deine Fotos in Alben und sichert sie auf deinem Telefon. +``` diff --git a/tests/fixtures/scan/play-listing/storebound.config.ts b/tests/fixtures/scan/play-listing/storebound.config.ts new file mode 100644 index 00000000..690d3bc7 --- /dev/null +++ b/tests/fixtures/scan/play-listing/storebound.config.ts @@ -0,0 +1,13 @@ +// Fixture config (made up, example.com placeholders only). +export default { + app: { + name: 'Snap Saver', + profile: 'app', + privacyPolicyUrl: 'https://example.com/privacy', + supportUrl: 'https://example.com/support', + website: 'https://example.com', + contactEmail: 'support@example.com', + }, + languages: [{ id: 'en', play: 'en-US' }, { id: 'de', play: 'de-DE' }], + play: { packageName: 'org.example.instagramsaver', accountType: 'organization' }, +}; diff --git a/tests/fixtures/scan/play-native/README.md b/tests/fixtures/scan/play-native/README.md new file mode 100644 index 00000000..42d35057 --- /dev/null +++ b/tests/fixtures/scan/play-native/README.md @@ -0,0 +1,5 @@ +# play-native fixture + +A made-up Flutter audio app with its own C++ code for `storebound scan` 16 KB page size tests: NDK r25 without the +16 KB linker flags, Android Gradle Plugin 8.1.0 with uncompressed native libraries (extractNativeLibs="false"), and a +prebuilt vendor library under jniLibs/arm64-v8a (a placeholder file, not a real ELF). Not a buildable project. diff --git a/tests/fixtures/scan/play-native/android/app/build.gradle b/tests/fixtures/scan/play-native/android/app/build.gradle new file mode 100644 index 00000000..7705c3d8 --- /dev/null +++ b/tests/fixtures/scan/play-native/android/app/build.gradle @@ -0,0 +1,21 @@ +plugins { + id "com.android.application" + id "kotlin-android" + id "dev.flutter.flutter-gradle-plugin" +} + +android { + namespace "org.example.echotuner" + compileSdk flutter.compileSdkVersion + ndkVersion "25.1.8937393" + defaultConfig { + applicationId "org.example.echotuner" + minSdk flutter.minSdkVersion + targetSdk 36 + } + externalNativeBuild { + cmake { + path "src/main/cpp/CMakeLists.txt" + } + } +} diff --git a/tests/fixtures/scan/play-native/android/app/src/main/AndroidManifest.xml b/tests/fixtures/scan/play-native/android/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000..a7688a5e --- /dev/null +++ b/tests/fixtures/scan/play-native/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/tests/fixtures/scan/play-native/android/app/src/main/cpp/CMakeLists.txt b/tests/fixtures/scan/play-native/android/app/src/main/cpp/CMakeLists.txt new file mode 100644 index 00000000..9b7b0b4b --- /dev/null +++ b/tests/fixtures/scan/play-native/android/app/src/main/cpp/CMakeLists.txt @@ -0,0 +1,3 @@ +cmake_minimum_required(VERSION 3.22.1) +project(pitch) +add_library(pitch SHARED pitch.cpp) diff --git a/tests/fixtures/scan/play-native/android/app/src/main/jniLibs/arm64-v8a/libvendorfx.so b/tests/fixtures/scan/play-native/android/app/src/main/jniLibs/arm64-v8a/libvendorfx.so new file mode 100644 index 00000000..19ff39f8 --- /dev/null +++ b/tests/fixtures/scan/play-native/android/app/src/main/jniLibs/arm64-v8a/libvendorfx.so @@ -0,0 +1 @@ +placeholder for a prebuilt vendor library (storebound scan only lists .so files, it never reads them) diff --git a/tests/fixtures/scan/play-native/android/settings.gradle b/tests/fixtures/scan/play-native/android/settings.gradle new file mode 100644 index 00000000..23e5c2be --- /dev/null +++ b/tests/fixtures/scan/play-native/android/settings.gradle @@ -0,0 +1,11 @@ +pluginManagement { + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") +} + +plugins { + id "dev.flutter.flutter-plugin-loader" version "1.0.0" + id "com.android.application" version "8.1.0" apply false + id "org.jetbrains.kotlin.android" version "1.8.22" apply false +} + +include ":app" diff --git a/tests/fixtures/scan/play-native/pubspec.yaml b/tests/fixtures/scan/play-native/pubspec.yaml new file mode 100644 index 00000000..d485ea78 --- /dev/null +++ b/tests/fixtures/scan/play-native/pubspec.yaml @@ -0,0 +1,11 @@ +name: echo_tuner +description: A made-up tuner app for storebound tests. +version: 1.0.0+4 + +environment: + sdk: ">=3.5.0 <4.0.0" + +dependencies: + flutter: + sdk: flutter + ffi: ^2.1.3 diff --git a/tests/fixtures/scan/play-native/storebound.config.ts b/tests/fixtures/scan/play-native/storebound.config.ts new file mode 100644 index 00000000..d4b881c1 --- /dev/null +++ b/tests/fixtures/scan/play-native/storebound.config.ts @@ -0,0 +1,13 @@ +// Fixture config (made up, example.com placeholders only). +export default { + app: { + name: 'Echo Tuner', + profile: 'app', + privacyPolicyUrl: 'https://example.com/privacy', + supportUrl: 'https://example.com/support', + website: 'https://example.com', + contactEmail: 'support@example.com', + }, + languages: [{ id: 'en', play: 'en-US' }], + play: { packageName: 'org.example.echotuner', accountType: 'organization' }, +}; diff --git a/tests/scan.test.ts b/tests/scan.test.ts index 3c6e560c..f279316c 100644 --- a/tests/scan.test.ts +++ b/tests/scan.test.ts @@ -1,14 +1,16 @@ // storebound scan: project detection, every rejection-risk rule on the fixtures (true positives) and the clean // fixture (no false positives), the declarations proposal and --write, validate / MCP integration, the demo projects. import { afterAll, beforeEach, describe, expect, test } from 'bun:test'; -import { cpSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { cpSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { FORBIDDEN_ARGS, TOOLS, toArgv } from '../cli/mcp-tools'; import { JSON_TOOLS } from '../cli/serve'; import { scanAsFindings } from '../cli/validate'; import { matchBrace, toTs, upsertBlock } from '../cli/lib/scan/config-edit'; +import { validateConfig } from '../cli/lib/config'; import { runScan } from '../cli/lib/scan'; +import { PLAY_REFS } from '../cli/lib/scan/play-rules'; import { vaguePurpose } from '../cli/lib/scan/permissions'; import { detectProject, parsePlist } from '../cli/lib/scan/project'; import type { ScanFinding } from '../cli/lib/scan/rules'; @@ -130,6 +132,123 @@ describe('rules: planted issues are found', () => { }); }); +/** A temp copy of a fixture, changed by `edit` (file -> new content from old), for the variants of one fixture. */ +async function scanVariant(name: string, edit: Record string>) { + const dir = mkdtempSync(join(tmpdir(), 'sb-scan-play-')); + try { + cpSync(join(FX, name), dir, { recursive: true }); + for (const [f, fn] of Object.entries(edit)) writeFileSync(join(dir, f), fn(existsSync(join(dir, f)) ? readFileSync(join(dir, f), 'utf8') : '')); + return (await runScan(dir)).report; + } finally { rmSync(dir, { recursive: true, force: true }); } +} + +describe('Google Play rules', () => { + test('detection: merged manifest, components, accessibility config, strings, native toolchain', () => { + const a = detectProject(join(FX, 'play-android')); + expect(a.androidInfo.mergedManifest).toBe('app/build/intermediates/merged_manifest/release/processReleaseMainManifest/AndroidManifest.xml'); + expect(a.androidInfo.permissions.find(x => x.name.endsWith('USE_FULL_SCREEN_INTENT'))!.at.file).toBe(a.androidInfo.mergedManifest!); + expect(a.androidInfo.permissions.find(x => x.name.endsWith('ACCESS_BACKGROUND_LOCATION'))!.at).toEqual({ file: 'app/src/main/AndroidManifest.xml', line: 5 }); + expect(a.androidInfo.components.filter(c => c.kind === 'service').map(c => c.name)).toEqual(['.TrailAssistService', '.OfflineMapVpnService']); + expect(a.androidInfo.components.find(c => c.categories.includes('android.intent.category.LAUNCHER'))!.name).toBe('.MainActivity'); + expect(a.androidInfo.accessibilityConfigs).toEqual([{ at: { file: 'app/src/main/res/xml/accessibility_service_config.xml', line: 2 }, isTool: false }]); + expect(a.androidInfo.strings.map(s => s.path)).toEqual(['app/src/main/res/values/strings.xml']); + expect(a.native.agp).toEqual({ value: '8.7.3', at: { file: 'settings.gradle.kts', line: 3 } }); + const n = detectProject(join(FX, 'play-native')); + expect(n.native.libs).toEqual(['android/app/src/main/jniLibs/arm64-v8a/libvendorfx.so']); + expect(n.native.ndkVersion).toEqual({ value: '25.1.8937393', at: { file: 'android/app/build.gradle', line: 10 } }); + expect(n.native.agp!.value).toBe('8.1.0'); + expect(n.native.nativeBuild).toEqual({ file: 'android/app/build.gradle', line: 16 }); + expect(n.androidInfo.extractNativeLibs).toEqual({ value: false, at: { file: 'android/app/src/main/AndroidManifest.xml', line: 3 } }); + expect(n.androidInfo.mergedManifest).toBeNull(); + expect(detectProject(join(FX, 'play-families')).native.unityVersion).toEqual({ value: '2022.3.20f1', at: { file: 'ProjectSettings/ProjectVersion.txt', line: 1 } }); + }); + test('sensitive permissions, prominent disclosure, privacy policy, ads at launch, payments, testing (play-android)', async () => { + const r = await scan('play-android'); + for (const id of ['play-background-location', 'play-photo-video', 'play-all-files-access', 'play-accessibility', 'play-install-packages', 'play-health-connect', + 'play-full-screen-intent', 'play-vpn', 'play-prominent-disclosure', 'play-privacy-policy', 'play-ad-id', 'play-ads-launch', 'play-payments', 'play-testing-requirement', 'privacy-labels']) + expect(rules(r.findings, 'play')).toContain(id); + expect(rules(r.findings, 'apple').size).toBe(0); + expect(find(r.findings, 'play-full-screen-intent')!.evidence[0]!.file).toContain('build/intermediates/merged_manifest'); + expect(find(r.findings, 'play-accessibility')!.severity).toBe('high'); + expect(r.findings.filter(f => f.rule === 'play-prominent-disclosure').map(f => f.severity)).toEqual(['high', 'medium']); + expect(find(r.findings, 'play-ads-launch')!.evidence[0]).toMatchObject({ file: 'app/src/main/java/org/example/trailmate/MainActivity.kt', line: 15 }); + expect(find(r.findings, 'play-ad-id')!.severity).toBe('medium'); + expect(find(r.findings, 'play-testing-requirement')).toMatchObject({ severity: 'medium', title: expect.stringContaining('12 opted-in testers for 14 days') }); + expect(r.findings.find(f => f.rule === 'privacy-labels' && f.title.includes('narrower'))!.title).toContain('PSL_DEVICE_ID'); + expect(rules(r.findings)).not.toContain('play-16kb'); + for (const f of r.findings) { expect(f.ref).toMatch(/^https:\/\/(support\.google\.com|developer\.android\.com)\//); expect(f.evidence.length).toBeGreaterThan(0); expect(f.fix.length).toBeGreaterThan(20); } + }); + test('variants: isAccessibilityTool, a disclosure string, organization account, billing program', async () => { + const r = await scanVariant('play-android', { + 'app/src/main/res/xml/accessibility_service_config.xml': s => s.replace('android:canRetrieveWindowContent', 'android:isAccessibilityTool="true"\n android:canRetrieveWindowContent'), + 'app/src/main/res/values/strings.xml': s => s.replace('', ' Trail Mate collects location data to record your hike even when the app is closed or not in use.\n'), + 'storebound.config.ts': s => s.replace("accountType: 'personal', accountCreated: '2025-03-01'", "accountType: 'organization', billingPrograms: ['user-choice-billing']"), + }); + expect(find(r.findings, 'play-accessibility')!.severity).toBe('medium'); + expect(rules(r.findings)).not.toContain('play-prominent-disclosure'); + expect(rules(r.findings)).not.toContain('play-testing-requirement'); + expect(rules(r.findings)).not.toContain('play-payments'); + const old = await scanVariant('play-android', { 'storebound.config.ts': s => s.replace("accountCreated: '2025-03-01'", "accountCreated: '2023-11-13'") }); + expect(rules(old.findings)).not.toContain('play-testing-requirement'); + }); + test('16 KB page sizes: old NDK and AGP (play-native), Unity versions, prebuilt libraries', async () => { + const r = await scan('play-native'); + const k = r.findings.filter(f => f.rule === 'play-16kb'); + expect(k.map(f => f.severity)).toEqual(['high', 'high']); + expect(k[0]!.title).toContain('NDK 25.1.8937393'); + expect(k[1]!.title).toContain('Android Gradle Plugin 8.1.0'); + expect(k.every(f => f.title.includes('2027-02-01'))).toBe(true); + const fixed = await scanVariant('play-native', { + 'android/app/build.gradle': s => s.replace('25.1.8937393', '27.2.12479018').replace('path "src/main/cpp/CMakeLists.txt"', 'path "src/main/cpp/CMakeLists.txt"\n arguments "-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON"'), + 'android/settings.gradle': s => s.replace('"8.1.0"', '"8.7.3"'), + }); + const left = fixed.findings.filter(f => f.rule === 'play-16kb'); + expect(left.map(f => [f.severity, f.evidence[0]!.file])).toEqual([['medium', 'android/app/src/main/jniLibs/arm64-v8a/libvendorfx.so']]); + const legacy = await scanVariant('play-native', { 'android/app/build.gradle': s => s.replace('externalNativeBuild', 'packaging { jniLibs { useLegacyPackaging = true } }\n externalNativeBuild') }); + expect(legacy.findings.filter(f => f.rule === 'play-16kb').map(f => f.title)).toEqual([expect.stringContaining('NDK')]); + for (const [v, flagged] of [['2022.3.56f1', false], ['2021.3.47f1', true], ['6000.0.38f1', false], ['6000.0.37f1', true], ['6000.1.2f1', false], ['2023.2.20f1', true]] as const) { + const u = await scanVariant('play-families', { 'ProjectSettings/ProjectVersion.txt': () => `m_EditorVersion: ${v}\n` }); + expect([v, rules(u.findings).has('play-16kb')]).toEqual([v, flagged]); + } + }); + test('Families: uncertified and old ad SDKs, AD_ID, location (play-families)', async () => { + const r = await scan('play-families'); + const ads = r.findings.filter(f => f.rule === 'play-families-ads'); + expect(ads.map(f => f.title)).toEqual([expect.stringContaining('AdMob 18.3.0 is older than 19.0.0'), expect.stringContaining('AppLovin MAX is not a Families Self-Certified')]); + expect(find(r.findings, 'play-families-ad-id')!.severity).toBe('high'); + expect(find(r.findings, 'play-families-location')!.evidence[0]).toMatchObject({ file: 'Assets/Plugins/Android/AndroidManifest.xml', line: 3 }); + expect(rules(r.findings)).not.toContain('kids-ads'); + expect(rules(r.findings)).not.toContain('play-ad-id'); + const mixed = await scanVariant('play-families', { 'storebound.config.ts': s => s.replace("['0-5', '6-8', '9-12']", "['9-12', '13-15', '16-17']") }); + expect(find(mixed.findings, 'play-families-ad-id')!.severity).toBe('medium'); + expect(rules(mixed.findings)).not.toContain('play-families-location'); + const adult = await scanVariant('play-families', { 'storebound.config.ts': s => s.replace("['0-5', '6-8', '9-12']", "['18+']") }); + expect([...rules(adult.findings)].filter(x => x.startsWith('play-families'))).toEqual([]); + }); + test('Play listing metadata, steering to the web, impersonation (play-listing)', async () => { + const r = await scan('play-listing'); + const m = r.findings.filter(f => f.rule === 'play-metadata').map(f => f.title); + for (const t of ['longer than 30 characters', 'Emoji', 'Rank, performance', 'ALL CAPS', 'Other apps or brands', 'Repeated keywords ("photo"']) + expect(m.some(x => x.includes(t))).toBe(true); + expect(m.find(x => x.includes('Repeated'))).toContain('and a keyword list'); + expect(find(r.findings, 'play-payments')!.evidence[0]).toMatchObject({ file: 'store/listing.md', line: 22 }); + expect(find(r.findings, 'play-impersonation')).toMatchObject({ severity: 'low', title: expect.stringContaining('"instagram"') }); + const ok = await scanVariant('play-listing', { 'storebound.config.ts': s => s.replace('org.example.instagramsaver', 'org.example.snapsaver') }); + expect(rules(ok.findings)).not.toContain('play-impersonation'); + const soft = await scanVariant('play-listing', { 'store/listing.md': s => s.replace('🔥 #1 Best Free Photo Saver App Pro', 'Free Photo Saver') }); + expect(soft.findings.filter(f => f.rule === 'play-metadata' && f.title.includes('Free Photo Saver')).map(f => f.severity)).toEqual(['low']); + expect(rules(await scan('ios-native').then(x => x.findings), 'play').size).toBe(0); + }); + test('the policy tables cite their sources', () => { + for (const u of Object.values(PLAY_REFS)) expect(u).toMatch(/^https:\/\//); + const fam = SDKS.filter(s => s.category === 'ads').map(s => [s.id, s.families?.certified]); + expect(fam).toEqual([['admob', true], ['applovin', false], ['levelplay', true], ['unity-ads', true], ['meta-an', false]]); + expect(validateConfig({ app: { name: 'X', privacyPolicyUrl: 'https://example.com/p', supportUrl: 'https://example.com/s', website: 'https://example.com', contactEmail: 'support@example.com' }, languages: [{ id: 'en' }], + play: { packageName: 'org.example.x', targetAges: ['7-9'], accountType: 'person', accountCreated: '2024', billingPrograms: ['stripe'] } })) + .toEqual(expect.arrayContaining([expect.stringContaining('play.targetAges'), expect.stringContaining('play.accountType'), expect.stringContaining('play.accountCreated'), expect.stringContaining('play.billingPrograms')])); + }); +}); + describe('rules: no false positives', () => { test('clean fixture has no finding at all', async () => { process.env.REVIEW_DEMO_USER = 'demo@example.com'; process.env.REVIEW_DEMO_PASSWORD = 'example';