From 00a38cd305e57d7401883354bdd28d33ce8b7ef0 Mon Sep 17 00:00:00 2001 From: CRT Date: Sun, 11 Oct 2026 15:20:55 +0000 Subject: [PATCH] storebound scan: offline rejection-risk scan of the project itself Detects the stack (native iOS / Android, React Native, Expo, Capacitor, Cordova, Flutter, Unity, Godot) and the SDKs from a maintained table with versions, file:line and each vendor's disclosure page, then reports App Store and Google Play rejection risks with guideline, evidence, fix, severity and skill: 2.1(a) demo account and placeholder text, 5.1.1(v) account deletion, 4.8 login services, 3.1.1 restore and outside payments, 3.1.2 subscription info, 5.1.2(i) ATT, purpose strings, privacy link, privacy manifest, 2.3.10, 2.3.7, 2.3.8, 4.2 web wrappers, 2.5.1, 2.5.5, ATS, export compliance, 1.3 kids ads, review prompts, privacy labels vs SDKs; Play target SDK 36, delete-account URL, App access, foreground services, exact alarms, QUERY_ALL_PACKAGES, SMS / call log, com.example package name. Proposes Data safety / App Privacy / ATT / privacy manifest answers (detected file:line or ask owner) as a diff against the config; --write adds only the detected ones. scan.ignore records owner-accepted findings. MCP tool scan (read-only), validate includes open findings, desktop Checks tab shows them. Fixtures for iOS, Android, Capacitor, Unity, Flutter, clean and teaser. --- .cursor/rules/storebound.mdc | 6 +- .github/copilot-instructions.md | 6 +- AGENTS.md | 6 +- CHANGELOG.md | 17 + GEMINI.md | 6 +- README.md | 80 ++- apps/desktop/src/dev/fixtures.ts | 27 +- apps/desktop/src/i18n/en.ts | 15 + apps/desktop/src/i18n/tr.ts | 15 + apps/desktop/src/lib/model.ts | 13 + apps/desktop/src/screens/tabs/Checks.tsx | 51 +- cli/index.ts | 1 + cli/lib/config.ts | 21 + cli/lib/profile.ts | 2 + cli/lib/scan/config-edit.ts | 71 +++ cli/lib/scan/declare.ts | 155 ++++++ cli/lib/scan/index.ts | 121 +++++ cli/lib/scan/permissions.ts | 55 ++ cli/lib/scan/project.ts | 430 +++++++++++++++ cli/lib/scan/rules.ts | 502 ++++++++++++++++++ cli/lib/scan/sdks.ts | 205 +++++++ cli/mcp-tools.ts | 6 +- cli/scan.ts | 57 ++ cli/serve.ts | 2 +- cli/validate.ts | 24 +- docs/agents-core.md | 4 +- docs/desktop.md | 3 +- examples/demo-app/README.md | 5 + examples/demo-app/storebound.config.ts | 8 + examples/demo-game/README.md | 5 + examples/demo-game/storebound.config.ts | 2 + skills/account-deletion/SKILL.md | 2 + skills/privacy-manifest/SKILL.md | 2 + skills/review-access/SKILL.md | 2 + skills/review-rejections/SKILL.md | 17 + skills/store-declarations/SKILL.md | 2 + skills/store-preflight/SKILL.md | 32 +- tests/fixtures/scan/android/README.md | 5 + .../scan/android/app/build.gradle.kts | 23 + .../android/app/src/main/AndroidManifest.xml | 18 + .../java/com/example/budget/AuthRepository.kt | 9 + .../scan/android/gradle/libs.versions.toml | 8 + .../scan/android/storebound.config.ts | 24 + tests/fixtures/scan/capacitor/README.md | 5 + .../android/app/src/main/AndroidManifest.xml | 5 + .../scan/capacitor/android/variables.gradle | 5 + .../scan/capacitor/capacitor.config.json | 9 + .../scan/capacitor/ios/App/App/Info.plist | 10 + tests/fixtures/scan/capacitor/package.json | 11 + tests/fixtures/scan/capacitor/src/main.ts | 5 + .../clean/Clean.xcodeproj/project.pbxproj | 15 + .../scan/clean/Clean/AccountView.swift | 11 + .../scan/clean/Clean/Clean.entitlements | 10 + tests/fixtures/scan/clean/Clean/Info.plist | 12 + .../fixtures/scan/clean/Clean/LoginView.swift | 16 + .../scan/clean/Clean/PrivacyInfo.xcprivacy | 23 + .../fixtures/scan/clean/Clean/StoreView.swift | 14 + .../fixtures/scan/clean/Clean/Tracking.swift | 8 + tests/fixtures/scan/clean/Podfile.lock | 9 + tests/fixtures/scan/clean/README.md | 7 + .../scan/clean/android/app/build.gradle.kts | 15 + .../android/app/src/main/AndroidManifest.xml | 5 + tests/fixtures/scan/clean/store/appstore.md | 28 + tests/fixtures/scan/clean/store/listing.md | 14 + .../fixtures/scan/clean/storebound.config.ts | 45 ++ tests/fixtures/scan/flutter/README.md | 6 + .../scan/flutter/android/app/build.gradle | 9 + .../android/app/src/main/AndroidManifest.xml | 7 + .../scan/flutter/ios/Runner/Info.plist | 10 + tests/fixtures/scan/flutter/lib/main.dart | 14 + tests/fixtures/scan/flutter/pubspec.lock | 19 + tests/fixtures/scan/flutter/pubspec.yaml | 19 + tests/fixtures/scan/flutter/store/appstore.md | 23 + .../scan/flutter/storebound.config.ts | 22 + .../Notes.xcodeproj/project.pbxproj | 17 + .../fixtures/scan/ios-native/Notes/Api.swift | 8 + .../fixtures/scan/ios-native/Notes/Info.plist | 19 + .../scan/ios-native/Notes/LegacyHelp.swift | 8 + .../scan/ios-native/Notes/LoginView.swift | 20 + .../scan/ios-native/Notes/ScannerView.swift | 13 + .../scan/ios-native/Notes/Store.swift | 7 + tests/fixtures/scan/ios-native/Podfile.lock | 13 + tests/fixtures/scan/ios-native/README.md | 7 + .../scan/ios-native/store/appstore.md | 25 + .../scan/ios-native/storebound.config.ts | 18 + .../teaser/Planner.xcodeproj/project.pbxproj | 13 + tests/fixtures/scan/teaser/Planner/Ads.swift | 9 + tests/fixtures/scan/teaser/Planner/Info.plist | 10 + .../scan/teaser/Planner/LoginView.swift | 20 + .../scan/teaser/Planner/PrivacyInfo.xcprivacy | 19 + .../scan/teaser/Planner/ProStore.swift | 7 + .../scan/teaser/Planner/SettingsView.swift | 10 + tests/fixtures/scan/teaser/Podfile.lock | 9 + tests/fixtures/scan/teaser/README.md | 6 + tests/fixtures/scan/teaser/store/appstore.md | 23 + .../fixtures/scan/teaser/storebound.config.ts | 18 + .../Editor/GoogleMobileAdsDependencies.xml | 9 + .../scan/unity/Assets/Scripts/PhotoBooth.cs | 12 + .../scan/unity/Assets/Scripts/RatePopup.cs | 12 + .../scan/unity/Assets/Scripts/Shop.cs | 9 + .../scan/unity/Packages/manifest.json | 8 + .../ProjectSettings/ProjectSettings.asset | 11 + tests/fixtures/scan/unity/README.md | 5 + tests/fixtures/scan/unity/store/appstore.md | 23 + .../fixtures/scan/unity/storebound.config.ts | 17 + tests/scan.test.ts | 245 +++++++++ tools/gen-adapters.ts | 2 +- tools/scrub.ts | 3 +- tsconfig.json | 3 +- 109 files changed, 3103 insertions(+), 31 deletions(-) create mode 100644 cli/lib/scan/config-edit.ts create mode 100644 cli/lib/scan/declare.ts create mode 100644 cli/lib/scan/index.ts create mode 100644 cli/lib/scan/permissions.ts create mode 100644 cli/lib/scan/project.ts create mode 100644 cli/lib/scan/rules.ts create mode 100644 cli/lib/scan/sdks.ts create mode 100644 cli/scan.ts create mode 100644 tests/fixtures/scan/android/README.md create mode 100644 tests/fixtures/scan/android/app/build.gradle.kts create mode 100644 tests/fixtures/scan/android/app/src/main/AndroidManifest.xml create mode 100644 tests/fixtures/scan/android/app/src/main/java/com/example/budget/AuthRepository.kt create mode 100644 tests/fixtures/scan/android/gradle/libs.versions.toml create mode 100644 tests/fixtures/scan/android/storebound.config.ts create mode 100644 tests/fixtures/scan/capacitor/README.md create mode 100644 tests/fixtures/scan/capacitor/android/app/src/main/AndroidManifest.xml create mode 100644 tests/fixtures/scan/capacitor/android/variables.gradle create mode 100644 tests/fixtures/scan/capacitor/capacitor.config.json create mode 100644 tests/fixtures/scan/capacitor/ios/App/App/Info.plist create mode 100644 tests/fixtures/scan/capacitor/package.json create mode 100644 tests/fixtures/scan/capacitor/src/main.ts create mode 100644 tests/fixtures/scan/clean/Clean.xcodeproj/project.pbxproj create mode 100644 tests/fixtures/scan/clean/Clean/AccountView.swift create mode 100644 tests/fixtures/scan/clean/Clean/Clean.entitlements create mode 100644 tests/fixtures/scan/clean/Clean/Info.plist create mode 100644 tests/fixtures/scan/clean/Clean/LoginView.swift create mode 100644 tests/fixtures/scan/clean/Clean/PrivacyInfo.xcprivacy create mode 100644 tests/fixtures/scan/clean/Clean/StoreView.swift create mode 100644 tests/fixtures/scan/clean/Clean/Tracking.swift create mode 100644 tests/fixtures/scan/clean/Podfile.lock create mode 100644 tests/fixtures/scan/clean/README.md create mode 100644 tests/fixtures/scan/clean/android/app/build.gradle.kts create mode 100644 tests/fixtures/scan/clean/android/app/src/main/AndroidManifest.xml create mode 100644 tests/fixtures/scan/clean/store/appstore.md create mode 100644 tests/fixtures/scan/clean/store/listing.md create mode 100644 tests/fixtures/scan/clean/storebound.config.ts create mode 100644 tests/fixtures/scan/flutter/README.md create mode 100644 tests/fixtures/scan/flutter/android/app/build.gradle create mode 100644 tests/fixtures/scan/flutter/android/app/src/main/AndroidManifest.xml create mode 100644 tests/fixtures/scan/flutter/ios/Runner/Info.plist create mode 100644 tests/fixtures/scan/flutter/lib/main.dart create mode 100644 tests/fixtures/scan/flutter/pubspec.lock create mode 100644 tests/fixtures/scan/flutter/pubspec.yaml create mode 100644 tests/fixtures/scan/flutter/store/appstore.md create mode 100644 tests/fixtures/scan/flutter/storebound.config.ts create mode 100644 tests/fixtures/scan/ios-native/Notes.xcodeproj/project.pbxproj create mode 100644 tests/fixtures/scan/ios-native/Notes/Api.swift create mode 100644 tests/fixtures/scan/ios-native/Notes/Info.plist create mode 100644 tests/fixtures/scan/ios-native/Notes/LegacyHelp.swift create mode 100644 tests/fixtures/scan/ios-native/Notes/LoginView.swift create mode 100644 tests/fixtures/scan/ios-native/Notes/ScannerView.swift create mode 100644 tests/fixtures/scan/ios-native/Notes/Store.swift create mode 100644 tests/fixtures/scan/ios-native/Podfile.lock create mode 100644 tests/fixtures/scan/ios-native/README.md create mode 100644 tests/fixtures/scan/ios-native/store/appstore.md create mode 100644 tests/fixtures/scan/ios-native/storebound.config.ts create mode 100644 tests/fixtures/scan/teaser/Planner.xcodeproj/project.pbxproj create mode 100644 tests/fixtures/scan/teaser/Planner/Ads.swift create mode 100644 tests/fixtures/scan/teaser/Planner/Info.plist create mode 100644 tests/fixtures/scan/teaser/Planner/LoginView.swift create mode 100644 tests/fixtures/scan/teaser/Planner/PrivacyInfo.xcprivacy create mode 100644 tests/fixtures/scan/teaser/Planner/ProStore.swift create mode 100644 tests/fixtures/scan/teaser/Planner/SettingsView.swift create mode 100644 tests/fixtures/scan/teaser/Podfile.lock create mode 100644 tests/fixtures/scan/teaser/README.md create mode 100644 tests/fixtures/scan/teaser/store/appstore.md create mode 100644 tests/fixtures/scan/teaser/storebound.config.ts create mode 100644 tests/fixtures/scan/unity/Assets/GoogleMobileAds/Editor/GoogleMobileAdsDependencies.xml create mode 100644 tests/fixtures/scan/unity/Assets/Scripts/PhotoBooth.cs create mode 100644 tests/fixtures/scan/unity/Assets/Scripts/RatePopup.cs create mode 100644 tests/fixtures/scan/unity/Assets/Scripts/Shop.cs create mode 100644 tests/fixtures/scan/unity/Packages/manifest.json create mode 100644 tests/fixtures/scan/unity/ProjectSettings/ProjectSettings.asset create mode 100644 tests/fixtures/scan/unity/README.md create mode 100644 tests/fixtures/scan/unity/store/appstore.md create mode 100644 tests/fixtures/scan/unity/storebound.config.ts create mode 100644 tests/scan.test.ts diff --git a/.cursor/rules/storebound.mdc b/.cursor/rules/storebound.mdc index 2c41da63..5e4b77e5 100644 --- a/.cursor/rules/storebound.mdc +++ b/.cursor/rules/storebound.mdc @@ -14,8 +14,8 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t chat). storebound's MCP server does not offer these at all. 2. **Dry run first.** Every write command has `--dry` (MCP: `dry_run`, default true). Show the dry run, then run it for real only after the owner agrees. -3. **Read before you write.** `storebound check` (offline) and `storebound validate` (read-only, both stores) tell you - what is missing and in which order to fix it. +3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check` + (offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it. 4. **Credentials only from the environment or `.storebound/`** in the project (gitignored). Never ask for keys, passwords or tokens in chat, never print them, never write them into the config, docs or commits. The same goes for the App Review demo account (`reviewDemoAccount` in `.storebound/credentials.json`): the owner puts it there. @@ -34,7 +34,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t - CLI: `storebound ` (`storebound help`); config `storebound.config.ts`, credentials in env or `.storebound/`. - MCP: `storebound mcp` (stdio). MCP 2026-07-28 + 2025-11-25. Write tools default to `dry_run: true`; submit / release / cancel / delete / send are not exposed. -- Readiness: `storebound check` (offline), `storebound validate` (read-only, both stores). +- Readiness: `storebound scan` (offline rejection risks in the project files), `storebound check` (offline), `storebound validate` (read-only, both stores). ## Skills diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index ecfa9e79..b142f365 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -14,8 +14,8 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t chat). storebound's MCP server does not offer these at all. 2. **Dry run first.** Every write command has `--dry` (MCP: `dry_run`, default true). Show the dry run, then run it for real only after the owner agrees. -3. **Read before you write.** `storebound check` (offline) and `storebound validate` (read-only, both stores) tell you - what is missing and in which order to fix it. +3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check` + (offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it. 4. **Credentials only from the environment or `.storebound/`** in the project (gitignored). Never ask for keys, passwords or tokens in chat, never print them, never write them into the config, docs or commits. The same goes for the App Review demo account (`reviewDemoAccount` in `.storebound/credentials.json`): the owner puts it there. @@ -34,7 +34,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t - CLI: `storebound ` (`storebound help`); config `storebound.config.ts`, credentials in env or `.storebound/`. - MCP: `storebound mcp` (stdio). MCP 2026-07-28 + 2025-11-25. Write tools default to `dry_run: true`; submit / release / cancel / delete / send are not exposed. -- Readiness: `storebound check` (offline), `storebound validate` (read-only, both stores). +- Readiness: `storebound scan` (offline rejection risks in the project files), `storebound check` (offline), `storebound validate` (read-only, both stores). ## Skills diff --git a/AGENTS.md b/AGENTS.md index 19cf225e..9381d6d3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,8 +15,8 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t chat). storebound's MCP server does not offer these at all. 2. **Dry run first.** Every write command has `--dry` (MCP: `dry_run`, default true). Show the dry run, then run it for real only after the owner agrees. -3. **Read before you write.** `storebound check` (offline) and `storebound validate` (read-only, both stores) tell you - what is missing and in which order to fix it. +3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check` + (offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it. 4. **Credentials only from the environment or `.storebound/`** in the project (gitignored). Never ask for keys, passwords or tokens in chat, never print them, never write them into the config, docs or commits. The same goes for the App Review demo account (`reviewDemoAccount` in `.storebound/credentials.json`): the owner puts it there. @@ -35,7 +35,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t - CLI: `storebound ` (`storebound help`); config `storebound.config.ts`, credentials in env or `.storebound/`. - MCP: `storebound mcp` (stdio). MCP 2026-07-28 + 2025-11-25. Write tools default to `dry_run: true`; submit / release / cancel / delete / send are not exposed. -- Readiness: `storebound check` (offline), `storebound validate` (read-only, both stores). +- Readiness: `storebound scan` (offline rejection risks in the project files), `storebound check` (offline), `storebound validate` (read-only, both stores). ## Skills diff --git a/CHANGELOG.md b/CHANGELOG.md index ba686186..d01836dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,23 @@ ## Unreleased +- `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, + analytics, attribution, crash, sign-in, payments, push, with versions, file:line and each vendor's data disclosure + page) and reports each risk with the guideline, evidence, fix, severity and skill: 2.1(a) demo account and + placeholder text, 5.1.1(v) account deletion, 4.8 login services, 3.1.1 Restore Purchases and outside payments, + 3.1.2(c) subscription information, 5.1.2(i) App Tracking Transparency, 5.1.1(ii) / (iv) purpose strings, 5.1.1(i) + privacy link, privacy manifests (ITMS-91053 / 91061), 2.3.10 other platforms, 2.3.7 keywords, 2.3.8 "For Kids", 4.2 + web wrappers, 2.5.1 UIWebView and private URL schemes, 2.5.5 IPv6, ATS, export compliance, 1.3 kids ads, 5.6.1 / + 3.2.2(x) review prompts, privacy labels vs SDKs, and on Play the API 36 target SDK requirement (since 2026-08-31), + the delete-account URL, App access, foreground service types, exact alarms, QUERY_ALL_PACKAGES, SMS / call log and + the reserved com.example package name. It also proposes the Data safety / App Privacy / ATT / privacy manifest + answers, each "detected (file:line)" or "ask owner", as a diff against the config; `--write` adds only the detected + answers (new `appPrivacy` block for tracking). `scan.ignore` records findings the owner accepts, with the reason. + `validate` includes the open findings (`--no-scan` skips), `check` now asks for unanswered dataSafety booleans. + Fixtures for iOS, Android, Capacitor, Unity, Flutter, a clean project and the teaser under `tests/fixtures/scan/`. + - New logo: a glossy indigo box with an upward arrow (`brand/master/logo-mark.png`, `brand/README.md`). Every logo file comes from it through `tools/brand-assets.py`: desktop app icons (PNG sizes, `.icns`, a `.ico` with its own image per size, Windows tiles), the site's favicon.ico, maskable web app icons with a manifest, apple-touch-icon, diff --git a/GEMINI.md b/GEMINI.md index dd0810f0..97a3416e 100644 --- a/GEMINI.md +++ b/GEMINI.md @@ -13,8 +13,8 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t chat). storebound's MCP server does not offer these at all. 2. **Dry run first.** Every write command has `--dry` (MCP: `dry_run`, default true). Show the dry run, then run it for real only after the owner agrees. -3. **Read before you write.** `storebound check` (offline) and `storebound validate` (read-only, both stores) tell you - what is missing and in which order to fix it. +3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check` + (offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it. 4. **Credentials only from the environment or `.storebound/`** in the project (gitignored). Never ask for keys, passwords or tokens in chat, never print them, never write them into the config, docs or commits. The same goes for the App Review demo account (`reviewDemoAccount` in `.storebound/credentials.json`): the owner puts it there. @@ -33,7 +33,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t - CLI: `storebound ` (`storebound help`); config `storebound.config.ts`, credentials in env or `.storebound/`. - MCP: `storebound mcp` (stdio). MCP 2026-07-28 + 2025-11-25. Write tools default to `dry_run: true`; submit / release / cancel / delete / send are not exposed. -- Readiness: `storebound check` (offline), `storebound validate` (read-only, both stores). +- Readiness: `storebound scan` (offline rejection risks in the project files), `storebound check` (offline), `storebound validate` (read-only, both stores). ## Skills diff --git a/README.md b/README.md index 4940806f..456a4c04 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ your own click. | 8 | **Privacy and accounts** | privacy policy page template (`init`), `privacy-manifest --ios ` (PrivacyInfo.xcprivacy, required-reason APIs, SDK manifests), `validate` checks the policy, delete-account and terms URLs answer | host the pages, link them in both consoles and inside the app; in-app account deletion (`privacy-policy`, `privacy-manifest`, `account-deletion`) | | | 9 | **Icons** | `icons`: App Store 1024 without alpha, Play 512, adaptive + legacy Android launcher icons, web icons, Capacitor sources | | | | 10 | **Screenshots and previews** | `shots capture / render / check / gallery`, `play images`, `apple screenshots`, `shots record / video`, `apple previews`, `apple ppo create / upload` (App Store product page tests from `shots` variants; see [Store art](#store-art)) | Play store listing experiments (optional, `store-screenshots`) | uploading the promo video to YouTube; `apple ppo start / stop` | -| 11 | **Validate** | `check` (offline) and `validate` (read-only on both stores: every blocker in fix order, plus the local renders) | the UI-only items `validate` cannot see (`store-preflight` lists them) | | +| 11 | **Validate** | `scan` (offline: rejection risks in the project files, see [Catch rejections before you submit](#catch-rejections-before-you-submit)), `check` (offline) and `validate` (read-only on both stores: every blocker in fix order, plus the local renders) | the UI-only items `validate` cannot see (`store-preflight` lists them) | | | 12 | **Submit** | `play release --version-code N --production draft`, `apple status` | Play: countries / regions, open the production draft and save it (`play-first-release`) | **Play: Send changes for review. App Store: Submit for Review.** | | 13 | **After review** | `apple status --wait-review`, `apple release --phased on / pause`, `play rollout --halt`, reply drafts (`review-rejections`) | | releasing the approved version, resuming or completing a phased release or rollout (terminal commands that ask first, `release-management`) | | 14 | **Live app** | `health [--weekly]` (crash / ANR vitals vs Play's thresholds, App Store diagnostics; also in `validate`), `reviews list / draft`, `analytics snapshot / compare`, `prices export`, `prices import --dry`, `apple ppo status` | `store-health`, `review-replies`, `store-analytics`; Play statistics come from the reports bucket (no API) | `reviews send` (approved drafts only), `prices import` (asks first) | @@ -88,6 +88,81 @@ New personal Play developer accounts also need a closed test with 12+ testers fo rollouts after approval, Beta App Review, tester invitations, sending review replies, applying price changes and starting / stopping a product page test too. None of these is an MCP tool; the terminal commands ask first. +## 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, +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 +from) and reports every rejection risk it can prove, each with the guideline, the evidence, the fix, a severity and the +skill to open. On the teaser fixture (`tests/fixtures/scan/teaser`): + +```text +$ storebound scan +Rejection risks: 2 blocker, 3 high, 0 medium, 0 low + 1. BLOCKER 2.1(a) · App Store · Sign-in is required but there is no demo account for App Review + at storebound.config.ts:12 reviewAccess: { signInRequired: true, instructions: 'Sign in with the demo account.' }, + at storebound.config.ts:11 accounts: { enabled: true }, + at Podfile.lock:3 Google Sign-In: GoogleSignIn 7.1.0 + 2. BLOCKER 5.1.1(v) · App Store · Accounts can be created but no in-app account deletion was found + at storebound.config.ts:11 accounts: { enabled: true }, + at Planner/LoginView.swift:11 Button("Create account") { Task { try await AccountApi.signUp() } } + at Planner/LoginView.swift:17 static func signUp() async throws { + 3. HIGH 4.8 · App Store · Third-party login (Google / Facebook / ...) without Sign in with Apple or another equivalent login option + at Podfile.lock:3 Google Sign-In: GoogleSignIn 7.1.0 + at Planner/LoginView.swift:9 GIDSignIn.sharedInstance.signIn(withPresenting: rootViewController()) { _, _ in } + 4. HIGH 3.1.1 · App Store · Restorable purchases (non-consumables or subscriptions) but no Restore Purchases path was found + at storebound.config.ts:16 com.example.planner.pro (non_consumable) + 5. HIGH 5.1.2(i) · App Store · Tracking-capable code without App Tracking Transparency (Google AdMob, IDFA) + at Podfile.lock:2 Google AdMob: Google-Mobile-Ads-SDK 11.10.0 + at Planner/Ads.swift:7 print(ASIdentifierManager.shared().advertisingIdentifier) +``` + +Every finding also has a `fix:` line and the skill. Below the risks comes the declarations proposal: the Play Data +safety and App Store App Privacy answers, App Tracking Transparency and privacy manifest entries the detected SDKs and +code imply, each marked **detected (file:line)** or **ask owner**, as a diff against `dataSafety` / `appPrivacy` in +the config. Nothing is written unless you run `storebound scan --write` (only detected answers; questions stay +questions). The MCP tool `scan` is read-only and cannot write; `validate` includes the open scan findings; the desktop +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 | + +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). + +**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. + ## 5-minute quick start You need [Bun](https://bun.sh) 1.1+ (and `ffmpeg` for icons, screenshots and video). @@ -209,6 +284,7 @@ run in the background with a log (`storebound shots render > .storebound/render. | `check` | local | config, copy limits, data safety, products, subscriptions, profile (delete-account URL, demo account, terms URL), files; warns on untranslated release notes | | `catalog diff [--store] [--threshold 10]` | API, read-only | one catalog vs both stores: missing / extra / mismatched products and subscriptions, US and override prices, locales, offers, per-region price differences between the stores; exit 1 on mismatches | | `check --aso` | local | keyword audit: App Store keyword field rules, Play stuffing / claims | +| `scan [--store apple\|play] [--json] [--write]` | local, read-only | rejection risks in the project itself (stack, SDKs, Info.plist, manifest, listings) with guideline, evidence file:line, fix and skill; Data safety / App Privacy / ATT / privacy manifest proposal as a diff (`--write` adds the detected answers to the config); exit 1 on blockers | | `validate [--apple] [--play]` | API, read-only | readiness report with ordered blockers plus the local renders checks (`--no-local` skips); exit 1 while any blocker is left | | `whats-new [--since ]` | local | draft player-facing release notes from git log into both listing files | | `privacy-manifest --ios ` | local | PrivacyInfo.xcprivacy, required-reason APIs, SDKs without manifests | @@ -394,7 +470,7 @@ per-request `_meta`, `resultType`, cacheable `tools/list`) and, on the same proc `initialize` (2025-11-25, 2025-06-18, 2025-03-26, 2024-11-05). It runs each tool as a CLI call in the project directory (the server's working directory, or `STOREBOUND_PROJECT`) and returns the output. -- One tool per command. Read-only: `check`, `check_aso`, `validate`, `catalog_diff`, `health`, `reviews_list`, `prices_diff`, +- One tool per command. Read-only: `scan`, `check`, `check_aso`, `validate`, `catalog_diff`, `health`, `reviews_list`, `prices_diff`, `analytics_compare`, `apple_status`, `apple_next_build`, `apple_testflight_status`, `apple_ppo_status`, `play_status`, `play_next_version_code`, `privacy_manifest`, `shots_check`. Local writes: `import_fastlane`, `whats_new`, `icons`, `health_report`, `reviews_draft`, `prices_export`, `analytics_snapshot`, `shots_capture`, `shots_render`, diff --git a/apps/desktop/src/dev/fixtures.ts b/apps/desktop/src/dev/fixtures.ts index 41fc83e3..9f03809d 100644 --- a/apps/desktop/src/dev/fixtures.ts +++ b/apps/desktop/src/dev/fixtures.ts @@ -6,7 +6,7 @@ import { type Account, type AccountCheck, type AppsListResult, type AppStatus, type CacheEntry, DEFAULT_SETTINGS, type DownloadEvent, type DraftsResult, type ListingField, type ListingsResult, type PortfolioResult, type Project, type ProjectSummary, type Settings, type StoreApp, type StoreRelease, type Studio, type ToolResult } from '../api'; import { buildApps, type Overrides } from '../lib/identity'; -import type { CatalogDiff, HealthSnapshot, MetricRow, Review, TestFlightStatus, ValidateResult } from '../lib/model'; +import type { CatalogDiff, HealthSnapshot, MetricRow, Review, TestFlightStatus, ValidateResult, ScanResult } from '../lib/model'; import { ANALYTICS, DECLARATIONS, LISTING_TEXT, PPO, PPO_STORE, PRICE_DIFF, PRICES, renderArt, RENDERS } from './fixtures-more'; export const FIXTURE_MARKER = 'storebound-dev-fixtures'; @@ -342,6 +342,30 @@ const VALIDATE: Record = { 'p-tidy': { blockers: 0, findings: [] }, }; +const scanCounts = (f: ScanResult['findings']): ScanResult['counts'] => { + const c = { blocker: 0, high: 0, medium: 0, low: 0, accepted: 0 }; + for (const x of f) { if (x.accepted) c.accepted++; else c[x.severity]++; } + return c; +}; +const SCAN_PRISM: ScanResult['findings'] = [ + { rule: 'att', guideline: '5.1.2(i)', store: 'apple', severity: 'high', title: 'Tracking-capable code without App Tracking Transparency (AppLovin MAX, Unity Ads)', + evidence: [{ file: 'Packages/manifest.json', line: 4, text: 'com.applovin.mediation.ads 8.1.0' }], fix: 'Add NSUserTrackingUsageDescription and request ATT before the SDKs start, or configure non-personalized ads and answer "no tracking".', skill: 'ads-mediation-checks', ref: 'https://developer.apple.com/app-store/review/guidelines/' }, + { rule: 'play-target-sdk', guideline: 'Play: Target API level', store: 'play', severity: 'blocker', title: 'targetSdk 35 is below 36, which new apps and updates need since 2026-08-31', + evidence: [{ file: 'ProjectSettings/ProjectSettings.asset', line: 212, text: 'targetSdk 35' }], fix: 'Raise targetSdk to 36, test, upload a new AAB.', skill: 'play-first-release', ref: 'https://developer.android.com/google/play/requirements/target-sdk' }, + { rule: 'restore-purchases', guideline: '3.1.1', store: 'apple', severity: 'high', title: 'Restorable purchases (non-consumables or subscriptions) but no Restore Purchases path was found', + evidence: [{ file: 'storebound.config.ts', line: 41, text: 'no_ads (non_consumable)' }], fix: 'Add a visible "Restore Purchases" button on the store screen or in Settings.', skill: 'store-iap-setup', ref: 'https://developer.apple.com/app-store/review/guidelines/' }, + { rule: 'demo-account', guideline: '2.1(a)', store: 'apple', severity: 'blocker', title: 'Sign-in is required but there is no demo account for App Review', + evidence: [{ file: 'storebound.config.ts', line: 17, text: 'reviewAccess: { signInRequired: true }' }], fix: 'Add the App Review demo account in .storebound/ (review-access skill).', skill: 'review-access', ref: 'https://developer.apple.com/app-store/review/guidelines/', accepted: 'leaderboards only; the game plays without signing in' }, +]; +const SCAN: Record = { + 'p-prism': { stacks: ['unity'], sdks: [{ id: 'applovin', name: 'AppLovin MAX', category: 'ads', tracking: true }, { id: 'unity-ads', name: 'Unity Ads', category: 'ads', tracking: true }, { id: 'gameanalytics', name: 'GameAnalytics', category: 'analytics', tracking: false }], + findings: SCAN_PRISM, counts: scanCounts(SCAN_PRISM), + declarations: { changed: true, items: [{ area: 'appPrivacy', what: 'tracking', value: 'AppLovin MAX, Unity Ads can track', status: 'ask', evidence: [] }, { area: 'dataSafety', what: 'PSL_DEVICE_ID', value: 'collect: advertising, analytics, fraud', status: 'detected', evidence: [{ file: 'Packages/manifest.json', line: 4 }] }] } }, + 'p-tidy': { stacks: ['ios-native', 'android-native'], sdks: [{ id: 'sentry', name: 'Sentry', category: 'crash', tracking: false }], findings: [], counts: scanCounts([]), + declarations: { changed: false, items: [] } }, +}; +const SCAN_EMPTY: ScanResult = { stacks: [], sdks: [], findings: [], counts: scanCounts([]), declarations: { changed: false, items: [] } }; + function field(f: string, length: number, limit: number, required = true): ListingField { return { field: f, length, limit, required, state: !length ? (required ? 'missing' : 'empty-optional') : length > limit ? 'over' : 'ok' }; } @@ -404,6 +428,7 @@ function read(method: string, id: string, args: Record = {}): T case 'apple.testflight_status': return ok(method, TF[id]); case 'catalog.diff': return ok(method, CATALOG[id]); case 'validate': return ok(method, VALIDATE[id]); + case 'scan': return ok(method, SCAN[id] ?? SCAN_EMPTY); case 'project.declarations': return ok(method, DECLARATIONS[id]); case 'project.listing_text': return ok(method, LISTING_TEXT[id]); case 'project.renders': return ok(method, RENDERS[id]); diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts index 3c3b80df..dab9d1b5 100644 --- a/apps/desktop/src/i18n/en.ts +++ b/apps/desktop/src/i18n/en.ts @@ -396,6 +396,21 @@ export const en = { 'checks.validateEmptyText': 'What is still missing on the App Store and Google Play before a submission, in the order to fix it.', 'checks.ready': 'No blockers', 'checks.readyText': 'Both stores have what a submission needs.', + 'checks.scan': 'Rejection risks', + '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.scanSdks': 'SDKs: {list}', + 'checks.scanAsk': '{count} declaration answers only you can give', + 'checks.scanAsk_one': '1 declaration answer only you can give', + 'checks.scanWrite': 'Detected Data safety / App Privacy answers differ from the config: storebound scan --write adds them', + 'checks.accepted': 'Accepted: {reason}', + 'checks.sev.blocker': 'Blocker', + 'checks.sev.high': 'High', + 'checks.sev.medium': 'Medium', + 'checks.sev.accepted': 'Accepted', + 'checks.sev.low': 'Low', 'folders.lead': 'One folder per app with its storebound.config.ts (iOS and Android in one config). Pick the store accounts each app uses; the keys stay in the keychain.', 'folders.list': 'App folders', diff --git a/apps/desktop/src/i18n/tr.ts b/apps/desktop/src/i18n/tr.ts index 1669f588..f52e84a4 100644 --- a/apps/desktop/src/i18n/tr.ts +++ b/apps/desktop/src/i18n/tr.ts @@ -398,6 +398,21 @@ export const tr: Record = { 'checks.validateEmptyText': 'Göndermeden önce App Store ve Google Play\'de hâlâ eksik olanlar, düzeltme sırasıyla.', 'checks.ready': 'Engel yok', 'checks.readyText': 'İki mağazada da gönderim için gerekenler tamam.', + 'checks.scan': 'Ret riskleri', + '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.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', + 'checks.scanWrite': 'Bulunan Data safety / App Privacy cevapları ayardan farklı: storebound scan --write ekler', + 'checks.accepted': 'Kabul edildi: {reason}', + 'checks.sev.blocker': 'Engel', + 'checks.sev.high': 'Yüksek', + 'checks.sev.medium': 'Orta', + 'checks.sev.accepted': 'Kabul', + 'checks.sev.low': 'Düşük', 'folders.lead': 'Her uygulama için storebound.config.ts dosyası olan bir klasör (iOS ve Android tek ayarda). Her uygulamanın kullandığı mağaza hesaplarını seçin; anahtarlar anahtar zincirinde kalır.', 'folders.list': 'Uygulama klasörleri', diff --git a/apps/desktop/src/lib/model.ts b/apps/desktop/src/lib/model.ts index 52e8b402..e685441d 100644 --- a/apps/desktop/src/lib/model.ts +++ b/apps/desktop/src/lib/model.ts @@ -31,6 +31,19 @@ export interface ParityRow { id: string; region: string; currency: string; apple export interface CatalogDiff { errors: number; rows: CatalogRow[]; parity: ParityRow[] } export interface Finding { store: 'apple' | 'play'; level: 'blocker' | 'warn' | 'ok'; code: string; msg: string; fix?: string } export interface ValidateResult { blockers: number; findings: Finding[] } +/** `storebound scan --json` (offline rejection-risk scan of the project files), the parts the Checks tab shows. */ +export type ScanSeverity = 'blocker' | 'high' | 'medium' | 'low'; +export interface ScanFinding { + rule: string; guideline: string; store: 'apple' | 'play'; severity: ScanSeverity; title: string; + evidence: { file: string; line: number; text?: string }[]; fix: string; skill: string; ref: string; accepted?: string; +} +export interface ScanResult { + stacks: string[]; + sdks: { id: string; name: string; category: string; tracking: boolean }[]; + findings: ScanFinding[]; + counts: Record & { accepted: number }; + declarations: { changed: boolean; items: { area: string; what: string; value: string; status: 'detected' | 'ask'; evidence: { file: string; line: number }[] }[] }; +} export const isError = (x: unknown): x is { error: string } => !!x && typeof x === 'object' && typeof (x as { error?: unknown }).error === 'string'; diff --git a/apps/desktop/src/screens/tabs/Checks.tsx b/apps/desktop/src/screens/tabs/Checks.tsx index 16972f2f..5e0dde69 100644 --- a/apps/desktop/src/screens/tabs/Checks.tsx +++ b/apps/desktop/src/screens/tabs/Checks.tsx @@ -1,9 +1,9 @@ -// Checks: the offline config check (every time) and the read-only store readiness report (`validate`, on demand) -// with its ordered blockers and fix hints. +// Checks: the offline rejection-risk scan of the project files (`scan`, every time), the offline config check and +// the read-only store readiness report (`validate`, on demand) with its ordered blockers and fix hints. import type { Project } from '../../api'; import { t } from '../../i18n'; import { ago } from '../../lib/format'; -import type { Finding, ValidateResult } from '../../lib/model'; +import type { Finding, ScanResult, ScanSeverity, ValidateResult } from '../../lib/model'; import { useData, useRead } from '../../store'; import { Icon } from '../../ui/icons'; import { Card, Chip, Empty, ErrorNotice, Skeleton } from '../../ui/kit'; @@ -12,6 +12,50 @@ import { useExports } from '../../ui/Exports'; const LEVEL: Record = { blocker: ['bad', 'alertCircle'], warn: ['warn', 'alert'], ok: ['ok', 'check'] }; +const SEV: Record = { blocker: ['bad', 'alertCircle'], high: ['bad', 'alert'], medium: ['warn', 'alert'], low: ['info', 'info'] }; + +/** The `storebound scan` card: rejection risks with guideline, evidence file:line, fix and skill. */ +function ScanCard({ project }: { project: Project }) { + const s = useRead(project.id, 'scan', { network: false, title: t('checks.scan') }); + const findings = Array.isArray(s.data?.findings) ? s.data!.findings : []; + const sdks = Array.isArray(s.data?.sdks) ? s.data!.sdks : []; + const asks = (Array.isArray(s.data?.declarations?.items) ? s.data!.declarations.items : []).filter(x => x.status === 'ask').length; + return ( + x.name).join(', ') }) : t('checks.scanSub')} pad={false} + actions={}> + {s.error &&
} + {!s.data ? (s.loading && !s.error ?
: null) + : !findings.length ? {t('checks.scanCleanText')} : ( +
+ {findings.map((f, i) => { + const [tone, icon] = f.accepted ? ['ok', 'check'] as const : SEV[f.severity] ?? SEV.low; + const ev = Array.isArray(f.evidence) ? f.evidence : []; + return ( +
+ +
+ {f.guideline} · {f.title} + {ev.slice(0, 2).map((e, j) => {e.file}:{e.line}{e.text ? ` ${e.text}` : ''})} + {f.accepted ? {t('checks.accepted', { reason: f.accepted })} + : {f.fix} {f.skill}} +
+ {t(f.accepted ? 'checks.sev.accepted' : `checks.sev.${f.severity}` as Parameters[0])} + {f.store === 'apple' ? 'App Store' : 'Google Play'} +
+ ); + })} +
+ )} + {s.data && (asks > 0 || s.data.declarations?.changed) && ( +
+ {asks > 0 &&
{t('checks.scanAsk', { count: asks })}
} + {s.data.declarations?.changed &&
{t('checks.scanWrite')}
} +
+ )} +
+ ); +} + export function ChecksTab({ project }: { project: Project }) { const d = useData(); const e = d.statusOf(project); @@ -23,6 +67,7 @@ export function ChecksTab({ project }: { project: Project }) { const findings = [...(v.data?.findings ?? [])].sort((a, b) => ['blocker', 'warn', 'ok'].indexOf(a.level) - ['blocker', 'warn', 'ok'].indexOf(b.level)); return (
+
d.refreshPortfolio(false)} disabled={!!d.portfolioBusy}>{t('checks.again')}}> {!e ?
: !problems.length && !warnings.length ? ( diff --git a/cli/index.ts b/cli/index.ts index 5644e5f7..66a98639 100755 --- a/cli/index.ts +++ b/cli/index.ts @@ -18,6 +18,7 @@ const PLAIN: Record Promise, string]> = { 'apps': [() => import('./apps'), 'list (every app the store keys can see: App Store Connect team, Play developer accounts; --icons) | check (key works / permission missing / revoked, with the fix); --store apple|play, --json; read-only'], 'desktop': [() => import('./desktop'), 'open the storebound desktop app (in an app folder: add or select it there); not installed: the download for this system, --download saves it to ~/Downloads after checking its signature (never installs)'], 'doctor': [() => import('./doctor'), 'local tools for screenshots, previews, icons and captures (ffmpeg, Chrome, playwright, Xcode, adb, git) and how to install what is missing; --json'], + 'scan': [() => import('./scan'), 'offline, read-only rejection-risk scan of the project itself (stack, SDKs, Info.plist, manifest, listings) with guideline, evidence file:line, fix and skill, plus the Data safety / App Privacy / ATT / privacy manifest proposal; --write puts the detected answers into the config; --json; exit 1 on blockers'], 'privacy-manifest': [() => import('./privacy-manifest'), 'iOS PrivacyInfo.xcprivacy + required-reason API + SDK manifest scan (--ios )'], }; const COMMANDS: Record Promise, string]> = { diff --git a/cli/lib/config.ts b/cli/lib/config.ts index b4ef28b0..37793fdd 100644 --- a/cli/lib/config.ts +++ b/cli/lib/config.ts @@ -304,6 +304,14 @@ export interface ReviewAccess { instructions?: string; } +/** App Privacy: does the app (or an SDK in it) track users across other companies' apps and websites? true needs + * App Tracking Transparency (NSUserTrackingUsageDescription + the prompt) and the privacy manifest's NSPrivacyTracking. */ +export interface AppPrivacyConfig { + tracking?: boolean; + /** Domains that receive tracking data (privacy manifest NSPrivacyTrackingDomains). */ + trackingDomains?: string[]; +} + export type SubscriptionPeriod = 'P1W' | 'P1M' | 'P2M' | 'P3M' | 'P6M' | 'P1Y'; /** Introductory offer for new subscribers. Apple: subscriptionIntroductoryOffers (first-time subscribers of the group, @@ -470,6 +478,11 @@ export interface ShipConfig { baseTerritory?: string; }; dataSafety?: DataSafety; + /** App Store App Privacy answers storebound cannot derive from dataSafety (App Privacy has no API: the owner enters + * them in App Store Connect). `storebound scan` proposes them from the detected SDKs and code. */ + appPrivacy?: AppPrivacyConfig; + /** `storebound scan`: findings the owner has looked at and accepts, by rule id (with the reason, shown in the report). */ + scan?: { ignore?: { rule: string; store?: 'apple' | 'play'; reason: string }[] }; /** Ads: `validate` checks that /app-ads.txt is reachable and contains every line listed here. */ ads?: { appAdsTxt?: string[] }; /** Rendered store graphics dir (///NN.png|jpg). Defaults to shots.out. */ @@ -549,6 +562,14 @@ export function validateConfig(c: unknown): string[] { if (cfg.apple.screenshotTypes && !cfg.apple.screenshotTypes.every(t => /^APP_[A-Z0-9_]+$/.test(t))) e.push('apple.screenshotTypes: display types like APP_IPHONE_67'); e.push(...validateTestflight(cfg.apple.testflight)); } + if (cfg.appPrivacy) { + if (cfg.appPrivacy.tracking !== undefined && typeof cfg.appPrivacy.tracking !== 'boolean') e.push('appPrivacy.tracking: true | false'); + if (cfg.appPrivacy.trackingDomains && !(Array.isArray(cfg.appPrivacy.trackingDomains) && cfg.appPrivacy.trackingDomains.every(d => typeof d === 'string' && /^[a-z0-9.-]+$/i.test(d)))) + e.push('appPrivacy.trackingDomains: a list of host names'); + } + for (const [i, x] of (cfg.scan?.ignore ?? []).entries()) + if (!x || typeof x.rule !== 'string' || !x.rule || typeof x.reason !== 'string' || !x.reason.trim() || (x.store !== undefined && x.store !== 'apple' && x.store !== 'play')) + e.push(`scan.ignore[${i}]: { rule: '', reason: 'why this is fine', store?: 'apple' | 'play' }`); if (cfg.ads?.appAdsTxt && !cfg.ads.appAdsTxt.every(l => typeof l === 'string' && l.split(',').length >= 3)) e.push('ads.appAdsTxt: lines like "example-network.com, pub-123, DIRECT, abc123"'); const seen = new Set(); diff --git a/cli/lib/profile.ts b/cli/lib/profile.ts index 609a4f3f..5145b08d 100644 --- a/cli/lib/profile.ts +++ b/cli/lib/profile.ts @@ -11,6 +11,8 @@ export function profileIssues(config: ShipConfig, o: { demoAccount: boolean }): const err = (msg: string) => out.push({ level: 'error', msg }); const warn = (msg: string) => out.push({ level: 'warn', msg }); const accounts = !!config.accounts?.enabled; + if (config.dataSafety) for (const k of ['collectsData', 'encryptedInTransit', 'deletionRequest'] as const) + if (typeof config.dataSafety[k] !== 'boolean') err(`dataSafety.${k}: not answered (true | false; ask the owner, store-declarations skill)`); const acm = config.dataSafety?.accountCreation ?? ['PSL_ACM_NONE']; if (accounts) { if (config.play && !config.accounts!.deletionUrl) err('accounts.enabled: set accounts.deletionUrl (Play asks for a web page to request account deletion; account-deletion skill)'); diff --git a/cli/lib/scan/config-edit.ts b/cli/lib/scan/config-edit.ts new file mode 100644 index 00000000..4eb064dd --- /dev/null +++ b/cli/lib/scan/config-edit.ts @@ -0,0 +1,71 @@ +// Writes one top-level block (dataSafety, appPrivacy) into storebound.config.ts / .js / .json text: replaces the +// existing `key: { ... }` property, or inserts it after the `app: { ... }` block. Pure text in, text out; the rest of +// the file (comments, order, formatting) stays as it is. Used by `storebound scan --write` only. + +/** Index of the brace that closes the one at `open`, skipping strings, template literals and comments. -1 if none. */ +export function matchBrace(text: string, open: number): number { + const pairs: Record = { '{': '}', '[': ']', '(': ')' }; + const stack: string[] = []; + for (let i = open; i < text.length; i++) { + const ch = text[i]!; + if (ch === '/' && text[i + 1] === '/') { i = text.indexOf('\n', i); if (i < 0) return -1; continue; } + if (ch === '/' && text[i + 1] === '*') { i = text.indexOf('*/', i + 2); if (i < 0) return -1; i++; continue; } + if (ch === '"' || ch === '\'' || ch === '`') { + for (i++; i < text.length && text[i] !== ch; i++) if (text[i] === '\\') i++; + continue; + } + if (pairs[ch]) stack.push(pairs[ch]!); + else if (ch === '}' || ch === ']' || ch === ')') { + if (stack.pop() !== ch) return -1; + if (!stack.length) return i; + } + } + return -1; +} + +const ID = /^[A-Za-z_$][A-Za-z0-9_$]*$/; + +/** A plain value as TypeScript source (single quotes, unquoted keys, trailing commas), indented by `ind`. */ +export function toTs(v: unknown, ind = ''): string { + const next = ind + ' '; + if (v === null || v === undefined) return 'undefined'; + if (typeof v === 'string') return `'${v.replace(/\\/g, '\\\\').replace(/'/g, '\\\'')}'`; + if (typeof v === 'number' || typeof v === 'boolean') return String(v); + if (Array.isArray(v)) { + const parts = v.map(x => toTs(x, next)); + const one = `[${parts.join(', ')}]`; + return one.length <= 100 && !one.includes('\n') ? one : `[\n${parts.map(p => `${next}${p},`).join('\n')}\n${ind}]`; + } + const entries = Object.entries(v as Record).filter(([, x]) => x !== undefined); + if (!entries.length) return '{}'; + const parts = entries.map(([k, x]) => `${ID.test(k) ? k : `'${k}'`}: ${toTs(x, next)}`); + const one = `{ ${parts.join(', ')} }`; + return one.length <= 110 && !one.includes('\n') && entries.every(([, x]) => typeof x !== 'object' || Array.isArray(x)) ? one : `{\n${parts.map(p => `${next}${p},`).join('\n')}\n${ind}}`; +} + +/** The config text with `key` set to `value` (plus an optional comment line above it). */ +export function upsertBlock(text: string, file: string, key: string, value: unknown, comment?: string): string { + if (file.endsWith('.json')) { + const j = JSON.parse(text) as Record; + j[key] = value; + return JSON.stringify(j, null, 2) + '\n'; + } + const re = new RegExp(`^([ \\t]*)${key}\\s*:\\s*\\{`, 'm'); + const m = re.exec(text); + if (m) { + const ind = m[1]!; + const open = m.index + m[0].length - 1; + const close = matchBrace(text, open); + if (close < 0) throw new Error(`${file}: could not find the end of the ${key} block`); + return `${text.slice(0, m.index)}${ind}${key}: ${toTs(value, ind)}${text.slice(close + 1)}`; + } + const app = /^([ \t]*)app\s*:\s*\{/m.exec(text); + if (!app) throw new Error(`${file}: no app block found to insert ${key} after; add it by hand`); + const ind = app[1]!; + const close = matchBrace(text, app.index + app[0].length - 1); + if (close < 0) throw new Error(`${file}: could not find the end of the app block`); + let at = close + 1; + if (text[at] === ',') at++; + const block = `\n${comment ? `${ind}// ${comment}\n` : ''}${ind}${key}: ${toTs(value, ind)},`; + return text.slice(0, at) + block + text.slice(at); +} diff --git a/cli/lib/scan/declare.ts b/cli/lib/scan/declare.ts new file mode 100644 index 00000000..2f4dadca --- /dev/null +++ b/cli/lib/scan/declare.ts @@ -0,0 +1,155 @@ +// Declarations proposal for `storebound scan`: from the detected SDKs, permissions and code, the Play Data safety and +// App Store App Privacy answers, App Tracking Transparency and the privacy manifest entries the project needs, each +// marked "detected (file:line)" or "ask owner", and a diff against the config's dataSafety / appPrivacy blocks. +// Only detected items are ever written (`scan --write`); "ask owner" items stay questions (AGENTS.md rule 5). Pure. +import type { AppPrivacyConfig, DataSafety, DataUsage, PlayPurpose, ShipConfig } from '../config'; +import { APPLE_PRIVACY, applePurpose } from '../declarations'; +import { REQUIRED_REASON_APIS } from '../privacy-manifest'; +import { IOS_PERMISSIONS } from './permissions'; +import { grep, type Hit, lineOf, type ProjectFacts } from './project'; +import { SIGNALS } from './rules'; + +export type DeclArea = 'dataSafety' | 'appPrivacy' | 'att' | 'privacyManifest'; +export interface DeclItem { area: DeclArea; what: string; value: string; status: 'detected' | 'ask'; evidence: Hit[]; note?: string } +export interface DataDiff { + type: string; + /** App Privacy category / type it maps to. */ + apple: string; + change: 'add' | 'merge' | 'same' | 'kept'; + before: DataUsage | null; + after: DataUsage; + evidence: Hit[]; +} +export interface Proposal { + items: DeclItem[]; + diff: DataDiff[]; + /** The dataSafety block --write would write (null when nothing was detected and the config has none). */ + dataSafety: Partial & { data: Record } | null; + appPrivacy: AppPrivacyConfig | null; + appPrivacyChange: { from: boolean | null; to: boolean } | null; + /** Types an SDK collects that the config's dataSafety does not declare (the privacy-labels rule). */ + labelGaps: { type: string; apple: string; evidence: Hit[] }[]; + /** --write would change the config. */ + changed: boolean; +} + +const PERMISSION_DATA: Record = { + NSCameraUsageDescription: { type: 'PSL_PHOTOS', note: 'only if photos / videos leave the device (uploaded, sent to an API)' }, + NSMicrophoneUsageDescription: { type: 'PSL_AUDIO', note: 'only if recordings leave the device' }, + NSPhotoLibraryUsageDescription: { type: 'PSL_PHOTOS', note: 'only if picked photos leave the device' }, + NSLocationWhenInUseUsageDescription: { type: 'PSL_APPROX_LOCATION', note: 'approximate or precise (PSL_PRECISE_LOCATION), only if it leaves the device' }, + NSContactsUsageDescription: { type: 'PSL_CONTACTS', note: 'only if contacts leave the device' }, + NSHealthShareUsageDescription: { type: 'PSL_HEALTH', note: 'only if health data leaves the device' }, + NSCalendarsFullAccessUsageDescription: { type: 'PSL_CALENDAR', note: 'only if events leave the device' }, +}; + +const uniq = (a: T[]): T[] => [...new Set(a)]; +const sorted = (a: readonly string[] | undefined) => [...(a ?? [])].sort().join(); +const usageEq = (a: DataUsage, b: DataUsage) => a.shared === b.shared && sorted(a.collect) === sorted(b.collect) && sorted(a.share) === sorted(b.share); + +export function proposeDeclarations(p: ProjectFacts, c: ShipConfig | null, configFile?: { path: string; text: string } | null): Proposal { + const items: DeclItem[] = []; + const detected = new Map; share: Set; evidence: Hit[]; from: string[] }>(); + for (const s of p.sdks) { + const d0 = s.deps[0]!; + const ev: Hit = { file: d0.file, line: d0.line, text: `${s.sdk.name}: ${d0.name}${d0.version ? ` ${d0.version}` : ''}` }; + for (const d of s.sdk.data) { + const e = detected.get(d.type) ?? { collect: new Set(), share: new Set(), evidence: [], from: [] }; + for (const x of d.collect) e.collect.add(x); + for (const x of d.share ?? []) e.share.add(x); + if (!e.from.includes(s.sdk.name)) { e.from.push(s.sdk.name); e.evidence.push(ev); } + detected.set(d.type, e); + } + } + // accounts proven by the config or sign-up code + const signUp = grep(p.sources, SIGNALS.signUp, 1); + if (c?.accounts?.enabled || signUp.length) { + const ev: Hit[] = signUp.length ? signUp : [{ file: configFile?.path ?? 'storebound.config.ts', line: configFile ? lineOf(configFile.text, /accounts\s*:/) : 1, text: 'accounts.enabled' }]; + for (const t of ['PSL_EMAIL', 'PSL_USER_ACCOUNT']) { + const e = detected.get(t) ?? { collect: new Set(), share: new Set(), evidence: [], from: [] }; + e.collect.add('account'); e.collect.add('functionality'); e.evidence.push(...ev); e.from.push('accounts'); + detected.set(t, e); + } + } + const have = c?.dataSafety?.data ?? {}; + const diff: DataDiff[] = []; + const out: Record = {}; + for (const [type, e] of detected) { + const share = [...e.share].sort(); + const det: DataUsage = { shared: share.length > 0, collect: [...e.collect].sort(), ...(share.length ? { share } : {}) }; + const before = have[type] ?? null; + const after: DataUsage = before ? { + ...before, shared: before.shared || det.shared, + collect: uniq([...before.collect, ...det.collect]).sort(), + ...((before.share?.length || share.length) ? { share: uniq([...(before.share ?? []), ...share]).sort() } : {}), + } : det; + out[type] = after; + const [cat, name] = APPLE_PRIVACY[type] ?? ['Other Data', 'Other Data Types']; + diff.push({ type, apple: `${cat} / ${name}`, change: !before ? 'add' : usageEq(before, after) ? 'same' : 'merge', before, after, evidence: e.evidence.slice(0, 3) }); + items.push({ area: 'dataSafety', what: type, value: `collect: ${after.collect.join(', ')}${after.shared ? `; shared: ${(after.share ?? []).join(', ')}` : ''}`, status: 'detected', evidence: e.evidence.slice(0, 2), + note: `from ${e.from.join(', ')}; ephemeral / optional: ask owner` }); + } + for (const [type, u] of Object.entries(have)) if (!detected.has(type)) { + out[type] = u; + const [cat, name] = APPLE_PRIVACY[type] ?? ['Other Data', 'Other Data Types']; + diff.push({ type, apple: `${cat} / ${name}`, change: 'kept', before: u, after: u, evidence: [] }); + } + // permissions that may mean collected data: questions, never written + for (const perm of IOS_PERMISSIONS) for (const k of perm.keys) { + const e = p.plist.get(k), pd = PERMISSION_DATA[k]; + if (!e || !pd || out[pd.type]) continue; + items.push({ area: 'dataSafety', what: pd.type, value: `collected? ${pd.note}`, status: 'ask', evidence: [{ ...e.at, text: k }] }); + } + const labelGaps = c?.dataSafety ? diff.filter(d => d.change === 'add').map(d => ({ type: d.type, apple: d.apple, evidence: d.evidence })) : []; + + // top-level Data safety answers + const anyData = Object.keys(out).length > 0; + if (anyData) items.push({ area: 'dataSafety', what: 'collectsData', value: 'true', status: 'detected', evidence: diff.flatMap(d => d.evidence).slice(0, 1) }); + for (const k of ['encryptedInTransit', 'deletionRequest'] as const) + items.push({ area: 'dataSafety', what: k, value: c?.dataSafety ? String(c.dataSafety[k]) : '?', status: 'ask', evidence: [], note: k === 'encryptedInTransit' ? 'all traffic over HTTPS / TLS? (ATS and the SDKs\' own endpoints)' : 'can users ask for their data to be deleted?' }); + if ((c?.accounts?.enabled || signUp.length) && (c?.dataSafety?.accountCreation ?? ['PSL_ACM_NONE']).includes('PSL_ACM_NONE')) + items.push({ area: 'dataSafety', what: 'accountCreation', value: 'which sign-up methods (PSL_ACM_USER_ID_PASSWORD, PSL_ACM_OAUTH, ...)?', status: 'ask', evidence: signUp.slice(0, 1) }); + + // App Privacy per type (linked / tracking are owner answers) + for (const d of diff) { + const shared = d.after.shared ? d.after.share ?? [] : []; + // a purpose the data is shared for counts once, as the third party's (AdMob: Third-Party Advertising, not the developer's) + const purposes = uniq([...d.after.collect.filter(x => !shared.includes(x)).map(x => applePurpose(x, false)), ...shared.map(x => applePurpose(x, true))]).sort(); + items.push({ area: 'appPrivacy', what: d.apple, value: purposes.join(', '), status: d.change === 'kept' ? 'ask' : 'detected', evidence: d.evidence.slice(0, 1), note: 'linked to identity? used for tracking? ask owner' }); + } + + // tracking + ATT + const attReq = grep(p.sources, SIGNALS.attRequest, 1); + const attStr = p.plist.get('NSUserTrackingUsageDescription'); + const trackers = p.sdks.filter(s => s.sdk.tracking); + let tracking: boolean | null = null; + if (attReq.length) { tracking = true; items.push({ area: 'appPrivacy', what: 'tracking', value: 'true (the app asks for App Tracking Transparency)', status: 'detected', evidence: attReq }); } + else if (trackers.length) items.push({ area: 'appPrivacy', what: 'tracking', value: `${trackers.map(s => s.sdk.name).join(', ')} can track: personalized ads / attribution on?`, status: 'ask', evidence: trackers.map(s => ({ file: s.deps[0]!.file, line: s.deps[0]!.line, text: s.sdk.name })).slice(0, 2) }); + if (attStr) items.push({ area: 'att', what: 'NSUserTrackingUsageDescription', value: String(attStr.value).slice(0, 80), status: 'detected', evidence: [{ ...attStr.at, text: 'NSUserTrackingUsageDescription' }] }); + else if (trackers.length || attReq.length) items.push({ area: 'att', what: 'NSUserTrackingUsageDescription', value: 'needed if anything tracks, e.g. "Your data is used to show ads that fit your interests."', status: 'ask', evidence: [] }); + if (attReq.length) items.push({ area: 'att', what: 'ATT request', value: 'found', status: 'detected', evidence: attReq }); + if (trackers.length || attReq.length) items.push({ area: 'appPrivacy', what: 'trackingDomains', value: 'the SDKs\' tracking domains (from each SDK\'s privacy manifest)', status: 'ask', evidence: [] }); + + // privacy manifest + if (p.ios) { + const declared = new Map(); + for (const m of p.privacyManifests) for (const [k, v] of Object.entries(m.apis)) declared.set(k, v); + const nativeSrc = p.sources.filter(s => /\.(swift|m|mm|h)$/.test(s.path)); + for (const [cat, def] of Object.entries(REQUIRED_REASON_APIS)) { + const h = grep(nativeSrc, def.symbols, 1); + if (!h.length) continue; + const have = declared.get(cat); + items.push({ area: 'privacyManifest', what: cat, value: have?.length ? `declared: ${have.join(', ')}` : `add with a reason: ${def.note}`, status: have?.length ? 'detected' : 'ask', evidence: h }); + } + const m = p.privacyManifests[0]; + if (tracking !== null || m) items.push({ area: 'privacyManifest', what: 'NSPrivacyTracking', value: tracking ? 'true' : m ? String(m.tracking) : '?', status: tracking ? 'detected' : 'ask', evidence: m ? [{ file: m.path, line: 1, text: 'PrivacyInfo.xcprivacy' }] : [] }); + if (diff.length) items.push({ area: 'privacyManifest', what: 'NSPrivacyCollectedDataTypes', value: uniq(diff.map(d => d.apple.split(' / ')[1]!)).join(', '), status: 'detected', evidence: diff.flatMap(d => d.evidence).slice(0, 1), note: 'the app\'s own collection; SDKs declare theirs in their manifests' }); + } + + const dsChanged = diff.some(d => d.change === 'add' || d.change === 'merge') || (anyData && c?.dataSafety?.collectsData === false); + const dataSafety = anyData || c?.dataSafety ? { ...(c?.dataSafety ?? {}), collectsData: anyData || !!c?.dataSafety?.collectsData, data: out } : null; + const from = c?.appPrivacy?.tracking ?? null; + const appPrivacyChange = tracking !== null && from !== tracking ? { from, to: tracking } : null; + const appPrivacy = appPrivacyChange ? { ...(c?.appPrivacy ?? {}), tracking: appPrivacyChange.to } : c?.appPrivacy ?? null; + return { items, diff, dataSafety, appPrivacy, appPrivacyChange, labelGaps, changed: dsChanged || !!appPrivacyChange }; +} diff --git a/cli/lib/scan/index.ts b/cli/lib/scan/index.ts new file mode 100644 index 00000000..894b715a --- /dev/null +++ b/cli/lib/scan/index.ts @@ -0,0 +1,121 @@ +// `storebound scan` engine: detect the project, run the rejection-risk rules, propose the declarations. Offline and +// read-only (the only write is `--write`, done by the command, never here). +import { existsSync, readFileSync } from 'node:fs'; +import { join, relative } from 'node:path'; +import { CONFIG_NAMES, loadConfig, type ShipConfig } from '../config'; +import { reviewDemoAccount } from '../credentials'; +import { proposeDeclarations, type Proposal } from './declare'; +import { detectProject, ECO_LABEL, type ProjectFacts, type Stack, where } from './project'; +import { type ScanFinding, scanRules, type Severity } from './rules'; +import type { SdkCategory } from './sdks'; + +export interface ScanReport { + root: string; + config: string | null; + configError: string | null; + stacks: Stack[]; + platforms: { ios: boolean; android: boolean }; + sdks: { id: string; name: string; category: SdkCategory; tracking: boolean; deps: { eco: string; name: string; version: string | null; file: string; line: number }[] }[]; + permissions: { key: string; value: string; file: string; line: number }[]; + android: { targetSdk: number | null; targetSdkAt: string | null; permissions: string[] }; + findings: ScanFinding[]; + counts: Record & { accepted: number }; + declarations: Proposal; + scanned: number; + notes: string[]; +} + +export interface ScanRun { report: ScanReport; facts: ProjectFacts; config: ShipConfig | null; configPath: string | null } + +/** Find the project's config: --config, else storebound.config.* in `dir` (no upward search: a fixture or a + * sub-project must not pick up a parent's config). */ +async function findConfig(dir: string, explicit?: string): Promise<{ config: ShipConfig | null; path: string | null; error: string | null }> { + const path = explicit ? join(dir, explicit) : CONFIG_NAMES.map(n => join(dir, n)).find(existsSync); + if (!path) return { config: null, path: null, error: null }; + try { return { config: (await loadConfig(path)).config, path, error: null }; } catch (e) { return { config: null, path, error: (e as Error).message.split('\n').slice(0, 4).join('; ') }; } +} + +export async function runScan(dir: string, o: { config?: string } = {}): Promise { + const facts = detectProject(dir); + const { config, path: configPath, error } = await findConfig(dir, o.config); + const rel = (p: string) => relative(dir, p) || p; + const readRel = (p: string | undefined): { path: string; text: string } | undefined => { + if (!p) return undefined; + const abs = join(dir, p); + try { return existsSync(abs) ? { path: rel(abs), text: readFileSync(abs, 'utf8') } : undefined; } catch { return undefined; } + }; + const listings = { + apple: (config ? config.apple : true) ? readRel(config?.apple?.listing ?? 'store/appstore.md') : undefined, + play: (config ? config.play : true) ? readRel(config?.play?.listing ?? 'store/listing.md') : undefined, + captions: readRel(config?.shots?.copy ?? 'store/shots/copy.json'), + }; + 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 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.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 = { + root: dir, config: configPath ? rel(configPath) : null, configError: error, + stacks: facts.stacks, platforms: { ios: facts.ios, android: facts.android }, + sdks: facts.sdks.map(s => ({ id: s.sdk.id, name: s.sdk.name, category: s.sdk.category, tracking: s.sdk.tracking, deps: s.deps.map(d => ({ eco: d.eco, name: d.name, version: d.version, file: d.file, line: d.line })) })), + permissions: [...facts.plist.values()].filter(e => /UsageDescription$/.test(e.key)).map(e => ({ key: e.key, value: String(e.value ?? ''), file: e.at.file, line: e.at.line })), + android: { targetSdk: facts.androidInfo.targetSdk?.value ?? null, targetSdkAt: facts.androidInfo.targetSdk ? where(facts.androidInfo.targetSdk.at) : null, permissions: [...new Set(facts.androidInfo.permissions.map(x => x.name.replace(/^android\.permission\./, '')))] }, + findings, counts, declarations, scanned: facts.scanned, notes, + }; + return { report, facts, config, configPath }; +} + +const TAG: Record = { blocker: 'BLOCKER', high: 'HIGH ', medium: 'MEDIUM ', low: 'low ' }; +const STACK: Record = { 'ios-native': 'iOS (native)', 'android-native': 'Android (native)', 'react-native': 'React Native', expo: 'Expo', capacitor: 'Capacitor', cordova: 'Cordova', flutter: 'Flutter', unity: 'Unity', godot: 'Godot', web: 'web' }; + +/** The report as plain text (the terminal output of `storebound scan`). */ +export function formatScan(r: ScanReport, o: { declarations?: boolean } = {}): string { + const L: string[] = []; + L.push(`storebound scan · ${r.config ? r.config : 'no storebound.config.ts (project files only)'}`); + if (r.configError) L.push(`config not loaded: ${r.configError}`); + L.push(`stack: ${r.stacks.map(s => STACK[s]).join(', ') || 'unknown'} · targets: ${[r.platforms.ios && 'iOS', r.platforms.android && 'Android'].filter(Boolean).join(', ') || 'none found'} · ${r.scanned} files`); + if (r.sdks.length) { + L.push('', 'SDKs'); + for (const s of r.sdks) { + const d = s.deps[0]!; + L.push(` ${s.name.padEnd(30)} ${s.category}${s.tracking ? ', tracking-capable' : ''} · ${ECO_LABEL[d.eco as keyof typeof ECO_LABEL] ?? d.eco} ${d.name}${d.version ? ` ${d.version}` : ''} (${d.file}:${d.line})${s.deps.length > 1 ? ` +${s.deps.length - 1}` : ''}`); + } + } + if (r.android.targetSdk !== null) L.push(`Android targetSdk ${r.android.targetSdk} (${r.android.targetSdkAt})`); + const open = r.findings.filter(f => !f.accepted); + L.push('', `Rejection risks: ${r.counts.blocker} blocker, ${r.counts.high} high, ${r.counts.medium} medium, ${r.counts.low} low${r.counts.accepted ? ` (+${r.counts.accepted} accepted by the owner)` : ''}`); + if (!open.length) L.push(' none found in the project files and config'); + r.findings.forEach((f, i) => { + L.push(`${String(i + 1).padStart(3)}. ${f.accepted ? 'accepted' : TAG[f.severity]} ${f.guideline} · ${f.store === 'apple' ? 'App Store' : 'Google Play'} · ${f.title}`); + for (const e of f.evidence.slice(0, 3)) L.push(` at ${e.file}:${e.line}${e.text ? ` ${e.text}` : ''}`); + if (f.accepted) L.push(` owner: ${f.accepted}`); + else L.push(` fix: ${f.fix}`, ` skill: ${f.skill} · ${f.ref}`); + }); + if (o.declarations !== false) { + const d = r.declarations; + L.push('', 'Declarations proposal (detected = proven by a file; ask owner = only the owner knows)'); + const areas: [string, string][] = [['dataSafety', 'Data safety'], ['appPrivacy', 'App Privacy'], ['att', 'App Tracking Transparency'], ['privacyManifest', 'Privacy manifest']]; + for (const [a, label] of areas) { + const items = d.items.filter(x => x.area === a); + if (!items.length) continue; + L.push(` ${label}`); + for (const x of items) L.push(` ${x.status === 'detected' ? 'detected ' : 'ask owner'} ${x.what}: ${x.value}${x.evidence[0] ? ` (${x.evidence[0].file}:${x.evidence[0].line})` : ''}${x.note ? ` · ${x.note}` : ''}`); + } + const changes = d.diff.filter(x => x.change === 'add' || x.change === 'merge'); + if (changes.length || d.appPrivacyChange) { + L.push('', ` Diff against ${r.config ?? 'the config'} (written only with --write):`); + for (const x of changes) { + if (x.change === 'add') L.push(` + dataSafety.data.${x.type}: { shared: ${x.after.shared}, collect: [${x.after.collect.join(', ')}]${x.after.share?.length ? `, share: [${x.after.share.join(', ')}]` : ''} }`); + else L.push(` ~ dataSafety.data.${x.type}: collect [${x.before!.collect.join(', ')}] -> [${x.after.collect.join(', ')}]${x.after.shared !== x.before!.shared ? `, shared ${x.before!.shared} -> ${x.after.shared}` : ''}${(x.after.share ?? []).join() !== (x.before!.share ?? []).join() ? `, share [${(x.before!.share ?? []).join(', ')}] -> [${(x.after.share ?? []).join(', ')}]` : ''}`); + } + if (d.appPrivacyChange) L.push(` ~ appPrivacy.tracking: ${d.appPrivacyChange.from ?? 'unset'} -> ${d.appPrivacyChange.to}`); + } else if (r.config) L.push('', ` No changes to ${r.config}: the dataSafety / appPrivacy blocks already cover what was detected.`); + } + if (r.notes.length) L.push('', ...r.notes.map(n => `note: ${n}`)); + L.push('', 'Checked at review, not by scan: crashes and bugs on the reviewer\'s device, broken links (storebound validate checks the URLs), screenshots that do not match the app, minimum functionality and spam judgement (4.2, 4.3), local law (5.2). See the review-rejections skill.'); + return L.join('\n'); +} diff --git a/cli/lib/scan/permissions.ts b/cli/lib/scan/permissions.ts new file mode 100644 index 00000000..56abf809 --- /dev/null +++ b/cli/lib/scan/permissions.ts @@ -0,0 +1,55 @@ +// iOS privacy-sensitive APIs and the Info.plist purpose string each one needs (Apple: "Requesting access to protected +// resources"; a missing string makes the app crash on the first request and App Store Connect rejects the upload +// with ITMS-90683). `code` finds the API in app sources, `packages` the npm / pub / Unity packages that call it. +// Checked 2026-10-11 against developer.apple.com/documentation/bundleresources/information-property-list. +export interface PermissionDef { + /** Info.plist keys; any one of them satisfies the check (e.g. calendars before / since iOS 17). */ + keys: string[]; + what: string; + code: RegExp; + packages: string[]; +} + +export const IOS_PERMISSIONS: PermissionDef[] = [ + { keys: ['NSCameraUsageDescription'], what: 'camera', + code: /\bAVCaptureDevice\b|sourceType\s*=\s*\.camera|UIImagePickerController\.SourceType\.camera|\bWebCamTexture\b|\bVNDocumentCameraViewController\b/, + packages: ['expo-camera', 'react-native-vision-camera', 'react-native-camera', '@capacitor/camera', 'image_picker', 'camera', 'mobile_scanner', 'expo-image-picker', 'react-native-image-picker', 'cordova-plugin-camera', '@capacitor-mlkit/barcode-scanning'] }, + { keys: ['NSMicrophoneUsageDescription'], what: 'microphone', + code: /\bAVAudioRecorder\b|requestRecordPermission|\.record\b.*AVAudioSession|AVAudioApplication\.requestRecordPermission|\bMicrophone\.Start\b|\bAudioEffectRecord\b/, + packages: ['expo-av', 'react-native-audio-recorder-player', 'record', 'flutter_sound', 'cordova-plugin-media-capture', '@capacitor-community/voice-recorder'] }, + { keys: ['NSPhotoLibraryUsageDescription'], what: 'photo library', + code: /\bPHPhotoLibrary\.(requestAuthorization|shared)|\bPHAsset\.fetch|\bALAssetsLibrary\b/, + packages: ['expo-media-library', 'photo_manager', '@react-native-camera-roll/camera-roll', 'image_picker', '@capacitor/camera'] }, + { keys: ['NSPhotoLibraryAddUsageDescription', 'NSPhotoLibraryUsageDescription'], what: 'saving to the photo library', + code: /UIImageWriteToSavedPhotosAlbum|UISaveVideoAtPathToSavedPhotosAlbum|PHAssetChangeRequest|PHAssetCreationRequest/, + packages: ['gallery_saver', 'image_gallery_saver'] }, + { keys: ['NSLocationWhenInUseUsageDescription', 'NSLocationAlwaysAndWhenInUseUsageDescription'], what: 'location', + code: /\bCLLocationManager\b|requestWhenInUseAuthorization|requestAlwaysAuthorization|\bInput\.location\.Start\b|\bCLLocationUpdate\b/, + packages: ['expo-location', '@capacitor/geolocation', 'geolocator', 'location', '@react-native-community/geolocation', 'react-native-geolocation-service', 'cordova-plugin-geolocation'] }, + { keys: ['NSContactsUsageDescription'], what: 'contacts', + code: /\bCNContactStore\b|\bABAddressBook/, + packages: ['expo-contacts', 'react-native-contacts', 'flutter_contacts', 'contacts_service', '@capacitor-community/contacts', 'cordova-plugin-contacts'] }, + { keys: ['NSCalendarsFullAccessUsageDescription', 'NSCalendarsWriteOnlyAccessUsageDescription', 'NSCalendarsUsageDescription'], what: 'calendars', + code: /\bEKEventStore\b/, packages: ['expo-calendar', 'device_calendar', 'react-native-calendar-events'] }, + { keys: ['NSRemindersFullAccessUsageDescription', 'NSRemindersUsageDescription'], what: 'reminders', code: /requestFullAccessToReminders|entityType:\s*\.reminder|EKEntityType\.reminder/, packages: [] }, + { keys: ['NSBluetoothAlwaysUsageDescription'], what: 'Bluetooth', + code: /\bCBCentralManager\b|\bCBPeripheralManager\b/, packages: ['react-native-ble-plx', 'flutter_blue_plus', 'flutter_blue', '@capacitor-community/bluetooth-le', 'cordova-plugin-ble-central'] }, + { keys: ['NSFaceIDUsageDescription'], what: 'Face ID', + code: /deviceOwnerAuthenticationWithBiometrics|evaluatePolicy\(/, packages: ['expo-local-authentication', 'local_auth', 'react-native-biometrics', '@capgo/capacitor-native-biometric'] }, + { keys: ['NSMotionUsageDescription'], what: 'motion and fitness', code: /\bCMMotionActivityManager\b|\bCMPedometer\b|\bCMAltimeter\b/, packages: ['expo-sensors'] }, + { keys: ['NSSpeechRecognitionUsageDescription'], what: 'speech recognition', code: /\bSFSpeechRecognizer\b/, packages: ['@react-native-voice/voice', 'speech_to_text', 'expo-speech-recognition'] }, + { keys: ['NSHealthShareUsageDescription'], what: 'Health data', code: /\bHKHealthStore\b/, packages: ['react-native-health', 'health', '@kingstinct/react-native-healthkit'] }, + { keys: ['NSUserTrackingUsageDescription'], what: 'App Tracking Transparency', + code: /requestTrackingAuthorization|ATTrackingStatusBinding\.RequestAuthorizationTracking/, + packages: ['expo-tracking-transparency', 'react-native-tracking-transparency', 'app_tracking_transparency', '@capacitor-community/app-tracking-transparency', 'com.unity.ads.ios-support'] }, +]; + +/** A purpose string that says nothing (empty, a placeholder, or a generic template Apple rejects under 5.1.1(ii)). */ +export function vaguePurpose(s: string): 'empty' | 'vague' | null { + const t = s.trim(); + if (!t) return 'empty'; + if (/^(todo|tbd|fixme|placeholder|lorem|test|xxx+|\.+|-+|description|usage description|\$\([A-Z_]+\))$/i.test(t)) return 'empty'; + // Expo / plugin defaults like "Allow $(PRODUCT_NAME) to access your camera" name no reason + if (t.length < 20 || /^(allow|let) \$\(PRODUCT_NAME\) to access your [a-z ]+\.?$/i.test(t) || /^(this app|we) (needs?|requires?|uses?) (access to )?(your )?[a-z ]+\.?$/i.test(t)) return 'vague'; + return null; +} diff --git a/cli/lib/scan/project.ts b/cli/lib/scan/project.ts new file mode 100644 index 00000000..7a610179 --- /dev/null +++ b/cli/lib/scan/project.ts @@ -0,0 +1,430 @@ +// Project detection for `storebound scan`: reads a mobile app or game project (read-only, offline) and works out the +// stack, the dependencies (with versions and the file:line they come from), the Info.plist keys (from Info.plist files, +// Xcode INFOPLIST_KEY_* build settings, Expo app.json, Unity ProjectSettings and Godot export presets), entitlements, +// privacy manifests, the Android manifest (permissions, services, target SDK) and the app's own source files. +// Tolerant on purpose: an unreadable or odd file is skipped, never an exception. +import { readdirSync, readFileSync, statSync } from 'node:fs'; +import { basename, extname, join, relative, sep } from 'node:path'; +import { type Manifest, parseManifest } from '../privacy-manifest'; +import { type DepRef, type Eco, matchesSdk, SDKS, type SdkDef } from './sdks'; + +export interface Loc { file: string; line: number } +export interface PlistEntry { key: string; value: unknown; at: Loc } +export interface Hit extends Loc { text: string } + +export type Stack = 'ios-native' | 'android-native' | 'react-native' | 'expo' | 'capacitor' | 'cordova' | 'flutter' | 'unity' | 'godot' | 'web'; + +export interface DetectedSdk { sdk: SdkDef; deps: DepRef[] } + +export interface ProjectFacts { + root: string; + stacks: Stack[]; + /** The project has iOS / Android build files (or a cross-platform engine that targets them). */ + ios: boolean; + android: boolean; + deps: DepRef[]; + sdks: DetectedSdk[]; + /** Info.plist keys merged from every source; first source wins. */ + plist: Map; + /** Where Info.plist keys came from (empty = the project has no readable iOS settings: plist rules are skipped). */ + plistSources: string[]; + entitlements: Map; + privacyManifests: Manifest[]; + androidInfo: { + manifests: string[]; + permissions: { name: string; at: Loc }[]; + services: { name: string; fgsType: string | null; at: Loc }[]; + targetSdk: { value: number; at: Loc } | null; + /** targetSdk is set by a tool we cannot read (Flutter SDK, Expo SDK, Unity "automatic"). */ + targetSdkFrom: string | null; + formFactor: 'phone' | 'wear' | 'tv' | 'automotive'; + }; + /** Capacitor server.url / Cordova pointing at a remote site. */ + remoteStart: { url: string; at: Loc } | null; + /** App source files (Swift, Objective-C, Kotlin, Java, Dart, JS / TS, C#, GDScript, HTML). */ + sources: { path: string; text: string }[]; + /** Files looked at, relative to root (for the report). */ + scanned: number; +} + +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']); +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[] { + const out: string[] = []; + const walk = (dir: string, depth: number) => { + if (depth > 14 || out.length >= MAX_FILES) return; + let names: string[]; + try { names = readdirSync(dir); } catch { return; } + for (const n of names.sort()) { + if (SKIP_DIRS.has(n) || n === '.DS_Store') continue; + const p = join(dir, n); + let st; + try { st = statSync(p); } catch { continue; } + if (st.isDirectory()) { + // 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('/')); + if (out.length >= MAX_FILES) return; + } + }; + walk(root, 0); + return out; +} + +export const lineAt = (text: string, index: number): number => (index <= 0 ? 1 : text.slice(0, index).split('\n').length); +/** Line of the first occurrence of `needle` (1 when not found). */ +export const lineOf = (text: string, needle: string | RegExp): number => { + const i = typeof needle === 'string' ? text.indexOf(needle) : text.search(needle); + return i < 0 ? 1 : lineAt(text, i); +}; + +// ---- plist ---- + +type PV = string | number | boolean | PV[] | { [k: string]: PV }; + +/** Minimal XML plist reader: the value tree, plus the line of every top-level key. Never throws (bad input -> {}). */ +export function parsePlist(xml: string): { value: Record; lines: Map } { + const lines = new Map(); + const re = /<(\/?)(dict|array|key|string|integer|real|true|false|date|data)(\s*\/)?>||<\?[\s\S]*?\?>|]*>|<\/?plist[^>]*>/g; + const toks: { tag: string; close: boolean; self: boolean; at: number; end: number }[] = []; + for (const m of xml.matchAll(re)) if (m[2]) toks.push({ tag: m[2], close: m[1] === '/', self: !!m[3] || m[2] === 'true' || m[2] === 'false', at: m.index!, end: m.index! + m[0].length }); + let i = 0; + const unesc = (s: string) => s.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, '\'').replace(/&/g, '&'); + const readText = (tag: string): string => { + const open = toks[i]!; + if (open.self) { i++; return ''; } + const close = toks[i + 1]; + i += 2; + return close && close.tag === tag && close.close ? unesc(xml.slice(open.end, close.at)) : ''; + }; + const value = (depth: number): PV => { + const t = toks[i]; + if (!t || depth > 30) { i++; return ''; } + switch (t.tag) { + case 'true': i++; if (toks[i]?.tag === 'true' && toks[i]!.close) i++; return true; + case 'false': i++; if (toks[i]?.tag === 'false' && toks[i]!.close) i++; return false; + case 'integer': case 'real': return Number(readText(t.tag)); + case 'string': case 'date': case 'data': return readText(t.tag); + case 'array': { + i++; + const a: PV[] = []; + if (t.self) return a; + while (i < toks.length && !(toks[i]!.tag === 'array' && toks[i]!.close)) a.push(value(depth + 1)); + i++; + return a; + } + case 'dict': { + i++; + const o: Record = {}; + if (t.self) return o; + while (i < toks.length && !(toks[i]!.tag === 'dict' && toks[i]!.close)) { + if (toks[i]!.tag !== 'key') { i++; continue; } + const at = toks[i]!.at; + const k = readText('key'); + if (depth === 0) lines.set(k, lineAt(xml, at)); + o[k] = value(depth + 1); + } + i++; + return o; + } + default: i++; return ''; + } + }; + while (i < toks.length && toks[i]!.tag !== 'dict') i++; + const v = i < toks.length ? value(0) : {}; + return { value: (v && typeof v === 'object' && !Array.isArray(v) ? v : {}) as Record, lines }; +} + +// ---- dependency files ---- + +function podsLock(file: string, text: string): DepRef[] { + const out: DepRef[] = []; + const pods = /^PODS:\n([\s\S]*?)(?=\n\S|$(?![\s\S]))/m.exec(text)?.[1] ?? ''; + const off = text.indexOf(pods); + for (const m of pods.matchAll(/^ {2}- "?([A-Za-z0-9_.+\-/]+) \(([^)]+)\)"?:?$/gm)) + out.push({ eco: 'cocoapods', name: m[1]!, version: m[2]!, file, line: lineAt(text, off + m.index!) }); + return out; +} +function podfile(file: string, text: string): DepRef[] { + return [...text.matchAll(/^\s*pod\s+['"]([^'"]+)['"](?:\s*,\s*['"]([^'"]+)['"])?/gm)].map(m => ({ eco: 'cocoapods' as const, name: m[1]!, version: m[2] ?? null, file, line: lineAt(text, m.index!) })); +} +function packageResolved(file: string, text: string): DepRef[] { + try { + const j = JSON.parse(text) as { pins?: { identity?: string; location?: string; state?: { version?: string } }[]; object?: { pins?: { package?: string; repositoryURL?: string; state?: { version?: string } }[] } }; + const pins = j.pins ?? j.object?.pins?.map(p => ({ identity: p.package, location: p.repositoryURL, state: p.state })) ?? []; + return pins.map(p => ({ eco: 'spm' as const, name: p.location ?? p.identity ?? '', version: p.state?.version ?? null, file, line: lineOf(text, p.location ?? p.identity ?? '') })); + } catch { return []; } +} +function pbxproj(file: string, text: string): DepRef[] { + const out: DepRef[] = []; + for (const m of text.matchAll(/repositoryURL = "([^"]+)";/g)) out.push({ eco: 'spm', name: m[1]!, version: null, file, line: lineAt(text, m.index!) }); + for (const m of text.matchAll(/isa = XCSwiftPackageProductDependency;[\s\S]{0,300}?productName = "?([A-Za-z0-9_-]+)"?;/g)) out.push({ eco: 'spm', name: m[1]!, version: null, file, line: lineAt(text, m.index!) }); + return out; +} +function cartfile(file: string, text: string): DepRef[] { + return [...text.matchAll(/^\s*(?:github|git|binary)\s+"([^"]+)"(?:\s+"?([^"\n]+)"?)?/gm)].map(m => ({ eco: 'carthage' as const, name: m[1]!, version: m[2]?.trim() ?? null, file, line: lineAt(text, m.index!) })); +} +function gradle(file: string, text: string): DepRef[] { + const out: DepRef[] = []; + for (const m of text.matchAll(/(?:implementation|api|compileOnly|runtimeOnly|kapt|ksp|annotationProcessor|classpath)\s*\(?\s*(?:platform\(\s*)?["']([A-Za-z0-9_.\-]+):([A-Za-z0-9_.\-]+)(?::([^"'@]+))?/g)) + out.push({ eco: 'gradle', name: `${m[1]}:${m[2]}`, version: m[3] ?? null, file, line: lineAt(text, m.index!) }); + return out; +} +function versionCatalog(file: string, text: string): DepRef[] { + const versions = new Map(); + const vsec = /^\[versions\]\n([\s\S]*?)(?=^\[|$(?![\s\S]))/m.exec(text)?.[1] ?? ''; + for (const m of vsec.matchAll(/^\s*([A-Za-z0-9_.\-]+)\s*=\s*"([^"]+)"/gm)) versions.set(m[1]!, m[2]!); + const out: DepRef[] = []; + for (const m of text.matchAll(/^\s*[A-Za-z0-9_.\-]+\s*=\s*\{([^}]*)\}/gm)) { + 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; + 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!) }); + } + for (const m of text.matchAll(/^\s*[A-Za-z0-9_.\-]+\s*=\s*"([A-Za-z0-9_.\-]+):([A-Za-z0-9_.\-]+):([^"]+)"/gm)) + out.push({ eco: 'gradle', name: `${m[1]}:${m[2]}`, version: m[3]!, file, line: lineAt(text, m.index!) }); + return out; +} +function packageJson(file: string, text: string): DepRef[] { + try { + const j = JSON.parse(text) as { dependencies?: Record }; + return Object.entries(j.dependencies ?? {}).map(([n, v]) => ({ eco: 'npm' as const, name: n, version: v, file, line: lineOf(text, `"${n}"`) })); + } catch { return []; } +} +function pubspec(file: string, text: string): DepRef[] { + const sec = /^dependencies:\n([\s\S]*?)(?=^\S|$(?![\s\S]))/m.exec(text); + if (!sec) return []; + const off = sec.index + 'dependencies:\n'.length; + return [...sec[1]!.matchAll(/^ {2}([a-z0-9_]+):\s*([^\n#]*)/gm)].map(m => ({ eco: 'pub' as const, name: m[1]!, version: m[2]!.trim() || null, file, line: lineAt(text, off + m.index!) })); +} +function pubspecLock(text: string): Map { + const out = new Map(); + for (const m of text.matchAll(/^ {2}([a-z0-9_]+):\n(?: {4}.*\n)*? {4}version: "([^"]+)"/gm)) out.set(m[1]!, m[2]!); + return out; +} +function unityManifest(file: string, text: string): DepRef[] { + try { + const j = JSON.parse(text) as { dependencies?: Record }; + return Object.entries(j.dependencies ?? {}).map(([n, v]) => ({ eco: 'unity' as const, name: n, version: v, file, line: lineOf(text, `"${n}"`) })); + } catch { return []; } +} +/** External Dependency Manager (Assets/.../Editor/*Dependencies.xml): the pods and Gradle packages a Unity plugin adds. */ +function edmXml(file: string, text: string): DepRef[] { + const out: DepRef[] = []; + for (const m of text.matchAll(/ ({ eco: 'npm' as const, name: m[1]!, version: m[2] ?? null, file, line: lineAt(text, m.index!) })); +} + +// ---- Info.plist key sources other than Info.plist ---- + +const UNITY_KEYS: Record = { cameraUsageDescription: 'NSCameraUsageDescription', locationUsageDescription: 'NSLocationWhenInUseUsageDescription', microphoneUsageDescription: 'NSMicrophoneUsageDescription' }; +const GODOT_KEYS: Record = { + 'privacy/camera_usage_description': 'NSCameraUsageDescription', 'privacy/microphone_usage_description': 'NSMicrophoneUsageDescription', + 'privacy/photolibrary_usage_description': 'NSPhotoLibraryUsageDescription', +}; + +export function detectProject(root: string): ProjectFacts { + const files = listFiles(root); + 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, ''); } } + return cache.get(f)!; + }; + const has = (re: RegExp) => files.some(f => re.test(f)); + const deps: DepRef[] = []; + const plist = new Map(); + const plistSources: string[] = []; + 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 sdkHits: { value: number; at: Loc; prio: number }[] = []; + let remoteStart: ProjectFacts['remoteStart'] = null; + const sources: { path: string; text: string }[] = []; + const stacks = new Set(); + let pubLock = new Map(); + + for (const f of files) { + const n = basename(f); + const testy = /(^|\/)(Tests?|UITests|[A-Za-z]+Tests|test|androidTest|__tests__|Example|Samples?)\//.test(f); + if (n === 'Info.plist' && !testy && !/\.(app|appex)\//.test(f)) { + const { value, lines } = parsePlist(read(f)); + if (Object.keys(value).length) plistSources.push(f); + for (const [k, v] of Object.entries(value)) setKey(plist, k, v, { file: f, line: lines.get(k) ?? 1 }); + } else if (n.endsWith('.entitlements')) { + const { value, lines } = parsePlist(read(f)); + for (const [k, v] of Object.entries(value)) setKey(entitlements, k, v, { file: f, line: lines.get(k) ?? 1 }); + } else if (n === 'PrivacyInfo.xcprivacy') privacyManifests.push(parseManifest(f, read(f))); + else if (n === 'project.pbxproj') { + const t = read(f); + deps.push(...pbxproj(f, t)); + let found = false; + for (const m of t.matchAll(/INFOPLIST_KEY_([A-Za-z]+) = ("(?:[^"\\]|\\.)*"|[^;\n]*);/g)) { + found = true; + setKey(plist, m[1]!, m[2]!.replace(/^"|"$/g, '').replace(/\\"/g, '"'), { file: f, line: lineAt(t, m.index!) }); + } + if (found) plistSources.push(f); + } else if (n === 'Podfile.lock') deps.push(...podsLock(f, read(f))); + else if (n === 'Podfile') deps.push(...podfile(f, read(f))); + else if (n === 'Package.resolved') deps.push(...packageResolved(f, read(f))); + else if (n === 'Cartfile' || n === 'Cartfile.resolved') deps.push(...cartfile(f, read(f))); + else if (/^(build\.gradle(\.kts)?|variables\.gradle|settings\.gradle(\.kts)?)$/.test(n)) { + const t = read(f); + deps.push(...gradle(f, t)); + 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)'; + } 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 }); + } 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'; + } else if (n === 'package.json' && !f.includes('/node_modules/')) { + const t = read(f); + const d = packageJson(f, t); + deps.push(...d); + const names = new Set(d.map(x => x.name)); + if (names.has('react-native')) stacks.add('react-native'); + if (names.has('expo')) stacks.add('expo'); + if ([...names].some(x => x.startsWith('@capacitor/'))) stacks.add('capacitor'); + if (names.has('cordova-android') || names.has('cordova-ios')) stacks.add('cordova'); + } else if ((n === 'app.json' || n === 'app.config.json') && !f.includes('/')) { + const t = read(f); + try { + const j = JSON.parse(t) as { expo?: { ios?: { infoPlist?: Record; usesAppleSignIn?: boolean }; android?: { permissions?: string[] }; plugins?: unknown[] } }; + if (j.expo) { + stacks.add('expo'); + plistSources.push(f); + for (const [k, v] of Object.entries(j.expo.ios?.infoPlist ?? {})) setKey(plist, k, v, { file: f, line: lineOf(t, `"${k}"`) }); + if (j.expo.ios?.usesAppleSignIn) setKey(entitlements, 'com.apple.developer.applesignin', ['Default'], { file: f, line: lineOf(t, '"usesAppleSignIn"') }); + for (const p of j.expo.android?.permissions ?? []) android.permissions.push({ name: p.includes('.') ? p : `android.permission.${p}`, at: { file: f, line: lineOf(t, `"${p}"`) } }); + for (const p of j.expo.plugins ?? []) { + if (Array.isArray(p) && p[0] === 'expo-build-properties') { + const ts = (p[1] as { android?: { targetSdkVersion?: number } } | undefined)?.android?.targetSdkVersion; + if (ts) sdkHits.push({ value: ts, at: { file: f, line: lineOf(t, '"targetSdkVersion"') }, prio: 0 }); + } + } + if (!android.targetSdkFrom) android.targetSdkFrom = 'the Expo SDK version (expo-build-properties android.targetSdkVersion overrides it)'; + } + } catch { /* not JSON */ } + } else if (/^capacitor\.config\.(json|ts|js)$/.test(n)) { + stacks.add('capacitor'); + const t = read(f); + const m = /server\s*["']?\s*:\s*\{[\s\S]*?\burl["']?\s*:\s*["'](https?:\/\/[^"']+)["']/.exec(t); + if (m && !/^https?:\/\/(localhost|127\.0\.0\.1|10\.0\.2\.2|192\.168\.)/.test(m[1]!)) remoteStart = { url: m[1]!, at: { file: f, line: lineAt(t, m.index! + m[0].indexOf(m[1]!)) } }; + } else if (n === 'config.xml' && / 0) sdkHits.push({ value: Number(ts[1]), at: { file: f, line: lineAt(t, ts.index) }, prio: 0 }); + else if (ts) android.targetSdkFrom = 'Unity "Automatic (highest installed)": the Android SDK the build machine has'; + } else if (n === 'export_presets.cfg') { + stacks.add('godot'); + const t = read(f); + let any = false; + for (const [gk, pk] of Object.entries(GODOT_KEYS)) { + const m = new RegExp(`^${gk.replace('/', '\\/')}="(.*)"`, 'm').exec(t); + if (m) { any = true; setKey(plist, pk, m[1]!, { file: f, line: lineAt(t, m.index) }); } + } + if (any) plistSources.push(f); + const ts = /^gradle_build\/target_sdk="(\d+)"/m.exec(t); + if (ts) sdkHits.push({ value: Number(ts[1]), at: { file: f, line: lineAt(t, ts.index) }, prio: 0 }); + for (const m of t.matchAll(/^permissions\/([a-z_]+)=true/gm)) android.permissions.push({ name: `android.permission.${m[1]!.toUpperCase()}`, at: { file: f, line: lineAt(t, m.index!) } }); + } + // app sources + if (SRC_EXT.has(extname(n)) && !testy && !/\.min\.js$|\.d\.ts$|(^|\/)(Plugins|ThirdParty|third_party|Packages|addons)\//.test(f) && !/\.config\.(ts|js)$/.test(n)) { + const t = read(f); + if (t && !t.includes('\u0000')) sources.push({ path: f, text: t }); + } + } + // Unity / Godot plugin folders count as dependencies (a folder under Assets/ or addons/) + for (const d of new Set(files.map(f => /^Assets\/([^/]+)\//.exec(f)?.[1]).filter((x): x is string => !!x))) + deps.push({ eco: 'unity', name: d, version: null, file: `Assets/${d}/`, line: 1 }); + for (const d of new Set(files.map(f => /^addons\/([^/]+)\//.exec(f)?.[1]).filter((x): x is string => !!x))) + deps.push({ eco: 'godot', name: d, version: null, file: `addons/${d}/`, line: 1 }); + for (const d of deps) if (d.eco === 'pub' && pubLock.has(d.name)) d.version = pubLock.get(d.name)!; + + if (has(/\.xcodeproj\/project\.pbxproj$/) && !stacks.has('flutter') && !stacks.has('react-native') && !stacks.has('capacitor') && !stacks.has('cordova') && !stacks.has('unity')) stacks.add('ios-native'); + if (android.manifests.length && !stacks.has('flutter') && !stacks.has('react-native') && !stacks.has('capacitor') && !stacks.has('cordova') && !stacks.has('unity') && !stacks.has('godot')) stacks.add('android-native'); + if (!stacks.size && has(/(^|\/)index\.html$/)) stacks.add('web'); + const ios = has(/\.xcodeproj\/project\.pbxproj$/) || plistSources.length > 0 || stacks.has('expo') || stacks.has('unity') || (stacks.has('godot') && /platform="iOS"/.test(read(files.find(f => basename(f) === 'export_presets.cfg') ?? ''))); + const isAndroid = android.manifests.length > 0 || has(/(^|\/)build\.gradle(\.kts)?$/) || stacks.has('expo') || stacks.has('unity') || (stacks.has('godot') && /platform="Android"/.test(read(files.find(f => basename(f) === 'export_presets.cfg') ?? ''))); + if (sdkHits.length) { + sdkHits.sort((a, b) => a.prio - b.prio || a.value - b.value); + android.targetSdk = { value: sdkHits[0]!.value, at: sdkHits[0]!.at }; + } + + const sdks: DetectedSdk[] = []; + for (const s of SDKS) { + 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 }; +} + +const COMMENT = /^\s*(\/\/|#|\*|\/\*| + +### short +``` +Notes that stay tidy, and paper notes turned into text. +``` + +### full +``` +Clean Notes keeps your notes tidy and turns paper notes into text. +``` diff --git a/tests/fixtures/scan/clean/storebound.config.ts b/tests/fixtures/scan/clean/storebound.config.ts new file mode 100644 index 00000000..378a33f9 --- /dev/null +++ b/tests/fixtures/scan/clean/storebound.config.ts @@ -0,0 +1,45 @@ +// Fixture config (made up, example.com placeholders only). +export default { + app: { + name: 'Clean Notes', + profile: 'subscription-app', + privacyPolicyUrl: 'https://example.com/privacy', + termsUrl: 'https://example.com/terms', + supportUrl: 'https://example.com/support', + website: 'https://example.com', + contactEmail: 'support@example.com', + }, + 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' }, + apple: { bundleId: 'org.example.cleannotes', usesNonExemptEncryption: false }, + appPrivacy: { tracking: true, trackingDomains: ['ads.example.com'] }, + products: [ + { id: 'org.example.cleannotes.themes', type: 'non_consumable', usd: 1.99, listings: { en: { title: 'Themes', description: 'Every color theme' } } }, + ], + subscriptions: [{ + name: 'Plus', + listings: { en: { name: 'Clean Notes Plus' } }, + subscriptions: [ + { id: 'org.example.cleannotes.plus_monthly', period: 'P1M', level: 1, usd: 2.99, listings: { en: { title: 'Plus', description: 'Unlimited scans' } } }, + ], + }], + dataSafety: { + collectsData: true, + encryptedInTransit: true, + deletionRequest: true, + accountCreation: ['PSL_ACM_OAUTH'], + data: { + PSL_NAME: { shared: false, collect: ['account'] }, + PSL_EMAIL: { shared: false, collect: ['account', 'functionality'] }, + PSL_USER_ACCOUNT: { shared: false, collect: ['account', 'functionality'] }, + 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'] }, + PSL_PURCHASE_HISTORY: { shared: false, collect: ['functionality'] }, + }, + }, + scan: { ignore: [] }, +}; diff --git a/tests/fixtures/scan/flutter/README.md b/tests/fixtures/scan/flutter/README.md new file mode 100644 index 00000000..49db225c --- /dev/null +++ b/tests/fixtures/scan/flutter/README.md @@ -0,0 +1,6 @@ +# flutter fixture + +A made-up Flutter subscription app: Google Sign-In without Sign in with Apple, sign-up without deletion, a +subscription without Terms of Use (config and listing) or renewal wording, app_tracking_transparency without +NSUserTrackingUsageDescription, a location foreground service without FOREGROUND_SERVICE_LOCATION, and a targetSdk +that comes from the Flutter SDK. Not a buildable project. diff --git a/tests/fixtures/scan/flutter/android/app/build.gradle b/tests/fixtures/scan/flutter/android/app/build.gradle new file mode 100644 index 00000000..e46b32ee --- /dev/null +++ b/tests/fixtures/scan/flutter/android/app/build.gradle @@ -0,0 +1,9 @@ +android { + namespace "com.example.habitcoach" + compileSdk flutter.compileSdkVersion + defaultConfig { + applicationId "com.example.habitcoach" + minSdk flutter.minSdkVersion + targetSdk flutter.targetSdkVersion + } +} diff --git a/tests/fixtures/scan/flutter/android/app/src/main/AndroidManifest.xml b/tests/fixtures/scan/flutter/android/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000..9e345236 --- /dev/null +++ b/tests/fixtures/scan/flutter/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/tests/fixtures/scan/flutter/ios/Runner/Info.plist b/tests/fixtures/scan/flutter/ios/Runner/Info.plist new file mode 100644 index 00000000..a98c73b0 --- /dev/null +++ b/tests/fixtures/scan/flutter/ios/Runner/Info.plist @@ -0,0 +1,10 @@ + + + + + CFBundleDisplayName + Habit Coach + ITSAppUsesNonExemptEncryption + + + diff --git a/tests/fixtures/scan/flutter/lib/main.dart b/tests/fixtures/scan/flutter/lib/main.dart new file mode 100644 index 00000000..b676ad76 --- /dev/null +++ b/tests/fixtures/scan/flutter/lib/main.dart @@ -0,0 +1,14 @@ +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:google_sign_in/google_sign_in.dart'; +import 'package:app_tracking_transparency/app_tracking_transparency.dart'; + +Future signInWithGoogle() async { + final account = await GoogleSignIn().signIn(); + final auth = await account!.authentication; + await FirebaseAuth.instance.signInWithCredential(GoogleAuthProvider.credential(idToken: auth.idToken)); +} + +Future signUp(String email, String password) => + FirebaseAuth.instance.createUserWithEmailAndPassword(email: email, password: password); + +Future askTracking() => AppTrackingTransparency.requestTrackingAuthorization(); diff --git a/tests/fixtures/scan/flutter/pubspec.lock b/tests/fixtures/scan/flutter/pubspec.lock new file mode 100644 index 00000000..0bfbd0be --- /dev/null +++ b/tests/fixtures/scan/flutter/pubspec.lock @@ -0,0 +1,19 @@ +packages: + firebase_auth: + dependency: "direct main" + description: + name: firebase_auth + source: hosted + version: "5.3.1" + google_mobile_ads: + dependency: "direct main" + description: + name: google_mobile_ads + source: hosted + version: "5.1.0" + google_sign_in: + dependency: "direct main" + description: + name: google_sign_in + source: hosted + version: "6.2.1" diff --git a/tests/fixtures/scan/flutter/pubspec.yaml b/tests/fixtures/scan/flutter/pubspec.yaml new file mode 100644 index 00000000..aa2b9b30 --- /dev/null +++ b/tests/fixtures/scan/flutter/pubspec.yaml @@ -0,0 +1,19 @@ +name: habit_coach +description: A made-up habit app for storebound tests. +version: 2.1.0+21 + +environment: + sdk: ">=3.5.0 <4.0.0" + +dependencies: + flutter: + sdk: flutter + firebase_auth: ^5.3.0 + google_sign_in: ^6.2.1 + purchases_flutter: ^8.1.0 + google_mobile_ads: ^5.1.0 + app_tracking_transparency: ^2.0.6 + +dev_dependencies: + flutter_test: + sdk: flutter diff --git a/tests/fixtures/scan/flutter/store/appstore.md b/tests/fixtures/scan/flutter/store/appstore.md new file mode 100644 index 00000000..987e952a --- /dev/null +++ b/tests/fixtures/scan/flutter/store/appstore.md @@ -0,0 +1,23 @@ +# Habit Coach · App Store listing copy + +## en-US · English (U.S.) + +### subtitle +``` +Small habits, every day +``` + +### promotionalText +``` +Build a streak that sticks. +``` + +### keywords +``` +habit,streak,routine,goals,tracker +``` + +### description +``` +Habit Coach helps you build small daily habits with reminders and streaks. Coach Plus adds unlimited habits. +``` diff --git a/tests/fixtures/scan/flutter/storebound.config.ts b/tests/fixtures/scan/flutter/storebound.config.ts new file mode 100644 index 00000000..d91d6507 --- /dev/null +++ b/tests/fixtures/scan/flutter/storebound.config.ts @@ -0,0 +1,22 @@ +// Fixture config (made up, example.com placeholders only). +export default { + app: { + name: 'Habit Coach', + profile: 'subscription-app', + privacyPolicyUrl: 'https://example.com/privacy', + supportUrl: 'https://example.com/support', + website: 'https://example.com', + contactEmail: 'support@example.com', + }, + reviewAccess: { signInRequired: false }, + languages: [{ id: 'en', play: 'en-US', apple: 'en-US' }], + play: { packageName: 'com.example.habitcoach' }, + apple: { bundleId: 'com.example.habitcoach', usesNonExemptEncryption: false }, + subscriptions: [{ + name: 'Coach Plus', + listings: { en: { name: 'Coach Plus' } }, + subscriptions: [ + { id: 'com.example.habitcoach.plus_monthly', period: 'P1M', level: 1, usd: 4.99, listings: { en: { title: 'Coach Plus', description: 'Unlimited habits' } } }, + ], + }], +}; diff --git a/tests/fixtures/scan/ios-native/Notes.xcodeproj/project.pbxproj b/tests/fixtures/scan/ios-native/Notes.xcodeproj/project.pbxproj new file mode 100644 index 00000000..9601d429 --- /dev/null +++ b/tests/fixtures/scan/ios-native/Notes.xcodeproj/project.pbxproj @@ -0,0 +1,17 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + objects = { + A1B2C3D4E5F6000000000001 /* XCRemoteSwiftPackageReference "GoogleSignIn-iOS" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/google/GoogleSignIn-iOS"; + }; + A1B2C3D4E5F6000000000002 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + INFOPLIST_FILE = Notes/Info.plist; + PRODUCT_BUNDLE_IDENTIFIER = com.example.notes; + }; + }; + }; +} diff --git a/tests/fixtures/scan/ios-native/Notes/Api.swift b/tests/fixtures/scan/ios-native/Notes/Api.swift new file mode 100644 index 00000000..8711570d --- /dev/null +++ b/tests/fixtures/scan/ios-native/Notes/Api.swift @@ -0,0 +1,8 @@ +import Foundation +import AdSupport + +enum Api { + static let base = URL(string: "http://192.0.2.10:8080/v1")! + static var adId: String { ASIdentifierManager.shared().advertisingIdentifier.uuidString } + static func lastSync() -> Date? { UserDefaults.standard.object(forKey: "lastSync") as? Date } +} diff --git a/tests/fixtures/scan/ios-native/Notes/Info.plist b/tests/fixtures/scan/ios-native/Notes/Info.plist new file mode 100644 index 00000000..966f34d2 --- /dev/null +++ b/tests/fixtures/scan/ios-native/Notes/Info.plist @@ -0,0 +1,19 @@ + + + + + CFBundleDisplayName + Notes + GADApplicationIdentifier + ca-app-pub-0000000000000000~0000000000 + NSAppTransportSecurity + + NSAllowsArbitraryLoads + + + NSPhotoLibraryUsageDescription + + NSLocationWhenInUseUsageDescription + Location + + diff --git a/tests/fixtures/scan/ios-native/Notes/LegacyHelp.swift b/tests/fixtures/scan/ios-native/Notes/LegacyHelp.swift new file mode 100644 index 00000000..e9e79d62 --- /dev/null +++ b/tests/fixtures/scan/ios-native/Notes/LegacyHelp.swift @@ -0,0 +1,8 @@ +import UIKit + +final class LegacyHelp: UIViewController { + let web = UIWebView() + func openSystemSettings() { + UIApplication.shared.open(URL(string: "App-Prefs:root=Privacy")!) + } +} diff --git a/tests/fixtures/scan/ios-native/Notes/LoginView.swift b/tests/fixtures/scan/ios-native/Notes/LoginView.swift new file mode 100644 index 00000000..fa518512 --- /dev/null +++ b/tests/fixtures/scan/ios-native/Notes/LoginView.swift @@ -0,0 +1,20 @@ +import SwiftUI +import GoogleSignIn +import FirebaseAuth + +struct LoginView: View { + var body: some View { + VStack { + Button("Continue with Google") { signInWithGoogle() } + Button("Create account") { createAccount() } + } + } + + func signInWithGoogle() { + GIDSignIn.sharedInstance.signIn(withPresenting: rootViewController()) { _, _ in } + } + + func createAccount() { + Auth.auth().createUserWithEmailAndPassword(withEmail: "demo@example.com", password: "example") { _, _ in } + } +} diff --git a/tests/fixtures/scan/ios-native/Notes/ScannerView.swift b/tests/fixtures/scan/ios-native/Notes/ScannerView.swift new file mode 100644 index 00000000..4e01413b --- /dev/null +++ b/tests/fixtures/scan/ios-native/Notes/ScannerView.swift @@ -0,0 +1,13 @@ +import AVFoundation +import CoreLocation + +final class ScannerView { + let session = AVCaptureSession() + let location = CLLocationManager() + + func start() { + guard let device = AVCaptureDevice.default(for: .video) else { return } + _ = device + location.requestWhenInUseAuthorization() + } +} diff --git a/tests/fixtures/scan/ios-native/Notes/Store.swift b/tests/fixtures/scan/ios-native/Notes/Store.swift new file mode 100644 index 00000000..f45afdc0 --- /dev/null +++ b/tests/fixtures/scan/ios-native/Notes/Store.swift @@ -0,0 +1,7 @@ +import StoreKit + +final class Store: NSObject { + func buyPro(_ product: SKProduct) { + SKPaymentQueue.default().add(SKPayment(product: product)) + } +} diff --git a/tests/fixtures/scan/ios-native/Podfile.lock b/tests/fixtures/scan/ios-native/Podfile.lock new file mode 100644 index 00000000..8647f7de --- /dev/null +++ b/tests/fixtures/scan/ios-native/Podfile.lock @@ -0,0 +1,13 @@ +PODS: + - FirebaseAuth (10.18.0): + - FirebaseCore (~> 10.0) + - FirebaseCore (10.18.0) + - Google-Mobile-Ads-SDK (10.14.0) + - GoogleSignIn (7.0.0) + +DEPENDENCIES: + - FirebaseAuth + - Google-Mobile-Ads-SDK + - GoogleSignIn + +COCOAPODS: 1.15.2 diff --git a/tests/fixtures/scan/ios-native/README.md b/tests/fixtures/scan/ios-native/README.md new file mode 100644 index 00000000..47b3b33b --- /dev/null +++ b/tests/fixtures/scan/ios-native/README.md @@ -0,0 +1,7 @@ +# ios-native fixture + +A made-up SwiftUI notes app with planted App Review problems for `storebound scan` tests: Google Sign-In without Sign +in with Apple, sign-up without in-app deletion, a non-consumable without Restore Purchases, AdMob and the IDFA without +App Tracking Transparency, the camera without a purpose string, an empty and a vague purpose string, UIWebView, a +private settings URL scheme, an IPv4 server URL, NSAllowsArbitraryLoads, no export compliance answer, no privacy +manifest, old SDKs, and an App Store listing that names Android, a competitor and lorem ipsum. Not a buildable project. diff --git a/tests/fixtures/scan/ios-native/store/appstore.md b/tests/fixtures/scan/ios-native/store/appstore.md new file mode 100644 index 00000000..44a72fd7 --- /dev/null +++ b/tests/fixtures/scan/ios-native/store/appstore.md @@ -0,0 +1,25 @@ +# Notes · App Store listing copy + +## en-US · English (U.S.) + +### subtitle +``` +Quick notes, synced +``` + +### promotionalText +``` +Write it down before you forget. +``` + +### keywords +``` +notes,todo,instagram,free,journal +``` + +### description +``` +Lorem ipsum dolor sit amet, notes for everyone. + +Also available on Android and Google Play. +``` diff --git a/tests/fixtures/scan/ios-native/storebound.config.ts b/tests/fixtures/scan/ios-native/storebound.config.ts new file mode 100644 index 00000000..b823717d --- /dev/null +++ b/tests/fixtures/scan/ios-native/storebound.config.ts @@ -0,0 +1,18 @@ +// Fixture config (made up, example.com placeholders only). +export default { + app: { + name: 'Notes', + profile: 'app', + privacyPolicyUrl: 'https://example.com/privacy', + supportUrl: 'https://example.com/support', + website: 'https://example.com', + contactEmail: 'support@example.com', + }, + accounts: { enabled: true }, + reviewAccess: { signInRequired: true }, + languages: [{ id: 'en', apple: 'en-US' }], + apple: { bundleId: 'com.example.notes' }, + products: [ + { id: 'com.example.notes.pro', type: 'non_consumable', usd: 4.99, listings: { en: { title: 'Notes Pro', description: 'Unlimited notes and themes' } } }, + ], +}; diff --git a/tests/fixtures/scan/teaser/Planner.xcodeproj/project.pbxproj b/tests/fixtures/scan/teaser/Planner.xcodeproj/project.pbxproj new file mode 100644 index 00000000..5343a49f --- /dev/null +++ b/tests/fixtures/scan/teaser/Planner.xcodeproj/project.pbxproj @@ -0,0 +1,13 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + objects = { + C1B2C3D4E5F6000000000002 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + INFOPLIST_FILE = Planner/Info.plist; + PRODUCT_BUNDLE_IDENTIFIER = com.example.planner; + }; + }; + }; +} diff --git a/tests/fixtures/scan/teaser/Planner/Ads.swift b/tests/fixtures/scan/teaser/Planner/Ads.swift new file mode 100644 index 00000000..5551e8a8 --- /dev/null +++ b/tests/fixtures/scan/teaser/Planner/Ads.swift @@ -0,0 +1,9 @@ +import AdSupport +import GoogleMobileAds + +enum Ads { + static func start() { + GADMobileAds.sharedInstance().start(completionHandler: nil) + print(ASIdentifierManager.shared().advertisingIdentifier) + } +} diff --git a/tests/fixtures/scan/teaser/Planner/Info.plist b/tests/fixtures/scan/teaser/Planner/Info.plist new file mode 100644 index 00000000..7339450c --- /dev/null +++ b/tests/fixtures/scan/teaser/Planner/Info.plist @@ -0,0 +1,10 @@ + + + + + CFBundleDisplayName + Planner + ITSAppUsesNonExemptEncryption + + + diff --git a/tests/fixtures/scan/teaser/Planner/LoginView.swift b/tests/fixtures/scan/teaser/Planner/LoginView.swift new file mode 100644 index 00000000..1926b537 --- /dev/null +++ b/tests/fixtures/scan/teaser/Planner/LoginView.swift @@ -0,0 +1,20 @@ +import FirebaseAuth +import GoogleSignIn +import SwiftUI + +struct LoginView: View { + var body: some View { + VStack { + Button("Continue with Google") { + GIDSignIn.sharedInstance.signIn(withPresenting: rootViewController()) { _, _ in } + } + Button("Create account") { Task { try await AccountApi.signUp() } } + } + } +} + +enum AccountApi { + static func signUp() async throws { + _ = try await Auth.auth().createUser(withEmail: "planner@example.com", password: "example") + } +} diff --git a/tests/fixtures/scan/teaser/Planner/PrivacyInfo.xcprivacy b/tests/fixtures/scan/teaser/Planner/PrivacyInfo.xcprivacy new file mode 100644 index 00000000..0e3bf796 --- /dev/null +++ b/tests/fixtures/scan/teaser/Planner/PrivacyInfo.xcprivacy @@ -0,0 +1,19 @@ + + + + + NSPrivacyTracking + + NSPrivacyAccessedAPITypes + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryUserDefaults + NSPrivacyAccessedAPITypeReasons + + CA92.1 + + + + + diff --git a/tests/fixtures/scan/teaser/Planner/ProStore.swift b/tests/fixtures/scan/teaser/Planner/ProStore.swift new file mode 100644 index 00000000..4cfd6a34 --- /dev/null +++ b/tests/fixtures/scan/teaser/Planner/ProStore.swift @@ -0,0 +1,7 @@ +import StoreKit + +enum ProStore { + static func buy(_ product: Product) async throws { + _ = try await product.purchase() + } +} diff --git a/tests/fixtures/scan/teaser/Planner/SettingsView.swift b/tests/fixtures/scan/teaser/Planner/SettingsView.swift new file mode 100644 index 00000000..13bcf2a9 --- /dev/null +++ b/tests/fixtures/scan/teaser/Planner/SettingsView.swift @@ -0,0 +1,10 @@ +import SwiftUI + +struct SettingsView: View { + var body: some View { + List { + Link("Privacy policy", destination: URL(string: "https://example.com/privacy")!) + Text("Last opened: \(UserDefaults.standard.string(forKey: "lastOpen") ?? "-")") + } + } +} diff --git a/tests/fixtures/scan/teaser/Podfile.lock b/tests/fixtures/scan/teaser/Podfile.lock new file mode 100644 index 00000000..a21b254c --- /dev/null +++ b/tests/fixtures/scan/teaser/Podfile.lock @@ -0,0 +1,9 @@ +PODS: + - Google-Mobile-Ads-SDK (11.10.0) + - GoogleSignIn (7.1.0) + +DEPENDENCIES: + - Google-Mobile-Ads-SDK + - GoogleSignIn + +COCOAPODS: 1.15.2 diff --git a/tests/fixtures/scan/teaser/README.md b/tests/fixtures/scan/teaser/README.md new file mode 100644 index 00000000..83627054 --- /dev/null +++ b/tests/fixtures/scan/teaser/README.md @@ -0,0 +1,6 @@ +# teaser fixture + +A made-up iOS planner app with the five classic App Review rejections and nothing else: sign-in without a demo +account (2.1), sign-up without in-app account deletion (5.1.1(v)), Google Sign-In without Sign in with Apple (4.8), a +non-consumable without Restore Purchases (3.1.1), and AdMob plus the IDFA without App Tracking Transparency (5.1.2). +Its `storebound scan` output is the one the teaser video shows. Not a buildable project. diff --git a/tests/fixtures/scan/teaser/store/appstore.md b/tests/fixtures/scan/teaser/store/appstore.md new file mode 100644 index 00000000..77033ff0 --- /dev/null +++ b/tests/fixtures/scan/teaser/store/appstore.md @@ -0,0 +1,23 @@ +# Planner · App Store listing copy + +## en-US · English (U.S.) + +### subtitle +``` +Plan your week in a minute +``` + +### promotionalText +``` +Weekly planning without the clutter. +``` + +### keywords +``` +planner,week,calendar,tasks,agenda +``` + +### description +``` +Planner lays out your week in one screen. Planner Pro adds themes and widgets. +``` diff --git a/tests/fixtures/scan/teaser/storebound.config.ts b/tests/fixtures/scan/teaser/storebound.config.ts new file mode 100644 index 00000000..fc5133b8 --- /dev/null +++ b/tests/fixtures/scan/teaser/storebound.config.ts @@ -0,0 +1,18 @@ +// Fixture config (made up, example.com placeholders only). +export default { + app: { + name: 'Planner', + profile: 'app', + privacyPolicyUrl: 'https://example.com/privacy', + supportUrl: 'https://example.com/support', + website: 'https://example.com', + contactEmail: 'support@example.com', + }, + accounts: { enabled: true }, + reviewAccess: { signInRequired: true, instructions: 'Sign in with the demo account.' }, + languages: [{ id: 'en', apple: 'en-US' }], + apple: { bundleId: 'com.example.planner', usesNonExemptEncryption: false }, + products: [ + { id: 'com.example.planner.pro', type: 'non_consumable', usd: 4.99, listings: { en: { title: 'Planner Pro', description: 'Themes and widgets' } } }, + ], +}; diff --git a/tests/fixtures/scan/unity/Assets/GoogleMobileAds/Editor/GoogleMobileAdsDependencies.xml b/tests/fixtures/scan/unity/Assets/GoogleMobileAds/Editor/GoogleMobileAdsDependencies.xml new file mode 100644 index 00000000..6a834541 --- /dev/null +++ b/tests/fixtures/scan/unity/Assets/GoogleMobileAds/Editor/GoogleMobileAdsDependencies.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/fixtures/scan/unity/Assets/Scripts/PhotoBooth.cs b/tests/fixtures/scan/unity/Assets/Scripts/PhotoBooth.cs new file mode 100644 index 00000000..75c44a27 --- /dev/null +++ b/tests/fixtures/scan/unity/Assets/Scripts/PhotoBooth.cs @@ -0,0 +1,12 @@ +using UnityEngine; + +public class PhotoBooth : MonoBehaviour +{ + WebCamTexture cam; + + void Start() + { + cam = new WebCamTexture(); + cam.Play(); + } +} diff --git a/tests/fixtures/scan/unity/Assets/Scripts/RatePopup.cs b/tests/fixtures/scan/unity/Assets/Scripts/RatePopup.cs new file mode 100644 index 00000000..6787c509 --- /dev/null +++ b/tests/fixtures/scan/unity/Assets/Scripts/RatePopup.cs @@ -0,0 +1,12 @@ +using UnityEngine; +using UnityEngine.UI; + +public class RatePopup : MonoBehaviour +{ + public Text message; + + void Show() + { + message.text = "Rate us 5 stars and get 50 free coins!"; + } +} diff --git a/tests/fixtures/scan/unity/Assets/Scripts/Shop.cs b/tests/fixtures/scan/unity/Assets/Scripts/Shop.cs new file mode 100644 index 00000000..8936d7e3 --- /dev/null +++ b/tests/fixtures/scan/unity/Assets/Scripts/Shop.cs @@ -0,0 +1,9 @@ +using UnityEngine.Purchasing; + +public class Shop : IDetailedStoreListener +{ + public void BuyNoAds(IStoreController controller) + { + controller.InitiatePurchase("com.example.bubblezoo.noads"); + } +} diff --git a/tests/fixtures/scan/unity/Packages/manifest.json b/tests/fixtures/scan/unity/Packages/manifest.json new file mode 100644 index 00000000..5277fc10 --- /dev/null +++ b/tests/fixtures/scan/unity/Packages/manifest.json @@ -0,0 +1,8 @@ +{ + "dependencies": { + "com.unity.ads": "4.12.0", + "com.unity.purchasing": "4.12.2", + "com.unity.services.levelplay": "8.4.0", + "com.unity.ugui": "2.0.0" + } +} diff --git a/tests/fixtures/scan/unity/ProjectSettings/ProjectSettings.asset b/tests/fixtures/scan/unity/ProjectSettings/ProjectSettings.asset new file mode 100644 index 00000000..2ad04481 --- /dev/null +++ b/tests/fixtures/scan/unity/ProjectSettings/ProjectSettings.asset @@ -0,0 +1,11 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!129 &1 +PlayerSettings: + productName: Bubble Zoo + companyName: Example Studio + AndroidMinSdkVersion: 23 + AndroidTargetSdkVersion: 35 + cameraUsageDescription: + locationUsageDescription: + microphoneUsageDescription: diff --git a/tests/fixtures/scan/unity/README.md b/tests/fixtures/scan/unity/README.md new file mode 100644 index 00000000..daa7704e --- /dev/null +++ b/tests/fixtures/scan/unity/README.md @@ -0,0 +1,5 @@ +# unity fixture + +A made-up Unity kids game: Kids Category age band with Unity Ads and LevelPlay (1.3, Play Families), "for kids" in the +listing, an empty camera usage description with WebCamTexture, a reward for rating the game, a non-consumable without +Restore, and targetSdk 35. Not a buildable project. diff --git a/tests/fixtures/scan/unity/store/appstore.md b/tests/fixtures/scan/unity/store/appstore.md new file mode 100644 index 00000000..55241ff2 --- /dev/null +++ b/tests/fixtures/scan/unity/store/appstore.md @@ -0,0 +1,23 @@ +# Bubble Zoo · App Store listing copy + +## en-US · English (U.S.) + +### subtitle +``` +Pop bubbles with zoo friends +``` + +### promotionalText +``` +New: the penguin pool. +``` + +### keywords +``` +bubble,zoo,animals,pop,toddler,learning +``` + +### description +``` +The cutest bubble game for kids! Pop bubbles, free the animals and learn their names. +``` diff --git a/tests/fixtures/scan/unity/storebound.config.ts b/tests/fixtures/scan/unity/storebound.config.ts new file mode 100644 index 00000000..430fec31 --- /dev/null +++ b/tests/fixtures/scan/unity/storebound.config.ts @@ -0,0 +1,17 @@ +// Fixture config (made up, example.com placeholders only). +export default { + app: { + name: 'Bubble Zoo', + 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', apple: 'en-US' }], + play: { packageName: 'com.example.bubblezoo' }, + apple: { bundleId: 'com.example.bubblezoo', usesNonExemptEncryption: false, info: { ageRating: { kidsAgeBand: 'FIVE_AND_UNDER' } } }, + products: [ + { id: 'com.example.bubblezoo.noads', type: 'non_consumable', usd: 2.99, listings: { en: { title: 'No ads', description: 'Remove all ads' } } }, + ], +}; diff --git a/tests/scan.test.ts b/tests/scan.test.ts new file mode 100644 index 00000000..3c6e560c --- /dev/null +++ b/tests/scan.test.ts @@ -0,0 +1,245 @@ +// 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 { 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 { runScan } from '../cli/lib/scan'; +import { vaguePurpose } from '../cli/lib/scan/permissions'; +import { detectProject, parsePlist } from '../cli/lib/scan/project'; +import type { ScanFinding } from '../cli/lib/scan/rules'; +import { matchesSdk, SDKS, versionAtLeast } from '../cli/lib/scan/sdks'; + +const ROOT = join(import.meta.dir, '..'); +const FX = join(import.meta.dir, 'fixtures', 'scan'); +const CLI = join(ROOT, 'cli', 'index.ts'); +const saved = { u: process.env.REVIEW_DEMO_USER, p: process.env.REVIEW_DEMO_PASSWORD }; +beforeEach(() => { delete process.env.REVIEW_DEMO_USER; delete process.env.REVIEW_DEMO_PASSWORD; }); +afterAll(() => { if (saved.u !== undefined) process.env.REVIEW_DEMO_USER = saved.u; if (saved.p !== undefined) process.env.REVIEW_DEMO_PASSWORD = saved.p; }); + +const scan = async (name: string) => (await runScan(join(FX, name))).report; +const rules = (f: ScanFinding[], store?: 'apple' | 'play') => new Set(f.filter(x => !x.accepted && (!store || x.store === store)).map(x => x.rule)); +const find = (f: ScanFinding[], rule: string, store?: 'apple' | 'play') => f.find(x => x.rule === rule && (!store || x.store === store)); + +describe('project detection', () => { + test('plist reader: values, nested dicts, top-level key lines', () => { + const { value, lines } = parsePlist(readFileSync(join(FX, 'ios-native/Notes/Info.plist'), 'utf8')); + expect(value.NSPhotoLibraryUsageDescription).toBe(''); + expect((value.NSAppTransportSecurity as Record).NSAllowsArbitraryLoads).toBe(true); + expect(lines.get('NSAppTransportSecurity')).toBe(9); + expect(parsePlist('not a plist').value).toEqual({}); + }); + test('stacks, SDKs with versions and file:line from every ecosystem', () => { + const ios = detectProject(join(FX, 'ios-native')); + expect(ios.stacks).toEqual(['ios-native']); + const admob = ios.sdks.find(s => s.sdk.id === 'admob')!.deps[0]!; + expect([admob.file, admob.line, admob.version]).toEqual(['Podfile.lock', 5, '10.14.0']); + expect(ios.sdks.find(s => s.sdk.id === 'google-signin')!.deps.map(d => d.eco).sort()).toEqual(['cocoapods', 'spm']); + const android = detectProject(join(FX, 'android')); + expect(android.androidInfo.targetSdk).toEqual({ value: 34, at: { file: 'app/build.gradle.kts', line: 12 } }); + expect(android.sdks.map(s => s.sdk.id).sort()).toEqual(['admob', 'firebase-auth']); + expect(detectProject(join(FX, 'capacitor')).stacks).toEqual(['capacitor']); + expect(detectProject(join(FX, 'capacitor')).remoteStart?.url).toBe('https://shop.example.com'); + expect(detectProject(join(FX, 'capacitor')).androidInfo.targetSdk?.value).toBe(35); + const unity = detectProject(join(FX, 'unity')); + expect(unity.stacks).toEqual(['unity']); + expect(unity.sdks.map(s => s.sdk.id).sort()).toEqual(['admob', 'iap-wrapper', 'levelplay', 'unity-ads']); + expect(unity.plist.get('NSCameraUsageDescription')?.at.file).toBe('ProjectSettings/ProjectSettings.asset'); + const flutter = detectProject(join(FX, 'flutter')); + expect(flutter.stacks).toEqual(['flutter']); + expect(flutter.deps.find(d => d.name === 'firebase_auth')?.version).toBe('5.3.1'); + expect(flutter.androidInfo.targetSdkFrom).toContain('Flutter'); + }); + test('SDK table: matchers and version compare', () => { + const admob = SDKS.find(s => s.id === 'admob')!; + expect(matchesSdk({ eco: 'cocoapods', name: 'Google-Mobile-Ads-SDK', version: null, file: '', line: 1 }, admob)).toBe(true); + expect(matchesSdk({ eco: 'gradle', name: 'com.google.android.gms:play-services-ads-lite', version: null, file: '', line: 1 }, admob)).toBe(false); + expect(matchesSdk({ eco: 'gradle', name: 'com.amplitude:analytics-android', version: null, file: '', line: 1 }, SDKS.find(s => s.id === 'amplitude')!)).toBe(true); + expect(matchesSdk({ eco: 'spm', name: 'FirebaseAnalytics', version: null, file: '', line: 1 }, SDKS.find(s => s.id === 'firebase-analytics')!)).toBe(true); + expect(versionAtLeast('10.14.0', '11.2.0')).toBe(false); + expect(versionAtLeast('~> 11.10.0', '11.2.0')).toBe(true); + expect(versionAtLeast('latest', '1.0')).toBeNull(); + for (const s of SDKS) expect(s.docs).toMatch(/^https:\/\//); + }); + test('purpose strings: empty, vague, fine', () => { + expect(vaguePurpose('')).toBe('empty'); + expect(vaguePurpose('TODO')).toBe('empty'); + expect(vaguePurpose('Location')).toBe('vague'); + expect(vaguePurpose('Allow $(PRODUCT_NAME) to access your camera')).toBe('vague'); + expect(vaguePurpose('Scan a paper note with the camera to turn it into text.')).toBeNull(); + }); +}); + +describe('rules: planted issues are found', () => { + test('ios-native', async () => { + const r = await scan('ios-native'); + for (const id of ['demo-account', 'account-deletion', 'login-services', 'restore-purchases', 'att', 'purpose-strings', 'privacy-manifest', 'other-platforms', + 'metadata-keywords', 'placeholder-text', 'deprecated-api', 'private-api', 'ats', 'ipv6', 'export-compliance']) expect(rules(r.findings)).toContain(id); + expect(find(r.findings, 'demo-account')!.severity).toBe('blocker'); + expect(find(r.findings, 'login-services')!.guideline).toBe('4.8'); + const cam = r.findings.find(f => f.rule === 'purpose-strings' && f.title.includes('NSCameraUsageDescription'))!; + expect(cam.severity).toBe('blocker'); + expect(cam.evidence[0]).toMatchObject({ file: 'Notes/ScannerView.swift', line: 9 }); + expect(r.findings.some(f => f.rule === 'purpose-strings' && f.title.includes('too vague'))).toBe(true); + expect(find(r.findings, 'other-platforms')!.evidence[0]).toMatchObject({ file: 'store/appstore.md', line: 24 }); + expect(find(r.findings, 'deprecated-api')!.evidence[0]!.file).toBe('Notes/LegacyHelp.swift'); + expect(r.findings.filter(f => f.title.includes('older than')).length).toBe(3); + for (const f of r.findings) { expect(f.fix.length).toBeGreaterThan(10); expect(f.skill).toBeTruthy(); expect(f.ref).toMatch(/^https:\/\//); expect(f.evidence.length).toBeGreaterThan(0); } + }); + test('android', async () => { + const r = await scan('android'); + for (const id of ['play-deletion-url', 'play-target-sdk', 'play-package-name', 'play-fgs', 'play-exact-alarm', 'play-query-all-packages', 'play-sms-call-log', 'privacy-labels']) + expect(rules(r.findings, 'play')).toContain(id); + expect(find(r.findings, 'play-target-sdk')!.evidence[0]).toMatchObject({ file: 'app/build.gradle.kts', line: 12 }); + expect(find(r.findings, 'play-sms-call-log')!.evidence[0]).toMatchObject({ file: 'app/src/main/AndroidManifest.xml', line: 5 }); + expect(rules(r.findings, 'apple').size).toBe(0); + expect(rules(r.findings)).not.toContain('play-app-access'); + expect(rules(r.findings)).not.toContain('account-deletion'); + }); + test('capacitor (no config: project files only)', async () => { + const r = await scan('capacitor'); + expect(r.config).toBeNull(); + for (const id of ['min-functionality', 'purpose-strings', 'play-target-sdk', 'privacy-manifest', 'att']) expect(rules(r.findings)).toContain(id); + expect(find(r.findings, 'min-functionality')!.evidence[0]).toMatchObject({ file: 'capacitor.config.json', line: 6 }); + expect(rules(r.findings)).not.toContain('export-compliance'); + }); + test('unity', async () => { + const r = await scan('unity'); + for (const id of ['purpose-strings', 'play-target-sdk', 'restore-purchases', 'kids-ads', 'review-prompt', 'privacy-manifest']) expect(rules(r.findings)).toContain(id); + expect(find(r.findings, 'kids-ads', 'apple')!.guideline).toBe('1.3'); + expect(find(r.findings, 'kids-ads', 'play')).toBeTruthy(); + expect(r.findings.find(f => f.rule === 'review-prompt' && f.severity === 'high')).toBeTruthy(); + expect(rules(r.findings)).not.toContain('kids-terms'); + }); + test('flutter', async () => { + const r = await scan('flutter'); + for (const id of ['account-deletion', 'play-deletion-url', 'login-services', 'restore-purchases', 'subscription-info', 'att', 'play-fgs', 'play-target-sdk']) expect(rules(r.findings)).toContain(id); + expect(find(r.findings, 'att')!.severity).toBe('blocker'); + expect(r.findings.find(f => f.rule === 'subscription-info' && f.severity === 'blocker')!.title).toContain('Terms of Use'); + expect(r.findings.find(f => f.rule === 'play-fgs' && f.title.includes('FOREGROUND_SERVICE_LOCATION'))).toBeTruthy(); + expect(find(r.findings, 'play-target-sdk')!.severity).toBe('low'); + }); + test('teaser: exactly the five classic rejections', async () => { + const r = await scan('teaser'); + expect([...rules(r.findings)].sort()).toEqual(['account-deletion', 'att', 'demo-account', 'login-services', 'restore-purchases']); + expect(r.findings.map(f => f.guideline)).toEqual(['2.1(a)', '5.1.1(v)', '4.8', '3.1.1', '5.1.2(i)']); + }); +}); + +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'; + const r = await scan('clean'); + expect(r.findings.map(f => `${f.rule}: ${f.title}`)).toEqual([]); + expect(r.declarations.changed).toBe(false); + expect(r.declarations.labelGaps).toEqual([]); + expect(r.stacks.sort()).toEqual(['android-native', 'ios-native']); + }); + test('the demo account comes from the environment or .storebound/', async () => { + expect(rules((await scan('clean')).findings)).toContain('demo-account'); + }); + test('the example projects have no open finding (the fictional ones are accepted in scan.ignore)', async () => { + for (const d of ['demo-app', 'demo-game']) { + const r = (await runScan(join(ROOT, 'examples', d))).report; + expect(r.findings.filter(f => !f.accepted).map(f => f.title)).toEqual([]); + for (const f of r.findings) expect(f.accepted!.length).toBeGreaterThan(10); + } + }); +}); + +describe('declarations proposal', () => { + test('detected SDK data types become additions, owner answers are kept, never removed', async () => { + const d = (await scan('android')).declarations; + expect(d.diff.find(x => x.type === 'PSL_DEVICE_ID')).toMatchObject({ change: 'add', after: { shared: true, collect: ['advertising', 'analytics', 'fraud'], share: ['advertising'] } }); + expect(d.diff.find(x => x.type === 'PSL_EMAIL')!.change).toBe('merge'); + expect(d.dataSafety!.data.PSL_EMAIL!.collect).toEqual(['account', 'functionality']); + expect(d.items.find(x => x.what === 'encryptedInTransit')!.status).toBe('ask'); + expect(d.items.find(x => x.what === 'PSL_DEVICE_ID')!.evidence[0]!.file).toBe('gradle/libs.versions.toml'); + expect(d.changed).toBe(true); + }); + test('ATT and the privacy manifest', async () => { + const d = (await scan('clean')).declarations; + expect(d.items.find(x => x.area === 'appPrivacy' && x.what === 'tracking')).toMatchObject({ status: 'detected', value: expect.stringContaining('true') }); + expect(d.items.find(x => x.area === 'privacyManifest' && x.what === 'NSPrivacyAccessedAPICategoryUserDefaults')).toMatchObject({ status: 'detected', value: 'declared: CA92.1' }); + const t = (await scan('teaser')).declarations; + expect(t.items.find(x => x.area === 'att')!.status).toBe('ask'); + }); +}); + +describe('config writing', () => { + test('matchBrace skips strings and comments', () => { + const s = "{ a: '}', b: { c: \"{\" }, // }\n d: `}` }"; + expect(matchBrace(s, 0)).toBe(s.length - 1); + }); + test('toTs writes plain TypeScript', () => { + expect(toTs({ shared: false, collect: ['a', 'b'] })).toBe("{ shared: false, collect: ['a', 'b'] }"); + expect(toTs({ PSL_X: { shared: true, collect: ['x'] } }, ' ')).toBe("{\n PSL_X: { shared: true, collect: ['x'] },\n }"); + }); + test('upsertBlock replaces an existing block and inserts after app', () => { + const src = "export default {\n app: { name: 'X' },\n dataSafety: { collectsData: false, data: {} },\n languages: [],\n};\n"; + const a = upsertBlock(src, 'c.ts', 'dataSafety', { collectsData: true, data: {} }); + expect(a).toBe("export default {\n app: { name: 'X' },\n dataSafety: {\n collectsData: true,\n data: {},\n },\n languages: [],\n};\n"); + const b = upsertBlock(src, 'c.ts', 'appPrivacy', { tracking: true }, 'note'); + expect(b).toContain(" app: { name: 'X' },\n // note\n appPrivacy: { tracking: true },\n dataSafety"); + expect(JSON.parse(upsertBlock('{"app":{}}', 'c.json', 'appPrivacy', { tracking: false }))).toEqual({ app: {}, appPrivacy: { tracking: false } }); + }); + test('scan is read-only without --write; --write adds the detected answers and the config still loads', async () => { + const dir = mkdtempSync(join(tmpdir(), 'sb-scan-')); + try { + cpSync(join(FX, 'android'), dir, { recursive: true }); + const before = readFileSync(join(dir, 'storebound.config.ts'), 'utf8'); + const run = (...a: string[]) => Bun.spawnSync(['bun', CLI, 'scan', '--dir', dir, ...a], { env: { ...process.env, REVIEW_DEMO_USER: '', REVIEW_DEMO_PASSWORD: '' } }); + const r1 = run(); + expect(r1.exitCode).toBe(1); + expect(r1.stdout.toString()).toContain('+ dataSafety.data.PSL_DEVICE_ID'); + expect(readFileSync(join(dir, 'storebound.config.ts'), 'utf8')).toBe(before); + run('--write', '--dry'); + expect(readFileSync(join(dir, 'storebound.config.ts'), 'utf8')).toBe(before); + run('--write'); + const after = readFileSync(join(dir, 'storebound.config.ts'), 'utf8'); + expect(after).toContain("PSL_DEVICE_ID: { shared: true, collect: ['advertising', 'analytics', 'fraud'], share: ['advertising'] }"); + expect(after).toContain("PSL_EMAIL: { shared: false, collect: ['account', 'functionality'] }"); + expect(after).toContain("accountCreation: ['PSL_ACM_USER_ID_PASSWORD']"); + const again = await runScan(dir); + expect(again.report.configError).toBeNull(); + expect(again.report.declarations.changed).toBe(false); + expect(rules(again.report.findings)).not.toContain('privacy-labels'); + } finally { rmSync(dir, { recursive: true, force: true }); } + }); +}); + +describe('integration', () => { + test('JSON output, --store filter, exit code', () => { + const r = Bun.spawnSync(['bun', CLI, 'scan', '--dir', join(FX, 'teaser'), '--json', '--store', 'apple'], { env: { ...process.env, REVIEW_DEMO_USER: '', REVIEW_DEMO_PASSWORD: '' } }); + expect(r.exitCode).toBe(1); + const j = JSON.parse(r.stdout.toString()) as { counts: { blocker: number }; findings: ScanFinding[] }; + expect(j.counts.blocker).toBe(2); + expect(j.findings.every(f => f.store === 'apple')).toBe(true); + }); + test('scan.ignore marks findings as accepted and they stop blocking', async () => { + const r = (await runScan(join(ROOT, 'examples', 'demo-app'))).report; + expect(r.findings.find(f => f.rule === 'demo-account')!.accepted).toContain('fictional'); + expect(r.counts.blocker).toBe(0); + }); + test('validate gets the open blockers and risks, not low or accepted ones', async () => { + const r = (await scan('flutter')).findings; + const v = scanAsFindings(r, { apple: true, play: false }); + expect(v.every(f => f.store === 'apple' && f.code.startsWith('scan-'))).toBe(true); + expect(v.filter(f => f.level === 'blocker').length).toBe(r.filter(f => f.store === 'apple' && f.severity === 'blocker').length); + expect(v.some(f => f.code === 'scan-subscription-info' && f.msg.startsWith('3.1.2'))).toBe(true); + expect(scanAsFindings([{ ...r[0]!, accepted: 'fine' }], { apple: true, play: true })).toEqual([]); + }); + test('MCP tool and desktop method are read-only and cannot write', () => { + const t = TOOLS.find(x => x.name === 'scan')!; + expect(t.write).toBe(false); + expect(t.network).toBe(false); + expect(toArgv(t, { store: 'play' }).argv).toEqual(['scan', '--store', 'play']); + expect(FORBIDDEN_ARGS).toContain('--write'); + for (const x of TOOLS) expect(toArgv(x, {}).argv).not.toContain('--write'); + expect(JSON_TOOLS.has('scan')).toBe(true); + }); +}); diff --git a/tools/gen-adapters.ts b/tools/gen-adapters.ts index 953fd4b2..38ed65f0 100644 --- a/tools/gen-adapters.ts +++ b/tools/gen-adapters.ts @@ -73,7 +73,7 @@ export function generate(root: string): Map { '', '- CLI: `storebound ` (`storebound help`); config `storebound.config.ts`, credentials in env or `.storebound/`.', '- MCP: `storebound mcp` (stdio). MCP 2026-07-28 + 2025-11-25. Write tools default to `dry_run: true`; submit / release / cancel / delete / send are not exposed.', - '- Readiness: `storebound check` (offline), `storebound validate` (read-only, both stores).', + '- Readiness: `storebound scan` (offline rejection risks in the project files), `storebound check` (offline), `storebound validate` (read-only, both stores).', ].join('\n'); // 4. AGENTS.md (Codex, Cursor, Copilot, Windsurf, OpenCode, ...) diff --git a/tools/scrub.ts b/tools/scrub.ts index 61cd1cdc..e718b7b8 100644 --- a/tools/scrub.ts +++ b/tools/scrub.ts @@ -21,7 +21,8 @@ export const RULES: Rule[] = [ allow: (_m, line) => /"macTeamId":/.test(line) }, { id: 'issuer-uuid', re: /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/g, allow: m => /^0{8}-0{4}-0{4}-0{4}-0{12}$/.test(m) }, - { id: 'ip-address', re: /(? ['127.0.0.1', '0.0.0.0'].includes(m) }, + { id: 'ip-address', re: /(? ['127.0.0.1', '0.0.0.0'].includes(m) || /^(192\.0\.2|198\.51\.100|203\.0\.113)\.\d{1,3}$/.test(m) }, { id: 'private-name', re: new RegExp(['Yon', 'ga'].join(''), 'gi') }, { id: 'google-api-key', re: new RegExp('AI' + 'za[0-9A-Za-z_-]{35}', 'g') }, // absolute home folders leak a machine's account name (placeholders like /Users/you are fine) diff --git a/tsconfig.json b/tsconfig.json index 85a64b54..58021c2d 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -13,5 +13,6 @@ "resolveJsonModule": true, "allowImportingTsExtensions": true }, - "include": ["cli", "tests", "tools", "templates/storebound.config.ts", "examples/demo-game/storebound.config.ts", "examples/demo-game/serve.ts", "examples/demo-app/storebound.config.ts", "examples/demo-app/serve.ts", "templates/profiles/*/storebound.config.ts", "media/teaser/render.ts"] + "include": ["cli", "tests", "tools", "templates/storebound.config.ts", "examples/demo-game/storebound.config.ts", "examples/demo-game/serve.ts", "examples/demo-app/storebound.config.ts", "examples/demo-app/serve.ts", "templates/profiles/*/storebound.config.ts", "media/teaser/render.ts"], + "exclude": ["tests/fixtures/scan"] }