Merge build-sign: signing, Xcode/Gradle build and upload, originality check

# Conflicts:
#	CHANGELOG.md
#	cli/index.ts
#	cli/lib/credentials.ts
This commit is contained in:
CRTkafa 2026-10-11 23:48:20 +08:00
commit 217d42cc9a
36 changed files with 2785 additions and 28 deletions

View file

@ -47,6 +47,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
- `skills/app-previews/SKILL.md`: Make App Store app preview videos and a Google Play promo video for a mobile app or game from real footage (gameplay or app flows) - `skills/app-previews/SKILL.md`: Make App Store app preview videos and a Google Play promo video for a mobile app or game from real footage (gameplay or app flows)
- `skills/appstore-first-release/SKILL.md`: Step-by-step first (and later) App Store release of a mobile app or game - `skills/appstore-first-release/SKILL.md`: Step-by-step first (and later) App Store release of a mobile app or game
- `skills/aso-basics/SKILL.md`: App store optimization basics for a mobile app's or game's text - `skills/aso-basics/SKILL.md`: App store optimization basics for a mobile app's or game's text
- `skills/build-and-sign/SKILL.md`: Sign, build and upload a mobile app or game from the terminal
- `skills/export-compliance/SKILL.md`: Answer App Store export compliance (encryption) for a mobile app or game correctly - `skills/export-compliance/SKILL.md`: Answer App Store export compliance (encryption) for a mobile app or game correctly
- `skills/migrate-from-fastlane/SKILL.md`: Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane` - `skills/migrate-from-fastlane/SKILL.md`: Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane`
- `skills/play-first-release/SKILL.md`: Step-by-step first (and later) Google Play release of a mobile app or game - `skills/play-first-release/SKILL.md`: Step-by-step first (and later) Google Play release of a mobile app or game

View file

@ -49,6 +49,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
| `app-previews` | Make App Store app preview videos and a Google Play promo video for a mobile app or game from real footage (gameplay or app flows) | | `app-previews` | Make App Store app preview videos and a Google Play promo video for a mobile app or game from real footage (gameplay or app flows) |
| `appstore-first-release` | Step-by-step first (and later) App Store release of a mobile app or game | | `appstore-first-release` | Step-by-step first (and later) App Store release of a mobile app or game |
| `aso-basics` | App store optimization basics for a mobile app's or game's text | | `aso-basics` | App store optimization basics for a mobile app's or game's text |
| `build-and-sign` | Sign, build and upload a mobile app or game from the terminal |
| `export-compliance` | Answer App Store export compliance (encryption) for a mobile app or game correctly | | `export-compliance` | Answer App Store export compliance (encryption) for a mobile app or game correctly |
| `migrate-from-fastlane` | Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane` | | `migrate-from-fastlane` | Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane` |
| `play-first-release` | Step-by-step first (and later) Google Play release of a mobile app or game | | `play-first-release` | Step-by-step first (and later) Google Play release of a mobile app or game |

View file

@ -48,6 +48,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
- `skills/app-previews/SKILL.md`: Make App Store app preview videos and a Google Play promo video for a mobile app or game from real footage (gameplay or app flows) - `skills/app-previews/SKILL.md`: Make App Store app preview videos and a Google Play promo video for a mobile app or game from real footage (gameplay or app flows)
- `skills/appstore-first-release/SKILL.md`: Step-by-step first (and later) App Store release of a mobile app or game - `skills/appstore-first-release/SKILL.md`: Step-by-step first (and later) App Store release of a mobile app or game
- `skills/aso-basics/SKILL.md`: App store optimization basics for a mobile app's or game's text - `skills/aso-basics/SKILL.md`: App store optimization basics for a mobile app's or game's text
- `skills/build-and-sign/SKILL.md`: Sign, build and upload a mobile app or game from the terminal
- `skills/export-compliance/SKILL.md`: Answer App Store export compliance (encryption) for a mobile app or game correctly - `skills/export-compliance/SKILL.md`: Answer App Store export compliance (encryption) for a mobile app or game correctly
- `skills/migrate-from-fastlane/SKILL.md`: Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane` - `skills/migrate-from-fastlane/SKILL.md`: Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane`
- `skills/play-first-release/SKILL.md`: Step-by-step first (and later) Google Play release of a mobile app or game - `skills/play-first-release/SKILL.md`: Step-by-step first (and later) Google Play release of a mobile app or game

View file

@ -52,6 +52,33 @@
resource, and which ones storebound's commands already call (a scan of `cli/`, `cli/api/wrapped.gen.ts`); the full resource, and which ones storebound's commands already call (a scan of `cli/`, `cli/api/wrapped.gen.ts`); the full
table is `docs/api-coverage.md`. CI fails when the tables, the scan or the doc are stale against `specs/`. table is `docs/api-coverage.md`. CI fails when the tables, the scan or the doc are stale against `specs/`.
- MCP: one new read-only tool, `api_get` (GET operations only; not in the desktop profile). New skill `store-api`. - MCP: one new read-only tool, `api_get` (GET operations only; not in the desktop profile). New skill `store-api`.
- Signing through the App Store Connect API: `apple signing status` (read-only; also an MCP tool) and
`apple signing ensure` (dry first, asks once). Bundle id capabilities from `apple.signing.capabilities` (added,
never removed), an Apple Distribution certificate when this machine holds no key for a valid one (RSA 2048 key
and CSR made in TypeScript, key kept 0600 in `.storebound/signing/`, never printed; `--keychain` imports key and
certificate), App Store profiles per bundle id (app + `apple.signing.extraBundleIds`) reused while active or
created, installed for Xcode 16+ (`~/Library/Developer/Xcode/UserData/Provisioning Profiles`) and older Xcode
(`~/Library/MobileDevice/Provisioning Profiles`). A 403 on a Developer ID certificate is explained (Account Holder
only), as are the certificate limit and a key without the Admin role.
- `apple build`: finds the workspace / project and scheme (native, Capacitor, React Native, Flutter with
`flutter build ios --config-only`, Unity-iPhone), takes the next free build number from App Store Connect,
writes ExportOptions.plist (`method` app-store-connect, `destination` export, team, signing style, profiles) and
runs xcodebuild archive and -exportArchive with the API key; full logs in `build/ios/`, the IPA checked at the end.
- `apple upload`: the IPA through the App Store Connect API build upload (Build Uploads, API 4.1: reserve, upload
parts, commit with the MD5, poll) or `--via altool` (`altool --upload-package` with the API key); the build number
is checked against App Store Connect first, then storebound waits until the build is VALID (exit 0), INVALID /
FAILED (1) or the timeout (7). Dry first, asks.
- `play build`: Gradle `bundleRelease` (Flutter: `flutter build appbundle`; Capacitor / React Native `android/`,
Unity exports with `launcher/`) with the next free versionCode and the upload key from `ANDROID_KEYSTORE*` (env or
`.storebound/credentials.json`), handed to Gradle as injected signing properties through the environment, never on
the command line. The versionCode is read back from the AAB's manifest. `play upload --track internal|alpha|beta`:
versionCode checked, `--dry` read-only, a real run asks; production stays `play release --production draft`.
- `originality --against <folders>` (also an MCP tool): offline Guideline 4.3 check against the owner's other apps:
name and listing text similarity, icon and screenshot perceptual hashes (dHash + pHash; PNG decoded in TypeScript,
JPEG / WebP through ffmpeg when installed), project structure (file layout, identical files), an overall score,
near-duplicate flags and suggestions; exit 1 when a pair is flagged. The portfolio-originality skill uses it.
- New skill `build-and-sign`; appstore-first-release and play-first-release use the new commands. Zero new
dependencies: plist (XML + binary), ZIP, aapt2 manifest and PNG readers are small TypeScript modules.
- New logo: a glossy indigo box with an upward arrow (`brand/master/logo-mark.png`, `brand/README.md`). Every logo - 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 file comes from it through `tools/brand-assets.py`: desktop app icons (PNG sizes, `.icns`, a `.ico` with its own

View file

@ -48,6 +48,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
| `app-previews` | Make App Store app preview videos and a Google Play promo video for a mobile app or game from real footage (gameplay or app flows) | | `app-previews` | Make App Store app preview videos and a Google Play promo video for a mobile app or game from real footage (gameplay or app flows) |
| `appstore-first-release` | Step-by-step first (and later) App Store release of a mobile app or game | | `appstore-first-release` | Step-by-step first (and later) App Store release of a mobile app or game |
| `aso-basics` | App store optimization basics for a mobile app's or game's text | | `aso-basics` | App store optimization basics for a mobile app's or game's text |
| `build-and-sign` | Sign, build and upload a mobile app or game from the terminal |
| `export-compliance` | Answer App Store export compliance (encryption) for a mobile app or game correctly | | `export-compliance` | Answer App Store export compliance (encryption) for a mobile app or game correctly |
| `migrate-from-fastlane` | Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane` | | `migrate-from-fastlane` | Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane` |
| `play-first-release` | Step-by-step first (and later) Google Play release of a mobile app or game | | `play-first-release` | Step-by-step first (and later) Google Play release of a mobile app or game |

View file

@ -54,7 +54,7 @@ your own click.
|---|---|---|---|---| |---|---|---|---|---|
| 1 | **Set up** | `init --profile app\|game\|subscription-app` (config, `store/*.md`, declarations, App Privacy and privacy templates per profile), `install --agent <tool>`, `check` | Play: service account + API access invite; App Store: API team key (`play-first-release`, `appstore-first-release`) | developer accounts; Paid Applications agreement, banking and tax; Play payments profile | | 1 | **Set up** | `init --profile app\|game\|subscription-app` (config, `store/*.md`, declarations, App Privacy and privacy templates per profile), `install --agent <tool>`, `check` | Play: service account + API access invite; App Store: API team key (`play-first-release`, `appstore-first-release`) | developer accounts; Paid Applications agreement, banking and tax; Play payments profile |
| 2 | **App records and bundle id** | `apple bundle` registers the bundle id, `apple status` finds the app record | App Store Connect > New App (no API); Play Console > Create app; the very first AAB upload when Play needs it from the Console | the declarations you accept when creating the Play app | | 2 | **App records and bundle id** | `apple bundle` registers the bundle id, `apple status` finds the app record | App Store Connect > New App (no API); Play Console > Create app; the very first AAB upload when Play needs it from the Console | the declarations you accept when creating the Play app |
| 3 | **Builds and testers** | `play next-version-code`, `play release app.aab` (internal track), `apple next-build`, `xcodebuild` archive + upload with the API key (the skill has the commands), `apple encryption`, `apple testflight groups / what-to-test / info / distribute` (internal groups) | Play internal testers list, Apple sandbox testers (`play-first-release`, `testflight`) | `apple testflight testers` (Apple emails the invitations), external groups and Beta App Review (`distribute --submit-review`) | | 3 | **Builds and testers** | `play next-version-code`, `play build`, `play upload --track internal`, `apple signing ensure`, `apple build`, `apple upload` (waits for processing), `apple encryption`, `apple testflight groups / what-to-test / info / distribute` (internal groups) | Play internal testers list, Apple sandbox testers (`play-first-release`, `testflight`) | `apple testflight testers` (Apple emails the invitations), external groups and Beta App Review (`distribute --submit-review`) |
| 4 | **In-app products and subscriptions** | `play products` (regional prices from USD + your overrides, activated), `apple iap` (consumable, non-consumable, non-renewing; localizations, price schedule, availability), `apple iap-review`, `apple subscriptions` (groups, levels, equalized prices, intro and promotional offers, offer codes), `play subscriptions` (base plans, regional prices, offers), `catalog diff` (both stores against one catalog) | Play license testers, Apple sandbox testers, "Add for Review" of the first IAPs and subscriptions into the version's submission, Play promo codes (`store-iap-setup`, `store-subscriptions`) | custom offer codes (`apple subscriptions --codes` asks first) | | 4 | **In-app products and subscriptions** | `play products` (regional prices from USD + your overrides, activated), `apple iap` (consumable, non-consumable, non-renewing; localizations, price schedule, availability), `apple iap-review`, `apple subscriptions` (groups, levels, equalized prices, intro and promotional offers, offer codes), `play subscriptions` (base plans, regional prices, offers), `catalog diff` (both stores against one catalog) | Play license testers, Apple sandbox testers, "Add for Review" of the first IAPs and subscriptions into the version's submission, Play promo codes (`store-iap-setup`, `store-subscriptions`) | custom offer codes (`apple subscriptions --codes` asks first) |
| 5 | **Store listings, every language** | `play listing` (title, short / full description, contact email + website, promo video URL), `apple listing --version x --build N` (name, subtitle, description, keywords, promo text, URLs, privacy URL, manual release), `whats-new`, `check` (limits), `check --aso` | Play store settings: category and tags (`play-first-release`) | | | 5 | **Store listings, every language** | `play listing` (title, short / full description, contact email + website, promo video URL), `apple listing --version x --build N` (name, subtitle, description, keywords, promo text, URLs, privacy URL, manual release), `whats-new`, `check` (limits), `check --aso` | Play store settings: category and tags (`play-first-release`) | |
| 6 | **Play questionnaires** | `play data-safety`: the whole Data safety form from `dataSafety` in the config (CSV import through the API) | Policy and programs > App content, answers prepared in `store/declarations.md` (`store-declarations`): privacy policy, app access with the demo account (`review-access`), delete-account URL (`account-deletion`), ads, content rating (IARC), target audience and content, advertising ID, news, government, financial and health features; Data safety summary check | the answers themselves are your statements: the agent asks when the code does not prove them | | 6 | **Play questionnaires** | `play data-safety`: the whole Data safety form from `dataSafety` in the config (CSV import through the API) | Policy and programs > App content, answers prepared in `store/declarations.md` (`store-declarations`): privacy policy, app access with the demo account (`review-access`), delete-account URL (`account-deletion`), ads, content rating (IARC), target audience and content, advertising ID, news, government, financial and health features; Data safety summary check | the answers themselves are your statements: the agent asks when the code does not prove them |
@ -242,6 +242,7 @@ Read from environment variables, or from `.storebound/credentials.json` in your
| `PLAY_SERVICE_ACCOUNT` | path to the Google Cloud service account JSON key (or the JSON itself) with access to your app in Play Console | | `PLAY_SERVICE_ACCOUNT` | path to the Google Cloud service account JSON key (or the JSON itself) with access to your app in Play Console |
| `ASC_KEY_ID`, `ASC_ISSUER_ID` | App Store Connect API team key (Users and Access > Integrations) | | `ASC_KEY_ID`, `ASC_ISSUER_ID` | App Store Connect API team key (Users and Access > Integrations) |
| `ASC_P8` | path to `AuthKey_<id>.p8` (default `~/.appstoreconnect/private_keys/AuthKey_<id>.p8`) | | `ASC_P8` | path to `AuthKey_<id>.p8` (default `~/.appstoreconnect/private_keys/AuthKey_<id>.p8`) |
| `ANDROID_KEYSTORE`, `ANDROID_KEYSTORE_PASSWORD`, `ANDROID_KEY_ALIAS`, `ANDROID_KEY_PASSWORD` | upload key for `play build` (path to the .jks / .p12 and its passwords; handed to Gradle through the environment) |
| `reviewContact` | (file only) App Review contact name / phone / email | | `reviewContact` | (file only) App Review contact name / phone / email |
| `reviewDemoAccount` / `REVIEW_DEMO_USER`, `REVIEW_DEMO_PASSWORD` | demo account for App Review (`reviewAccess.signInRequired`); never in the config or the repo, masked in logs | | `reviewDemoAccount` / `REVIEW_DEMO_USER`, `REVIEW_DEMO_PASSWORD` | demo account for App Review (`reviewAccess.signInRequired`); never in the config or the repo, masked in logs |
@ -289,6 +290,7 @@ run in the background with a log (`storebound shots render > .storebound/render.
| `check --aso` | local | keyword audit: App Store keyword field rules, Play stuffing / claims | | `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 | | `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 | | `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 |
| `originality --against <folders> [--json]` | local, read-only | Guideline 4.3 check vs your other apps: name, listing text, icon and screenshot perceptual hashes, project structure; scores, near-duplicate flags, suggestions; exit 1 when flagged |
| `whats-new [--since <tag>]` | local | draft player-facing release notes from git log into both listing files | | `whats-new [--since <tag>]` | local | draft player-facing release notes from git log into both listing files |
| `privacy-manifest --ios <path>` | local | PrivacyInfo.xcprivacy, required-reason APIs, SDKs without manifests | | `privacy-manifest --ios <path>` | local | PrivacyInfo.xcprivacy, required-reason APIs, SDKs without manifests |
| `api list \| coverage \| apple\|play <operation>` | API | every App Store Connect / Google Play operation (see [Every endpoint](#every-endpoint)); GET runs, writes are dry unless `--yes` in a terminal | | `api list \| coverage \| apple\|play <operation>` | API | every App Store Connect / Google Play operation (see [Every endpoint](#every-endpoint)); GET runs, writes are dry unless `--yes` in a terminal |
@ -308,6 +310,8 @@ run in the background with a log (`storebound shots render > .storebound/render.
| `play products` | API | one-time products: regional prices from `convertRegionPrices` + your overrides, activate | | `play products` | API | one-time products: regional prices from `convertRegionPrices` + your overrides, activate |
| `play subscriptions [--csv]` | API | subscriptions: listings + benefits, one auto-renewing base plan, regional prices, intro and extra offers, activate (plan first, asks) | | `play subscriptions [--csv]` | API | subscriptions: listings + benefits, one auto-renewing base plan, regional prices, intro and extra offers, activate (plan first, asks) |
| `play data-safety` | API | Data safety form (CSV import); `--csv` writes the file | | `play data-safety` | API | Data safety form (CSV import); `--csv` writes the file |
| `play build [--version-code N] [--flavor f]` | local + API read | Gradle `bundleRelease` (Flutter `flutter build appbundle`; Capacitor, React Native, Unity export found) with the next free versionCode and the upload key from env / `.storebound` (passed through the environment, never argv); AAB checked and copied to `build/android/` |
| `play upload [<aab>] --track internal\|alpha\|beta` | API | AAB to a testing track with release notes; versionCode checked first; `--dry` is read-only, a real run asks |
| `play release <aab>` | API | upload + tracks (`--internal completed --production draft`, `--production inProgress --fraction 0.05`), release notes | | `play release <aab>` | API | upload + tracks (`--internal completed --production draft`, `--production inProgress --fraction 0.05`), release notes |
| `play rollout` | API | `--fraction x`, `--halt`, `--resume`, `--complete` (asks first, except halt) | | `play rollout` | API | `--fraction x`, `--halt`, `--resume`, `--complete` (asks first, except halt) |
| `play next-version-code` | API, read-only | next free versionCode | | `play next-version-code` | API, read-only | next free versionCode |
@ -330,6 +334,10 @@ run in the background with a log (`storebound shots render > .storebound/render.
| `apple review-details` | API | App Review contact, demo account (from `.storebound/`, masked), notes (+ sign-in steps, where account deletion is) | | `apple review-details` | API | App Review contact, demo account (from `.storebound/`, masked), notes (+ sign-in steps, where account deletion is) |
| `apple encryption` | API | export compliance answer from `apple.usesNonExemptEncryption` (never guessed) | | `apple encryption` | API | export compliance answer from `apple.usesNonExemptEncryption` (never guessed) |
| `apple release --phased on\|pause\|resume\|complete`, `--manual-release` | API | phased release, release an approved version (resume / complete / release ask first) | | `apple release --phased on\|pause\|resume\|complete`, `--manual-release` | API | phased release, release an approved version (resume / complete / release ask first) |
| `apple signing status` | API, read-only | bundle id capabilities, distribution certificates (with / without a private key on this Mac), App Store profiles per bundle id, installed or not |
| `apple signing ensure [--keychain] [--no-install]` | API | missing capabilities, a distribution certificate from a key made here (kept 0600 in `.storebound/signing/`, never printed), App Store profiles installed for Xcode; dry first, asks; Developer ID needs the Account Holder (403 explained) |
| `apple build [--version x.y.z] [--build-number N]` | local + API read | xcodebuild archive + exportArchive with a generated ExportOptions.plist (app-store-connect, team, signing style, profiles) and the API key; next build number; Capacitor, React Native, Flutter, Unity projects found |
| `apple upload [<ipa>] [--via api\|altool]` | API | IPA through the App Store Connect API build upload (or altool), build number checked, waits until VALID (exit 0 / 1 / 7); dry first, asks |
| `apple next-build` | API, read-only | next safe build number | | `apple next-build` | API, read-only | next safe build number |
| `apple status` | API | versions, builds, IAPs, submissions; `--wait-review` (exit 0 / 1 / 7); `--cancel-submission <id>` | | `apple status` | API | versions, builds, IAPs, submissions; `--wait-review` (exit 0 / 1 / 7); `--cancel-submission <id>` |
| `apple ppo status \| create --variant b \| upload --variant b` | API | Product Page Optimization test from `shots` variants: treatments, localizations, screenshot sets | | `apple ppo status \| create --variant b \| upload --variant b` | API | Product Page Optimization test from `shots` variants: treatments, localizations, screenshot sets |
@ -563,7 +571,8 @@ navigation.
|---|---| |---|---|
| `migrate-from-fastlane` | `storebound import fastlane`: ids, listings, languages and screenshots from fastlane; keys and accounts stay out | | `migrate-from-fastlane` | `storebound import fastlane`: ids, listings, languages and screenshots from fastlane; keys and accounts stay out |
| `play-first-release` | Google Play from zero to "In review" | | `play-first-release` | Google Play from zero to "In review" |
| `appstore-first-release` | App Store from API key to "Waiting for review", incl. xcodebuild with the API key | | `appstore-first-release` | App Store from API key to "Waiting for review" |
| `build-and-sign` | API signing (capabilities, certificate, profiles), `apple build` / `apple upload`, `play build` / `play upload`, for native, Capacitor, React Native, Flutter and Unity projects |
| `testflight` | beta groups, testers from a CSV that never enters git, What to Test, Test Information, Beta App Review | | `testflight` | beta groups, testers from a CSV that never enters git, What to Test, Test Information, Beta App Review |
| `store-iap-setup` | in-app products on both stores (consumable, non-consumable, non-renewing), prices and the price sheet CSV, catalog diff, testers, the first-IAP-with-version rule | | `store-iap-setup` | in-app products on both stores (consumable, non-consumable, non-renewing), prices and the price sheet CSV, catalog diff, testers, the first-IAP-with-version rule |
| `store-subscriptions` | subscription groups, levels, base plans, prices, intro and promotional offers, offer codes, disclosure and Terms (3.1.2), first submission | | `store-subscriptions` | subscription groups, levels, base plans, prices, intro and promotional offers, offer codes, disclosure and Terms (3.1.2), first submission |
@ -588,7 +597,7 @@ navigation.
| `whats-new` | player-facing release notes from git, localized, within store limits | | `whats-new` | player-facing release notes from git, localized, within store limits |
| `review-rejections` | triage a rejection (fix / clarify / push back / appeal), reply template, the guidelines apps and games hit | | `review-rejections` | triage a rejection (fix / clarify / push back / appeal), reply template, the guidelines apps and games hit |
| `ads-mediation-checks` | AdMob, AppLovin MAX and LevelPlay: ids, debug tools, adapters, app-ads.txt, SKAdNetwork, no-fill (`ads-levelplay-checks` stays as a pointer) | | `ads-mediation-checks` | AdMob, AppLovin MAX and LevelPlay: ids, debug tools, adapters, app-ads.txt, SKAdNetwork, no-fill (`ads-levelplay-checks` stays as a pointer) |
| `portfolio-originality` | Guideline 4.3 gate for developers shipping many similar apps or games | | `portfolio-originality` | Guideline 4.3 gate for developers shipping many similar apps or games, with `storebound originality` scores |
## MCP server ## MCP server

148
cli/apple/build.ts Normal file
View file

@ -0,0 +1,148 @@
// Archive and export an App Store IPA with xcodebuild, no Xcode UI.
// storebound apple build [--version 1.2.0] [--build-number N] [--scheme S] [--workspace W | --project P]
// [--configuration Release] [--out build/ios] [--dry] [--json]
// Finds the workspace / project and scheme (native, Capacitor ios/App, React Native ios/<Name>, Flutter ios/Runner,
// Unity Unity-iPhone), takes the next safe build number from App Store Connect (apple next-build) unless
// --build-number is given, writes <out>/ExportOptions.plist (method app-store-connect, team, signing style and the
// profiles from apple.signing), runs xcodebuild archive and -exportArchive with the API key
// (-allowProvisioningUpdates -authenticationKey*), and leaves <out>/export/<App>.ipa for `storebound apple upload`.
// Full xcodebuild output goes to <out>/xcodebuild-*.log; the terminal gets the result lines.
// Local only: nothing is sent to App Store Connect except reads (build numbers, team id, profiles).
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { join, relative } from 'node:path';
import { ascKeyFile } from '../lib/credentials';
import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx';
import { done, log, printJson, warn } from '../lib/log';
import { pump } from '../lib/runner';
import { parseMobileprovision, toXmlPlist } from '../lib/plist';
import { nextBuildNumber } from '../lib/release';
import { exportOptions, profileDirs } from '../lib/signing';
import { archiveArgs, type AscAuth, exportArgs, flutterConfigArgs, ipaInfo, pickXcode, scanXcode, showCmd } from '../lib/xcode';
import { ascClient } from './asc';
import { findBundleId } from './signing';
const TAG = 'build';
/** Installed App Store profiles for a bundle id, newest expiry first: { uuid, name, team }. */
export function installedProfiles(bundleId: string, teamId: string | null, home = homedir()): { uuid: string; name: string; team: string; expires: string }[] {
const out: { uuid: string; name: string; team: string; expires: string }[] = [];
for (const d of profileDirs(home)) {
let files: string[] = [];
try { files = readdirSync(d).filter(f => f.endsWith('.mobileprovision')); } catch { continue; }
for (const f of files) {
try {
const p = parseMobileprovision(readFileSync(join(d, f)));
const ent = p.Entitlements as Record<string, unknown> | undefined;
const appId = String(ent?.['application-identifier'] ?? '');
const team = String((p.TeamIdentifier as string[] | undefined)?.[0] ?? '');
const store = !p.ProvisionedDevices && !p.ProvisionsAllDevices && ent?.['get-task-allow'] !== true;
if (!store || appId !== `${team}.${bundleId}` || (teamId && team !== teamId)) continue;
if (Date.parse(String(p.ExpirationDate)) < Date.now()) continue;
if (!out.some(x => x.uuid === p.UUID)) out.push({ uuid: String(p.UUID), name: String(p.Name), team, expires: String(p.ExpirationDate) });
} catch { /* not a profile */ }
}
}
return out.sort((a, b) => Date.parse(b.expires) - Date.parse(a.expires));
}
async function runLogged(argv: string[], cwd: string, logFile: string, show: string, env?: Record<string, string>): Promise<void> {
log(TAG, `$ ${show}`);
log(TAG, `full output: ${logFile}`);
const p = Bun.spawn(argv, { cwd, stdout: 'pipe', stderr: 'pipe', env: { ...process.env, LANG: 'en_US.UTF-8', LC_ALL: 'en_US.UTF-8', ...env } });
const chunks: string[] = [];
const keep = /(\berror:|\*\* (ARCHIVE|EXPORT|BUILD) (SUCCEEDED|FAILED) \*\*|requires a provisioning profile|No signing certificate|Signing for .* requires|Exported .* to)/;
const each = (line: string): void => { chunks.push(line); if (keep.test(line)) log(TAG, line.trim().slice(0, 300)); };
await Promise.all([pump(p.stdout, 'stdout', each), pump(p.stderr, 'stderr', each)]);
const code = await p.exited;
writeFileSync(logFile, chunks.join('\n'));
if (code !== 0) throw new Error(`${argv[0]} ${argv[1] ?? ''} failed (exit ${code}); last lines:\n${chunks.slice(-15).join('\n')}\nfull log: ${logFile}`);
}
export async function run(ctx: Ctx): Promise<void> {
const { config, root, resolve } = ctx.loaded;
const a = ctx.args;
const bundleId = need(config.apple?.bundleId, 'apple.bundleId');
const cfg = config.apple?.build ?? {};
const signing = config.apple?.signing ?? {};
const style = signing.style ?? 'automatic';
const dry = a.has('dry');
const json = a.has('json');
const target = pickXcode(scanXcode(root), { ...cfg, workspace: a.get('workspace') ?? cfg.workspace, project: a.get('project') ?? cfg.project, scheme: a.get('scheme') ?? cfg.scheme });
const configuration = a.str('configuration', cfg.configuration ?? 'Release');
const out = resolve(a.get('out') ?? cfg.out ?? 'build/ios');
const version = a.get('version');
if (version && !/^\d+(\.\d+){0,2}$/.test(version)) throw new Error('--version: x.y.z');
// reads: build number and team id from App Store Connect (only if not given)
let build = a.get('build-number');
let teamId = signing.teamId ?? null;
if (!build || !teamId) {
try {
const c = await ascClient(root, bundleId, config.apple?.appId);
if (!build) {
const builds = await c.all(`/v1/builds?filter[app]=${await c.app()}&limit=200&fields[builds]=version`);
build = nextBuildNumber(builds.map(b => String(b.attributes.version)));
log(TAG, `${builds.length} builds on App Store Connect: next build number ${build}`);
}
if (!teamId) teamId = (await findBundleId(c, bundleId))?.attributes?.seedId ?? null;
} catch (e) {
if (!dry) throw new Error(`${(e as Error).message}\n(pass --build-number N and set apple.signing.teamId to build without App Store Connect reads)`);
warn(TAG, `App Store Connect not readable (${(e as Error).message.split('\n')[0]?.slice(0, 120)}): dry run continues with placeholders`);
}
}
if (build && !/^\d+(\.\d+){0,2}$/.test(build)) throw new Error('--build-number: digits, e.g. 42 or 1.0.42');
const buildNo = build ?? '<next build number>';
const ids = [bundleId, ...(signing.extraBundleIds ?? [])];
const profiles: Record<string, string> = {};
if (style === 'manual') for (const id of ids) {
const p = installedProfiles(id, teamId)[0];
if (p) profiles[id] = p.uuid; else if (!dry) throw new Error(`no installed App Store profile for ${id}: storebound apple signing ensure`);
else warn(TAG, `no installed App Store profile for ${id} (storebound apple signing ensure)`);
}
const opts = exportOptions({ teamId: teamId ?? '<TEAM_ID>', style, profiles: style === 'manual' ? (Object.keys(profiles).length ? profiles : { [bundleId]: '<profile uuid>' }) : undefined });
const plist = toXmlPlist(opts);
const archivePath = join(out, `${target.scheme}.xcarchive`);
const exportPath = join(out, 'export');
const authPreview: AscAuth = { keyPath: '$ASC_P8', keyId: '$ASC_KEY_ID', issuerId: '$ASC_ISSUER_ID' };
const auth = style === 'automatic' ? authPreview : null;
const steps = [
...(target.framework === 'flutter' ? [showCmd(flutterConfigArgs(buildNo, version), null)] : []),
showCmd(archiveArgs({ target, root, configuration, archivePath, version, build: buildNo, teamId: teamId ?? undefined, auth }), auth),
showCmd(exportArgs(archivePath, join(out, 'ExportOptions.plist'), exportPath, auth), auth),
];
const plan = { framework: target.framework, workspace: target.workspace ?? null, project: target.project ?? null, scheme: target.scheme, configuration,
version: version ?? '(project value)', build: buildNo, teamId, signingStyle: style, exportOptions: opts, out: relative(root, out) || '.', steps, notes: target.notes };
if (dry) {
if (json) { printJson(plan); return; }
log(TAG, `${target.framework}: ${target.workspace ?? target.project} scheme ${target.scheme} (${configuration}), build ${buildNo}${version ? `, version ${version}` : ''}, signing ${style}`);
for (const n of target.notes) log(TAG, n);
for (const s of steps) log(TAG, `would run: ${s}`);
console.log(`\n${relative(root, join(out, 'ExportOptions.plist'))}:\n${plist}`);
done(TAG, 'build planned (dry run)');
return;
}
if (process.platform !== 'darwin' || !Bun.which('xcodebuild')) throw new Error('apple build needs macOS with Xcode (xcode-select --install is not enough: the full Xcode app)');
for (const n of target.notes) log(TAG, n);
mkdirSync(out, { recursive: true });
writeFileSync(join(out, 'ExportOptions.plist'), plist);
const key = style === 'automatic' ? ascKeyFile(root) : null;
const realAuth: AscAuth | null = key ? { keyPath: key.keyPath, keyId: key.keyId, issuerId: key.issuerId } : null;
try {
if (target.framework === 'flutter') await runLogged(flutterConfigArgs(build!, version), root, join(out, 'flutter-config.log'), showCmd(flutterConfigArgs(build!, version), null));
const arch = archiveArgs({ target, root, configuration, archivePath, version, build: build!, teamId: teamId ?? undefined, auth: realAuth });
await runLogged(arch, root, join(out, 'xcodebuild-archive.log'), showCmd(arch, realAuth));
const exp = exportArgs(archivePath, join(out, 'ExportOptions.plist'), exportPath, realAuth);
await runLogged(exp, root, join(out, 'xcodebuild-export.log'), showCmd(exp, realAuth));
} finally { key?.cleanup(); }
const ipa = existsSync(exportPath) ? readdirSync(exportPath).find(f => f.endsWith('.ipa')) : undefined;
if (!ipa) throw new Error(`export finished but no .ipa in ${exportPath}`);
const info = ipaInfo(join(exportPath, ipa));
if (info.bundleId !== bundleId) warn(TAG, `the IPA's bundle id is ${info.bundleId}, the config says ${bundleId}`);
if (info.build !== build) warn(TAG, `the IPA has build ${info.build}, not ${build}: the project sets CFBundleVersion itself (use $(CURRENT_PROJECT_VERSION) in Info.plist)`);
const result = { ipa: join(exportPath, ipa), bundleId: info.bundleId, version: info.version, build: info.build };
if (json) printJson(result);
done(TAG, `${relative(root, result.ipa)}: ${info.bundleId} ${info.version} (${info.build}). Next: storebound apple upload ${relative(root, result.ipa)} --dry`);
}

232
cli/apple/signing.ts Normal file
View file

@ -0,0 +1,232 @@
// Code signing through the App Store Connect API: bundle id capabilities, the distribution certificate and the
// provisioning profiles, so `apple build` can sign without anyone opening Xcode's Accounts settings.
// storebound apple signing status [--json] read-only: capabilities, certificates (with / without a
// private key on this machine), profiles, what is installed
// storebound apple signing ensure [--dry] [--yes] [--keychain [path]] [--no-install] [--json]
// adds missing capabilities (apple.signing.capabilities), creates a distribution certificate when this machine
// holds no key for any valid one (RSA 2048 key generated here, kept 0600 in .storebound/signing/, never printed;
// --keychain also imports key + certificate into the login keychain or the given one), creates or reuses an
// App Store profile per bundle id (apple.bundleId + apple.signing.extraBundleIds) and installs it for Xcode.
// Every write is shown first (--dry shows only that) and asks once before anything is created. Developer ID
// certificates need the Account Holder: the API's 403 is explained. Pure planning: cli/lib/signing.ts.
import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import type { Ctx } from '../lib/ctx';
import { confirm, need } from '../lib/ctx';
import { buildCsr, csrContent, newSigningKey, spkiOfKey } from '../lib/csr';
import { done, log, printJson, warn } from '../lib/log';
import {
type ApiCert, type ApiProfile, type AppleSigning, capabilitySpecs, CERT_LIMIT, certificateReq, certSha1, certSpki, type CertType,
explainCertError, parseIdentities, pickCertificate, planCapabilities, planProfile, profileDirs, type ProfileType,
} from '../lib/signing';
import { textTable } from '../lib/table';
import { type Asc, ascClient, type J } from './asc';
import { describeReq, execute, type Req } from './jsonapi';
const TAG = 'signing';
const USAGE = 'usage: storebound apple signing status | ensure [--dry] [--keychain [path]] [--no-install]';
export const signingDir = (root: string): string => join(root, '.storebound', 'signing');
/** SPKIs of the private keys in .storebound/signing (file name = certificate id once created). */
function localKeys(root: string): Map<string, string> {
const dir = signingDir(root);
const out = new Map<string, string>();
if (!existsSync(dir)) return out;
for (const f of readdirSync(dir).filter(f => f.endsWith('.key'))) {
try { out.set(spkiOfKey(readFileSync(join(dir, f), 'utf8')), f); } catch { warn(TAG, `${f}: not a private key, ignored`); }
}
return out;
}
/** SHA-1s of code signing identities in the keychain search list (macOS; empty elsewhere). Read-only. */
function keychainIdentities(): Set<string> {
if (process.platform !== 'darwin' || !Bun.which('security')) return new Set();
const r = Bun.spawnSync(['security', 'find-identity', '-v', '-p', 'codesigning'], { stdout: 'pipe', stderr: 'pipe' });
return new Set(parseIdentities(r.stdout.toString()).map(i => i.sha1));
}
export async function findBundleId(c: Asc, identifier: string): Promise<J | null> {
const r = await c.asc('GET', `/v1/bundleIds?filter[identifier]=${encodeURIComponent(identifier)}&include=bundleIdCapabilities&limit=200`);
const hit = (r.data as J[]).find(b => b.attributes.identifier === identifier) ?? null;
if (hit) hit.capabilities = (r.included ?? []).filter((x: J) => x.type === 'bundleIdCapabilities' && (hit.relationships?.bundleIdCapabilities?.data ?? []).some((d: J) => d.id === x.id))
.map((x: J) => x.attributes.capabilityType as string);
return hit;
}
async function profilesOf(c: Asc, bundleIdId: string, type: ProfileType): Promise<ApiProfile[]> {
const ps = await c.all(`/v1/bundleIds/${bundleIdId}/profiles?limit=200`);
const out: ApiProfile[] = [];
for (const p of ps.filter((p: J) => p.attributes.profileType === type)) {
const certs = await c.all(`/v1/profiles/${p.id}/relationships/certificates?limit=200`);
out.push({ id: p.id, attributes: p.attributes, certIds: certs.map((x: J) => x.id) });
}
return out;
}
const installedAt = (uuid: string | undefined): string[] => (uuid ? profileDirs(homedir()).map(d => join(d, `${uuid}.mobileprovision`)).filter(existsSync) : []);
function install(p: ApiProfile): string[] {
const content = p.attributes.profileContent;
if (!content || !p.attributes.uuid) throw new Error(`profile ${p.attributes.name}: no content to install`);
const out: string[] = [];
for (const d of profileDirs(homedir())) {
mkdirSync(d, { recursive: true });
const f = join(d, `${p.attributes.uuid}.mobileprovision`);
writeFileSync(f, Buffer.from(content, 'base64'));
out.push(f);
}
return out;
}
function keychainImport(keyFile: string, cerFile: string, keychain: string | null): void {
if (process.platform !== 'darwin') throw new Error('--keychain: macOS only (on other systems keep the key in .storebound/signing)');
const kc = keychain ? ['-k', keychain] : [];
for (const cmd of [['security', 'import', keyFile, ...kc, '-t', 'priv', '-f', 'openssl', '-T', '/usr/bin/codesign', '-T', '/usr/bin/productbuild'], ['security', 'import', cerFile, ...kc, '-t', 'cert']]) {
const r = Bun.spawnSync(cmd, { stdout: 'pipe', stderr: 'pipe' });
const msg = (r.stdout.toString() + r.stderr.toString()).trim();
if (r.exitCode !== 0 && !/already exists/i.test(msg)) throw new Error(`security import failed: ${msg.slice(0, 300)}`);
}
log(TAG, `key and certificate imported into ${keychain ?? 'the default keychain'}`);
}
export interface SigningState {
bundleId: string; teamId: string | null; registered: boolean;
capabilities: { present: string[]; missing: string[]; extra: string[] };
certificate: { type: CertType; chosen: string | null; why: string; onTeam: number; withKey: number; limit: number | null };
profiles: { bundleId: string; name: string | null; uuid: string | null; state: string; installed: boolean; why: string }[];
}
export async function run(ctx: Ctx): Promise<void> {
const { config, root } = ctx.loaded;
const a = ctx.args;
const sub = a._[0];
if (sub !== 'status' && sub !== 'ensure') throw new Error(USAGE);
const bundleId = need(config.apple?.bundleId, 'apple.bundleId');
const s: AppleSigning = config.apple?.signing ?? {};
const certType: CertType = s.certificateType ?? 'DISTRIBUTION';
const profileType: ProfileType = s.profileType ?? 'IOS_APP_STORE';
const dry = a.has('dry');
const json = a.has('json');
const c = await ascClient(root, bundleId, config.apple?.appId);
// --- read everything first (read-only)
const ids = [bundleId, ...(s.extraBundleIds ?? [])];
const bundles = new Map<string, J | null>();
for (const id of ids) bundles.set(id, await findBundleId(c, id));
const main = bundles.get(bundleId);
const capPlan = main ? planCapabilities(main.id, main.capabilities ?? [], capabilitySpecs(s)) : { create: [], present: [], extra: [] };
const certs: ApiCert[] = await c.all(`/v1/certificates?filter[certificateType]=${certType}&limit=200`);
const keys = localKeys(root);
const identities = keychainIdentities();
const hasKey = (x: ApiCert): boolean => {
const content = x.attributes.certificateContent;
if (!content) return false;
const spki = certSpki(content);
return (!!spki && keys.has(spki)) || identities.has(certSha1(content));
};
const choice = pickCertificate(certs, certType, hasKey);
const profiles = new Map<string, { list: ApiProfile[]; plan: ReturnType<typeof planProfile> | null }>();
for (const id of ids) {
const b = bundles.get(id);
if (!b) { profiles.set(id, { list: [], plan: null }); continue; }
const list = await profilesOf(c, b.id, profileType);
profiles.set(id, { list, plan: choice.cert ? planProfile(list, { bundleId: id, bundleIdId: b.id, certId: choice.cert.id, type: profileType }) : null });
}
const state: SigningState = {
bundleId, teamId: s.teamId ?? main?.attributes?.seedId ?? null, registered: !!main,
capabilities: { present: capPlan.present, missing: capabilitySpecs(s).filter(w => !capPlan.present.includes(w.type)).map(w => w.type), extra: capPlan.extra },
certificate: { type: certType, chosen: choice.cert?.attributes.name ?? choice.cert?.attributes.displayName ?? null, why: choice.why,
onTeam: certs.filter(x => Date.parse(x.attributes.expirationDate ?? '') > Date.now()).length, withKey: choice.usable.length, limit: CERT_LIMIT[certType] ?? null },
profiles: ids.map(id => {
const p = profiles.get(id)!;
if (!bundles.get(id)) return { bundleId: id, name: null, uuid: null, state: 'bundle id not registered', installed: false, why: 'register it first (storebound apple bundle for the app; extensions in Certificates, Identifiers & Profiles)' };
const r = p.plan?.reuse;
return { bundleId: id, name: r?.attributes.name ?? null, uuid: r?.attributes.uuid ?? null, state: r ? 'ACTIVE' : 'needs a new profile',
installed: installedAt(r?.attributes.uuid).length > 0, why: p.plan?.why ?? 'waits for a usable certificate' };
}),
};
if (sub === 'status') {
if (json) { printJson(state); return; }
log(TAG, `${bundleId}: ${main ? `registered, team ${state.teamId ?? '?'}` : 'NOT registered (storebound apple bundle)'}`);
log(TAG, `capabilities: ${state.capabilities.present.join(', ') || 'none configured'}${state.capabilities.missing.length ? `; missing ${state.capabilities.missing.join(', ')}` : ''}${state.capabilities.extra.length ? `; also on the bundle id: ${state.capabilities.extra.join(', ')}` : ''}`);
log(TAG, `certificate ${certType}: ${choice.why} (${state.certificate.onTeam} valid on the team${state.certificate.limit ? `, limit ${state.certificate.limit}` : ''})`);
for (const x of choice.expiring) warn(TAG, `${x.attributes.name ?? x.id} expires ${x.attributes.expirationDate?.slice(0, 10)}: make a new one soon (storebound apple signing ensure)`);
console.log(textTable(['bundle id', 'profile', 'state', 'installed', ''], state.profiles.map(p => [p.bundleId, p.name ?? '', p.state, p.installed ? 'yes' : 'no', p.why])));
done(TAG, 'status read');
return;
}
// --- ensure: plan, show, ask once, then write
if (!main) throw new Error(`bundle id ${bundleId} is not registered: storebound apple bundle --dry, then without --dry`);
const missingExtra = ids.filter(id => !bundles.get(id));
if (missingExtra.length) throw new Error(`not registered: ${missingExtra.join(', ')} (register extension bundle ids in Certificates, Identifiers & Profiles first)`);
const needCert = !choice.cert;
const plan: string[] = [
...capPlan.create.map(r => describeReq(r)),
...(needCert ? [describeReq(certificateReq(certType, '<CSR of a new RSA 2048 key>'))] : []),
...ids.flatMap(id => {
const p = profiles.get(id)!.plan;
return !p || p.create ? [`POST /v1/profiles {name=..., profileType="${profileType}"} # ${id}: ${p?.why ?? 'with the new certificate'}`] : [];
}),
];
if (needCert && state.certificate.limit && state.certificate.onTeam >= state.certificate.limit)
warn(TAG, `the team already has ${state.certificate.onTeam} valid ${certType} certificates (limit ${state.certificate.limit}): Apple will refuse a new one until one is revoked (owner decision, developer.apple.com > Certificates)`);
if (json && dry) { printJson({ ...state, plan }); return; }
for (const line of plan) log(TAG, `${dry ? 'would ' : ''}${line}`);
if (!plan.length) log(TAG, 'nothing to create on App Store Connect');
if (dry) {
for (const p of state.profiles) if (p.uuid && !p.installed && !a.has('no-install')) log(TAG, `would install profile ${p.name} (${p.uuid}) for Xcode`);
done(TAG, `signing checked (dry run): ${plan.length} write(s)`);
return;
}
if (plan.length && !(await confirm(ctx, `Create ${plan.length} item(s) on the Apple Developer team (${[capPlan.create.length && `${capPlan.create.length} capabilities`, needCert && `a ${certType} certificate`, plan.length - capPlan.create.length - (needCert ? 1 : 0) && 'provisioning profiles'].filter(Boolean).join(', ')})?`))) return;
await execute(c.asc, capPlan.create, { dry: false, tag: TAG });
let cert = choice.cert;
if (needCert) {
const dir = signingDir(root);
mkdirSync(dir, { recursive: true, mode: 0o700 });
const { key } = newSigningKey();
const pending = join(dir, `pending-${Date.now()}.key`);
writeFileSync(pending, key.export({ type: 'pkcs1', format: 'pem' }).toString(), { mode: 0o600 });
chmodSync(pending, 0o600);
let created: J;
try {
const csr = buildCsr(key, { commonName: `storebound ${config.app.name}`.slice(0, 64) });
created = (await c.asc('POST', '/v1/certificates', certificateReq(certType, csrContent(csr)).body)).data;
} catch (e) {
rmSync(pending, { force: true });
const why = explainCertError(e, certType);
throw new Error(why ? `${(e as Error).message}\n\n${why}` : (e as Error).message);
}
const keyFile = join(dir, `${created.id}.key`), cerFile = join(dir, `${created.id}.cer`);
renameSync(pending, keyFile);
writeFileSync(cerFile, Buffer.from(created.attributes.certificateContent, 'base64'), { mode: 0o600 });
log(TAG, `certificate ${created.attributes.name ?? created.id} created (expires ${String(created.attributes.expirationDate).slice(0, 10)}); key and certificate in .storebound/signing/ (gitignored, back them up)`);
if (a.has('keychain')) keychainImport(keyFile, cerFile, a.get('keychain') === 'true' ? null : a.get('keychain')!);
else warn(TAG, 'xcodebuild signs with identities from the keychain: re-run with --keychain to import it there (or import the .key + .cer yourself)');
cert = created;
}
for (const id of ids) {
const b = bundles.get(id)!;
const list = profiles.get(id)!.list;
const p = planProfile(list, { bundleId: id, bundleIdId: b.id, certId: cert!.id, type: profileType });
let prof: ApiProfile;
if (p.create) {
const r = (await c.asc('POST', p.create.path, p.create.body)).data;
prof = { id: r.id, attributes: r.attributes };
log(TAG, `${id}: profile "${prof.attributes.name}" created (${prof.attributes.uuid})`);
} else {
prof = p.reuse!;
if (!prof.attributes.profileContent) prof = { ...prof, attributes: (await c.asc('GET', `/v1/profiles/${prof.id}`)).data.attributes };
log(TAG, `${id}: ${p.why}`);
}
if (!a.has('no-install')) for (const f of install(prof)) log(TAG, `${id}: installed ${f.replace(homedir(), '~')}`);
}
if (json) printJson({ ...state, plan, done: true });
done(TAG, 'signing ready (storebound apple build --dry shows the ExportOptions.plist it will use)');
}

163
cli/apple/upload.ts Normal file
View file

@ -0,0 +1,163 @@
// Upload an IPA to App Store Connect and wait until Apple has processed the build.
// storebound apple upload [<app.ipa>] [--via api|altool] [--no-wait] [--timeout 60m] [--dry] [--yes] [--json]
// Default IPA: the newest in <apple.build.out or build/ios>/export. The bundle id, version and build number come from
// the IPA's Info.plist; the upload is refused when that build number is already on App Store Connect for the app
// (`apple next-build` / `apple build` pick a free one).
// --via api (default): the App Store Connect API build upload (Build Uploads, API 4.1+): POST /v1/buildUploads,
// reserve /v1/buildUploadFiles, PUT the parts, commit with the MD5, then poll the upload state. Same API key, no
// Xcode needed, works on any OS.
// --via altool: `xcrun altool --upload-package` with the API key (Xcode's own uploader; macOS).
// Both are listed by Apple (App Store Connect Help > Upload builds); neither is deprecated. Then the build is polled
// until processingState is VALID (exit 0), INVALID / FAILED (exit 1) or the timeout (exit 7).
// An upload is a write: --dry shows the plan; a real run asks first (--yes in scripts).
import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from 'node:fs';
import { basename, join, relative } from 'node:path';
import { ascKeyFile } from '../lib/credentials';
import type { Ctx } from '../lib/ctx';
import { confirm, need } from '../lib/ctx';
import { done, log, printJson, warn } from '../lib/log';
import { compareBuild, nextBuildNumber, nextPollDelay, parseDuration, WAIT_EXIT } from '../lib/release';
import { altoolArgs, BUILD_DONE, buildUploadReqs, ipaInfo, showCmd, UPLOAD_DONE, uploadProblems } from '../lib/xcode';
import { type Asc, ascClient, type J } from './asc';
import { describeReq } from './jsonapi';
const TAG = 'upload';
function md5File(path: string): string {
const h = new Bun.CryptoHasher('md5');
const fd = openSync(path, 'r');
try {
const buf = Buffer.alloc(8 * 1048576);
for (let n; (n = readSync(fd, buf, 0, buf.length, null)) > 0;) h.update(buf.subarray(0, n));
} finally { closeSync(fd); }
return h.digest('hex');
}
function slice(path: string, offset: number, length: number): Buffer {
const fd = openSync(path, 'r');
try { const b = Buffer.alloc(length); readSync(fd, b, 0, length, offset); return b; } finally { closeSync(fd); }
}
async function apiUpload(c: Asc, appId: string, ipa: string, info: ReturnType<typeof ipaInfo>, deadline: number): Promise<void> {
const size = statSync(ipa).size;
const reqs = buildUploadReqs(appId, info, basename(ipa), size);
const up = (await c.asc('POST', reqs.upload.path, reqs.upload.body)).data;
log(TAG, `build upload ${up.id} created`);
const file = (await c.asc('POST', reqs.file(up.id).path, reqs.file(up.id).body)).data;
const ops = (file.attributes.uploadOperations ?? []) as J[];
log(TAG, `uploading ${(size / 1048576).toFixed(1)} MB in ${ops.length} part(s)`);
let sent = 0;
for (const [i, op] of ops.entries()) {
const headers: Record<string, string> = {};
for (const h of op.requestHeaders ?? []) headers[h.name] = h.value;
for (let attempt = 1; ; attempt++) {
const r = await fetch(op.url, { method: op.method, headers, body: new Uint8Array(slice(ipa, op.offset, op.length)) });
if (r.ok) break;
if (attempt >= 4 || (r.status < 500 && r.status !== 429)) throw new Error(`part ${i + 1}/${ops.length} -> ${r.status}`);
await Bun.sleep(2000 * attempt);
}
sent += op.length;
if ((i + 1) % 10 === 0 || i === ops.length - 1) log(TAG, `${i + 1}/${ops.length} parts (${Math.round((sent / size) * 100)}%)`);
}
const commit = reqs.commit(file.id, md5File(ipa));
await c.asc('PATCH', commit.path, commit.body);
log(TAG, 'file committed; waiting for App Store Connect to accept the upload');
for (let delay: number | null = null; ;) {
const u = (await c.asc('GET', `/v1/buildUploads/${up.id}`)).data;
const st = u.attributes?.state ?? {};
const p = uploadProblems(st);
for (const w of p.warnings) warn(TAG, w);
if (UPLOAD_DONE.has(st.state)) {
if (st.state === 'FAILED') throw new Error(`upload rejected: ${p.errors.join('; ') || 'no reason given'}`);
log(TAG, 'upload accepted');
return;
}
if (Date.now() > deadline) throw Object.assign(new Error(`upload still ${st.state ?? 'pending'} at the timeout`), { exit: WAIT_EXIT.timeout });
delay = nextPollDelay(delay, { first: 15_000, max: 60_000 });
log(TAG, `upload ${st.state ?? 'pending'}, next check in ${Math.round(delay / 1000)} s`);
await Bun.sleep(delay);
}
}
async function altoolUpload(root: string, ipa: string): Promise<void> {
if (process.platform !== 'darwin' || !Bun.which('xcrun')) throw new Error('--via altool needs macOS with Xcode; use --via api elsewhere');
const k = ascKeyFile(root);
try {
const argv = altoolArgs(ipa, k);
log(TAG, `$ ${showCmd(argv, k)}`);
const r = Bun.spawnSync(argv, { stdout: 'pipe', stderr: 'pipe' });
const outText = (r.stdout.toString() + '\n' + r.stderr.toString()).trim();
if (r.exitCode !== 0) throw new Error(`altool failed (exit ${r.exitCode}): ${outText.split('\n').filter(l => /error|fail/i.test(l)).slice(0, 8).join('\n') || outText.slice(-800)}`);
const id = /"?delivery-uuid"?\s*[:=]\s*"?([0-9a-f-]{36})/i.exec(outText)?.[1];
log(TAG, `altool: upload done${id ? ` (delivery ${id})` : ''}`);
} finally { k.cleanup(); }
}
/** Polls the build until processed. */
async function waitProcessing(c: Asc, appId: string, info: ReturnType<typeof ipaInfo>, deadline: number): Promise<string> {
const q = new URLSearchParams({ 'filter[app]': appId, 'filter[version]': info.build, 'filter[preReleaseVersion.version]': info.version, 'filter[preReleaseVersion.platform]': 'IOS', limit: '5' });
for (let delay: number | null = null; ;) {
const b = ((await c.asc('GET', `/v1/builds?${q}`)).data as J[])[0];
const state = b?.attributes?.processingState ?? 'NOT_YET_VISIBLE';
if (BUILD_DONE.has(state)) return state;
if (Date.now() > deadline) return 'TIMEOUT';
delay = nextPollDelay(delay, { first: 30_000, max: 120_000 });
log(TAG, `build ${info.build}: ${state}, next check in ${Math.round(delay / 1000)} s`);
await Bun.sleep(delay);
}
}
export async function run(ctx: Ctx): Promise<void> {
const { config, root, resolve } = ctx.loaded;
const a = ctx.args;
const bundleId = need(config.apple?.bundleId, 'apple.bundleId');
const via = a.str('via', 'api');
if (via !== 'api' && via !== 'altool') throw new Error('--via api | altool');
let ipa = a._.find(x => x.endsWith('.ipa'));
if (!ipa) {
const dir = join(resolve(config.apple?.build?.out ?? 'build/ios'), 'export');
const found = existsSync(dir) ? readdirSync(dir).filter(f => f.endsWith('.ipa')).map(f => join(dir, f)).sort((x, y) => statSync(y).mtimeMs - statSync(x).mtimeMs) : [];
if (!found[0]) throw new Error(`usage: storebound apple upload <app.ipa> (nothing in ${relative(root, dir)}; storebound apple build makes one)`);
ipa = found[0];
} else ipa = resolve(ipa);
const info = ipaInfo(ipa);
if (info.bundleId !== bundleId) throw new Error(`${relative(root, ipa)} is ${info.bundleId}, the config says ${bundleId}`);
const size = statSync(ipa).size;
const dry = a.has('dry');
const json = a.has('json');
const wait = !a.has('no-wait');
const timeout = parseDuration(a.str('timeout', '60m'));
const c = await ascClient(root, bundleId, config.apple?.appId);
const appId = await c.app();
const builds = await c.all(`/v1/builds?filter[app]=${appId}&limit=200&fields[builds]=version`);
const numbers = builds.map(b => String(b.attributes.version));
const next = nextBuildNumber(numbers);
if (numbers.includes(info.build)) throw new Error(`build ${info.build} is already on App Store Connect: rebuild with --build-number ${next} (storebound apple build)`);
if (numbers.length && compareBuild(info.build, next) < 0) warn(TAG, `build ${info.build} is lower than the highest uploaded one (next free: ${next}); Apple accepts it only if this version train has no higher build`);
const reqs = buildUploadReqs(appId, info, basename(ipa), size);
const plan = via === 'api'
? [describeReq(reqs.upload), describeReq(reqs.file('<upload id>')), `PUT the file parts to the upload URLs Apple returns`, describeReq(reqs.commit('<file id>', '<md5>')), 'GET /v1/buildUploads/<id> until COMPLETE']
: [showCmd(altoolArgs(ipa, { keyPath: '$ASC_P8', keyId: '$ASC_KEY_ID', issuerId: '$ASC_ISSUER_ID' }), null)];
if (wait) plan.push(`GET /v1/builds?filter[version]=${info.build} until processingState is VALID (timeout ${a.str('timeout', '60m')})`);
const summary = { ipa: relative(root, ipa), bundleId: info.bundleId, version: info.version, build: info.build, sizeMB: Math.round(size / 104857.6) / 10, via, plan };
if (dry) {
if (json) { printJson(summary); return; }
log(TAG, `${summary.ipa}: ${info.bundleId} ${info.version} (${info.build}), ${summary.sizeMB} MB, build number free`);
for (const p of plan) log(TAG, `would ${p}`);
done(TAG, 'upload planned (dry run)');
return;
}
if (!(await confirm(ctx, `Upload ${info.bundleId} ${info.version} (${info.build}) to App Store Connect? It shows up in TestFlight once processed.`))) return;
const deadline = Date.now() + timeout;
if (via === 'api') {
try { await apiUpload(c, appId, ipa, info, deadline); } catch (e) { if ((e as { exit?: number }).exit) { warn(TAG, (e as Error).message); process.exit((e as { exit: number }).exit); } throw e; }
} else await altoolUpload(root, ipa);
if (!wait) { if (json) printJson({ ...summary, uploaded: true }); done(TAG, `build ${info.build} uploaded; storebound apple status shows when it is VALID`); return; }
const state = await waitProcessing(c, appId, info, deadline);
if (json) printJson({ ...summary, uploaded: true, processingState: state });
if (state === 'VALID') { done(TAG, `build ${info.build} is VALID. Next: storebound apple encryption --build ${info.build}, apple testflight distribute --build ${info.build} --group <name> --dry`); return; }
if (state === 'TIMEOUT') { warn(TAG, `build ${info.build} not processed after ${a.str('timeout', '60m')}; check again with storebound apple status`); process.exit(WAIT_EXIT.timeout); }
warn(TAG, `build ${info.build} is ${state}: Apple emails the reason (ITMS-xxxxx) to the team; fix it and upload a new build number`);
process.exit(1);
}

View file

@ -33,6 +33,7 @@ const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
'catalog': [() => import('./catalog'), 'diff: cross-store parity of products + subscriptions (missing / extra / mismatched, prices per region, offers); read-only, exit 1 on mismatches'], 'catalog': [() => import('./catalog'), 'diff: cross-store parity of products + subscriptions (missing / extra / mismatched, prices per region, offers); read-only, exit 1 on mismatches'],
'prices': [() => import('./prices'), 'export | import a CSV of product x store x region prices (diff first, asks before writing; Apple future-dated changes)'], 'prices': [() => import('./prices'), 'export | import a CSV of product x store x region prices (diff first, asks before writing; Apple future-dated changes)'],
'reviews': [() => import('./reviews'), 'list | draft (local reply drafts in .storebound/replies) | send (approved drafts only, asks first)'], 'reviews': [() => import('./reviews'), 'list | draft (local reply drafts in .storebound/replies) | send (approved drafts only, asks first)'],
'originality': [() => import('./originality'), 'Guideline 4.3 check vs your other apps (--against <folders>): listing text, name, icon and screenshot perceptual hashes, project structure; scores, flags, suggestions; offline, exit 1 on a near-duplicate'],
'whats-new': [() => import('./whats-new'), 'draft user-facing release notes from git log into the listing files (--since <tag>)'], 'whats-new': [() => import('./whats-new'), 'draft user-facing release notes from git log into the listing files (--since <tag>)'],
'play products': [() => import('./play/products'), 'one-time products: create / update, regional prices, activate'], 'play products': [() => import('./play/products'), 'one-time products: create / update, regional prices, activate'],
'play subscriptions': [() => import('./play/subscriptions'), 'auto-renewable subscriptions: listings, base plan, regional prices, intro offer, activate (--csv prices sheet; asks first)'], 'play subscriptions': [() => import('./play/subscriptions'), 'auto-renewable subscriptions: listings, base plan, regional prices, intro offer, activate (--csv prices sheet; asks first)'],
@ -40,6 +41,8 @@ const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
'play images': [() => import('./play/images'), 'icon, feature graphic, phone / 7" / 10" screenshots per language; --variant <id>'], 'play images': [() => import('./play/images'), 'icon, feature graphic, phone / 7" / 10" screenshots per language; --variant <id>'],
'play data-safety': [() => import('./play/data-safety'), 'Data safety form (CSV import through the API)'], 'play data-safety': [() => import('./play/data-safety'), 'Data safety form (CSV import through the API)'],
'play release': [() => import('./play/release'), 'upload an AAB and put it on tracks with release notes'], 'play release': [() => import('./play/release'), 'upload an AAB and put it on tracks with release notes'],
'play build': [() => import('./play/build'), 'gradle bundleRelease (Flutter: flutter build appbundle) with the next free versionCode and the upload key from env / .storebound; --dry'],
'play upload': [() => import('./play/upload'), 'upload an AAB to a testing track (--track internal|alpha|beta), versionCode checked first; --dry read-only, asks first'],
'play status': [() => import('./play/status'), 'tracks, listings, products (read-only)'], 'play status': [() => import('./play/status'), 'tracks, listings, products (read-only)'],
'play rollout': [() => import('./play/rollout'), 'staged rollout: --fraction x | --halt | --resume | --complete (asks first)'], 'play rollout': [() => import('./play/rollout'), 'staged rollout: --fraction x | --halt | --resume | --complete (asks first)'],
'play next-version-code': [() => import('./play/next-version-code'), 'next free versionCode (prints the number)'], 'play next-version-code': [() => import('./play/next-version-code'), 'next free versionCode (prints the number)'],
@ -54,6 +57,9 @@ const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
'apple status': [() => import('./apple/status'), 'versions, builds, IAPs, review submissions (--wait-review, --cancel-submission <id>)'], 'apple status': [() => import('./apple/status'), 'versions, builds, IAPs, review submissions (--wait-review, --cancel-submission <id>)'],
'apple previews': [() => import('./apple/previews'), 'app preview videos per locale (MD5-idempotent, poster frame time code); --dry'], 'apple previews': [() => import('./apple/previews'), 'app preview videos per locale (MD5-idempotent, poster frame time code); --dry'],
'apple release': [() => import('./apple/release'), 'phased release on|pause|resume|complete, --manual-release (asks first)'], 'apple release': [() => import('./apple/release'), 'phased release on|pause|resume|complete, --manual-release (asks first)'],
'apple signing': [() => import('./apple/signing'), 'status | ensure: bundle id capabilities, distribution certificate (key kept in .storebound/signing), App Store profiles installed for Xcode; --dry, asks first'],
'apple build': [() => import('./apple/build'), 'xcodebuild archive + exportArchive (ExportOptions.plist generated, next build number, API key signing); Capacitor, React Native, Flutter, Unity; --dry'],
'apple upload': [() => import('./apple/upload'), 'upload an IPA (App Store Connect API build upload, or --via altool), build number checked, waits for processing; --dry, asks first'],
'apple next-build': [() => import('./apple/next-build'), 'next safe build number (prints the number)'], 'apple next-build': [() => import('./apple/next-build'), 'next safe build number (prints the number)'],
'apple encryption': [() => import('./apple/encryption'), 'export compliance answer for builds, from the config'], 'apple encryption': [() => import('./apple/encryption'), 'export compliance answer for builds, from the config'],
'apple ppo': [() => import('./apple/ppo'), 'Product Page Optimization: status | create --variant b | upload --variant b | start | stop (asks first)'], 'apple ppo': [() => import('./apple/ppo'), 'Product Page Optimization: status | create --variant b | upload --variant b | start | stop (asks first)'],
@ -78,7 +84,7 @@ ${Object.entries(PLAIN).map(([k, [, d]]) => ` ${k.padEnd(25)} ${d}`).join('\n')
${Object.entries(COMMANDS).map(([k, [, d]]) => ` ${k.padEnd(25)} ${d}`).join('\n')} ${Object.entries(COMMANDS).map(([k, [, d]]) => ` ${k.padEnd(25)} ${d}`).join('\n')}
common options: --config <path> --dry (no writes) --only <ids> --yes (skip confirmations) --account <profile> (credential profile) common options: --config <path> --dry (no writes) --only <ids> --yes (skip confirmations) --account <profile> (credential profile)
credentials: PLAY_SERVICE_ACCOUNT, ASC_KEY_ID, ASC_ISSUER_ID, ASC_P8, REVIEW_DEMO_USER / REVIEW_DEMO_PASSWORD (env or .storebound/credentials.json); credentials: PLAY_SERVICE_ACCOUNT, ASC_KEY_ID, ASC_ISSUER_ID, ASC_P8, ANDROID_KEYSTORE(_PASSWORD) / ANDROID_KEY_ALIAS / ANDROID_KEY_PASSWORD, REVIEW_DEMO_USER / REVIEW_DEMO_PASSWORD (env or .storebound/credentials.json);
profiles for many accounts: ~/.storebound/credentials/<profile>.json (same names), picked with --account <profile> profiles for many accounts: ~/.storebound/credentials/<profile>.json (same names), picked with --account <profile>
docs: README.md and the skills/ folder of the toolchain`); docs: README.md and the skills/ folder of the toolchain`);
} }

View file

@ -5,6 +5,10 @@ import { dirname, isAbsolute, join, resolve } from 'node:path';
import { validateCapture, validateRecord } from '../shots/devices'; import { validateCapture, validateRecord } from '../shots/devices';
import { validateSubscriptions } from './subscriptions'; import { validateSubscriptions } from './subscriptions';
import { type TfConfig, validateTestflight } from './testflight'; import { type TfConfig, validateTestflight } from './testflight';
import { type AppleSigning, validateSigning } from './signing';
import { type AppleBuildConfig, validateAppleBuild } from './xcode';
import { type PlayBuildConfig, validatePlayBuild } from './gradle';
import { type OriginalityConfig, validateOriginality } from './originality';
/** consumable / non_consumable: both stores. non_renewing: Apple NON_RENEWING_SUBSCRIPTION (access for a fixed time, /** consumable / non_consumable: both stores. non_renewing: Apple NON_RENEWING_SUBSCRIPTION (access for a fixed time,
* you track the expiry); Google Play has no such type, so it becomes a one-time product your app consumes when the * you track the expiry); Google Play has no such type, so it becomes a one-time product your app consumes when the
@ -444,6 +448,8 @@ export interface ShipConfig {
/** Cloud Storage bucket of the Play Console report exports, e.g. "pubsite_prod_rev_<number>" (Play Console > /** Cloud Storage bucket of the Play Console report exports, e.g. "pubsite_prod_rev_<number>" (Play Console >
* Download reports > Statistics > Copy Cloud Storage URI). Used by `storebound analytics snapshot`. */ * Download reports > Statistics > Copy Cloud Storage URI). Used by `storebound analytics snapshot`. */
reportsBucket?: string; reportsBucket?: string;
/** `storebound play build`: Gradle project folder, module, flavor (found automatically when unset). */
build?: PlayBuildConfig;
}; };
apple?: { apple?: {
bundleId: string; appId?: string; primaryLocale?: string; listing?: string; info?: AppleAppInfo; reviewShots?: string; bundleId: string; appId?: string; primaryLocale?: string; listing?: string; info?: AppleAppInfo; reviewShots?: string;
@ -466,6 +472,10 @@ export interface ShipConfig {
iphoneMedium?: boolean; iphoneMedium?: boolean;
/** TestFlight beta groups, the tester CSV (in .storebound/) and Test Information (`storebound apple testflight`). */ /** TestFlight beta groups, the tester CSV (in .storebound/) and Test Information (`storebound apple testflight`). */
testflight?: TfConfig; testflight?: TfConfig;
/** Certificates, profiles and capabilities through the API (`storebound apple signing`), signing style of `apple build`. */
signing?: AppleSigning;
/** `storebound apple build`: workspace / project, scheme, configuration, output folder (found automatically when unset). */
build?: AppleBuildConfig;
}; };
products?: Product[]; products?: Product[];
/** Auto-renewable subscriptions (`storebound apple subscriptions`, `storebound play subscriptions`). */ /** Auto-renewable subscriptions (`storebound apple subscriptions`, `storebound play subscriptions`). */
@ -489,6 +499,9 @@ export interface ShipConfig {
renders?: string; renders?: string;
shots?: ShotsConfig; shots?: ShotsConfig;
icons?: IconsConfig; icons?: IconsConfig;
/** `storebound originality`: the owner's other apps to compare with (folders with a storebound.config.ts, or a
* workspace folder holding several), and the score above which a pair is flagged. */
originality?: OriginalityConfig;
} }
/** Platforms of the app (app identity): app.platforms, else from the store sections. */ /** Platforms of the app (app identity): app.platforms, else from the store sections. */
@ -552,6 +565,7 @@ export function validateConfig(c: unknown): string[] {
if (cfg.play && !ID_RE.test(cfg.play.packageName ?? '')) e.push('play.packageName: not a package name (com.example.game)'); if (cfg.play && !ID_RE.test(cfg.play.packageName ?? '')) e.push('play.packageName: not a package name (com.example.game)');
if (cfg.play?.video && !/^https:\/\/(www\.youtube\.com\/watch\?v=[\w-]{6,}|youtu\.be\/[\w-]{6,})$/.test(cfg.play.video)) if (cfg.play?.video && !/^https:\/\/(www\.youtube\.com\/watch\?v=[\w-]{6,}|youtu\.be\/[\w-]{6,})$/.test(cfg.play.video))
e.push('play.video: a plain YouTube video URL (https://www.youtube.com/watch?v=... or https://youtu.be/...), no playlist, channel or extra parameters'); e.push('play.video: a plain YouTube video URL (https://www.youtube.com/watch?v=... or https://youtu.be/...), no playlist, channel or extra parameters');
e.push(...validatePlayBuild(cfg.play?.build), ...validateOriginality(cfg.originality));
if (cfg.play?.reportsBucket && !/^(gs:\/\/)?pubsite_prod(_rev)?_\d+\/?$/.test(cfg.play.reportsBucket)) if (cfg.play?.reportsBucket && !/^(gs:\/\/)?pubsite_prod(_rev)?_\d+\/?$/.test(cfg.play.reportsBucket))
e.push('play.reportsBucket: the Play reports bucket, e.g. "pubsite_prod_rev_<number>" (Play Console > Download reports > Copy Cloud Storage URI)'); e.push('play.reportsBucket: the Play reports bucket, e.g. "pubsite_prod_rev_<number>" (Play Console > Download reports > Copy Cloud Storage URI)');
if (cfg.apple) { if (cfg.apple) {
@ -561,6 +575,7 @@ export function validateConfig(c: unknown): string[] {
if (enc !== undefined && typeof enc !== 'boolean') e.push('apple.usesNonExemptEncryption: true | false'); if (enc !== undefined && typeof enc !== 'boolean') e.push('apple.usesNonExemptEncryption: true | false');
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'); 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)); e.push(...validateTestflight(cfg.apple.testflight));
e.push(...validateSigning(cfg.apple.signing), ...validateAppleBuild(cfg.apple.build));
} }
if (cfg.appPrivacy) { if (cfg.appPrivacy) {
if (cfg.appPrivacy.tracking !== undefined && typeof cfg.appPrivacy.tracking !== 'boolean') e.push('appPrivacy.tracking: true | false'); if (cfg.appPrivacy.tracking !== undefined && typeof cfg.appPrivacy.tracking !== 'boolean') e.push('appPrivacy.tracking: true | false');

View file

@ -11,8 +11,8 @@
// ~/.storebound/credentials/<name>.json (same four names; relative paths are relative to that file; folder: // ~/.storebound/credentials/<name>.json (same four names; relative paths are relative to that file; folder:
// STOREBOUND_CREDENTIALS_DIR) or env STOREBOUND_PROFILE_<NAME>_<KEY> (NAME upper case, other characters as _). // STOREBOUND_CREDENTIALS_DIR) or env STOREBOUND_PROFILE_<NAME>_<KEY> (NAME upper case, other characters as _).
// Many studios / store accounts from one machine: one profile per account; storebound.workspace.json names them. // Many studios / store accounts from one machine: one profile per account; storebound.workspace.json names them.
import { existsSync, readFileSync } from 'node:fs'; import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os'; import { homedir, tmpdir } from 'node:os';
import { isAbsolute, join, resolve } from 'node:path'; import { isAbsolute, join, resolve } from 'node:path';
export interface ServiceAccount { client_email: string; private_key: string; token_uri?: string } export interface ServiceAccount { client_email: string; private_key: string; token_uri?: string }
@ -128,3 +128,31 @@ export const maskUser = (u: string): string => {
return at > 0 ? `${u[0]}***${u.slice(at)}` : `${u[0] ?? ''}***`; return at > 0 ? `${u[0]}***${u.slice(at)}` : `${u[0] ?? ''}***`;
}; };
export const maskSecret = (s: string): string => (s ? '********' : '(empty)'); export const maskSecret = (s: string): string => (s ? '********' : '(empty)');
/** The App Store Connect key as a file, for tools that want a path (xcodebuild -authenticationKeyPath, altool).
* A path in ASC_P8 (or the usual ~/.appstoreconnect location) is used as is; inline PEM content goes to a private
* temporary folder (0700 / 0600) that `cleanup` removes. Commands show the path as $ASC_P8. */
export function ascKeyFile(root: string): { keyPath: string; keyId: string; issuerId: string; cleanup: () => void } {
const k = ascKey(root);
const raw = value(root, 'ASC_P8') ?? join(homedir(), '.appstoreconnect/private_keys', `AuthKey_${k.keyId}.p8`);
if (!/BEGIN PRIVATE KEY/.test(raw)) return { keyPath: raw.replace(/^~(?=\/)/, homedir()), keyId: k.keyId, issuerId: k.issuerId, cleanup: () => {} };
const dir = mkdtempSync(join(tmpdir(), 'storebound-key-'));
chmodSync(dir, 0o700);
const keyPath = join(dir, `AuthKey_${k.keyId}.p8`);
writeFileSync(keyPath, k.pem, { mode: 0o600 });
return { keyPath, keyId: k.keyId, issuerId: k.issuerId, cleanup: () => rmSync(dir, { recursive: true, force: true }) };
}
export interface AndroidSigning { storeFile: string; storePassword: string; keyAlias: string; keyPassword: string }
/** Android upload key for `play build` (env or .storebound/credentials.json): ANDROID_KEYSTORE (path to the .jks /
* .keystore), ANDROID_KEYSTORE_PASSWORD, ANDROID_KEY_ALIAS, ANDROID_KEY_PASSWORD (default: the keystore password).
* null when no keystore is set (the project's own signingConfig signs then, e.g. Flutter's key.properties). */
export function androidSigning(root: string): AndroidSigning | null {
const storeFile = value(root, 'ANDROID_KEYSTORE');
if (!storeFile) return null;
const storePassword = value(root, 'ANDROID_KEYSTORE_PASSWORD'), keyAlias = value(root, 'ANDROID_KEY_ALIAS');
if (!storePassword || !keyAlias) throw new Error('ANDROID_KEYSTORE is set but ANDROID_KEYSTORE_PASSWORD / ANDROID_KEY_ALIAS are not (env or .storebound/credentials.json)');
const abs = storeFile.replace(/^~(?=\/)/, homedir());
return { storeFile: abs.startsWith('/') ? abs : join(root, abs), storePassword, keyAlias, keyPassword: value(root, 'ANDROID_KEY_PASSWORD') ?? storePassword };
}

57
cli/lib/csr.ts Normal file
View file

@ -0,0 +1,57 @@
// A certificate signing request (PKCS #10, RFC 2986) built with node:crypto and a minimal DER encoder: no openssl,
// no Keychain Access. The private key is generated here and only ever written to a 0600 file in .storebound/signing/
// (and, when asked, imported into a keychain); the CSR carries only the public key.
import { createPrivateKey, createPublicKey, generateKeyPairSync, type KeyObject, sign } from 'node:crypto';
function derLen(n: number): Buffer {
if (n < 0x80) return Buffer.from([n]);
const bytes: number[] = [];
for (let v = n; v > 0; v = Math.floor(v / 256)) bytes.unshift(v & 255);
return Buffer.from([0x80 | bytes.length, ...bytes]);
}
export const der = (tag: number, ...parts: Buffer[]): Buffer => { const body = Buffer.concat(parts); return Buffer.concat([Buffer.from([tag]), derLen(body.length), body]); };
const seq = (...p: Buffer[]) => der(0x30, ...p);
const set = (...p: Buffer[]) => der(0x31, ...p);
/** DER object identifier from its arcs, e.g. [2, 5, 4, 3] (commonName). */
export function oid(arcs: number[]): Buffer {
const [a, b, ...rest] = arcs as [number, number, ...number[]];
const out = [40 * a + b];
for (const n of rest) {
const groups: number[] = [];
for (let v = n; ; v = Math.floor(v / 128)) { groups.unshift(v & 127); if (v < 128) break; }
out.push(...groups.map((g, i) => (i < groups.length - 1 ? g | 128 : g)));
}
return der(0x06, Buffer.from(out));
}
const OID = { commonName: [2, 5, 4, 3], countryName: [2, 5, 4, 6], emailAddress: [1, 2, 840, 113549, 1, 9, 1], sha256WithRSA: [1, 2, 840, 113549, 1, 1, 11] };
export interface CsrSubject { commonName: string; country?: string; email?: string }
/** PEM CSR for the key. Subject: CN (and C / emailAddress when given; Apple ignores them for API-made certificates). */
export function buildCsr(key: KeyObject, subject: CsrSubject): string {
const rdn = (o: number[], value: Buffer) => set(seq(oid(o), value));
const name = seq(
...(subject.email ? [rdn(OID.emailAddress, der(0x16, Buffer.from(subject.email, 'ascii')))] : []),
rdn(OID.commonName, der(0x0c, Buffer.from(subject.commonName, 'utf8'))),
...(subject.country ? [rdn(OID.countryName, der(0x13, Buffer.from(subject.country, 'ascii')))] : []),
);
const spki = createPublicKey(key).export({ type: 'spki', format: 'der' });
const info = seq(der(0x02, Buffer.from([0])), name, spki, der(0xa0));
const sig = sign('sha256', info, key);
const csr = seq(info, seq(oid(OID.sha256WithRSA), der(0x05)), der(0x03, Buffer.from([0]), sig));
return `-----BEGIN CERTIFICATE REQUEST-----\n${csr.toString('base64').match(/.{1,64}/g)!.join('\n')}\n-----END CERTIFICATE REQUEST-----\n`;
}
/** New RSA 2048 key (Apple's signing certificates use RSA 2048) as PKCS #8 PEM plus its KeyObject. */
export function newSigningKey(): { pem: string; key: KeyObject } {
const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
return { pem: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(), key: privateKey };
}
/** The CSR's base64 body (what the App Store Connect API takes as csrContent). */
export const csrContent = (pem: string): string => pem.replace(/-----[^-]+-----/g, '').replace(/\s+/g, '');
/** SPKI (DER, base64) of a private key PEM: matches a certificate's public key. */
export const spkiOfKey = (pem: string): string => createPublicKey(createPrivateKey(pem)).export({ type: 'spki', format: 'der' }).toString('base64');

180
cli/lib/gradle.ts Normal file
View file

@ -0,0 +1,180 @@
// Android release builds: find the Gradle project (native, Capacitor, React Native, Flutter, Unity export), the
// bundle task, the signing environment (the upload key from env / .storebound, handed to Gradle as injected
// properties through ORG_GRADLE_PROJECT_* variables, so passwords never appear on a command line), and read
// package / versionCode / versionName back from the built AAB (its manifest is protocol buffers, aapt2 format).
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
import { join, relative } from 'node:path';
import type { AndroidSigning } from './credentials';
import { zipEntries, zipRead } from './zip';
export interface PlayBuildConfig {
/** Gradle project folder (with gradlew / settings.gradle), relative to the config. Default: android/, else the root. */
dir?: string;
/** Application module. Default app (Unity export: launcher). */
module?: string;
/** Product flavor, e.g. "prod" -> bundleProdRelease. */
flavor?: string;
}
export function validatePlayBuild(b: PlayBuildConfig | undefined): string[] {
if (!b) return [];
const e: string[] = [];
if (b.module !== undefined && !/^[A-Za-z0-9_-]+(:[A-Za-z0-9_-]+)*$/.test(b.module)) e.push('play.build.module: a Gradle module name like app');
if (b.flavor !== undefined && !/^[A-Za-z][A-Za-z0-9]*$/.test(b.flavor)) e.push('play.build.flavor: a product flavor name like prod');
return e;
}
export type AndroidFramework = 'flutter' | 'capacitor' | 'react-native' | 'unity' | 'native';
export interface GradleTarget { framework: AndroidFramework; dir: string; module: string; task: string; notes: string[] }
const isGradleDir = (d: string): boolean => ['settings.gradle', 'settings.gradle.kts'].some(f => existsSync(join(d, f)));
/** Finds the Gradle project. `root` is the folder of storebound.config.ts. */
export function pickGradle(root: string, cfg: PlayBuildConfig = {}): GradleTarget {
const notes: string[] = [];
const framework: AndroidFramework = existsSync(join(root, 'pubspec.yaml')) ? 'flutter'
: ['capacitor.config.ts', 'capacitor.config.json', 'capacitor.config.js'].some(f => existsSync(join(root, f))) ? 'capacitor'
: (() => { try { const p = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')); return !!(p.dependencies?.['react-native'] ?? p.devDependencies?.['react-native']); } catch { return false; } })() ? 'react-native'
: 'native';
const dirs = cfg.dir ? [join(root, cfg.dir)] : [join(root, 'android'), root];
let dir = dirs.find(isGradleDir);
if (!dir) throw new Error(`no Gradle project (settings.gradle) in ${dirs.map(d => relative(root, d) || '.').join(' or ')}: set play.build.dir${framework === 'capacitor' ? ' (or npx cap add android)' : ''}`);
const unity = existsSync(join(dir, 'launcher')) && existsSync(join(dir, 'unityLibrary'));
const fw: AndroidFramework = unity ? 'unity' : framework;
const module = cfg.module ?? (unity ? 'launcher' : 'app');
if (!existsSync(join(dir, ...module.split(':')))) throw new Error(`module "${module}" not found in ${relative(root, dir) || '.'} (set play.build.module)`);
const flavor = cfg.flavor ? cfg.flavor[0]!.toUpperCase() + cfg.flavor.slice(1) : '';
if (fw === 'capacitor') notes.push('Capacitor: run npx cap sync android after the web build so the bundle has the current web assets');
if (fw === 'unity') notes.push('Unity: export the Gradle project from Unity (Build Settings > Android > Export Project) before each build');
if (fw === 'flutter') notes.push('Flutter: built with flutter build appbundle (build number = versionCode)');
if (!existsSync(join(dir, process.platform === 'win32' ? 'gradlew.bat' : 'gradlew'))) notes.push('no Gradle wrapper (gradlew) in the project: using gradle from PATH');
return { framework: fw, dir, module, task: `:${module}:bundle${flavor}Release`, notes };
}
/** Command line of the release bundle build. Version code / name go in as injected properties (the same ones Android
* Studio uses) and as -PversionCode / -PversionName for build files that read those. */
export function gradleArgs(t: GradleTarget, o: { versionCode?: number; versionName?: string; flavor?: string; hasWrapper: boolean }): string[] {
if (t.framework === 'flutter')
return ['flutter', 'build', 'appbundle', '--release', ...(o.flavor ? ['--flavor', o.flavor] : []), ...(o.versionCode ? ['--build-number', String(o.versionCode)] : []), ...(o.versionName ? ['--build-name', o.versionName] : [])];
return [o.hasWrapper ? (process.platform === 'win32' ? 'gradlew.bat' : './gradlew') : 'gradle', t.task, '--no-daemon', '--console=plain',
...(o.versionCode ? [`-Pandroid.injected.version.code=${o.versionCode}`, `-PversionCode=${o.versionCode}`] : []),
...(o.versionName ? [`-Pandroid.injected.version.name=${o.versionName}`, `-PversionName=${o.versionName}`] : [])];
}
/** Environment that hands the upload key to the Android Gradle plugin (injected signing properties). */
export function signingEnv(s: AndroidSigning | null): Record<string, string> {
if (!s) return {};
return {
'ORG_GRADLE_PROJECT_android.injected.signing.store.file': s.storeFile,
'ORG_GRADLE_PROJECT_android.injected.signing.store.password': s.storePassword,
'ORG_GRADLE_PROJECT_android.injected.signing.key.alias': s.keyAlias,
'ORG_GRADLE_PROJECT_android.injected.signing.key.password': s.keyPassword,
};
}
/** AABs written since `since` (ms) below the folders a build writes to. Newest first. */
export function findBundles(dirs: string[], since: number): string[] {
const out: { f: string; t: number }[] = [];
const walk = (d: string, depth: number): void => {
let names: string[];
try { names = readdirSync(d); } catch { return; }
for (const n of names) {
const p = join(d, n);
let st;
try { st = statSync(p); } catch { continue; }
if (st.isDirectory()) { if (depth > 0 && n !== 'intermediates' && n !== 'tmp') walk(p, depth - 1); }
else if (n.endsWith('.aab') && st.mtimeMs >= since) out.push({ f: p, t: st.mtimeMs });
}
};
for (const d of dirs) walk(d, 6);
return out.sort((a, b) => b.t - a.t).map(x => x.f);
}
// ---- AAB manifest (aapt2 protobuf XmlNode) ----
type Field = { no: number; wire: number; v: number | Buffer };
function fields(b: Buffer): Field[] | null {
const out: Field[] = [];
let i = 0;
const varint = (): number => {
let r = 0, mul = 1;
for (let k = 0; k < 10; k++) {
if (i >= b.length) throw new Error('eof');
const x = b[i++]!;
r += (x & 127) * mul;
if (!(x & 128)) return r;
mul *= 128;
}
throw new Error('varint');
};
try {
while (i < b.length) {
const key = varint(), no = Math.floor(key / 8), wire = key & 7;
if (no === 0) return null;
if (wire === 0) out.push({ no, wire, v: varint() });
else if (wire === 2) { const n = varint(); if (i + n > b.length) return null; out.push({ no, wire, v: b.subarray(i, i + n) }); i += n; }
else if (wire === 5) { i += 4; } else if (wire === 1) { i += 8; } else return null;
}
} catch { return null; }
return i === b.length ? out : null;
}
/** Attributes (name -> raw value) of every element in an aapt2 proto XML, element name first. */
function elements(b: Buffer, out: { name: string; attrs: Record<string, string> }[] = [], depth = 0): { name: string; attrs: Record<string, string> }[] {
// XmlNode { XmlElement element = 1; string text = 2; ... } XmlElement { ns 1; string name = 4; XmlAttribute attribute = 5; XmlNode child = 6 }
// XmlAttribute { string namespace_uri = 1; string name = 2; string value = 3; ...; Item compiled_item = 6 }
if (depth > 64) return out;
const node = fields(b);
const el = node?.find(f => f.no === 1 && f.wire === 2);
if (!el) return out;
const ef = fields(el.v as Buffer) ?? [];
const name = (ef.find(f => f.no === 4)?.v as Buffer | undefined)?.toString('utf8') ?? '';
const attrs: Record<string, string> = {};
for (const a of ef.filter(f => f.no === 5 && f.wire === 2)) {
const af = fields(a.v as Buffer) ?? [];
const an = (af.find(f => f.no === 2)?.v as Buffer | undefined)?.toString('utf8');
let av = (af.find(f => f.no === 3)?.v as Buffer | undefined)?.toString('utf8') ?? '';
if (!av) {
// compiled_item { Prim prim = 7 { int_decimal_value = 6 ... } } or { Str str = 2 { value = 1 } }
const item = fields((af.find(f => f.no === 6)?.v as Buffer | undefined) ?? Buffer.alloc(0)) ?? [];
const prim = fields((item.find(f => f.no === 7)?.v as Buffer | undefined) ?? Buffer.alloc(0)) ?? [];
const n = prim.find(f => f.wire === 0);
const str = fields((item.find(f => f.no === 2)?.v as Buffer | undefined) ?? Buffer.alloc(0)) ?? [];
av = n ? String(n.v) : (str.find(f => f.no === 1)?.v as Buffer | undefined)?.toString('utf8') ?? '';
}
if (an) attrs[an] = av;
}
out.push({ name, attrs });
for (const c of ef.filter(f => f.no === 6 && f.wire === 2)) elements(c.v as Buffer, out, depth + 1);
return out;
}
export interface AabInfo { packageName: string; versionCode: number; versionName?: string; minSdk?: number; targetSdk?: number }
/** Package, versionCode and versionName of an Android App Bundle (base/manifest/AndroidManifest.xml). */
export function aabInfo(aab: string | Buffer): AabInfo {
const e = zipEntries(aab).find(x => x.name === 'base/manifest/AndroidManifest.xml');
if (!e) throw new Error('not an Android App Bundle (no base/manifest/AndroidManifest.xml)');
const els = elements(zipRead(aab, e));
const m = els.find(x => x.name === 'manifest');
if (!m?.attrs.package || !m.attrs.versionCode) throw new Error('AAB manifest without package / versionCode');
const sdk = els.find(x => x.name === 'uses-sdk')?.attrs;
return { packageName: m.attrs.package, versionCode: Number(m.attrs.versionCode), versionName: m.attrs.versionName || undefined,
minSdk: sdk?.minSdkVersion ? Number(sdk.minSdkVersion) : undefined, targetSdk: sdk?.targetSdkVersion ? Number(sdk.targetSdkVersion) : undefined };
}
/** Builds an aapt2-style proto manifest (tests and fixtures). */
export function encodeProtoManifest(els: { name: string; attrs: Record<string, string> }[]): Buffer {
const vint = (n: number): Buffer => { const o: number[] = []; do { let x = n % 128; n = Math.floor(n / 128); if (n) x |= 128; o.push(x); } while (n); return Buffer.from(o); };
const ld = (no: number, b: Buffer): Buffer => Buffer.concat([vint(no * 8 + 2), vint(b.length), b]);
const s = (no: number, t: string) => ld(no, Buffer.from(t, 'utf8'));
const element = (i: number): Buffer => {
const e = els[i]!;
const attrs = Object.entries(e.attrs).map(([k, v]) => ld(5, Buffer.concat([s(1, 'http://schemas.android.com/apk/res/android'), s(2, k), s(3, v)])));
const child = i + 1 < els.length ? [ld(6, ld(1, element(i + 1)))] : [];
return Buffer.concat([s(4, e.name), ...attrs, ...child]);
};
return ld(1, element(0));
}

138
cli/lib/imagehash.ts Normal file
View file

@ -0,0 +1,138 @@
// Perceptual image hashes without dependencies: a PNG decoder in TypeScript (node:zlib inflates), a 32 x 32 grey
// thumbnail, then dHash (gradients, 64 bit) and pHash (DCT low frequencies, 64 bit). JPEG / WebP go through ffmpeg
// when it is installed (one grey 32 x 32 frame on stdout), else they are skipped with a reason. Two images whose
// hashes differ in few bits look alike to a person (and to a reviewer comparing store pages).
import { readFileSync } from 'node:fs';
import { inflateSync } from 'node:zlib';
export interface Gray { w: number; h: number; px: Float64Array }
/** Decodes a PNG to grey (alpha composited over white). 1-16 bit, every color type, Adam7 interlacing included. */
export function decodePng(buf: Buffer): Gray {
if (buf.readUInt32BE(0) !== 0x89504e47) throw new Error('not a PNG');
let w = 0, h = 0, depth = 0, ctype = 0, interlace = 0;
let palette: Buffer | null = null, trns: Buffer | null = null;
const idat: Buffer[] = [];
for (let p = 8; p + 8 <= buf.length;) {
const len = buf.readUInt32BE(p), type = buf.toString('latin1', p + 4, p + 8), data = buf.subarray(p + 8, p + 8 + len);
if (type === 'IHDR') { w = data.readUInt32BE(0); h = data.readUInt32BE(4); depth = data[8]!; ctype = data[9]!; interlace = data[12]!; }
else if (type === 'PLTE') palette = data;
else if (type === 'tRNS') trns = data;
else if (type === 'IDAT') idat.push(data);
else if (type === 'IEND') break;
p += 12 + len;
}
if (!w || !h) throw new Error('PNG without IHDR');
if (w * h > 40_000_000) throw new Error('PNG too large to hash');
const channels = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }[ctype];
if (!channels) throw new Error(`PNG color type ${ctype} not supported`);
const raw = inflateSync(Buffer.concat(idat));
const bpp = Math.max(1, (channels * depth) >> 3);
const out = new Float64Array(w * h);
const max = (1 << depth) - 1;
let off = 0;
const pass = (x0: number, y0: number, dx: number, dy: number): void => {
const pw = Math.ceil((w - x0) / dx), ph = Math.ceil((h - y0) / dy);
if (pw <= 0 || ph <= 0) return;
const stride = Math.ceil((pw * channels * depth) / 8);
let prev = new Uint8Array(stride);
for (let y = 0; y < ph; y++) {
const ft = raw[off]!;
const line = new Uint8Array(raw.subarray(off + 1, off + 1 + stride));
off += 1 + stride;
for (let i = 0; i < stride; i++) {
const a = i >= bpp ? line[i - bpp]! : 0, b = prev[i]!, c = i >= bpp ? prev[i - bpp]! : 0;
let v = line[i]!;
if (ft === 1) v += a; else if (ft === 2) v += b; else if (ft === 3) v += (a + b) >> 1;
else if (ft === 4) { const pp = a + b - c, pa = Math.abs(pp - a), pb = Math.abs(pp - b), pc = Math.abs(pp - c); v += pa <= pb && pa <= pc ? a : pb <= pc ? b : c; }
line[i] = v & 255;
}
const sample = (x: number, ch: number): number => {
if (depth === 8) return line[x * channels + ch]!;
if (depth === 16) { const i = (x * channels + ch) * 2; return (line[i]! << 8) | line[i + 1]!; }
const bit = (x * channels + ch) * depth;
return (line[bit >> 3]! >> (8 - depth - (bit & 7))) & max;
};
for (let x = 0; x < pw; x++) {
let r: number, g: number, bl: number, al = 1;
if (ctype === 3) {
const i = sample(x, 0);
r = palette![i * 3]! / 255; g = palette![i * 3 + 1]! / 255; bl = palette![i * 3 + 2]! / 255;
if (trns && i < trns.length) al = trns[i]! / 255;
} else if (ctype === 0 || ctype === 4) { r = g = bl = sample(x, 0) / max; if (ctype === 4) al = sample(x, 1) / max; }
else { r = sample(x, 0) / max; g = sample(x, 1) / max; bl = sample(x, 2) / max; if (ctype === 6) al = sample(x, 3) / max; }
const lum = 0.299 * r + 0.587 * g + 0.114 * bl;
out[(y0 + y * dy) * w + x0 + x * dx] = (lum * al + (1 - al)) * 255;
}
prev = line;
}
};
if (interlace) for (const [x0, y0, dx, dy] of [[0, 0, 8, 8], [4, 0, 8, 8], [0, 4, 4, 8], [2, 0, 4, 4], [0, 2, 2, 4], [1, 0, 2, 2], [0, 1, 1, 2]] as const) pass(x0, y0, dx, dy);
else pass(0, 0, 1, 1);
return { w, h, px: out };
}
/** Area-average resize of a grey image. */
export function resize(g: Gray, W: number, H: number): Gray {
const out = new Float64Array(W * H);
for (let Y = 0; Y < H; Y++) for (let X = 0; X < W; X++) {
const x0 = Math.floor((X * g.w) / W), x1 = Math.max(x0 + 1, Math.floor(((X + 1) * g.w) / W));
const y0 = Math.floor((Y * g.h) / H), y1 = Math.max(y0 + 1, Math.floor(((Y + 1) * g.h) / H));
let s = 0;
for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) s += g.px[y * g.w + x]!;
out[Y * W + X] = s / ((x1 - x0) * (y1 - y0));
}
return { w: W, h: H, px: out };
}
/** 64-bit hashes as 16 hex characters. */
export interface ImageHash { d: string; p: string }
const toHex = (bits: number[]): string => { let s = ''; for (let i = 0; i < 64; i += 4) s += ((bits[i]! << 3) | (bits[i + 1]! << 2) | (bits[i + 2]! << 1) | bits[i + 3]!).toString(16); return s; };
export function dHash(g: Gray): string {
const s = resize(g, 9, 8);
const bits: number[] = [];
for (let y = 0; y < 8; y++) for (let x = 0; x < 8; x++) bits.push(s.px[y * 9 + x]! < s.px[y * 9 + x + 1]! ? 1 : 0);
return toHex(bits);
}
export function pHash(g: Gray): string {
const N = 32, s = resize(g, N, N);
const cos = Array.from({ length: 8 }, (_, u) => Array.from({ length: N }, (_, x) => Math.cos(((2 * x + 1) * u * Math.PI) / (2 * N))));
const coef: number[] = [];
for (let u = 0; u < 8; u++) for (let v = 0; v < 8; v++) {
let sum = 0;
for (let y = 0; y < N; y++) for (let x = 0; x < N; x++) sum += s.px[y * N + x]! * cos[u]![y]! * cos[v]![x]!;
coef.push(sum);
}
const ac = coef.slice(1).sort((a, b) => a - b);
const median = ac[Math.floor(ac.length / 2)]!;
return toHex(coef.map((c, i) => (i === 0 ? 0 : c > median ? 1 : 0)));
}
export const hashGray = (g: Gray): ImageHash => ({ d: dHash(g), p: pHash(g) });
export function hamming(a: string, b: string): number {
let n = 0;
for (let i = 0; i < a.length; i++) { let x = parseInt(a[i]!, 16) ^ parseInt(b[i]!, 16); while (x) { n += x & 1; x >>= 1; } }
return n;
}
/** 1 = same picture, about 0.5 = unrelated. The mean of both hashes. */
export const imageSimilarity = (a: ImageHash, b: ImageHash): number => 1 - (hamming(a.d, b.d) + hamming(a.p, b.p)) / 128;
/** Hash of an image file: PNG in TypeScript, anything else through ffmpeg (null with a reason when that is missing). */
export function hashFile(path: string): { hash: ImageHash | null; reason?: string } {
try {
const buf = readFileSync(path);
if (buf.length > 8 && buf.readUInt32BE(0) === 0x89504e47) return { hash: hashGray(decodePng(buf)) };
const ffmpeg = Bun.which('ffmpeg');
if (!ffmpeg) return { hash: null, reason: 'not a PNG and ffmpeg is not installed' };
const r = Bun.spawnSync([ffmpeg, '-v', 'error', '-i', path, '-frames:v', '1', '-vf', 'scale=32:32:flags=area,format=gray', '-f', 'rawvideo', '-'], { stdout: 'pipe', stderr: 'pipe', timeout: 20_000 });
const px = r.stdout;
if (r.exitCode !== 0 || px.length !== 1024) return { hash: null, reason: `ffmpeg could not read it (${r.stderr.toString().trim().split('\n')[0]?.slice(0, 120) ?? r.exitCode})` };
return { hash: hashGray({ w: 32, h: 32, px: Float64Array.from(px) }) };
} catch (e) { return { hash: null, reason: (e as Error).message }; }
}

267
cli/lib/originality.ts Normal file
View file

@ -0,0 +1,267 @@
// Originality check against the owner's other apps (App Store Guideline 4.3 "spam", Google Play repetitive content):
// listing text, icon, screenshots and project structure of this app vs each other app, offline. Every axis is a
// 0-1 likeness (1 = the same), the overall score weighs the axes that both apps have, and a pair is flagged as a
// near-duplicate above the threshold or when one axis alone is nearly identical. Suggestions follow the
// portfolio-originality skill: deepen one axis until it is clearly different, or merge the idea into the other app.
import { createHash } from 'node:crypto';
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
import { join, relative } from 'node:path';
import type { ShipConfig } from './config';
import { parseAppStoreListing, parsePlayListing } from './copy';
import { hashFile, type ImageHash, imageSimilarity } from './imagehash';
import { findIcon } from './project-files';
export interface OriginalityConfig {
/** Other apps: folders with a storebound.config.ts, or workspace folders holding several (one level down). */
against?: string[];
/** Overall score from which a pair counts as a near-duplicate (0-1). Default 0.7. */
threshold?: number;
}
export function validateOriginality(o: OriginalityConfig | undefined): string[] {
if (!o) return [];
const e: string[] = [];
if (o.against && (!Array.isArray(o.against) || o.against.some(x => typeof x !== 'string' || !x))) e.push('originality.against: a list of folders');
if (o.threshold !== undefined && !(o.threshold > 0 && o.threshold < 1)) e.push('originality.threshold: between 0 and 1 (e.g. 0.7)');
return e;
}
export const DEFAULT_THRESHOLD = 0.7;
/** One axis alone at or above this likeness flags the pair too. */
export const AXIS_FLAG = { text: 0.8, name: 0.85, icon: 0.85, screenshots: 0.8, structure: 0.85 } as const;
const WEIGHTS = { text: 0.3, icon: 0.2, screenshots: 0.3, structure: 0.2 } as const;
// ---- text ----
const STOP = new Set(('a an and are as at be but by for from has have in is it its of on or our so that the their them this to us was we were will '
+ 'with you your yours all any can more most new no not now one only just get got out up very than then there these those into over each '
+ 'app apps game games play free').split(' '));
export const words = (s: string): string[] => (s.toLowerCase().normalize('NFKC').match(/[\p{L}\p{N}]+/gu) ?? []).filter(w => w.length > 1 && !STOP.has(w));
function cosine(a: string[], b: string[]): number {
if (!a.length || !b.length) return 0;
const ta = new Map<string, number>(), tb = new Map<string, number>();
for (const w of a) ta.set(w, (ta.get(w) ?? 0) + 1);
for (const w of b) tb.set(w, (tb.get(w) ?? 0) + 1);
let dot = 0, na = 0, nb = 0;
for (const [w, n] of ta) { na += n * n; dot += n * (tb.get(w) ?? 0); }
for (const n of tb.values()) nb += n * n;
return dot / Math.sqrt(na * nb);
}
const shingles = (w: string[], k = 3): Set<string> => { const s = new Set<string>(); for (let i = 0; i + k <= w.length; i++) s.add(w.slice(i, i + k).join(' ')); return s; };
export function jaccard<T>(a: Set<T>, b: Set<T>): number {
if (!a.size && !b.size) return 0;
let n = 0;
for (const x of a) if (b.has(x)) n++;
return n / (a.size + b.size - n);
}
/** Bigram (character pair) Dice coefficient of two short strings (app names). */
export function nameSimilarity(a: string, b: string): number {
const norm = (s: string) => s.toLowerCase().normalize('NFKC').replace(/[^\p{L}\p{N}]+/gu, '');
const x = norm(a), y = norm(b);
if (!x || !y) return 0;
if (x === y) return 1;
const bi = (s: string) => { const m = new Map<string, number>(); for (let i = 0; i < s.length - 1; i++) { const k = s.slice(i, i + 2); m.set(k, (m.get(k) ?? 0) + 1); } return m; };
const A = bi(x), B = bi(y);
let inter = 0;
for (const [k, n] of A) inter += Math.min(n, B.get(k) ?? 0);
const total = Math.max(1, x.length - 1 + y.length - 1);
return (2 * inter) / total;
}
/** Listing text likeness: word frequency cosine (same promises and vocabulary) and 3-word shingle overlap (copied
* sentences), 0.6 / 0.4. */
export function textSimilarity(a: string, b: string): { score: number; cosine: number; shingles: number } {
const wa = words(a), wb = words(b);
const c = cosine(wa, wb), s = jaccard(shingles(wa), shingles(wb));
return { score: 0.6 * c + 0.4 * s, cosine: c, shingles: s };
}
// ---- fingerprint ----
export interface AppFingerprint {
name: string;
dir: string;
ids: string[];
/** Listing text of the primary language (name, subtitle, keywords, descriptions). */
text: string;
icon: ImageHash | null;
shots: ImageHash[];
/** Relative file paths (folder layout) and content hashes of the project's own files. */
paths: Set<string>;
contents: Set<string>;
notes: string[];
}
const SKIP = new Set(['node_modules', '.git', 'build', 'dist', 'Pods', 'DerivedData', '.gradle', '.storebound', '.dart_tool', 'Library', 'Temp', 'Logs',
'obj', '.idea', '.vscode', 'renders', '.next', '.expo', 'coverage', 'www', 'public']);
export const MAX_FILES = 20_000;
const MAX_HASH_BYTES = 4_000_000;
/** Folder layout and content hashes of a project, bounded (MAX_FILES). Store renders and build output are left out:
* screenshots have their own axis, build output is not the developer's work. */
export function projectStructure(root: string): { paths: Set<string>; contents: Set<string>; truncated: boolean } {
const paths = new Set<string>(), contents = new Set<string>();
let count = 0, truncated = false;
const walk = (d: string): void => {
let names: string[];
try { names = readdirSync(d).sort(); } catch { return; }
for (const n of names) {
if (count >= MAX_FILES) { truncated = true; return; }
if (n.startsWith('.') && n !== '.github') continue;
const p = join(d, n);
let st;
try { st = statSync(p); } catch { continue; }
if (st.isDirectory()) { if (!SKIP.has(n) && !n.endsWith('.xcarchive')) walk(p); continue; }
count++;
// names that carry the app's identity (bundle id folders, app names) are normalized away by keeping the extension and depth
paths.add(relative(root, p).split(/[\\/]/).map((seg, i, all) => (i === all.length - 1 ? seg.toLowerCase() : seg.toLowerCase().replace(/[^a-z]+/g, '-'))).join('/'));
if (st.size > 0 && st.size <= MAX_HASH_BYTES) { try { contents.add(createHash('md5').update(readFileSync(p)).digest('hex')); } catch { /* unreadable */ } }
}
};
walk(root);
return { paths, contents, truncated };
}
function primaryText(config: ShipConfig, root: string, notes: string[]): string {
const parts: string[] = [config.app.name];
const read = (rel: string): string | null => { try { return readFileSync(join(root, rel), 'utf8'); } catch { return null; } };
if (config.apple) {
const md = read(config.apple.listing ?? 'store/appstore.md');
if (md) try {
const all = parseAppStoreListing(md);
const loc = config.apple.primaryLocale ?? (all['en-US'] ? 'en-US' : Object.keys(all)[0]);
const c = loc ? all[loc] : undefined;
if (c) parts.push(c.name ?? '', c.subtitle ?? '', (c.keywords ?? '').replace(/,/g, ' '), c.promotionalText ?? '', c.description ?? '');
} catch (e) { notes.push(`App Store listing not readable: ${(e as Error).message.slice(0, 120)}`); }
else notes.push('no App Store listing file');
}
if (config.play) {
const md = read(config.play.listing ?? 'store/listing.md');
if (md) try {
const all = parsePlayListing(md, config.app.name);
const c = all.find(x => x.lang === (config.play!.defaultLanguage ?? 'en-US')) ?? all[0];
if (c) parts.push(c.title, c.short, c.full);
} catch (e) { notes.push(`Play listing not readable: ${(e as Error).message.slice(0, 120)}`); }
else notes.push('no Play listing file');
}
return parts.filter(Boolean).join('\n');
}
function screenshotFiles(config: ShipConfig, root: string): string[] {
const dir = join(root, config.renders ?? config.shots?.out ?? 'store/renders');
if (!existsSync(dir)) return [];
const langs = readdirSync(dir).filter(n => { try { return statSync(join(dir, n)).isDirectory(); } catch { return false; } });
const lang = langs.find(l => l === config.languages[0]?.id) ?? langs.find(l => l !== 'feature') ?? null;
if (!lang) return [];
const sizes = readdirSync(join(dir, lang)).map(s => join(dir, lang, s)).filter(p => { try { return statSync(p).isDirectory(); } catch { return false; } });
const imgs = (d: string) => readdirSync(d).filter(f => /\.(png|jpe?g|webp)$/i.test(f) && !/contact|sheet|index/i.test(f)).sort().map(f => join(d, f));
const best = sizes.map(imgs).sort((a, b) => b.length - a.length)[0] ?? imgs(join(dir, lang));
return best.slice(0, 10);
}
/** Everything the comparison needs from one app's folder and config. */
export function fingerprint(config: ShipConfig, root: string): AppFingerprint {
const notes: string[] = [];
const iconPath = findIcon(config, root);
let icon: ImageHash | null = null;
if (iconPath) { const h = hashFile(iconPath); icon = h.hash; if (!h.hash) notes.push(`icon not hashed: ${h.reason}`); } else notes.push('no icon found');
const files = screenshotFiles(config, root);
const shots: ImageHash[] = [];
for (const f of files) { const h = hashFile(f); if (h.hash) shots.push(h.hash); else notes.push(`${relative(root, f)}: ${h.reason}`); }
if (!files.length) notes.push('no rendered screenshots (shots render)');
const st = projectStructure(root);
if (st.truncated) notes.push(`project structure: first ${MAX_FILES} files only`);
return { name: config.app.name, dir: root, ids: [config.apple?.bundleId, config.play?.packageName].filter((x): x is string => !!x),
text: primaryText(config, root, notes), icon, shots, paths: st.paths, contents: st.contents, notes };
}
// ---- comparison ----
/** Image likeness on a 0-1 scale where unrelated pictures land near 0 (raw hash similarity of unrelated images is ~0.5). */
export const imageLikeness = (a: ImageHash, b: ImageHash): number => Math.max(0, (imageSimilarity(a, b) - 0.5) / 0.5);
/** Mean of each screenshot's best match in the other set, both directions. */
export function screenshotSimilarity(a: ImageHash[], b: ImageHash[]): number | null {
if (!a.length || !b.length) return null;
const best = (x: ImageHash[], y: ImageHash[]) => x.reduce((s, h) => s + Math.max(...y.map(k => imageLikeness(h, k))), 0) / x.length;
return (best(a, b) + best(b, a)) / 2;
}
export interface Axis { score: number | null; detail: string }
export interface PairResult {
other: { name: string; dir: string; ids: string[] };
axes: { name: Axis; text: Axis; icon: Axis; screenshots: Axis; structure: Axis };
overall: number;
flagged: boolean;
reasons: string[];
suggestions: string[];
}
const r2 = (x: number): number => Math.round(x * 100) / 100;
export function compare(a: AppFingerprint, b: AppFingerprint, threshold = DEFAULT_THRESHOLD): PairResult {
const name = nameSimilarity(a.name, b.name);
const t = a.text && b.text ? textSimilarity(a.text, b.text) : null;
const icon = a.icon && b.icon ? imageLikeness(a.icon, b.icon) : null;
const shots = screenshotSimilarity(a.shots, b.shots);
const layout = a.paths.size && b.paths.size ? jaccard(a.paths, b.paths) : null;
const content = a.contents.size && b.contents.size ? jaccard(a.contents, b.contents) : null;
const structure = layout === null || content === null ? null : 0.4 * layout + 0.6 * content;
const axes: PairResult['axes'] = {
name: { score: r2(name), detail: `"${a.name}" vs "${b.name}"` },
text: { score: t ? r2(t.score) : null, detail: t ? `vocabulary ${Math.round(t.cosine * 100)}%, copied phrases ${Math.round(t.shingles * 100)}%` : 'no listing text on one side' },
icon: { score: icon === null ? null : r2(icon), detail: icon === null ? 'no icon on one side' : `perceptual hash likeness ${Math.round(icon * 100)}%` },
screenshots: { score: shots === null ? null : r2(shots), detail: shots === null ? 'no screenshots on one side' : `${a.shots.length} vs ${b.shots.length} screenshots, best-match likeness ${Math.round(shots * 100)}%` },
structure: { score: structure === null ? null : r2(structure), detail: structure === null ? 'no project files on one side' : `same file layout ${Math.round(layout! * 100)}%, identical files ${Math.round(content! * 100)}%` },
};
let wsum = 0, sum = 0;
for (const k of ['text', 'icon', 'screenshots', 'structure'] as const) { const s = axes[k].score; if (s !== null) { wsum += WEIGHTS[k]; sum += WEIGHTS[k] * s; } }
const overall = wsum ? r2(sum / wsum) : 0;
const reasons: string[] = [];
if (overall >= threshold) reasons.push(`overall ${overall} >= ${threshold}`);
for (const k of ['name', 'text', 'icon', 'screenshots', 'structure'] as const) { const s = axes[k].score; if (s !== null && s >= AXIS_FLAG[k]) reasons.push(`${k} ${s} (${axes[k].detail})`); }
return { other: { name: b.name, dir: b.dir, ids: b.ids }, axes, overall, flagged: reasons.length > 0, reasons, suggestions: suggest(axes, reasons.length > 0, overall, b.name) };
}
export function suggest(axes: PairResult['axes'], flagged: boolean, overall: number, other: string): string[] {
const s: string[] = [];
const hi = (k: keyof typeof axes, x: number) => (axes[k].score ?? 0) >= x;
if (hi('text', 0.6)) s.push(`Rewrite the listing around what is different from ${other} (another promise and audience), not synonyms: reviewers read both pages side by side`);
if (hi('name', 0.7)) s.push(`Pick a name that does not read as a variant of "${other}"`);
if (hi('icon', 0.7)) s.push('Make an icon with its own shape and subject, not a recolour of the other icon');
if (hi('screenshots', 0.6)) s.push('Show different scenes and messages in the screenshots: the first screenshot should show what this app does that the other cannot');
if (hi('structure', 0.6)) s.push(`Most project files are shared with ${other}: a template or reskin. Apple reviewers compare binaries; deepen one axis (core mechanic, progression, main task) until a user sees it in the first minute`);
if (flagged) {
s.push(`Write the differentiator: "Unlike ${other}, in this app the user <does something they cannot do there>". If it needs "theme", "skin", "colours" or "levels", it is not one`);
if (overall >= 0.85) s.push(`Consider merging this into ${other} as a mode, world or event instead of a separate app (Guideline 4.3: fewer, richer apps)`);
}
return s;
}
export interface OriginalityReport { app: { name: string; dir: string; ids: string[]; notes: string[] }; threshold: number; pairs: PairResult[]; flagged: number; others: { dir: string; notes: string[] }[] }
export function report(self: AppFingerprint, others: AppFingerprint[], threshold = DEFAULT_THRESHOLD): OriginalityReport {
const pairs = others.map(o => compare(self, o, threshold)).sort((x, y) => y.overall - x.overall);
return { app: { name: self.name, dir: self.dir, ids: self.ids, notes: self.notes }, threshold, pairs, flagged: pairs.filter(p => p.flagged).length,
others: others.map(o => ({ dir: o.dir, notes: o.notes })) };
}
/** Config files of the apps to compare with: each folder itself when it holds a storebound config, else its
* sub-folders that do (a workspace). `self` (this app's folder) is left out. */
export function findApps(folders: string[], self: string, configNames = ['storebound.config.ts', 'storebound.config.js', 'storebound.config.json']): string[] {
const cfg = (d: string) => configNames.map(n => join(d, n)).find(existsSync) ?? null;
const out: string[] = [];
for (const f of folders) {
const own = cfg(f);
if (own) { out.push(own); continue; }
let subs: string[] = [];
try { subs = readdirSync(f).map(n => join(f, n)).filter(p => { try { return statSync(p).isDirectory(); } catch { return false; } }); } catch { /* missing */ }
for (const s of subs.sort()) { const c = cfg(s); if (c) out.push(c); }
}
return [...new Set(out)].filter(p => !p.startsWith(join(self, 'storebound.config')));
}

125
cli/lib/plist.ts Normal file
View file

@ -0,0 +1,125 @@
// Property lists without dependencies: write XML plists (ExportOptions.plist), read XML and binary plists (an IPA's
// Info.plist, the plist inside a .mobileprovision). Only the types those files use: dict, array, string, integer,
// real, true / false, date (as an ISO string) and data (as a Buffer).
export type PlistValue = string | number | boolean | Buffer | PlistValue[] | { [k: string]: PlistValue };
const esc = (s: string): string => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
function xmlValue(v: PlistValue, ind: string): string {
if (typeof v === 'string') return `${ind}<string>${esc(v)}</string>`;
if (typeof v === 'boolean') return `${ind}<${v}/>`;
if (typeof v === 'number') return Number.isInteger(v) ? `${ind}<integer>${v}</integer>` : `${ind}<real>${v}</real>`;
if (Buffer.isBuffer(v)) return `${ind}<data>${v.toString('base64')}</data>`;
if (Array.isArray(v)) return v.length ? `${ind}<array>\n${v.map(x => xmlValue(x, ind + '\t')).join('\n')}\n${ind}</array>` : `${ind}<array/>`;
const keys = Object.keys(v).filter(k => v[k] !== undefined);
if (!keys.length) return `${ind}<dict/>`;
return `${ind}<dict>\n${keys.map(k => `${ind}\t<key>${esc(k)}</key>\n${xmlValue(v[k]!, ind + '\t')}`).join('\n')}\n${ind}</dict>`;
}
/** XML plist text, the format Xcode writes. */
export function toXmlPlist(v: PlistValue): string {
return '<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n'
+ `<plist version="1.0">\n${xmlValue(v, '')}\n</plist>\n`;
}
const unesc = (s: string): string => s.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&apos;/g, "'")
.replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n))).replace(/&#x([0-9a-f]+);/gi, (_, n) => String.fromCodePoint(parseInt(n, 16))).replace(/&amp;/g, '&');
/** Parses an XML plist (tolerant of comments and whitespace). Throws on anything it does not understand. */
export function parseXmlPlist(text: string): PlistValue {
const body = /<plist[^>]*>([\s\S]*)<\/plist>/.exec(text);
if (!body) throw new Error('not an XML plist');
const toks = [...body[1]!.replace(/<!--[\s\S]*?-->/g, '').matchAll(/<(\/?)([a-zA-Z]+)(\/?)>|([^<]+)/g)];
let i = 0;
const skipWs = () => { while (i < toks.length && toks[i]![4] !== undefined && !toks[i]![4]!.trim()) i++; };
const text_ = (tag: string): string => {
let s = '';
while (i < toks.length && !(toks[i]![1] === '/' && toks[i]![2] === tag)) { s += toks[i]![4] ?? ''; i++; }
i++;
return unesc(s);
};
function value(): PlistValue {
skipWs();
const t = toks[i++];
if (!t || t[1]) throw new Error('plist: unexpected end or closing tag');
const tag = t[2]!, selfClose = t[3] === '/';
if (tag === 'true' || tag === 'false') { if (!selfClose) text_(tag); return tag === 'true'; }
if (selfClose) return tag === 'array' ? [] : tag === 'dict' ? {} : tag === 'data' ? Buffer.alloc(0) : '';
if (tag === 'string' || tag === 'date') return text_(tag);
if (tag === 'integer' || tag === 'real') return Number(text_(tag).trim());
if (tag === 'data') return Buffer.from(text_(tag).replace(/\s+/g, ''), 'base64');
if (tag === 'array') {
const out: PlistValue[] = [];
for (;;) { skipWs(); if (toks[i]?.[1] === '/' && toks[i]![2] === 'array') { i++; return out; } out.push(value()); }
}
if (tag === 'dict') {
const out: Record<string, PlistValue> = {};
for (;;) {
skipWs();
const k = toks[i];
if (k?.[1] === '/' && k[2] === 'dict') { i++; return out; }
if (k?.[2] !== 'key') throw new Error('plist: <key> expected in <dict>');
i++;
out[text_('key')] = value();
}
}
throw new Error(`plist: unsupported <${tag}>`);
}
return value();
}
/** Parses a binary plist ("bplist00"). */
export function parseBinaryPlist(b: Buffer): PlistValue {
if (b.subarray(0, 8).toString('latin1') !== 'bplist00') throw new Error('not a binary plist');
const t = b.subarray(b.length - 32);
const offSize = t[6]!, refSize = t[7]!;
const numObjects = Number(t.readBigUInt64BE(8)), top = Number(t.readBigUInt64BE(16)), tableOff = Number(t.readBigUInt64BE(24));
const uint = (at: number, n: number): number => { let v = 0; for (let k = 0; k < n; k++) v = v * 256 + b[at + k]!; return v; };
const offset = (ref: number): number => uint(tableOff + ref * offSize, offSize);
const depth = { n: 0 };
function obj(ref: number): PlistValue {
if (ref >= numObjects) throw new Error('bplist: bad object reference');
if (++depth.n > 512) throw new Error('bplist: too deep');
try {
const at = offset(ref);
const m = b[at]!, hi = m >> 4, lo = m & 15;
const len = (): [number, number] => {
if (lo !== 15) return [lo, at + 1];
const sz = 1 << (b[at + 1]! & 15);
return [uint(at + 2, sz), at + 2 + sz];
};
switch (hi) {
case 0: return lo === 9; // 0x08 false, 0x09 true (0x00 null -> false)
case 1: { const n = 1 << lo; return n === 8 ? Number(b.readBigInt64BE(at + 1)) : uint(at + 1, n); }
case 2: return lo === 2 ? b.readFloatBE(at + 1) : b.readDoubleBE(at + 1);
case 3: return new Date(Date.UTC(2001, 0, 1) + b.readDoubleBE(at + 1) * 1000).toISOString();
case 4: { const [n, s] = len(); return Buffer.from(b.subarray(s, s + n)); }
case 5: { const [n, s] = len(); return b.subarray(s, s + n).toString('latin1'); }
case 6: { const [n, s] = len(); const u = Buffer.from(b.subarray(s, s + n * 2)); u.swap16(); return u.toString('utf16le'); }
case 8: return uint(at + 1, lo + 1);
case 10: { const [n, s] = len(); return Array.from({ length: n }, (_, k) => obj(uint(s + k * refSize, refSize))); }
case 13: {
const [n, s] = len();
const out: Record<string, PlistValue> = {};
for (let k = 0; k < n; k++) out[String(obj(uint(s + k * refSize, refSize)))] = obj(uint(s + (n + k) * refSize, refSize));
return out;
}
default: throw new Error(`bplist: unsupported object type 0x${m.toString(16)}`);
}
} finally { depth.n--; }
}
return obj(top);
}
/** XML or binary plist bytes. */
export function parsePlist(b: Buffer): PlistValue {
return b.subarray(0, 8).toString('latin1') === 'bplist00' ? parseBinaryPlist(b) : parseXmlPlist(b.toString('utf8'));
}
/** The plist embedded in a .mobileprovision (a CMS envelope around an XML plist; the signature is not checked). */
export function parseMobileprovision(b: Buffer): Record<string, PlistValue> {
const s = b.toString('latin1');
const start = s.indexOf('<?xml'), end = s.indexOf('</plist>');
if (start < 0 || end < 0) throw new Error('not a provisioning profile (no embedded plist)');
return parseXmlPlist(Buffer.from(s.slice(start, end + 8), 'latin1').toString('utf8')) as Record<string, PlistValue>;
}

View file

@ -46,7 +46,7 @@ export function childEnv(extra: Record<string, string> = {}, machine = false): R
return { ...base, ...extra, NO_COLOR: '1', ...(machine ? { STOREBOUND_MACHINE: '1', STOREBOUND_SERVE: '1' } : {}) }; return { ...base, ...extra, NO_COLOR: '1', ...(machine ? { STOREBOUND_MACHINE: '1', STOREBOUND_SERVE: '1' } : {}) };
} }
async function pump(stream: ReadableStream<Uint8Array>, kind: 'stdout' | 'stderr', each: (line: string, kind: 'stdout' | 'stderr') => void): Promise<void> { export async function pump(stream: ReadableStream<Uint8Array>, kind: 'stdout' | 'stderr', each: (line: string, kind: 'stdout' | 'stderr') => void): Promise<void> {
const dec = new TextDecoder(); const dec = new TextDecoder();
let buf = ''; let buf = '';
const reader = stream.getReader(); const reader = stream.getReader();

173
cli/lib/signing.ts Normal file
View file

@ -0,0 +1,173 @@
// Code signing through the App Store Connect API (Certificates, Identifiers & Profiles), pure planning:
// bundle id capabilities, which distribution certificate to use, which provisioning profile to (re)create, where
// profiles are installed, and the ExportOptions.plist for `xcodebuild -exportArchive`. The command is
// cli/apple/signing.ts; requests are JSON:API `Req`s (printed on --dry, sent otherwise).
// API reference: https://developer.apple.com/documentation/appstoreconnectapi (Bundle IDs, Bundle ID Capabilities,
// Certificates, Profiles).
import { createHash, X509Certificate } from 'node:crypto';
import { join } from 'node:path';
import type { Req } from '../apple/jsonapi';
import { one, many } from '../apple/jsonapi';
import type { PlistValue } from './plist';
/** CapabilityType values of the App Store Connect API (BundleIdCapability.capabilityType). */
export const CAPABILITY_TYPES = ['ICLOUD', 'IN_APP_PURCHASE', 'GAME_CENTER', 'PUSH_NOTIFICATIONS', 'WALLET', 'INTER_APP_AUDIO', 'MAPS',
'ASSOCIATED_DOMAINS', 'PERSONAL_VPN', 'APP_GROUPS', 'HEALTHKIT', 'HOMEKIT', 'WIRELESS_ACCESSORY_CONFIGURATION', 'APPLE_PAY', 'DATA_PROTECTION',
'SIRIKIT', 'NETWORK_EXTENSIONS', 'MULTIPATH', 'HOT_SPOT', 'NFC_TAG_READING', 'CLASSKIT', 'AUTOFILL_CREDENTIAL_PROVIDER',
'ACCESS_WIFI_INFORMATION', 'NETWORK_CUSTOM_PROTOCOL', 'COREMEDIA_HLS_LOW_LATENCY', 'SYSTEM_EXTENSION_INSTALL', 'USER_MANAGEMENT',
'APPLE_ID_AUTH'] as const;
export type CapabilityType = typeof CAPABILITY_TYPES[number];
/** Certificate types storebound creates: Apple Distribution (DISTRIBUTION, all platforms), the older iOS Distribution,
* and Developer ID Application (Mac apps outside the App Store; Account Holder only). */
export const CERT_TYPES = ['DISTRIBUTION', 'IOS_DISTRIBUTION', 'DEVELOPER_ID_APPLICATION', 'DEVELOPER_ID_APPLICATION_G2'] as const;
export type CertType = typeof CERT_TYPES[number];
/** Profile types for store builds (Profile.profileType). */
export const PROFILE_TYPES = ['IOS_APP_STORE', 'IOS_APP_ADHOC', 'TVOS_APP_STORE', 'MAC_APP_STORE', 'MAC_APP_DIRECT', 'MAC_CATALYST_APP_STORE'] as const;
export type ProfileType = typeof PROFILE_TYPES[number];
export interface CapabilitySpec { type: CapabilityType; settings?: unknown[] }
export interface AppleSigning {
/** automatic (default): xcodebuild -allowProvisioningUpdates with the API key creates what it needs.
* manual: the certificate and profiles from `storebound apple signing ensure`, named in ExportOptions.plist. */
style?: 'automatic' | 'manual';
/** Team ID (10 characters). Default: the bundle id's seedId from the API. */
teamId?: string;
/** Default DISTRIBUTION (Apple Distribution). */
certificateType?: CertType;
/** Default IOS_APP_STORE. */
profileType?: ProfileType;
/** Capabilities the bundle id must have (Certificates, Identifiers & Profiles), e.g. ['IN_APP_PURCHASE', 'GAME_CENTER']. */
capabilities?: (CapabilityType | CapabilitySpec)[];
/** Bundle ids of app extensions / widgets / watch apps in the same archive: each gets its own profile. */
extraBundleIds?: string[];
}
export function validateSigning(s: AppleSigning | undefined): string[] {
if (!s) return [];
const e: string[] = [];
if (s.style && !['automatic', 'manual'].includes(s.style)) e.push('apple.signing.style: automatic | manual');
if (s.teamId && !/^[A-Z0-9]{10}$/.test(s.teamId)) e.push('apple.signing.teamId: the 10-character Team ID');
if (s.certificateType && !CERT_TYPES.includes(s.certificateType)) e.push(`apple.signing.certificateType: one of ${CERT_TYPES.join(', ')}`);
if (s.profileType && !PROFILE_TYPES.includes(s.profileType)) e.push(`apple.signing.profileType: one of ${PROFILE_TYPES.join(', ')}`);
for (const c of s.capabilities ?? []) {
const t = typeof c === 'string' ? c : c?.type;
if (!CAPABILITY_TYPES.includes(t as CapabilityType)) e.push(`apple.signing.capabilities: unknown capability "${String(t)}" (${CAPABILITY_TYPES.slice(0, 6).join(', ')}, ...)`);
}
for (const b of s.extraBundleIds ?? []) if (!/^[A-Za-z0-9.-]+$/.test(b)) e.push(`apple.signing.extraBundleIds: "${b}" is not a bundle id`);
return e;
}
export const capabilitySpecs = (s: AppleSigning | undefined): CapabilitySpec[] =>
(s?.capabilities ?? []).map(c => (typeof c === 'string' ? { type: c } : c));
/** Capabilities to add (never removes one: removing can break a shipped feature; extra ones are reported). */
export function planCapabilities(bundleIdId: string, existing: string[], want: CapabilitySpec[]): { create: Req[]; present: string[]; extra: string[] } {
const have = new Set(existing);
const create = want.filter(w => !have.has(w.type)).map((w): Req => ({
method: 'POST', path: '/v1/bundleIdCapabilities', note: `capability ${w.type}`,
body: { data: { type: 'bundleIdCapabilities', attributes: { capabilityType: w.type, ...(w.settings ? { settings: w.settings } : {}) }, relationships: { bundleId: one('bundleIds', bundleIdId) } } },
}));
return { create, present: want.filter(w => have.has(w.type)).map(w => w.type), extra: existing.filter(t => !want.some(w => w.type === t)) };
}
export interface ApiCert { id: string; attributes: { certificateType?: string; certificateContent?: string; expirationDate?: string; displayName?: string; name?: string; serialNumber?: string; activated?: boolean } }
/** SHA-1 of the certificate DER, upper-case hex: what `security find-identity` prints. */
export const certSha1 = (contentB64: string): string => createHash('sha1').update(Buffer.from(contentB64, 'base64')).digest('hex').toUpperCase();
/** SPKI (DER, base64) of a certificate's public key, or null when it does not parse. */
export function certSpki(contentB64: string): string | null {
try { return new X509Certificate(Buffer.from(contentB64, 'base64')).publicKey.export({ type: 'spki', format: 'der' }).toString('base64'); } catch { return null; }
}
export interface CertChoice { cert: ApiCert | null; why: string; usable: ApiCert[]; withoutKey: ApiCert[]; expiring: ApiCert[] }
/** A certificate is usable when it is of the wanted type, active, valid for 30 more days and this machine holds its
* private key (a key file in .storebound/signing or a code signing identity in the keychain). Newest first. */
export function pickCertificate(certs: ApiCert[], type: CertType, hasKey: (c: ApiCert) => boolean, now = Date.now()): CertChoice {
const ofType = certs.filter(c => c.attributes.certificateType === type && c.attributes.activated !== false);
const valid = ofType.filter(c => Date.parse(c.attributes.expirationDate ?? '') > now);
const expiring = valid.filter(c => Date.parse(c.attributes.expirationDate!) - now < 30 * 86_400_000);
const usable = valid.filter(c => hasKey(c) && !expiring.includes(c)).sort((a, b) => Date.parse(b.attributes.expirationDate!) - Date.parse(a.attributes.expirationDate!));
const withoutKey = valid.filter(c => !hasKey(c));
const cert = usable[0] ?? null;
const why = cert ? `using ${cert.attributes.name ?? cert.attributes.displayName ?? type} (expires ${cert.attributes.expirationDate?.slice(0, 10)})`
: withoutKey.length ? `${withoutKey.length} ${type} certificate(s) on the team, but this machine has none of their private keys: a new one is needed (or import the .p12 from the Mac that made it)`
: `no valid ${type} certificate`;
return { cert, why, usable, withoutKey, expiring };
}
/** Apple caps distribution certificates per team (Apple Distribution: 3 per team). */
export const CERT_LIMIT: Partial<Record<CertType, number>> = { DISTRIBUTION: 3, IOS_DISTRIBUTION: 3, DEVELOPER_ID_APPLICATION: 5, DEVELOPER_ID_APPLICATION_G2: 5 };
export function certificateReq(type: CertType, csr: string): Req {
return { method: 'POST', path: '/v1/certificates', note: `create ${type} certificate (key in .storebound/signing, never printed)`,
body: { data: { type: 'certificates', attributes: { certificateType: type, csrContent: csr } } } };
}
/** A 403 when creating a Developer ID certificate: only the Account Holder may create them. Explanation or null. */
export function explainCertError(err: unknown, type: CertType): string | null {
const s = String(err);
if (/DEVELOPER_ID/.test(type) && /-> 403/.test(s))
return 'Developer ID certificates can only be created by the Account Holder of the team. An API key (even Admin) gets 403 here. '
+ 'The Account Holder creates it once in Xcode (Settings > Accounts > Manage Certificates > + > Developer ID Application) or at '
+ 'developer.apple.com > Certificates, then exports the .p12 for this machine. App Store builds need DISTRIBUTION instead.';
if (/-> 409/.test(s) && /maximum|limit|already/i.test(s))
return 'The team has reached its limit of this certificate type. Revoke an unused one at developer.apple.com > Certificates (owner decision: '
+ 'builds signed with it keep working, but its profiles become invalid), or use a certificate whose key is on another Mac (export a .p12 there).';
if (/-> 403/.test(s)) return 'The API key may not manage certificates: it needs the Admin role (Users and Access > Integrations).';
return null;
}
export interface ApiProfile { id: string; attributes: { name?: string; profileType?: string; profileState?: string; expirationDate?: string; uuid?: string; profileContent?: string }; certIds?: string[] }
export const profileName = (bundleId: string, type: ProfileType, date = new Date()): string =>
`storebound ${bundleId} ${type === 'IOS_APP_STORE' ? 'App Store' : type} ${date.toISOString().slice(0, 16).replace('T', ' ')}`;
export interface ProfilePlan { reuse: ApiProfile | null; create: Req | null; why: string }
/** Reuse an ACTIVE profile of the type that holds the certificate and is valid for 14 more days; else create one. */
export function planProfile(existing: ApiProfile[], o: { bundleId: string; bundleIdId: string; certId: string; type: ProfileType; now?: number }): ProfilePlan {
const now = o.now ?? Date.now();
const ok = existing.filter(p => p.attributes.profileType === o.type && p.attributes.profileState === 'ACTIVE'
&& Date.parse(p.attributes.expirationDate ?? '') - now > 14 * 86_400_000 && (p.certIds ?? []).includes(o.certId))
.sort((a, b) => Date.parse(b.attributes.expirationDate!) - Date.parse(a.attributes.expirationDate!));
if (ok[0]) return { reuse: ok[0], create: null, why: `profile "${ok[0].attributes.name}" is active (expires ${ok[0].attributes.expirationDate?.slice(0, 10)})` };
const stale = existing.filter(p => p.attributes.profileType === o.type);
const why = stale.length ? `${stale.length} ${o.type} profile(s), none active with this certificate (states: ${[...new Set(stale.map(p => p.attributes.profileState))].join(', ')})` : `no ${o.type} profile`;
return { reuse: null, why, create: {
method: 'POST', path: '/v1/profiles', note: `create ${o.type} profile for ${o.bundleId}`,
body: { data: { type: 'profiles', attributes: { name: profileName(o.bundleId, o.type, new Date(now)), profileType: o.type },
relationships: { bundleId: one('bundleIds', o.bundleIdId), certificates: many('certificates', [o.certId]) } } },
} };
}
/** Where provisioning profiles are installed: Xcode 16 and later read ~/Library/Developer/Xcode/UserData/Provisioning
* Profiles; older Xcode (and some tools) ~/Library/MobileDevice/Provisioning Profiles. storebound writes both. */
export const profileDirs = (home: string): string[] => [join(home, 'Library/Developer/Xcode/UserData/Provisioning Profiles'), join(home, 'Library/MobileDevice/Provisioning Profiles')];
/** Lines of `security find-identity -v -p codesigning` -> SHA-1 hashes of identities with a private key. */
export function parseIdentities(out: string): { sha1: string; name: string }[] {
return [...out.matchAll(/^\s*\d+\)\s+([0-9A-F]{40})\s+"([^"]+)"/gm)].map(m => ({ sha1: m[1]!, name: m[2]! }));
}
export interface ExportOptionsInput { teamId: string; style: 'automatic' | 'manual'; profiles?: Record<string, string>; method?: string; uploadSymbols?: boolean; certificate?: string }
/** ExportOptions.plist for an App Store Connect export (`method` app-store-connect, Xcode 15.3+; "app-store" is the
* deprecated name). destination export: storebound uploads the IPA itself (`apple upload`), with the build number it
* chose, so Xcode must not change it (manageAppVersionAndBuildNumber false). */
export function exportOptions(i: ExportOptionsInput): Record<string, PlistValue> {
const o: Record<string, PlistValue> = {
method: i.method ?? 'app-store-connect', teamID: i.teamId, signingStyle: i.style, destination: 'export',
uploadSymbols: i.uploadSymbols ?? true, manageAppVersionAndBuildNumber: false,
};
if (i.style === 'manual') {
if (!i.profiles || !Object.keys(i.profiles).length) throw new Error('manual signing needs a provisioning profile per bundle id (storebound apple signing ensure)');
o.provisioningProfiles = { ...i.profiles };
o.signingCertificate = i.certificate ?? 'Apple Distribution';
}
return o;
}

189
cli/lib/xcode.ts Normal file
View file

@ -0,0 +1,189 @@
// Xcode builds without Xcode's UI: find the workspace / project and scheme (native, Capacitor, React Native, Flutter,
// Unity-exported projects), build the xcodebuild archive and export command lines, read an IPA's Info.plist.
// Pure except scanXcode (a bounded directory walk) and ipaInfo (reads the IPA).
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
import { basename, dirname, join, relative } from 'node:path';
import { parsePlist, type PlistValue } from './plist';
import { zipEntries, zipRead } from './zip';
export type Framework = 'flutter' | 'capacitor' | 'react-native' | 'unity' | 'native';
export interface AppleBuildConfig {
/** .xcworkspace (CocoaPods / Flutter / React Native) relative to the config; wins over `project`. */
workspace?: string;
/** .xcodeproj when there is no workspace. */
project?: string;
scheme?: string;
/** Default Release. */
configuration?: string;
/** Output folder for the archive, ExportOptions.plist, the IPA and logs. Default build/ios. */
out?: string;
}
export function validateAppleBuild(b: AppleBuildConfig | undefined): string[] {
if (!b) return [];
const e: string[] = [];
if (b.workspace && !b.workspace.endsWith('.xcworkspace')) e.push('apple.build.workspace: a path ending in .xcworkspace');
if (b.project && !b.project.endsWith('.xcodeproj')) e.push('apple.build.project: a path ending in .xcodeproj');
if (b.scheme !== undefined && !b.scheme.trim()) e.push('apple.build.scheme: empty');
return e;
}
/** What scanXcode found, relative to the project root. */
export interface XcodeScan {
/** Files that tell the framework: pubspec.yaml, capacitor.config.*, package.json with react-native, Unity-iPhone.xcodeproj. */
markers: string[];
workspaces: string[];
projects: string[];
/** Shared scheme names per container (xcshareddata/xcschemes). */
schemes: Record<string, string[]>;
/** Folders with a Podfile and whether Pods/ exists next to it. */
pods: { dir: string; installed: boolean }[];
}
const SKIP_DIRS = new Set(['node_modules', 'Pods', 'build', 'DerivedData', '.git', '.storebound', '.dart_tool', 'Library', 'Temp', '.gradle', 'dist', 'www']);
/** Walks at most `depth` folders deep (default 4) for Xcode containers. */
export function scanXcode(root: string, depth = 4): XcodeScan {
const s: XcodeScan = { markers: [], workspaces: [], projects: [], schemes: {}, pods: [] };
for (const m of ['pubspec.yaml', 'capacitor.config.ts', 'capacitor.config.json', 'capacitor.config.js']) if (existsSync(join(root, m))) s.markers.push(m);
try {
const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
if (pkg.dependencies?.['react-native'] || pkg.devDependencies?.['react-native']) s.markers.push('package.json:react-native');
} catch { /* no package.json */ }
const walk = (dir: string, d: number): void => {
let names: string[];
try { names = readdirSync(dir); } catch { return; }
if (names.includes('Podfile')) s.pods.push({ dir: relative(root, dir) || '.', installed: names.includes('Pods') });
for (const n of names) {
const p = join(dir, n);
if (n.endsWith('.xcworkspace')) { s.workspaces.push(relative(root, p)); continue; }
if (n.endsWith('.xcodeproj')) {
s.projects.push(relative(root, p));
if (n === 'Unity-iPhone.xcodeproj') s.markers.push('Unity-iPhone.xcodeproj');
const sd = join(p, 'xcshareddata', 'xcschemes');
try { s.schemes[relative(root, p)] = readdirSync(sd).filter(f => f.endsWith('.xcscheme')).map(f => f.slice(0, -9)); } catch { /* none shared */ }
continue;
}
if (d <= 0 || n.startsWith('.') || SKIP_DIRS.has(n)) continue;
try { if (statSync(p).isDirectory()) walk(p, d - 1); } catch { /* unreadable */ }
}
};
walk(root, depth);
return s;
}
export interface XcodeTarget { framework: Framework; workspace?: string; project?: string; scheme: string; notes: string[] }
const stem = (p: string): string => basename(p).replace(/\.(xcworkspace|xcodeproj)$/, '');
/** Picks the container and scheme. Config values win; else the framework's usual layout; else the only one found. */
export function pickXcode(scan: XcodeScan, cfg: AppleBuildConfig = {}): XcodeTarget {
const notes: string[] = [];
const has = (m: string) => scan.markers.includes(m);
const framework: Framework = has('pubspec.yaml') ? 'flutter' : scan.markers.some(m => m.startsWith('capacitor.config')) ? 'capacitor'
: has('package.json:react-native') ? 'react-native' : has('Unity-iPhone.xcodeproj') ? 'unity' : 'native';
let workspace = cfg.workspace, project = cfg.project;
if (!workspace && !project) {
const pref: Record<Framework, (string | RegExp)[]> = {
flutter: ['ios/Runner.xcworkspace', 'ios/Runner.xcodeproj'],
capacitor: ['ios/App/App.xcworkspace', 'ios/App/App.xcodeproj'],
'react-native': [/^ios\/[^/]+\.xcworkspace$/, /^ios\/[^/]+\.xcodeproj$/],
unity: [/(^|\/)Unity-iPhone\.xcworkspace$/, /(^|\/)Unity-iPhone\.xcodeproj$/],
native: [],
};
const all = [...scan.workspaces, ...scan.projects];
let hit = pref[framework].map(p => all.find(x => (typeof p === 'string' ? x === p : p.test(x)))).find(Boolean);
if (!hit) {
// a workspace next to a project (CocoaPods) beats the project; a lone container is taken as is
const ws = scan.workspaces.filter(w => !w.includes('.xcodeproj/'));
if (ws.length === 1) hit = ws[0];
else if (!ws.length && scan.projects.length === 1) hit = scan.projects[0];
else if (ws.length + scan.projects.length === 0) throw new Error('no .xcworkspace or .xcodeproj found (set apple.build.workspace or apple.build.project; Flutter: flutter create, Capacitor: npx cap add ios, Unity: Build Settings > iOS > Build)');
else throw new Error(`several Xcode containers (${[...ws, ...scan.projects].slice(0, 6).join(', ')}): set apple.build.workspace or apple.build.project`);
}
if (hit!.endsWith('.xcworkspace')) workspace = hit; else project = hit;
// CocoaPods: the workspace next to the project
if (project) { const w = project.replace(/\.xcodeproj$/, '.xcworkspace'); if (scan.workspaces.includes(w)) { workspace = w; project = undefined; } }
}
const container = (workspace ?? project)!;
const projOf = workspace ? scan.projects.find(p => dirname(p) === dirname(workspace!) && !/^Pods\//.test(basename(p))) : project;
const shared = projOf ? scan.schemes[projOf] ?? [] : [];
const usual: Record<Framework, string | null> = { flutter: 'Runner', capacitor: 'App', 'react-native': null, unity: 'Unity-iPhone', native: null };
const scheme = cfg.scheme ?? usual[framework] ?? (shared.includes(stem(projOf ?? container)) ? stem(projOf ?? container) : shared.length === 1 ? shared[0]! : stem(projOf ?? container));
if (!cfg.scheme && shared.length > 1 && !usual[framework]) notes.push(`several shared schemes (${shared.join(', ')}); using "${scheme}" (set apple.build.scheme to pick another)`);
const podDir = dirname(container);
const pod = scan.pods.find(p => p.dir === podDir || (p.dir === '.' && podDir === '.'));
if (pod && !pod.installed) notes.push(`Podfile without Pods/ in ${pod.dir}: run pod install there first${framework === 'capacitor' ? ' (or npx cap sync ios)' : ''}`);
if (framework === 'capacitor') notes.push('Capacitor: run npx cap sync ios after the web build so the archive has the current web assets');
if (framework === 'flutter') notes.push('Flutter: storebound runs flutter build ios --config-only first (build number and name, Generated.xcconfig)');
if (framework === 'unity') notes.push('Unity: build the Xcode project from Unity (Build Settings > iOS) before each archive; signing team can stay empty in Unity');
return { framework, ...(workspace ? { workspace } : { project }), scheme, notes };
}
export interface AscAuth { keyPath: string; keyId: string; issuerId: string }
const authArgs = (a: AscAuth | null): string[] => (a ? ['-allowProvisioningUpdates', '-authenticationKeyPath', a.keyPath, '-authenticationKeyID', a.keyId, '-authenticationKeyIssuerID', a.issuerId] : []);
export interface ArchiveInput { target: XcodeTarget; root: string; configuration: string; archivePath: string; version?: string; build: string; teamId?: string; auth: AscAuth | null }
/** xcodebuild archive. Version / build go in as build settings (they beat the project's values). */
export function archiveArgs(i: ArchiveInput): string[] {
return ['xcodebuild', ...(i.target.workspace ? ['-workspace', join(i.root, i.target.workspace)] : ['-project', join(i.root, i.target.project!)]),
'-scheme', i.target.scheme, '-configuration', i.configuration, '-destination', 'generic/platform=iOS', '-archivePath', i.archivePath,
...authArgs(i.auth), 'archive', `CURRENT_PROJECT_VERSION=${i.build}`, ...(i.version ? [`MARKETING_VERSION=${i.version}`] : []),
...(i.teamId ? [`DEVELOPMENT_TEAM=${i.teamId}`] : [])];
}
export function exportArgs(archivePath: string, plist: string, exportPath: string, auth: AscAuth | null): string[] {
return ['xcodebuild', '-exportArchive', '-archivePath', archivePath, '-exportOptionsPlist', plist, '-exportPath', exportPath, ...authArgs(auth)];
}
/** flutter build ios --config-only: writes Generated.xcconfig with the build name / number, no build, no signing. */
export const flutterConfigArgs = (build: string, version?: string): string[] =>
['flutter', 'build', 'ios', '--release', '--config-only', '--no-codesign', '--build-number', build, ...(version ? ['--build-name', version] : [])];
/** A command line for logs: the API key path is shown as $ASC_P8. */
export const showCmd = (argv: string[], auth: AscAuth | null): string =>
argv.map(a => (auth && a === auth.keyPath ? '$ASC_P8' : /[\s"'$]/.test(a) ? JSON.stringify(a) : a)).join(' ');
export interface IpaInfo { bundleId: string; version: string; build: string; minOs?: string; name?: string; platform?: string }
/** Bundle id, CFBundleShortVersionString and CFBundleVersion from Payload/<App>.app/Info.plist of an IPA. */
export function ipaInfo(ipa: string | Buffer): IpaInfo {
const e = zipEntries(ipa).find(x => /^Payload\/[^/]+\.app\/Info\.plist$/.test(x.name));
if (!e) throw new Error('not an iOS app archive (no Payload/<App>.app/Info.plist)');
const p = parsePlist(zipRead(ipa, e)) as Record<string, PlistValue>;
const str = (k: string): string | undefined => (typeof p[k] === 'string' ? p[k] as string : undefined);
const bundleId = str('CFBundleIdentifier'), version = str('CFBundleShortVersionString'), build = str('CFBundleVersion');
if (!bundleId || !version || !build) throw new Error('Info.plist without CFBundleIdentifier / CFBundleShortVersionString / CFBundleVersion');
return { bundleId, version, build, minOs: str('MinimumOSVersion'), name: str('CFBundleDisplayName') ?? str('CFBundleName'), platform: (p.CFBundleSupportedPlatforms as string[] | undefined)?.[0] };
}
/** States of an App Store Connect build upload (BuildUploadState) and of a processed build (processingState). */
export const UPLOAD_DONE = new Set(['COMPLETE', 'FAILED']);
export const BUILD_DONE = new Set(['VALID', 'INVALID', 'FAILED']);
/** Requests of an App Store Connect API build upload (Build Uploads, API 4.1): the upload, then the file reservation. */
export function buildUploadReqs(appId: string, info: IpaInfo, fileName: string, fileSize: number) {
return {
upload: { method: 'POST' as const, path: '/v1/buildUploads', note: `build ${info.build} (${info.version})`,
body: { data: { type: 'buildUploads', attributes: { cfBundleShortVersionString: info.version, cfBundleVersion: info.build, platform: 'IOS' },
relationships: { app: { data: { type: 'apps', id: appId } } } } } },
file: (uploadId: string) => ({ method: 'POST' as const, path: '/v1/buildUploadFiles', note: `${fileName} (${(fileSize / 1048576).toFixed(1)} MB)`,
body: { data: { type: 'buildUploadFiles', attributes: { assetType: 'ASSET', fileName, fileSize, uti: 'com.apple.ipa' },
relationships: { buildUpload: { data: { type: 'buildUploads', id: uploadId } } } } } }),
commit: (fileId: string, md5: string) => ({ method: 'PATCH' as const, path: `/v1/buildUploadFiles/${fileId}`, note: 'commit',
body: { data: { type: 'buildUploadFiles', id: fileId, attributes: { uploaded: true, sourceFileChecksums: { file: { hash: md5, algorithm: 'MD5' } } } } } }),
};
}
/** altool upload (Xcode's command line uploader) with the API key. */
export const altoolArgs = (ipa: string, auth: AscAuth): string[] =>
['xcrun', 'altool', '--upload-package', ipa, '--api-key', auth.keyId, '--api-issuer', auth.issuerId, '--p8-file-path', auth.keyPath, '--output-format', 'json'];
/** Errors and warnings of a build upload's state (StateDetail: code, message). */
export function uploadProblems(state: { errors?: { code?: string; message?: string; description?: string }[]; warnings?: { code?: string; message?: string; description?: string }[] } | undefined): { errors: string[]; warnings: string[] } {
const f = (x: { code?: string; message?: string; description?: string }) => [x.code, x.message ?? x.description].filter(Boolean).join(': ');
return { errors: (state?.errors ?? []).map(f), warnings: (state?.warnings ?? []).map(f) };
}

52
cli/lib/zip.ts Normal file
View file

@ -0,0 +1,52 @@
// Reads entries of a ZIP archive (an .ipa) without dependencies: the central directory, then one entry, stored or
// deflated (node:zlib). Enough to read Payload/<App>.app/Info.plist; ZIP64 archives (> 4 GB) are not supported.
import { closeSync, fstatSync, openSync, readSync } from 'node:fs';
import { inflateRawSync } from 'node:zlib';
export interface ZipEntry { name: string; method: number; compressedSize: number; size: number; localOffset: number }
function readAt(fd: number, pos: number, len: number): Buffer {
const b = Buffer.alloc(len);
const n = readSync(fd, b, 0, len, pos);
return b.subarray(0, n);
}
/** Entries of the central directory of a ZIP file (path) or buffer. */
export function zipEntries(src: string | Buffer): ZipEntry[] {
const fd = typeof src === 'string' ? openSync(src, 'r') : -1;
try {
const size = fd >= 0 ? fstatSync(fd).size : (src as Buffer).length;
const read = (pos: number, len: number): Buffer => (fd >= 0 ? readAt(fd, pos, len) : (src as Buffer).subarray(pos, pos + len));
const tailLen = Math.min(size, 65_557);
const tail = read(size - tailLen, tailLen);
let eocd = -1;
for (let i = tail.length - 22; i >= 0; i--) if (tail.readUInt32LE(i) === 0x06054b50) { eocd = i; break; }
if (eocd < 0) throw new Error('not a ZIP archive (no end of central directory)');
const count = tail.readUInt16LE(eocd + 10), cdSize = tail.readUInt32LE(eocd + 12), cdOff = tail.readUInt32LE(eocd + 16);
if (cdOff === 0xffffffff) throw new Error('ZIP64 archives are not supported');
const cd = read(cdOff, cdSize);
const out: ZipEntry[] = [];
for (let p = 0, k = 0; k < count && p + 46 <= cd.length; k++) {
if (cd.readUInt32LE(p) !== 0x02014b50) throw new Error('ZIP: bad central directory entry');
const nameLen = cd.readUInt16LE(p + 28), extraLen = cd.readUInt16LE(p + 30), commentLen = cd.readUInt16LE(p + 32);
out.push({ name: cd.subarray(p + 46, p + 46 + nameLen).toString('utf8'), method: cd.readUInt16LE(p + 10),
compressedSize: cd.readUInt32LE(p + 20), size: cd.readUInt32LE(p + 24), localOffset: cd.readUInt32LE(p + 42) });
p += 46 + nameLen + extraLen + commentLen;
}
return out;
} finally { if (fd >= 0) closeSync(fd); }
}
/** The uncompressed bytes of one entry. */
export function zipRead(src: string | Buffer, e: ZipEntry): Buffer {
const fd = typeof src === 'string' ? openSync(src, 'r') : -1;
try {
const read = (pos: number, len: number): Buffer => (fd >= 0 ? readAt(fd, pos, len) : (src as Buffer).subarray(pos, pos + len));
const h = read(e.localOffset, 30);
if (h.readUInt32LE(0) !== 0x04034b50) throw new Error(`ZIP: bad local header for ${e.name}`);
const data = read(e.localOffset + 30 + h.readUInt16LE(26) + h.readUInt16LE(28), e.compressedSize);
if (e.method === 0) return Buffer.from(data);
if (e.method === 8) return inflateRawSync(data);
throw new Error(`ZIP: compression method ${e.method} not supported (${e.name})`);
} finally { if (fd >= 0) closeSync(fd); }
}

View file

@ -91,6 +91,14 @@ export const TOOLS: ToolDef[] = [
description: 'Read-only App Store Connect overview: versions and their states, recent builds, in-app purchases, review submissions.' }, description: 'Read-only App Store Connect overview: versions and their states, recent builds, in-app purchases, review submissions.' },
{ name: 'apple_next_build', title: 'Next iOS build number', command: ['apple', 'next-build'], write: false, network: true, { name: 'apple_next_build', title: 'Next iOS build number', command: ['apple', 'next-build'], write: false, network: true,
description: 'Next safe CFBundleVersion: one above every build uploaded for the app.' }, description: 'Next safe CFBundleVersion: one above every build uploaded for the app.' },
{ name: 'apple_signing_status', title: 'Code signing status', command: ['apple', 'signing', 'status'], write: false, network: true,
description: 'Read-only signing overview from App Store Connect: bundle id capabilities vs apple.signing.capabilities, distribution certificates (and whether this machine holds a private key for one), App Store provisioning profiles per bundle id and whether they are installed for Xcode. Creating certificates and profiles stays a terminal command (apple signing ensure, asks first).',
args: () => ['--json'] },
{ name: 'originality', title: 'Originality check (Guideline 4.3)', command: ['originality'], write: false, network: false,
description: 'Offline comparison of this app with the owner\'s other apps (folders with a storebound.config.ts): listing text, name, icon and screenshot perceptual hashes, project structure. Scores per axis, overall, near-duplicate flags and suggestions; exit 1 when a pair is flagged. Pair with the portfolio-originality skill.',
props: { against: { type: 'string', description: 'Comma-separated folders of the other apps, or a folder holding several (default: originality.against in the config)' },
threshold: { type: 'number', minimum: 0.05, maximum: 0.95, description: 'Overall score that counts as a near-duplicate (default 0.7)' } },
args: i => ['--json', ...opt('against', i.against), ...opt('threshold', i.threshold)] },
{ name: 'play_status', title: 'Google Play status', command: ['play', 'status'], write: false, network: true, { name: 'play_status', title: 'Google Play status', command: ['play', 'status'], write: false, network: true,
description: 'Read-only Play overview: tracks and releases (with rollout fraction), listing languages, one-time products.' }, description: 'Read-only Play overview: tracks and releases (with rollout fraction), listing languages, one-time products.' },
{ name: 'play_next_version_code', title: 'Next Play versionCode', command: ['play', 'next-version-code'], write: false, network: true, { name: 'play_next_version_code', title: 'Next Play versionCode', command: ['play', 'next-version-code'], write: false, network: true,

53
cli/originality.ts Normal file
View file

@ -0,0 +1,53 @@
// Originality check (App Store Guideline 4.3, Google Play repetitive content) against the owner's other apps. Offline.
// storebound originality [--against <folder>[,<folder>]] [--threshold 0.7] [--json]
// --against (or originality.against in the config): folders with a storebound.config.ts, or workspace folders that
// hold several apps one level down. Per other app: listing text, name, icon and screenshot perceptual hashes, project
// structure (file layout and identical files), an overall score, why a pair is flagged, and what to change.
// Exit 1 when a pair is flagged as a near-duplicate. The scoring is in cli/lib/originality.ts; the judgement
// (mechanic, content, differentiator sentence) is the portfolio-originality skill.
import { realpathSync } from 'node:fs';
import { relative } from 'node:path';
import { loadConfig } from './lib/config';
import type { Ctx } from './lib/ctx';
import { done, log, printJson, warn } from './lib/log';
import { DEFAULT_THRESHOLD, findApps, fingerprint, report } from './lib/originality';
import { textTable } from './lib/table';
const TAG = 'originality';
export async function run(ctx: Ctx): Promise<void> {
const { config, root, resolve } = ctx.loaded;
const a = ctx.args;
const folders = (a.list('against').length ? a.list('against') : config.originality?.against ?? []).map(f => resolve(f));
if (!folders.length) throw new Error('nothing to compare with: --against <folder of another app, or a folder holding several> (or originality.against in the config)');
const threshold = a.has('threshold') ? a.num('threshold', DEFAULT_THRESHOLD) : config.originality?.threshold ?? DEFAULT_THRESHOLD;
if (!(threshold > 0 && threshold < 1)) throw new Error('--threshold: between 0 and 1');
const self = realpathSync(root);
const configs = findApps(folders.map(f => { try { return realpathSync(f); } catch { return f; } }), self);
if (!configs.length) throw new Error(`no other app (storebound.config.ts) in ${folders.map(f => relative(root, f) || '.').join(', ')}`);
const json = a.has('json');
if (!json) log(TAG, `${config.app.name} vs ${configs.length} app(s), offline`);
const me = fingerprint(config, root);
const others = [];
for (const p of configs) {
try {
const l = await loadConfig(p);
others.push(fingerprint(l.config, l.root));
} catch (e) { warn(TAG, `${p}: skipped (${(e as Error).message.split('\n')[0]?.slice(0, 160)})`); }
}
const r = report(me, others, threshold);
if (json) { printJson(r); if (r.flagged) process.exitCode = 1; return; }
for (const n of me.notes) warn(TAG, `${config.app.name}: ${n}`);
const pct = (x: number | null) => (x === null ? '-' : `${Math.round(x * 100)}%`);
console.log(textTable(['app', 'overall', 'name', 'text', 'icon', 'screens', 'structure', ''], r.pairs.map(p =>
[p.other.name, pct(p.overall), pct(p.axes.name.score), pct(p.axes.text.score), pct(p.axes.icon.score), pct(p.axes.screenshots.score), pct(p.axes.structure.score), p.flagged ? 'NEAR-DUPLICATE' : ''])));
for (const p of r.pairs) {
if (!p.flagged && !p.suggestions.length) continue;
console.log(`\n${p.other.name} (${relative(root, p.other.dir) || '.'})${p.flagged ? ': flagged' : ''}`);
for (const why of p.reasons) console.log(` - ${why}`);
for (const s of p.suggestions) console.log(` > ${s}`);
}
for (const o of r.others) for (const n of o.notes) log(TAG, `${relative(root, o.dir) || '.'}: ${n}`);
if (r.flagged) { warn(TAG, `${r.flagged} near-duplicate(s) at threshold ${threshold}: see the portfolio-originality skill before submitting`); process.exitCode = 1; }
done(TAG, `${r.pairs.length} pair(s) compared, ${r.flagged} flagged`);
}

91
cli/play/build.ts Normal file
View file

@ -0,0 +1,91 @@
// Build a signed release Android App Bundle.
// storebound play build [--version-code N] [--version-name 1.2.0] [--flavor prod] [--dir android] [--module app]
// [--out build/android] [--dry] [--json]
// Finds the Gradle project (android/ of Capacitor, React Native and Flutter apps, the root of a native one, a Unity
// export with launcher/ + unityLibrary/), takes the next free versionCode from Google Play (play next-version-code)
// unless --version-code is given, runs `gradlew :app:bundleRelease` (Flutter: flutter build appbundle) and copies the
// AAB to <out>/<package>-<versionCode>.aab, checked by reading its manifest. Signing: the upload key from env or
// .storebound/credentials.json (ANDROID_KEYSTORE, ANDROID_KEYSTORE_PASSWORD, ANDROID_KEY_ALIAS, ANDROID_KEY_PASSWORD)
// goes to Gradle as injected signing properties through the environment, never on the command line; without it the
// project's own signingConfig signs. Local only: Play is only read (version codes).
import { copyFileSync, existsSync, mkdirSync, writeFileSync } from 'node:fs';
import { join, relative } from 'node:path';
import { androidSigning } from '../lib/credentials';
import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx';
import { done, log, printJson, warn } from '../lib/log';
import { pump } from '../lib/runner';
import { aabInfo, findBundles, gradleArgs, pickGradle, signingEnv } from '../lib/gradle';
import { nextVersionCode } from '../lib/release';
import { playClient } from './client';
import { usedVersionCodes } from './next-version-code';
const TAG = 'build';
export async function run(ctx: Ctx): Promise<void> {
const { config, root, resolve } = ctx.loaded;
const a = ctx.args;
const pkg = need(config.play?.packageName, 'play.packageName');
const cfg = config.play?.build ?? {};
const flavor = a.get('flavor') ?? cfg.flavor;
const t = pickGradle(root, { dir: a.get('dir') ?? cfg.dir, module: a.get('module') ?? cfg.module, flavor });
const dry = a.has('dry');
const json = a.has('json');
const out = resolve(a.get('out') ?? 'build/android');
let code = a.has('version-code') ? a.num('version-code', 0) : 0;
if (a.has('version-code') && !(Number.isInteger(code) && code > 0 && code <= 2_100_000_000)) throw new Error('--version-code: 1-2100000000');
if (!code) {
try {
const play = await playClient(root, pkg);
code = await play.read(async id => nextVersionCode(await usedVersionCodes(play, id)));
log(TAG, `next free versionCode on Google Play: ${code}`);
} catch (e) {
if (!dry) throw new Error(`${(e as Error).message}\n(pass --version-code N to build without reading Google Play)`);
warn(TAG, `Google Play not readable (${(e as Error).message.split('\n')[0]?.slice(0, 120)}): dry run continues without a versionCode`);
}
}
const versionName = a.get('version-name');
const signing = androidSigning(root);
const hasWrapper = existsSync(join(t.dir, 'gradlew'));
const argv = gradleArgs(t, { versionCode: code || undefined, versionName, flavor, hasWrapper });
const cwd = t.framework === 'flutter' ? root : t.dir;
const plan = { framework: t.framework, dir: relative(root, t.dir) || '.', module: t.module, task: t.framework === 'flutter' ? 'flutter build appbundle' : t.task,
versionCode: code || null, versionName: versionName ?? null, signing: signing ? `upload key from ${process.env.ANDROID_KEYSTORE ? 'env' : '.storebound/credentials.json'} (alias ${signing.keyAlias})` : 'the project\'s own signingConfig',
command: argv.join(' '), out: relative(root, out) || '.', notes: t.notes };
if (dry) {
if (json) { printJson(plan); return; }
log(TAG, `${t.framework}: ${plan.dir} ${plan.task}, versionCode ${code || '?'}${versionName ? `, versionName ${versionName}` : ''}`);
log(TAG, `signing: ${plan.signing}`);
for (const n of t.notes) log(TAG, n);
log(TAG, `would run (in ${relative(root, cwd) || '.'}): ${plan.command}`);
done(TAG, 'build planned (dry run)');
return;
}
if (signing && !existsSync(signing.storeFile)) throw new Error('ANDROID_KEYSTORE: the keystore file does not exist');
if (!signing) warn(TAG, 'no ANDROID_KEYSTORE: the project\'s own release signingConfig must sign, else Play refuses the bundle');
for (const n of t.notes) log(TAG, n);
log(TAG, `$ ${plan.command}`);
const started = Date.now();
mkdirSync(out, { recursive: true });
const p = Bun.spawn(argv, { cwd, stdout: 'pipe', stderr: 'pipe', env: { ...process.env, ...signingEnv(signing) } });
const lines: string[] = [];
const each = (line: string): void => {
lines.push(line);
if (/^(> Task .*bundle|BUILD (SUCCESSFUL|FAILED)|FAILURE:|\* What went wrong|e: |error:|✓ Built)/.test(line)) log(TAG, line.trim().slice(0, 300));
};
await Promise.all([pump(p.stdout, 'stdout', each), pump(p.stderr, 'stderr', each)]);
const exit = await p.exited;
const logFile = join(out, 'gradle.log');
writeFileSync(logFile, lines.join('\n'));
if (exit !== 0) throw new Error(`build failed (exit ${exit}); last lines:\n${lines.slice(-20).join('\n')}\nfull log: ${relative(root, logFile)}`);
const aab = findBundles([join(t.dir, t.module, 'build', 'outputs', 'bundle'), join(root, 'build', 'app', 'outputs', 'bundle')], started - 1000)[0];
if (!aab) throw new Error(`build finished but no new .aab under ${relative(root, t.dir)}/${t.module}/build/outputs/bundle`);
const info = aabInfo(aab);
if (info.packageName !== pkg) warn(TAG, `the AAB's package is ${info.packageName}, the config says ${pkg}`);
if (code && info.versionCode !== code) warn(TAG, `the AAB has versionCode ${info.versionCode}, not ${code}: the build file sets it itself; read -PversionCode there or pass that number to play upload knowingly`);
const dest = join(out, `${info.packageName}-${info.versionCode}.aab`);
copyFileSync(aab, dest);
const result = { aab: dest, packageName: info.packageName, versionCode: info.versionCode, versionName: info.versionName ?? null };
if (json) printJson(result);
done(TAG, `${relative(root, dest)}: ${info.packageName} ${info.versionName ?? ''} (${info.versionCode}). Next: storebound play upload ${relative(root, dest)} --track internal --dry`);
}

View file

@ -6,16 +6,21 @@ import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx'; import { need } from '../lib/ctx';
import { printJson } from '../lib/log'; import { printJson } from '../lib/log';
import { nextVersionCode } from '../lib/release'; import { nextVersionCode } from '../lib/release';
import { playClient } from './client'; import { type PlayClient, playClient } from './client';
/** Every versionCode Play knows for the app: uploaded bundles and APKs, and the codes on every track (read-only edit). */
export async function usedVersionCodes(play: PlayClient, id: string): Promise<number[]> {
const bundles = (await play.call<{ bundles?: { versionCode: number }[] }>('GET', `${play.API}/edits/${id}/bundles`)).bundles ?? [];
const apks = (await play.call<{ apks?: { versionCode: number }[] }>('GET', `${play.API}/edits/${id}/apks`).catch(() => ({ apks: [] }))).apks ?? [];
const tracks = (await play.call<{ tracks?: { releases?: { versionCodes?: string[] }[] }[] }>('GET', `${play.API}/edits/${id}/tracks`)).tracks ?? [];
return [...bundles.map(b => b.versionCode), ...apks.map(a => a.versionCode), ...tracks.flatMap(t => (t.releases ?? []).flatMap(r => (r.versionCodes ?? []).map(Number)))];
}
export async function run(ctx: Ctx): Promise<void> { export async function run(ctx: Ctx): Promise<void> {
const { config, root } = ctx.loaded; const { config, root } = ctx.loaded;
const play = await playClient(root, need(config.play?.packageName, 'play.packageName')); const play = await playClient(root, need(config.play?.packageName, 'play.packageName'));
await play.read(async id => { await play.read(async id => {
const bundles = (await play.call<{ bundles?: { versionCode: number }[] }>('GET', `${play.API}/edits/${id}/bundles`)).bundles ?? []; const codes = await usedVersionCodes(play, id);
const apks = (await play.call<{ apks?: { versionCode: number }[] }>('GET', `${play.API}/edits/${id}/apks`).catch(() => ({ apks: [] }))).apks ?? [];
const tracks = (await play.call<{ tracks?: { releases?: { versionCodes?: string[] }[] }[] }>('GET', `${play.API}/edits/${id}/tracks`)).tracks ?? [];
const codes = [...bundles.map(b => b.versionCode), ...apks.map(a => a.versionCode), ...tracks.flatMap(t => (t.releases ?? []).flatMap(r => r.versionCodes ?? []))];
// the same code is in the bundle list and on every track it was released to: count distinct codes // the same code is in the bundle list and on every track it was released to: count distinct codes
const distinct = new Set(codes.map(String)).size; const distinct = new Set(codes.map(String)).size;
if (ctx.args.has('json')) printJson({ next: nextVersionCode(codes), seen: distinct }); if (ctx.args.has('json')) printJson({ next: nextVersionCode(codes), seen: distinct });

78
cli/play/upload.ts Normal file
View file

@ -0,0 +1,78 @@
// Upload an Android App Bundle to a Google Play testing track.
// storebound play upload [<app.aab>] [--track internal|alpha|beta] [--status completed|draft] [--name text] [--dry] [--yes] [--json]
// Default AAB: the newest in build/android (storebound play build). Package and versionCode are read from the bundle;
// the upload is refused when Play already has that versionCode. Release notes: the "What's new" of every listing
// language. --dry is read-only (one throwaway edit: version codes and the track are read, the edit is deleted).
// A real run asks first (--yes in scripts). Production is not offered here: `storebound play release --production
// draft` (and the play-first-release / release-management skills) keep that the owner's step.
import { readdirSync, readFileSync, statSync } from 'node:fs';
import { join, relative } from 'node:path';
import type { Ctx } from '../lib/ctx';
import { confirm, need } from '../lib/ctx';
import { aabInfo } from '../lib/gradle';
import { done, log, printJson } from '../lib/log';
import { nextVersionCode } from '../lib/release';
import { playClient } from './client';
import { readPlayCopy } from './listing';
import { usedVersionCodes } from './next-version-code';
const TAG = 'upload';
export const UPLOAD_TRACKS = ['internal', 'alpha', 'beta'] as const;
export async function run(ctx: Ctx): Promise<void> {
const { config, root, resolve } = ctx.loaded;
const a = ctx.args;
const pkg = need(config.play?.packageName, 'play.packageName');
const track = a.str('track', 'internal');
if (track === 'production') throw new Error('play upload is for testing tracks; production goes through storebound play release --production draft (the owner sends it)');
if (!(UPLOAD_TRACKS as readonly string[]).includes(track)) throw new Error(`--track: ${UPLOAD_TRACKS.join(' | ')}`);
const status = a.str('status', 'completed');
if (!['completed', 'draft'].includes(status)) throw new Error('--status: completed | draft');
let aab = a._.find(x => x.endsWith('.aab'));
if (aab) aab = resolve(aab);
else {
const dir = resolve('build/android');
let found: string[] = [];
try { found = readdirSync(dir).filter(f => f.endsWith('.aab')).map(f => join(dir, f)).sort((x, y) => statSync(y).mtimeMs - statSync(x).mtimeMs); } catch { /* none */ }
if (!found[0]) throw new Error('usage: storebound play upload <app.aab> --track internal (nothing in build/android; storebound play build makes one)');
aab = found[0];
}
const info = aabInfo(aab);
if (info.packageName !== pkg) throw new Error(`${relative(root, aab)} is ${info.packageName}, the config says ${pkg}`);
const size = statSync(aab).size;
const dry = a.has('dry');
const json = a.has('json');
const notes = readPlayCopy(ctx).filter(c => c.whatsNew).map(c => ({ language: c.lang, text: c.whatsNew }));
const play = await playClient(root, pkg);
const { used, current } = await play.read(async id => ({
used: await usedVersionCodes(play, id),
current: (await play.call<{ releases?: { status: string; versionCodes?: string[] }[] }>('GET', `${play.API}/edits/${id}/tracks/${track}`).catch(() => ({ releases: [] }))).releases ?? [],
}));
if (used.includes(info.versionCode)) throw new Error(`versionCode ${info.versionCode} is already on Google Play: rebuild with --version-code ${nextVersionCode(used)} (storebound play build)`);
const summary = { aab: relative(root, aab), packageName: info.packageName, versionCode: info.versionCode, versionName: info.versionName ?? null, sizeMB: Math.round(size / 104857.6) / 10,
track, status, notes: notes.map(n => n.language), replaces: current.map(r => `${r.status} ${(r.versionCodes ?? []).join(',')}`) };
if (dry) {
if (json) { printJson(summary); return; }
log(TAG, `${summary.aab}: ${info.packageName} ${info.versionName ?? ''} (${info.versionCode}), ${summary.sizeMB} MB, versionCode free`);
log(TAG, `would upload it and set track ${track} to ${status} ${info.versionCode}${notes.length ? `, notes in ${notes.length} language(s)` : ', no release notes'}${current.length ? ` (now on ${track}: ${summary.replaces.join('; ')})` : ''}`);
done(TAG, 'upload planned (dry run, read-only)');
return;
}
if (!(await confirm(ctx, `Upload ${info.packageName} versionCode ${info.versionCode} and put it on the ${track} track (${status})? Testers of that track get it.`))) return;
try {
await play.edit(async id => {
log(TAG, `uploading ${summary.sizeMB} MB, this can take minutes`);
const b = await play.call<{ versionCode: number }>('POST', `${play.UPLOAD}/edits/${id}/bundles?uploadType=media`, new Uint8Array(readFileSync(aab!)), { 'Content-Type': 'application/octet-stream' });
log(TAG, `uploaded versionCode ${b.versionCode}`);
const release: Record<string, unknown> = { versionCodes: [String(b.versionCode)], status, ...(notes.length ? { releaseNotes: notes } : {}), ...(a.get('name') ? { name: a.get('name') } : {}) };
await play.call('PUT', `${play.API}/edits/${id}/tracks/${track}`, { track, releases: [release] });
log(TAG, `${track} <- ${b.versionCode} (${status})`);
}, { retries: 0 });
} catch (e) {
if (/draft app|status draft/i.test(String(e)) && status !== 'draft')
throw new Error(`${(e as Error).message}\n\nThis app has never been published: Play only takes draft releases. Re-run with --status draft and roll it out from the Console (skill play-first-release).`);
throw e;
}
if (json) printJson({ ...summary, uploaded: true });
done(TAG, `versionCode ${info.versionCode} on ${track}`);
}

View file

@ -1,6 +1,6 @@
--- ---
name: appstore-first-release name: appstore-first-release
description: Step-by-step first (and later) App Store release of a mobile app or game - App Store Connect API key, bundle id, app record, signing and xcodebuild archive/upload with the API key, TestFlight, version + listing text in many locales, screenshots, age rating, App Privacy, review details, in-app purchases with the first version, and submitting for review. Use when the user wants to publish, release, upload or set up an iOS app or game on the App Store or TestFlight, or hits App Store Connect API errors. description: Step-by-step first (and later) App Store release of a mobile app or game - App Store Connect API key, bundle id, app record, signing, build and upload with the API key (apple signing, apple build, apple upload), TestFlight, version + listing text in many locales, screenshots, age rating, App Privacy, review details, in-app purchases with the first version, and submitting for review. Use when the user wants to publish, release, upload or set up an iOS app or game on the App Store or TestFlight, or hits App Store Connect API errors.
--- ---
# App Store: first release # App Store: first release
@ -24,17 +24,18 @@ of a first version is the owner's click. Shared agent rules: `docs/agents-core.m
4. **Local · Info.plist.** `ITSAppUsesNonExemptEncryption` with the true answer (`export-compliance` skill; `NO` only 4. **Local · Info.plist.** `ITSAppUsesNonExemptEncryption` with the true answer (`export-compliance` skill; `NO` only
when the app uses nothing beyond OS / HTTPS encryption) so builds arrive answered; when the app uses nothing beyond OS / HTTPS encryption) so builds arrive answered;
`NSUserTrackingUsageDescription` if ads use the IDFA; privacy policy reachable inside the app (guideline 5.1.1). `NSUserTrackingUsageDescription` if ads use the IDFA; privacy policy reachable inside the app (guideline 5.1.1).
5. **Local · Build + upload** (Mac, no Xcode account login needed, the API key does signing): 5. **Local · Sign, build + upload** (Mac with Xcode; the API key signs, no Xcode account login needed). Details and
the manual-signing route: `build-and-sign` skill.
```sh ```sh
K="-allowProvisioningUpdates -authenticationKeyPath $ASC_P8 -authenticationKeyID $ASC_KEY_ID -authenticationKeyIssuerID $ASC_ISSUER_ID" storebound apple signing status # capabilities, certificate with a key on this Mac, profiles
xcodebuild -project ios/App/App.xcodeproj -scheme App -configuration Release -destination generic/platform=iOS \ storebound apple build --version 1.0.0 --dry # project + scheme found, next build number, ExportOptions.plist
-archivePath build/App.xcarchive MARKETING_VERSION=1.0.0 CURRENT_PROJECT_VERSION=3 $K archive storebound apple build --version 1.0.0 # xcodebuild archive + exportArchive -> build/ios/export/*.ipa
xcodebuild -exportArchive -archivePath build/App.xcarchive -exportOptionsPlist ExportOptions.plist -exportPath build/export $K storebound apple upload --dry # then without --dry (asks): API build upload, waits for VALID
``` ```
ExportOptions.plist: `method` app-store-connect, `destination` upload, `teamID` <your team>, `signingStyle` `apple build` takes the build number from `storebound apple next-build` unless `--build-number N` is given, and
automatic. `MARKETING_VERSION` / `CURRENT_PROJECT_VERSION` overrides beat the project values. Take the build prints it at the end: **note it**, every later step selects that exact build, never "the latest". The generated
number from `storebound apple next-build` right before archiving and **note it**: every later step selects that ExportOptions.plist uses `method` app-store-connect, `destination` export, your team and the signing style of
exact build, never "the latest". Processing takes 5-30 min (`storebound apple status` shows VALID). `apple.signing.style` (automatic by default). Processing takes 5-30 min; `apple upload` waits for it.
6. **API · TestFlight.** Put an internal group with `allBuilds: true` in `apple.testflight.groups` and run 6. **API · TestFlight.** Put an internal group with `allBuilds: true` in `apple.testflight.groups` and run
`storebound apple testflight groups`: every new build reaches the team automatically. External testers, What to `storebound apple testflight groups`: every new build reaches the team automatically. External testers, What to
Test, Test Information and Beta App Review: the testflight skill. Sandbox testers stay UI: Users and Access > Sandbox. Test, Test Information and Beta App Review: the testflight skill. Sandbox testers stay UI: Users and Access > Sandbox.

View file

@ -0,0 +1,92 @@
---
name: build-and-sign
description: Sign, build and upload a mobile app or game from the terminal - App Store Connect API signing (bundle id capabilities, distribution certificate, provisioning profiles), xcodebuild archive and export with a generated ExportOptions.plist, IPA upload through the App Store Connect API or altool with processing wait, and the Android counterpart (Gradle bundleRelease with the upload key, AAB to a testing track). Native, Capacitor, React Native, Flutter and Unity-exported projects. Use when the user wants to build, sign, archive, export, upload or ship a new build, hits code signing or provisioning errors, or needs a build number / versionCode.
---
# Build, sign and upload
The CLI is `storebound` (`storebound help`). Credentials only from env or `.storebound/credentials.json`
(gitignored): `ASC_KEY_ID`, `ASC_ISSUER_ID`, `ASC_P8` (Admin key for signing), `PLAY_SERVICE_ACCOUNT`, and the
Android upload key `ANDROID_KEYSTORE`, `ANDROID_KEYSTORE_PASSWORD`, `ANDROID_KEY_ALIAS`, `ANDROID_KEY_PASSWORD`.
Never ask for them in chat, never print them. Shared agent rules: `docs/agents-core.md`.
**Every write is dry first, then asks.** Certificates, profiles and uploads change the owner's developer account:
show the `--dry` output, run it for real only after a clear yes (the command asks again in the terminal; `--yes` only
when the owner said so for this run). The MCP server offers only `apple_signing_status` (read-only) from this skill.
## iOS
1. **Read.** `storebound apple signing status`: is the bundle id registered (else `storebound apple bundle`), which
capabilities it has vs `apple.signing.capabilities`, the distribution certificates of the team and whether this
Mac holds a private key for one (a key file in `.storebound/signing/` or an identity in the keychain), App Store
profiles per bundle id (app + `apple.signing.extraBundleIds` for extensions) and whether Xcode has them installed.
2. **Pick the style.** `apple.signing.style`:
- `automatic` (default): `xcodebuild -allowProvisioningUpdates` with the API key creates and fetches what it needs.
Nothing to do in step 3 unless capabilities are missing. Easiest for one developer on one Mac.
- `manual`: certificate and profiles from step 3, named in ExportOptions.plist. Best for CI and teams; set the app
target to manual signing with the installed profile in Xcode (Signing & Capabilities) once.
3. **Ensure.** `storebound apple signing ensure --dry`, show it, then without `--dry` after a yes:
- adds missing capabilities (never removes one; extra ones are only reported). Adding a capability makes existing
profiles invalid: `ensure` creates new ones in the same run.
- creates an Apple Distribution certificate only when no valid one has its key on this machine. The RSA key is made
locally, kept 0600 in `.storebound/signing/<id>.key` next to `<id>.cer`; it is never printed and never leaves the
machine. `--keychain` imports both into the login keychain (or `--keychain <path>`) so xcodebuild can sign.
Back the key up (encrypted). Apple allows 3 distribution certificates per team: at the limit, revoking one is
the owner's decision (developer.apple.com > Certificates).
- Developer ID certificates (Mac apps outside the App Store): only the **Account Holder** can create them; the API
answers 403 for every other key, and storebound says so. The Account Holder makes it in Xcode > Settings >
Accounts > Manage Certificates and exports a .p12.
- creates or reuses an App Store profile per bundle id and installs it into
`~/Library/Developer/Xcode/UserData/Provisioning Profiles` (Xcode 16+) and `~/Library/MobileDevice/Provisioning
Profiles` (older Xcode). `--no-install` skips that.
4. **Build.** `storebound apple build --dry --version 1.4.0` shows the project it found (Capacitor `ios/App`, React
Native `ios/<Name>.xcworkspace`, Flutter `ios/Runner`, Unity `Unity-iPhone`, or `apple.build.workspace` /
`project` / `scheme`), the build number (next free one from App Store Connect, or `--build-number N`), the
ExportOptions.plist (`method` app-store-connect, `destination` export, team, style, profiles) and both xcodebuild
commands. Then run it without `--dry` (minutes; full logs in `build/ios/xcodebuild-*.log`). It ends with the IPA
path, version and build. **Note the build number**: later steps use exactly it.
- Capacitor: `npx cap sync ios` after the web build first. React Native / CocoaPods: `pod install` first (the dry
run warns when Pods/ is missing). Flutter: storebound runs `flutter build ios --config-only` with the build
number. Unity: build the Xcode project from Unity first.
- Capacitor needs a UTF-8 locale; storebound sets `LANG` / `LC_ALL` for xcodebuild.
5. **Upload.** `storebound apple upload --dry` (default: the newest IPA in `build/ios/export`): bundle id, version,
build, and a refusal when that build number is already on App Store Connect. Then without `--dry` after a yes. Default
`--via api` is the App Store Connect API build upload (Build Uploads: reserve, upload the parts, commit with the
MD5, poll the upload state; any OS). `--via altool` uses `xcrun altool --upload-package` with the API key. Apple
lists both (and Xcode / Transporter); neither is deprecated. storebound then waits until the build is VALID
(exit 0), INVALID / FAILED (exit 1, Apple emails the ITMS reason) or `--timeout` (default 60m, exit 7). Run long
uploads in the background with a log: `storebound apple upload --yes > .storebound/upload.log 2>&1 &` (only
after the owner's yes).
6. **Next.** `storebound apple encryption --build N`, `storebound apple testflight distribute --build N --group Team
--dry` (`testflight` skill), `storebound apple listing --version x.y.z --build N` (`appstore-first-release`).
## Android
1. **Upload key.** Generate once (`keytool -genkeypair -v -storetype PKCS12 -keystore upload.p12 -alias upload
-keyalg RSA -keysize 4096 -validity 10950`), keep it outside git, put the four `ANDROID_*` values in env or
`.storebound/credentials.json`. storebound hands them to Gradle as injected signing properties through the
environment, never on the command line. Without them the project's own `signingConfigs.release` signs (e.g.
Flutter's `key.properties`).
2. **Build.** `storebound play build --dry` shows the Gradle project (`android/` for Capacitor, React Native and
Flutter, the root for native, a Unity export with `launcher/` + `unityLibrary/`; or `play.build.dir` / `module` /
`flavor`), the task (`:app:bundleRelease`; Flutter: `flutter build appbundle`), the next free versionCode from Play
(or `--version-code N`) and where the key comes from. Then without `--dry`. The AAB lands in
`build/android/<package>-<versionCode>.aab`; storebound reads the versionCode back from the bundle and warns when
the build file ignored the one it passed (read `-PversionCode` there, or `android.injected.version.code`).
3. **Upload.** `storebound play upload --track internal --dry` (read-only: checks the versionCode is free, shows
what is on the track now and the release notes languages). Then without `--dry` after a yes. Tracks: internal,
alpha (closed), beta (open). Production stays `storebound play release --version-code N --production draft` plus
the owner's click in the Console (`play-first-release`, `release-management`). A never-published app only takes
drafts: `--status draft`.
## Gotchas
- "No signing certificate iOS Distribution found": the certificate exists on the team but its key is on another Mac.
`apple signing status` shows this as "without key"; import that Mac's .p12, or `ensure` makes a new one.
- "Provisioning profile doesn't include the currently selected device / capability": a capability was added after the
profile was made. `apple signing ensure` (profiles are recreated when they are not ACTIVE).
- Xcode 16+ reads profiles only from `~/Library/Developer/Xcode/UserData/Provisioning Profiles`: profiles copied into
the old folder alone are not seen.
- ITMS-90189 / "bundle version must be higher": the build number is taken. `apple next-build` gives a free one;
`apple build` uses it by default.
- Play "Version code N has already been used": `play next-version-code`; `play build` uses it by default.

View file

@ -25,12 +25,17 @@ deleting products. Sending a first release for review is the owner's action in t
3. **Local · Signing.** Generate an upload key (`keytool -genkeypair -v -storetype PKCS12 -keystore upload.p12 3. **Local · Signing.** Generate an upload key (`keytool -genkeypair -v -storetype PKCS12 -keystore upload.p12
-alias upload -keyalg RSA -keysize 4096 -validity 10950`), keep keystore + passwords out of git and back them up -alias upload -keyalg RSA -keysize 4096 -validity 10950`), keep keystore + passwords out of git and back them up
(encrypted, two places). Play App Signing holds the real app key; a lost upload key can be reset via the Console. (encrypted, two places). Play App Signing holds the real app key; a lost upload key can be reset via the Console.
Check the AAB signer before uploading: `keytool -printcert -jarfile app-release.aab`. Check the AAB signer before uploading: `keytool -printcert -jarfile app-release.aab`. Put the keystore path and
passwords in `ANDROID_KEYSTORE`, `ANDROID_KEYSTORE_PASSWORD`, `ANDROID_KEY_ALIAS`, `ANDROID_KEY_PASSWORD` (env or
`.storebound/credentials.json`) and `storebound play build` signs with it (`build-and-sign` skill).
4. **Local · Version.** versionName (e.g. 1.0.0) and a versionCode that always increases 4. **Local · Version.** versionName (e.g. 1.0.0) and a versionCode that always increases
(`storebound play next-version-code` prints the next free one; use exactly that code in later steps). Capacitor: set them in (`storebound play next-version-code` prints the next free one; use exactly that code in later steps).
`android/app/build.gradle` (or env-driven) before `./gradlew bundleRelease`. `storebound play build --version-name 1.0.0 --dry`, then without `--dry`: Gradle `bundleRelease` (Flutter:
`flutter build appbundle`) with the next free versionCode, AAB in `build/android/`. Capacitor, React Native,
Flutter and Unity exports are found automatically.
5. **UI or API · First upload.** The very first AAB may need the Console (Testing > Internal testing > Create new 5. **UI or API · First upload.** The very first AAB may need the Console (Testing > Internal testing > Create new
release) so Play links the package name; after that: `storebound play release app-release.aab` (internal, completed). release) so Play links the package name; after that: `storebound play upload --track internal --dry`, then without
`--dry` (asks first; `play release app-release.aab` does the same with more track options).
Add testers (internal testing list) and **license testers** (Settings > License testing) so test purchases are free. Add testers (internal testing list) and **license testers** (Settings > License testing) so test purchases are free.
6. **API · Listing text.** Fill `store/listing.md` (one section per language), then `storebound play listing`. 6. **API · Listing text.** Fill `store/listing.md` (one section per language), then `storebound play listing`.
It also sets contact email + website (website = the domain serving app-ads.txt). It also sets contact email + website (website = the domain serving app-ads.txt).

View file

@ -1,6 +1,6 @@
--- ---
name: portfolio-originality name: portfolio-originality
description: Originality gate for studios and developers that ship many similar mobile apps or games (templates, white-label apps, reskins) - score a planned or finished app or game against your own catalogue (mechanic, content, art, metadata, screenshots), require a clear differentiator, and suggest merging thin ideas, to avoid App Store Guideline 4.3 (spam) and Play repetitive content rejections. Use before starting a new app or game, before submitting one, or after a 4.3 / "repetitive content" rejection. description: Originality gate for studios and developers that ship many similar mobile apps or games (templates, white-label apps, reskins) - measure listing text, icon, screenshot and project similarity offline with storebound originality, score a planned or finished app or game against your own catalogue (mechanic, content, art, metadata, screenshots), require a clear differentiator, and suggest merging thin ideas, to avoid App Store Guideline 4.3 (spam) and Play repetitive content rejections. Use before starting a new app or game, before submitting one, or after a 4.3 / "repetitive content" rejection.
--- ---
# Portfolio originality (Guideline 4.3 gate) # Portfolio originality (Guideline 4.3 gate)
@ -14,6 +14,17 @@ Studios with a template engine and white-label / reskinned apps hit this first.
subtitle, short description, keywords, screenshot captions). subtitle, short description, keywords, screenshot captions).
- The catalogue: the same for every app or game you have published or submitted (store links are fine). - The catalogue: the same for every app or game you have published or submitted (store links are fine).
## Measure first (offline)
`storebound originality --against <folder>` compares this app with your other apps: each folder with a
`storebound.config.ts`, or a folder holding several (one level down); or list them once in `originality.against`.
Per pair it reports a 0-100 % likeness for the **name**, the **listing text** (word frequency + copied 3-word
phrases), the **icon** and the **screenshots** (perceptual hashes: dHash + DCT pHash of the icon and of the rendered
screenshots of the first language, PNG decoded in TypeScript, JPEG / WebP through ffmpeg if installed), and the
**project structure** (same file layout, byte-identical files; build output and dependencies left out), an overall
score, why a pair is flagged (overall >= 70 % by default, `--threshold`, or one axis nearly identical) and what to
change. `--json` for agents (MCP tool `originality`); exit 1 when a pair is flagged. It measures what reviewers see
and what a template shares; it cannot judge the core mechanic or content. Feed its numbers into the scores below.
## Score each pair (new app vs each catalogue app), 0 = identical, 2 = clearly different ## Score each pair (new app vs each catalogue app), 0 = identical, 2 = clearly different
| axis | 0 | 1 | 2 | | axis | 0 | 1 | 2 |
|---|---|---|---| |---|---|---|---|
@ -38,5 +49,6 @@ If the sentence needs the words "theme", "skin", "colours" or "levels" to work,
- After a 4.3 rejection: list the concrete differences in the reply (`review-rejections`); if there are none, merge. - After a 4.3 rejection: list the concrete differences in the reply (`review-rejections`); if there are none, merge.
## Output for the owner ## Output for the owner
A table per catalogue app with the five scores, the total, the differentiator sentence, and a recommendation: A table per catalogue app with the `storebound originality` likeness per axis, the five scores, the total, the
differentiator sentence, and a recommendation:
ship / ship after <change> / merge into <app>. ship / ship after <change> / merge into <app>.

View file

@ -3,6 +3,10 @@
"ASC_KEY_ID": "YOUR_KEY_ID", "ASC_KEY_ID": "YOUR_KEY_ID",
"ASC_ISSUER_ID": "00000000-0000-0000-0000-000000000000", "ASC_ISSUER_ID": "00000000-0000-0000-0000-000000000000",
"ASC_P8": "/absolute/path/to/AuthKey_<KEY_ID>.p8", "ASC_P8": "/absolute/path/to/AuthKey_<KEY_ID>.p8",
"ANDROID_KEYSTORE": "/absolute/path/to/upload.p12",
"ANDROID_KEYSTORE_PASSWORD": "",
"ANDROID_KEY_ALIAS": "upload",
"ANDROID_KEY_PASSWORD": "",
"reviewContact": { "firstName": "", "lastName": "", "phone": "+1 555 0100", "email": "review-contact@example.com" }, "reviewContact": { "firstName": "", "lastName": "", "phone": "+1 555 0100", "email": "review-contact@example.com" },
"reviewDemoAccount": { "username": "", "password": "" } "reviewDemoAccount": { "username": "", "password": "" }
} }

64
tests/build-fixtures.ts Normal file
View file

@ -0,0 +1,64 @@
// Real (tiny) PNG, ZIP, IPA and AAB files for the build, signing and originality tests. Sanitized: example.com ids only.
import { deflateRawSync, deflateSync } from 'node:zlib';
import { encodeProtoManifest } from '../cli/lib/gradle';
/** A real PNG (8 bit RGBA, RGB or grey) from a pixel function. filter 1 writes Sub-filtered rows. */
export function encodePng(w: number, h: number, px: (x: number, y: number) => [number, number, number, number?], o: { colorType?: 0 | 2 | 6; filter?: 0 | 1 } = {}): Buffer {
const ct = o.colorType ?? 6, ch = ct === 0 ? 1 : ct === 2 ? 3 : 4;
const stride = w * ch + 1;
const raw = Buffer.alloc(stride * h);
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const [r, g, b, a = 255] = px(x, y);
const v = ct === 0 ? [Math.round(0.299 * r + 0.587 * g + 0.114 * b)] : ct === 2 ? [r, g, b] : [r, g, b, a];
v.forEach((c, i) => { raw[y * stride + 1 + x * ch + i] = c; });
}
if (o.filter === 1) {
raw[y * stride] = 1;
for (let i = w * ch; i > ch; i--) raw[y * stride + i] = (raw[y * stride + i]! - raw[y * stride + i - ch]! + 256) & 255;
}
}
const table = Array.from({ length: 256 }, (_, n) => { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0; });
const crc = (b: Buffer) => { let c = 0xffffffff; for (const x of b) c = table[(c ^ x) & 255]! ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; };
const chunk = (type: string, data: Buffer) => {
const len = Buffer.alloc(4); len.writeUInt32BE(data.length);
const td = Buffer.concat([Buffer.from(type, 'latin1'), data]);
const c = Buffer.alloc(4); c.writeUInt32BE(crc(td));
return Buffer.concat([len, td, c]);
};
const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = ct;
return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk('IHDR', ihdr), chunk('IDAT', deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]);
}
/** A ZIP archive (deflated entries, or stored with store: true). */
export function makeZip(entries: { name: string; data: Buffer | string; store?: boolean }[]): Buffer {
const locals: Buffer[] = [], central: Buffer[] = [];
let off = 0;
for (const e of entries) {
const data = Buffer.from(e.data), comp = e.store ? data : deflateRawSync(data), name = Buffer.from(e.name, 'utf8');
const lh = Buffer.alloc(30); lh.writeUInt32LE(0x04034b50, 0); lh.writeUInt16LE(20, 4); lh.writeUInt16LE(e.store ? 0 : 8, 8);
lh.writeUInt32LE(comp.length, 18); lh.writeUInt32LE(data.length, 22); lh.writeUInt16LE(name.length, 26);
const ch = Buffer.alloc(46); ch.writeUInt32LE(0x02014b50, 0); ch.writeUInt16LE(20, 4); ch.writeUInt16LE(20, 6); ch.writeUInt16LE(e.store ? 0 : 8, 10);
ch.writeUInt32LE(comp.length, 20); ch.writeUInt32LE(data.length, 24); ch.writeUInt16LE(name.length, 28); ch.writeUInt32LE(off, 42);
locals.push(lh, name, comp); central.push(ch, name);
off += 30 + name.length + comp.length;
}
const cd = Buffer.concat(central);
const end = Buffer.alloc(22); end.writeUInt32LE(0x06054b50, 0); end.writeUInt16LE(entries.length, 8); end.writeUInt16LE(entries.length, 10);
end.writeUInt32LE(cd.length, 12); end.writeUInt32LE(off, 16);
return Buffer.concat([...locals, cd, end]);
}
/** An IPA with the given Info.plist bytes. */
export const makeIpa = (infoPlist: Buffer | string, app = 'Example.app'): Buffer => makeZip([
{ name: 'Payload/', data: '', store: true },
{ name: `Payload/${app}/Example`, data: Buffer.alloc(2048, 7) },
{ name: `Payload/${app}/Info.plist`, data: infoPlist },
]);
/** An AAB with an aapt2 proto manifest. */
export const makeAab = (pkg: string, versionCode: number, versionName = '1.0.0'): Buffer => makeZip([
{ name: 'BundleConfig.pb', data: Buffer.from([8, 1]) },
{ name: 'base/manifest/AndroidManifest.xml', data: encodeProtoManifest([{ name: 'manifest', attrs: { package: pkg, versionCode: String(versionCode), versionName } }, { name: 'uses-sdk', attrs: { minSdkVersion: '24', targetSdkVersion: '35' } }]) },
{ name: 'base/dex/classes.dex', data: Buffer.alloc(512, 1) },
]);

353
tests/build-sign.test.ts Normal file
View file

@ -0,0 +1,353 @@
import { afterAll, describe, expect, test } from 'bun:test';
import { createPrivateKey, createPublicKey, verify } from 'node:crypto';
import { mkdirSync, mkdtempSync, readFileSync, rmSync, utimesSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { installedProfiles } from '../cli/apple/build';
import { androidSigning, ascKeyFile } from '../cli/lib/credentials';
import { buildCsr, csrContent, newSigningKey, spkiOfKey } from '../cli/lib/csr';
import { aabInfo, findBundles, gradleArgs, pickGradle, signingEnv, validatePlayBuild } from '../cli/lib/gradle';
import { parseBinaryPlist, parseMobileprovision, parsePlist, parseXmlPlist, toXmlPlist } from '../cli/lib/plist';
import {
type ApiCert, type ApiProfile, certSha1, certSpki, certificateReq, explainCertError, exportOptions, parseIdentities, pickCertificate, planCapabilities,
planProfile, profileDirs, validateSigning,
} from '../cli/lib/signing';
import { validateConfig } from '../cli/lib/config';
import { altoolArgs, archiveArgs, buildUploadReqs, exportArgs, flutterConfigArgs, ipaInfo, pickXcode, scanXcode, showCmd, uploadProblems, type XcodeScan } from '../cli/lib/xcode';
import { zipEntries, zipRead } from '../cli/lib/zip';
import { makeAab, makeIpa, makeZip } from './build-fixtures';
import { TOOLS } from '../cli/mcp-tools';
const ROOT = join(import.meta.dir, '..');
const FIX = join(import.meta.dir, 'fixtures', 'build');
const tmp = mkdtempSync(join(tmpdir(), 'sb-build-'));
afterAll(() => rmSync(tmp, { recursive: true, force: true }));
const dir = (name: string): string => { const d = join(tmp, name); mkdirSync(d, { recursive: true }); return d; };
const touch = (base: string, rel: string, text = ''): void => { mkdirSync(join(base, rel, '..'), { recursive: true }); writeFileSync(join(base, rel), text); };
describe('plist', () => {
test('XML: write and read back every type', () => {
const v = { method: 'app-store-connect', n: 3, x: 1.5, ok: true, no: false, list: ['a', 'b & <c>'], nested: { k: 'v' }, empty: {}, data: Buffer.from([0, 1, 2]) };
const text = toXmlPlist(v);
expect(text).toContain('<key>method</key>\n\t<string>app-store-connect</string>');
expect(text).toContain('<string>b &amp; &lt;c&gt;</string>');
expect(parseXmlPlist(text)).toEqual(v);
});
test('the fixture Info.plist, XML and binary (plutil) agree', () => {
const xml = parsePlist(readFileSync(join(FIX, 'Info.plist'))) as Record<string, unknown>;
const bin = parseBinaryPlist(readFileSync(join(FIX, 'Info.bplist'))) as Record<string, unknown>;
expect(xml.CFBundleIdentifier).toBe('com.example.game');
expect(bin.CFBundleDisplayName).toBe('Example Gäme');
expect(bin.UIDeviceFamily).toEqual([1, 2]);
expect(bin.Scale).toBe(1.5);
expect(bin.UIRequiresFullScreen).toBe(true);
expect(bin.Built).toBe('2026-10-01T12:00:00.000Z');
expect(xml.Built).toBe('2026-10-01T12:00:00Z');
const { Built: _a, ...x } = xml, { Built: _b, ...b } = bin;
expect(b).toEqual(x);
});
test('mobileprovision: the plist inside the CMS envelope', () => {
const inner = toXmlPlist({ UUID: '00000000-0000-0000-0000-000000000000', Name: 'storebound com.example.game App Store', TeamIdentifier: ['TEAMID1234'], ExpirationDate: '2099-01-01T00:00:00Z',
Entitlements: { 'application-identifier': 'TEAMID1234.com.example.game', 'get-task-allow': false } });
const p = parseMobileprovision(Buffer.concat([Buffer.from([0x30, 0x82, 0x01]), Buffer.from(inner), Buffer.from([0xa0, 0x00])]));
expect(p.Name).toBe('storebound com.example.game App Store');
expect(() => parseMobileprovision(Buffer.from('nope'))).toThrow('not a provisioning profile');
});
});
describe('zip + IPA + AAB', () => {
test('zip entries, stored and deflated', () => {
const z = makeZip([{ name: 'a.txt', data: 'hello', store: true }, { name: 'dir/b.txt', data: 'world '.repeat(100) }]);
const es = zipEntries(z);
expect(es.map(e => e.name)).toEqual(['a.txt', 'dir/b.txt']);
expect(zipRead(z, es[1]!).toString()).toBe('world '.repeat(100));
expect(() => zipEntries(Buffer.from('not a zip at all, sorry'))).toThrow('not a ZIP');
});
test('ipaInfo reads binary and XML Info.plist', () => {
const bin = makeIpa(readFileSync(join(FIX, 'Info.bplist')));
expect(ipaInfo(bin)).toEqual({ bundleId: 'com.example.game', version: '1.4.0', build: '42', minOs: '15.0', name: 'Example Gäme', platform: 'iPhoneOS' });
const f = join(dir('ipa'), 'Example.ipa');
writeFileSync(f, makeIpa(readFileSync(join(FIX, 'Info.plist'))));
expect(ipaInfo(f).build).toBe('42');
expect(() => ipaInfo(makeZip([{ name: 'x', data: 'y' }]))).toThrow('not an iOS app archive');
});
test('aabInfo reads the proto manifest', () => {
expect(aabInfo(makeAab('com.example.game', 1234, '2.0.1'))).toEqual({ packageName: 'com.example.game', versionCode: 1234, versionName: '2.0.1', minSdk: 24, targetSdk: 35 });
expect(() => aabInfo(makeZip([{ name: 'x', data: 'y' }]))).toThrow('not an Android App Bundle');
});
});
describe('CSR', () => {
test('PKCS #10 with the public key, signed by the private key', () => {
const { pem, key } = newSigningKey();
const csr = buildCsr(key, { commonName: 'storebound Example' });
expect(csr).toStartWith('-----BEGIN CERTIFICATE REQUEST-----');
const b64 = csrContent(csr);
expect(b64).toMatch(/^[A-Za-z0-9+/=]+$/);
const der = Buffer.from(b64, 'base64');
// the SPKI of the key is inside, and the signature verifies over CertificationRequestInfo
const spki = createPublicKey(key).export({ type: 'spki', format: 'der' });
expect(der.includes(spki)).toBe(true);
expect(spkiOfKey(pem)).toBe(spki.toString('base64'));
const infoLenBytes = der[5]! & 0x80 ? (der[5]! & 0x7f) : 0;
const infoStart = 4, infoLen = infoLenBytes ? der.readUIntBE(6, infoLenBytes) : der[5]!;
const info = der.subarray(infoStart, infoStart + 2 + infoLenBytes + infoLen);
const sig = der.subarray(der.length - 256);
expect(verify('sha256', info, createPublicKey(createPrivateKey(pem)), sig)).toBe(true);
if (Bun.which('openssl')) {
const f = join(dir('csr'), 'req.csr');
writeFileSync(f, csr);
const r = Bun.spawnSync(['openssl', 'req', '-in', f, '-noout', '-verify', '-subject'], { stdout: 'pipe', stderr: 'pipe' });
expect(r.exitCode).toBe(0);
expect(r.stdout.toString() + r.stderr.toString()).toContain('storebound Example');
}
});
});
const cert = (id: string, type: string, days: number, extra: Partial<ApiCert['attributes']> = {}): ApiCert =>
({ id, attributes: { certificateType: type, expirationDate: new Date(Date.now() + days * 86_400_000).toISOString(), name: `Apple Distribution ${id}`, certificateContent: Buffer.from(id).toString('base64'), ...extra } });
describe('signing plans', () => {
test('capabilities: adds the missing ones, never removes', () => {
const p = planCapabilities('B1', ['IN_APP_PURCHASE', 'PUSH_NOTIFICATIONS'], [{ type: 'IN_APP_PURCHASE' }, { type: 'GAME_CENTER' }, { type: 'ICLOUD', settings: [{ key: 'ICLOUD_VERSION', options: [{ key: 'XCODE_6' }] }] }]);
expect(p.present).toEqual(['IN_APP_PURCHASE']);
expect(p.extra).toEqual(['PUSH_NOTIFICATIONS']);
expect(p.create.map(r => (r.body as any).data.attributes.capabilityType)).toEqual(['GAME_CENTER', 'ICLOUD']);
expect((p.create[1]!.body as any).data.attributes.settings[0].key).toBe('ICLOUD_VERSION');
expect((p.create[0]!.body as any).data.relationships.bundleId.data).toEqual({ type: 'bundleIds', id: 'B1' });
});
test('certificate: newest usable one with a local key, not expiring', () => {
const certs = [cert('old', 'DISTRIBUTION', 400), cert('new', 'DISTRIBUTION', 700), cert('soon', 'DISTRIBUTION', 10), cert('nokey', 'DISTRIBUTION', 900), cert('dev', 'DEVELOPMENT', 900), cert('gone', 'DISTRIBUTION', -1)];
const has = (c: ApiCert) => c.id !== 'nokey';
const c = pickCertificate(certs, 'DISTRIBUTION', has);
expect(c.cert?.id).toBe('new');
expect(c.expiring.map(x => x.id)).toEqual(['soon']);
expect(c.withoutKey.map(x => x.id)).toEqual(['nokey']);
const none = pickCertificate([cert('nokey', 'DISTRIBUTION', 900)], 'DISTRIBUTION', () => false);
expect(none.cert).toBeNull();
expect(none.why).toContain('none of their private keys');
expect(pickCertificate([], 'DISTRIBUTION', () => true).why).toBe('no valid DISTRIBUTION certificate');
expect(pickCertificate([cert('off', 'DISTRIBUTION', 500, { activated: false })], 'DISTRIBUTION', () => true).cert).toBeNull();
});
test('certificate request carries only the CSR', () => {
const r = certificateReq('DISTRIBUTION', 'MIIB');
expect(r.body).toEqual({ data: { type: 'certificates', attributes: { certificateType: 'DISTRIBUTION', csrContent: 'MIIB' } } });
});
test('Developer ID 403, certificate limit and role errors are explained', () => {
expect(explainCertError(new Error('POST /v1/certificates -> 403 FORBIDDEN_ERROR'), 'DEVELOPER_ID_APPLICATION')).toContain('Account Holder');
expect(explainCertError(new Error('POST /v1/certificates -> 403 FORBIDDEN_ERROR'), 'DISTRIBUTION')).toContain('Admin role');
expect(explainCertError(new Error('POST /v1/certificates -> 409 You already have a current Distribution certificate or a pending request (maximum)'), 'DISTRIBUTION')).toContain('limit');
expect(explainCertError(new Error('-> 500'), 'DISTRIBUTION')).toBeNull();
});
test('profile: reuse an active one with the certificate, else create', () => {
const now = Date.now();
const p = (id: string, state: string, days: number, certIds: string[]): ApiProfile => ({ id, certIds, attributes: { name: id, profileType: 'IOS_APP_STORE', profileState: state, expirationDate: new Date(now + days * 86_400_000).toISOString(), uuid: `u-${id}` } });
const o = { bundleId: 'com.example.game', bundleIdId: 'B1', certId: 'C1', type: 'IOS_APP_STORE' as const, now };
expect(planProfile([p('a', 'ACTIVE', 200, ['C1']), p('b', 'ACTIVE', 300, ['C1'])], o).reuse?.id).toBe('b');
const c = planProfile([p('x', 'INVALID', 200, ['C1']), p('y', 'ACTIVE', 300, ['C0']), p('z', 'ACTIVE', 5, ['C1'])], o);
expect(c.reuse).toBeNull();
expect(c.why).toContain('none active with this certificate');
const body = (c.create!.body as any).data;
expect(body.attributes.profileType).toBe('IOS_APP_STORE');
expect(body.attributes.name).toStartWith('storebound com.example.game App Store ');
expect(body.relationships.certificates.data).toEqual([{ type: 'certificates', id: 'C1' }]);
});
test('ExportOptions: app-store-connect, export destination, manual profiles', () => {
expect(exportOptions({ teamId: 'TEAMID1234', style: 'automatic' })).toEqual({ method: 'app-store-connect', teamID: 'TEAMID1234', signingStyle: 'automatic', destination: 'export', uploadSymbols: true, manageAppVersionAndBuildNumber: false });
const m = exportOptions({ teamId: 'TEAMID1234', style: 'manual', profiles: { 'com.example.game': 'u-1' } });
expect(m.provisioningProfiles).toEqual({ 'com.example.game': 'u-1' });
expect(m.signingCertificate).toBe('Apple Distribution');
expect(() => exportOptions({ teamId: 'T', style: 'manual' })).toThrow('signing ensure');
expect(toXmlPlist(m)).toContain('<key>signingStyle</key>\n\t<string>manual</string>');
});
test('identities, sha1, spki, profile folders', () => {
const out = ' 1) 0123456789ABCDEF0123456789ABCDEF01234567 "Apple Distribution: Example (TEAMID1234)"\n 1 valid identities found\n';
expect(parseIdentities(out)).toEqual([{ sha1: '0123456789ABCDEF0123456789ABCDEF01234567', name: 'Apple Distribution: Example (TEAMID1234)' }]);
expect(certSha1(Buffer.from('abc').toString('base64'))).toBe('A9993E364706816ABA3E25717850C26C9CD0D89D');
expect(certSpki('bm9wZQ==')).toBeNull();
expect(profileDirs('/Users/you')).toEqual(['/Users/you/Library/Developer/Xcode/UserData/Provisioning Profiles', '/Users/you/Library/MobileDevice/Provisioning Profiles']);
});
test('config validation', () => {
expect(validateSigning({ style: 'manual', teamId: 'TEAMID1234', capabilities: ['IN_APP_PURCHASE', { type: 'GAME_CENTER' }], extraBundleIds: ['com.example.game.widget'] })).toEqual([]);
const e = validateSigning({ style: 'auto' as any, teamId: 'x', certificateType: 'NOPE' as any, capabilities: ['TELEPORT' as any], extraBundleIds: ['bad id'] }).join('\n');
for (const s of ['style', 'teamId', 'certificateType', 'TELEPORT', 'bad id']) expect(e).toContain(s);
const base = { app: { name: 'X', privacyPolicyUrl: 'https://example.com/p', supportUrl: 'https://example.com', website: 'https://example.com', contactEmail: 'a@example.com' }, languages: [{ id: 'en', apple: 'en-US', play: 'en-US' }] };
expect(validateConfig({ ...base, apple: { bundleId: 'com.example.game', signing: { style: 'manual' }, build: { workspace: 'ios/App/App.xcworkspace', scheme: 'App' } }, play: { packageName: 'com.example.game', build: { module: 'app', flavor: 'prod' } }, originality: { against: ['..'], threshold: 0.7 } })).toEqual([]);
expect(validateConfig({ ...base, apple: { bundleId: 'com.example.game', build: { workspace: 'App.xcodeproj' } } }).join()).toContain('.xcworkspace');
expect(validatePlayBuild({ module: 'a b', flavor: '1x' }).length).toBe(2);
expect(validateConfig({ ...base, originality: { threshold: 2 } }).join()).toContain('originality.threshold');
});
test('installed App Store profiles are found by bundle id and team', () => {
const home = dir('home');
const write = (uuid: string, appId: string, extra: Record<string, unknown> = {}) => {
const d = profileDirs(home)[0]!;
mkdirSync(d, { recursive: true });
writeFileSync(join(d, `${uuid}.mobileprovision`), Buffer.concat([Buffer.from([0x30, 0x80]), Buffer.from(toXmlPlist({ UUID: uuid, Name: uuid, TeamIdentifier: ['TEAMID1234'],
ExpirationDate: '2099-01-01T00:00:00Z', Entitlements: { 'application-identifier': appId, 'get-task-allow': false }, ...extra } as any))]));
};
write('store', 'TEAMID1234.com.example.game');
write('dev', 'TEAMID1234.com.example.game', { ProvisionedDevices: ['x'] });
write('other', 'TEAMID1234.com.example.other');
expect(installedProfiles('com.example.game', 'TEAMID1234', home).map(p => p.uuid)).toEqual(['store']);
expect(installedProfiles('com.example.game', 'OTHERTEAM1', home)).toEqual([]);
});
});
describe('xcode projects', () => {
const S = (o: Partial<XcodeScan>): XcodeScan => ({ markers: [], workspaces: [], projects: [], schemes: {}, pods: [], ...o });
test('Capacitor, Flutter, React Native, Unity, native', () => {
expect(pickXcode(S({ markers: ['capacitor.config.ts'], workspaces: ['ios/App/App.xcworkspace'], projects: ['ios/App/App.xcodeproj', 'ios/App/Pods/Pods.xcodeproj'], pods: [{ dir: 'ios/App', installed: true }] })))
.toMatchObject({ framework: 'capacitor', workspace: 'ios/App/App.xcworkspace', scheme: 'App' });
expect(pickXcode(S({ markers: ['capacitor.config.json'], projects: ['ios/App/App.xcodeproj'] }))).toMatchObject({ project: 'ios/App/App.xcodeproj', scheme: 'App' });
expect(pickXcode(S({ markers: ['pubspec.yaml'], workspaces: ['ios/Runner.xcworkspace'], projects: ['ios/Runner.xcodeproj'] }))).toMatchObject({ framework: 'flutter', workspace: 'ios/Runner.xcworkspace', scheme: 'Runner' });
const rn = pickXcode(S({ markers: ['package.json:react-native'], workspaces: ['ios/ExampleGame.xcworkspace'], projects: ['ios/ExampleGame.xcodeproj'], schemes: { 'ios/ExampleGame.xcodeproj': ['ExampleGame', 'ExampleGame-tvOS'] }, pods: [{ dir: 'ios', installed: false }] }));
expect(rn).toMatchObject({ framework: 'react-native', workspace: 'ios/ExampleGame.xcworkspace', scheme: 'ExampleGame' });
expect(rn.notes.join()).toContain('pod install');
expect(pickXcode(S({ markers: ['Unity-iPhone.xcodeproj'], projects: ['Builds/iOS/Unity-iPhone.xcodeproj'] }))).toMatchObject({ framework: 'unity', project: 'Builds/iOS/Unity-iPhone.xcodeproj', scheme: 'Unity-iPhone' });
expect(pickXcode(S({ projects: ['Example.xcodeproj'], schemes: { 'Example.xcodeproj': ['Example Release'] } }))).toMatchObject({ framework: 'native', project: 'Example.xcodeproj', scheme: 'Example Release' });
expect(pickXcode(S({ projects: ['Example.xcodeproj'] }), { scheme: 'Mine' }).scheme).toBe('Mine');
expect(() => pickXcode(S({}))).toThrow('no .xcworkspace');
expect(() => pickXcode(S({ projects: ['A.xcodeproj', 'B.xcodeproj'] }))).toThrow('several Xcode containers');
});
test('scanXcode walks a real folder (Capacitor layout)', () => {
const d = dir('cap');
touch(d, 'capacitor.config.ts', 'export default {}');
touch(d, 'ios/App/App.xcodeproj/project.pbxproj');
touch(d, 'ios/App/App.xcodeproj/xcshareddata/xcschemes/App.xcscheme');
touch(d, 'ios/App/App.xcworkspace/contents.xcworkspacedata');
touch(d, 'ios/App/Podfile');
touch(d, 'node_modules/x/ios/X.xcodeproj/project.pbxproj');
const s = scanXcode(d);
expect(s.workspaces).toEqual(['ios/App/App.xcworkspace']);
expect(s.projects).toEqual(['ios/App/App.xcodeproj']);
expect(s.schemes['ios/App/App.xcodeproj']).toEqual(['App']);
expect(s.pods).toEqual([{ dir: 'ios/App', installed: false }]);
expect(pickXcode(s).notes.join()).toContain('pod install');
});
test('command lines: archive, export, flutter, altool; the key path is never shown', () => {
const t = { framework: 'capacitor' as const, workspace: 'ios/App/App.xcworkspace', scheme: 'App', notes: [] };
const auth = { keyPath: '/tmp/k/AuthKey_X.p8', keyId: 'KEYID', issuerId: 'ISSUER' };
const a = archiveArgs({ target: t, root: '/p', configuration: 'Release', archivePath: '/p/build/ios/App.xcarchive', version: '1.4.0', build: '42', teamId: 'TEAMID1234', auth });
expect(a.slice(0, 3)).toEqual(['xcodebuild', '-workspace', '/p/ios/App/App.xcworkspace']);
expect(a).toContain('-allowProvisioningUpdates');
expect(a.slice(-4)).toEqual(['archive', 'CURRENT_PROJECT_VERSION=42', 'MARKETING_VERSION=1.4.0', 'DEVELOPMENT_TEAM=TEAMID1234']);
expect(showCmd(a, auth)).toContain('-authenticationKeyPath $ASC_P8');
expect(showCmd(a, auth)).not.toContain('/tmp/k');
expect(exportArgs('/a.xcarchive', '/E.plist', '/out', null)).toEqual(['xcodebuild', '-exportArchive', '-archivePath', '/a.xcarchive', '-exportOptionsPlist', '/E.plist', '-exportPath', '/out']);
expect(flutterConfigArgs('42', '1.4.0')).toEqual(['flutter', 'build', 'ios', '--release', '--config-only', '--no-codesign', '--build-number', '42', '--build-name', '1.4.0']);
expect(altoolArgs('/x.ipa', auth).slice(0, 4)).toEqual(['xcrun', 'altool', '--upload-package', '/x.ipa']);
});
test('API build upload requests (Build Uploads)', () => {
const r = buildUploadReqs('APPID', { bundleId: 'com.example.game', version: '1.4.0', build: '42' }, 'Example.ipa', 1048576 * 12);
expect(r.upload.body).toEqual({ data: { type: 'buildUploads', attributes: { cfBundleShortVersionString: '1.4.0', cfBundleVersion: '42', platform: 'IOS' }, relationships: { app: { data: { type: 'apps', id: 'APPID' } } } } });
expect(r.file('U1').body.data.attributes).toEqual({ assetType: 'ASSET', fileName: 'Example.ipa', fileSize: 12582912, uti: 'com.apple.ipa' });
expect(r.commit('F1', 'abc').body.data.attributes).toEqual({ uploaded: true, sourceFileChecksums: { file: { hash: 'abc', algorithm: 'MD5' } } });
expect(uploadProblems({ errors: [{ code: 'ITMS-90062', message: 'version must be higher' }] }).errors).toEqual(['ITMS-90062: version must be higher']);
});
});
describe('gradle projects', () => {
test('React Native / Capacitor android/, Unity export, native root, Flutter', () => {
const rn = dir('rn');
touch(rn, 'package.json', JSON.stringify({ dependencies: { 'react-native': '0.80.0' } }));
touch(rn, 'android/settings.gradle'); touch(rn, 'android/gradlew', '#!/bin/sh'); touch(rn, 'android/app/build.gradle');
const t = pickGradle(rn);
expect(t).toMatchObject({ framework: 'react-native', module: 'app', task: ':app:bundleRelease' });
expect(gradleArgs(t, { versionCode: 7, versionName: '1.2.0', hasWrapper: true })).toEqual(['./gradlew', ':app:bundleRelease', '--no-daemon', '--console=plain',
'-Pandroid.injected.version.code=7', '-PversionCode=7', '-Pandroid.injected.version.name=1.2.0', '-PversionName=1.2.0']);
expect(pickGradle(rn, { flavor: 'prod' }).task).toBe(':app:bundleProdRelease');
const unity = dir('unity');
touch(unity, 'Export/settings.gradle'); touch(unity, 'Export/launcher/build.gradle'); touch(unity, 'Export/unityLibrary/build.gradle');
expect(pickGradle(unity, { dir: 'Export' })).toMatchObject({ framework: 'unity', module: 'launcher', task: ':launcher:bundleRelease' });
const native = dir('native');
touch(native, 'settings.gradle.kts'); touch(native, 'app/build.gradle.kts');
expect(pickGradle(native).notes.join()).toContain('no Gradle wrapper');
const fl = dir('flutter');
touch(fl, 'pubspec.yaml', 'name: example'); touch(fl, 'android/settings.gradle'); touch(fl, 'android/app/build.gradle');
const ft = pickGradle(fl);
expect(gradleArgs(ft, { versionCode: 9, hasWrapper: false })).toEqual(['flutter', 'build', 'appbundle', '--release', '--build-number', '9']);
expect(() => pickGradle(dir('empty'))).toThrow('no Gradle project');
expect(() => pickGradle(native, { module: 'mobile' })).toThrow('module "mobile" not found');
});
test('signing goes through the environment, never argv', () => {
const env = signingEnv({ storeFile: '/k/upload.jks', storePassword: 'pw1', keyAlias: 'upload', keyPassword: 'pw2' });
expect(env['ORG_GRADLE_PROJECT_android.injected.signing.store.password']).toBe('pw1');
expect(env['ORG_GRADLE_PROJECT_android.injected.signing.key.alias']).toBe('upload');
expect(signingEnv(null)).toEqual({});
});
test('findBundles: only new AABs, newest first', () => {
const d = dir('out');
touch(d, 'app/build/outputs/bundle/release/app-release.aab', 'x');
touch(d, 'app/build/outputs/bundle/release/old.aab', 'x');
const past = new Date(Date.now() - 3_600_000);
utimesSync(join(d, 'app/build/outputs/bundle/release/old.aab'), past, past);
expect(findBundles([join(d, 'app/build/outputs/bundle')], Date.now() - 60_000).map(f => f.split('/').pop())).toEqual(['app-release.aab']);
});
});
describe('credentials for builds', () => {
test('android upload key from .storebound/credentials.json; inline ASC key goes to a private temp file', () => {
const d = dir('creds');
touch(d, '.storebound/credentials.json', JSON.stringify({ ANDROID_KEYSTORE: 'keys/upload.jks', ANDROID_KEYSTORE_PASSWORD: 'pw', ANDROID_KEY_ALIAS: 'upload' }));
const saved = { ...process.env };
try {
delete process.env.ANDROID_KEYSTORE;
expect(androidSigning(d)).toEqual({ storeFile: join(d, 'keys/upload.jks'), storePassword: 'pw', keyAlias: 'upload', keyPassword: 'pw' });
expect(androidSigning(dir('nocreds'))).toBeNull();
const { pem } = newSigningKey();
const p8 = createPrivateKey(pem).export({ type: 'pkcs8', format: 'pem' }).toString();
Object.assign(process.env, { ASC_KEY_ID: 'KEYID00001', ASC_ISSUER_ID: '00000000-0000-0000-0000-000000000000', ASC_P8: p8 });
const k = ascKeyFile(d);
expect(readFileSync(k.keyPath, 'utf8')).toBe(p8);
expect(k.keyPath.split('/').pop()).toBe(['AuthKey', 'KEYID00001.p8'].join('_'));
k.cleanup();
expect(() => readFileSync(k.keyPath)).toThrow();
} finally { for (const key of ['ASC_KEY_ID', 'ASC_ISSUER_ID', 'ASC_P8']) if (saved[key] === undefined) delete process.env[key]; else process.env[key] = saved[key]; }
});
});
describe('CLI dry runs (no store access)', () => {
const cli = (cwd: string, args: string[]) => Bun.spawnSync([process.execPath, join(ROOT, 'cli/index.ts'), ...args], { cwd, stdout: 'pipe', stderr: 'pipe', env: { ...process.env, ASC_KEY_ID: '', ASC_ISSUER_ID: '', ASC_P8: '', PLAY_SERVICE_ACCOUNT: '', HOME: dir('clihome') } });
const project = (name: string): string => {
const d = dir(name);
touch(d, 'storebound.config.ts', `export default { app: { name: 'Example', privacyPolicyUrl: 'https://example.com/p', supportUrl: 'https://example.com', website: 'https://example.com', contactEmail: 'hi@example.com' },
languages: [{ id: 'en', apple: 'en-US', play: 'en-US' }], apple: { bundleId: 'com.example.game', signing: { teamId: 'TEAMID1234' } }, play: { packageName: 'com.example.game' } };\n`);
touch(d, 'capacitor.config.ts', 'export default {}');
touch(d, 'ios/App/App.xcodeproj/project.pbxproj');
touch(d, 'android/settings.gradle'); touch(d, 'android/gradlew', '#!/bin/sh'); touch(d, 'android/app/build.gradle');
return d;
};
test('apple build --dry --json: plan with ExportOptions and the commands', () => {
const r = cli(project('cli-apple'), ['apple', 'build', '--dry', '--json', '--build-number', '42', '--version', '1.4.0']);
expect(r.exitCode).toBe(0);
const j = JSON.parse(r.stdout.toString());
expect(j).toMatchObject({ framework: 'capacitor', project: 'ios/App/App.xcodeproj', scheme: 'App', build: '42', teamId: 'TEAMID1234', signingStyle: 'automatic' });
expect(j.exportOptions.method).toBe('app-store-connect');
expect(j.steps[0]).toContain('CURRENT_PROJECT_VERSION=42');
expect(j.steps[0]).toContain('-authenticationKeyPath $ASC_P8');
});
test('play build --dry --json: task, versionCode, signing source', () => {
const r = cli(project('cli-play'), ['play', 'build', '--dry', '--json', '--version-code', '12']);
expect(r.exitCode).toBe(0);
const j = JSON.parse(r.stdout.toString());
expect(j).toMatchObject({ framework: 'capacitor', dir: 'android', task: ':app:bundleRelease', versionCode: 12, signing: "the project's own signingConfig" });
expect(j.command).toContain('-Pandroid.injected.version.code=12');
});
test('play upload refuses production', () => {
const d = project('cli-up');
writeFileSync(join(d, 'app.aab'), makeAab('com.example.game', 3));
const r = cli(d, ['play', 'upload', 'app.aab', '--track', 'production', '--dry']);
expect(r.exitCode).toBe(1);
expect(r.stderr.toString()).toContain('testing tracks');
});
});
describe('MCP', () => {
test('read-only tools only: signing status, originality; no build / upload / ensure', () => {
const names = TOOLS.map(t => t.name);
expect(names).toContain('apple_signing_status');
expect(names).toContain('originality');
for (const n of ['apple_signing_ensure', 'apple_build', 'apple_upload', 'play_build', 'play_upload']) expect(names).not.toContain(n);
for (const t of TOOLS.filter(t => ['apple_signing_status', 'originality'].includes(t.name))) expect(t.write).toBe(false);
});
});

BIN
tests/fixtures/build/Info.bplist vendored Normal file

Binary file not shown.

33
tests/fixtures/build/Info.plist vendored Normal file
View file

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleIdentifier</key>
<string>com.example.game</string>
<key>CFBundleShortVersionString</key>
<string>1.4.0</string>
<key>CFBundleVersion</key>
<string>42</string>
<key>CFBundleDisplayName</key>
<string>Example Gäme</string>
<key>MinimumOSVersion</key>
<string>15.0</string>
<key>CFBundleSupportedPlatforms</key>
<array>
<string>iPhoneOS</string>
</array>
<key>UIRequiresFullScreen</key>
<true/>
<key>UIDeviceFamily</key>
<array>
<integer>1</integer>
<integer>2</integer>
</array>
<key>Scale</key>
<real>1.5</real>
<key>Built</key>
<date>2026-10-01T12:00:00Z</date>
<key>Blob</key>
<data>AAEC</data>
</dict>
</plist>

145
tests/originality.test.ts Normal file
View file

@ -0,0 +1,145 @@
import { afterAll, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { decodePng, dHash, hamming, hashFile, hashGray, imageSimilarity, pHash, resize } from '../cli/lib/imagehash';
import { compare, findApps, fingerprint, jaccard, nameSimilarity, projectStructure, report, screenshotSimilarity, textSimilarity, words } from '../cli/lib/originality';
import { loadConfig } from '../cli/lib/config';
import { encodePng } from './build-fixtures';
const ROOT = join(import.meta.dir, '..');
const tmp = mkdtempSync(join(tmpdir(), 'sb-orig-'));
afterAll(() => rmSync(tmp, { recursive: true, force: true }));
const put = (base: string, rel: string, data: string | Buffer): void => { mkdirSync(join(base, rel, '..'), { recursive: true }); writeFileSync(join(base, rel), data); };
// pictures: a disc on a gradient (icon A), the same disc shifted in hue (a recolour), a striped square (another app)
const disc = (hue: number) => (x: number, y: number): [number, number, number, number] => {
const inside = (x - 32) ** 2 + (y - 30) ** 2 < 18 ** 2;
return inside ? [(200 + hue) % 256, 60, (40 + hue) % 256, 255] : [20 + x, 30 + y, 120, 255];
};
const stripes = (x: number, y: number): [number, number, number, number] => ((Math.floor(x / 8) + Math.floor(y / 16)) % 2 ? [240, 240, 240, 255] : [10, 80, 30, 255]);
const scene = (k: number) => (x: number, y: number): [number, number, number, number] => {
const bar = y > 20 + k * 15 && y < 40 + k * 15;
return bar ? [250, 200, 0, 255] : [30, 30 + x, 90 + k * 30, 255];
};
describe('image hashes', () => {
test('PNG decoding: RGBA, RGB, grey, Sub filter, alpha over white', () => {
const rgba = decodePng(encodePng(4, 2, (x, y) => [x * 60, y * 100, 0, 255]));
expect(rgba.w).toBe(4);
expect(Math.round(rgba.px[1]!)).toBe(Math.round(0.299 * 60));
const filtered = decodePng(encodePng(4, 2, (x, y) => [x * 60, y * 100, 0, 255], { filter: 1 }));
expect([...filtered.px]).toEqual([...rgba.px]);
expect(Math.round(decodePng(encodePng(1, 1, () => [0, 0, 0, 0])).px[0]!)).toBe(255);
expect(Math.round(decodePng(encodePng(1, 1, () => [100, 100, 100], { colorType: 0 })).px[0]!)).toBe(100);
expect(Math.round(decodePng(encodePng(1, 1, () => [0, 255, 0], { colorType: 2 })).px[0]!)).toBe(Math.round(0.587 * 255));
expect(() => decodePng(Buffer.from('GIF89a........'))).toThrow('not a PNG');
});
test('same picture at another size hashes the same; a recolour is close; another picture is far', () => {
const a = hashGray(decodePng(encodePng(64, 64, disc(0))));
const big = hashGray(decodePng(encodePng(128, 128, (x, y) => disc(0)(x / 2, y / 2))));
const recolour = hashGray(decodePng(encodePng(64, 64, disc(25))));
const other = hashGray(decodePng(encodePng(64, 64, stripes)));
expect(imageSimilarity(a, a)).toBe(1);
expect(imageSimilarity(a, big)).toBeGreaterThan(0.9);
expect(imageSimilarity(a, recolour)).toBeGreaterThan(0.8);
expect(imageSimilarity(a, other)).toBeLessThan(0.75);
expect(dHash(resize(decodePng(encodePng(8, 8, stripes)), 32, 32))).toHaveLength(16);
expect(pHash(decodePng(encodePng(8, 8, stripes)))).toHaveLength(16);
expect(hamming('ffff', '0000')).toBe(16);
});
test('hashFile: PNG in TypeScript; other files say why when they cannot be read', () => {
const d = join(tmp, 'files');
put(d, 'a.png', encodePng(16, 16, stripes));
put(d, 'b.jpg', Buffer.from('not really a jpeg'));
expect(hashFile(join(d, 'a.png')).hash).not.toBeNull();
const j = hashFile(join(d, 'b.jpg'));
expect(j.hash).toBeNull();
expect(j.reason).toBeTruthy();
});
});
describe('text and structure', () => {
test('words, cosine + shingles, names', () => {
expect(words('The FREE app: Merge, match & win!')).toEqual(['merge', 'match', 'win']);
const a = 'Merge fruit tiles to grow a garden. Daily puzzles, calm music and hundreds of levels to relax.';
const copied = 'Merge fruit tiles to grow a garden. Daily puzzles, calm music and hundreds of levels to unwind.';
const other = 'Track your running pace and heart rate with GPS, plan intervals and share routes with friends.';
expect(textSimilarity(a, copied).score).toBeGreaterThan(0.8);
expect(textSimilarity(a, other).score).toBeLessThan(0.1);
expect(nameSimilarity('Fruit Merge Garden', 'Fruit Merge Garden 2')).toBeGreaterThan(0.85);
expect(nameSimilarity('Fruit Merge', 'Pace Runner')).toBeLessThan(0.3);
expect(jaccard(new Set([1, 2]), new Set([2, 3]))).toBeCloseTo(1 / 3);
expect(screenshotSimilarity([], [])).toBeNull();
});
test('project structure skips build output and dependencies', () => {
const d = join(tmp, 'struct');
put(d, 'src/main.ts', 'console.log(1)');
put(d, 'node_modules/x/index.js', 'x');
put(d, 'android/app/build/outputs/a.aab', 'x');
put(d, '.git/HEAD', 'ref');
const s = projectStructure(d);
expect([...s.paths]).toEqual(['src/main.ts']);
expect(s.contents.size).toBe(1);
});
});
/** One app folder: config, App Store listing, icon, three screenshots, a few source files. */
function app(dir: string, o: { name: string; bundle: string; subtitle: string; description: string; keywords: string; icon: (x: number, y: number) => [number, number, number, number]; scene: (k: number) => (x: number, y: number) => [number, number, number, number]; src: Record<string, string> }): string {
put(dir, 'storebound.config.ts', `export default { app: { name: ${JSON.stringify(o.name)}, privacyPolicyUrl: 'https://example.com/p', supportUrl: 'https://example.com', website: 'https://example.com', contactEmail: 'hi@example.com' },
languages: [{ id: 'en', apple: 'en-US' }], apple: { bundleId: '${o.bundle}' }, renders: 'store/renders' };\n`);
put(dir, 'store/appstore.md', `# listing\n\n## en-US\n\n### subtitle\n\`\`\`\n${o.subtitle}\n\`\`\`\n\n### promotionalText\n\`\`\`\n${o.subtitle}\n\`\`\`\n\n### keywords\n\`\`\`\n${o.keywords}\n\`\`\`\n\n### description\n\`\`\`\n${o.description}\n\`\`\`\n`);
put(dir, 'store/icon.png', encodePng(64, 64, o.icon));
for (let k = 0; k < 3; k++) put(dir, `store/renders/en/phone-6.9/0${k + 1}.png`, encodePng(48, 96, o.scene(k)));
for (const [f, t] of Object.entries(o.src)) put(dir, f, t);
return dir;
}
const engine = { 'src/engine.ts': 'export const grid = 8; // merge engine\n'.repeat(20), 'src/levels.json': JSON.stringify(Array.from({ length: 40 }, (_, i) => ({ i, goal: i * 10 }))), 'src/ui/board.ts': 'export function board() { return 1 }\n' };
describe('originality report', () => {
const ws = join(tmp, 'ws');
const me = app(join(ws, 'fruit'), { name: 'Fruit Merge Garden', bundle: 'com.example.fruit', subtitle: 'Merge fruit, grow a garden', keywords: 'merge,fruit,garden,puzzle,relax',
description: 'Merge fruit tiles to grow a garden. Daily puzzles, calm music and hundreds of levels to relax after work.', icon: disc(0), scene, src: { ...engine, 'src/theme.ts': 'export const theme = "fruit";' } });
app(join(ws, 'candy'), { name: 'Candy Merge Garden', bundle: 'com.example.candy', subtitle: 'Merge candy, grow a garden', keywords: 'merge,candy,garden,puzzle,relax',
description: 'Merge candy tiles to grow a garden. Daily puzzles, calm music and hundreds of levels to relax after work.', icon: disc(30), scene, src: { ...engine, 'src/theme.ts': 'export const theme = "candy";' } });
app(join(ws, 'pace'), { name: 'Pace Runner', bundle: 'com.example.pace', subtitle: 'Running pace and heart rate', keywords: 'run,pace,gps,interval,heart',
description: 'Track your running pace and heart rate with GPS, plan intervals and share routes with friends.', icon: stripes,
scene: k => (x, y) => (Math.floor((x + k * 7) / 6) % 2 ? [255, 255, 255, 255] : [y * 2, 0, 0, 255]), src: { 'App/Run.swift': 'struct Run {}', 'App/Map.swift': 'struct Map {}' } });
test('a reskin is flagged with reasons and suggestions; a different app is not', async () => {
const self = (await loadConfig(join(me, 'storebound.config.ts'))).config;
const others = findApps([ws], me);
expect(others.map(p => p.split('/').slice(-2, -1)[0])).toEqual(['candy', 'pace']);
const fps = await Promise.all(others.map(async p => { const l = await loadConfig(p); return fingerprint(l.config, l.root); }));
const r = report(fingerprint(self, me), fps);
const candy = r.pairs.find(p => p.other.name === 'Candy Merge Garden')!;
const pace = r.pairs.find(p => p.other.name === 'Pace Runner')!;
expect(candy.flagged).toBe(true);
expect(candy.overall).toBeGreaterThan(0.7);
expect(candy.axes.screenshots.score).toBe(1);
expect(candy.axes.icon.score!).toBeGreaterThan(0.6);
expect(candy.reasons.join()).toContain('screenshots');
expect(candy.suggestions.join('\n')).toContain('Unlike Candy Merge Garden');
expect(pace.flagged).toBe(false);
expect(pace.overall).toBeLessThan(0.35);
expect(r.pairs[0]!.other.name).toBe('Candy Merge Garden');
expect(r.flagged).toBe(1);
expect(compare(fps[1]!, fps[1]!).overall).toBe(1);
});
test('CLI: --json, exit 1 on a near-duplicate; text table otherwise', () => {
const run = (args: string[]) => Bun.spawnSync([process.execPath, join(ROOT, 'cli/index.ts'), 'originality', ...args], { cwd: me, stdout: 'pipe', stderr: 'pipe' });
const j = run(['--against', '..', '--json']);
expect(j.exitCode).toBe(1);
const out = JSON.parse(j.stdout.toString());
expect(out.flagged).toBe(1);
expect(out.pairs.map((p: { other: { name: string } }) => p.other.name)).toEqual(['Candy Merge Garden', 'Pace Runner']);
const only = run(["--against", "../pace"]);
expect(only.exitCode).toBe(0);
expect(only.stdout.toString()).toContain('Pace Runner');
const none = run([]);
expect(none.exitCode).toBe(1);
expect(none.stderr.toString()).toContain('nothing to compare with');
});
});