TestFlight through the App Store Connect API: apple testflight status | groups | testers | what-to-test | info | distribute

Beta groups from apple.testflight.groups (created when missing, never changed), testers from a CSV in .storebound/
(masked in logs, confirmation before Apple emails invitations, --remove / --invite), What to Test per locale from the
App Store listing (whatToTest or whatsNew), Test Information and Beta App Review details, builds by exact number to
groups, Beta App Review submission behind --submit-review and a confirmation. Pure planners in cli/lib/testflight.ts,
shared CSV / table / JSON:API helpers. MCP: apple_testflight_status, _groups, _what_to_test, _info, _distribute
(internal groups only). Skill testflight.
This commit is contained in:
CRTkafa 2026-10-10 15:08:37 +00:00
parent 9abe8b9f78
commit 48bd9780dd
19 changed files with 838 additions and 4 deletions

29
cli/apple/jsonapi.ts Normal file
View file

@ -0,0 +1,29 @@
// JSON:API request builders for App Store Connect. Pure: commands build `Req`s, print them on --dry and send them
// with the client otherwise. Request / response format: https://developer.apple.com/documentation/appstoreconnectapi
import { log } from '../lib/log';
export interface Req { method: 'GET' | 'POST' | 'PATCH' | 'DELETE'; path: string; body?: unknown; note?: string }
export const one = (type: string, id: string) => ({ data: { type, id } });
export const many = (type: string, ids: string[]) => ({ data: ids.map(id => ({ type, id })) });
/** One-line description of a request for dry runs and logs. Attribute values are cut short; `hide` keys (emails,
* passwords) are masked. */
export function describeReq(r: Req, hide: string[] = ['email', 'demoAccountPassword', 'contactEmail', 'contactPhone']): string {
const attrs = (r.body as { data?: { attributes?: Record<string, unknown> } } | undefined)?.data?.attributes;
const show = (k: string, v: unknown) => (hide.includes(k) ? '"***"' : typeof v === 'string' && v.length > 40 ? JSON.stringify(v.slice(0, 37) + '...') : JSON.stringify(v));
const keys = attrs ? Object.entries(attrs).map(([k, v]) => `${k}=${show(k, v)}`) : [];
return `${r.method} ${r.path}${keys.length ? ` {${keys.join(', ')}}` : ''}${r.note ? ` # ${r.note}` : ''}`;
}
/** Logs every planned request; sends them in order unless dry. Returns the responses (empty on dry). */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export async function execute(asc: (m: string, p: string, b?: unknown) => Promise<any>, reqs: Req[], o: { dry: boolean; tag: string }): Promise<unknown[]> {
const out: unknown[] = [];
for (const r of reqs) {
if (o.dry) { log(o.tag, `would ${describeReq(r)}`); continue; }
out.push(await asc(r.method, r.path, r.body));
log(o.tag, `${describeReq(r)}: done`);
}
return out;
}

182
cli/apple/testflight.ts Normal file
View file

@ -0,0 +1,182 @@
// TestFlight through the App Store Connect API.
// storebound apple testflight status groups, testers per group, recent builds + beta states
// storebound apple testflight groups [--dry] create the groups of apple.testflight.groups that are missing
// storebound apple testflight testers [--csv f] [--group a,b] [--remove] [--invite] [--dry] [--yes]
// storebound apple testflight what-to-test --build N [--version x.y.z] [--locale en-US,tr] [--text "..."] [--dry]
// storebound apple testflight info [--dry] Test Information + Beta App Review contact / notes
// storebound apple testflight distribute --build N --group a,b [--version x.y.z] [--internal-only] [--submit-review] [--dry] [--yes]
// Testers come from a CSV in .storebound/ (gitignored; never commit tester emails): email, first_name, last_name,
// groups (";"-separated). Emails are masked in every log line. Adding testers makes Apple email TestFlight invitations
// (once the group has a build), so `testers` asks first; `--remove` takes testers out of the managed groups.
// `distribute --submit-review` sends the build to Beta App Review (external groups) after a confirmation; neither
// testers nor external distribution nor the review submission are MCP tools. Pure planning: cli/lib/testflight.ts.
import { existsSync, readFileSync } from 'node:fs';
import type { Ctx } from '../lib/ctx';
import { confirm, need } from '../lib/ctx';
import { reviewContact } from '../lib/credentials';
import { done, log, warn } from '../lib/log';
import { textTable } from '../lib/table';
import {
type ApiBuild, betaDescriptions, betaReadiness, betaReviewReq, buildsWithVersion, type Group, groupFromApi, inviteReq, maskEmail,
parseTesters, pickBuild, planBetaInfo, planBetaReviewDetail, planDistribute, planGroups, planTesters, planWhatToTest, whatToTestFromListing,
} from '../lib/testflight';
import { type Asc, ascClient, type J } from './asc';
import { execute } from './jsonapi';
const TAG = 'testflight';
const USAGE = 'usage: storebound apple testflight status | groups | testers | what-to-test --build N | info | distribute --build N --group <names>';
async function groups(c: Asc, appId: string): Promise<Group[]> {
return (await c.all(`/v1/apps/${appId}/betaGroups?limit=200`)).map(groupFromApi);
}
async function findBuild(c: Asc, appId: string, number: string, marketing?: string): Promise<ApiBuild & { detail: J }> {
const q = new URLSearchParams({ 'filter[app]': appId, 'filter[version]': number, 'filter[preReleaseVersion.platform]': 'IOS', include: 'preReleaseVersion,buildBetaDetail', limit: '50' });
if (marketing) q.set('filter[preReleaseVersion.version]', marketing);
const resp = await c.asc('GET', `/v1/builds?${q}`);
const b = pickBuild(buildsWithVersion(resp), number, marketing);
const detail = (resp.included ?? []).find((x: J) => x.type === 'buildBetaDetails' && x.id === (b as J).relationships?.buildBetaDetail?.data?.id)?.attributes ?? null;
return { ...b, detail };
}
export async function run(ctx: Ctx): Promise<void> {
const { config, root, resolve } = ctx.loaded;
const a = ctx.args;
const sub = a._[0];
if (!sub) throw new Error(USAGE);
const dry = a.has('dry');
const tf = config.apple?.testflight;
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
const appId = await c.app();
if (sub === 'status') {
const gs = await groups(c, appId);
const rows: (string | number)[][] = [];
for (const g of gs) {
const testers = await c.all(`/v1/betaGroups/${g.id}/betaTesters?limit=200`);
const builds = await c.all(`/v1/betaGroups/${g.id}/builds?limit=200`);
rows.push([g.name, g.internal ? 'internal' : 'external', testers.length, g.internal && g.hasAccessToAllBuilds ? 'all' : builds.length, g.publicLinkEnabled ? 'public link on' : '']);
}
console.log(textTable(['group', 'kind', 'testers', 'builds', ''], rows));
const q = new URLSearchParams({ 'filter[app]': appId, include: 'preReleaseVersion,buildBetaDetail', sort: '-uploadedDate', limit: '8' });
const resp = await c.asc('GET', `/v1/builds?${q}`);
const details = new Map((resp.included ?? []).filter((x: J) => x.type === 'buildBetaDetails').map((x: J) => [x.id, x.attributes] as const));
console.log('\n' + textTable(['version', 'build', 'processing', 'internal', 'external', 'uploaded'], buildsWithVersion(resp).map(b => {
const d = details.get((b as J).relationships?.buildBetaDetail?.data?.id) as J;
return [b.marketing ?? '', b.attributes.version ?? '', b.attributes.processingState ?? '', d?.internalBuildState ?? '', d?.externalBuildState ?? '', (b.attributes.uploadedDate ?? '').slice(0, 10)];
})));
const missing = (tf?.groups ?? []).filter(w => !gs.some(g => g.name === w.name)).map(w => w.name);
if (missing.length) warn(TAG, `configured but not on App Store Connect: ${missing.join(', ')} (storebound apple testflight groups)`);
return;
}
if (sub === 'groups') {
const plan = planGroups(appId, await groups(c, appId), tf?.groups ?? []);
if (!tf?.groups?.length) warn(TAG, 'apple.testflight.groups is empty: nothing to create');
for (const n of plan.existing) log(TAG, `group "${n}": exists`);
await execute(c.asc, plan.create, { dry, tag: TAG });
done(TAG, dry ? `groups checked (dry run): ${plan.create.length} to create` : `groups done (${plan.create.length} created)`);
return;
}
if (sub === 'testers') {
const csvPath = resolve(a.get('csv') ?? tf?.testers ?? '.storebound/testers.csv');
if (!existsSync(csvPath)) throw new Error(`no tester CSV at ${csvPath} (columns: email, first_name, last_name, groups; keep it in .storebound/)`);
const only = a.list('group');
const want = parseTesters(readFileSync(csvPath, 'utf8'), only.length === 1 ? only[0] : undefined);
const gs = await groups(c, appId);
const existing = new Map<string, { id: string; groupIds: string[]; state?: string }>();
const resp = await c.all(`/v1/betaTesters?filter[apps]=${appId}&include=betaGroups&limit=200`);
for (const t of resp) existing.set(String(t.attributes.email ?? '').toLowerCase(), { id: t.id, groupIds: (t.relationships?.betaGroups?.data ?? []).map((g: J) => g.id), state: t.attributes.state });
const plan = planTesters(gs, existing, want, { remove: a.has('remove'), only });
if (plan.unknownGroups.length) throw new Error(`unknown group(s): ${plan.unknownGroups.join(', ')} (storebound apple testflight groups creates the configured ones)`);
const internal = gs.filter(g => g.internal && want.some(t => t.groups.includes(g.name)));
if (internal.length) warn(TAG, `internal groups (${internal.map(g => g.name).join(', ')}) only take App Store Connect users of your team (Users and Access)`);
log(TAG, `${want.length} testers in the CSV: ${plan.summary.join(', ')}`);
const reqs = [...plan.create, ...plan.add, ...plan.remove];
if (!reqs.length && !a.has('invite')) { done(TAG, 'testers up to date'); return; }
if (dry) { await execute(c.asc, reqs, { dry, tag: TAG }); done(TAG, 'testers checked (dry run)'); return; }
if (reqs.length && !(await confirm(ctx, `Apply ${plan.summary.join(', ')}? New testers get a TestFlight invitation email from Apple.`))) return;
await execute(c.asc, reqs, { dry, tag: TAG });
if (a.has('invite')) {
const fresh = new Map((await c.all(`/v1/betaTesters?filter[apps]=${appId}&limit=200`)).map((t: J) => [String(t.attributes.email ?? '').toLowerCase(), t] as const));
const pending = want.map(t => fresh.get(t.email)).filter((t): t is J => !!t && ['NOT_INVITED', 'INVITED'].includes(t.attributes.state));
if (pending.length && await confirm(ctx, `(Re)send the TestFlight invitation email to ${pending.length} tester(s)?`))
await execute(c.asc, pending.map(t => inviteReq(appId, t.id, maskEmail(String(t.attributes.email)))), { dry: false, tag: TAG });
}
done(TAG, 'testers done');
return;
}
if (sub === 'what-to-test') {
const number = need(a.get('build'), '--build N (the exact build number)');
const b = await findBuild(c, appId, number, a.get('version'));
let want: Record<string, string>;
const locales = a.list('locale');
if (a.get('text')) {
const ls = locales.length ? locales : [config.apple?.primaryLocale ?? config.languages.find(l => l.apple)?.apple ?? 'en-US'];
want = Object.fromEntries(ls.map(l => [l, a.get('text')!]));
} else {
const f = resolve(config.apple?.listing ?? 'store/appstore.md');
want = whatToTestFromListing(readFileSync(f, 'utf8'));
if (locales.length) want = Object.fromEntries(Object.entries(want).filter(([l]) => locales.includes(l)));
if (!Object.keys(want).length) throw new Error(`${f}: no "### whatToTest" or "### whatsNew" block (storebound whats-new drafts one), or pass --text`);
}
const existing = (await c.all(`/v1/builds/${b.id}/betaBuildLocalizations?limit=200`)).map((l: J) => ({ id: l.id, locale: l.attributes.locale, whatsNew: l.attributes.whatsNew }));
const reqs = planWhatToTest(b.id, existing, want);
if (!reqs.length) { done(TAG, `build ${number}: What to Test up to date (${Object.keys(want).join(', ')})`); return; }
await execute(c.asc, reqs, { dry, tag: TAG });
done(TAG, dry ? `build ${number}: ${reqs.length} locale(s) to set (dry run)` : `build ${number}: What to Test set for ${reqs.length} locale(s)`);
return;
}
if (sub === 'info') {
const desc = betaDescriptions(tf, config.languages);
if (!Object.keys(desc).length) warn(TAG, 'apple.testflight.description is not set: external testing needs a Beta App Description per locale');
const want = Object.fromEntries(Object.entries(desc).map(([locale, description]) => [locale, { description, feedbackEmail: config.app.contactEmail,
privacyPolicyUrl: config.app.privacyPolicyUrl, marketingUrl: config.app.marketingUrl ?? config.app.website }]));
const locs = (await c.all(`/v1/apps/${appId}/betaAppLocalizations?limit=200`)).map((l: J) => ({ id: l.id, locale: l.attributes.locale, attributes: l.attributes }));
const detail = (await c.maybe(`/v1/apps/${appId}/betaAppReviewDetail`))?.data ?? null;
const contact = reviewContact(root);
if (!contact) warn(TAG, 'no reviewContact in .storebound/credentials.json: Beta App Review contact left as it is');
const reqs = [...planBetaInfo(appId, locs, want), ...planBetaReviewDetail(detail, contact, tf?.reviewNotes ?? config.apple?.info?.reviewNotes)];
await execute(c.asc, reqs, { dry, tag: TAG });
done(TAG, reqs.length ? (dry ? `${reqs.length} change(s) (dry run)` : `test information updated (${reqs.length})`) : 'test information up to date');
return;
}
if (sub === 'distribute') {
const number = need(a.get('build'), '--build N (the exact build number you uploaded)');
const names = a.list('group');
if (!names.length) throw new Error('--group <name>[,<name>]: which beta groups get the build');
const gs = await groups(c, appId);
const target = names.map(n => gs.find(g => g.name === n) ?? (() => { throw new Error(`unknown group "${n}" (${gs.map(g => g.name).join(', ')})`); })());
const external = target.filter(g => !g.internal);
if (a.has('internal-only') && external.length) throw new Error(`external group(s) ${external.map(g => g.name).join(', ')}: distribute to external testers from the terminal (asks first)`);
const b = await findBuild(c, appId, number, a.get('version'));
const problems = betaReadiness(b.attributes, b.detail);
if (problems.length) throw new Error(`build ${number}: ${problems.join('; ')}`);
log(TAG, `build ${number} (${b.marketing ?? '?'}): internal ${b.detail?.internalBuildState ?? '?'}, external ${b.detail?.externalBuildState ?? '?'}`);
const inGroups = (await c.all(`/v1/betaGroups?filter[app]=${appId}&filter[builds]=${b.id}&limit=200`)).map((g: J) => g.id);
const reqs = planDistribute(b.id, target, inGroups);
const review = a.has('submit-review') && external.length ? (await c.maybe(`/v1/builds/${b.id}/betaAppReviewSubmission`))?.data ?? null : null;
const wantsReview = a.has('submit-review') && external.length > 0 && !review && !['BETA_APPROVED', 'IN_BETA_REVIEW', 'WAITING_FOR_BETA_REVIEW', 'IN_BETA_TESTING'].includes(b.detail?.externalBuildState);
if (a.has('submit-review') && review) log(TAG, `beta review: already submitted (${review.attributes?.betaReviewState ?? '?'})`);
if (external.length && !a.has('submit-review') && b.detail?.externalBuildState === 'READY_FOR_BETA_SUBMISSION')
warn(TAG, 'external testers only get the build after Beta App Review: add --submit-review (asks first) or submit it in App Store Connect');
if (dry) {
await execute(c.asc, [...reqs, ...(wantsReview ? [betaReviewReq(b.id)] : [])], { dry, tag: TAG });
done(TAG, 'distribute checked (dry run)');
return;
}
if (external.length && reqs.some(r => external.some(g => r.path.includes(g.id))) && !(await confirm(ctx, `Give build ${number} to external group(s) ${external.map(g => g.name).join(', ')}? Testers are notified once Beta App Review approves it.`))) return;
await execute(c.asc, reqs, { dry, tag: TAG });
if (wantsReview) {
if (await confirm(ctx, `Submit build ${number} to Beta App Review now? Apple reviews it for external testing (Test Information must be complete: storebound apple testflight info).`))
await execute(c.asc, [betaReviewReq(b.id)], { dry: false, tag: TAG });
}
done(TAG, `build ${number}: ${reqs.length ? `added to ${reqs.length} group(s)` : 'already in every group'}`);
return;
}
throw new Error(`unknown testflight command "${sub}"\n${USAGE}`);
}

View file

@ -38,6 +38,7 @@ const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
'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'],
'apple testflight': [() => import('./apple/testflight'), 'TestFlight: status | groups | testers (CSV in .storebound/) | what-to-test --build N | info | distribute --build N --group g [--submit-review]'],
'icons': [() => import('./icons'), 'App Store / Play / web / adaptive / legacy launcher icons from one artwork'],
'shots capture': [() => import('./shots/capture'), 'raw frames: --source web (playwright) | ios-sim (simctl) | android-emu (adb) | folder; --dry'],
'shots fonts': [() => import('./shots/fonts'), 'download font subsets for the copy (CJK / Arabic / Cyrillic ...)'],

View file

@ -15,6 +15,7 @@ const FILES: [string, string][] = [
['declarations.md', 'store/declarations.md'],
['privacy-policy.html', 'store/privacy-policy.html'],
['credentials.example.json', '.storebound/credentials.json'],
['testers.csv', '.storebound/testers.csv'],
];
export async function run(args: Args): Promise<void> {

View file

@ -3,6 +3,7 @@
import { existsSync } from 'node:fs';
import { dirname, isAbsolute, join, resolve } from 'node:path';
import { validateCapture, validateRecord } from '../shots/devices';
import { type TfConfig, validateTestflight } from './testflight';
export type ProductType = 'consumable' | 'non_consumable';
@ -283,6 +284,8 @@ export interface ShipConfig {
screenshotTypes?: string[];
/** The app runs on iPad: renders, checks and uploads 13" iPad screenshots (2064 x 2752) and iPad app previews. */
ipad?: boolean;
/** TestFlight beta groups, the tester CSV (in .storebound/) and Test Information (`storebound apple testflight`). */
testflight?: TfConfig;
};
products?: Product[];
dataSafety?: DataSafety;
@ -331,6 +334,7 @@ export function validateConfig(c: unknown): string[] {
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');
e.push(...validateTestflight(cfg.apple.testflight));
}
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"');

43
cli/lib/csv.ts Normal file
View file

@ -0,0 +1,43 @@
// Small RFC 4180 CSV reader / writer (quotes, doubled quotes, CR LF, a UTF-8 BOM). Pure. Used for tester lists,
// price sheets and the Play statistics exports.
import { csvCell } from './data-safety';
/** Rows of cells. Empty lines are dropped. */
export function parseCsv(text: string, sep = ','): string[][] {
const rows: string[][] = [];
let row: string[] = [];
let cell = '';
let quoted = false;
const s = text.replace(/^/, '');
for (let i = 0; i < s.length; i++) {
const ch = s[i]!;
if (quoted) {
if (ch === '"') { if (s[i + 1] === '"') { cell += '"'; i++; } else quoted = false; }
else cell += ch;
continue;
}
if (ch === '"' && cell === '') { quoted = true; continue; }
if (ch === sep) { row.push(cell); cell = ''; continue; }
if (ch === '\n' || ch === '\r') {
if (ch === '\r' && s[i + 1] === '\n') i++;
row.push(cell); cell = '';
if (row.some(c => c !== '')) rows.push(row);
row = [];
continue;
}
cell += ch;
}
row.push(cell);
if (row.some(c => c !== '')) rows.push(row);
return rows;
}
/** Header row -> objects keyed by the lower-cased, trimmed header (spaces and dashes become "_"). */
export function parseCsvRecords(text: string, sep = ','): Record<string, string>[] {
const [head, ...rest] = parseCsv(text, sep);
if (!head) return [];
const keys = head.map(h => h.trim().toLowerCase().replace(/[\s-]+/g, '_'));
return rest.map(r => Object.fromEntries(keys.map((k, i) => [k, (r[i] ?? '').trim()])));
}
export const toCsv = (rows: (string | number)[][]): string => rows.map(r => r.map(c => csvCell(String(c))).join(',')).join('\n') + '\n';

16
cli/lib/table.ts Normal file
View file

@ -0,0 +1,16 @@
// Aligned text tables for the terminal and Markdown tables for reports. Pure.
export function textTable(head: string[], rows: (string | number)[][]): string {
const all = [head, ...rows.map(r => r.map(String))];
const w = head.map((_, i) => Math.max(...all.map(r => [...(r[i] ?? '')].length)));
const line = (r: string[]) => r.map((c, i) => c + ' '.repeat(w[i]! - [...c].length)).join(' ').trimEnd();
return [line(head), line(w.map(n => '-'.repeat(n))), ...all.slice(1).map(line)].join('\n');
}
const md = (c: string | number) => String(c).replace(/\|/g, '\\|').replace(/\n/g, ' ');
export function mdTable(head: string[], rows: (string | number)[][]): string {
return [`| ${head.map(md).join(' | ')} |`, `|${head.map(() => '---').join('|')}|`, ...rows.map(r => `| ${r.map(md).join(' | ')} |`)].join('\n');
}
/** 0.01234 -> "1.23%" */
export const pct = (x: number | null | undefined, digits = 2): string => (x === null || x === undefined || Number.isNaN(x) ? 'n/a' : `${(x * 100).toFixed(digits)}%`);

297
cli/lib/testflight.ts Normal file
View file

@ -0,0 +1,297 @@
// TestFlight through the App Store Connect API, as pure planners: what exists (read with GETs) + what the config / CSV
// wants -> the requests to send. The command (cli/apple/testflight.ts) reads, plans, prints the plan on --dry and sends.
// API references (checked October 2026):
// beta groups https://developer.apple.com/documentation/appstoreconnectapi/beta-groups
// beta testers https://developer.apple.com/documentation/appstoreconnectapi/beta-testers
// invitations https://developer.apple.com/documentation/appstoreconnectapi/beta-tester-invitations
// What to Test https://developer.apple.com/documentation/appstoreconnectapi/beta-build-localizations
// beta review https://developer.apple.com/documentation/appstoreconnectapi/beta-app-review-submissions
// test information https://developer.apple.com/documentation/appstoreconnectapi/beta-app-localizations
// https://developer.apple.com/documentation/appstoreconnectapi/beta-app-review-details
import { type Req, many, one } from '../apple/jsonapi';
import { parseCsvRecords } from './csv';
import { len } from './copy';
/** "What to Test" per build and locale (betaBuildLocalizations.whatsNew). Apple's API docs state no maximum; 4000 is
* assumed (the App Store "What's New" limit). NOT VERIFIED: keep it well below, testers read it on a phone. */
export const WHAT_TO_TEST_LIMIT = 4000;
/** Beta App Review notes (betaAppReviewDetails.notes): "Review notes have a maximum of 4,000 characters." */
export const BETA_NOTES_LIMIT = 4000;
/** Beta App Description (betaAppLocalizations.description) shown to external testers. */
export const BETA_DESCRIPTION_LIMIT = 4000;
export interface TfGroupSpec {
name: string;
/** Internal group (App Store Connect users of your team; no beta review). Default false = external. */
internal?: boolean;
/** Internal groups only: every new build is available to the group automatically. */
allBuilds?: boolean;
/** External groups only: public TestFlight link (anyone with the link can join, up to publicLinkLimit). */
publicLink?: boolean;
publicLinkLimit?: number;
/** Testers can send feedback (screenshots, comments) from TestFlight. Default true. */
feedback?: boolean;
}
export interface TfConfig {
groups?: TfGroupSpec[];
/** CSV of testers: email, first_name, last_name, groups (";"-separated group names). Must live in .storebound/
* (gitignored): tester emails are personal data and never go into the repo. Default .storebound/testers.csv. */
testers?: string;
/** Beta App Description per language id (or one text for every locale); shown to external testers. */
description?: string | Record<string, string>;
/** Notes for Beta App Review (where to find what, test account hints). The contact comes from
* .storebound/credentials.json reviewContact like for App Review. */
reviewNotes?: string;
}
export interface Group { id: string; name: string; internal: boolean; publicLinkEnabled?: boolean; publicLink?: string | null; hasAccessToAllBuilds?: boolean }
export const groupFromApi = (g: { id: string; attributes: Record<string, unknown> }): Group => ({
id: g.id, name: String(g.attributes.name ?? ''), internal: g.attributes.isInternalGroup === true,
publicLinkEnabled: g.attributes.publicLinkEnabled as boolean | undefined, publicLink: (g.attributes.publicLink as string | null | undefined) ?? null,
hasAccessToAllBuilds: g.attributes.hasAccessToAllBuilds as boolean | undefined,
});
/** Problems with the testflight config. Pure. */
export function validateTestflight(t: TfConfig | undefined): string[] {
if (!t) return [];
const e: string[] = [];
const names = new Set<string>();
for (const [i, g] of (t.groups ?? []).entries()) {
const at = `apple.testflight.groups[${i}]`;
if (!g.name || len(g.name) > 50) e.push(`${at}.name: 1-50 characters`);
if (names.has(g.name)) e.push(`${at}.name: duplicate "${g.name}"`);
names.add(g.name);
if (g.internal && (g.publicLink || g.publicLinkLimit !== undefined)) e.push(`${at}: public links are for external groups only`);
if (!g.internal && g.allBuilds !== undefined) e.push(`${at}.allBuilds: internal groups only (external builds go through beta review one by one)`);
if (g.publicLinkLimit !== undefined && !(Number.isInteger(g.publicLinkLimit) && g.publicLinkLimit >= 1 && g.publicLinkLimit <= 10000)) e.push(`${at}.publicLinkLimit: 1-10000`);
}
if (t.testers !== undefined && !/^\.storebound\//.test(t.testers.replace(/^\.\//, '')))
e.push('apple.testflight.testers: keep the tester CSV in .storebound/ (gitignored); emails never go into the repo');
return e;
}
/** POST /v1/betaGroups for every configured group missing on App Store Connect (matched by name). Existing groups are
* never renamed, changed or deleted. */
export function planGroups(appId: string, existing: Group[], want: TfGroupSpec[]): { create: Req[]; existing: string[] } {
const have = new Set(existing.map(g => g.name));
const create: Req[] = want.filter(g => !have.has(g.name)).map(g => ({
method: 'POST', path: '/v1/betaGroups', note: `${g.internal ? 'internal' : 'external'} group "${g.name}"`,
body: { data: { type: 'betaGroups', attributes: {
name: g.name,
...(g.internal ? { isInternalGroup: true, hasAccessToAllBuilds: g.allBuilds ?? false } : {}),
...(!g.internal && g.publicLink ? { publicLinkEnabled: true, publicLinkLimitEnabled: g.publicLinkLimit !== undefined, ...(g.publicLinkLimit !== undefined ? { publicLinkLimit: g.publicLinkLimit } : {}) } : {}),
feedbackEnabled: g.feedback ?? true,
}, relationships: { app: one('apps', appId) } } },
}));
return { create, existing: want.filter(g => have.has(g.name)).map(g => g.name) };
}
export interface Tester { email: string; firstName?: string; lastName?: string; groups: string[] }
const EMAIL = /^[^@\s,;]+@[^@\s,;]+\.[^@\s,;]+$/;
/** Tester CSV -> testers. Columns (header row, any order): email, first_name (or firstname / first), last_name,
* groups (";"-separated group names; empty = `defaultGroup`). Throws on bad emails or duplicates. */
export function parseTesters(csv: string, defaultGroup?: string): Tester[] {
const out: Tester[] = [];
const seen = new Set<string>();
const errors: string[] = [];
for (const [i, r] of parseCsvRecords(csv).entries()) {
const email = (r.email ?? '').toLowerCase();
if (!EMAIL.test(email)) { errors.push(`row ${i + 2}: "${maskEmail(email)}" is not an email`); continue; }
if (seen.has(email)) { errors.push(`row ${i + 2}: ${maskEmail(email)} listed twice`); continue; }
seen.add(email);
const groups = (r.groups ?? r.group ?? '').split(';').map(s => s.trim()).filter(Boolean);
if (!groups.length && defaultGroup) groups.push(defaultGroup);
out.push({ email, firstName: r.first_name || r.firstname || r.first || undefined, lastName: r.last_name || r.lastname || r.last || undefined, groups });
}
if (errors.length) throw new Error(`testers CSV: ${errors.join('; ')}`);
return out;
}
/** "jane.doe@example.com" -> "j***@example.com": emails in logs and MCP output stay readable but not harvestable. */
export function maskEmail(e: string): string {
const at = e.indexOf('@');
if (at < 1) return '***';
return `${e[0]}***${e.slice(at)}`;
}
export interface TesterPlan {
/** New testers: POST /v1/betaTesters with their groups (Apple emails the invitation once a build is available). */
create: Req[];
/** Existing testers added to more groups: POST /v1/betaGroups/{id}/relationships/betaTesters. */
add: Req[];
/** Testers in a managed group but not in the CSV (only with remove): DELETE .../relationships/betaTesters. */
remove: Req[];
unknownGroups: string[];
summary: string[];
}
/**
* Testers of the managed groups (those named in the CSV or `only`) vs the CSV. `existing` maps a beta tester (by
* lower-case email) to its id and current group ids. Removal only with `remove` (it ends their access to the builds
* of that group; the tester record itself is kept).
*/
export function planTesters(groups: Group[], existing: Map<string, { id: string; groupIds: string[] }>, want: Tester[], o: { remove?: boolean; only?: string[] } = {}): TesterPlan {
const byName = new Map(groups.map(g => [g.name, g] as const));
const plan: TesterPlan = { create: [], add: [], remove: [], unknownGroups: [], summary: [] };
const managed = new Set(o.only?.length ? o.only : want.flatMap(t => t.groups));
for (const n of managed) if (!byName.has(n)) plan.unknownGroups.push(n);
const addTo = new Map<string, string[]>();
for (const t of want) {
const target = t.groups.filter(n => managed.has(n) && byName.has(n)).map(n => byName.get(n)!);
if (!target.length) continue;
const cur = existing.get(t.email);
if (!cur) {
plan.create.push({ method: 'POST', path: '/v1/betaTesters', note: `${maskEmail(t.email)} -> ${target.map(g => g.name).join(', ')}`,
body: { data: { type: 'betaTesters', attributes: { email: t.email, ...(t.firstName ? { firstName: t.firstName } : {}), ...(t.lastName ? { lastName: t.lastName } : {}) },
relationships: { betaGroups: many('betaGroups', target.map(g => g.id)) } } } });
continue;
}
for (const g of target) if (!cur.groupIds.includes(g.id)) addTo.set(g.id, [...(addTo.get(g.id) ?? []), cur.id]);
}
for (const [gid, ids] of addTo) {
const g = groups.find(x => x.id === gid)!;
plan.add.push({ method: 'POST', path: `/v1/betaGroups/${gid}/relationships/betaTesters`, body: many('betaTesters', ids), note: `${ids.length} existing tester(s) -> "${g.name}"` });
}
if (o.remove) {
const wanted = new Map<string, Set<string>>();
for (const t of want) for (const n of t.groups) if (byName.has(n)) wanted.set(byName.get(n)!.id, (wanted.get(byName.get(n)!.id) ?? new Set()).add(t.email));
const drop = new Map<string, string[]>();
for (const [email, cur] of existing) for (const gid of cur.groupIds) {
const g = groups.find(x => x.id === gid);
if (!g || !managed.has(g.name)) continue;
if (!wanted.get(gid)?.has(email)) drop.set(gid, [...(drop.get(gid) ?? []), cur.id]);
}
for (const [gid, ids] of drop) {
const g = groups.find(x => x.id === gid)!;
plan.remove.push({ method: 'DELETE', path: `/v1/betaGroups/${gid}/relationships/betaTesters`, body: many('betaTesters', ids), note: `${ids.length} tester(s) leave "${g.name}"` });
}
}
plan.summary.push(`${plan.create.length} new tester(s)`, `${plan.add.reduce((n, r) => n + (r.body as { data: unknown[] }).data.length, 0)} added to groups`,
`${plan.remove.reduce((n, r) => n + (r.body as { data: unknown[] }).data.length, 0)} removed from groups`);
return plan;
}
/** POST /v1/betaTesterInvitations: (re)send the TestFlight invitation email of one tester for this app. */
export const inviteReq = (appId: string, testerId: string, label: string): Req => ({ method: 'POST', path: '/v1/betaTesterInvitations', note: `invite ${label}`,
body: { data: { type: 'betaTesterInvitations', relationships: { app: one('apps', appId), betaTester: one('betaTesters', testerId) } } } });
/** POST /v1/betaGroups/{id}/relationships/builds for every group that does not have the build yet. */
export function planDistribute(buildId: string, groups: Group[], buildGroupIds: string[]): Req[] {
return groups.filter(g => !buildGroupIds.includes(g.id) && !(g.internal && g.hasAccessToAllBuilds)).map(g => ({ method: 'POST', path: `/v1/betaGroups/${g.id}/relationships/builds`,
body: many('builds', [buildId]), note: `build -> ${g.internal ? 'internal' : 'external'} group "${g.name}"` }));
}
/**
* "What to Test" texts for TestFlight per App Store locale from the App Store listing file: a `### whatToTest` block
* when a locale section has one, else its `### whatsNew` block (what `storebound whats-new` drafts). Pure.
*/
export function whatToTestFromListing(md: string): Record<string, string> {
const out: Record<string, string> = {};
for (const sec of md.split(/^## /m).slice(1)) {
const locale = sec.split(/[\s·]/)[0]!.trim();
if (!/^[a-z]{2,3}(-[A-Za-z]{2,4})?$/.test(locale)) continue;
const block = (name: string) => new RegExp(`^### ${name}[^\\n]*\\n\`\`\`[^\\n]*\\n([\\s\\S]*?)\\n\`\`\``, 'm').exec(sec)?.[1]?.trim();
const text = block('whatToTest') ?? block('whatsNew');
if (text) out[locale] = text;
}
return out;
}
/** betaBuildLocalizations to create (POST) or update (PATCH) so the build has exactly these texts. Locales on the
* build that are not in `want` are left alone. Throws when a text is over the limit. */
export function planWhatToTest(buildId: string, existing: { id: string; locale: string; whatsNew?: string | null }[], want: Record<string, string>): Req[] {
const tooLong = Object.entries(want).filter(([, t]) => len(t) > WHAT_TO_TEST_LIMIT).map(([l, t]) => `${l} ${len(t)}`);
if (tooLong.length) throw new Error(`What to Test over ${WHAT_TO_TEST_LIMIT} characters: ${tooLong.join(', ')}`);
const have = new Map(existing.map(l => [l.locale, l] as const));
const out: Req[] = [];
for (const [locale, whatsNew] of Object.entries(want)) {
const cur = have.get(locale);
if (!cur) out.push({ method: 'POST', path: '/v1/betaBuildLocalizations', note: locale,
body: { data: { type: 'betaBuildLocalizations', attributes: { locale, whatsNew }, relationships: { build: one('builds', buildId) } } } });
else if ((cur.whatsNew ?? '') !== whatsNew) out.push({ method: 'PATCH', path: `/v1/betaBuildLocalizations/${cur.id}`, note: locale,
body: { data: { type: 'betaBuildLocalizations', id: cur.id, attributes: { whatsNew } } } });
}
return out;
}
/** POST /v1/betaAppReviewSubmissions: send one build to Beta App Review (needed once per version for external
* testing; later builds of the same version are often approved automatically). */
export const betaReviewReq = (buildId: string): Req => ({ method: 'POST', path: '/v1/betaAppReviewSubmissions', note: 'submit for Beta App Review',
body: { data: { type: 'betaAppReviewSubmissions', relationships: { build: one('builds', buildId) } } } });
/** Build states in which a build can be tested / sent to beta review. */
export function betaReadiness(b: { processingState?: string; expired?: boolean; usesNonExemptEncryption?: boolean | null }, detail: { externalBuildState?: string; internalBuildState?: string } | null): string[] {
const p: string[] = [];
if (b.processingState !== 'VALID') p.push(`processing state ${b.processingState ?? 'unknown'} (wait for VALID)`);
if (b.expired) p.push('expired (TestFlight builds expire after 90 days)');
if (b.usesNonExemptEncryption === null || b.usesNonExemptEncryption === undefined) {
if (detail?.internalBuildState === 'MISSING_EXPORT_COMPLIANCE' || detail?.externalBuildState === 'MISSING_EXPORT_COMPLIANCE')
p.push('export compliance missing (storebound apple encryption --build N)');
}
return p;
}
export interface BetaInfo { description?: string; feedbackEmail?: string; privacyPolicyUrl?: string; marketingUrl?: string }
/** Test Information per locale (betaAppLocalizations): POST missing locales, PATCH changed fields. Apple requires a
* description on every beta app localization before a build can go to Beta App Review; fields cannot be cleared. */
export function planBetaInfo(appId: string, existing: { id: string; locale: string; attributes: BetaInfo }[], want: Record<string, BetaInfo>): Req[] {
const have = new Map(existing.map(l => [l.locale, l] as const));
const out: Req[] = [];
for (const [locale, w] of Object.entries(want)) {
const attrs = Object.fromEntries(Object.entries(w).filter(([, v]) => v !== undefined && v !== '')) as BetaInfo;
if (attrs.description && len(attrs.description) > BETA_DESCRIPTION_LIMIT) throw new Error(`beta description ${locale}: over ${BETA_DESCRIPTION_LIMIT} characters`);
const cur = have.get(locale);
if (!cur) { out.push({ method: 'POST', path: '/v1/betaAppLocalizations', note: locale, body: { data: { type: 'betaAppLocalizations', attributes: { locale, ...attrs }, relationships: { app: one('apps', appId) } } } }); continue; }
const changed = Object.fromEntries(Object.entries(attrs).filter(([k, v]) => (cur.attributes as Record<string, unknown>)[k] !== v));
if (Object.keys(changed).length) out.push({ method: 'PATCH', path: `/v1/betaAppLocalizations/${cur.id}`, note: locale, body: { data: { type: 'betaAppLocalizations', id: cur.id, attributes: changed } } });
}
return out;
}
export interface ReviewContactLike { firstName: string; lastName: string; phone: string; email: string }
/** Beta App Review contact + notes (PATCH /v1/betaAppReviewDetails/{id}; the record exists for every app). */
export function planBetaReviewDetail(detail: { id: string; attributes: Record<string, unknown> } | null, contact: ReviewContactLike | null, notes?: string): Req[] {
if (!detail) return [];
if (notes && len(notes) > BETA_NOTES_LIMIT) throw new Error(`beta review notes: over ${BETA_NOTES_LIMIT} characters`);
const want: Record<string, unknown> = {
...(contact ? { contactFirstName: contact.firstName, contactLastName: contact.lastName, contactPhone: contact.phone, contactEmail: contact.email } : {}),
...(notes ? { notes } : {}),
};
const changed = Object.fromEntries(Object.entries(want).filter(([k, v]) => v && detail.attributes[k] !== v));
return Object.keys(changed).length ? [{ method: 'PATCH', path: `/v1/betaAppReviewDetails/${detail.id}`, note: 'Beta App Review contact / notes',
body: { data: { type: 'betaAppReviewDetails', id: detail.id, attributes: changed } } }] : [];
}
export interface ApiBuild { id: string; attributes: { version?: string; processingState?: string; expired?: boolean; usesNonExemptEncryption?: boolean | null; uploadedDate?: string }; marketing?: string }
/** The one build with this number (CFBundleVersion), optionally of one marketing version. Never "the latest". */
export function pickBuild(builds: ApiBuild[], number: string, marketing?: string): ApiBuild {
const hits = builds.filter(b => b.attributes.version === number && (!marketing || b.marketing === marketing));
if (!hits.length) throw new Error(`no build ${number}${marketing ? ` of version ${marketing}` : ''} on App Store Connect (still processing? storebound apple status)`);
if (hits.length > 1) throw new Error(`build number ${number} exists for several versions (${hits.map(b => b.marketing ?? '?').join(', ')}): add --version x.y.z`);
return hits[0]!;
}
/** Builds response with include=preReleaseVersion -> builds tagged with their marketing version. */
export function buildsWithVersion(resp: { data?: ApiBuild[]; included?: { type: string; id: string; attributes?: { version?: string } }[] }): ApiBuild[] {
const pre = new Map((resp.included ?? []).filter(x => x.type === 'preReleaseVersions').map(x => [x.id, x.attributes?.version] as const));
return (resp.data ?? []).map(b => ({ ...b, marketing: pre.get((b as unknown as { relationships?: { preReleaseVersion?: { data?: { id: string } } } }).relationships?.preReleaseVersion?.data?.id ?? '') }));
}
/** Beta App Description per App Store locale from the config (a string = every locale). */
export function betaDescriptions(t: TfConfig | undefined, langs: { id: string; apple?: string }[]): Record<string, string> {
if (!t?.description) return {};
const out: Record<string, string> = {};
for (const l of langs) {
if (!l.apple) continue;
const d = typeof t.description === 'string' ? t.description : t.description[l.id];
if (d) out[l.apple] = d;
}
return out;
}

View file

@ -129,12 +129,29 @@ export const TOOLS: ToolDef[] = [
description: 'Sync app preview videos per locale to the editable App Store version (checked locally first; MD5-idempotent, changed sets are replaced; poster frame time code). Not public until the version is submitted and released. Slow: prefer the terminal with a log.',
props: { only, poster: { type: 'integer', minimum: 0, maximum: 29, description: 'Poster frame second (default shots.video.poster or 5)' } },
args: i => [...opt('only', i.only), ...opt('poster', i.poster)] },
{ name: 'apple_testflight_status', title: 'TestFlight status', command: ['apple', 'testflight', 'status'], write: false, network: true,
description: 'Read-only TestFlight overview: beta groups (internal / external, tester and build counts, public link), recent builds with processing, internal and external beta states.' },
{ name: 'apple_testflight_groups', title: 'Create TestFlight groups', command: ['apple', 'testflight', 'groups'], write: true, network: true, idempotent: true,
description: 'Create the beta groups of apple.testflight.groups that are missing on App Store Connect (matched by name; existing groups are never changed or deleted). Sends nothing to testers.' },
{ name: 'apple_testflight_what_to_test', title: 'TestFlight What to Test', command: ['apple', 'testflight', 'what-to-test'], write: true, network: true, idempotent: true,
description: 'Set "What to Test" (betaBuildLocalizations) of one build, by its exact number, per locale from the App Store listing file (### whatToTest, else ### whatsNew) or from text.',
props: { build: { type: 'string', pattern: '^[0-9][0-9.]*$', description: 'Exact build number (CFBundleVersion) you uploaded' }, version: { type: 'string', pattern: '^\\d+(\\.\\d+){0,2}$', description: 'Marketing version when the build number repeats' },
locale: { type: 'string', description: 'Comma-separated App Store locales (default: every locale with text)' }, text: { type: 'string', description: 'Same text for the given locales instead of the listing file' } },
required: ['build'], args: i => [...opt('build', i.build), ...opt('version', i.version), ...opt('locale', i.locale), ...opt('text', i.text)] },
{ name: 'apple_testflight_info', title: 'TestFlight test information', command: ['apple', 'testflight', 'info'], write: true, network: true, idempotent: true,
description: 'Beta App Description per locale (apple.testflight.description), feedback email, privacy and marketing URLs, and the Beta App Review contact (.storebound/credentials.json) and notes. Needed before external testing.' },
{ name: 'apple_testflight_distribute', title: 'Build to internal TestFlight groups', command: ['apple', 'testflight', 'distribute'], write: true, network: true, idempotent: true,
description: 'Add one build (exact number) to INTERNAL beta groups (your App Store Connect team; they get the TestFlight notification). External groups and Beta App Review submissions are owner-only terminal commands.',
props: { build: { type: 'string', pattern: '^[0-9][0-9.]*$', description: 'Exact build number you uploaded' }, groups: { type: 'string', description: 'Comma-separated internal group names' },
version: { type: 'string', pattern: '^\\d+(\\.\\d+){0,2}$' } },
required: ['build', 'groups'], args: i => [...opt('build', i.build), ...opt('group', i.groups), ...opt('version', i.version), '--internal-only'] },
{ name: 'icons', title: 'Generate icons', command: ['icons'], write: true, network: false, idempotent: true,
description: 'Write every store / launcher / web icon from the artwork in the config (local files, needs ffmpeg).' },
];
/** CLI flags / commands that must never be reachable through MCP. Tests assert none of the tools can produce them. */
export const FORBIDDEN_ARGS = ['--yes', '--manual-release', '--cancel-submission', '--production', 'rollout', 'resume', 'complete'];
export const FORBIDDEN_ARGS = ['--yes', '--manual-release', '--cancel-submission', '--production', 'rollout', 'resume', 'complete',
'--submit-review', '--remove', '--invite', 'testers'];
export function inputSchema(t: ToolDef): Record<string, unknown> {
const props: Record<string, JsonSchema> = { ...(t.props ?? {}) };