console fill: one app shown twice is one app; App Privacy opens by app id via the API

`console fill apple-app-privacy` without apple.appId stopped at "the app
in the list" with "more than one app matches: X | X" for an account with
one app: the Apps grid names each app twice (the icon link's aria-label
and the title link), both opening the same /apps/<id>/... page.

- pickApp tells hits apart by the app they open (/apps/<id>, else the
  link target), not by name. Two apps of one name with different targets
  still stop and are listed.
- Without apple.appId, but with App Store Connect API credentials, the
  app id is looked up from apple.bundleId (GET /v1/apps?filter[bundleId],
  as `apple status` does), cached in .storebound/console-app-ids.json, and
  App Privacy opens by deep link. Without credentials, or when the lookup
  fails, the Apps list by name is used, and the log says so.

Fixture asc-apps-card.html (a card with the name in the title and an
aria-label); tests for both paths.
This commit is contained in:
CRTkafa 2026-10-11 22:32:21 +00:00
parent 48d6211e5b
commit 0c2261cb33
9 changed files with 199 additions and 10 deletions

View file

@ -77,7 +77,7 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
'apps_betaGroups_getToManyRelated': 'apple/testflight',
'apps_buildUploads_getToManyRelated': 'apple/upload',
'apps_customerReviews_getToManyRelated': 'reviews',
'apps_getCollection': 'apple/asc apple/bundle apps lib/store-apps',
'apps_getCollection': 'apple/asc apple/bundle apps console/app-id lib/store-apps',
'apps_getInstance': 'apple/appinfo apple/status',
'apps_inAppPurchasesV2_getToManyRelated': 'apple/iap apple/iap-review apple/iap-submit apple/offer-codes apple/promoted apple/status catalog prices validate',
'apps_perfPowerMetrics_getToManyRelated': 'health',

69
cli/console/app-id.ts Normal file
View file

@ -0,0 +1,69 @@
// The App Store Connect app id (Apple ID) for `console fill` when the config has no apple.appId: with App Store Connect
// API credentials it is looked up from apple.bundleId (GET /v1/apps?filter[bundleId], the lookup `apple status` uses),
// cached in .storebound/console-app-ids.json (gitignored, never the config) and the form opens by deep link
// (/apps/<id>/...). 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<string | null>;
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 <root>/.storebound/console-app-ids.json). */
cacheFile?: string;
}
const APP_ID = /^\d{1,20}$/;
function readCache(file: string): Record<string, string> {
try {
const j = JSON.parse(readFileSync(file, 'utf8')) as Record<string, unknown>;
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<AppIdLookup> {
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<string | null> {
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;

View file

@ -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<T>(ms: number, fn: () => Promise<T | null>, stop?: St
}
}
/** The app a list link opens: "apps/<id>" 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<NavStep, { kind: 'pickApp' }>, ms: number, stop?: Stop): Promise<{ loc?: Locator; candidates?: string[] } | null> {
@ -329,14 +337,19 @@ export async function pickApp(page: Page, s: Extract<NavStep, { kind: 'pickApp'
for (const role of ['row', 'link']) {
const all = vis(page.getByRole(role));
const n = await all.count();
const hits: { loc: Locator; name: string }[] = [];
const hits: { loc: Locator; name: string; key: string | null }[] = [];
for (let i = 0; i < n; i++) {
const loc = all.nth(i), name = await accName(loc);
// innerText keeps the cells apart ("Example Game\tcom.example.game"), the accessible name may glue them
const text: string = s.tokens.length ? await loc.evaluate((el: any) => `${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/<id>, 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<void> {
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); }
}