diff --git a/cli/api/wrapped.gen.ts b/cli/api/wrapped.gen.ts index d9b8ac30..cca89656 100644 --- a/cli/api/wrapped.gen.ts +++ b/cli/api/wrapped.gen.ts @@ -77,7 +77,7 @@ export const WRAPPED: { apple: Record; play: Record/...). Without credentials (or when the lookup fails) navigation falls back to the Apps list by name. +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import type { ShipConfig } from '../lib/config'; + +/** Looks the app id up by bundle id: the id, null when no app has that bundle id; throws without credentials. */ +export type AppIdLookup = (bundleId: string) => Promise; + +export interface AppIdOpts { + say: (m: string) => void; + /** Tests: the API lookup (default: ascClient with the project's credentials). */ + lookup?: AppIdLookup; + /** Tests: the cache file (default /.storebound/console-app-ids.json). */ + cacheFile?: string; +} + +const APP_ID = /^\d{1,20}$/; + +function readCache(file: string): Record { + try { + const j = JSON.parse(readFileSync(file, 'utf8')) as Record; + return Object.fromEntries(Object.entries(j).filter((e): e is [string, string] => typeof e[1] === 'string' && APP_ID.test(e[1]))); + } catch { return {}; } +} + +async function apiLookup(root: string): Promise { + const { ascClient } = await import('../apple/asc'); + return async bundleId => { + const c = await ascClient(root, bundleId); // throws without ASC_KEY_ID / ASC_ISSUER_ID / key + const found = await c.asc('GET', `/v1/apps?filter[bundleId]=${encodeURIComponent(bundleId)}`); + const hit = (found.data as { id: string; attributes: { bundleId: string } }[]).find(a => a.attributes.bundleId === bundleId); + return hit?.id ?? null; + }; +} + +/** + * apple.appId, else the cached one for apple.bundleId, else the API lookup (then cached). null: the Apps list by name is + * used (no bundle id, no credentials, no such app, or the API failed: said in the log). + */ +export async function appleAppId(root: string, config: ShipConfig, o: AppIdOpts): Promise { + if (config.apple?.appId) return config.apple.appId; + const bundleId = config.apple?.bundleId; + if (!bundleId) return null; + const file = o.cacheFile ?? join(root, '.storebound', 'console-app-ids.json'); + const cache = readCache(file); + if (cache[bundleId]) { + o.say(`app: ${bundleId} is Apple ID ${cache[bundleId]} (looked up earlier, ${file}); opening it by link`); + return cache[bundleId]!; + } + let id: string | null; + try { id = await (o.lookup ?? await apiLookup(root))(bundleId); } catch (e) { + o.say(`app: no apple.appId in the config and the App Store Connect API lookup did not work (${(e as Error).message.split('\n')[0]}); finding the app in the Apps list by name`); + return null; + } + if (!id || !APP_ID.test(id)) { + o.say(`app: the App Store Connect API has no app with bundle id ${bundleId}; finding it in the Apps list by name`); + return null; + } + try { mkdirSync(dirname(file), { recursive: true }); writeFileSync(file, `${JSON.stringify({ ...cache, [bundleId]: id }, null, 1)}\n`); } catch { /* cache only */ } + o.say(`app: ${bundleId} is Apple ID ${id} (App Store Connect API); opening it by link. Put "appId": "${id}" in apple of the config to skip the lookup`); + return id; +} + +/** The config with apple.appId filled in (unchanged when there is none). */ +export const withAppleAppId = (config: ShipConfig, id: string | null): ShipConfig => + id && config.apple && !config.apple.appId ? { ...config, apple: { ...config.apple, appId: id } } : config; diff --git a/cli/console/fill.ts b/cli/console/fill.ts index 49dda9b8..5ce1f258 100644 --- a/cli/console/fill.ts +++ b/cli/console/fill.ts @@ -32,6 +32,7 @@ import type { ShipConfig } from '../lib/config'; import { ALL_APPS, consoleReached, CREATE_FORM_FIELD, createAppAllowed, type FieldDef, type FormDef, formDef, FORM_OPENERS, forbiddenControl, hasToken, isSignInText, isSignInUrl, type Name, navAllowed, type NavBases, type NavStep, navPlan } from '../lib/console-forms'; import { log, printJson, warn } from '../lib/log'; import { openAcross, withAccountIds } from './accounts'; +import { appleAppId, withAppleAppId } from './app-id'; import { type ConsoleBrowser, openConsoleBrowser } from './session'; /* eslint-disable @typescript-eslint/no-explicit-any */ @@ -318,6 +319,13 @@ export async function poll(ms: number, fn: () => Promise, stop?: St } } +/** The app a list link opens: "apps/" for an App Store Connect app URL (any sub page), else the URL without its fragment. */ +export function appKey(href: string | null): string | null { + if (!href) return null; + const id = href.match(/\/apps\/(\d+)(?:[/?#]|$)/)?.[1]; + return id ? `apps/${id}` : href.replace(/#.*$/, ''); +} + const opener = new RegExp(`^(?:${FORM_OPENERS.join('|')})$`); export async function pickApp(page: Page, s: Extract, ms: number, stop?: Stop): Promise<{ loc?: Locator; candidates?: string[] } | null> { @@ -329,14 +337,19 @@ export async function pickApp(page: Page, s: Extract `${el.innerText ?? ''} ${el.textContent ?? ''}`) : ''; const byToken = s.tokens.some(t => hasToken(name, t) || hasToken(text.replace(/\s+/g, ' '), t)); const byName = role === 'link' && s.name !== undefined && name === s.name; - if (byToken || byName) hits.push({ loc, name }); + if (!byToken && !byName) continue; + // one app shown twice (App Store Connect's grid: the card's title link and its icon link / aria-label) is ONE + // app: hits are told apart by the app they open (/apps/, else the link target), not by their name + const key = appKey(await loc.evaluate((el: any) => (el.closest('a[href]') ?? el.querySelector('a[href]'))?.href ?? null).catch(() => null)); + if (key && hits.some(h => h.key === key)) continue; + hits.push({ loc, name, key }); } if (hits.length === 1) { const row = hits[0]!.loc; @@ -518,7 +531,9 @@ export async function run(ctx: Ctx): Promise { const bye = () => { if (stopping) return; stopping = true; void b.close().finally(() => { b.cleanup(); process.exit(130); }); }; process.on('SIGINT', bye); process.on('SIGTERM', bye); try { - const out = await fillSession(b, { form, config, say, ...(startUrl ? { startUrl } : {}) }); + // App Privacy opens by deep link when the app id is known (config, cache or the API by bundle id), else by the list + const cfg = form === 'apple-app-privacy' && !startUrl ? withAppleAppId(config, await appleAppId(root, config, { say })) : config; + const out = await fillSession(b, { form, config: cfg, say, ...(startUrl ? { startUrl } : {}) }); if (json) printJson({ ...res, ...out, stoppedAt: meta.stopBefore, browser: b.mode }); } finally { b.cleanup(); process.off('SIGINT', bye); process.off('SIGTERM', bye); } } diff --git a/docs/api-coverage.md b/docs/api-coverage.md index 11832d92..65e26f3b 100644 --- a/docs/api-coverage.md +++ b/docs/api-coverage.md @@ -458,7 +458,7 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co | `apps_gameCenterDetail_getToOneRelationship` | GET | `/v1/apps/{id}/relationships/gameCenterDetail` | read | | | `apps_gameCenterEnabledVersions_getToManyRelated` | GET | `/v1/apps/{id}/gameCenterEnabledVersions` | read | | | `apps_gameCenterEnabledVersions_getToManyRelationship` | GET | `/v1/apps/{id}/relationships/gameCenterEnabledVersions` | read | | -| `apps_getCollection` | GET | `/v1/apps` | read | apple/asc, apple/bundle, apps, lib/store-apps | +| `apps_getCollection` | GET | `/v1/apps` | read | apple/asc, apple/bundle, apps, console/app-id, lib/store-apps | | `apps_getInstance` | GET | `/v1/apps/{id}` | read | apple/appinfo, apple/status | | `apps_inAppPurchasesV2_getToManyRelated` | GET | `/v1/apps/{id}/inAppPurchasesV2` | read | apple/iap, apple/iap-review, apple/iap-submit, apple/offer-codes, apple/promoted, apple/status, catalog, prices, validate | | `apps_inAppPurchasesV2_getToManyRelationship` | GET | `/v1/apps/{id}/relationships/inAppPurchasesV2` | read | | diff --git a/skills/console-autofill/SKILL.md b/skills/console-autofill/SKILL.md index 7596bcdc..b233863e 100644 --- a/skills/console-autofill/SKILL.md +++ b/skills/console-autofill/SKILL.md @@ -69,8 +69,10 @@ It is not available over MCP. 10 minutes, never typing or reading anything there; when the console is back (no sign-in page, the console URL) it opens the form again from step 1. 4. After sign-in storebound opens the form itself and logs every step ("opening the form, step 2/4: the add button - (+)"): New App: Apps > + > New App; App Privacy: `/apps//distribution/privacy`, or the app list > the - app (by name / bundle id) > App Privacy; Play forms: the app list > the app (by `play.packageName`) > Policy and + (+)"): New App: Apps > + > New App; App Privacy: `/apps//distribution/privacy` (without `apple.appId` + but with App Store Connect API credentials, storebound looks the id up from `apple.bundleId` and caches it in + `.storebound/console-app-ids.json`), else the app list > the app (by name / bundle id; one app shown twice on its + card, title and icon, is one app) > App Privacy; Play forms: the app list > the app (by `play.packageName`) > Policy and programs > App content > the form's Start or Manage link. These navigation clicks pass the same click gate: never Save, Submit, Publish, Create, Send, Next or the Turkish equivalents; only a LINK named exactly Start / Manage / Başla / Yönet is let through. If a step is not found in time, or two apps match (they are listed: set diff --git a/tests/console-app-id.test.ts b/tests/console-app-id.test.ts new file mode 100644 index 00000000..e45505a8 --- /dev/null +++ b/tests/console-app-id.test.ts @@ -0,0 +1,70 @@ +// console fill apple-app-privacy without apple.appId: the app id from the App Store Connect API (by bundle id, cached) +// -> deep link; no credentials / no app -> the Apps list by name. No network: the lookup is injected. +import { afterAll, describe, expect, test } from 'bun:test'; +import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { appleAppId, withAppleAppId } from '../cli/console/app-id'; +import { appKey } from '../cli/console/fill'; +import type { ShipConfig } from '../cli/lib/config'; +import { navPlan } from '../cli/lib/console-forms'; + +const tmp = mkdtempSync(join(tmpdir(), 'sb-app-id-')); +afterAll(() => rmSync(tmp, { recursive: true, force: true })); + +const config = { + app: { name: 'Example Game', profile: 'game', privacyPolicyUrl: 'https://example.com/privacy', supportUrl: 'https://example.com/support', website: 'https://example.com', contactEmail: 'support@example.com' }, + languages: [{ id: 'en', play: 'en-US', apple: 'en-US' }], + apple: { bundleId: 'com.example.game', primaryLocale: 'en-US' }, +} as ShipConfig; + +describe('apple app id for console fill', () => { + test('API credentials: looked up by bundle id, cached, and the form opens by deep link', async () => { + const cacheFile = join(tmp, 'a', 'console-app-ids.json'); + const said: string[] = []; + const asked: string[] = []; + const lookup = async (b: string) => { asked.push(b); return '6800000001'; }; + const id = await appleAppId(tmp, config, { say: m => said.push(m), lookup, cacheFile }); + expect(id).toBe('6800000001'); + expect(asked).toEqual(['com.example.game']); + expect(JSON.parse(readFileSync(cacheFile, 'utf8'))).toEqual({ 'com.example.game': '6800000001' }); + expect(said.some(m => m.includes('Apple ID 6800000001 (App Store Connect API)'))).toBe(true); + const plan = navPlan('apple-app-privacy', withAppleAppId(config, id)); + expect(plan.map(s => s.kind)).toEqual(['goto', 'wait']); + expect(plan[0]).toMatchObject({ url: 'https://appstoreconnect.apple.com/apps/6800000001/distribution/privacy' }); + // the second run reads the cache, no API call + const again = await appleAppId(tmp, config, { say: () => {}, lookup: async () => { throw new Error('not called'); }, cacheFile }); + expect(again).toBe('6800000001'); + }); + + test('no API credentials: null, said, and the Apps list by name is used', async () => { + const cacheFile = join(tmp, 'b', 'console-app-ids.json'); + const said: string[] = []; + const id = await appleAppId(tmp, config, { say: m => said.push(m), lookup: async () => { throw new Error('ASC_KEY_ID and ASC_ISSUER_ID are not set (env, or .storebound/credentials.json)'); }, cacheFile }); + expect(id).toBeNull(); + expect(existsSync(cacheFile)).toBe(false); + expect(said.join('\n')).toContain('finding the app in the Apps list by name'); + const plan = navPlan('apple-app-privacy', withAppleAppId(config, id)); + expect(plan.map(s => s.kind)).toEqual(['goto', 'pickApp', 'click', 'wait']); + }); + + test('no app with that bundle id: null; apple.appId in the config wins without a lookup; no bundle id: null', async () => { + const cacheFile = join(tmp, 'c', 'console-app-ids.json'); + expect(await appleAppId(tmp, config, { say: () => {}, lookup: async () => null, cacheFile })).toBeNull(); + const set = { ...config, apple: { ...config.apple!, appId: '123' } } as ShipConfig; + expect(await appleAppId(tmp, set, { say: () => {}, lookup: async () => { throw new Error('not called'); }, cacheFile })).toBe('123'); + expect(withAppleAppId(set, '999')).toBe(set); + const noBundle = { ...config, apple: { primaryLocale: 'en-US' } } as unknown as ShipConfig; + expect(await appleAppId(tmp, noBundle, { say: () => {}, lookup: async () => { throw new Error('not called'); }, cacheFile })).toBeNull(); + }); +}); + +describe('appKey (one app shown twice in the list is one app)', () => { + test('App Store Connect app URLs by id, any sub page; other links by URL without fragment', () => { + expect(appKey('https://appstoreconnect.apple.com/apps/6800000001/distribution/ios/version/inflight')).toBe('apps/6800000001'); + expect(appKey('https://appstoreconnect.apple.com/apps/6800000001/appstore')).toBe('apps/6800000001'); + expect(appKey('https://appstoreconnect.apple.com/apps/6800000001')).toBe('apps/6800000001'); + expect(appKey('http://127.0.0.1:1/asc-app.html?id=1#x')).toBe('http://127.0.0.1:1/asc-app.html?id=1'); + expect(appKey(null)).toBeNull(); + }); +}); diff --git a/tests/console-fill.test.ts b/tests/console-fill.test.ts index 34b338b6..db7a3dc3 100644 --- a/tests/console-fill.test.ts +++ b/tests/console-fill.test.ts @@ -182,7 +182,7 @@ const FOUND_MS = 15_000; const FIX = join(import.meta.dir, 'fixtures', 'console'); /** Console URLs of the navigation plans -> modeled pages (bases: asc = asc, play = play). */ const ROUTES: Record = { - '/asc/apps': 'asc-apps.html', '/asc-tr/apps': 'asc-apps-tr.html', '/asc-noplus/apps': 'asc-apps-noplus.html', '/asc-dup/apps': 'asc-apps-dup.html', + '/asc/apps': 'asc-apps.html', '/asc-tr/apps': 'asc-apps-tr.html', '/asc-noplus/apps': 'asc-apps-noplus.html', '/asc-dup/apps': 'asc-apps-dup.html', '/asc-card/apps': 'asc-apps-card.html', '/asc/apps/123/distribution/privacy': 'apple-app-privacy.html', '/play': 'play-apps.html', '/teams/apps': 'asc-teams.html', '/playc': 'play-home.html', '/playc-tr': 'play-home-tr.html', }; @@ -196,6 +196,7 @@ beforeAll(() => { const devNew = path.match(/^\/playn\/u\/0\/developers(?:\/(\d+)\/app-list)?$/); const name = path.endsWith('/_common.js') ? '_common.js' : devNew ? (devNew[1] ? 'play-home.html' : 'play-chooser.html') : dev ? (!dev[1] ? 'play-chooser.html' : dev[1] === '4444' ? 'play-apps.html' : 'play-apps-other.html') + : /^\/asc-card\/apps\/\d+\/distribution\//.test(path) ? 'asc-app.html' : ROUTES[path] ?? path.slice(1); if (!/^[a-z_-]+\.(html|js)$/.test(name)) return new Response('not found', { status: 404 }); return new Response(Bun.file(join(FIX, name))); @@ -464,6 +465,16 @@ describe.skipIf(!browser)('navigation (headless, modeled pages)', () => { await page.close(); }, BROWSER_TEST_MS); + test('App Privacy: an app card that names the app twice (icon aria-label + title link, same /apps/) is one app', async () => { + const page = await fresh(); + const r = await navigate(page, navPlan('apple-app-privacy', config, bases('asc-card')), quiet); + expect(r).toMatchObject({ ok: true }); + expect(r.candidates).toBeUndefined(); + expect(await navClicks(page)).toEqual(['Example Game', 'App Privacy']); + expect(await clicks(page)).toEqual([]); + await page.close(); + }, BROWSER_TEST_MS); + test('Play: the app by package name > Policy and programs > App content > Start / Manage; nothing deny-listed clicked', async () => { for (const [form, link, heading] of [['play-content-rating', 'Start', 'Content rating'], ['play-target-audience', 'Manage', 'Target audience and content']] as const) { const page = await fresh(); diff --git a/tests/fixtures/console/asc-apps-card.html b/tests/fixtures/console/asc-apps-card.html new file mode 100644 index 00000000..9effb46a --- /dev/null +++ b/tests/fixtures/console/asc-apps-card.html @@ -0,0 +1,22 @@ + + +Apps - App Store Connect + +

Apps

+ +
    +
  • + + Example Game + iOS 1.0 Prepare for Submission +
  • +
  • + + Other App + iOS 2.1 Ready for Distribution +
  • +
+ + diff --git a/tests/fixtures/console/asc-apps-dup.html b/tests/fixtures/console/asc-apps-dup.html index b630d73c..f252b17e 100644 --- a/tests/fixtures/console/asc-apps-dup.html +++ b/tests/fixtures/console/asc-apps-dup.html @@ -1,8 +1,8 @@ - Apps - App Store Connect

Apps

- +