apps / health / catalog / validate: fixes from a read-only run against live store accounts

- API error bodies on one line (errorBody): Google and App Store Connect pretty-print errors, which hid
  SERVICE_DISABLED from the Play account check (reported permission instead of api-disabled), broke tables
  and turned serve's apps.list error into a JSON fragment
- apps list: failure says the reason and the fix (same words as apps check)
- newest App Store version by createdDate, iOS first (the API groups versions by platform); all versions
  read so no platform is missed; per-app reads four at a time
- apps check (apple): team app count from meta.paging.total with a one-app read
- Play Money without units (prices under 1.00) read as 0.xx, not NaN (catalog diff, subscription diffs)
- health: App Store Connect 404 for perfPowerMetrics / diagnosticSignatures means no field data yet;
  Play vitals behind a disabled Reporting API say so with the fix
- validate: gracRatingClassificationNumber optional, socialMediaAgeRestricted only when socialMedia is yes,
  socialMedia unanswered is a warning
- tests with sanitized recorded responses (tests/store-real-shapes.test.ts)
This commit is contained in:
CRTkafa 2026-10-10 20:50:26 +00:00
parent 8bb28db45c
commit b8da75e519
14 changed files with 342 additions and 34 deletions

View file

@ -2,6 +2,14 @@
## Unreleased
- Fixes from a read-only run against live store accounts: `apps check` says `api-disabled` (not `permission`) when the
Play Developer Reporting API is off, and `apps list` / serve `apps.list` fail with that reason and the fix instead of
a JSON fragment (API error bodies are kept on one line everywhere); the newest App Store version is the newest by
date (the API groups versions by platform), per-app reads run four at a time; the account check counts every app
of the team; Play prices under 1.00 (no `units` in the answer) no longer read as NaN in `catalog diff` and
subscription price diffs; `health` treats App Store Connect's 404 for builds without field data as no diagnostics;
`validate` no longer blocks on age rating fields accepted submissions leave empty (`gracRatingClassificationNumber`,
`socialMediaAgeRestricted` unless social media is yes; `socialMedia` is a warning).
- **Desktop machine interface** (`serve --stdio`): JSON-RPC session for the coming desktop app, built on the MCP core.
Typed methods with argument schemas, structured results, progress notifications, cancellation, `project.inspect`
and `portfolio.status`: apps across iOS and Android with identity, config check, release trains (current and next

View file

@ -3,6 +3,7 @@
import { createHash, createPrivateKey, sign } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { ascKey } from '../lib/credentials';
import { errorBody } from '../lib/http';
const b64 = (b: Buffer | string): string => Buffer.from(b).toString('base64url');
export const md5 = (b: Buffer | Uint8Array): string => createHash('md5').update(b).digest('hex');
@ -42,7 +43,7 @@ export async function ascClient(root: string, bundleId: string, appIdHint?: stri
});
const t = await r.text();
if ((r.status >= 500 || r.status === 429) && attempt < 5) { await Bun.sleep(2000 * attempt); return asc(method, path, body, attempt + 1); }
if (!r.ok) throw new Error(`${method} ${path} -> ${r.status} ${t.slice(0, 1500)}`);
if (!r.ok) throw new Error(`${method} ${path} -> ${r.status} ${errorBody(t)}`);
return t ? JSON.parse(t) : {};
}
@ -52,7 +53,7 @@ export async function ascClient(root: string, bundleId: string, appIdHint?: stri
const r = await fetch('https://api.appstoreconnect.apple.com' + path, { headers: { Authorization: 'Bearer ' + jwt(), Accept: accept } });
const t = await r.text();
if ((r.status >= 500 || r.status === 429) && attempt < 5) { await Bun.sleep(2000 * attempt); continue; }
if (!r.ok) throw new Error(`GET ${path} -> ${r.status} ${t.slice(0, 800)}`);
if (!r.ok) throw new Error(`GET ${path} -> ${r.status} ${errorBody(t, 800)}`);
return t ? JSON.parse(t) : {};
}
}

View file

@ -9,6 +9,7 @@ import type { Args } from './lib/args';
import { ascKey, playServiceAccount } from './lib/credentials';
import type { AccountCheck, AppsListResult } from './lib/desktop-protocol';
import { PLAY_SCOPE, REPORTING_SCOPE, tokenSource } from './lib/google-auth';
import { errorBody } from './lib/http';
import { log, printJson, warn } from './lib/log';
import { appleCheck, type Bytes, dataUrl, type Get, listAppleApps, listPlayApps, MAX_ICON_BYTES, playCheck } from './lib/store-apps';
import { textTable } from './lib/table';
@ -48,7 +49,7 @@ function googleGet(token: () => Promise<string>, base: string): Get {
const r = await fetch(path.startsWith('http') ? path : base + path, { headers: { Authorization: 'Bearer ' + (await token()) } });
const t = await r.text();
if ((r.status === 429 || r.status >= 500) && attempt < 3) { await Bun.sleep(1500 * (attempt + 1)); continue; }
if (!r.ok) throw new Error(`GET ${path.replace(/^https:\/\/[^/]+/, '')} -> ${r.status} ${/^\s*</.test(t) ? '(HTML error page)' : t.slice(0, 800)}`);
if (!r.ok) throw new Error(`GET ${path.replace(/^https:\/\/[^/]+/, '')} -> ${r.status} ${errorBody(t, 800)}`);
return t ? JSON.parse(t) : {};
}
};
@ -61,7 +62,7 @@ function playIcon(root: string): (pkg: string) => Promise<string | null> {
const call = async (method: string, url: string) => {
const r = await fetch(url, { method, headers: { Authorization: 'Bearer ' + (await token()) } });
const t = await r.text();
if (!r.ok) throw new Error(`${method} -> ${r.status} ${t.slice(0, 300)}`);
if (!r.ok) throw new Error(`${method} -> ${r.status} ${errorBody(t, 300)}`);
return t ? JSON.parse(t) : {};
};
return async pkg => {
@ -81,6 +82,8 @@ function playIcon(root: string): (pkg: string) => Promise<string | null> {
};
}
const principalOf = (root: string): string | null => { try { return playServiceAccount(root).client_email; } catch { return null; } };
export async function listApps(store: Store, root: string, icons: boolean): Promise<AppsListResult> {
const at = new Date().toISOString();
if (store === 'apple') {
@ -95,8 +98,9 @@ export async function listApps(store: Store, root: string, icons: boolean): Prom
export async function checkAccount(store: Store, root: string): Promise<AccountCheck> {
if (store === 'apple') {
try {
const page = await (await appleGet(root))('/v1/apps?fields[apps]=bundleId&limit=200');
return appleCheck({ apps: (page.data ?? []).length });
// one app is enough to prove the key; the team's app count is meta.paging.total
const page = await (await appleGet(root))('/v1/apps?fields[apps]=bundleId&limit=1');
return appleCheck({ apps: Number(page.meta?.paging?.total ?? (page.data ?? []).length) });
} catch (e) { return appleCheck({ error: e }); }
}
let principal: string | null = null;
@ -116,8 +120,11 @@ export async function run(args: Args): Promise<void> {
const out: AppsListResult[] = [];
for (const s of stores(args, root)) {
try { out.push(await listApps(s, root, args.has('icons'))); } catch (e) {
if (args.get('store')) throw e;
warn('apps', `${s}: ${(e as Error).message.split('\n')[0]}`);
// say what is wrong and how to fix it (the same words as `apps check`), not the raw API error
const c = s === 'apple' ? appleCheck({ error: e }) : playCheck(principalOf(root), { error: e });
const why = `${c.message}${c.fix ? ` Fix: ${c.fix}` : ''}`;
if (args.get('store')) throw new Error(why);
warn('apps', `${s}: ${why}`);
}
}
if (json) { printJson(args.get('store') ? out[0] : out); return; }

View file

@ -41,12 +41,14 @@ export async function collectAppleHealth(root: string, bundleId: string, appIdHi
const c = await ascClient(root, bundleId, appIdHint);
const appId = await c.app();
log('health', 'apple: power and performance metrics');
const metrics = parsePerfPower(await c.getAs(`/v1/apps/${appId}/perfPowerMetrics?filter[platform]=IOS`, 'application/vnd.apple.xcode-metrics+json'));
// App Store Connect answers 404 (not an empty list) while there is no field data yet: a new app, or TestFlight-only builds
const none = <T>(fallback: T) => (e: unknown): T => { if (/-> 404\b/.test(String(e))) return fallback; throw e; };
const metrics = parsePerfPower(await c.getAs(`/v1/apps/${appId}/perfPowerMetrics?filter[platform]=IOS`, 'application/vnd.apple.xcode-metrics+json').catch(none({})));
const builds = (await c.asc('GET', `/v1/builds?filter[app]=${appId}&filter[processingState]=VALID&sort=-uploadedDate&limit=3`)).data as J[];
const signatures: AppleHealth['signatures'] = [];
for (const b of builds) {
log('health', `apple: diagnostic signatures of build ${b.attributes.version}`);
for (const s of (await c.asc('GET', `/v1/builds/${b.id}/diagnosticSignatures?limit=10`)).data as J[])
for (const s of ((await c.asc('GET', `/v1/builds/${b.id}/diagnosticSignatures?limit=10`).catch(none({ data: [] }))).data ?? []) as J[])
signatures.push({ build: b.attributes.version, type: s.attributes.diagnosticType, signature: s.attributes.signature ?? '', weight: Number(s.attributes.weight ?? 0) });
}
signatures.sort((a, b) => b.weight - a.weight);

View file

@ -172,10 +172,18 @@ const levelFor = (v: number | null, limit: number): Level => (v === null ? 'ok'
/** Health -> validate findings. Over a Play bad behavior threshold = blocker (Play lowers discoverability and may
* warn users on the listing), from 80 % of it = warn. Apple publishes no thresholds: "poor" goals and heavy
* diagnostic signatures are warnings. */
/** A Google 403 for an API that is not enabled in the caller's Cloud project. */
export const REPORTING_OFF = /SERVICE_DISABLED|has not been used in project|accessNotConfigured/;
export function healthFindings(h: HealthSnapshot, o: { unreadable?: Level } = {}): Finding[] {
const f: Finding[] = [];
const play = h.play;
if (play && 'error' in play) f.push({ store: 'play', level: o.unreadable ?? 'warn', code: 'vitals', msg: `vitals not readable: ${play.error.slice(0, 200)}`, fix: 'store-health skill (Reporting API access)' });
if (play && 'error' in play) {
f.push(REPORTING_OFF.test(play.error)
? { store: 'play', level: o.unreadable ?? 'warn', code: 'vitals', msg: 'vitals not readable: the Google Play Developer Reporting API is off in the service account\'s Google Cloud project',
fix: 'Google Cloud console > APIs & Services > Library: enable "Google Play Developer Reporting API" in that project, wait a few minutes (store-health skill)' }
: { store: 'play', level: o.unreadable ?? 'warn', code: 'vitals', msg: `vitals not readable: ${play.error.slice(0, 200)}`, fix: 'store-health skill (Reporting API access)' });
}
else if (play) {
const crash = lastValue(play.crash, 'userPerceivedCrashRate28dUserWeighted') ?? weightedAverage(play.crash, 'userPerceivedCrashRate');
const anr = lastValue(play.anr, 'userPerceivedAnrRate28dUserWeighted') ?? weightedAverage(play.anr, 'userPerceivedAnrRate');

View file

@ -11,3 +11,15 @@ export async function checkUrl(url: string, o: { body?: boolean; timeoutMs?: num
return { url, status: null, error: (e as Error).message };
}
}
/**
* An API error body for an Error message: JSON on one line (App Store Connect and Google pretty-print their errors,
* which broke tables, `lastLine` in serve and matching on the error reason), an HTML page named as such, else the text
* with its whitespace collapsed. At most `max` characters.
*/
export function errorBody(text: string, max = 1500): string {
if (/^\s*</.test(text)) return '(HTML error page)';
let s: string;
try { s = JSON.stringify(JSON.parse(text)); } catch { s = text.replace(/\s+/g, ' ').trim(); }
return s.length > max ? s.slice(0, max) + '…' : s;
}

View file

@ -10,7 +10,9 @@ export function toMoney(currencyCode: string, value: number): Money {
return { currencyCode, units: String(Math.floor(cents / 100)), nanos: (cents % 100) * 10_000_000 };
}
export const fromMoney = (m: Money): number => Number(m.units) + (m.nanos ?? 0) / 1e9;
/** Google Money -> number. Proto3 JSON leaves out zero fields: a 0.99 price comes back as { nanos: 990000000 } with no
* units (and 1.00 with no nanos), so both default to 0. */
export const fromMoney = (m: Omit<Money, 'units'> & { units?: string | number | null }): number => Number(m.units ?? 0) + (m.nanos ?? 0) / 1e9;
export interface RegionConfig { regionCode: string; availability: 'AVAILABLE'; price: Money }

View file

@ -41,18 +41,18 @@ export async function listAppleApps(get: Get, o: { icons?: boolean; bytes?: Byte
raw.push(...(page.data ?? []));
url = page.links?.next ?? null;
}
const apps: StoreApp[] = [];
for (const a of raw) {
const one = async (a: J): Promise<StoreApp> => {
const app: StoreApp = {
store: 'ios', id: String(a.id), bundleId: String(a.attributes?.bundleId ?? ''), name: String(a.attributes?.name ?? a.attributes?.bundleId ?? a.id),
platforms: [], sku: a.attributes?.sku ?? null, primaryLocale: a.attributes?.primaryLocale ?? null, latest: null, icon: null,
};
try {
const vs: J[] = (await get(`/v1/apps/${a.id}/appStoreVersions?limit=5&fields[appStoreVersions]=platform,versionString,appStoreState,appVersionState,createdDate`)).data ?? [];
// App Store Connect groups this list by platform (not by date), so a short page can hide a platform and its
// first item is not the newest version: read them all (small, fields only) and sort by createdDate.
const vs: J[] = (await get(`/v1/apps/${a.id}/appStoreVersions?limit=200&fields[appStoreVersions]=platform,versionString,appStoreState,appVersionState,createdDate`)).data ?? [];
app.platforms = [...new Set(vs.map(v => String(v.attributes?.platform ?? '')).filter(Boolean))];
const v = vs[0];
if (v) app.latest = { version: String(v.attributes?.versionString ?? ''), state: ASC_STATE(v), platform: v.attributes?.platform ?? null };
} catch (e) { warnings.push(`${app.bundleId}: versions not read (${short(e)})`); }
app.latest = latestVersion(vs);
} catch (e) { warns.set(a, [...(warns.get(a) ?? []), `${app.bundleId}: versions not read (${short(e)})`]); }
if (o.icons && o.bytes) {
try {
const b: J = (await get(`/v1/builds?filter[app]=${a.id}&sort=-uploadedDate&limit=1&fields[builds]=iconAssetToken,version`)).data?.[0];
@ -61,13 +61,35 @@ export async function listAppleApps(get: Get, o: { icons?: boolean; bytes?: Byte
const img = await o.bytes(iconUrl(tpl));
if (img && img.data.length <= MAX_ICON_BYTES) app.icon = dataUrl(img.type, img.data);
}
} catch (e) { warnings.push(`${app.bundleId}: icon not read (${short(e)})`); }
} catch (e) { warns.set(a, [...(warns.get(a) ?? []), `${app.bundleId}: icon not read (${short(e)})`]); }
}
apps.push(app);
}
return app;
};
const warns = new Map<J, string[]>();
const apps = await pool(raw, APPLE_CONCURRENCY, one);
for (const a of raw) warnings.push(...(warns.get(a) ?? []));
return { apps: apps.sort((x, y) => x.name.localeCompare(y.name)), warnings };
}
/** Per-app App Store Connect reads in flight at once (a 50-app team took a minute one by one). */
export const APPLE_CONCURRENCY = 4;
/** fn over items, `n` at a time, results in input order. */
export async function pool<T, R>(items: T[], n: number, fn: (x: T) => Promise<R>): Promise<R[]> {
const out: R[] = new Array(items.length);
let next = 0;
await Promise.all(Array.from({ length: Math.min(n, items.length) }, async () => { while (next < items.length) { const i = next++; out[i] = await fn(items[i]!); } }));
return out;
}
/** Newest App Store version by createdDate; the iOS one when the app has iOS versions (the store-side twin of an
* Android app), else the newest of any platform. */
export function latestVersion(vs: J[]): StoreApp['latest'] {
const sorted = [...vs].sort((x, y) => String(y.attributes?.createdDate ?? '').localeCompare(String(x.attributes?.createdDate ?? '')));
const v = sorted.find(x => x.attributes?.platform === 'IOS') ?? sorted[0];
return v ? { version: String(v.attributes?.versionString ?? ''), state: ASC_STATE(v), platform: v.attributes?.platform ?? null } : null;
}
/** Every app a Play service account can see (all developer accounts that invited it), from the Reporting API. */
export async function listPlayApps(get: Get, o: { icon?: (pkg: string) => Promise<string | null> } = {}): Promise<{ apps: StoreApp[]; warnings: string[] }> {
const warnings: string[] = [];
@ -92,7 +114,13 @@ export async function listPlayApps(get: Get, o: { icon?: (pkg: string) => Promis
return { apps: apps.sort((x, y) => x.name.localeCompare(y.name)), warnings };
}
const short = (e: unknown): string => String((e as Error)?.message ?? e).split('\n')[0]!.slice(0, 200);
/** One readable line of an error: the API's own message (Google error.message, App Store Connect errors[].detail)
* after the "GET ... -> 403" head when the body is JSON, else the first line. */
const short = (e: unknown): string => {
const m = String((e as Error)?.message ?? e);
const api = /^(.*?-> \d{3}) .*?"(?:detail|message)":"((?:[^"\\]|\\.)*)"/.exec(m);
return (api ? `${api[1]} ${api[2]!.replace(/\\(.)/g, '$1')}` : m.split('\n')[0]!).slice(0, 200);
};
const statusOf = (e: unknown): number | null => { const m = /-> (\d{3})\b/.exec(String((e as Error)?.message ?? e)); return m ? Number(m[1]) : null; };
export const ASC_KEYS_URL = 'https://appstoreconnect.apple.com/access/integrations/api';
@ -127,16 +155,16 @@ export function playCheck(principal: string | null, outcome: { apps: number } |
? { store: 'android', status: 'ok', principal, apps: outcome.apps, message: `The service account can see ${outcome.apps} app${outcome.apps === 1 ? '' : 's'}.`, fix: null, docs: null }
: { store: 'android', status: 'permission', principal, apps: 0, message: 'The key works, but no developer account has invited this service account (it sees no apps).', fix: invite, docs: PLAY_USERS_URL };
}
const code = statusOf(outcome.error), msg = short(outcome.error);
if (code === 403 && /SERVICE_DISABLED|has not been used|is disabled|accessNotConfigured/i.test(msg))
const code = statusOf(outcome.error), msg = short(outcome.error), full = String((outcome.error as Error)?.message ?? outcome.error);
if (code === 403 && /SERVICE_DISABLED|has not been used|is disabled|accessNotConfigured/i.test(full))
return { store: 'android', status: 'api-disabled', principal, apps: null, message: 'The Google Play Developer Reporting API is off in this service account\'s Google Cloud project.',
fix: 'Google Cloud console > APIs & Services > Library: enable "Google Play Developer Reporting API" (and "Google Play Android Developer API") in the service account\'s project, wait a few minutes, test again.', docs: REPORTING_API_URL };
if (code === null && /invalid_grant|Invalid JWT|account not found|disabled/i.test(msg))
if (code === null && /invalid_grant|Invalid JWT|account not found|disabled/i.test(full))
return { store: 'android', status: 'revoked', principal, apps: null, message: `Google refused the key: ${msg}`,
fix: 'The JSON key was deleted or the service account disabled. Google Cloud console > IAM & Admin > Service accounts > Keys: add a new JSON key, then add it here again.', docs: null };
if (code === 403 || code === 401)
return { store: 'android', status: 'permission', principal, apps: null, message: `The service account is missing a permission (${code}).`, fix: invite, docs: PLAY_USERS_URL };
if (/not a Google service account|PLAY_SERVICE_ACCOUNT/i.test(msg))
if (/not a Google service account|PLAY_SERVICE_ACCOUNT/i.test(full))
return { store: 'android', status: 'error', principal, apps: null, message: msg, fix: 'Add the service account JSON key again (Google Cloud console > IAM & Admin > Service accounts > Keys > Add key > JSON).', docs: null };
return { store: 'android', status: 'error', principal, apps: null, message: `Could not reach Google: ${msg}`, fix: 'Check the connection and try again.', docs: null };
}

View file

@ -18,7 +18,7 @@
// https://developers.google.com/android-publisher/api-ref/rest/v3/monetization.subscriptions.basePlans.offers
import type { IntroOffer, Language, OfferCodeDef, PriceOverride, Subscription, SubscriptionGroup, SubscriptionOfferDef, SubscriptionPeriod } from './config';
import { playCodes } from './config';
import { ALPHA3, type Money, toMoney } from './money';
import { ALPHA3, fromMoney, type Money, toMoney } from './money';
import type { PriceRow } from './prices';
// ---- mappings ----
@ -428,7 +428,7 @@ export function playOfferBody(pkg: string, s: Subscription, regions: PlayRegionP
};
}
const moneyKey = (m?: Money): string => (m ? `${m.currencyCode} ${cents(Number(m.units) + (m.nanos ?? 0) / 1e9)}` : '-');
const moneyKey = (m?: Money): string => (m ? `${m.currencyCode} ${cents(fromMoney(m))}` : '-');
export interface PlaySubDiff { create: boolean; listings: string[]; basePlan: 'new' | 'same' | 'changed'; priceChanges: { regionCode: string; from: string; to: string }[]; activate: boolean }

View file

@ -108,7 +108,15 @@ const EDITABLE = ['PREPARE_FOR_SUBMISSION', 'DEVELOPER_REJECTED', 'REJECTED', 'M
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']);
// Left null on apps App Review accepted: gracRatingClassificationNumber (a Korean GRAC rating number, for apps GRAC
// rated), socialMediaAgeRestricted (asked only when socialMedia is true). socialMedia itself is a newer question that
// App Store Connect let submissions through without: a warning, not a blocker.
const AGE_OPTIONAL = new Set(['kidsAgeBand', 'ageRatingOverride', 'ageRatingOverrideV2', 'koreaAgeRatingOverride', 'developerAgeRatingInfoUrl', 'gracRatingClassificationNumber']);
const AGE_SOFT = new Set(['socialMedia']);
const ageOpen = (r: Record<string, unknown>): { open: string[]; soft: string[] } => {
const unset = Object.entries(r).filter(([k, v]) => v === null && !AGE_OPTIONAL.has(k) && !(k === 'socialMediaAgeRestricted' && r.socialMedia !== true)).map(([k]) => k);
return { open: unset.filter(k => !AGE_SOFT.has(k)), soft: unset.filter(k => AGE_SOFT.has(k)) };
};
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}`);
@ -154,9 +162,10 @@ export function appleRules(s: AppleSnapshot): Finding[] {
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);
const { open, soft } = ageOpen(s.ageRating);
if (open.length) add('blocker', 'age-rating', `age rating unanswered: ${open.join(', ')}`, 'storebound apple appinfo');
else add('ok', 'age-rating', 'age rating answered');
if (soft.length) add('warn', 'age-rating', `age rating question not answered yet: ${soft.join(', ')} (App Store Connect > App Information > Age Rating)`);
}
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',

View file

@ -2,6 +2,7 @@
import { playServiceAccount } from '../lib/credentials';
import { tokenSource } from '../lib/google-auth';
import { log } from '../lib/log';
import { errorBody } from '../lib/http';
export type PlayClient = Awaited<ReturnType<typeof playClient>>;
@ -24,7 +25,7 @@ export async function playClient(root: string, packageName: string) {
if ((r.status === 429 || r.status >= 500) && attempt < 4) { await Bun.sleep(2000 * (attempt + 1)); continue; }
const short = url.replace(API, '').replace(UPLOAD, '');
// A wrong path casing answers with an HTML 404 page, not JSON: say so instead of dumping the HTML.
const msg = /^\s*</.test(text) ? `(HTML ${r.status} page: wrong path or casing?)` : text.slice(0, 1500);
const msg = /^\s*</.test(text) ? `(HTML ${r.status} page: wrong path or casing?)` : errorBody(text);
throw new Error(`${method} ${short} -> ${r.status} ${msg}`);
}
}

View file

@ -2,6 +2,7 @@
// Reporting API (vitals) and Cloud Storage (Play statistics exports). Read-only callers; retries 429 / 5xx.
import { playServiceAccount } from '../lib/credentials';
import { tokenSource } from '../lib/google-auth';
import { errorBody } from '../lib/http';
export const REPORTING_API = 'https://playdeveloperreporting.googleapis.com/v1beta1';
@ -19,12 +20,12 @@ export function googleClient(root: string, scope: string) {
async json<T = unknown>(method: string, url: string, body?: unknown): Promise<T> {
const r = await send(method, url, body);
const t = await r.text();
if (!r.ok) throw new Error(`${method} ${url.replace(/^https:\/\/[^/]+/, '')} -> ${r.status} ${/^\s*</.test(t) ? '(HTML error page)' : t.slice(0, 800)}`);
if (!r.ok) throw new Error(`${method} ${url.replace(/^https:\/\/[^/]+/, '')} -> ${r.status} ${errorBody(t, 800)}`);
return (t ? JSON.parse(t) : {}) as T;
},
async bytes(url: string): Promise<Uint8Array> {
const r = await send('GET', url);
if (!r.ok) throw new Error(`GET ${url.replace(/^https:\/\/[^/]+/, '')} -> ${r.status} ${(await r.text()).slice(0, 300)}`);
if (!r.ok) throw new Error(`GET ${url.replace(/^https:\/\/[^/]+/, '')} -> ${r.status} ${errorBody(await r.text(), 300)}`);
return new Uint8Array(await r.arrayBuffer());
},
};

View file

@ -161,7 +161,7 @@ describe('storebound apps (CLI functions, mocked HTTP)', () => {
expect(r.store).toBe('ios');
expect(r.apps.length).toBe(3);
expect(r.apps.find(a => a.id === '6400000101')!.icon).toBe('data:image/png;base64,AQID');
expect(await checkAccount('apple', root)).toMatchObject({ status: 'ok', apps: 2 });
expect(await checkAccount('apple', root)).toMatchObject({ status: 'ok', apps: 3 }); // meta.paging.total of the team
globalThis.fetch = (async () => json({ errors: [{ status: '401', code: 'NOT_AUTHORIZED' }] }, 401)) as unknown as typeof fetch;
expect((await checkAccount('apple', root)).status).toBe('revoked');
});

View file

@ -0,0 +1,229 @@
// Shapes the real App Store Connect and Google APIs answered during a read-only run against live accounts, where they
// differ from what the first fixtures assumed. Every id, name, email and project number here is a placeholder.
// - Google and App Store Connect pretty-print error bodies (multi-line JSON): the reason (SERVICE_DISABLED) sits on a
// later line, tables broke and serve's last-line error became a JSON fragment.
// - appStoreVersions come grouped by platform, not newest first.
// - Play Money leaves out zero fields: 0.99 USD is { currencyCode, nanos } without units.
// - App Store Connect answers 404 for diagnostics / power metrics of a build or app with no field data yet.
// - Age rating fields an accepted submission left null (gracRatingClassificationNumber, socialMedia*).
import { afterEach, describe, expect, test } from 'bun:test';
import { generateKeyPairSync } from 'node:crypto';
import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { checkAccount, listApps, run as appsRun } from '../cli/apps';
import { collectAppleHealth } from '../cli/health';
import { parseArgs } from '../cli/lib/args';
import { healthFindings } from '../cli/lib/health';
import { errorBody } from '../cli/lib/http';
import { fromMoney } from '../cli/lib/money';
import { appleCheck, latestVersion, listAppleApps, playCheck, pool } from '../cli/lib/store-apps';
import { type AppleSnapshot, appleRules } from '../cli/lib/validate-rules';
type J = Record<string, unknown>;
// Google's 403 for an API that is off in the service account's Cloud project, as sent (pretty-printed).
const SERVICE_DISABLED_BODY = `{
"error": {
"code": 403,
"message": "Google Play Developer Reporting API has not been used in project 123456789000 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/playdeveloperreporting.googleapis.com/overview?project=123456789000 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.",
"status": "PERMISSION_DENIED",
"details": [
{
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "SERVICE_DISABLED",
"domain": "googleapis.com",
"metadata": {
"service": "playdeveloperreporting.googleapis.com",
"consumer": "projects/123456789000",
"containerInfo": "123456789000",
"activationUrl": "https://console.developers.google.com/apis/api/playdeveloperreporting.googleapis.com/overview?project=123456789000",
"serviceTitle": "Google Play Developer Reporting API"
}
}
]
}
}
`;
// App Store Connect's 404 for diagnostics of a build without field data, as sent (pretty-printed, space before colon).
const ASC_NOT_FOUND_BODY = `{
"errors" : [ {
"id" : "00000000-0000-0000-0000-000000000000",
"status" : "404",
"code" : "NOT_FOUND",
"title" : "The specified resource does not exist",
"detail" : "There is no resource of type '/v1/builds/{id}/diagnosticSignatures' with id 'build-1'"
} ]
}`;
// appStoreVersions of an iOS + macOS app: grouped by platform, macOS first, not sorted by date.
const VERSIONS_BY_PLATFORM = { data: [
{ type: 'appStoreVersions', id: 'v-mac-2', attributes: { platform: 'MAC_OS', versionString: '0.8.1', appStoreState: 'READY_FOR_SALE', appVersionState: 'READY_FOR_DISTRIBUTION', createdDate: '2026-09-28T09:36:56-07:00' } },
{ type: 'appStoreVersions', id: 'v-mac-1', attributes: { platform: 'MAC_OS', versionString: '0.7.1', appStoreState: 'READY_FOR_SALE', appVersionState: 'READY_FOR_DISTRIBUTION', createdDate: '2026-09-14T13:26:21-07:00' } },
{ type: 'appStoreVersions', id: 'v-ios-3', attributes: { platform: 'IOS', versionString: '0.8.1', appStoreState: 'READY_FOR_SALE', appVersionState: 'READY_FOR_DISTRIBUTION', createdDate: '2026-09-30T07:37:04-07:00' } },
{ type: 'appStoreVersions', id: 'v-ios-2', attributes: { platform: 'IOS', versionString: '0.8.0', appStoreState: 'READY_FOR_SALE', appVersionState: 'READY_FOR_DISTRIBUTION', createdDate: '2026-09-28T09:36:52-07:00' } },
{ type: 'appStoreVersions', id: 'v-ios-1', attributes: { platform: 'IOS', versionString: '0.7.0', appStoreState: 'READY_FOR_SALE', appVersionState: 'READY_FOR_DISTRIBUTION', createdDate: '2026-09-06T16:22:51-07:00' } },
], meta: { paging: { total: 5, limit: 200 } } };
const realFetch = globalThis.fetch;
const saved = { ...process.env };
afterEach(() => { globalThis.fetch = realFetch; for (const k of ['ASC_KEY_ID', 'ASC_ISSUER_ID', 'ASC_P8', 'PLAY_SERVICE_ACCOUNT']) { if (saved[k] === undefined) delete process.env[k]; else process.env[k] = saved[k]; } });
const json = (o: unknown, status = 200) => new Response(JSON.stringify(o), { status, headers: { 'content-type': 'application/json' } });
const raw = (text: string, status: number) => new Response(text, { status, headers: { 'content-type': 'application/json' } });
function playKey(): void {
const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
process.env.PLAY_SERVICE_ACCOUNT = JSON.stringify({ client_email: 'sb@example.com', private_key: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(), token_uri: 'https://oauth2.googleapis.com/token' });
}
function ascKey(): void {
const { privateKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' });
process.env.ASC_KEY_ID = 'ABCDE12345';
process.env.ASC_ISSUER_ID = '00000000-0000-0000-0000-000000000000';
process.env.ASC_P8 = privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();
}
describe('error bodies', () => {
test('pretty-printed JSON becomes one line; HTML is named; plain text collapses', () => {
const one = errorBody(SERVICE_DISABLED_BODY);
expect(one).not.toContain('\n');
expect(one).toContain('"reason":"SERVICE_DISABLED"');
expect(errorBody(ASC_NOT_FOUND_BODY)).toStartWith('{"errors":[{"id":');
expect(errorBody('<html><body>404</body></html>')).toBe('(HTML error page)');
expect(errorBody('upstream\n timed out')).toBe('upstream timed out');
expect(errorBody('x'.repeat(50), 10)).toBe('xxxxxxxxxx…');
});
});
describe('Play account check with the real 403', () => {
test('SERVICE_DISABLED on a later line of the body is api-disabled, not a permission problem', () => {
// the error as the getter built it before the fix: the raw, multi-line body after the status
const before = new Error(`GET /apps:search?pageSize=1000 -> 403 ${SERVICE_DISABLED_BODY}`);
expect(playCheck('sb@example.com', { error: before }).status).toBe('api-disabled');
const after = new Error(`GET /apps:search?pageSize=1000 -> 403 ${errorBody(SERVICE_DISABLED_BODY, 800)}`);
expect(playCheck('sb@example.com', { error: after }).status).toBe('api-disabled');
});
test('the CLI: check says api-disabled; list fails with the reason and the fix on one line', async () => {
playKey();
globalThis.fetch = (async (input: string | URL | Request) => {
const url = String(input instanceof Request ? input.url : input);
if (url === 'https://oauth2.googleapis.com/token') return json({ access_token: 'ya29.test', expires_in: 3600 });
if (url.startsWith('https://playdeveloperreporting.googleapis.com/v1beta1/apps:search')) return raw(SERVICE_DISABLED_BODY, 403);
return json({ error: 'not recorded' }, 404);
}) as typeof fetch;
const root = mkdtempSync(join(tmpdir(), 'sb-real-'));
const c = await checkAccount('play', root);
expect(c).toMatchObject({ status: 'api-disabled', principal: 'sb@example.com' });
await expect(listApps('play', root, false)).rejects.toThrow(/-> 403 \{"error":/);
const cwd = process.cwd();
process.chdir(root);
try {
let msg = '';
try { await appsRun(parseArgs(['list', '--store', 'play', '--json'], ['json', 'icons'])); } catch (e) { msg = (e as Error).message; }
expect(msg).not.toContain('\n');
expect(msg).toContain('Reporting API is off');
expect(msg).toContain('Fix: Google Cloud console');
} finally { process.chdir(cwd); }
});
});
describe('App Store Connect shapes', () => {
test('versions grouped by platform: platforms from every page item, newest iOS version by createdDate', async () => {
expect(latestVersion(VERSIONS_BY_PLATFORM.data)).toEqual({ version: '0.8.1', state: 'READY_FOR_DISTRIBUTION', platform: 'IOS' });
// only macOS: the newest of any platform
expect(latestVersion(VERSIONS_BY_PLATFORM.data.slice(0, 2).reverse())).toMatchObject({ version: '0.8.1', platform: 'MAC_OS' });
expect(latestVersion([])).toBeNull();
const calls: string[] = [];
const r = await listAppleApps(async p => {
calls.push(p);
if (p.startsWith('/v1/apps?')) return { data: [{ type: 'apps', id: '6400000201', attributes: { name: 'Example Aquarium', bundleId: 'com.example.aquarium', sku: 'AQ1', primaryLocale: 'en-US' } }], links: {} };
return VERSIONS_BY_PLATFORM;
});
expect(r.apps[0]).toMatchObject({ platforms: ['MAC_OS', 'IOS'], latest: { version: '0.8.1', platform: 'IOS' } });
expect(calls[1]).toContain('appStoreVersions?limit=200&');
});
test('per-app reads run a few at a time and keep the order of apps and warnings', async () => {
let inFlight = 0, most = 0;
const out = await pool([1, 2, 3, 4, 5, 6, 7, 8, 9], 4, async n => { inFlight++; most = Math.max(most, inFlight); await Bun.sleep(10 - n); inFlight--; return n * 2; });
expect(out).toEqual([2, 4, 6, 8, 10, 12, 14, 16, 18]);
expect(most).toBe(4);
const ids = Array.from({ length: 6 }, (_, i) => String(6400000300 + i));
const r = await listAppleApps(async p => {
if (p.startsWith('/v1/apps?')) return { data: ids.map(id => ({ type: 'apps', id, attributes: { name: `App ${id.slice(-1)}`, bundleId: `com.example.a${id.slice(-1)}` } })), links: {} };
await Bun.sleep(Number(p.split('/')[3]!.slice(-1)) % 3);
throw new Error(`GET ${p} -> 500 ${errorBody(ASC_NOT_FOUND_BODY)}`);
});
expect(r.warnings.map(w => w.split(':')[0])).toEqual(ids.map(id => `com.example.a${id.slice(-1)}`));
expect(r.warnings[0]).toContain('There is no resource of type');
});
test('account check counts the team\'s apps from meta.paging.total, one app read', async () => {
ascKey();
const seen: string[] = [];
globalThis.fetch = (async (input: string | URL | Request) => {
seen.push(String(input));
return json({ data: [{ type: 'apps', id: '6400000201', attributes: { bundleId: 'com.example.aquarium' } }], links: {}, meta: { paging: { total: 5, limit: 1 } } });
}) as typeof fetch;
expect(await checkAccount('apple', mkdtempSync(join(tmpdir(), 'sb-real-')))).toMatchObject({ status: 'ok', apps: 5 });
expect(seen).toEqual(['https://api.appstoreconnect.apple.com/v1/apps?fields[apps]=bundleId&limit=1']);
expect(appleCheck({ error: new Error(`GET /v1/apps -> 403 ${errorBody('{\n "errors" : [ { "status" : "403", "code" : "FORBIDDEN_ERROR" } ]\n}')}`) }).status).toBe('permission');
});
});
describe('health with no field data yet', () => {
test('404 for power metrics and diagnostic signatures means none, not an unreadable store', async () => {
ascKey();
globalThis.fetch = (async (input: string | URL | Request) => {
const url = String(input).replace('https://api.appstoreconnect.apple.com', '');
if (url.startsWith('/v1/apps/6400000401/perfPowerMetrics')) return raw(ASC_NOT_FOUND_BODY, 404);
if (url.startsWith('/v1/builds?filter[app]=6400000401')) return json({ data: [{ type: 'builds', id: 'build-1', attributes: { version: '11' } }, { type: 'builds', id: 'build-2', attributes: { version: '10' } }], links: {} });
if (url === '/v1/builds/build-1/diagnosticSignatures?limit=10') return raw(ASC_NOT_FOUND_BODY, 404);
if (url === '/v1/builds/build-2/diagnosticSignatures?limit=10') return json({ data: [{ type: 'diagnosticSignatures', id: 's1', attributes: { diagnosticType: 'HANGS', signature: 'main thread', weight: 0.4 } }] });
if (url.startsWith('/v1/apps/6400000401/betaFeedbackCrashSubmissions')) return json({ data: [], links: {} });
return raw(ASC_NOT_FOUND_BODY.replace('404', '500'), 418);
}) as typeof fetch;
const h = await collectAppleHealth(mkdtempSync(join(tmpdir(), 'sb-real-')), 'com.example.cutter', '6400000401', 7);
expect(h.metrics).toEqual([]);
expect(h.signatures).toEqual([{ build: '10', type: 'HANGS', signature: 'main thread', weight: 0.4 }]);
});
test('other errors still make the store unreadable', async () => {
ascKey();
globalThis.fetch = (async () => raw('{\n "errors" : [ { "status" : "403", "code" : "FORBIDDEN_ERROR" } ]\n}', 403)) as unknown as typeof fetch;
await expect(collectAppleHealth(mkdtempSync(join(tmpdir(), 'sb-real-')), 'com.example.cutter', '6400000401', 7)).rejects.toThrow(/-> 403 \{"errors"/);
});
test('Play vitals behind a disabled Reporting API: says so and how to turn it on', () => {
const f = healthFindings({ date: '2026-10-10', play: { error: `GET /v1beta1/apps/com.example.cutter/crashRateMetricSet -> 403 ${errorBody(SERVICE_DISABLED_BODY, 800)}` } });
expect(f).toEqual([expect.objectContaining({ store: 'play', level: 'warn', code: 'vitals', msg: expect.stringContaining('Reporting API is off') })]);
expect(f[0]!.fix).toContain('enable "Google Play Developer Reporting API"');
expect(f[0]!.msg).not.toContain('\n');
});
});
describe('Play money without units', () => {
test('0.99 comes back as nanos only; whole prices without nanos', () => {
expect(fromMoney({ currencyCode: 'USD', nanos: 990000000 })).toBeCloseTo(0.99, 9);
expect(fromMoney({ currencyCode: 'USD', units: '3' })).toBe(3);
expect(fromMoney({ currencyCode: 'USD', units: '2', nanos: 990000000 })).toBeCloseTo(2.99, 9);
});
});
describe('validate: age rating fields accepted submissions leave null', () => {
const snap = (ageRating: J): AppleSnapshot => ({
version: { versionString: '1.0.0', state: 'PREPARE_FOR_SUBMISSION' },
build: { number: '1', processingState: 'VALID', usesNonExemptEncryption: false, declarationState: null },
expectedLocales: ['en-US'], locales: [{ locale: 'en-US', subtitle: 's', description: 'd', keywords: 'k', screenshots: { APP_IPHONE_67: 5 } }],
requiredDisplayTypes: ['APP_IPHONE_67'],
reviewDetail: { contactEmail: 'review@example.com', contactPhone: '+1 555 0100', contactFirstName: 'A', contactLastName: 'B', notes: 'n' },
ageRating, priceSchedule: true, availability: true, iaps: [], expectedProducts: [], privacyUrl: { url: 'https://example.com/privacy', status: 200 },
});
// the declaration of an app in review (values as returned; 30 fields in 2026)
const IN_REVIEW: J = { advertising: true, gambling: false, kidsAgeBand: null, lootBox: false, messagingAndChat: false, socialMedia: null, socialMediaAgeRestricted: null,
userGeneratedContent: false, ageRatingOverride: 'NONE', ageRatingOverrideV2: 'NONE', koreaAgeRatingOverride: 'NONE', gracRatingClassificationNumber: null, developerAgeRatingInfoUrl: null };
test('no blocker; socialMedia unanswered is a warning', () => {
const f = appleRules(snap(IN_REVIEW)).filter(x => x.code === 'age-rating');
expect(f.map(x => x.level).sort()).toEqual(['ok', 'warn']);
const w = f.find(x => x.level === 'warn')!;
expect(w.msg).toContain('socialMedia');
expect(w.msg).not.toContain('socialMediaAgeRestricted');
});
test('socialMediaAgeRestricted is asked once socialMedia is yes; other nulls still block', () => {
expect(appleRules(snap({ ...IN_REVIEW, socialMedia: true })).find(x => x.code === 'age-rating')).toMatchObject({ level: 'blocker', msg: 'age rating unanswered: socialMediaAgeRestricted' });
expect(appleRules(snap({ ...IN_REVIEW, socialMedia: false, lootBox: null })).filter(x => x.code === 'age-rating').map(x => `${x.level}:${x.msg}`)).toEqual(['blocker:age rating unanswered: lootBox']);
});
});