CLI: store readiness, release management, export compliance, ASO audit, release notes, privacy manifest scan

- validate: read-only App Store Connect + Play report with ordered blockers (exit 1)
- apple release --phased on|pause|resume|complete and --manual-release (asks first)
- apple status --wait-review (exit 0 approved, 1 rejected, 7 timeout), apple next-build, apple encryption
- play rollout --fraction|--halt|--resume|--complete, play next-version-code
- check --aso, whats-new --since <tag>, privacy-manifest --ios <path>, version
- Apple IAP description limit is 45 characters (App Store Connect Help), not 55
- config: apple.usesNonExemptEncryption, apple.screenshotTypes, ads.appAdsTxt
This commit is contained in:
CRTkafa 2026-10-10 13:02:55 +00:00
parent 0ca1d464e4
commit f846fdc765
24 changed files with 1153 additions and 16 deletions

52
cli/apple/encryption.ts Normal file
View file

@ -0,0 +1,52 @@
// Export compliance for App Store builds, from apple.usesNonExemptEncryption in storebound.config.ts.
// storebound apple encryption [--build 42] [--dry]
// false (only OS-provided encryption such as HTTPS through the system): sets usesNonExemptEncryption = false on every
// build that has no answer yet (or on --build). Better: ITSAppUsesNonExemptEncryption = NO in Info.plist, then builds
// arrive answered.
// true: needs an approved encryption declaration (App Store Connect > App Information > App Encryption Documentation,
// with documents where required). This command lists the declarations and links the approved one to the builds; it
// never creates a declaration or claims an exemption for you (export-compliance skill).
// Not set: refuses. storebound never guesses this answer.
import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx';
import { done, log, warn } from '../lib/log';
import { ascClient, type J } from './asc';
export async function run(ctx: Ctx): Promise<void> {
const { config, root } = ctx.loaded;
const answer = config.apple?.usesNonExemptEncryption;
if (answer === undefined) throw new Error('apple.usesNonExemptEncryption is not set in storebound.config.ts. Decide it with the export-compliance skill (false only if the game uses no encryption beyond the OS); storebound never guesses it.');
const dry = ctx.args.has('dry');
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
const appId = await c.app();
const only = ctx.args.get('build');
const builds = (await c.all(`/v1/builds?filter[app]=${appId}&sort=-uploadedDate&limit=50`))
.filter(b => (only ? String(b.attributes.version) === only : b.attributes.usesNonExemptEncryption == null) && !b.attributes.expired);
if (only && !builds.length) throw new Error(`build ${only} not found (or expired)`);
log('apple', `${builds.length} build(s) to answer: ${builds.map(b => b.attributes.version).join(', ') || 'none'}`);
if (answer === false) {
for (const b of builds) {
if (b.attributes.usesNonExemptEncryption === false) { log('apple', `build ${b.attributes.version}: already exempt`); continue; }
if (!dry) await c.asc('PATCH', `/v1/builds/${b.id}`, { data: { type: 'builds', id: b.id, attributes: { usesNonExemptEncryption: false } } });
log('apple', `build ${b.attributes.version}: usesNonExemptEncryption = false${dry ? ' (dry)' : ''}`);
}
done('apple', 'encryption answered (add ITSAppUsesNonExemptEncryption = NO to Info.plist so new builds come answered)');
return;
}
const decls: J[] = await c.all(`/v1/appEncryptionDeclarations?filter[app]=${appId}&limit=50`);
for (const d of decls) log('apple', `declaration ${d.id}: ${d.attributes.appEncryptionDeclarationState} exempt=${d.attributes.exempt} code=${d.attributes.codeValue ?? '-'}`);
const approved = decls.find(d => d.attributes.appEncryptionDeclarationState === 'APPROVED');
if (!approved) {
warn('apple', 'no APPROVED encryption declaration: create it in App Store Connect > App Information > App Encryption Documentation (export-compliance skill), then re-run');
process.exitCode = 1;
return;
}
for (const b of builds) {
if (!dry) await c.asc('PATCH', `/v1/builds/${b.id}`, { data: { type: 'builds', id: b.id, attributes: { usesNonExemptEncryption: true },
relationships: { appEncryptionDeclaration: { data: { type: 'appEncryptionDeclarations', id: approved.id } } } } });
log('apple', `build ${b.attributes.version}: linked to declaration ${approved.id}${dry ? ' (dry)' : ''}`);
}
done('apple', 'encryption done');
}

View file

@ -4,6 +4,7 @@
// storebound apple iap [--dry] [--only id1,id2]
// Then `apple iap-review` for the review screenshots. First IAPs can only be submitted together with an app version,
// from the IAP page in the web UI (see the store-iap-setup skill).
import { APPLE_IAP_LIMITS } from '../lib/copy';
import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx';
import { done, log, step } from '../lib/log';
@ -48,7 +49,7 @@ export async function run(ctx: Ctx): Promise<void> {
for (const [langId, l] of Object.entries(p.listings)) {
const locale = langs.get(langId)?.apple;
if (!locale || have.has(locale)) continue;
if ([...l.description].length > 55) throw new Error(`${p.id} ${locale}: description over 55 characters (Apple limit)`);
if ([...l.description].length > APPLE_IAP_LIMITS.description) throw new Error(`${p.id} ${locale}: description over ${APPLE_IAP_LIMITS.description} characters (Apple limit)`);
await c.asc('POST', '/v1/inAppPurchaseLocalizations', { data: { type: 'inAppPurchaseLocalizations', attributes: { locale, name: l.title, description: l.description },
relationships: { inAppPurchaseV2: { data: { type: 'inAppPurchases', id } } } } });
log('apple', ` localization ${locale}`);

19
cli/apple/next-build.ts Normal file
View file

@ -0,0 +1,19 @@
// Next safe build number (CFBundleVersion) from App Store Connect: one above the highest build ever uploaded for the
// app, across every version train. Prints only the number on stdout, so scripts can use it:
// storebound apple next-build -> 42
// xcodebuild ... CURRENT_PROJECT_VERSION=$(storebound apple next-build)
// Then attach exactly that build: storebound apple listing --version x.y.z --build 42 (never "the latest").
import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx';
import { nextBuildNumber } from '../lib/release';
import { ascClient } from './asc';
export async function run(ctx: Ctx): Promise<void> {
const { config, root } = ctx.loaded;
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.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 next = nextBuildNumber(builds.map(b => String(b.attributes.version)));
console.error(`[apple] ${builds.length} builds on App Store Connect; next build number:`);
console.log(next);
}

59
cli/apple/release.ts Normal file
View file

@ -0,0 +1,59 @@
// Release management for an App Store version.
// storebound apple release --phased on|pause|resume|complete [--version 1.2.0] [--dry] [--yes]
// storebound apple release --manual-release [--version 1.2.0] [--yes]
// Phased release: 7-day automatic rollout to users with automatic updates (1, 2, 5, 10, 20, 50, 100 %); anyone can
// still update by hand from the App Store. Pause holds it (up to 30 days in total), it is NOT a rollback: users who
// updated keep the build. "complete" releases to everyone at once.
// --manual-release releases an approved version (PENDING_DEVELOPER_RELEASE). Public and irreversible: asks first.
// Neither --manual-release nor resume / complete is offered to agents through `storebound mcp`.
import type { Ctx } from '../lib/ctx';
import { confirm, need } from '../lib/ctx';
import { done, log } from '../lib/log';
import { type PhasedAction, phasedRequest } from '../lib/release';
import { ascClient, type J } from './asc';
export async function run(ctx: Ctx): Promise<void> {
const { config, root } = ctx.loaded;
const a = ctx.args;
const phased = a.get('phased') as PhasedAction | undefined;
const manual = a.has('manual-release');
if (!phased && !manual) throw new Error('usage: apple release --phased on|pause|resume|complete | --manual-release [--version x.y.z] [--dry] [--yes]');
if (phased && !['on', 'pause', 'resume', 'complete'].includes(phased)) throw new Error('--phased: on | pause | resume | complete');
const dry = a.has('dry');
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
const appId = await c.app();
const versions = await c.all(`/v1/apps/${appId}/appStoreVersions?filter[platform]=IOS&limit=20`);
const want = a.get('version');
const state = (v: J): string => v.attributes.appVersionState ?? v.attributes.appStoreState;
const v: J | undefined = want ? versions.find(x => x.attributes.versionString === want)
: manual ? versions.find(x => state(x) === 'PENDING_DEVELOPER_RELEASE')
: phased === 'on' ? versions.find(x => !['READY_FOR_DISTRIBUTION', 'READY_FOR_SALE', 'REPLACED_WITH_NEW_VERSION', 'REMOVED_FROM_SALE'].includes(state(x)))
: versions.find(x => ['READY_FOR_DISTRIBUTION', 'READY_FOR_SALE'].includes(state(x))) ?? versions[0];
if (!v) throw new Error(want ? `no version ${want}` : manual ? 'no version waiting for developer release (PENDING_DEVELOPER_RELEASE)' : 'no matching version');
const tag = `${v.attributes.versionString} (${state(v)})`;
if (manual) {
if (state(v) !== 'PENDING_DEVELOPER_RELEASE') throw new Error(`${tag}: only an approved version waiting for developer release can be released`);
const pr = (await c.maybe(`/v1/appStoreVersions/${v.id}/appStoreVersionPhasedRelease`))?.data;
const how = pr ? 'phased over 7 days (phased release is on)' : 'to everyone at once (no phased release)';
if (dry) { log('apple', `would release ${tag} ${how} (dry)`); return; }
if (!(await confirm(ctx, `Release ${tag} on the App Store now, ${how}? This is public.`))) return;
await c.asc('POST', '/v1/appStoreVersionReleaseRequests', { data: { type: 'appStoreVersionReleaseRequests',
relationships: { appStoreVersion: { data: { type: 'appStoreVersions', id: v.id } } } } });
done('apple', `release requested for ${tag}; the store updates within a few hours`);
return;
}
const cur = (await c.maybe(`/v1/appStoreVersions/${v.id}/appStoreVersionPhasedRelease`))?.data as J | undefined;
const req = phasedRequest(cur ? { id: cur.id, state: cur.attributes.phasedReleaseState } : null, phased!);
if (req.method === 'NONE') { log('apple', `${tag}: ${req.note}`); return; }
if (dry) { log('apple', `${tag}: would ${req.method === 'POST' ? 'turn phased release on' : `set phased release ${req.state}`} (dry)`); return; }
if ((phased === 'resume' || phased === 'complete') && !(await confirm(ctx, `${phased === 'complete' ? 'Release' : 'Resume the phased release of'} ${tag} ${phased === 'complete' ? 'to every user now' : ''}?`))) return;
if (req.method === 'POST') {
await c.asc('POST', '/v1/appStoreVersionPhasedReleases', { data: { type: 'appStoreVersionPhasedReleases',
relationships: { appStoreVersion: { data: { type: 'appStoreVersions', id: v.id } } } } });
} else {
await c.asc('PATCH', `/v1/appStoreVersionPhasedReleases/${cur!.id}`, { data: { type: 'appStoreVersionPhasedReleases', id: cur!.id, attributes: { phasedReleaseState: req.state } } });
}
done('apple', `${tag}: ${req.note}`);
}

View file

@ -2,16 +2,45 @@
// storebound apple status [--json]
// And the one write it offers: cancel a review submission (to re-add first IAPs to it from the web UI):
// storebound apple status --cancel-submission <id> [--yes]
// Wait for App Review (polls with backoff: 1 min, x1.5, max 15 min):
// storebound apple status --wait-review [--version 1.2.0] [--timeout 48h]
// exit codes: 0 approved, 1 rejected, 7 timeout (2 = nothing in review)
import type { Ctx } from '../lib/ctx';
import { confirm, need } from '../lib/ctx';
import { log } from '../lib/log';
import { ascClient } from './asc';
import { classifyReviewState, nextPollDelay, parseDuration, WAIT_EXIT } from '../lib/release';
import { type Asc, ascClient, type J } from './asc';
async function waitReview(ctx: Ctx, c: Asc, appId: string): Promise<never> {
const want = ctx.args.get('version');
const deadline = Date.now() + parseDuration(ctx.args.str('timeout', '48h'));
const state = (v: J): string => v.attributes.appVersionState ?? v.attributes.appStoreState;
let delay: number | null = null;
let last = '';
for (;;) {
const vs = await c.all(`/v1/apps/${appId}/appStoreVersions?filter[platform]=IOS&limit=10`);
const v = want ? vs.find(x => x.attributes.versionString === want) : vs.find(x => classifyReviewState(state(x)) === 'pending') ?? vs[0];
if (!v) { log('apple', `no version ${want ?? ''} found`); process.exit(2); }
const st = state(v);
const outcome = classifyReviewState(st);
if (st !== last) { log('apple', `${v.attributes.versionString}: ${st}`); last = st; }
if (outcome === 'approved') { log('apple', 'approved (release it yourself, or it goes out automatically if the release type says so)'); process.exit(WAIT_EXIT.approved); }
if (outcome === 'rejected') { log('apple', 'rejected: read the message in App Store Connect > App Review, then the review-rejections skill'); process.exit(WAIT_EXIT.rejected); }
if (outcome === 'not-submitted') { log('apple', 'nothing is waiting for review'); process.exit(2); }
delay = nextPollDelay(delay);
if (Date.now() + delay > deadline) { log('apple', 'timeout, still in review'); process.exit(WAIT_EXIT.timeout); }
log('apple', `next check in ${Math.round(delay / 1000)}s`);
await Bun.sleep(delay);
}
}
export async function run(ctx: Ctx): Promise<void> {
const { config, root } = ctx.loaded;
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
const appId = await c.app();
if (ctx.args.has('wait-review')) await waitReview(ctx, c, appId);
const cancel = ctx.args.get('cancel-submission');
if (cancel) {
if (!(await confirm(ctx, `Cancel review submission ${cancel}? (the version goes back to "Prepare for Submission")`))) return;

View file

@ -1,15 +1,30 @@
// Offline sanity check of everything the store commands read: config, both listing files, the screenshot copy, data
// safety answers, product texts vs store limits, and the files the config points at. No network, no credentials.
// storebound check
// storebound check everything above
// storebound check --aso keyword audit of both listing files (App Store keyword field, Play stuffing); exit 1 on errors
import { existsSync, readFileSync } from 'node:fs';
import { type AsoFinding, auditAso } from './lib/aso';
import { playCodes } from './lib/config';
import { len, parseAppStoreListing, parsePlayListing } from './lib/copy';
import { APPLE_IAP_LIMITS, len, parseAppStoreListing, parsePlayListing } from './lib/copy';
import type { Ctx } from './lib/ctx';
import { dataSafetyRows } from './lib/data-safety';
import { log, warn } from './lib/log';
import { type CopyFile, validateCopy } from './shots/lib';
function aso(ctx: Ctx): void {
const { config, resolve } = ctx.loaded;
const apple = config.apple ? parseAppStoreListing(readFileSync(resolve(config.apple.listing ?? 'store/appstore.md'), 'utf8')) : undefined;
const play = config.play ? parsePlayListing(readFileSync(resolve(config.play.listing ?? 'store/listing.md'), 'utf8'), config.app.name) : undefined;
const f: AsoFinding[] = auditAso({ apple, play, appName: config.app.name, storefront: ctx.args.get('storefront') ?? 'US' });
const tag = { error: 'ERROR', warn: 'warn ', info: 'info ' } as const;
for (const x of f) console.log(`${tag[x.level]} [${x.where}] ${x.msg}`);
const errors = f.filter(x => x.level === 'error').length;
log('aso', `${errors} errors, ${f.filter(x => x.level === 'warn').length} warnings, ${f.filter(x => x.level === 'info').length} hints`);
if (errors) process.exitCode = 1;
}
export async function run(ctx: Ctx): Promise<void> {
if (ctx.args.has('aso')) return aso(ctx);
const { config, resolve, path } = ctx.loaded;
log('check', `config ok: ${path}`);
const problems: string[] = [];
@ -21,6 +36,9 @@ export async function run(ctx: Ctx): Promise<void> {
const want = config.languages.flatMap(playCodes);
const missing = want.filter(c => !copy.some(x => x.lang === c));
if (missing.length) warn('check', `play listing has no section for ${missing.join(', ')}`);
const def = copy.find(x => x.lang === (config.play!.defaultLanguage ?? 'en-US'));
const same = copy.filter(x => def && x !== def && x.whatsNew && x.whatsNew === def.whatsNew && x.lang.slice(0, 2) !== def.lang.slice(0, 2));
if (same.length) warn('check', `what's new of ${same.map(x => x.lang).join(', ')} is the same text as ${def!.lang}: translate it`);
return `${copy.length} languages`;
});
if (config.apple) tryDo('appstore listing', () => {
@ -32,7 +50,7 @@ export async function run(ctx: Ctx): Promise<void> {
});
if (config.dataSafety) tryDo('data safety', () => `${dataSafetyRows(config.dataSafety!).length - 1} CSV rows`);
for (const p of config.products ?? []) for (const [lang, l] of Object.entries(p.listings)) {
if (config.apple && len(l.description) > 55) problems.push(`product ${p.id} ${lang}: description ${len(l.description)} > 55 (App Store limit)`);
if (config.apple && len(l.description) > APPLE_IAP_LIMITS.description) problems.push(`product ${p.id} ${lang}: description ${len(l.description)} > ${APPLE_IAP_LIMITS.description} (App Store limit)`);
if (len(l.description) > 200) problems.push(`product ${p.id} ${lang}: description ${len(l.description)} > 200 (Play limit)`);
}
if (config.shots) tryDo('shots copy', () => {

22
cli/index.ts Executable file → Normal file
View file

@ -6,14 +6,24 @@ import { loadConfig } from './lib/config';
import type { Ctx } from './lib/ctx';
type Mod = { run(ctx: Ctx): Promise<void> };
type Plain = { run(args: ReturnType<typeof parseArgs>): Promise<void> };
/** Commands that work without a storebound.config.ts. */
const PLAIN: Record<string, [() => Promise<Plain>, string]> = {
'init': [() => import('./init'), 'copy the templates (config, listing, copy, privacy policy) into this project'],
'privacy-manifest': [() => import('./privacy-manifest'), 'iOS PrivacyInfo.xcprivacy + required-reason API + SDK manifest scan (--ios <path>)'],
};
const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
'check': [() => import('./check'), 'validate config, copy files, data safety answers and products (offline)'],
'check': [() => import('./check'), 'validate config, copy files, data safety answers and products (offline); --aso keyword audit'],
'validate': [() => import('./validate'), 'read-only store readiness report with ordered blockers (--apple / --play); exit 1 on blockers'],
'whats-new': [() => import('./whats-new'), 'draft player-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 listing': [() => import('./play/listing'), 'app details + title / short / full description per language'],
'play images': [() => import('./play/images'), 'icon, feature graphic, phone / 7" / 10" screenshots per language'],
'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 status': [() => import('./play/status'), 'tracks, listings, products (read-only)'],
'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)'],
'apple bundle': [() => import('./apple/bundle'), 'register the bundle id; finds the app record'],
'apple iap': [() => import('./apple/iap'), 'in-app purchases, localizations, price schedules, availability'],
'apple iap-review': [() => import('./apple/iap-review'), 'IAP review screenshots + product states'],
@ -21,7 +31,10 @@ const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
'apple screenshots': [() => import('./apple/screenshots'), '6.9" + 6.5" screenshots per locale'],
'apple appinfo': [() => import('./apple/appinfo'), 'categories, age rating, content rights, Free price, territories'],
'apple review-details': [() => import('./apple/review-details'), 'App Review contact + notes'],
'apple status': [() => import('./apple/status'), 'versions, builds, IAPs, review submissions (--cancel-submission <id>)'],
'apple status': [() => import('./apple/status'), 'versions, builds, IAPs, review submissions (--wait-review, --cancel-submission <id>)'],
'apple release': [() => import('./apple/release'), 'phased release on|pause|resume|complete, --manual-release (asks first)'],
'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'],
'icons': [() => import('./icons'), 'App Store / Play / web / adaptive / legacy launcher icons from one artwork'],
'shots capture': [() => import('./shots/capture'), 'raw frames from a running build of your game (playwright)'],
'shots fonts': [() => import('./shots/fonts'), 'download font subsets for the copy (CJK / Arabic / Cyrillic ...)'],
@ -34,7 +47,7 @@ function help(): void {
usage: storebound <command> [options]
init copy the templates (config, listing, copy, privacy policy) into this project
${Object.entries(PLAIN).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)
@ -46,7 +59,8 @@ async function main(): Promise<void> {
const argv = process.argv.slice(2);
const [a, b] = argv;
if (!a || a === 'help' || a === '--help' || a === '-h') return help();
if (a === 'init') return (await import('./init')).run(parseArgs(argv.slice(1)));
if (a === 'version' || a === '--version') return console.log((await import('../package.json')).version);
if (PLAIN[a]) return (await PLAIN[a]![0]()).run(parseArgs(argv.slice(1)));
const key = COMMANDS[`${a} ${b}`] ? `${a} ${b}` : COMMANDS[a] ? a : '';
if (!key) { console.error(`unknown command: ${argv.slice(0, 2).join(' ')}\n`); help(); process.exit(2); }
const args = parseArgs(argv.slice(key.split(' ').length));

95
cli/lib/aso.ts Normal file
View file

@ -0,0 +1,95 @@
// Offline keyword audit over the two listing sources (store/appstore.md, store/listing.md). Pure.
// Rules are the boring, well-documented ones: use the App Store keyword field fully, do not waste it on words the
// name / subtitle already index, no duplicates, no stuffing in Play descriptions. Nothing here guesses search volume.
import type { AppleCopy, PlayCopy } from './copy';
import { len } from './copy';
export type AsoLevel = 'error' | 'warn' | 'info';
export interface AsoFinding { level: AsoLevel; where: string; msg: string }
/** Storefront -> App Store localizations that storefront supports (Apple's "App Store localizations" table, App Store
* Connect Help). Apple says keywords of a localization are searchable in every storefront that supports its language.
* That several localizations' keyword fields STACK in one storefront's search is community ASO knowledge, not an Apple
* statement: use it as a hint and verify with your own data. Add rows for other storefronts from Apple's table. */
export const CROSS_LOCALES: Record<string, string[]> = {
US: ['en-US', 'ar-SA', 'zh-Hans', 'zh-Hant', 'fr-FR', 'ko', 'pt-BR', 'ru', 'es-MX', 'vi'],
};
/** Words that add nothing in the keyword field (Apple: the category name and "app" are matched anyway). */
const FILLER = new Set(['app', 'apps', 'game', 'games', 'free', 'the', 'and', 'for', 'with', 'a', 'an', 'of', 'iphone', 'ipad', 'ios']);
const words = (s: string, locale: string): string[] =>
s.toLocaleLowerCase(locale).split(/[^\p{L}\p{N}]+/u).filter(w => w.length > 1);
/** One locale of the App Store listing: keyword field rules. */
export function auditAppleKeywords(locale: string, c: AppleCopy, appName: string): AsoFinding[] {
const out: AsoFinding[] = [];
const at = `apple ${locale}`;
const kw = c.keywords ?? '';
if (!kw) return [{ level: 'error', where: at, msg: 'keywords: empty' }];
const chars = len(kw);
if (chars > 100) out.push({ level: 'error', where: at, msg: `keywords: ${chars} characters > 100` });
if (/,\s|\s,/.test(kw)) out.push({ level: 'error', where: at, msg: 'keywords: spaces around commas waste characters' });
if (chars < 90) out.push({ level: 'warn', where: at, msg: `keywords: ${chars}/100 used; fill at least 90 (${100 - chars} characters free)` });
const terms = kw.split(',').map(t => t.trim().toLocaleLowerCase(locale)).filter(Boolean);
const seen = new Set<string>();
for (const t of terms) {
if (seen.has(t)) out.push({ level: 'warn', where: at, msg: `keywords: "${t}" listed twice` });
seen.add(t);
}
const indexed = new Set([...words(c.name ?? appName, locale), ...words(c.subtitle ?? '', locale)]);
const kwWords = terms.flatMap(t => words(t, locale));
const repeated = [...new Set(kwWords.filter(w => indexed.has(w)))];
if (repeated.length) out.push({ level: 'warn', where: at, msg: `keywords repeat words from the name / subtitle (already indexed): ${repeated.join(', ')}` });
const filler = [...new Set(kwWords.filter(w => FILLER.has(w)))];
if (filler.length) out.push({ level: 'info', where: at, msg: `keywords: filler words that rarely help: ${filler.join(', ')}` });
const multi = terms.filter(t => /\s/.test(t));
if (multi.length) out.push({ level: 'info', where: at, msg: `keywords: multi-word phrases (${multi.join(' | ')}); single words combine on their own and save characters` });
return out;
}
/** Which extra locales a storefront is commonly said to index, and which of them the listing fills. */
export function crossLocaleHint(storefront: string, locales: string[]): AsoFinding | null {
const extra = CROSS_LOCALES[storefront];
if (!extra) return null;
const have = extra.filter(l => locales.includes(l));
const free = extra.filter(l => !locales.includes(l));
return { level: 'info', where: `apple ${storefront} storefront`, msg:
`supports ${extra.join(', ')} (Apple table); stacked keyword indexing across them is unverified community knowledge. You fill ${have.join(', ') || 'none'}; ` +
`${free.length ? `free keyword room in ${free.join(', ')}: a locale there can carry extra keywords, but its text must still be a real translation` : 'all covered'}` };
}
/** Play: keyword placement without stuffing. Play indexes title, short and full description. */
export function auditPlayListing(c: PlayCopy): AsoFinding[] {
const out: AsoFinding[] = [];
const at = `play ${c.lang}`;
const loc = c.lang;
if (len(c.short) < 50) out.push({ level: 'info', where: at, msg: `short description ${len(c.short)}/80: room for the core keyword phrase` });
const full = words(c.full, loc);
if (full.length >= 80) {
const counts = new Map<string, number>();
for (const w of full) if (w.length > 3 && !FILLER.has(w)) counts.set(w, (counts.get(w) ?? 0) + 1);
for (const [w, n] of counts) {
const density = n / full.length;
if (n >= 6 && density > 0.03) out.push({ level: 'warn', where: at, msg: `full description: "${w}" ${n}x (${(density * 100).toFixed(1)}%): reads as keyword stuffing (Play metadata policy)` });
}
}
const firstLines = c.full.split('\n').slice(0, 3).join(' ');
const shortWords = new Set(words(c.short, loc).filter(w => w.length > 3));
if (shortWords.size && !words(firstLines, loc).some(w => shortWords.has(w)))
out.push({ level: 'info', where: at, msg: 'full description: the first lines share no word with the short description; lead with the core phrase' });
if (/\b(best|#1|no\.? ?1|top)\b/i.test(`${c.title} ${c.short}`)) out.push({ level: 'warn', where: at, msg: 'title / short: "best", "#1", "top" style claims are not allowed in Play metadata' });
if (/[A-Z]{6,}/.test(c.title) && c.title === c.title.toUpperCase()) out.push({ level: 'warn', where: at, msg: 'title: all caps (not allowed unless it is the brand)' });
if (/\p{Extended_Pictographic}/u.test(`${c.title} ${c.short}`)) out.push({ level: 'warn', where: at, msg: 'title / short: emoji are not allowed there' });
return out;
}
export interface AsoInput { apple?: Record<string, AppleCopy>; play?: PlayCopy[]; appName: string; storefront?: string }
export function auditAso(i: AsoInput): AsoFinding[] {
const out: AsoFinding[] = [];
for (const [locale, c] of Object.entries(i.apple ?? {})) out.push(...auditAppleKeywords(locale, c, i.appName));
if (i.apple) { const h = crossLocaleHint(i.storefront ?? 'US', Object.keys(i.apple)); if (h) out.push(h); }
for (const c of i.play ?? []) out.push(...auditPlayListing(c));
return out;
}

View file

@ -25,7 +25,7 @@ export interface Product {
/** Base price in USD. Play converts it per region (convertRegionPrices); Apple equalizes it from the USA base. */
usd: number;
overrides?: PriceOverride[];
/** Language id (see `languages`) -> title + description. Apple caps the description at 55 characters. */
/** Language id (see `languages`) -> title + description. Apple: title 30, description 45 characters. */
listings: Record<string, ProductListing>;
/** Apple only: internal reference name (defaults to the first listing title). */
referenceName?: string;
@ -141,9 +141,21 @@ export interface ShipConfig {
};
languages: Language[];
play?: { packageName: string; defaultLanguage?: string; listing?: string; icon?: string };
apple?: { bundleId: string; appId?: string; primaryLocale?: string; listing?: string; info?: AppleAppInfo; reviewShots?: string };
apple?: {
bundleId: string; appId?: string; primaryLocale?: string; listing?: string; info?: AppleAppInfo; reviewShots?: string;
/**
* Export compliance answer for every build (`storebound apple encryption`, `validate`). false ONLY when the game uses
* no encryption beyond what the OS provides (HTTPS / TLS through the system, standard auth). Never set it to false
* to skip the question: a wrong answer is a legal problem, not a store one. Unset = storebound will not answer.
*/
usesNonExemptEncryption?: boolean;
/** Screenshot display types every locale must have (validate). Default ["APP_IPHONE_67"]; add "APP_IPAD_PRO_3GEN_129" for iPad apps. */
screenshotTypes?: string[];
};
products?: Product[];
dataSafety?: DataSafety;
/** Ads: `validate` checks that <app.website>/app-ads.txt is reachable and contains every line listed here. */
ads?: { appAdsTxt?: string[] };
/** Rendered store graphics dir (<renders>/<languageId>/<size>/NN.png|jpg). Defaults to shots.out. */
renders?: string;
shots?: ShotsConfig;
@ -182,7 +194,12 @@ export function validateConfig(c: unknown): string[] {
if (cfg.apple) {
if (!ID_RE.test(cfg.apple.bundleId ?? '')) e.push('apple.bundleId: not a bundle id (com.example.game)');
if (cfg.apple.appId && !/^\d+$/.test(cfg.apple.appId)) e.push('apple.appId: numeric Apple ID of the app (App Store Connect > App Information)');
const enc = cfg.apple.usesNonExemptEncryption;
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.ads?.appAdsTxt && !cfg.ads.appAdsTxt.every(l => typeof l === 'string' && l.split(',').length >= 3))
e.push('ads.appAdsTxt: lines like "example-network.com, pub-123, DIRECT, abc123"');
const seen = new Set<string>();
for (const [i, p] of (cfg.products ?? []).entries()) {
const at = `products[${i}]`;

View file

@ -2,6 +2,10 @@
// limit checks; the consoles count characters (code points), so do we.
export const PLAY_LIMITS = { title: 30, short: 80, full: 4000, whatsNew: 500 } as const;
/** App Store Connect Help, "In-app purchase information": display name 2-30, description at most 45 characters.
* (The older App Store product page article says 55; App Store Connect enforces the Help reference.) */
export const APPLE_IAP_LIMITS = { name: 30, description: 45 } as const;
export const APPLE_LIMITS = { name: 30, subtitle: 30, promotionalText: 170, keywords: 100, description: 4000, whatsNew: 4000 } as const;
export interface PlayCopy { lang: string; title: string; short: string; full: string; whatsNew: string }

13
cli/lib/http.ts Normal file
View file

@ -0,0 +1,13 @@
// Plain URL reachability check for public pages (privacy policy, app-ads.txt). No credentials are ever sent.
import type { UrlCheck } from './validate-rules';
export async function checkUrl(url: string, o: { body?: boolean; timeoutMs?: number } = {}): Promise<UrlCheck> {
try {
const r = await fetch(url, { redirect: 'follow', signal: AbortSignal.timeout(o.timeoutMs ?? 15_000), headers: { 'User-Agent': 'storebound-validate' } });
const body = o.body ? (await r.text()).slice(0, 200_000) : undefined;
if (!o.body) await r.body?.cancel();
return { url, status: r.status, body };
} catch (e) {
return { url, status: null, error: (e as Error).message };
}
}

117
cli/lib/privacy-manifest.ts Normal file
View file

@ -0,0 +1,117 @@
// Apple privacy manifest (PrivacyInfo.xcprivacy) checks for an iOS project. Pure: callers pass file paths and text.
// What Apple requires (since May 2024): the app and every third-party SDK that uses a "required reason" API declare
// the API category and an approved reason in a PrivacyInfo.xcprivacy; SDKs on Apple's list of commonly used SDKs
// must ship their own manifest (and a signature when linked as a binary).
/** Required-reason API categories and the symbols that typically mean the code uses one. Heuristic, not a compiler. */
export const REQUIRED_REASON_APIS: Record<string, { symbols: RegExp; reasons: string[]; note: string }> = {
NSPrivacyAccessedAPICategoryUserDefaults: {
symbols: /\b(NSUserDefaults|UserDefaults)\b/,
reasons: ['CA92.1', '1C8F.1', 'C56D.1', 'AC6B.1'],
note: 'CA92.1 = read / write data only this app uses (typical for game saves and settings)',
},
NSPrivacyAccessedAPICategoryFileTimestamp: {
symbols: /\b(creationDate|modificationDate|fileModificationDate|contentModificationDateKey|creationDateKey|NSFileCreationDate|NSFileModificationDate|getattrlist|fstatat|lstat)\b/,
reasons: ['DDA9.1', 'C617.1', '3B52.1', '0A2A.1'],
note: 'C617.1 = timestamps of files inside the app container',
},
NSPrivacyAccessedAPICategorySystemBootTime: {
symbols: /\b(systemUptime|mach_absolute_time)\b/,
reasons: ['35F9.1', '8FFB.1', '3D61.1'],
note: '35F9.1 = measure elapsed time between in-app events',
},
NSPrivacyAccessedAPICategoryDiskSpace: {
symbols: /\b(NSFileSystemFreeSize|NSFileSystemSize|volumeAvailableCapacityKey|volumeAvailableCapacityForImportantUsageKey|volumeAvailableCapacityForOpportunisticUsageKey|volumeTotalCapacityKey|statfs|statvfs)\b/,
reasons: ['85F4.1', 'E174.1', '7D9E.1', 'B728.1'],
note: 'E174.1 = check there is room before writing files',
},
NSPrivacyAccessedAPICategoryActiveKeyboards: {
symbols: /\bactiveInputModes\b/,
reasons: ['3EC4.1', '54BD.1'],
note: 'rare in games',
},
};
/** Part of Apple's "commonly used third-party SDKs" list (must ship a manifest + signature). Check Apple's page for
* the current list: developer.apple.com/support/third-party-SDK-requirements */
export const LISTED_SDKS = ['Abseil', 'AFNetworking', 'Alamofire', 'AppAuth', 'BoringSSL', 'Capacitor', 'Charts', 'Cordova',
'DKImagePickerController', 'DKPhotoGallery', 'FBAEMKit', 'FBLPromises', 'FBSDKCoreKit', 'FBSDKCoreKit_Basics', 'FBSDKLoginKit',
'FBSDKShareKit', 'FirebaseABTesting', 'FirebaseAuth', 'FirebaseCore', 'FirebaseCoreDiagnostics', 'FirebaseCoreExtension',
'FirebaseCoreInternal', 'FirebaseCrashlytics', 'FirebaseDynamicLinks', 'FirebaseFirestore', 'FirebaseInstallations',
'FirebaseMessaging', 'FirebaseRemoteConfig', 'Flutter', 'FMDB', 'GoogleDataTransport', 'GoogleSignIn', 'GoogleToolboxForMac',
'GoogleUtilities', 'grpcpp', 'GTMAppAuth', 'GTMSessionFetcher', 'hermes', 'IQKeyboardManager', 'IQKeyboardManagerSwift',
'Kingfisher', 'leveldb', 'Lottie', 'MBProgressHUD', 'nanopb', 'OneSignal', 'OneSignalCore', 'OneSignalExtension',
'OneSignalOutcomes', 'OpenSSL', 'OrderedSet', 'Promises', 'Protobuf', 'Reachability', 'RealmSwift', 'RxCocoa', 'RxRelay',
'RxSwift', 'SDWebImage', 'SnapKit', 'Starscream', 'SVProgressHUD', 'SwiftyGif', 'SwiftyJSON', 'Toast', 'UnityFramework'];
export interface Manifest { path: string; tracking: boolean | null; trackingDomains: string[]; apis: Record<string, string[]>; collectedTypes: string[] }
/** Minimal plist reader for the keys a privacy manifest uses (no plist dependency). */
export function parseManifest(path: string, xml: string): Manifest {
const apis: Record<string, string[]> = {};
const accessed = /<key>NSPrivacyAccessedAPITypes<\/key>\s*<array>([\s\S]*?)<\/array>\s*(<key>|<\/dict>\s*<\/plist>)/.exec(xml)?.[1] ?? '';
for (const d of accessed.split(/<dict>/).slice(1)) {
const cat = /<key>NSPrivacyAccessedAPIType<\/key>\s*<string>([^<]+)<\/string>/.exec(d)?.[1];
if (!cat) continue;
const reasonsBlock = /<key>NSPrivacyAccessedAPITypeReasons<\/key>\s*<array>([\s\S]*?)<\/array>/.exec(d)?.[1] ?? '';
apis[cat.trim()] = [...reasonsBlock.matchAll(/<string>([^<]+)<\/string>/g)].map(m => m[1]!.trim());
}
const t = /<key>NSPrivacyTracking<\/key>\s*<(true|false)\s*\/>/.exec(xml)?.[1];
const domainsBlock = /<key>NSPrivacyTrackingDomains<\/key>\s*<array>([\s\S]*?)<\/array>/.exec(xml)?.[1] ?? '';
const collected = [...xml.matchAll(/<key>NSPrivacyCollectedDataType<\/key>\s*<string>([^<]+)<\/string>/g)].map(m => m[1]!.trim());
return { path, tracking: t === undefined ? null : t === 'true', trackingDomains: [...domainsBlock.matchAll(/<string>([^<]+)<\/string>/g)].map(m => m[1]!.trim()), apis, collectedTypes: collected };
}
/** Categories whose symbols appear in source text (file path -> categories hit). */
export function scanSources(files: { path: string; text: string }[]): Map<string, Set<string>> {
const hits = new Map<string, Set<string>>();
for (const f of files) for (const [cat, def] of Object.entries(REQUIRED_REASON_APIS)) {
if (!def.symbols.test(f.text)) continue;
if (!hits.has(cat)) hits.set(cat, new Set());
hits.get(cat)!.add(f.path);
}
return hits;
}
export interface SdkInfo { name: string; path: string; hasManifest: boolean }
export type PmLevel = 'blocker' | 'warn' | 'ok' | 'info';
export interface PmFinding { level: PmLevel; msg: string }
export interface PmInput {
appManifest: Manifest | null;
sourceHits: Map<string, Set<string>>;
sdks: SdkInfo[];
/** Info.plist has NSUserTrackingUsageDescription (the app asks for ATT). */
asksTracking: boolean;
}
export function evaluatePrivacyManifest(i: PmInput): PmFinding[] {
const out: PmFinding[] = [];
if (!i.appManifest) out.push({ level: 'blocker', msg: 'no PrivacyInfo.xcprivacy in the app target (Xcode > New File > App Privacy; add it to the app target)' });
else out.push({ level: 'ok', msg: `app manifest: ${i.appManifest.path}` });
const declared = i.appManifest?.apis ?? {};
for (const [cat, files] of i.sourceHits) {
const def = REQUIRED_REASON_APIS[cat]!;
const reasons = declared[cat];
const where = [...files].slice(0, 3).join(', ') + (files.size > 3 ? ` +${files.size - 3}` : '');
if (!reasons) out.push({ level: 'blocker', msg: `${cat} used (${where}) but not declared; ${def.note}` });
else if (!reasons.length) out.push({ level: 'blocker', msg: `${cat} declared without a reason; ${def.note}` });
else {
const bad = reasons.filter(r => !def.reasons.includes(r));
out.push(bad.length ? { level: 'warn', msg: `${cat}: unknown reason code(s) ${bad.join(', ')} (known: ${def.reasons.join(', ')})` }
: { level: 'ok', msg: `${cat}: declared (${reasons.join(', ')})` });
}
}
for (const cat of Object.keys(declared)) if (!i.sourceHits.has(cat)) out.push({ level: 'info', msg: `${cat} declared; no use found in the scanned app sources (fine if an SDK or plugin compiled into the app uses it)` });
if (i.asksTracking && i.appManifest && i.appManifest.tracking !== true)
out.push({ level: 'warn', msg: 'Info.plist asks for tracking (NSUserTrackingUsageDescription) but the manifest has NSPrivacyTracking false / missing; keep it consistent with App Privacy "used for tracking"' });
if (i.appManifest?.tracking && !i.appManifest.trackingDomains.length)
out.push({ level: 'info', msg: 'NSPrivacyTracking true without NSPrivacyTrackingDomains: list the tracking domains if your SDKs connect to them' });
for (const s of i.sdks) {
const listed = LISTED_SDKS.includes(s.name);
if (s.hasManifest) continue;
out.push({ level: listed ? 'blocker' : 'warn', msg: `${s.name} (${s.path}) ships no PrivacyInfo.xcprivacy${listed ? ': it is on Apple\'s list, update to a version with a manifest' : '; ad / analytics SDKs usually have one in newer versions'}` });
}
const order: Record<PmLevel, number> = { blocker: 0, warn: 1, info: 2, ok: 3 };
return out.sort((a, b) => order[a.level] - order[b.level]);
}

114
cli/lib/release.ts Normal file
View file

@ -0,0 +1,114 @@
// Pure helpers for release management on both stores: review state classification, polling backoff, next build
// numbers, Play staged rollout transitions and Apple phased release transitions.
export type ReviewOutcome = 'pending' | 'approved' | 'rejected' | 'not-submitted';
/** App Store version state -> what `apple status --wait-review` should do. */
export function classifyReviewState(state: string): ReviewOutcome {
if (['WAITING_FOR_REVIEW', 'IN_REVIEW', 'PENDING_APPLE_RELEASE', 'WAITING_FOR_EXPORT_COMPLIANCE', 'PROCESSING_FOR_APP_STORE', 'UNRESOLVED_ISSUES'].includes(state)) return 'pending';
if (['PENDING_DEVELOPER_RELEASE', 'PROCESSING_FOR_DISTRIBUTION', 'READY_FOR_DISTRIBUTION', 'READY_FOR_SALE', 'ACCEPTED', 'PREORDER_READY_FOR_SALE'].includes(state)) return 'approved';
if (['REJECTED', 'METADATA_REJECTED', 'INVALID_BINARY', 'DEVELOPER_REJECTED'].includes(state)) return 'rejected';
return 'not-submitted';
}
/** Exit codes of `apple status --wait-review`. */
export const WAIT_EXIT = { approved: 0, rejected: 1, timeout: 7 } as const;
/** Polling delay: starts at 60 s, x1.5 per round, capped at 15 min. */
export function nextPollDelay(prevMs: number | null, o: { first?: number; factor?: number; max?: number } = {}): number {
const first = o.first ?? 60_000;
const max = o.max ?? 15 * 60_000;
if (prevMs === null) return first;
return Math.min(max, Math.round(prevMs * (o.factor ?? 1.5)));
}
/** "48h", "90m", "30s", "2d" or plain seconds -> ms. */
export function parseDuration(s: string): number {
const m = /^(\d+(?:\.\d+)?)(s|m|h|d)?$/.exec(s.trim());
if (!m) throw new Error(`bad duration "${s}" (use 30m, 12h, 2d)`);
const mult = { s: 1e3, m: 6e4, h: 36e5, d: 864e5 }[(m[2] ?? 's') as 's' | 'm' | 'h' | 'd'];
return Math.round(Number(m[1]) * mult);
}
/** Compares build numbers like "12", "1.0.12" by numeric parts. */
export function compareBuild(a: string, b: string): number {
const pa = a.split('.').map(Number);
const pb = b.split('.').map(Number);
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
const d = (pa[i] ?? 0) - (pb[i] ?? 0);
if (d) return d;
}
return 0;
}
/** Next safe CFBundleVersion: one above the highest build ever uploaded for the app (any version train). */
export function nextBuildNumber(existing: string[]): string {
const valid = existing.filter(b => /^\d+(\.\d+){0,2}$/.test(b));
if (!valid.length) return '1';
const top = valid.sort(compareBuild).at(-1)!;
const parts = top.split('.');
parts[parts.length - 1] = String(Number(parts.at(-1)) + 1);
return parts.join('.');
}
/** Next Play versionCode: one above every code seen in bundles and tracks. Play caps it at 2100000000. */
export function nextVersionCode(codes: (string | number)[]): number {
const max = codes.map(Number).filter(n => Number.isInteger(n) && n > 0).reduce((a, b) => Math.max(a, b), 0);
if (max + 1 > 2_100_000_000) throw new Error('versionCode would exceed 2100000000');
return max + 1;
}
export interface PlayRelease { name?: string; versionCodes?: string[]; status: string; userFraction?: number; releaseNotes?: unknown[]; [k: string]: unknown }
export type RolloutAction = { kind: 'fraction'; value: number } | { kind: 'halt' } | { kind: 'resume'; value?: number } | { kind: 'complete' };
/**
* New releases array for a track after a staged-rollout action. Works on the release that is being rolled out
* (inProgress or halted). Completing keeps only that release (Play drops the older completed one itself).
*/
export function rolloutReleases(releases: PlayRelease[], a: RolloutAction): { releases: PlayRelease[]; summary: string } {
const staged = releases.find(r => r.status === 'inProgress' || r.status === 'halted');
if (!staged) throw new Error(`no staged rollout on this track (releases: ${releases.map(r => r.status).join(', ') || 'none'}); start one with play release --production inProgress --fraction 0.05`);
const codes = (staged.versionCodes ?? []).join(',');
const others = releases.filter(r => r !== staged);
const now = staged.userFraction ?? 0;
const pct = (x: number) => `${Math.round(x * 1000) / 10}%`;
switch (a.kind) {
case 'fraction': {
if (!(a.value > 0 && a.value < 1)) throw new Error('--fraction must be between 0 and 1 (exclusive); use --complete for 100%');
if (staged.status === 'halted') throw new Error('rollout is halted: use --resume [--fraction x]');
if (a.value < now) throw new Error(`rollout is at ${pct(now)}; Play does not lower a fraction (halt instead)`);
return { releases: [...others, { ...staged, userFraction: a.value }], summary: `${codes}: ${pct(now)} -> ${pct(a.value)}` };
}
case 'halt':
if (staged.status === 'halted') return { releases, summary: `${codes}: already halted` };
return { releases: [...others, { ...staged, status: 'halted' }], summary: `${codes}: halted at ${pct(now)} (users who updated keep it)` };
case 'resume': {
if (staged.status !== 'halted') throw new Error('rollout is not halted');
const v = a.value ?? now;
if (!(v > 0 && v < 1)) throw new Error('resume needs a fraction between 0 and 1');
return { releases: [...others, { ...staged, status: 'inProgress', userFraction: v }], summary: `${codes}: resumed at ${pct(v)}` };
}
case 'complete': {
const { userFraction: _drop, ...rest } = staged;
return { releases: [{ ...rest, status: 'completed' }], summary: `${codes}: completed (100%)` };
}
}
}
export type PhasedAction = 'on' | 'pause' | 'resume' | 'complete';
/** Apple phased release: request for an action given the current phased release (or none). */
export function phasedRequest(current: { id: string; state: string } | null, action: PhasedAction):
{ method: 'POST' | 'PATCH' | 'NONE'; state?: string; note: string } {
if (action === 'on') {
if (current) return { method: 'NONE', note: `phased release already exists (${current.state})` };
return { method: 'POST', note: 'phased release on: starts when the version is released (7 days, 1% -> 100%)' };
}
if (!current) throw new Error('no phased release on this version (storebound apple release --phased on first)');
const want = { pause: 'PAUSED', resume: 'ACTIVE', complete: 'COMPLETE' }[action];
if (current.state === want) return { method: 'NONE', note: `already ${want}` };
if (current.state === 'COMPLETE') throw new Error('phased release is COMPLETE; nothing to change');
if (action === 'pause' && current.state !== 'ACTIVE') throw new Error(`can only pause an ACTIVE phased release (it is ${current.state})`);
if (action === 'resume' && current.state !== 'PAUSED') throw new Error(`can only resume a PAUSED phased release (it is ${current.state})`);
return { method: 'PATCH', state: want, note: { pause: 'paused (max 30 days in total; users can still update manually)', resume: 'resumed', complete: 'released to everyone' }[action] };
}

168
cli/lib/validate-rules.ts Normal file
View file

@ -0,0 +1,168 @@
// Store readiness rules for `storebound validate`. Pure: the command collects a snapshot from both APIs (read-only),
// these functions turn it into an ordered list of findings. Order = the order you would fix things in.
export type Level = 'blocker' | 'warn' | 'ok';
export interface Finding { store: 'apple' | 'play'; level: Level; code: string; msg: string; fix?: string }
export interface UrlCheck { url: string; status: number | null; error?: string; body?: string }
export interface AppleSnapshot {
version: { versionString: string; state: string } | null;
build: { number: string; processingState: string; usesNonExemptEncryption: boolean | null; declarationState: string | null } | null;
/** Locales the config expects (apple: entries of `languages`). */
expectedLocales: string[];
locales: { locale: string; name?: string; subtitle?: string; description?: string; keywords?: string; screenshots: Record<string, number> }[];
requiredDisplayTypes: string[];
reviewDetail: { contactEmail?: string | null; contactPhone?: string | null; contactFirstName?: string | null; contactLastName?: string | null; demoAccountRequired?: boolean; demoAccountName?: string | null; notes?: string | null } | null;
/** Age rating declaration attributes (null = not readable). */
ageRating: Record<string, unknown> | null;
priceSchedule: boolean;
availability: boolean;
iaps: { productId: string; state: string; reviewScreenshot: boolean }[];
expectedProducts: string[];
privacyUrl: UrlCheck;
}
export interface PlaySnapshot {
defaultLanguage: string;
expectedLanguages: string[];
listings: { language: string; title?: string; shortDescription?: string; fullDescription?: string; images: Record<string, number> }[];
privacyUrl: UrlCheck;
website: string | null;
appAds: UrlCheck | null;
appAdsLines: string[];
adsLikely: boolean;
tracks: { track: string; releases: { status: string; versionCodes: string[]; userFraction?: number }[] }[];
products: { productId: string; states: string[] }[];
expectedProducts: string[];
}
const EDITABLE = ['PREPARE_FOR_SUBMISSION', 'DEVELOPER_REJECTED', 'REJECTED', 'METADATA_REJECTED', 'INVALID_BINARY'];
const IN_FLIGHT = ['WAITING_FOR_REVIEW', 'IN_REVIEW', 'PENDING_DEVELOPER_RELEASE', 'PROCESSING_FOR_DISTRIBUTION', 'READY_FOR_DISTRIBUTION', 'READY_FOR_SALE', 'ACCEPTED'];
const IAP_OK = ['READY_TO_SUBMIT', 'WAITING_FOR_REVIEW', 'IN_REVIEW', 'APPROVED'];
/** Age rating questions whose null means "not answered" (kidsAgeBand null = not a kids app). */
const AGE_OPTIONAL = new Set(['kidsAgeBand', 'ageRatingOverride', 'ageRatingOverrideV2', 'koreaAgeRatingOverride', 'developerAgeRatingInfoUrl']);
const urlOk = (u: UrlCheck) => u.status !== null && u.status >= 200 && u.status < 300;
const urlMsg = (u: UrlCheck) => (u.status === null ? `unreachable (${u.error ?? 'no answer'})` : `HTTP ${u.status}`);
export function appleRules(s: AppleSnapshot): Finding[] {
const f: Finding[] = [];
const add = (level: Level, code: string, msg: string, fix?: string) => f.push({ store: 'apple', level, code, msg, fix });
if (!s.version) add('blocker', 'version', 'no App Store version being prepared', 'storebound apple listing --version x.y.z');
else if (EDITABLE.includes(s.version.state)) add('ok', 'version', `version ${s.version.versionString}: ${s.version.state}`);
else if (IN_FLIGHT.includes(s.version.state)) add('warn', 'version', `version ${s.version.versionString} is ${s.version.state} (nothing to prepare)`);
else add('warn', 'version', `version ${s.version.versionString}: ${s.version.state}`);
if (!s.build) add('blocker', 'build', 'no build attached to the version', 'storebound apple listing --version x.y.z --build N (pick the build number you just uploaded)');
else {
if (s.build.processingState !== 'VALID') add('blocker', 'build', `build ${s.build.number} is ${s.build.processingState}`, 'wait for VALID (storebound apple status), or upload a new build');
else add('ok', 'build', `build ${s.build.number} VALID and attached`);
if (s.build.usesNonExemptEncryption === null && !s.build.declarationState)
add('blocker', 'encryption', `build ${s.build.number}: export compliance not answered`, 'ITSAppUsesNonExemptEncryption in Info.plist, or storebound apple encryption (export-compliance skill)');
else if (s.build.usesNonExemptEncryption && s.build.declarationState !== 'APPROVED')
add('blocker', 'encryption', `build ${s.build.number} uses non-exempt encryption; declaration ${s.build.declarationState ?? 'missing'}`, 'export-compliance skill');
else add('ok', 'encryption', 'export compliance answered');
}
const have = new Map(s.locales.map(l => [l.locale, l] as const));
for (const loc of s.expectedLocales) if (!have.has(loc)) add('blocker', 'locale', `${loc}: no localization on the version`, 'storebound apple listing');
for (const l of s.locales) {
const miss = (['description', 'keywords', 'subtitle'] as const).filter(k => !l[k]);
if (miss.length) add('blocker', 'metadata', `${l.locale}: missing ${miss.join(', ')}`, 'store/appstore.md, then storebound apple listing');
for (const t of s.requiredDisplayTypes) if (!l.screenshots[t]) add('blocker', 'screenshots', `${l.locale}: no ${t} screenshots`, 'storebound apple screenshots');
}
if (s.locales.length && !f.some(x => x.code === 'metadata' || x.code === 'screenshots' || x.code === 'locale')) add('ok', 'metadata', `${s.locales.length} locales with text and screenshots`);
const r = s.reviewDetail;
if (!r) add('blocker', 'review-details', 'no App Review information', 'storebound apple review-details');
else {
const miss = (['contactFirstName', 'contactLastName', 'contactPhone', 'contactEmail'] as const).filter(k => !r[k]);
if (miss.length) add('blocker', 'review-details', `review contact missing ${miss.join(', ')}`, 'storebound apple review-details');
else if (r.demoAccountRequired && !r.demoAccountName) add('blocker', 'review-details', 'demo account required but not given');
else add('ok', 'review-details', 'review contact set');
if (!r.notes) add('warn', 'review-notes', 'no review notes: say where IAPs, Restore Purchases, ads and the privacy policy are', 'apple.info.reviewNotes');
}
if (!s.ageRating) add('blocker', 'age-rating', 'age rating declaration not readable / missing', 'storebound apple appinfo');
else {
const open = Object.entries(s.ageRating).filter(([k, v]) => v === null && !AGE_OPTIONAL.has(k)).map(([k]) => k);
if (open.length) add('blocker', 'age-rating', `age rating unanswered: ${open.join(', ')}`, 'storebound apple appinfo');
else add('ok', 'age-rating', 'age rating answered');
}
add(s.priceSchedule ? 'ok' : 'blocker', 'price', s.priceSchedule ? 'app price set' : 'no app price schedule', 'storebound apple appinfo');
add(s.availability ? 'ok' : 'blocker', 'availability', s.availability ? 'availability set' : 'no territory availability',
'storebound apple appinfo; if the API refuses the first availability record, set it once in App Store Connect > Pricing and Availability');
const iaps = new Map(s.iaps.map(i => [i.productId, i] as const));
for (const id of s.expectedProducts) if (!iaps.has(id)) add('blocker', 'iap', `${id}: not on App Store Connect`, 'storebound apple iap');
for (const i of s.iaps) {
if (!IAP_OK.includes(i.state)) add('blocker', 'iap', `${i.productId}: ${i.state}`, i.state === 'MISSING_METADATA' ? 'storebound apple iap + apple iap-review' : 'see the review-rejections skill');
else if (!i.reviewScreenshot && i.state !== 'APPROVED') add('blocker', 'iap', `${i.productId}: no review screenshot`, 'storebound apple iap-review');
}
if (s.iaps.length && !f.some(x => x.code === 'iap')) add('ok', 'iap', `${s.iaps.length} in-app purchases ready`);
add(urlOk(s.privacyUrl) ? 'ok' : 'blocker', 'privacy-url', `privacy policy ${s.privacyUrl.url}: ${urlMsg(s.privacyUrl)}`, 'privacy-policy skill');
return sortFindings(f);
}
export const PLAY_REQUIRED_IMAGES: Record<string, number> = { icon: 1, featureGraphic: 1, phoneScreenshots: 2 };
/** app-ads.txt lines compared without spaces and case (the format is case-insensitive except the ids, which we keep). */
export const normAdsLine = (l: string) => l.split('#')[0]!.split(',').map(p => p.trim().toLowerCase()).filter(Boolean).join(',');
export function playRules(s: PlaySnapshot): Finding[] {
const f: Finding[] = [];
const add = (level: Level, code: string, msg: string, fix?: string) => f.push({ store: 'play', level, code, msg, fix });
const have = new Map(s.listings.map(l => [l.language, l] as const));
if (!have.has(s.defaultLanguage)) add('blocker', 'listing', `no listing for the default language ${s.defaultLanguage}`, 'storebound play listing');
for (const lang of s.expectedLanguages) if (!have.has(lang)) add('blocker', 'listing', `${lang}: no listing`, 'storebound play listing');
for (const l of s.listings) {
const miss = (['title', 'shortDescription', 'fullDescription'] as const).filter(k => !l[k]);
if (miss.length) add('blocker', 'listing', `${l.language}: missing ${miss.join(', ')}`, 'storebound play listing');
for (const [type, n] of Object.entries(PLAY_REQUIRED_IMAGES)) if ((l.images[type] ?? 0) < n) add('blocker', 'images', `${l.language}: ${type} ${l.images[type] ?? 0}/${n}`, 'storebound play images');
}
if (s.listings.length && !f.some(x => x.code === 'listing' || x.code === 'images')) add('ok', 'listing', `${s.listings.length} listings with text and graphics`);
add(urlOk(s.privacyUrl) ? 'ok' : 'blocker', 'privacy-url', `privacy policy ${s.privacyUrl.url}: ${urlMsg(s.privacyUrl)}`, 'privacy-policy skill');
if (s.appAdsLines.length || s.adsLikely) {
if (!s.website) add('blocker', 'app-ads', 'no developer website on the listing (app-ads.txt is looked up there)', 'storebound play listing (app.website)');
else if (!s.appAds || !urlOk(s.appAds)) add(s.appAdsLines.length ? 'blocker' : 'warn', 'app-ads', `${s.website.replace(/\/$/, '')}/app-ads.txt: ${s.appAds ? urlMsg(s.appAds) : 'not checked'}`, 'ads-levelplay-checks skill');
else if (s.appAdsLines.length) {
const body = new Set((s.appAds.body ?? '').split(/\r?\n/).map(normAdsLine).filter(Boolean));
const missing = s.appAdsLines.filter(l => !body.has(normAdsLine(l)));
if (missing.length) add('blocker', 'app-ads', `app-ads.txt lacks ${missing.length} line(s): ${missing.slice(0, 3).join(' | ')}${missing.length > 3 ? ' ...' : ''}`, 'ads-levelplay-checks skill');
else add('ok', 'app-ads', `app-ads.txt has all ${s.appAdsLines.length} lines`);
} else add('warn', 'app-ads', 'app-ads.txt reachable; set ads.appAdsTxt in the config to check its lines');
}
const anyRelease = s.tracks.some(t => t.releases.length);
if (!anyRelease) add('blocker', 'tracks', 'no release on any track', 'storebound play release <aab>');
for (const t of s.tracks) for (const r of t.releases) {
if (r.status === 'halted') add('warn', 'tracks', `${t.track}: release ${r.versionCodes.join(',')} is halted`, 'storebound play rollout --resume (owner)');
if (r.status === 'inProgress') add('ok', 'tracks', `${t.track}: rollout ${Math.round((r.userFraction ?? 0) * 100)}% of ${r.versionCodes.join(',')}`);
}
if (anyRelease && !f.some(x => x.code === 'tracks')) add('ok', 'tracks', s.tracks.filter(t => t.releases.length).map(t => `${t.track}: ${t.releases.map(r => r.status).join('/')}`).join(', '));
const prods = new Map(s.products.map(p => [p.productId, p] as const));
for (const id of s.expectedProducts) {
const p = prods.get(id);
if (!p) add('blocker', 'products', `${id}: not on Play`, 'storebound play products');
else if (!p.states.includes('ACTIVE')) add('blocker', 'products', `${id}: purchase option ${p.states.join(',') || 'no state'}`, 'storebound play products');
}
if (s.expectedProducts.length && !f.some(x => x.code === 'products')) add('ok', 'products', `${s.expectedProducts.length} products active`);
return sortFindings(f);
}
/** Blockers first, then warnings, then ok; stable inside a level (rule order). */
export function sortFindings(f: Finding[]): Finding[] {
const rank: Record<Level, number> = { blocker: 0, warn: 1, ok: 2 };
return f.map((x, i) => [x, i] as const).sort(([a, i], [b, j]) => rank[a.level] - rank[b.level] || i - j).map(([x]) => x);
}
export function formatFindings(f: Finding[]): string {
const tag: Record<Level, string> = { blocker: 'BLOCKER', warn: 'warn ', ok: 'ok ' };
return f.map((x, i) => `${String(i + 1).padStart(2)}. ${tag[x.level]} [${x.store}] ${x.msg}${x.fix && x.level !== 'ok' ? `\n fix: ${x.fix}` : ''}`).join('\n');
}

100
cli/lib/whats-new.ts Normal file
View file

@ -0,0 +1,100 @@
// Player-facing release notes from commit subjects, and writing them into the two listing files. Pure.
// The draft is a starting point for a human: commit messages are written for developers, notes are for players.
import { len, PLAY_LIMITS } from './copy';
export const NOTES_LIMITS = { play: PLAY_LIMITS.whatsNew, apple: 4000 } as const;
/** Roughly what both stores show before "more" on a phone. */
export const HOOK_CHARS = 170;
const SKIP = /^(chore|ci|build|docs?|test|tests|refactor|style|revert|wip|merge|bump|release|lint|deps?)(\(.+?\))?!?:|^Merge |^v?\d+\.\d+\.\d+$|^Release\b/i;
const KIND: [RegExp, 'new' | 'fix' | 'better'][] = [
[/^feat(\(.+?\))?!?:\s*/i, 'new'],
[/^(fix|bugfix|hotfix)(\(.+?\))?!?:\s*/i, 'fix'],
[/^(perf|improve|ux|ui|balance|content)(\(.+?\))?!?:\s*/i, 'better'],
];
export interface NoteItem { kind: 'new' | 'fix' | 'better'; text: string }
/** Commit subjects -> note items: drops housekeeping, strips conventional prefixes and issue refs, dedupes. */
export function noteItems(subjects: string[]): NoteItem[] {
const out: NoteItem[] = [];
const seen = new Set<string>();
for (const raw of subjects) {
const s = raw.trim();
if (!s || SKIP.test(s) || /\[(skip notes|internal)\]/i.test(s)) continue;
let kind: NoteItem['kind'] = 'better';
let text = s;
for (const [re, k] of KIND) if (re.test(text)) { kind = k; text = text.replace(re, ''); break; }
text = text.replace(/\s*\((#|!)\d+\)\s*$/, '').replace(/\s*(closes|fixes|refs?)\s+#\d+.*$/i, '').trim();
if (!text) continue;
text = kind === 'fix' && !/^fix(ed)?\b/i.test(text) ? `Fixed: ${text[0]!.toLocaleLowerCase() + text.slice(1)}` : text[0]!.toLocaleUpperCase() + text.slice(1);
if (!/[.!?]$/.test(text)) text += '.';
const key = text.toLowerCase();
if (seen.has(key)) continue;
seen.add(key);
out.push({ kind, text });
}
const rank = { new: 0, better: 1, fix: 2 } as const;
return out.sort((a, b) => rank[a.kind] - rank[b.kind]);
}
/** Bullet list under a one-line hook, cut to `limit` characters at a whole line. */
export function formatNotes(items: NoteItem[], o: { hook?: string; limit: number }): string {
const hook = o.hook ?? (items.some(i => i.kind === 'new') ? 'New in this update:' : 'Fixes and polish in this update:');
if (!items.length) return 'Bug fixes and performance improvements.'.slice(0, o.limit);
const lines = [hook, ...items.map(i => `• ${i.text}`)];
let text = '';
for (const l of lines) {
const next = text ? `${text}\n${l}` : l;
if (len(next) > o.limit) break;
text = next;
}
return text;
}
/** Problems with a finished note text for one store. */
export function checkNotes(text: string, store: 'play' | 'apple'): string[] {
const e: string[] = [];
const n = len(text);
if (n > NOTES_LIMITS[store]) e.push(`${n} > ${NOTES_LIMITS[store]} characters`);
const firstBreak = text.indexOf('\n');
const hook = firstBreak < 0 ? text : text.slice(0, firstBreak);
if (len(hook) > HOOK_CHARS) e.push(`first line is ${len(hook)} characters; the part before "more" is about ${HOOK_CHARS}`);
if (/\b(bump|refactor|merge|ci|lint)\b/i.test(text)) e.push('reads like a commit log (bump / refactor / merge ...)');
return e;
}
const fence = (t: string) => '```\n' + t + '\n```';
/** Sets the "What's new" block of every `<!-- play: ... -->` section that contains `lang` (or of all, lang = '*'). */
export function setPlayWhatsNew(md: string, lang: string, text: string): { md: string; changed: string[] } {
const parts = md.split(/^(?=## )/m);
const changed: string[] = [];
const out = parts.map(sec => {
const m = /^<!--\s*play:\s*([^>]+?)\s*-->$/m.exec(sec);
if (!m) return sec;
const codes = m[1]!.split(',').map(s => s.trim());
if (lang !== '*' && !codes.includes(lang)) return sec;
changed.push(...codes);
const re = /(^### [^\n]*(what'?s new|release notes)[^\n]*\n)```[^\n]*\n[\s\S]*?\n```/im;
if (re.test(sec)) return sec.replace(re, (_a, h: string) => h + fence(text));
return sec.replace(/\s*$/, '') + `\n\n### What's new (max 500)\n${fence(text)}\n\n`;
});
return { md: out.join(''), changed };
}
/** Sets `### whatsNew` of one App Store locale section (or of all, locale = '*'). */
export function setAppleWhatsNew(md: string, locale: string, text: string): { md: string; changed: string[] } {
const parts = md.split(/^(?=## )/m);
const changed: string[] = [];
const out = parts.map(sec => {
if (!sec.startsWith('## ')) return sec;
const loc = sec.slice(3).split(/[\s·]/)[0]!.trim();
if (!/^[a-z]{2,3}(-[A-Za-z]{2,4})?$/.test(loc) || (locale !== '*' && loc !== locale)) return sec;
changed.push(loc);
const re = /(^### whatsNew[^\n]*\n)```[^\n]*\n[\s\S]*?\n```/m;
if (re.test(sec)) return sec.replace(re, (_a, h: string) => h + fence(text));
return sec.replace(/\s*$/, '') + `\n\n### whatsNew\n${fence(text)}\n\n`;
});
return { md: out.join(''), changed };
}

View file

@ -0,0 +1,24 @@
// Next Play versionCode: one above every code in uploaded bundles and on any track. Read-only (the edit is deleted).
// Prints only the number on stdout:
// storebound play next-version-code -> 43
// ./gradlew bundleRelease -PversionCode=$(storebound play next-version-code)
import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx';
import { nextVersionCode } from '../lib/release';
import { playClient } from './client';
export async function run(ctx: Ctx): Promise<void> {
const { config, root } = ctx.loaded;
const play = await playClient(root, need(config.play?.packageName, 'play.packageName'));
const e = await play.call<{ id: string }>('POST', `${play.API}/edits`, {});
try {
const bundles = (await play.call<{ bundles?: { versionCode: number }[] }>('GET', `${play.API}/edits/${e.id}/bundles`)).bundles ?? [];
const apks = (await play.call<{ apks?: { versionCode: number }[] }>('GET', `${play.API}/edits/${e.id}/apks`).catch(() => ({ apks: [] }))).apks ?? [];
const tracks = (await play.call<{ tracks?: { releases?: { versionCodes?: string[] }[] }[] }>('GET', `${play.API}/edits/${e.id}/tracks`)).tracks ?? [];
const codes = [...bundles.map(b => b.versionCode), ...apks.map(a => a.versionCode), ...tracks.flatMap(t => (t.releases ?? []).flatMap(r => r.versionCodes ?? []))];
console.error(`[play] ${codes.length} version codes seen; next versionCode:`);
console.log(nextVersionCode(codes));
} finally {
await play.call('DELETE', `${play.API}/edits/${e.id}`).catch(() => {});
}
}

42
cli/play/rollout.ts Normal file
View file

@ -0,0 +1,42 @@
// Staged rollout of the release on a Play track (production by default).
// storebound play rollout --fraction 0.2 | --halt | --resume [--fraction 0.1] | --complete [--track production] [--dry] [--yes]
// Start a staged rollout with: storebound play release --version-code N --production inProgress --fraction 0.05
// Halting stops new installs of the update; it is NOT a rollback (users who updated keep it). To roll back, ship a
// fixed build with a higher versionCode. Production changes ask for confirmation unless --yes, except --halt.
// Not offered to agents through `storebound mcp`.
import type { Ctx } from '../lib/ctx';
import { confirm, need } from '../lib/ctx';
import { done, log } from '../lib/log';
import { type PlayRelease, type RolloutAction, rolloutReleases } from '../lib/release';
import { playClient } from './client';
export function rolloutAction(a: Ctx['args']): RolloutAction {
const picked = ['halt', 'resume', 'complete'].filter(k => a.has(k));
if (picked.length > 1) throw new Error('pick one of --halt, --resume, --complete');
const f = a.get('fraction');
const value = f === undefined ? undefined : Number(f);
if (value !== undefined && Number.isNaN(value)) throw new Error('--fraction: a number like 0.2');
if (picked[0] === 'halt') return { kind: 'halt' };
if (picked[0] === 'complete') return { kind: 'complete' };
if (picked[0] === 'resume') return { kind: 'resume', value };
if (value === undefined) throw new Error('usage: play rollout --fraction 0.2 | --halt | --resume [--fraction x] | --complete [--track production]');
return { kind: 'fraction', value };
}
export async function run(ctx: Ctx): Promise<void> {
const { config, root } = ctx.loaded;
const action = rolloutAction(ctx.args);
const track = ctx.args.str('track', 'production');
const dry = ctx.args.has('dry');
const play = await playClient(root, need(config.play?.packageName, 'play.packageName'));
let confirmed = dry || action.kind === 'halt' || track !== 'production';
await play.edit(async id => {
const cur = await play.call<{ releases?: PlayRelease[] }>('GET', `${play.API}/edits/${id}/tracks/${track}`);
const next = rolloutReleases(cur.releases ?? [], action);
log('play', `${track}: ${next.summary}${dry ? ' (dry)' : ''}`);
if (!confirmed) confirmed = await confirm(ctx, `${track}: ${next.summary}. Apply?`);
if (!confirmed) throw new Error('not confirmed, nothing changed');
await play.call('PUT', `${play.API}/edits/${id}/tracks/${track}`, { track, releases: next.releases });
}, { dry, retries: 1 });
done('play', dry ? 'rollout checked (dry run, edit discarded)' : 'rollout updated');
}

74
cli/privacy-manifest.ts Normal file
View file

@ -0,0 +1,74 @@
// Local scan of an iOS project for Apple's privacy manifest rules (no network, no credentials, no config needed).
// storebound privacy-manifest --ios ios/App [--sdk-dirs node_modules/@capacitor,node_modules/some-plugin] [--json]
// Reports: the app's PrivacyInfo.xcprivacy, required-reason API categories used in app sources vs declared, tracking
// flag vs the ATT usage string, and every SDK (CocoaPods, .xcframework / .framework, SwiftPM checkouts, --sdk-dirs)
// without its own manifest. Heuristic text scan: it can miss uses inside binaries and flag harmless matches.
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
import { basename, join, relative, resolve } from 'node:path';
import type { Args } from './lib/args';
import { log } from './lib/log';
import { evaluatePrivacyManifest, type Manifest, parseManifest, scanSources, type SdkInfo } from './lib/privacy-manifest';
const SKIP = new Set(['.git', 'build', 'DerivedData', 'node_modules', '.build', 'xcuserdata']);
const SRC = /\.(swift|m|mm|c|cc|cpp|h|hpp)$/;
const POD_META = new Set(['Target Support Files', 'Headers', 'Local Podspecs', 'Pods.xcodeproj', 'Manifest.lock']);
function walk(dir: string, visit: (p: string, isDir: boolean) => boolean | void, depth = 0): void {
if (depth > 14) return;
let names: string[] = [];
try { names = readdirSync(dir); } catch { return; }
for (const n of names) {
if (SKIP.has(n)) continue;
const p = join(dir, n);
let st;
try { st = statSync(p); } catch { continue; }
const descend = visit(p, st.isDirectory());
if (st.isDirectory() && descend !== false) walk(p, visit, depth + 1);
}
}
function hasManifest(dir: string): boolean {
let found = false;
walk(dir, p => { if (basename(p) === 'PrivacyInfo.xcprivacy') found = true; return !found; });
return found;
}
export async function run(args: Args): Promise<void> {
const ios = args.get('ios');
if (!ios) throw new Error('usage: privacy-manifest --ios <path to the iOS project folder, e.g. ios/App> [--sdk-dirs a,b] [--json]');
const root = resolve(ios);
if (!existsSync(root)) throw new Error(`${root} does not exist`);
const sdks: SdkInfo[] = [];
const sdkRoots = new Set<string>();
const addSdk = (p: string) => { if (sdkRoots.has(p)) return; sdkRoots.add(p); sdks.push({ name: basename(p).replace(/\.(xc)?framework$/, ''), path: relative(process.cwd(), p), hasManifest: hasManifest(p) }); };
const pods = join(root, 'Pods');
if (existsSync(pods)) for (const n of readdirSync(pods)) if (!POD_META.has(n) && statSync(join(pods, n)).isDirectory()) addSdk(join(pods, n));
for (const extra of args.list('sdk-dirs')) {
const d = resolve(extra);
if (!existsSync(d)) continue;
const kids = readdirSync(d).filter(n => statSync(join(d, n)).isDirectory());
if (kids.some(k => k === 'ios' || k === 'src')) addSdk(d); else for (const k of kids) addSdk(join(d, k));
}
const manifests: string[] = [];
const sources: { path: string; text: string }[] = [];
let infoPlist = '';
walk(root, (p, isDir) => {
if ([...sdkRoots].some(s => p.startsWith(s + '/') || p === s)) return false;
if (isDir) {
if (/\.(xc)?framework$/.test(p)) { addSdk(p); return false; }
if (basename(p) === 'checkouts' && p.includes('SourcePackages')) { for (const n of readdirSync(p)) addSdk(join(p, n)); return false; }
return true;
}
const n = basename(p);
if (n === 'PrivacyInfo.xcprivacy') manifests.push(p);
else if (n === 'Info.plist' && !infoPlist && !/Tests?\//.test(p)) infoPlist = readFileSync(p, 'utf8');
else if (SRC.test(n) && statSync(p).size < 2_000_000) sources.push({ path: relative(process.cwd(), p), text: readFileSync(p, 'utf8') });
});
const appManifest: Manifest | null = manifests[0] ? parseManifest(relative(process.cwd(), manifests[0]), readFileSync(manifests[0], 'utf8')) : null;
log('privacy', `${sources.length} source files, ${sdks.length} SDKs, ${manifests.length} app manifest(s)`);
const findings = evaluatePrivacyManifest({ appManifest, sourceHits: scanSources(sources), sdks, asksTracking: /NSUserTrackingUsageDescription/.test(infoPlist) });
if (args.has('json')) console.log(JSON.stringify({ appManifest, sdks, findings }, null, 2));
else for (const f of findings) console.log(`${f.level.toUpperCase().padEnd(7)} ${f.msg}`);
if (findings.some(f => f.level === 'blocker')) process.exitCode = 1;
}

119
cli/validate.ts Normal file
View file

@ -0,0 +1,119 @@
// Store readiness report (read-only on both stores): what still blocks a submission, in the order to fix it.
// storebound validate [--apple] [--play] [--json]
// Without --apple / --play: every store the config has. Exit code 1 when there is at least one blocker.
// Reads only: GETs on App Store Connect, a Play edit that is opened, read and deleted (never committed), and plain GETs
// of the public privacy policy and app-ads.txt URLs.
import { ascClient, type J } from './apple/asc';
import { playCodes } from './lib/config';
import type { Ctx } from './lib/ctx';
import { checkUrl } from './lib/http';
import { log, warn } from './lib/log';
import { type AppleSnapshot, appleRules, type Finding, formatFindings, PLAY_REQUIRED_IMAGES, type PlaySnapshot, playRules } from './lib/validate-rules';
import { playClient } from './play/client';
import { listOneTimeProducts } from './play/products';
export async function collectApple(ctx: Ctx): Promise<AppleSnapshot> {
const { config, root } = ctx.loaded;
const c = await ascClient(root, config.apple!.bundleId, config.apple?.appId);
const appId = await c.app();
log('validate', 'apple: reading version, build, localizations');
const versions = await c.all(`/v1/apps/${appId}/appStoreVersions?filter[platform]=IOS&limit=10`);
const v: J = (await c.editableVersion()) ?? versions[0] ?? null;
let build: AppleSnapshot['build'] = null;
const locales: AppleSnapshot['locales'] = [];
let reviewDetail: AppleSnapshot['reviewDetail'] = null;
if (v) {
const b = (await c.maybe(`/v1/appStoreVersions/${v.id}/build`))?.data;
if (b) {
const decl = (await c.maybe(`/v1/builds/${b.id}/appEncryptionDeclaration`))?.data;
build = { number: b.attributes.version, processingState: b.attributes.processingState, usesNonExemptEncryption: b.attributes.usesNonExemptEncryption ?? null,
declarationState: decl?.attributes?.appEncryptionDeclarationState ?? null };
}
const info = await c.editableAppInfo();
const infoLocs = new Map((await c.all(`/v1/appInfos/${info.id}/appInfoLocalizations?limit=50`)).map((l: J) => [l.attributes.locale, l.attributes] as const));
for (const l of await c.all(`/v1/appStoreVersions/${v.id}/appStoreVersionLocalizations?limit=50`)) {
const sets = await c.all(`/v1/appStoreVersionLocalizations/${l.id}/appScreenshotSets?limit=50`);
const screenshots: Record<string, number> = {};
for (const s of sets) screenshots[s.attributes.screenshotDisplayType] = (await c.all(`/v1/appScreenshotSets/${s.id}/appScreenshots?limit=50`)).length;
const ia = infoLocs.get(l.attributes.locale) ?? {};
locales.push({ locale: l.attributes.locale, name: ia.name, subtitle: ia.subtitle, description: l.attributes.description, keywords: l.attributes.keywords, screenshots });
}
reviewDetail = (await c.maybe(`/v1/appStoreVersions/${v.id}/appStoreReviewDetail`))?.data?.attributes ?? null;
}
log('validate', 'apple: age rating, price, availability, in-app purchases');
const info = await c.editableAppInfo();
const ageRating = (await c.maybe(`/v1/appInfos/${info.id}/ageRatingDeclaration`))?.data?.attributes ?? null;
const sched = await c.maybe(`/v1/apps/${appId}/appPriceSchedule?include=manualPrices`);
const avail = await c.maybe(`/v1/apps/${appId}/appAvailabilityV2`);
const iaps: AppleSnapshot['iaps'] = [];
for (const p of await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`)) {
const shot = (await c.maybe(`/v2/inAppPurchases/${p.id}/appStoreReviewScreenshot`))?.data;
iaps.push({ productId: p.attributes.productId, state: p.attributes.state, reviewScreenshot: !!shot });
}
return {
version: v ? { versionString: v.attributes.versionString, state: v.attributes.appVersionState ?? v.attributes.appStoreState } : null,
build, locales, reviewDetail, ageRating,
expectedLocales: config.languages.map(l => l.apple).filter((x): x is string => !!x),
requiredDisplayTypes: config.apple?.screenshotTypes ?? ['APP_IPHONE_67'],
priceSchedule: !!sched?.included?.some((x: J) => x.type === 'appPrices'),
availability: !!avail?.data,
iaps, expectedProducts: (config.products ?? []).map(p => p.id),
privacyUrl: await checkUrl(config.app.privacyPolicyUrl),
};
}
export async function collectPlay(ctx: Ctx): Promise<PlaySnapshot> {
const { config, root } = ctx.loaded;
const play = await playClient(root, config.play!.packageName);
const e = await play.call<{ id: string }>('POST', `${play.API}/edits`, {});
log('validate', `play: read-only edit ${e.id} (deleted afterwards)`);
try {
const details = await play.call<{ defaultLanguage?: string; contactWebsite?: string }>('GET', `${play.API}/edits/${e.id}/details`);
const raw = (await play.call<{ listings?: { language: string; title?: string; shortDescription?: string; fullDescription?: string }[] }>('GET', `${play.API}/edits/${e.id}/listings`)).listings ?? [];
const listings: PlaySnapshot['listings'] = [];
for (const l of raw) {
const images: Record<string, number> = {};
for (const type of Object.keys(PLAY_REQUIRED_IMAGES))
images[type] = ((await play.call<{ images?: unknown[] }>('GET', `${play.API}/edits/${e.id}/listings/${l.language}/${type}`)).images ?? []).length;
listings.push({ ...l, images });
}
const tracks = ((await play.call<{ tracks?: { track: string; releases?: { status: string; versionCodes?: string[]; userFraction?: number }[] }[] }>('GET', `${play.API}/edits/${e.id}/tracks`)).tracks ?? [])
.map(t => ({ track: t.track, releases: (t.releases ?? []).map(r => ({ status: r.status, versionCodes: r.versionCodes ?? [], userFraction: r.userFraction })) }));
const products = (await listOneTimeProducts(play)).map(p => ({ productId: p.productId, states: (p.purchaseOptions ?? []).map(o => o.state ?? '') }));
const website = details.contactWebsite ?? null;
const appAdsLines = config.ads?.appAdsTxt ?? [];
const adsLikely = !!config.ads || Object.values(config.dataSafety?.data ?? {}).some(u => u.collect.includes('advertising'));
let appAds = null;
if (website && (appAdsLines.length || adsLikely)) {
try { appAds = await checkUrl(new URL('/app-ads.txt', website).href, { body: true }); } catch { appAds = { url: website, status: null, error: 'bad website URL' }; }
}
return {
defaultLanguage: details.defaultLanguage ?? config.play?.defaultLanguage ?? 'en-US',
expectedLanguages: config.languages.flatMap(playCodes), listings, tracks, products,
expectedProducts: (config.products ?? []).map(p => p.id),
privacyUrl: await checkUrl(config.app.privacyPolicyUrl), website, appAds, appAdsLines, adsLikely,
};
} finally {
await play.call('DELETE', `${play.API}/edits/${e.id}`).catch(() => {});
}
}
export async function run(ctx: Ctx): Promise<void> {
const { config } = ctx.loaded;
const a = ctx.args;
const both = !a.has('apple') && !a.has('play');
const findings: Finding[] = [];
if ((both || a.has('apple')) && config.apple) {
try { findings.push(...appleRules(await collectApple(ctx))); } catch (e) { findings.push({ store: 'apple', level: 'blocker', code: 'api', msg: (e as Error).message.slice(0, 400) }); }
} else if (a.has('apple')) warn('validate', 'no apple section in the config');
if ((both || a.has('play')) && config.play) {
try { findings.push(...playRules(await collectPlay(ctx))); } catch (e) { findings.push({ store: 'play', level: 'blocker', code: 'api', msg: (e as Error).message.slice(0, 400) }); }
} else if (a.has('play')) warn('validate', 'no play section in the config');
const blockers = findings.filter(f => f.level === 'blocker').length;
if (a.has('json')) console.log(JSON.stringify({ blockers, findings }, null, 2));
else {
console.log(formatFindings(findings));
log('validate', blockers ? `${blockers} blocker(s)` : 'no blockers (UI-only steps are not visible to the API: App Privacy, Play App content)');
}
if (blockers) process.exitCode = 1;
}

49
cli/whats-new.ts Normal file
View file

@ -0,0 +1,49 @@
// Draft player-facing release notes from the git log and write them into the listing files (text only; nothing is
// sent to a store). A human (or an agent with the whats-new skill) rewrites and translates before `play release` /
// `apple listing` push them.
// storebound whats-new [--since v1.1.0] [--lang en-US] [--all] [--hook "text"] [--dry]
// --since: default the latest tag (git describe --tags --abbrev=0); --lang: the Play code / App Store locale to write
// (default: the Play default language and the first App Store locale); --all: write the same draft into every
// language (to translate afterwards; `storebound check` warns while they are identical).
import { readFileSync, writeFileSync } from 'node:fs';
import type { Ctx } from './lib/ctx';
import { log, warn } from './lib/log';
import { checkNotes, formatNotes, NOTES_LIMITS, noteItems, setAppleWhatsNew, setPlayWhatsNew } from './lib/whats-new';
function git(args: string[], cwd: string): string {
const r = Bun.spawnSync(['git', ...args], { cwd, stdout: 'pipe', stderr: 'pipe' });
if (r.exitCode !== 0) throw new Error(`git ${args.join(' ')}: ${r.stderr.toString().trim()}`);
return r.stdout.toString();
}
export async function run(ctx: Ctx): Promise<void> {
const { config, root, resolve } = ctx.loaded;
const a = ctx.args;
const since = a.get('since') ?? (() => { try { return git(['describe', '--tags', '--abbrev=0'], root).trim(); } catch { return ''; } })();
const range = since ? `${since}..HEAD` : 'HEAD';
const subjects = git(['log', range, '--no-merges', '--format=%s'], root).split('\n').filter(Boolean);
const items = noteItems(subjects);
log('whats-new', `${subjects.length} commits since ${since || 'the first commit'} -> ${items.length} player-facing items`);
const hook = a.get('hook');
const play = formatNotes(items, { hook, limit: NOTES_LIMITS.play });
const apple = formatNotes(items, { hook, limit: NOTES_LIMITS.apple });
for (const [store, text] of [['play', play], ['apple', apple]] as const) for (const p of checkNotes(text, store)) warn('whats-new', `${store}: ${p}`);
console.log(`--- draft (Play, ${[...play].length}/500) ---\n${play}\n---`);
if (a.has('dry')) return;
const all = a.has('all');
if (config.play) {
const f = resolve(config.play.listing ?? 'store/listing.md');
const lang = all ? '*' : a.get('lang') ?? config.play.defaultLanguage ?? 'en-US';
const r = setPlayWhatsNew(readFileSync(f, 'utf8'), lang, play);
if (r.changed.length) { writeFileSync(f, r.md); log('whats-new', `${f}: ${r.changed.join(', ')}`); } else warn('whats-new', `${f}: no section for ${lang}`);
}
if (config.apple) {
const f = resolve(config.apple.listing ?? 'store/appstore.md');
const first = config.apple.primaryLocale ?? config.languages.find(l => l.apple)?.apple ?? 'en-US';
const locale = all ? '*' : a.get('lang') ?? first;
const r = setAppleWhatsNew(readFileSync(f, 'utf8'), locale, apple);
if (r.changed.length) { writeFileSync(f, r.md); log('whats-new', `${f}: ${r.changed.join(', ')}`); } else warn('whats-new', `${f}: no section for ${locale}`);
}
log('whats-new', 'draft written: edit it, translate every language, then storebound check');
}

View file

@ -1,6 +1,6 @@
{
"PLAY_SERVICE_ACCOUNT": "/absolute/path/to/play-service-account.json",
"ASC_KEY_ID": "ABC123DEFG",
"ASC_KEY_ID": "YOUR_KEY_ID",
"ASC_ISSUER_ID": "00000000-0000-0000-0000-000000000000",
"ASC_P8": "/absolute/path/to/AuthKey_<KEY_ID>.p8",
"reviewContact": { "firstName": "", "lastName": "", "phone": "+1 555 0100", "email": "review-contact@example.com" }

View file

@ -53,7 +53,7 @@ Expected: PEGI 3, ESRB Everyone, USK 0, IARC 3+. Apple age rating 4+ (all conten
- App record: App Store Connect > Apps > + > New App (platform, name, primary language, bundle id, SKU). No API.
- App Privacy: `app-privacy.md`, then **Publish**.
- Export compliance: put `ITSAppUsesNonExemptEncryption = NO` in Info.plist (only HTTPS / standard encryption) so
- Export compliance (export-compliance skill): `ITSAppUsesNonExemptEncryption = NO` in Info.plist only if true (HTTPS / OS encryption only) so
every build skips the question.
- First in-app purchases: from the IAP page "Add for Review" into the draft submission with the version (see the
store-iap-setup skill).

View file

@ -36,6 +36,10 @@ const config: ShipConfig = {
// appId: '1234567890', // Apple ID of the app record; looked up by bundle id when left out
listing: 'store/appstore.md',
reviewShots: 'store/iap-review',
// Export compliance (export-compliance skill). false ONLY if the game uses no encryption beyond the OS (HTTPS through
// the system). Left unset on purpose: decide it, then uncomment. Same answer as ITSAppUsesNonExemptEncryption.
// usesNonExemptEncryption: false,
// screenshotTypes: ['APP_IPHONE_67'], // what `storebound validate` requires per locale; iPad apps add APP_IPAD_PRO_3GEN_129
info: {
categories: { primary: 'GAMES', primarySubOne: 'GAMES_CASUAL', primarySubTwo: 'GAMES_PUZZLE', secondary: 'ENTERTAINMENT' },
ageRating: { advertising: true }, // everything else NONE / false
@ -89,6 +93,10 @@ const config: ShipConfig = {
},
},
// Ads: `storebound validate --play` checks <app.website>/app-ads.txt for these lines (copy them from your mediation
// dashboard's app-ads.txt page). Placeholder line below; replace it.
// ads: { appAdsTxt: ['example-network.com, pub-0000000000000000, DIRECT, 0000000000000000'] },
renders: 'store/renders',
shots: {

View file

@ -3,13 +3,14 @@
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"types": ["bun"],
"strict": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"noEmit": true,
"skipLibCheck": true
"skipLibCheck": true,
"resolveJsonModule": true
},
"include": ["cli", "tests", "templates/storebound.config.ts"]
"include": ["cli", "tests", "tools", "templates/storebound.config.ts"]
}