Merge desktop-d3: studios and accounts, store import, pairing, ignore list, settings, confirm-gated writes

This commit is contained in:
CRTkafa 2026-10-10 20:33:03 +00:00
commit fa6215ebbe
66 changed files with 5103 additions and 424 deletions

171
tests/desktop-d3.test.ts Normal file
View file

@ -0,0 +1,171 @@
// Desktop D3 write actions: every write the window offers is a dry run unless the host's confirm token for exactly
// that method, project and arguments comes with it (single use, short-lived); owner actions (rollout share, phased
// release, sending one approved reply) additionally answer the command's own confirmation, and only with such a token.
import { afterEach, describe, expect, test } from 'bun:test';
import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { mint } from '../cli/lib/confirm-token';
import { confirm } from '../cli/lib/ctx';
import { ERR } from '../cli/lib/desktop-protocol';
import { parseDraft } from '../cli/lib/reviews';
import { setReplyText } from '../cli/lib/project-files';
import { childEnv, type RunOptions, type Running } from '../cli/lib/runner';
import { TOOLS } from '../cli/mcp-tools';
import { describeMethods, methodName, OWNER_FORBIDDEN_ARGS, OWNER_TOOLS, Session } from '../cli/serve';
import { toArgv } from '../cli/mcp-tools';
type J = Record<string, unknown>;
const DEMO = join(import.meta.dir, '..', 'examples', 'demo-game');
const SECRET_HEX = Array.from({ length: 32 }, (_, i) => (i + 7).toString(16).padStart(2, '0')).join('');
const SECRET = Buffer.from(SECRET_HEX, 'hex');
async function session(now = () => Date.now()) {
const calls: { argv: string[]; o: RunOptions }[] = [];
const run = (argv: string[], o: RunOptions): Running => { calls.push({ argv, o }); return { result: Promise.resolve({ code: 0, out: 'done', cancelled: false }), cancel: () => {} }; };
const s = new Session(() => {}, run, now);
let id = 0;
const call = async (method: string, params: unknown = {}) => (await s.handle({ jsonrpc: '2.0', id: ++id, method, params }))! as J;
await call('session.hello', { secret: SECRET_HEX });
return { calls, call };
}
const err = (r: J) => r.error as { code: number; data?: J };
/** The writes the D3 screens offer, with arguments as the window sends them. */
const D3_WRITES: [string, J][] = [
['play.listing', {}], ['apple.listing', { version: '2.4.0' }], ['play.images', { only: 'en-US' }], ['apple.screenshots', {}], ['apple.previews', {}],
['play.products', {}], ['apple.iap', {}], ['play.subscriptions', {}], ['apple.subscriptions', {}],
['apple.testflight_distribute', { build: '52', groups: 'Studio team' }], ['apple.testflight_what_to_test', { build: '52', text: 'New combo meter' }],
['reviews.reply', { file: 'play-r-p1.md', text: 'Thanks! The fix is in 2.4.0.' }], ['reviews.approve', { file: 'play-r-p1.md' }],
['shots.render', {}], ['shots.video', {}], ['shots.gallery', {}], ['icons', {}],
['owner.play_rollout', { action: 'percent', percent: 50 }], ['owner.play_rollout', { action: 'halt' }], ['owner.ios_phased', { action: 'pause', version: '2.3.0' }],
['owner.ios_phased', { action: 'resume' }], ['owner.reply_send', { file: 'play-r-p1.md' }], ['owner.testflight_testers', { groups: 'Friends and family' }],
];
describe('D3 writes: token binding for every method the window offers', () => {
for (const [method, args] of D3_WRITES) {
test(`${method} ${JSON.stringify(args)}`, async () => {
let now = 1_000_000;
const s = await session(() => now);
const p = { project: DEMO, args };
// dry run by default, and without a token
const dry = await s.call(method, p);
expect(err(dry)).toBeUndefined();
expect(s.calls.at(-1)!.argv).toContain('--dry');
expect(s.calls.at(-1)!.o.env?.STOREBOUND_OWNER_CONFIRMED).toBeUndefined();
expect(err(await s.call(method, { ...p, dryRun: false })).code).toBe(ERR.confirmRequired);
// a token for other arguments, another method or another project is refused
const other = method === 'play.listing' ? 'play.images' : 'play.listing';
expect(err(await s.call(method, { ...p, dryRun: false, confirmToken: mint(SECRET, other, p, { now }) })).code).toBe(ERR.confirmInvalid);
expect(err(await s.call(method, { ...p, dryRun: false, confirmToken: mint(SECRET, method, { project: '/elsewhere', args }, { now }) })).code).toBe(ERR.confirmInvalid);
expect(err(await s.call(method, { ...p, dryRun: false, confirmToken: mint(SECRET, method, { project: DEMO, args: { ...args, x: 1 } }, { now }) })).code).toBe(ERR.confirmInvalid);
expect(err(await s.call(method, { ...p, dryRun: false, confirmToken: mint(Buffer.alloc(32, 1), method, p, { now }) })).code).toBe(ERR.confirmInvalid);
// the right token runs it for real, once
const n = s.calls.length;
const token = mint(SECRET, method, p, { now });
const real = await s.call(method, { ...p, dryRun: false, confirmToken: token, credentials: { PLAY_SERVICE_ACCOUNT: '{}' } });
expect(err(real)).toBeUndefined();
expect((real.result as J).dryRun).toBe(false);
const c = s.calls.at(-1)!;
expect(s.calls.length).toBe(n + 1);
expect(c.argv).not.toContain('--dry');
expect(c.o.env?.PLAY_SERVICE_ACCOUNT).toBe('{}');
expect(c.o.env?.STOREBOUND_OWNER_CONFIRMED).toBe(method.startsWith('owner.') ? '1' : undefined);
expect(err(await s.call(method, { ...p, dryRun: false, confirmToken: token })).data).toEqual({ reason: 'replayed' });
// and expires
const late = mint(SECRET, method, p, { now, ttlMs: 1000 });
now += 1000;
expect(err(await s.call(method, { ...p, dryRun: false, confirmToken: late })).data).toEqual({ reason: 'expired' });
});
}
});
describe('owner actions', () => {
test('exactly these, desktop only, kind owner, never a submit / release request / cancel / external TestFlight flag', () => {
expect(OWNER_TOOLS.map(t => methodName(t.name)).sort()).toEqual(['owner.ios_phased', 'owner.play_rollout', 'owner.reply_send', 'owner.testflight_testers']);
for (const t of OWNER_TOOLS) expect(TOOLS.some(x => x.name === t.name)).toBe(false);
const ds = describeMethods().filter(m => m.method.startsWith('owner.'));
for (const d of ds) expect(d.kind).toBe('owner');
const samples: J[] = [
{ action: 'percent', percent: 5 }, { action: 'halt' }, { action: 'resume', percent: 10 }, { action: 'complete', track: 'beta' },
{ action: 'on' }, { action: 'pause', version: '1.2.3' }, { action: 'resume' }, { action: 'complete' }, { file: 'apple-123.md' }, {}, { groups: 'Studio team,Friends' },
];
for (const t of OWNER_TOOLS) for (const s of samples) {
let argv: string[];
try { argv = toArgv(t, s).argv; } catch { continue; }
for (const a of argv) expect(OWNER_FORBIDDEN_ARGS).not.toContain(a);
}
});
test('argv: rollout share in percent -> fraction, halt / resume / complete, track; phased actions; one reply', () => {
const t = (name: string) => OWNER_TOOLS.find(x => x.name === name)!;
expect(toArgv(t('owner_play_rollout'), { action: 'percent', percent: 20, dry_run: false }).argv).toEqual(['play', 'rollout', '--fraction', '0.2', '--track', 'production']);
expect(toArgv(t('owner_play_rollout'), { action: 'halt' }).argv).toEqual(['play', 'rollout', '--halt', '--track', 'production', '--dry']);
expect(toArgv(t('owner_play_rollout'), { action: 'resume', percent: 50, dry_run: false }).argv).toEqual(['play', 'rollout', '--resume', '--fraction', '0.5', '--track', 'production']);
expect(toArgv(t('owner_play_rollout'), { action: 'complete', percent: 50, track: 'beta', dry_run: false }).argv).toEqual(['play', 'rollout', '--complete', '--track', 'beta']);
expect(toArgv(t('owner_ios_phased'), { action: 'resume', version: '2.3.0', dry_run: false }).argv).toEqual(['apple', 'release', '--phased', 'resume', '--version', '2.3.0']);
expect(toArgv(t('owner_reply_send'), { file: 'play-r1.md', dry_run: false }).argv).toEqual(['reviews', 'send', '--file', 'play-r1.md']);
expect(toArgv(t('owner_testflight_testers'), { groups: 'Studio team', dry_run: false }).argv).toEqual(['apple', 'testflight', 'testers', '--group', 'Studio team']);
expect(toArgv(t('owner_testflight_testers'), {}).argv).toEqual(['apple', 'testflight', 'testers', '--dry']);
});
test('bad arguments never reach a command', async () => {
const s = await session();
for (const [m, args] of [['owner.play_rollout', { action: 'manual' }], ['owner.play_rollout', { action: 'percent', percent: 100 }], ['owner.play_rollout', { action: 'percent', percent: 0.5 }],
['owner.ios_phased', { action: 'release' }], ['owner.ios_phased', { action: 'on', version: '--manual-release' }], ['owner.reply_send', { file: '../../etc/passwd' }],
['owner.reply_send', {}], ['reviews.reply', { file: 'play-1.md', text: '--yes' }], ['reviews.reply', { file: 'play-1.md', text: 'x'.repeat(6001) }]] as [string, J][])
expect(err(await s.call(m, { project: DEMO, args })).code).toBe(ERR.invalidParams);
expect(s.calls.length).toBe(0);
});
});
describe('the owner flag', () => {
const saved = { ...process.env };
afterEach(() => { for (const k of ['STOREBOUND_SERVE', 'STOREBOUND_OWNER_CONFIRMED']) { if (saved[k] === undefined) delete process.env[k]; else process.env[k] = saved[k]; } });
const ctx = { loaded: {} as never, args: { has: (n: string) => n === 'yes', get: () => undefined, str: (_: string, d: string) => d, num: (_: string, d: number) => d, list: () => [], _: [] } };
test('under serve: no by default, even with --yes; yes only with the owner flag', async () => {
process.env.STOREBOUND_SERVE = '1';
delete process.env.STOREBOUND_OWNER_CONFIRMED;
expect(await confirm(ctx, 'Resume?')).toBe(false);
process.env.STOREBOUND_OWNER_CONFIRMED = '1';
expect(await confirm(ctx, 'Resume?')).toBe(true);
});
test('a child never inherits it; it comes only per call', () => {
process.env.STOREBOUND_OWNER_CONFIRMED = '1';
expect(childEnv({}, true).STOREBOUND_OWNER_CONFIRMED).toBeUndefined();
expect(childEnv({ STOREBOUND_OWNER_CONFIRMED: '1' }, true).STOREBOUND_OWNER_CONFIRMED).toBe('1');
});
});
describe('reply drafts: write the reply', () => {
const draft = ['---', 'store: play', 'review_id: r-p1', 'rating: 2', 'approved: true', 'sent: null', '---', '# ★★☆☆☆ Crashes', '', '> Game closes at a 20x combo.', '', '## Reply', '',
'<!-- Write the reply below. -->', '', 'Old text', ''].join('\n');
test('replaces the reply, keeps the review, resets the approval', () => {
const next = setReplyText(draft, ' Sorry! Fixed in 2.4.0.\r\nThanks for the level number. ');
const d = parseDraft('/x/play-r-p1.md', next);
expect(d.reply).toBe('Sorry! Fixed in 2.4.0.\nThanks for the level number.');
expect(d.approved).toBe(false);
expect(next).toContain('> Game closes at a 20x combo.');
expect(next).not.toContain('Old text');
expect(parseDraft('/x', setReplyText(next, 'Again <!-- hidden -->')).reply).toBe('Again');
});
test('sent drafts and other files are not edited', () => {
expect(() => setReplyText(draft.replace('sent: null', 'sent: 2026-10-01T00:00:00Z'), 'x')).toThrow();
expect(() => setReplyText('# not a draft', 'x')).toThrow();
});
test('CLI: reviews reply writes one draft, dry run first', async () => {
const dir = mkdtempSync(join(tmpdir(), 'sb-reply-'));
const cfg = readFileSync(join(DEMO, 'storebound.config.ts'), 'utf8');
writeFileSync(join(dir, 'storebound.config.ts'), cfg);
const replies = join(dir, '.storebound', 'replies');
await Bun.$`mkdir -p ${replies}`.quiet();
writeFileSync(join(replies, 'play-r-p1.md'), draft);
const cli = join(import.meta.dir, '..', 'cli', 'index.ts');
const dry = await Bun.$`bun ${cli} reviews reply play-r-p1.md --text ${'New reply'} --dry`.cwd(dir).quiet().nothrow();
expect(dry.exitCode).toBe(0);
expect(readFileSync(join(replies, 'play-r-p1.md'), 'utf8')).toBe(draft);
const real = await Bun.$`bun ${cli} reviews reply play-r-p1.md --text ${'New reply'}`.cwd(dir).quiet().nothrow();
expect(real.exitCode).toBe(0);
expect(parseDraft('x', readFileSync(join(replies, 'play-r-p1.md'), 'utf8'))).toMatchObject({ reply: 'New reply', approved: false });
const outside = await Bun.$`bun ${cli} reviews reply ../../x.md --text y`.cwd(dir).quiet().nothrow();
expect(outside.exitCode).not.toBe(0);
});
});

View file

@ -6,7 +6,7 @@ import { canonical, mac, MAX_TTL_MS, mint, parseSecret, TokenGuard } from '../cl
import { ERR } from '../cli/lib/desktop-protocol';
import { childEnv, pickCallEnv, type RunOptions, type Running } from '../cli/lib/runner';
import { FORBIDDEN_ARGS, TOOLS } from '../cli/mcp-tools';
import { describeMethods, DESKTOP_ONLY, DESKTOP_TOOLS, FORBIDDEN_METHOD_WORDS, JSON_TOOLS, methodName, Session } from '../cli/serve';
import { describeMethods, DESKTOP_ONLY, DESKTOP_TOOLS, FORBIDDEN_METHOD_WORDS, JSON_TOOLS, methodName, OWNER_TOOLS, Session } from '../cli/serve';
import { buildOne, hostTarget, leaks } from '../tools/build-sidecars';
type J = Record<string, unknown>;
@ -86,7 +86,13 @@ describe('confirm tokens', () => {
describe('serve --stdio: methods', () => {
test('nothing submits, releases or publishes', () => {
const names = describeMethods().map(m => m.method);
for (const n of names) expect(n).not.toMatch(FORBIDDEN_METHOD_WORDS);
// the owner actions (rollout share, phased release, sending one approved reply: tests/desktop-d3.test.ts) are the
// only methods with those words, all under "owner.", and none submits, publishes, cancels, deletes or invites
const owner = describeMethods().filter(m => m.kind === 'owner').map(m => m.method);
expect(owner.sort()).toEqual(OWNER_TOOLS.map(t => methodName(t.name)).sort());
for (const n of owner) expect(n.startsWith('owner.')).toBe(true);
for (const n of names.filter(x => !owner.includes(x))) expect(n).not.toMatch(FORBIDDEN_METHOD_WORDS);
for (const n of names) expect(n).not.toMatch(/submit|publish|cancel|delete|remove|invite|manual/i);
for (const n of ['apple.submit', 'apple.release', 'play.release', 'play.release_testing', 'apple.phased_release', 'play.rollout', 'reviews.send', 'apple.ppo_start', 'prices.import'])
expect(names).not.toContain(n);
// every desktop tool still goes through the MCP rules: no forbidden flag can come out of any of them

256
tests/store-apps.test.ts Normal file
View file

@ -0,0 +1,256 @@
// storebound apps list / check (D3: many studios, many store accounts): parsing of recorded App Store Connect and
// Play Reporting API responses, account health classification, the CLI over a mocked fetch, and the serve methods
// (apps.list, account.check, store-only apps through a generated config).
import { afterEach, describe, expect, test } from 'bun:test';
import { generateKeyPairSync } from 'node:crypto';
import { existsSync, mkdtempSync, readFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { checkAccount, listApps } from '../cli/apps';
import { ERR } from '../cli/lib/desktop-protocol';
import type { RunOptions, Running } from '../cli/lib/runner';
import { appleCheck, iconUrl, listAppleApps, listPlayApps, playCheck } from '../cli/lib/store-apps';
import { checkVirtual, describeMethods, Session, STORE_KEY_RE, VIRTUAL_READS, virtualConfig, virtualDir } from '../cli/serve';
import { validateConfig } from '../cli/lib/config';
type J = Record<string, unknown>;
// ---- recorded responses (shapes as the APIs return them; ids and names are placeholders) ----
const ASC_APPS_1 = {
data: [
{ type: 'apps', id: '6400000101', attributes: { name: 'Example Puzzle', bundleId: 'com.example.puzzle', sku: 'PUZZLE1', primaryLocale: 'en-US' } },
{ type: 'apps', id: '6400000102', attributes: { name: 'Example Notes', bundleId: 'com.example.notes', sku: 'NOTES1', primaryLocale: 'en-GB' } },
],
links: { self: 'https://api.appstoreconnect.apple.com/v1/apps?limit=200', next: 'https://api.appstoreconnect.apple.com/v1/apps?cursor=Mg&limit=200' },
meta: { paging: { total: 3, limit: 200 } },
};
const ASC_APPS_2 = { data: [{ type: 'apps', id: '6400000103', attributes: { name: 'A Mac Tool', bundleId: 'com.example.mactool', sku: 'MAC1', primaryLocale: 'en-US' } }], links: { self: '' } };
const ASC_VERSIONS: Record<string, J> = {
'6400000101': { data: [
{ type: 'appStoreVersions', id: 'v1', attributes: { platform: 'IOS', versionString: '2.4.0', appStoreState: 'WAITING_FOR_REVIEW', appVersionState: 'WAITING_FOR_REVIEW' } },
{ type: 'appStoreVersions', id: 'v0', attributes: { platform: 'IOS', versionString: '2.3.0', appStoreState: 'READY_FOR_SALE', appVersionState: 'READY_FOR_DISTRIBUTION' } },
] },
'6400000102': { data: [] },
'6400000103': { data: [{ type: 'appStoreVersions', id: 'v9', attributes: { platform: 'MAC_OS', versionString: '1.0', appStoreState: 'PREPARE_FOR_SUBMISSION' } }] },
};
const ASC_BUILD = { data: [{ type: 'builds', id: 'b1', attributes: { version: '52', iconAssetToken: { templateUrl: 'https://is1-ssl.mzstatic.com/image/thumb/Purple/v4/ab/cd/AppIcon.png/{w}x{h}bb.{f}', width: 1024, height: 1024 } } }] };
const PLAY_SEARCH_1 = { apps: [{ name: 'apps/com.example.puzzle', packageName: 'com.example.puzzle', displayName: 'Example Puzzle' }, { name: 'apps/com.example.runner', packageName: 'com.example.runner', displayName: 'Runner' }], nextPageToken: 'tok2' };
const PLAY_SEARCH_2 = { apps: [{ name: 'apps/com.example.ledger', packageName: 'com.example.ledger', displayName: '' }] };
function ascGet(calls: string[]) {
return async (path: string): Promise<J> => {
calls.push(path);
if (path.startsWith('/v1/apps?fields')) return ASC_APPS_1;
if (path.includes('cursor=Mg')) return ASC_APPS_2;
const v = /^\/v1\/apps\/(\d+)\/appStoreVersions/.exec(path);
if (v) return ASC_VERSIONS[v[1]!]!;
if (path.startsWith('/v1/builds?filter[app]=6400000101')) return ASC_BUILD;
if (path.startsWith('/v1/builds')) return { data: [] };
throw new Error(`GET ${path} -> 404 not recorded`);
};
}
describe('apps list: App Store Connect', () => {
test('pages through /v1/apps, platforms and newest version per app, icon as a data URL', async () => {
const calls: string[] = [];
const icons: string[] = [];
const r = await listAppleApps(ascGet(calls), { icons: true, bytes: async url => { icons.push(url); return { type: 'image/png', data: new Uint8Array([137, 80, 78, 71]) }; } });
expect(r.apps.map(a => a.name)).toEqual(['A Mac Tool', 'Example Notes', 'Example Puzzle']);
const p = r.apps.find(a => a.bundleId === 'com.example.puzzle')!;
expect(p).toMatchObject({ store: 'ios', id: '6400000101', platforms: ['IOS'], latest: { version: '2.4.0', state: 'WAITING_FOR_REVIEW', platform: 'IOS' }, sku: 'PUZZLE1' });
expect(p.icon).toBe('data:image/png;base64,iVBORw==');
expect(icons).toEqual(['https://is1-ssl.mzstatic.com/image/thumb/Purple/v4/ab/cd/AppIcon.png/128x128bb.png']);
expect(r.apps.find(a => a.id === '6400000103')!.platforms).toEqual(['MAC_OS']);
expect(r.apps.find(a => a.id === '6400000102')!).toMatchObject({ platforms: [], latest: null, icon: null });
expect(calls.filter(c => c.startsWith('/v1/builds')).length).toBe(3);
expect(r.warnings).toEqual([]);
});
test('no icons unless asked; a failing version read is a warning, not a failure', async () => {
const calls: string[] = [];
const get = ascGet(calls);
const r = await listAppleApps(async p => { if (p.includes('6400000102/appStoreVersions')) throw new Error(`GET ${p} -> 500 boom`); return get(p); });
expect(calls.some(c => c.startsWith('/v1/builds'))).toBe(false);
expect(r.apps.every(a => a.icon === null)).toBe(true);
expect(r.warnings).toEqual([expect.stringContaining('com.example.notes: versions not read')]);
});
test('icon templates only from Apple\'s CDN', async () => {
const r = await listAppleApps(async p => {
if (p.startsWith('/v1/apps?fields')) return { data: [ASC_APPS_1.data[0]] };
if (p.includes('appStoreVersions')) return { data: [] };
return { data: [{ attributes: { iconAssetToken: { templateUrl: 'https://evil.example.com/{w}x{h}bb.{f}' } } }] };
}, { icons: true, bytes: async () => { throw new Error('must not fetch'); } });
expect(r.apps[0]!.icon).toBeNull();
expect(iconUrl('https://a.mzstatic.com/x/{w}x{h}{c}.{f}', 64)).toBe('https://a.mzstatic.com/x/64x64bb.png');
});
});
describe('apps list: Google Play', () => {
test('apps:search pages, display name falls back to the package', async () => {
const calls: string[] = [];
const r = await listPlayApps(async p => { calls.push(p); return p.includes('pageToken=tok2') ? PLAY_SEARCH_2 : PLAY_SEARCH_1; });
expect(calls).toEqual(['/apps:search?pageSize=1000', '/apps:search?pageSize=1000&pageToken=tok2']);
expect(r.apps.map(a => [a.name, a.id, a.store])).toEqual([['com.example.ledger', 'com.example.ledger', 'android'], ['Example Puzzle', 'com.example.puzzle', 'android'], ['Runner', 'com.example.runner', 'android']]);
});
});
describe('account health', () => {
test('App Store Connect: ok, no apps, revoked (401), permission (403), unreachable', () => {
expect(appleCheck({ apps: 3 })).toMatchObject({ status: 'ok', apps: 3, fix: null });
expect(appleCheck({ apps: 0 }).status).toBe('no-apps');
const revoked = appleCheck({ error: new Error('GET /v1/apps -> 401 {"errors":[{"status":"401","code":"NOT_AUTHORIZED"}]}') });
expect(revoked.status).toBe('revoked');
expect(revoked.fix).toContain('Integrations');
expect(appleCheck({ error: new Error('GET /v1/apps -> 403 {"errors":[{"code":"FORBIDDEN_ERROR"}]}') }).status).toBe('permission');
expect(appleCheck({ error: new Error('fetch failed') }).status).toBe('error');
});
test('Play: ok, not invited (0 apps), API off, revoked key, missing permission; the hint names the service account', () => {
const who = 'play-bot@example.com';
expect(playCheck(who, { apps: 2 })).toMatchObject({ status: 'ok', apps: 2, principal: who });
const none = playCheck(who, { apps: 0 });
expect(none.status).toBe('permission');
expect(none.fix).toContain(`Invite new users: add ${who}`);
expect(none.fix).toContain('several developer accounts');
expect(playCheck(who, { error: new Error('GET /v1beta1/apps:search -> 403 {"error":{"code":403,"status":"PERMISSION_DENIED","details":[{"reason":"SERVICE_DISABLED"}],"message":"Google Play Developer Reporting API has not been used in project 123 before or it is disabled."}}') }).status).toBe('api-disabled');
expect(playCheck(who, { error: new Error('Google token: Invalid JWT Signature.') }).status).toBe('revoked');
expect(playCheck(who, { error: new Error('Google token: invalid_grant') }).status).toBe('revoked');
expect(playCheck(who, { error: new Error('GET /apps:search -> 403 {"error":{"status":"PERMISSION_DENIED","message":"The caller does not have permission"}}') }).status).toBe('permission');
});
});
// ---- the CLI over a mocked fetch (real JWT signing with throwaway keys) ----
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]; } });
function mockFetch(routes: (url: string, init?: RequestInit) => Response | null): string[] {
const seen: string[] = [];
globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
const url = String(input instanceof Request ? input.url : input);
seen.push(`${init?.method ?? 'GET'} ${url}`);
const r = routes(url, init);
if (!r) return new Response('{"error":"not recorded"}', { status: 404 });
return r;
}) as typeof fetch;
return seen;
}
const json = (o: unknown, status = 200) => new Response(JSON.stringify(o), { status, headers: { 'content-type': 'application/json' } });
describe('storebound apps (CLI functions, mocked HTTP)', () => {
const root = mkdtempSync(join(tmpdir(), 'sb-apps-'));
test('apple: list with icons, check', async () => {
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();
const get = ascGet([]);
const seen = mockFetch(url => {
if (url.startsWith('https://is1-ssl.mzstatic.com/')) return new Response(new Uint8Array([1, 2, 3]), { headers: { 'content-type': 'image/png' } });
if (url.startsWith('https://api.appstoreconnect.apple.com')) return null;
return null;
});
// route ASC through the recorded getter
globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
const url = String(input);
seen.push(url);
const auth = new Headers(init?.headers).get('Authorization') ?? '';
if (url.startsWith('https://api.appstoreconnect')) expect(auth).toMatch(/^Bearer [\w-]+\.[\w-]+\.[\w-]+$/);
if (url.startsWith('https://is1-ssl.mzstatic.com/')) return new Response(new Uint8Array([1, 2, 3]), { headers: { 'content-type': 'image/png' } });
try { return json(await get(url.replace('https://api.appstoreconnect.apple.com', ''))); } catch { return json({ errors: [{ status: '404' }] }, 404); }
}) as typeof fetch;
const r = await listApps('apple', root, true);
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 });
globalThis.fetch = (async () => json({ errors: [{ status: '401', code: 'NOT_AUTHORIZED' }] }, 401)) as unknown as typeof fetch;
expect((await checkAccount('apple', root)).status).toBe('revoked');
});
test('play: token exchange, apps:search, check; no apps = not invited', async () => {
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' });
let apps: unknown[] = PLAY_SEARCH_2.apps;
const seen = mockFetch(url => {
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 json({ apps });
return null;
});
const r = await listApps('play', root, false);
expect(r.apps.map(a => a.id)).toEqual(['com.example.ledger']);
expect(seen.some(s => s.startsWith('POST https://oauth2.googleapis.com/token'))).toBe(true);
expect(await checkAccount('play', root)).toMatchObject({ status: 'ok', principal: 'sb@example.com' });
apps = [];
expect((await checkAccount('play', root)).status).toBe('permission');
});
});
// ---- serve: apps.list, account.check, store-only apps ----
const SECRET_HEX = Array.from({ length: 32 }, (_, i) => i.toString(16).padStart(2, '0')).join('');
async function session(reply: (argv: string[], o: RunOptions) => { code?: number; out?: string; data?: unknown } = () => ({})) {
const calls: { argv: string[]; o: RunOptions }[] = [];
const run = (argv: string[], o: RunOptions): Running => { calls.push({ argv, o }); const r = reply(argv, o); return { result: Promise.resolve({ code: r.code ?? 0, out: r.out ?? '', ...(r.data === undefined ? {} : { data: r.data }), cancelled: false }), cancel: () => {} }; };
const s = new Session(() => {}, run);
let id = 0;
const call = async (method: string, params: unknown = {}) => (await s.handle({ jsonrpc: '2.0', id: ++id, method, params }))! as J;
await call('session.hello', { secret: SECRET_HEX });
return { calls, call };
}
const PLAY = { PLAY_SERVICE_ACCOUNT: JSON.stringify({ client_email: 'x@example.com', private_key: '-----BEGIN PRIVATE KEY-----' }) };
const APPLE = { ASC_KEY_ID: 'ABCDE12345', ASC_ISSUER_ID: '00000000-0000-0000-0000-000000000000', ASC_P8: '-----BEGIN PRIVATE KEY-----\nx\n-----END PRIVATE KEY-----' };
describe('serve: account methods', () => {
test('described as kind "account", network reads', () => {
const m = describeMethods().filter(x => x.kind === 'account').map(x => x.method).sort();
expect(m).toEqual(['account.check', 'apps.list']);
});
test('apps.list: one account, its store from the credentials, icons on request, in an empty folder', async () => {
const s = await session(() => ({ data: { store: 'android', apps: [], warnings: [], at: 'x' } }));
const r = await s.call('apps.list', { credentials: PLAY, args: { icons: true } });
expect(r.result).toEqual({ store: 'android', apps: [], warnings: [], at: 'x' });
expect(s.calls[0]!.argv).toEqual(['apps', 'list', '--store', 'play', '--icons', '--json']);
expect(s.calls[0]!.o.env).toEqual(PLAY);
expect(existsSync(join(s.calls[0]!.o.cwd, '.storebound'))).toBe(false);
await s.call('account.check', { credentials: APPLE });
expect(s.calls[1]!.argv).toEqual(['apps', 'check', '--store', 'apple', '--json']);
});
test('apps.list: refuses no account, two accounts, unknown args', async () => {
const s = await session();
for (const p of [{ credentials: {} }, { credentials: { ...PLAY, ...APPLE } }, { credentials: PLAY, args: { only: 'x' } }, { credentials: PLAY, project: '/tmp' }, { credentials: APPLE, args: { icons: 'yes' } }])
expect((await s.call('apps.list', p)).error).toMatchObject({ code: ERR.invalidParams });
expect((await s.call('account.check', { credentials: PLAY, args: { icons: true } })).error).toMatchObject({ code: ERR.invalidParams });
expect(s.calls.length).toBe(0);
});
});
describe('serve: store-only apps (virtual)', () => {
const V = { name: 'Example Puzzle', apple: { bundleId: 'com.example.puzzle', appId: '6400000101' }, play: { packageName: 'com.example.puzzle' } };
test('generated config validates and only carries store ids and placeholders', () => {
expect(validateConfig(virtualConfig(V))).toEqual([]);
expect(validateConfig(virtualConfig({ name: 'Only Play', play: { packageName: 'com.example.runner' } }))).toEqual([]);
const dir = virtualDir(V);
expect(JSON.parse(readFileSync(join(dir, 'storebound.config.json'), 'utf8')).apple).toEqual({ bundleId: 'com.example.puzzle', appId: '6400000101' });
expect(virtualDir(V)).toBe(dir);
for (const bad of [{}, { name: '' }, { name: 'x' }, { name: 'x', apple: { bundleId: '../etc' } }, { name: 'x', play: { packageName: 'nope' } }, { name: 'x', apple: { bundleId: 'com.a.b', appId: '12a' } }, { name: 'x', play: { packageName: 'com.a.b' }, path: '/etc' }])
expect(() => checkVirtual(bad)).toThrow();
});
test('store reads run in the generated folder; writes and offline project reads are refused', async () => {
const s = await session(() => ({ data: { ok: true } }));
const r = await s.call('reviews.list', { virtual: V, args: { days: 30 }, credentials: APPLE });
expect(r.error).toBeUndefined();
expect(existsSync(join(s.calls[0]!.o.cwd, 'storebound.config.json'))).toBe(true);
expect([...VIRTUAL_READS].sort()).toEqual(['apple_ppo_status', 'apple_status', 'apple_testflight_status', 'health', 'play_status', 'reviews_list']);
for (const m of ['play.listing', 'catalog.diff', 'project.listings', 'check', 'reviews.approve'])
expect((await s.call(m, { virtual: V, args: m === 'reviews.approve' ? { file: 'apple-1.md' } : {} })).error).toMatchObject({ code: ERR.invalidParams });
expect((await s.call('health', { virtual: V, project: '/tmp' })).error).toMatchObject({ code: ERR.invalidParams });
});
test('portfolio.status takes store-only entries by key: inspected, no config check, keyed back', async () => {
const s = await session(argv => (argv[0] === 'inspect' ? { data: { dir: '/x', config: '/x/c', name: 'Example Puzzle', languages: ['en'], play: { packageName: 'com.example.puzzle' }, apple: { bundleId: 'com.example.puzzle', appId: '6400000101' }, platforms: ['ios', 'android'], products: 0, productIds: [], subscriptions: 0, subscriptionIds: [], catalog: { ios: [], android: [] }, shots: false, testflightGroups: 0 } } : { data: {} }));
const key = 'store:ios:a1b2:6400000101:com.example.puzzle;android:c3d4:com.example.puzzle';
expect(STORE_KEY_RE.test(key)).toBe(true);
const r = await s.call('portfolio.status', { projects: [{ key, virtual: V }] });
const app = (r.result as { apps: J[] }).apps[0]!;
expect(app).toMatchObject({ project: key, virtual: true, check: { ok: true, problems: [], warnings: [] } });
expect(s.calls.map(c => c.argv[0])).toEqual(['inspect']);
const bad = await s.call('portfolio.status', { projects: [{ key: 'store:../x y', virtual: V }] });
expect(((bad.result as { apps: J[] }).apps[0]!.errors as string[])[0]).toContain('store target key');
});
});