Merge origin/main into shots-glyphs

# Conflicts:
#	CHANGELOG.md
This commit is contained in:
CRTkafa 2026-10-12 03:05:32 +08:00
commit 8bfa49807d
22 changed files with 1101 additions and 110 deletions

View file

@ -17,6 +17,24 @@
- New `shots.fonts.fallback: ['Noto Sans Display']` to accept a fallback. Default game title font is now Paytone One - New `shots.fonts.fallback: ['Noto Sans Display']` to accept a fallback. Default game title font is now Paytone One
(covers Latin Extended and Vietnamese) in the template, the demo and the built-in default; README and the (covers Latin Extended and Vietnamese) in the template, the demo and the built-in default; README and the
store-screenshots skill document the default stack per script. store-screenshots skill document the default stack per script.
- `console fill`, from a real run whose App Store Connect session had expired (the add button was "not found" while
the window showed the sign-in form):
- Sign-in is detected by URL and frame (App Store Connect `/login`, idmsa.apple.com / appleid.apple.com frames,
Google sign-in), a password field in any frame, and the form's texts (Sign in with Passkey, Email or Phone Number,
Turkish too), before every navigation step, after each click or load and while a step waits. storebound waits for
the owner (never typing or reading there) and then opens the form again from step 1.
- After the printed manual steps it keeps watching: a finished sign-in restarts navigation, the owner moving on by
hand resumes it from that step, a form the owner opened is filled. A field missing only while a page loads no
longer counts as a UI change.
- The sign-in is kept: copy and own-profile modes launch with `--restore-last-session` (session cookies such as
Apple's are loaded again; restored tabs are closed) and Ctrl+C closes the browser gracefully so cookies are
written. Hints to tick "Keep me signed in" / "Trust" (Apple) and "Stay signed in" (Google).
- One login, many developer accounts / teams: Play finds `play.packageName` across every developer account of the
login (or opens `play.developerId` directly), App Store Connect switches teams in the account menu (`apple.teamId`
first, else the bundle id in each team); the match is remembered in `~/.storebound/console-accounts.json` (ids
only). New config `play.developerId`; workspace accounts take `developerId` / `teamId`. Switch clicks pass their
own gate (an account name just read from the list, never sign out or a deny-listed name).
- Fixes from a live monorepo game (username accounts, Capacitor in `apps/native`): - Fixes from a live monorepo game (username accounts, Capacitor in `apps/native`):
- `scan` no longer turns accounts into "Email Address" / `PSL_EMAIL`: accounts mean User ID; email is "detected" - `scan` no longer turns accounts into "Email Address" / `PSL_EMAIL`: accounts mean User ID; email is "detected"
only with real evidence (an email field or keyboard, an `email` property in a body / schema / type, an email only with real evidence (an email field or keyboard, an `email` property in a body / schema / type, an email

View file

@ -490,7 +490,13 @@ a terminal first and are never offered over MCP.
debugging, else (macOS) reuses your Chrome sign-in: it copies ONLY `Local State` and your profile's `Cookies` debugging, else (macOS) reuses your Chrome sign-in: it copies ONLY `Local State` and your profile's `Cookies`
(+ journal) into a temporary profile, keeps only the apple.com / google.com cookies the consoles use, opens real (+ journal) into a temporary profile, keeps only the apple.com / google.com cookies the consoles use, opens real
Chrome on it and deletes it when the run ends (never passwords, history or extensions; cookies are never printed Chrome on it and deletes it when the run ends (never passwords, history or extensions; cookies are never printed
or sent anywhere; macOS may ask once for Keychain access). `--fresh-profile` uses storebound's own profile instead. or sent anywhere; macOS may ask once for Keychain access). `--fresh-profile` uses storebound's own profile instead
(one per store; the sign-in is kept between runs: session restore on launch, graceful close; tick "Keep me signed
in" / "Stay signed in"). It detects sign-in pages by URL, frame and text (Apple's starts with no password field),
waits while you sign in and then opens the form from step 1; after printing manual steps it keeps watching and picks
up where you are. **One login, many studios:** it finds the Play developer account (by `play.packageName`, or
`play.developerId`) and the App Store Connect team (account menu; `apple.teamId`, or by bundle id) that has the
app and remembers it in `~/.storebound/console-accounts.json` (ids only).
When a page has changed it falls back to step-by-step guidance with copyable answers. **Console pages change; this is AI-assisted: review every field and save it yourself.** Desktop: "Fill in When a page has changed it falls back to step-by-step guidance with copyable answers. **Console pages change; this is AI-assisted: review every field and save it yourself.** Desktop: "Fill in
console" on the App info tab. Never over MCP. Skill: `console-autofill`. console" on the App info tab. Never over MCP. Skill: `console-autofill`.

263
cli/console/accounts.ts Normal file
View file

@ -0,0 +1,263 @@
// One sign-in, many developer accounts and teams (`storebound console fill`): the owner's ONE Google login can be an
// admin of several Play developer accounts, and ONE Apple ID a member of several App Store Connect teams. storebound
// never asks for a second sign-in: it finds the account that has the app and remembers it.
// Play: the app list of one developer account is play.google.com/console/u/0/developers/<id>/app-list. The id comes
// from play.developerId (config), STOREBOUND_PLAY_DEVELOPER_ID (a workspace account's developerId, set by
// `ws`), or the cache; else storebound reads every developer account link on the chooser
// (/console/u/0/developers) and looks for play.packageName in each app list.
// Apple: the team is switched in the account menu at the top right (the team list; Apple's help "Switch between
// teams"). The order tried: the cached team, the menu entry that names apple.teamId, then every other team; the
// app is found by its list entry (App Privacy) or, for a new app, by the bundle id in the New App dialog's Bundle ID
// list (the dialog is closed again with Cancel when the bundle id is not there). App Store Connect has no
// documented URL parameter that selects a team, so storebound does not use one.
// The id mappings (no cookies, no names of people) live in ~/.storebound/console-accounts.json, shared with the
// desktop app: { "version": 1, "play": { "<package>": { "developerId", "account", "at" } }, "apple": { "<bundle id>":
// { "team", "teamId"?, "at" } } }. Switching only changes what the console shows: every switch click goes through the
// account-switch gate (switchAllowed: the exact name just read from the list, never sign out or a deny-listed name).
// The chooser and the team menu are MODELED from the public help pages, not recorded: a miss falls back to the account
// that is open, and the log says to set play.developerId / apple.teamId.
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { dirname, join } from 'node:path';
import type { ShipConfig } from '../lib/config';
import type { FormId } from '../lib/console-answers';
import { hasToken, type Name, NAV_BASES, type NavBases, type NavStep, navPlan, playDeveloperId, switchAllowed } from '../lib/console-forms';
import { accName, findAny, type Locator, navClick, navigate, type NavResult, type Page, poll, realRole, safeClick, signInPage, SignInSeen, type Stop, vis } from './fill';
// ---- the cache ----
export interface PlayEntry { developerId: string; account?: string; at: string }
export interface AppleEntry { team: string; teamId?: string; at: string }
export interface AccountsCache { version: 1; play: Record<string, PlayEntry>; apple: Record<string, AppleEntry> }
export const accountsFile = (): string => process.env.STOREBOUND_CONSOLE_ACCOUNTS || join(homedir(), '.storebound', 'console-accounts.json');
const KEY = /^[A-Za-z0-9._-]{1,200}$/;
const str = (v: unknown, max = 200): v is string => typeof v === 'string' && v.length > 0 && v.length <= max;
/** The cache, cleaned (anything malformed is dropped); empty when there is none. */
export function readAccounts(file = accountsFile()): AccountsCache {
const out: AccountsCache = { version: 1, play: {}, apple: {} };
let j: any;
try { j = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : null; } catch { return out; }
for (const [k, v] of Object.entries((j?.play ?? {}) as Record<string, any>)) {
if (KEY.test(k) && typeof v?.developerId === 'string' && /^\d{1,25}$/.test(v.developerId)) out.play[k] = { developerId: v.developerId, ...(str(v.account) ? { account: v.account } : {}), at: str(v.at, 40) ? v.at : '' };
}
for (const [k, v] of Object.entries((j?.apple ?? {}) as Record<string, any>)) {
if (KEY.test(k) && str(v?.team)) out.apple[k] = { team: v.team, ...(typeof v.teamId === 'string' && /^[A-Z0-9]{10}$/.test(v.teamId) ? { teamId: v.teamId } : {}), at: str(v.at, 40) ? v.at : '' };
}
return out;
}
/** Remembers which account has the app (written atomically: the desktop app may read it at the same time). */
export function rememberPlay(pkg: string, e: Omit<PlayEntry, 'at'>, file = accountsFile()): void {
const c = readAccounts(file);
c.play[pkg] = { ...e, at: new Date().toISOString() };
write(c, file);
}
export function rememberApple(bundleId: string, e: Omit<AppleEntry, 'at'>, file = accountsFile()): void {
const c = readAccounts(file);
c.apple[bundleId] = { ...e, at: new Date().toISOString() };
write(c, file);
}
function write(c: AccountsCache, file: string): void {
mkdirSync(dirname(file), { recursive: true });
const tmp = `${file}.${process.pid}.tmp`;
writeFileSync(tmp, JSON.stringify(c, null, 2) + '\n');
renameSync(tmp, file);
}
// ---- Play: developer accounts ----
/**
* The developer accounts the login can see: every link to /developers/<id> on the account chooser
* (/console/u/0/developers), as { id, name }. A login with one account lands in that account: its id only.
*/
export async function playAccounts(page: Page, playBase: string, ms: number, stop?: Stop): Promise<{ id: string; name: string }[]> {
await page.goto(`${playBase.replace(/\/$/, '')}/u/0/developers`, { waitUntil: 'domcontentloaded' }).catch(() => { /* read what is there */ });
const found = await poll(ms, async () => {
const links = vis(page.locator('a[href*="/developers/"]'));
const n: number = await links.count();
const out: { id: string; name: string }[] = [];
for (let i = 0; i < n; i++) {
const href: string | null = await links.nth(i).getAttribute('href');
const id = href ? playDeveloperId(new URL(href, page.url()).href) : null;
if (id && !out.some(o => o.id === id)) out.push({ id, name: await accName(links.nth(i)) });
}
return out.length ? out : null;
}, stop);
if (found) return found;
const here = playDeveloperId(page.url());
return here ? [{ id: here, name: '' }] : [];
}
// ---- App Store Connect: teams ----
/** The account menu button at the top right (it lists the teams). */
export const ACCOUNT_MENU: Name[] = ['Account', 'Account menu', 'Your account', 'Hesap', 'Hesabım', 'Hesap menüsü', /^account\b/i, /^hesap\b/iu];
const CANCEL: Name[] = ['Cancel', 'İptal', 'Vazgeç'];
interface TeamItem { name: string; loc: Locator; role: string; current: boolean }
async function teamMenu(page: Page, ms: number, stop?: Stop): Promise<TeamItem[] | null> {
const t = await poll(ms, async () => { const f = await findAny(page, ['button'], ACCOUNT_MENU); return f.state === 'ok' ? f.loc : null; }, stop);
if (!t || !(await navClick(t)).clicked) return null;
return poll(Math.min(ms, 3000), async () => {
const menus = vis(page.getByRole('menu'));
if (await menus.count() !== 1) return null;
const out: TeamItem[] = [];
for (const role of ['menuitemradio', 'menuitem', 'option', 'link', 'button']) {
const l = vis(menus.getByRole(role));
const n: number = await l.count();
for (let i = 0; i < n; i++) {
const loc = l.nth(i), name = await accName(loc);
if (out.some(o => o.name === name) || !switchAllowed(name, role, [name])) continue;
out.push({ name, loc, role, current: (await loc.getAttribute('aria-checked')) === 'true' || (await loc.getAttribute('aria-current')) !== null });
}
}
return out.length ? out : null;
}, stop);
}
const closeMenu = async (page: Page) => { await page.keyboard.press('Escape').catch(() => { /* gone */ }); };
/** The teams in the account menu (read, then the menu is closed again), or null when there is no team menu. */
export async function appleTeams(page: Page, ms: number, stop?: Stop): Promise<string[] | null> {
const items = await teamMenu(page, ms, stop);
if (items) await closeMenu(page);
return items ? items.map(i => i.name) : null;
}
/** Switches to the team `name` (one of `listed`) through the account menu. true when switched (or already current). */
export async function switchTeam(page: Page, name: string, listed: string[], ms: number, stop?: Stop): Promise<boolean> {
const items = await teamMenu(page, ms, stop);
const it = items?.find(i => i.name === name);
if (!it) { await closeMenu(page); return false; }
if (it.current) { await closeMenu(page); return true; }
const real = await accName(it.loc), role = await realRole(it.loc);
if (!switchAllowed(real, role, listed)) { await closeMenu(page); return false; }
await it.loc.click();
await page.waitForLoadState('domcontentloaded').catch(() => { /* same page */ });
await Bun.sleep(300);
return true;
}
/** In the open New App dialog: does the Bundle ID list offer `bundleId`? null when it cannot tell (no native list). */
export async function bundleOffered(page: Page, bundleId: string): Promise<boolean | null> {
const box = vis(page.getByRole('dialog').getByRole('combobox', { name: /bundle id|paket kimliği|bundle kimliği/iu }));
if (await box.count() !== 1) return null;
const opts: string[] | null = await box.evaluate((el: any) => (el.tagName === 'SELECT' ? [...el.options].map((o: any) => o.textContent || '') : null));
return opts ? opts.some(o => hasToken(o, bundleId)) : null;
}
// ---- opening the form in the right account ----
export interface AcrossOpts {
form: FormId;
config: ShipConfig;
say: (m: string) => void;
bases?: NavBases;
navMs: number;
signIn?: (page: Page) => Promise<boolean>;
file?: string;
env?: Record<string, string | undefined>;
}
/** The config with the ids a workspace account passes (env) when the config itself has none. */
export function withAccountIds(config: ShipConfig, env: Record<string, string | undefined> = process.env): ShipConfig {
const dev = env.STOREBOUND_PLAY_DEVELOPER_ID, team = env.STOREBOUND_APPLE_TEAM_ID;
let c = config;
if (c.play && !c.play.developerId && dev && /^\d{1,25}$/.test(dev)) c = { ...c, play: { ...c.play, developerId: dev } };
if (c.apple && !c.apple.teamId && team && /^[A-Z0-9]{10}$/.test(team)) c = { ...c, apple: { ...c.apple, teamId: team } };
return c;
}
/** The navigation stopped because the app is not in this account (not because the page changed). */
function notHere(r: NavResult, plan: NavStep[]): boolean {
const s = plan.find(p => p.label === r.failed);
if (!s || r.signIn) return false;
if (s.kind === 'pickApp') return !r.candidates && /^no app matching/.test(r.why ?? '');
return s.kind === 'wait' && plan.length === 2 && plan[0]!.kind === 'goto'; // a deep link (apple.appId) of another team
}
/**
* Opens the form in the account that has the app: the remembered / configured one first, else every account the one
* login can see. Returns the navigation result and the plan used (resumeAt continues with it). A sign-in page ->
* `signIn` (the caller waits and calls again).
*/
export async function openAcross(page: Page, o: AcrossOpts): Promise<{ nav: NavResult; plan: NavStep[] }> {
try { return await across(page, o); } catch (e) {
if (e instanceof SignInSeen) return { nav: { ok: false, steps: [], failed: 'the account list', why: 'a sign-in page appeared', signIn: true }, plan: [] };
throw e;
}
}
async function across(page: Page, o: AcrossOpts): Promise<{ nav: NavResult; plan: NavStep[] }> {
const config = withAccountIds(o.config, o.env), file = o.file ?? accountsFile(), cache = readAccounts(file);
const bases = o.bases ?? NAV_BASES, say = o.say;
const isSignIn = o.signIn ?? signInPage;
const stop: Stop = () => isSignIn(page).catch(() => false);
const nav = (plan: NavStep[], ms = o.navMs) => navigate(page, plan, { say, timeoutMs: ms, signIn: isSignIn });
const store = o.form.startsWith('play-') ? 'play' : 'apple';
const quick = Math.min(o.navMs, 8000);
if (store === 'play') {
const pkg = config.play?.packageName;
const planFor = (id?: string) => navPlan(o.form, id ? { ...config, play: { ...config.play!, developerId: id } } : config, bases);
const known = config.play?.developerId ?? (pkg ? cache.play[pkg]?.developerId : undefined);
if (known) {
const plan = planFor(known), r = await nav(plan);
if (r.ok && pkg) rememberPlay(pkg, { developerId: known, ...(cache.play[pkg]?.account ? { account: cache.play[pkg]!.account! } : {}) }, file);
if (r.ok || r.signIn || !notHere(r, plan)) return { nav: r, plan };
say(`${pkg} is not in developer account ${known}: looking in every developer account this Google login can see`);
}
const all = (await playAccounts(page, bases.play, quick, stop)).filter(a => a.id !== known);
if (!pkg || all.length <= 1) {
const plan = planFor(all[0]?.id);
const r = await nav(plan);
if (r.ok && pkg && all[0]) rememberPlay(pkg, { developerId: all[0].id, ...(all[0].name ? { account: all[0].name } : {}) }, file);
return { nav: r, plan };
}
say(`this Google login sees ${all.length} developer accounts: looking for ${pkg} in each`);
for (const [i, a] of all.entries()) {
say(`developer account ${i + 1}/${all.length}: ${a.name || a.id}`);
const plan = planFor(a.id), r = await nav(plan, quick);
if (r.ok) { rememberPlay(pkg, { developerId: a.id, ...(a.name ? { account: a.name } : {}) }, file); say(`${pkg} is in ${a.name || a.id} (remembered in ${file})`); }
if (r.ok || r.signIn || !notHere(r, plan)) return { nav: r, plan };
}
const plan = planFor();
return { nav: { ok: false, steps: [], failed: 'the developer account', why: `${pkg} is in none of the ${all.length} developer accounts this Google login can see (${all.map(a => a.name || a.id).join(', ')}). Create the app first, or ask the account owner to invite you` }, plan };
}
// Apple
const plan = navPlan(o.form, config, bases), bundle = config.apple?.bundleId;
if (!plan.length) return { nav: { ok: true, steps: [] }, plan };
const found = async (r: NavResult): Promise<boolean | null> => {
if (!r.ok) return notHere(r, plan) ? false : null;
if (o.form !== 'apple-app-record' || !bundle) return true;
const has = await bundleOffered(page, bundle);
if (has !== false) return true;
const c = await findAny(vis(page.getByRole('dialog')), ['button'], CANCEL);
if (c.state === 'ok') await safeClick(c.loc, await accName(c.loc));
return false;
};
const teams = bundle ? await appleTeams(page, Math.min(quick, 3000), stop).catch(() => null) : null;
if (!teams || teams.length < 2) return { nav: await nav(plan), plan };
const cached = cache.apple[bundle!]?.team, teamId = config.apple?.teamId;
const order = [...new Set([
...(cached && teams.includes(cached) ? [cached] : []),
...(teamId ? teams.filter(t => hasToken(t, teamId)) : []),
...teams,
])];
say(`this Apple Account is in ${teams.length} teams: looking for ${bundle} in each`);
for (const [i, t] of order.entries()) {
say(`team ${i + 1}/${order.length}: ${t}`);
if (!await switchTeam(page, t, teams, quick, stop)) { say(` could not switch to ${t} in the account menu`); continue; }
const r = await nav(plan, quick);
if (r.signIn) return { nav: r, plan };
const f = await found(r);
if (f) { rememberApple(bundle!, { team: t, ...(teamId ? { teamId } : {}) }, file); say(`${bundle} is in team ${t} (remembered in ${file})`); return { nav: r, plan }; }
if (f === null) return { nav: r, plan };
}
return { nav: { ok: false, steps: [], failed: 'the team', why: `${bundle} is in none of the ${teams.length} teams of this Apple Account (${teams.join(', ')}): register the bundle id in the right team (Certificates, Identifiers & Profiles), or set apple.teamId` }, plan };
}

View file

@ -9,8 +9,11 @@
// cookies or storage, and never clicks Save / Submit / Publish / Create / Next: every click goes through safeClick and // cookies or storage, and never clicks Save / Submit / Publish / Create / Next: every click goes through safeClick and
// its gate. After sign-in it opens the form itself (navPlan in cli/lib/console-forms.ts: Apps > + > New App, the app's // its gate. After sign-in it opens the form itself (navPlan in cli/lib/console-forms.ts: Apps > + > New App, the app's
// App Privacy page, Play app list > the app > App content > Start / Manage); those clicks go through navClick, which // App Privacy page, Play app list > the app > App content > Start / Manage); those clicks go through navClick, which
// applies the same gate (only a link named exactly Start / Manage / Başla / Yönet is let through). A step not found in // applies the same gate (only a link named exactly Start / Manage / Başla / Yönet is let through). A sign-in page at
// time -> the printed steps, and storebound waits as before. The owner reviews each page, clicks Next, and presses the // any point (signInPage: URL, frames, texts) -> storebound waits for the owner, then starts again at step 1. A step not
// found in time -> the printed steps, and storebound keeps watching (fillSession). With several Play developer
// accounts or App Store Connect teams behind one login, the account that has the app is found and remembered
// (cli/console/accounts.ts). The owner reviews each page, clicks Next, and presses the
// final button; the command ends when the window is closed. Locators are accessible names only // final button; the command ends when the window is closed. Locators are accessible names only
// (cli/lib/console-forms.ts); a missing or ambiguous field means the UI changed: filling stops and the guidance is // (cli/lib/console-forms.ts); a missing or ambiguous field means the UI changed: filling stops and the guidance is
// printed instead. Not exposed over MCP. // printed instead. Not exposed over MCP.
@ -24,19 +27,21 @@ import { homedir } from 'node:os';
import { join } from 'node:path'; import { join } from 'node:path';
import type { Ctx } from '../lib/ctx'; import type { Ctx } from '../lib/ctx';
import { type Answer, type ConsoleResult, consoleResult, DISCLAIMER, FORM_IDS, type FormId, fillValue, formMeta, isForm, valueText } from '../lib/console-answers'; import { type Answer, type ConsoleResult, consoleResult, DISCLAIMER, FORM_IDS, type FormId, fillValue, formMeta, isForm, valueText } from '../lib/console-answers';
import { consoleReached, type FieldDef, type FormDef, formDef, FORM_OPENERS, forbiddenControl, hasToken, isSignInUrl, type Name, navAllowed, type NavStep, navPlan } from '../lib/console-forms'; import type { ShipConfig } from '../lib/config';
import { consoleReached, 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 { log, printJson, warn } from '../lib/log';
import { openAcross, withAccountIds } from './accounts';
import { type ConsoleBrowser, openConsoleBrowser } from './session'; import { type ConsoleBrowser, openConsoleBrowser } from './session';
/* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/no-explicit-any */
type Page = any; export type Page = any;
type Locator = any; export type Locator = any;
const TAG = 'console'; const TAG = 'console';
const CHECK = 'storebound: check this'; const CHECK = 'storebound: check this';
/** Locators with only the visible matches (hidden earlier pages stay in many consoles' DOM). */ /** Locators with only the visible matches (hidden earlier pages stay in many consoles' DOM). */
const vis = (l: Locator): Locator => { try { return l.filter({ visible: true }); } catch { return l; } }; export const vis = (l: Locator): Locator => { try { return l.filter({ visible: true }); } catch { return l; } };
const nameOpts = (n: Name) => (typeof n === 'string' ? { name: n, exact: true } : { name: n }); const nameOpts = (n: Name) => (typeof n === 'string' ? { name: n, exact: true } : { name: n });
type Found = { state: 'ok'; loc: Locator } | { state: 'none' | 'ambiguous' }; type Found = { state: 'ok'; loc: Locator } | { state: 'none' | 'ambiguous' };
@ -86,7 +91,7 @@ async function resolve(root: Locator, f: FieldDef): Promise<Resolved> {
} }
/** The accessible name of a control as the page labels it (what the click gate checks). */ /** The accessible name of a control as the page labels it (what the click gate checks). */
async function accName(loc: Locator): Promise<string> { export async function accName(loc: Locator): Promise<string> {
return (await loc.evaluate((el: any) => { return (await loc.evaluate((el: any) => {
const by = el.getAttribute('aria-labelledby'); const by = el.getAttribute('aria-labelledby');
const ref = by ? by.split(/\s+/).map((id: string) => el.ownerDocument.getElementById(id)?.textContent ?? '').join(' ') : ''; const ref = by ? by.split(/\s+/).map((id: string) => el.ownerDocument.getElementById(id)?.textContent ?? '').join(' ') : '';
@ -194,18 +199,43 @@ export async function fillPage(page: Page, def: FormDef, answers: Answer[], done
return { section: null, filled: [], highlighted: [], missing: [], fallback: false }; return { section: null, filled: [], highlighted: [], missing: [], fallback: false };
} }
/** A sign-in page: Apple ID / Google accounts hosts, a sign-in frame, or any password field. Read-only check. */ /**
* A sign-in page, read-only: the page or any frame on a sign-in URL (App Store Connect /login, idmsa.apple.com /
* appleid.apple.com, accounts.google.com, Google /signin), a visible password field in any frame, or a visible text,
* label or placeholder only a sign-in form shows (isSignInText: "Sign in with Passkey", "Email or Phone Number" ...).
* Apple's form sits in an idmsa.apple.com frame and starts with no password field, so the URL and texts matter most.
* Only element texts are read (never values, cookies or storage).
*/
export async function signInPage(page: Page): Promise<boolean> { export async function signInPage(page: Page): Promise<boolean> {
if (isSignInUrl(page.url())) return true; if (isSignInUrl(page.url())) return true;
if (page.frames().some((f: any) => isSignInUrl(f.url()))) return true; const frames: any[] = page.frames();
try { return (await page.locator('input[type="password"]').count()) > 0; } catch { return false; } if (frames.some(f => isSignInUrl(f.url()))) return true;
for (const f of frames) {
try {
const r: { pw: boolean; texts: string[] } = await f.evaluate(() => {
const shown = (el: any) => !!(el.getClientRects().length && getComputedStyle(el).visibility !== 'hidden');
const pw = [...document.querySelectorAll('input[type="password"]')].some(shown);
const texts: string[] = [];
for (const el of document.querySelectorAll('label, button, a, h1, h2, h3, legend, span, p, div, [role="button"], input, [aria-label]')) {
if (texts.length > 3000) break;
const e = el as any;
for (const t of [e.getAttribute('aria-label'), e.getAttribute('placeholder'), e.children.length ? null : e.textContent, e.tagName === 'LABEL' ? e.textContent : null]) {
if (t && t.length <= 80 && shown(e)) texts.push(t);
}
}
return { pw, texts };
});
if (r.pw || r.texts.some(t => isSignInText(t, f !== page.mainFrame()))) return true;
} catch { /* a frame that navigates or went away */ }
}
return false;
} }
// ---- navigation to the form (after sign-in) ---- // ---- navigation to the form (after sign-in) ----
/** The ARIA role the element really has (explicit role, else the implicit one for links, buttons and rows). */ /** The ARIA role the element really has (explicit role, else the implicit one for links, buttons and rows). */
async function realRole(loc: Locator): Promise<string> { export async function realRole(loc: Locator): Promise<string> {
return loc.evaluate((el: any) => el.getAttribute('role') || (el.tagName === 'A' && el.hasAttribute('href') ? 'link' : el.tagName === 'BUTTON' ? 'button' : el.tagName === 'TR' ? 'row' : el.tagName.toLowerCase())); return loc.evaluate((el: any) => el.getAttribute('role') || (el.tagName === 'A' && el.hasAttribute('href') ? 'link' : el.tagName === 'BUTTON' ? 'button' : el.tagName === 'TR' ? 'row' : el.tagName.toLowerCase()));
} }
@ -230,17 +260,29 @@ export interface NavResult {
why?: string; why?: string;
/** pickApp: the matching apps when more than one matched (storebound stops and lists them). */ /** pickApp: the matching apps when more than one matched (storebound stops and lists them). */
candidates?: string[]; candidates?: string[];
/** A sign-in page appeared: wait for the owner, then start again at step 1. */
signIn?: boolean;
} }
async function findAny(root: Locator, roles: string[], names: Name[]): Promise<Found> { export async function findAny(root: Locator, roles: string[], names: Name[]): Promise<Found> {
for (const role of roles) { const f = await find(root, role, names); if (f.state !== 'none') return f; } for (const role of roles) { const f = await find(root, role, names); if (f.state !== 'none') return f; }
return { state: 'none' }; return { state: 'none' };
} }
/** Polls `fn` until it returns a value or the time is up (errors while the page navigates count as "not yet"). */ /** Thrown by poll when a sign-in page shows up while a navigation step waits (navigate turns it into `signIn`). */
async function poll<T>(ms: number, fn: () => Promise<T | null>): Promise<T | null> { export class SignInSeen extends Error {}
/** A check run on every poll round: true -> a sign-in page is showing. */
export type Stop = () => Promise<boolean>;
/**
* Polls `fn` until it returns a value or the time is up (errors while the page navigates count as "not yet"). `stop`
* is checked first on every round: a sign-in page ends the wait at once (SignInSeen).
*/
export async function poll<T>(ms: number, fn: () => Promise<T | null>, stop?: Stop): Promise<T | null> {
const end = Date.now() + ms; const end = Date.now() + ms;
for (;;) { for (;;) {
if (stop && await stop().catch(() => false)) throw new SignInSeen();
try { const r = await fn(); if (r !== null) return r; } catch { /* navigating */ } try { const r = await fn(); if (r !== null) return r; } catch { /* navigating */ }
if (Date.now() >= end) return null; if (Date.now() >= end) return null;
await Bun.sleep(200); await Bun.sleep(200);
@ -249,9 +291,9 @@ async function poll<T>(ms: number, fn: () => Promise<T | null>): Promise<T | nul
const opener = new RegExp(`^(?:${FORM_OPENERS.join('|')})$`); const opener = new RegExp(`^(?:${FORM_OPENERS.join('|')})$`);
async function pickApp(page: Page, s: Extract<NavStep, { kind: 'pickApp' }>, ms: number): Promise<{ loc?: Locator; candidates?: string[] } | null> { export async function pickApp(page: Page, s: Extract<NavStep, { kind: 'pickApp' }>, ms: number, stop?: Stop): Promise<{ loc?: Locator; candidates?: string[] } | null> {
if (s.search && s.tokens[0]) { if (s.search && s.tokens[0]) {
const box = await poll(Math.min(ms, 3000), async () => { const f = await findAny(page, ['searchbox', 'textbox', 'combobox'], s.search!); return f.state === 'ok' ? f.loc : null; }); const box = await poll(Math.min(ms, 3000), async () => { const f = await findAny(page, ['searchbox', 'textbox', 'combobox'], s.search!); return f.state === 'ok' ? f.loc : null; }, stop);
if (box) { await box.fill(s.tokens[0]); } if (box) { await box.fill(s.tokens[0]); }
} }
return poll(ms, async () => { return poll(ms, async () => {
@ -261,7 +303,9 @@ async function pickApp(page: Page, s: Extract<NavStep, { kind: 'pickApp' }>, ms:
const hits: { loc: Locator; name: string }[] = []; const hits: { loc: Locator; name: string }[] = [];
for (let i = 0; i < n; i++) { for (let i = 0; i < n; i++) {
const loc = all.nth(i), name = await accName(loc); const loc = all.nth(i), name = await accName(loc);
const byToken = s.tokens.some(t => hasToken(name, t)); // 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; const byName = role === 'link' && s.name !== undefined && name === s.name;
if (byToken || byName) hits.push({ loc, name }); if (byToken || byName) hits.push({ loc, name });
} }
@ -273,10 +317,10 @@ async function pickApp(page: Page, s: Extract<NavStep, { kind: 'pickApp' }>, ms:
if (hits.length > 1) return { candidates: hits.map(h => h.name) }; if (hits.length > 1) return { candidates: hits.map(h => h.name) };
} }
return null; return null;
}); }, stop);
} }
async function formLink(page: Page, entry: Name[], ms: number): Promise<{ loc?: Locator; ambiguous?: boolean } | null> { async function formLink(page: Page, entry: Name[], ms: number, stop?: Stop): Promise<{ loc?: Locator; ambiguous?: boolean } | null> {
return poll(ms, async () => { return poll(ms, async () => {
const found: { loc: Locator; key: string }[] = []; const found: { loc: Locator; key: string }[] = [];
const add = async (box: Locator) => { const add = async (box: Locator) => {
@ -300,7 +344,7 @@ async function formLink(page: Page, entry: Name[], ms: number): Promise<{ loc?:
} }
if (found.length === 1) return { loc: found[0]!.loc }; if (found.length === 1) return { loc: found[0]!.loc };
return found.length > 1 ? { ambiguous: true } : null; return found.length > 1 ? { ambiguous: true } : null;
}); }, stop);
} }
/** The wait target is on the page (a heading of `level` when given). */ /** The wait target is on the page (a heading of `level` when given). */
@ -310,12 +354,25 @@ async function present(page: Page, s: Extract<NavStep, { kind: 'wait' }>): Promi
return false; return false;
} }
export interface NavOpts {
timeoutMs?: number;
say?: (m: string) => void;
/** Start at this step (0-based; resumeAt picks it after the owner moved on by hand). */
from?: number;
/** The sign-in check (default signInPage), run before every step, after each step's click or load, and on every poll round. */
signIn?: (page: Page) => Promise<boolean>;
}
/** /**
* Opens the form step by step (navPlan). Logs every step; stops at the first step that is not found within * Opens the form step by step (navPlan). Logs every step; stops at the first step that is not found within
* `timeoutMs`, is ambiguous, or is refused by the click gate, and says which. Never throws for a missing step. * `timeoutMs`, is ambiguous, or is refused by the click gate, and says which. A sign-in page at any point (before a
* step, after its click or load, or while it waits) stops at once with `signIn: true`: the caller waits for the owner
* to sign in and starts again at step 1. Never throws for a missing step.
*/ */
export async function navigate(page: Page, plan: NavStep[], opts: { timeoutMs?: number; say?: (m: string) => void } = {}): Promise<NavResult> { export async function navigate(page: Page, plan: NavStep[], opts: NavOpts = {}): Promise<NavResult> {
const ms = opts.timeoutMs ?? 20_000, say = opts.say ?? ((m: string) => log(TAG, m)); const ms = opts.timeoutMs ?? 20_000, say = opts.say ?? ((m: string) => log(TAG, m));
const isSignIn = opts.signIn ?? signInPage;
const stop: Stop = () => isSignIn(page).catch(() => false);
const steps: string[] = []; const steps: string[] = [];
const target = plan.at(-1); const target = plan.at(-1);
if (target?.kind === 'wait' && await present(page, target).catch(() => false)) { if (target?.kind === 'wait' && await present(page, target).catch(() => false)) {
@ -323,39 +380,68 @@ export async function navigate(page: Page, plan: NavStep[], opts: { timeoutMs?:
return { ok: true, steps: ['already open'] }; return { ok: true, steps: ['already open'] };
} }
const fail = (s: NavStep, why: string, candidates?: string[]): NavResult => ({ ok: false, steps, failed: s.label, why, ...(candidates ? { candidates } : {}) }); const fail = (s: NavStep, why: string, candidates?: string[]): NavResult => ({ ok: false, steps, failed: s.label, why, ...(candidates ? { candidates } : {}) });
for (const [i, s] of plan.entries()) { const signedOut = (s: NavStep): NavResult => ({ ok: false, steps, failed: s.label, why: 'a sign-in page appeared', signIn: true });
for (let i = Math.max(0, opts.from ?? 0); i < plan.length; i++) {
const s = plan[i]!;
if (await stop()) return signedOut(s);
say(`opening the form, step ${i + 1}/${plan.length}: ${s.label}`); say(`opening the form, step ${i + 1}/${plan.length}: ${s.label}`);
if (s.kind === 'goto') { try {
try { await page.goto(s.url, { waitUntil: 'domcontentloaded' }); } catch (e) { return fail(s, `could not load ${s.url} (${(e as Error).message.split('\n')[0]})`); } if (s.kind === 'goto') {
} else if (s.kind === 'click') { try { await page.goto(s.url, { waitUntil: 'domcontentloaded' }); } catch (e) { return fail(s, `could not load ${s.url} (${(e as Error).message.split('\n')[0]})`); }
if (s.optional && s.unless && (await findAny(page, s.unless.roles, s.unless.names)).state !== 'none') { say(' (not needed)'); continue; } } else if (s.kind === 'click') {
const f = await poll(s.optional ? Math.min(ms, 2000) : ms, async () => { const r = await findAny(page, s.roles, s.names); return r.state === 'none' ? null : r; }); if (s.optional && s.unless && (await findAny(page, s.unless.roles, s.unless.names)).state !== 'none') { say(' (not needed)'); continue; }
if (!f) { if (s.optional) { say(' (not on this page, skipped)'); continue; } return fail(s, 'not found'); } const f = await poll(s.optional ? Math.min(ms, 2000) : ms, async () => { const r = await findAny(page, s.roles, s.names); return r.state === 'none' ? null : r; }, stop);
if (f.state !== 'ok') return fail(s, 'more than one match'); if (!f) { if (s.optional) { say(' (not on this page, skipped)'); continue; } return fail(s, 'not found'); }
const c = await navClick(f.loc); if (f.state !== 'ok') return fail(s, 'more than one match');
if (!c.clicked) return fail(s, `refused to click "${c.name}"`); const c = await navClick(f.loc);
} else if (s.kind === 'pickApp') { if (!c.clicked) return fail(s, `refused to click "${c.name}"`);
if (!s.tokens.length && !s.name) return fail(s, 'no bundle id, package name or app name in the config'); } else if (s.kind === 'pickApp') {
const r = await pickApp(page, s, ms); if (!s.tokens.length && !s.name) return fail(s, 'no bundle id, package name or app name in the config');
if (!r) return fail(s, `no app matching ${[...s.tokens, ...(s.name ? [`"${s.name}"`] : [])].join(' / ')} in the list`); const r = await pickApp(page, s, ms, stop);
if (r.candidates) return fail(s, 'more than one app matches', r.candidates); if (!r) return fail(s, `no app matching ${[...s.tokens, ...(s.name ? [`"${s.name}"`] : [])].join(' / ')} in the list`);
const c = await navClick(r.loc); if (r.candidates) return fail(s, 'more than one app matches', r.candidates);
if (!c.clicked) return fail(s, `refused to click "${c.name}"`); const c = await navClick(r.loc);
} else if (s.kind === 'formLink') { if (!c.clicked) return fail(s, `refused to click "${c.name}"`);
const r = await formLink(page, s.entry, ms); } else if (s.kind === 'formLink') {
if (!r) return fail(s, 'no Start or Manage link next to it'); const r = await formLink(page, s.entry, ms, stop);
if (r.ambiguous) return fail(s, 'more than one Start or Manage link matches'); if (!r) return fail(s, 'no Start or Manage link next to it');
const c = await navClick(r.loc); if (r.ambiguous) return fail(s, 'more than one Start or Manage link matches');
if (!c.clicked) return fail(s, `refused to click "${c.name}"`); const c = await navClick(r.loc);
} else { if (!c.clicked) return fail(s, `refused to click "${c.name}"`);
const f = await poll(ms, async () => ((await present(page, s)) ? true : null)); } else {
if (!f) return fail(s, 'did not appear'); const f = await poll(ms, async () => ((await present(page, s)) ? true : null), stop);
if (!f) return fail(s, 'did not appear');
}
} catch (e) {
if (e instanceof SignInSeen) return signedOut(s);
throw e;
} }
if (s.kind !== 'wait' && await stop()) return signedOut(s);
steps.push(s.label); steps.push(s.label);
} }
return { ok: true, steps }; return { ok: true, steps };
} }
/**
* Where navigation can pick up on the page as it is now (the owner moved on by hand): the furthest step whose target is
* visible (the form itself, the New App menu item, the + button, the app in the list ...), 0-based, or null. Never
* the initial page load (a `goto`): storebound does not take the owner away from where they are. Read-only.
*/
export async function resumeAt(page: Page, plan: NavStep[]): Promise<number | null> {
for (let i = plan.length - 1; i >= 0; i--) {
const s = plan[i]!;
try {
if (s.kind === 'wait') { if (await present(page, s)) return i; }
else if (s.kind === 'click') { if ((await findAny(page, s.roles, s.names)).state === 'ok') return i; }
else if (s.kind === 'pickApp') {
const { search: _search, ...look } = s; // look only: never types into the search box here
if ((await pickApp(page, look, 0))?.loc) return i;
} else if (s.kind === 'formLink') { if ((await formLink(page, s.entry, 0))?.loc) return i; }
} catch { /* navigating */ }
}
return null;
}
function printText(res: ConsoleResult): void { function printText(res: ConsoleResult): void {
console.log(`${res.title}\n${res.url}\n`); console.log(`${res.title}\n${res.url}\n`);
for (const a of res.answers) console.log(` ${a.certain ? '[ok] ' : '[check]'} ${a.label}: ${valueText(a)} (${a.source})${a.certain || !a.note ? '' : `\n ${a.note}`}`); for (const a of res.answers) console.log(` ${a.certain ? '[ok] ' : '[check]'} ${a.label}: ${valueText(a)} (${a.source})${a.certain || !a.note ? '' : `\n ${a.note}`}`);
@ -374,7 +460,6 @@ export async function run(ctx: Ctx): Promise<void> {
return; return;
} }
if (!isForm(form)) throw new Error(`console fill: unknown form "${form}" (one of ${FORM_IDS.join(', ')})`); if (!isForm(form)) throw new Error(`console fill: unknown form "${form}" (one of ${FORM_IDS.join(', ')})`);
const fid: FormId = form;
const meta = formMeta(form, config); const meta = formMeta(form, config);
const store = args.get('store'); const store = args.get('store');
if (store && store !== 'apple' && store !== 'play') throw new Error('--store: apple | play'); if (store && store !== 'apple' && store !== 'play') throw new Error('--store: apple | play');
@ -395,49 +480,160 @@ export async function run(ctx: Ctx): Promise<void> {
store: meta.store, profileDir: dir, say, fresh: args.has('fresh-profile') || ownProfile, store: meta.store, profileDir: dir, say, fresh: args.has('fresh-profile') || ownProfile,
...(args.get('cdp') ? { cdp: args.get('cdp') } : {}), ...(args.get('chrome-profile') ? { chromeProfile: args.get('chrome-profile') } : {}), ...(args.get('cdp') ? { cdp: args.get('cdp') } : {}), ...(args.get('chrome-profile') ? { chromeProfile: args.get('chrome-profile') } : {}),
}); });
// the temporary profile of copy mode goes away on every exit path // Ctrl+C: close the browser gracefully (Chromium writes its cookies on a clean exit, so the sign-in is kept for the
const bye = () => { b.cleanup(); process.exit(130); }; // next run), then remove the temporary profile of copy mode; that also happens on every other exit path
process.once('SIGINT', bye); process.once('SIGTERM', bye); let stopping = false;
try { await fillRun(b); } finally { b.cleanup(); process.off('SIGINT', bye); process.off('SIGTERM', bye); } 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 } : {}) });
if (json) printJson({ ...res, ...out, stoppedAt: meta.stopBefore, browser: b.mode });
} finally { b.cleanup(); process.off('SIGINT', bye); process.off('SIGTERM', bye); }
}
async function fillRun(b: ConsoleBrowser): Promise<void> { export interface FillSessionOpts {
form: FormId;
config: ShipConfig;
say: (m: string) => void;
/** Tests only: a local page instead of the console (no navigation plan). */
startUrl?: string;
/** Tests only: the navigation plan's URL bases (127.0.0.1 or routed fixtures). */
bases?: NavBases;
/** Timings (tests shorten them): one watch round, the wait for each navigation step, the wait for sign-in. */
tickMs?: number;
navTimeoutMs?: number;
signInWaitMs?: number;
/** Tests only: the account cache file (default ~/.storebound/console-accounts.json) and the env ids are read from. */
accountsFile?: string;
env?: Record<string, string | undefined>;
}
/**
* One fill run in an open browser, until the owner closes the window:
* 1. sign-in: while a sign-in page shows (signInPage), the owner signs in and storebound waits (up to 10 minutes; it
* never types or reads anything there). Signed in = the console URL, no sign-in page, for two rounds in a row.
* 2. opens the form (navigate). A sign-in page during navigation -> wait for sign-in again, then from step 1.
* 3. a step not found -> the printed steps, and storebound keeps watching: a sign-in page that goes away -> from step
* 1; the owner moving on by hand (the + button, the New App menu item, the app in the list appear) -> from that step
* (resumeAt); the owner opening the form -> it is filled.
* 4. fills section by section as the owner moves through the form; never saves, submits or publishes.
*/
export async function fillSession(b: ConsoleBrowser, o: FillSessionOpts): Promise<{ filled: number; highlighted: number; fallback: boolean }> {
const { form, config, say, startUrl } = o;
const tick = o.tickMs ?? 1000, navMs = o.navTimeoutMs ?? 20_000, signInMs = o.signInWaitMs ?? 10 * 60_000;
const meta = formMeta(form, config), res = consoleResult(form, config);
const active = (): Page | undefined => b.pages().at(-1); const active = (): Page | undefined => b.pages().at(-1);
const page = b.page; const isSignIn = (p: Page) => signInPage(p).catch(() => false);
await page.goto(startUrl ?? meta.url).catch(() => { /* the owner can navigate */ }); const reached = (p: Page) => consoleReached(meta.store, p.url(), startUrl);
let hinted = false;
const signInHint = () => {
say('sign in in the browser window; storebound waits (up to 10 minutes) and never types or reads anything on the sign-in page');
if (hinted) return;
hinted = true;
say(meta.store === 'apple'
? 'tick "Keep me signed in" and choose "Trust" for this browser, so the next run starts signed in'
: 'leave "Stay signed in" on, so the next run starts signed in');
};
// 1. sign-in: the owner does it; storebound only watches the URL /** Waits until the console is open and no sign-in page shows (two rounds in a row). false: window closed or time up. */
const deadline = Date.now() + 10 * 60_000; async function signedIn(): Promise<boolean> {
let told = false; const end = Date.now() + signInMs;
while (!b.isClosed() && Date.now() < deadline) { let told = false, ok = 0;
const p = active(); while (!b.isClosed() && Date.now() < end) {
if (p && !(await signInPage(p).catch(() => false)) && consoleReached(meta.store, p.url(), startUrl)) break; const p = active();
if (p && !told && await signInPage(p).catch(() => false)) { say('sign in in the browser window, storebound waits'); told = true; } if (p && await isSignIn(p)) { ok = 0; if (!told) { signInHint(); told = true; } }
await Bun.sleep(1000); else if (p && reached(p)) { if (++ok >= 2) { if (told) say('signed in'); return true; } }
else ok = 0;
await Bun.sleep(tick);
}
return false;
} }
// 2. fill section by section as the owner moves through the form let plan = startUrl ? [] : navPlan(form, withAccountIds(config, o.env), o.bases);
const def = formDef(fid, res.answers); const broken = (e: Error): NavResult => ({ ok: false, steps: [], failed: 'navigation', why: e.message.split('\n')[0] });
const pageAnswers = res.answers.map(a => ({ ...a, value: fillValue(fid, a, config) })); /**
* From step 1 in the account that has the app (openAcross: the remembered / configured developer account or team,
* else every one the login can see), or from `from` in the account that is open. A sign-in page -> wait for sign-in,
* then again from step 1 (at most 5 times).
*/
async function openForm(from: number): Promise<NavResult> {
let r: NavResult = { ok: false, steps: [], failed: 'navigation', why: 'the window was closed' };
for (let n = 0; n < 5 && !b.isClosed(); n++) {
const p = active() ?? b.page;
if (from === 0) {
const a = await openAcross(p, { form, config, say, navMs, ...(o.bases ? { bases: o.bases } : {}), ...(o.accountsFile ? { file: o.accountsFile } : {}), ...(o.env ? { env: o.env } : {}) })
.catch((e: Error) => ({ nav: broken(e), plan }));
r = a.nav; if (a.plan.length) plan = a.plan;
} else r = await navigate(p, plan, { say, from, timeoutMs: navMs }).catch(broken);
if (!r.signIn) return r;
say(`a sign-in page appeared at step "${r.failed}"`);
if (!await signedIn()) return r;
say('signed in: opening the form again from step 1');
from = 0;
}
return r;
}
let tried = '';
const report = (r: NavResult, first: boolean) => {
if (r.ok) { if (meta.then) say(`now click ${meta.then} yourself; storebound fills the form when it appears`); return; }
if (r.signIn) return;
// refused / ambiguous: not retried on this page; "not found" / "did not appear" is retried when the step shows up
if (!/^(not found|did not appear)$/.test(r.why ?? '')) tried = `${(active() ?? b.page).url()}#${plan.findIndex(s => s.label === r.failed)}`;
warn(TAG, `could not open the form by itself at step "${r.failed}" (${r.why}). Open it yourself; storebound keeps watching and fills it when it appears:`);
if (r.candidates) say(`apps that match: ${r.candidates.join(' | ')} (set apple.appId / play.packageName in the config to pick one)`);
if (first) for (const s of meta.open) say(`open the form: ${s}`);
};
await b.page.goto(startUrl ?? meta.url).catch(() => { /* the owner can navigate */ });
await signedIn();
const def = formDef(form, res.answers);
const pageAnswers = res.answers.map(a => ({ ...a, value: fillValue(form, a, config) }));
const labels = new Map(res.answers.map(a => [a.id, a.label])); const labels = new Map(res.answers.map(a => [a.id, a.label]));
const done = new Set<number>(); const done = new Set<number>();
let filled = 0, highlighted = 0, fallback = false; let filled = 0, highlighted = 0, fallback = false;
// 2a. open the form: navigation clicks only (navClick); on any miss, the printed steps and wait as before let nav: NavResult | null = plan.length && !b.isClosed() ? await openForm(0) : null;
const plan = startUrl || b.isClosed() ? [] : navPlan(fid, config); if (nav) report(nav, true);
const nav = plan.length ? await navigate(active() ?? page, plan, { say }).catch((e: Error): NavResult => ({ ok: false, steps: [], failed: 'navigation', why: e.message.split('\n')[0] })) : null; else for (const s of meta.open) say(`open the form: ${s}`);
if (nav && !nav.ok) {
warn(TAG, `could not open the form by itself at step "${nav.failed}" (${nav.why}). Open it yourself; storebound waits and fills it when it appears:`);
if (nav.candidates) say(`apps that match: ${nav.candidates.join(' | ')} (set apple.appId / play.packageName in the config to pick one)`);
}
if (!nav?.ok) for (const o of meta.open) say(`open the form: ${o}`);
else if (meta.then) say(`now click ${meta.then} yourself; storebound fills the form when it appears`);
const last = def.sections.length - 1; const last = def.sections.length - 1;
const finished = () => done.size === def.sections.length || (form !== 'apple-app-privacy' && done.has(last)); const finished = () => done.size === def.sections.length || (form !== 'apple-app-privacy' && done.has(last));
let signedOut = false, misses = 0, firstMiss = 0;
while (!b.isClosed() && !finished()) { while (!b.isClosed() && !finished()) {
const p = active(); const p = active();
if (!p || await signInPage(p).catch(() => true)) { await Bun.sleep(1500); continue; } if (!p) { await Bun.sleep(tick); continue; }
if (await signInPage(p).catch(() => true)) {
if (!signedOut && plan.length) signInHint();
signedOut = true;
await Bun.sleep(tick); continue;
}
// sign-in finished while watching: open the form again from step 1 (nothing filled yet)
if (signedOut) {
signedOut = false;
if (plan.length && !done.size && !nav?.ok && await signedIn()) {
say('signed in: opening the form again from step 1');
tried = ''; nav = await openForm(0); report(nav, false);
}
continue;
}
// after the printed steps: keep watching; when the owner moved on (or the page finished loading), pick up there
if (plan.length && nav && !nav.ok && !done.size) {
const at = await resumeAt(p, plan);
const key = `${p.url()}#${at}`;
if (at !== null && key !== tried) {
tried = key;
say(`the page changed: storebound opens the form from step ${at + 1}/${plan.length}`);
nav = await openForm(at); report(nav, false);
if (nav.ok) say('the form is open');
continue;
}
}
let s: FillStep; let s: FillStep;
try { s = await fillPage(p, def, pageAnswers, done); } catch { await Bun.sleep(1500); continue; } // navigating try { s = await fillPage(p, def, pageAnswers, done); } catch { await Bun.sleep(tick); continue; } // navigating
if (s.section !== null) { if (s.section !== null) {
// a page still loading can miss a field for a moment: only a miss that lasts (3 rounds, at least 1.5 s) is a UI change
if (s.fallback && (++misses < 3 || Date.now() - firstMiss < 1500)) { if (misses === 1) firstMiss = Date.now(); await Bun.sleep(tick); continue; }
misses = 0;
if (s.fallback) { if (s.fallback) {
fallback = true; fallback = true;
warn(TAG, `the page does not match what storebound expects (${s.missing.join(', ')}): the console UI changed. Nothing more is filled; follow these steps:`); warn(TAG, `the page does not match what storebound expects (${s.missing.join(', ')}): the console UI changed. Nothing more is filled; follow these steps:`);
@ -448,11 +644,10 @@ export async function run(ctx: Ctx): Promise<void> {
say(`${s.title}: filled ${s.filled.length}, check ${s.highlighted.length}${s.highlighted.length ? `: ${s.highlighted.map(id => labels.get(id) ?? id).join('; ')}` : ''}`); say(`${s.title}: filled ${s.filled.length}, check ${s.highlighted.length}${s.highlighted.length ? `: ${s.highlighted.map(id => labels.get(id) ?? id).join('; ')}` : ''}`);
if (!finished()) say('review this page, then click Next (or open the next part) yourself; storebound fills it when it appears'); if (!finished()) say('review this page, then click Next (or open the next part) yourself; storebound fills it when it appears');
} }
await Bun.sleep(1500); await Bun.sleep(tick);
} }
if (!b.isClosed() && !fallback) say(`review every field and press ${meta.stopBefore} yourself. storebound never saves, submits or publishes. Close the window when done.`); if (!b.isClosed() && !fallback) say(`review every field and press ${meta.stopBefore} yourself. storebound never saves, submits or publishes. Close the window when done.`);
else if (!b.isClosed()) say('close the browser window when done'); else if (!b.isClosed()) say('close the browser window when done');
await b.closed; await b.closed;
if (json) printJson({ ...res, filled, highlighted, fallback, stoppedAt: meta.stopBefore, browser: b.mode }); return { filled, highlighted, fallback };
}
} }

View file

@ -11,6 +11,16 @@
// default: the last used one. `--fresh-profile` skips (a) and (b). // default: the last used one. `--fresh-profile` skips (a) and (b).
// (c) storebound's own persistent profile (~/.storebound/console-profile/<store>): the owner signs in there once. // (c) storebound's own persistent profile (~/.storebound/console-profile/<store>): the owner signs in there once.
// Cookies are never printed, logged or sent anywhere: only file names and counts are reported. // Cookies are never printed, logged or sent anywhere: only file names and counts are reported.
// Keeping the sign-in (b, c): App Store Connect's and Google's sign-in cookies are partly SESSION cookies (no expiry).
// Chromium writes them to its Cookies file but deletes them at the next start unless that start restores the last
// session, so storebound launches with --restore-last-session (the tabs it brings back are closed again; storebound
// works in one new tab) and always closes the browser gracefully (window closed, Ctrl+C), never kills it, so Chromium
// flushes its cookie store. Apple keeps a long sign-in only with "Keep me signed in" / "Trust this browser" ticked
// (storebound says so when it sees the sign-in page). Copy mode: the owner's Chrome Cookies file holds the session
// cookies only while that Chrome runs, or after it quit with "On startup: Continue where you left off" on (a normal
// Chrome start without it deletes them); otherwise the owner signs in once in the window storebound opens.
// The session.restore_on_startup preference is not written: it is a tracked (MAC-protected) Chrome preference, and an
// edit from outside can be reset by Chrome; the switch does the same for this launch only.
// Sources (checked October 2026): Chrome user data dir and DevToolsActivePort // Sources (checked October 2026): Chrome user data dir and DevToolsActivePort
// https://chromium.googlesource.com/chromium/src/+/main/docs/user_data_dir.md ; Chrome 136 remote debugging change // https://chromium.googlesource.com/chromium/src/+/main/docs/user_data_dir.md ; Chrome 136 remote debugging change
// https://developer.chrome.com/blog/remote-debugging-port ; Playwright connectOverCDP / ignoreDefaultArgs // https://developer.chrome.com/blog/remote-debugging-port ; Playwright connectOverCDP / ignoreDefaultArgs
@ -135,6 +145,8 @@ export interface ConsoleBrowser {
/** Resolves when the owner closed the window (copy / profile) or storebound's tab (attach). */ /** Resolves when the owner closed the window (copy / profile) or storebound's tab (attach). */
closed: Promise<void>; closed: Promise<void>;
isClosed: () => boolean; isClosed: () => boolean;
/** Closes gracefully (cookies flushed): the whole browser (copy / profile) or storebound's tab (attach). Max 10 s. */
close: () => Promise<void>;
/** Removes the temporary profile (copy mode); safe to call twice. */ /** Removes the temporary profile (copy mode); safe to call twice. */
cleanup: () => void; cleanup: () => void;
/** Copy mode: the temporary profile (deleted by cleanup and when the window closes). */ /** Copy mode: the temporary profile (deleted by cleanup and when the window closes). */
@ -168,7 +180,26 @@ function wrapContext(mode: BrowserMode, context: any, page: any, cleanup: () =>
cleanup(); cleanup();
r(); r();
})); }));
return { mode, context, page, pages: () => context.pages(), closed: done, isClosed: () => closed, cleanup }; return { mode, context, page, pages: () => context.pages(), closed: done, isClosed: () => closed, close: () => gracefully(() => context.close()), cleanup };
}
/** Runs a graceful close, at most `ms`; errors (already closed) are ignored. */
async function gracefully(fn: () => Promise<unknown>, ms = 10_000): Promise<void> {
await Promise.race([Promise.resolve().then(fn).catch(() => { /* already closed */ }), Bun.sleep(ms)]);
}
/**
* Launch switches of the copy and profile modes: bring back the last session's cookies (session cookies included,
* see the header). The restored tabs are closed again by ownTab.
*/
export const KEEP_SESSION_ARGS = ['--restore-last-session'];
/** One new tab for storebound; the tabs the session restore brought back are closed (they would compete for "the active tab"). */
async function ownTab(context: any): Promise<any> {
const restored: any[] = context.pages();
const page = await context.newPage();
for (const p of restored) await p.close().catch(() => { /* gone */ });
return page;
} }
/** Opens the browser in the first mode that works: attach, copy, then storebound's own profile. */ /** Opens the browser in the first mode that works: attach, copy, then storebound's own profile. */
@ -189,7 +220,7 @@ export async function openConsoleBrowser(root: string, o: OpenOpts): Promise<Con
let closed = false; let closed = false;
const done = new Promise<void>(r => page.on('close', () => { closed = true; r(); })); const done = new Promise<void>(r => page.on('close', () => { closed = true; r(); }));
o.say('browser: attached to your running Chrome (remote debugging); storebound works in one new tab and closes only that tab'); o.say('browser: attached to your running Chrome (remote debugging); storebound works in one new tab and closes only that tab');
return { mode: 'attach', context, page, pages: () => [...own].filter(p => !p.isClosed()), closed: done, isClosed: () => closed, cleanup: () => { /* nothing copied */ } }; return { mode: 'attach', context, page, pages: () => [...own].filter(p => !p.isClosed()), closed: done, isClosed: () => closed, close: () => gracefully(() => page.close()), cleanup: () => { /* nothing copied */ } };
} catch (e) { } catch (e) {
if (o.cdp) throw new Error(`--cdp: could not attach to ${o.cdp} (${(e as Error).message.split('\n')[0]})`); if (o.cdp) throw new Error(`--cdp: could not attach to ${o.cdp} (${(e as Error).message.split('\n')[0]})`);
o.say('browser: Chrome has a DevTools port file but storebound could not attach; trying your Chrome sign-in instead'); o.say('browser: Chrome has a DevTools port file but storebound could not attach; trying your Chrome sign-in instead');
@ -202,14 +233,14 @@ export async function openConsoleBrowser(root: string, o: OpenOpts): Promise<Con
copy = await copySession(chromeDir, { ...(o.chromeProfile ? { profile: o.chromeProfile } : {}), ...(o.hosts ? { hosts: o.hosts } : {}) }); copy = await copySession(chromeDir, { ...(o.chromeProfile ? { profile: o.chromeProfile } : {}), ...(o.hosts ? { hosts: o.hosts } : {}) });
const c = await chromiumFor(root); const c = await chromiumFor(root);
const context = await c.launchPersistentContext(copy.dir, { const context = await c.launchPersistentContext(copy.dir, {
channel: 'chrome', headless: o.headless ?? false, viewport: null, channel: 'chrome', headless: o.headless ?? false, viewport: null, args: KEEP_SESSION_ARGS,
// Playwright's mock keychain would hide Chrome's own key, and the cookies could not be read // Playwright's mock keychain would hide Chrome's own key, and the cookies could not be read
ignoreDefaultArgs: ['--use-mock-keychain', '--password-store=basic'], ignoreDefaultArgs: ['--use-mock-keychain', '--password-store=basic'],
}); });
o.say(`browser: your Chrome sign-in (profile "${copy.profile}"). storebound copied only ${copy.files.join(', ')} into a temporary profile` o.say(`browser: your Chrome sign-in (profile "${copy.profile}"). storebound copied only ${copy.files.join(', ')} into a temporary profile`
+ `${copy.filtered ? `, kept only the cookies for App Store Connect and Play Console (${copy.kept ?? 0})` : ' (the whole cookie file: it could not be filtered)'}` + `${copy.filtered ? `, kept only the cookies for App Store Connect and Play Console (${copy.kept ?? 0})` : ' (the whole cookie file: it could not be filtered)'}`
+ ', and deletes it when this run ends. Passwords, history and extensions are never copied. macOS may ask once to let Google Chrome use "Chrome Safe Storage" in your Keychain: that is Chrome reading its own cookies. Opt out: --fresh-profile'); + ', and deletes it when this run ends. Passwords, history and extensions are never copied. macOS may ask once to let Google Chrome use "Chrome Safe Storage" in your Keychain: that is Chrome reading its own cookies. Opt out: --fresh-profile');
const page = context.pages()[0] ?? await context.newPage(); const page = await ownTab(context);
const cp = copy; const cp = copy;
return { ...wrapContext('copy', context, page, () => cp.cleanup()), tempDir: cp.dir }; return { ...wrapContext('copy', context, page, () => cp.cleanup()), tempDir: cp.dir };
} catch (e) { } catch (e) {
@ -220,8 +251,8 @@ export async function openConsoleBrowser(root: string, o: OpenOpts): Promise<Con
} }
// (c) storebound's persistent profile, the owner signs in there // (c) storebound's persistent profile, the owner signs in there
mkdirSync(o.profileDir, { recursive: true }); mkdirSync(o.profileDir, { recursive: true });
const context = await launchPersistent(root, o.profileDir, { headless: o.headless ?? false, viewport: null }); const context = await launchPersistent(root, o.profileDir, { headless: o.headless ?? false, viewport: null, args: KEEP_SESSION_ARGS });
o.say(`browser: storebound's own profile (${o.profileDir}); sign in there once, it is kept for the next run`); o.say(`browser: storebound's own profile (${o.profileDir}); sign in there once, it is kept for the next run`);
const page = context.pages()[0] ?? await context.newPage(); const page = await ownTab(context);
return wrapContext('profile', context, page, () => { /* kept on purpose */ }); return wrapContext('profile', context, page, () => { /* kept on purpose */ });
} }

View file

@ -468,6 +468,10 @@ export interface ShipConfig {
languages: Language[]; languages: Language[];
play?: { play?: {
packageName: string; defaultLanguage?: string; listing?: string; icon?: string; packageName: string; defaultLanguage?: string; listing?: string; icon?: string;
/** The Play developer account id (the digits in play.google.com/console/u/0/developers/<id>/...). Optional: with
* one Google login in several developer accounts, `storebound console fill` finds the app by package name and
* remembers the account (~/.storebound/console-accounts.json); this skips that search. */
developerId?: string;
/** Promo video: a YouTube URL (public or unlisted, ads off, embeddable). Play takes no video upload. Sent by `play listing`. */ /** Promo video: a YouTube URL (public or unlisted, ads off, embeddable). Play takes no video upload. Sent by `play listing`. */
video?: string; video?: string;
/** Cloud Storage bucket of the Play Console report exports, e.g. "pubsite_prod_rev_<number>" (Play Console > /** Cloud Storage bucket of the Play Console report exports, e.g. "pubsite_prod_rev_<number>" (Play Console >
@ -638,6 +642,7 @@ const SHA256_RE = /^([0-9A-F]{2}:){31}[0-9A-F]{2}$/;
export function validateExtras(cfg: Partial<ShipConfig>): string[] { export function validateExtras(cfg: Partial<ShipConfig>): string[] {
const e: string[] = []; const e: string[] = [];
if (cfg.apple?.teamId !== undefined && !/^[A-Z0-9]{10}$/.test(cfg.apple.teamId)) e.push('apple.teamId: the 10-character Team ID (Membership details)'); if (cfg.apple?.teamId !== undefined && !/^[A-Z0-9]{10}$/.test(cfg.apple.teamId)) e.push('apple.teamId: the 10-character Team ID (Membership details)');
if (cfg.play?.developerId !== undefined && !/^\d{1,25}$/.test(cfg.play.developerId)) e.push('play.developerId: the digits of play.google.com/console/u/0/developers/<id>');
const ad = cfg.apple?.adhoc; const ad = cfg.apple?.adhoc;
if (ad?.method !== undefined && ad.method !== 'release-testing' && ad.method !== 'ad-hoc') e.push('apple.adhoc.method: release-testing | ad-hoc'); if (ad?.method !== undefined && ad.method !== 'release-testing' && ad.method !== 'ad-hoc') e.push('apple.adhoc.method: release-testing | ad-hoc');
const ppp = cfg.prices?.ppp; const ppp = cfg.prices?.ppp;

View file

@ -112,14 +112,39 @@ export const forbiddenControl = (name: string): boolean => FORBIDDEN.test(name.t
const SIGN_IN_HOSTS = ['appleid.apple.com', 'idmsa.apple.com', 'accounts.google.com']; const SIGN_IN_HOSTS = ['appleid.apple.com', 'idmsa.apple.com', 'accounts.google.com'];
/** A sign-in page (storebound never touches those; the owner signs in). */ /**
* A sign-in page or frame (storebound never touches those; the owner signs in): Apple ID / Google accounts hosts, App
* Store Connect's /login, and Google sign-in paths (/signin, ServiceLogin) on any google.com host.
*/
export function isSignInUrl(url: string): boolean { export function isSignInUrl(url: string): boolean {
try { try {
const u = new URL(url); const u = new URL(url), h = u.hostname;
return SIGN_IN_HOSTS.includes(u.hostname) || (u.hostname === 'appstoreconnect.apple.com' && u.pathname.startsWith('/login')); if (SIGN_IN_HOSTS.includes(h)) return true;
if (h === 'appstoreconnect.apple.com' && /^\/login(\/|$)/.test(u.pathname)) return true;
return (h === 'google.com' || h.endsWith('.google.com')) && /\/(signin|ServiceLogin)(\/|$)/i.test(u.pathname);
} catch { return false; } } catch { return false; }
} }
/**
* Whole visible texts (or labels / placeholders) that only a sign-in form shows, English and Turkish. Apple's form
* lives in an idmsa.apple.com frame and starts with no password field (Email or Phone Number > Continue > passkey or
* password). `weak`: also used elsewhere (an account menu), so they count only inside a child frame.
*/
export const SIGN_IN_TEXTS = {
strong: ['Sign in with Passkey', 'Email or Phone Number', 'Sign in to App Store Connect', 'Keep me signed in', 'Email or phone',
'Geçiş Anahtarıyla Giriş Yap', 'Geçiş anahtarı ile giriş yap', 'Geçiş Anahtarı ile Giriş Yap', 'E-posta veya Telefon Numarası',
'App Store Connect’e giriş yap', "App Store Connect'e giriş yap", 'Oturumum açık kalsın', 'E-posta veya telefon'],
weak: ['Apple Account', 'Apple Hesabı', 'Apple ID'],
};
const textRe = (list: string[]) => new RegExp(`^\\s*(?:${list.map(esc).join('|')})\\s*$`, 'iu');
const STRONG = textRe(SIGN_IN_TEXTS.strong), WEAK = textRe(SIGN_IN_TEXTS.weak);
/** A text that marks a sign-in form (`inFrame`: it is inside a child frame, where the weak texts count too). */
export const isSignInText = (t: string, inFrame = false): boolean => {
const s = t.normalize('NFC').replace(/\s+/g, ' ');
return STRONG.test(s) || (inFrame && WEAK.test(s));
};
/** The console itself is open (signed in). `base` overrides the console origin (tests only, 127.0.0.1). */ /** The console itself is open (signed in). `base` overrides the console origin (tests only, 127.0.0.1). */
export function consoleReached(store: 'apple' | 'play', url: string, base?: string): boolean { export function consoleReached(store: 'apple' | 'play', url: string, base?: string): boolean {
try { try {
@ -192,8 +217,12 @@ export function navPlan(id: FormId, config: ShipConfig, bases: NavBases = NAV_BA
? ['Content rating', ['Content rating', 'Content ratings', 'İçerik derecelendirmesi', /^content ratings?$/i]] ? ['Content rating', ['Content rating', 'Content ratings', 'İçerik derecelendirmesi', /^content ratings?$/i]]
: ['Target audience and content', ['Target audience and content', 'Hedef kitle ve içerik', /^target audience\b/i, /^hedef kitle\b/iu]]; : ['Target audience and content', ['Target audience and content', 'Hedef kitle ve içerik', /^target audience\b/i, /^hedef kitle\b/iu]];
return [ return [
{ kind: 'goto', label: 'open Play Console', url: play }, config.play?.developerId
{ kind: 'pickApp', label: 'the app in the list', tokens: config.play?.packageName ? [config.play.packageName] : [], ...named, search: [/^search/i, 'Uygulama ara', /^ara$/iu] }, ? { kind: 'goto', label: 'open the app list of the developer account', url: playAppList(play, config.play.developerId) }
: { kind: 'goto', label: 'open Play Console', url: play },
// by package name only when there is one: with several developer accounts, an app of the same name in another
// account must not count
{ kind: 'pickApp', label: 'the app in the list', tokens: config.play?.packageName ? [config.play.packageName] : [], ...(config.play?.packageName ? {} : named), search: [/^search/i, 'Uygulama ara', /^ara$/iu] },
{ kind: 'click', label: 'Policy and programs (opens the menu)', roles: ['button', 'link'], names: POLICY, optional: true, unless: { roles: ['link'], names: APP_CONTENT } }, { kind: 'click', label: 'Policy and programs (opens the menu)', roles: ['button', 'link'], names: POLICY, optional: true, unless: { roles: ['link'], names: APP_CONTENT } },
{ kind: 'click', label: 'App content', roles: ['link'], names: APP_CONTENT }, { kind: 'click', label: 'App content', roles: ['link'], names: APP_CONTENT },
{ kind: 'formLink', label: `${title}: Start or Manage`, entry }, { kind: 'formLink', label: `${title}: Start or Manage`, entry },
@ -213,5 +242,30 @@ export function navAllowed(name: string, role: string): boolean {
return n.length > 0 && !forbiddenControl(n); return n.length > 0 && !forbiddenControl(n);
} }
// ---- one login, several developer accounts / teams ----
// Switching the developer account (Play) or the team (App Store Connect) changes what the console shows, it writes
// nothing: such a click is let through when its target is one of the accounts storebound just read from the chooser or
// the team menu (exact name), is a link / menu item / option / row / button, and is never a sign-out or a deny-listed
// control (forbiddenControl stays absolute, so a studio named "Next Games" is not clicked: the owner picks it).
/** Play Console's app list of one developer account. */
export const playAppList = (playBase: string, developerId: string): string => `${playBase.replace(/\/$/, '')}/u/0/developers/${encodeURIComponent(developerId)}/app-list`;
/** The developer account id in a Play Console URL (/developers/<digits>), or null. */
export function playDeveloperId(url: string): string | null {
try { return new URL(url).pathname.match(/\/developers\/(\d{1,25})(?:\/|$)/)?.[1] ?? null; } catch { return null; }
}
const SIGN_OUT = /\b(sign|log)\s*(out|off)\b|çıkış|oturumu kapat|hesap ekle|add account/iu;
/** Entries of an account menu that are not accounts (profile, settings, help, sign out). */
export const NOT_AN_ACCOUNT = /^(?:edit profile|profile|settings|account settings|help|users and access|switch team|teams?|profil(?:i düzenle)?|ayarlar|yardım|kullanıcılar ve erişim|ekip değiştir|ekipler?)$/iu;
/** The account-switch click gate: `name` must be one of `listed` (read from the chooser / team menu just before). */
export function switchAllowed(name: string, role: string, listed: string[]): boolean {
const n = name.trim().replace(/\s+/g, ' ');
return ['link', 'menuitem', 'menuitemradio', 'option', 'radio', 'row', 'button'].includes(role) && listed.includes(n)
&& !SIGN_OUT.test(n) && !NOT_AN_ACCOUNT.test(n) && navAllowed(n, role);
}
/** `id` as a whole token of `text` (com.example.game, not com.example.game2 or com.example.gamepro). */ /** `id` as a whole token of `text` (com.example.game, not com.example.game2 or com.example.gamepro). */
export const hasToken = (text: string, id: string): boolean => new RegExp(`(?<![\\w.])${esc(id)}(?![\\w.])`).test(text); export const hasToken = (text: string, id: string): boolean => new RegExp(`(?<![\\w.])${esc(id)}(?![\\w.])`).test(text);

View file

@ -35,6 +35,10 @@ export interface WsAccount {
label?: string; label?: string;
/** The desktop's account id (16 hex) when it came from there; else derived from store + profile. */ /** The desktop's account id (16 hex) when it came from there; else derived from store + profile. */
id?: string; id?: string;
/** play: the developer account id (console URL /developers/<id>); `console fill` opens that account directly. Not a secret. */
developerId?: string;
/** apple: the 10-character Team ID; `console fill` switches to that team. Not a secret. */
teamId?: string;
} }
export interface WsStudio { id?: string; name: string; color?: StudioColor; accounts?: WsAccount[]; apps?: string[] } export interface WsStudio { id?: string; name: string; color?: StudioColor; accounts?: WsAccount[]; apps?: string[] }
export interface WsAppEntry { path: string; name?: string; apple?: string; play?: string } export interface WsAppEntry { path: string; name?: string; apple?: string; play?: string }
@ -96,7 +100,7 @@ export async function loadWorkspace(from: string, explicit?: string): Promise<Lo
return { file, root: resolve(file, '..'), ws: raw as Workspace }; return { file, root: resolve(file, '..'), ws: raw as Workspace };
} }
const ACCOUNT_KEYS = ['store', 'profile', 'label', 'id']; const ACCOUNT_KEYS = ['store', 'profile', 'label', 'id', 'developerId', 'teamId'];
/** Problems of a workspace file (empty = fine). Secrets are refused: only profile names belong here. */ /** Problems of a workspace file (empty = fine). Secrets are refused: only profile names belong here. */
export function checkWorkspace(raw: unknown): string[] { export function checkWorkspace(raw: unknown): string[] {
@ -120,6 +124,8 @@ export function checkWorkspace(raw: unknown): string[] {
if (typeof o.profile !== 'string' || !PROFILE_RE.test(o.profile)) e.push(`${where}.profile: a credential profile name (letters, digits, . _ -)`); if (typeof o.profile !== 'string' || !PROFILE_RE.test(o.profile)) e.push(`${where}.profile: a credential profile name (letters, digits, . _ -)`);
if (o.id !== undefined && (typeof o.id !== 'string' || !/^[0-9a-f]{16}$/.test(o.id))) e.push(`${where}.id: 16 hex characters (the desktop's account id)`); if (o.id !== undefined && (typeof o.id !== 'string' || !/^[0-9a-f]{16}$/.test(o.id))) e.push(`${where}.id: 16 hex characters (the desktop's account id)`);
if (o.label !== undefined && (typeof o.label !== 'string' || o.label.length > 60)) e.push(`${where}.label: up to 60 characters`); if (o.label !== undefined && (typeof o.label !== 'string' || o.label.length > 60)) e.push(`${where}.label: up to 60 characters`);
if (o.developerId !== undefined && (o.store !== 'play' || typeof o.developerId !== 'string' || !/^\d{1,25}$/.test(o.developerId))) e.push(`${where}.developerId: a play account's developer id (digits)`);
if (o.teamId !== undefined && (o.store !== 'apple' || typeof o.teamId !== 'string' || !/^[A-Z0-9]{10}$/.test(o.teamId))) e.push(`${where}.teamId: an apple account's 10-character Team ID`);
}; };
if (w.accounts !== undefined) { if (!Array.isArray(w.accounts)) e.push('accounts: a list'); else w.accounts.forEach((a, i) => account(a, `accounts[${i}]`)); } if (w.accounts !== undefined) { if (!Array.isArray(w.accounts)) e.push('accounts: a list'); else w.accounts.forEach((a, i) => account(a, `accounts[${i}]`)); }
if (w.studios !== undefined) { if (w.studios !== undefined) {

View file

@ -52,6 +52,13 @@ export function appEnv(u: UnifiedApp<AppFolder>, accounts: Account[]): { env: Re
const ref = store === 'apple' ? u.ios : u.android; const ref = store === 'apple' ? u.ios : u.android;
return ref ? accounts.find(a => a.id === ref.account)?.profile ?? null : null; return ref ? accounts.find(a => a.id === ref.account)?.profile ?? null : null;
}; };
// the console ids of the store accounts (not secrets): console fill picks the developer account / team with them
for (const store of ['apple', 'play'] as const) {
const p = profileOf(store);
const acc = p ? accounts.find(a => a.store === store && a.profile === p) : undefined;
if (store === 'play' && acc?.developerId) env.STOREBOUND_PLAY_DEVELOPER_ID = acc.developerId;
if (store === 'apple' && acc?.teamId) env.STOREBOUND_APPLE_TEAM_ID = acc.teamId;
}
for (const store of ['apple', 'play'] as const) { for (const store of ['apple', 'play'] as const) {
const p = profileOf(store); const p = profileOf(store);
if (!p) continue; if (!p) continue;

View file

@ -202,6 +202,12 @@ macOS the owner's Chrome sign-in (real Google Chrome on a temporary copy of only
deleted when the run ends or is cancelled; the native dialog says "It uses your Chrome sign-in"), else storebound's own deleted when the run ends or is cancelled; the native dialog says "It uses your Chrome sign-in"), else storebound's own
profile in the desktop's Chrome for Testing (`STOREBOUND_CHROME`) with the bundled playwright-core. The tool's profile in the desktop's Chrome for Testing (`STOREBOUND_CHROME`) with the bundled playwright-core. The tool's
`fresh_profile: true` passes `--fresh-profile`. storebound opens the form itself after sign-in (navigation clicks only). `fresh_profile: true` passes `--fresh-profile`. storebound opens the form itself after sign-in (navigation clicks only).
The own profile is one per store (every studio shares the one login) and keeps the sign-in between runs: launched with
session restore, closed gracefully on Cancel. With one login in several Play developer accounts or App Store Connect
teams, the run finds the account that has the app and remembers it in `~/.storebound/console-accounts.json`
(`{ version, play: { <package>: { developerId, account, at } }, apple: { <bundle id>: { team, teamId?, at } } }`, ids
and account names only), the same file the desktop reads. A workspace account's `developerId` (play) / `teamId`
(apple) is passed as `STOREBOUND_PLAY_DEVELOPER_ID` / `STOREBOUND_APPLE_TEAM_ID`.
## Every CLI area in the window ## Every CLI area in the window

View file

@ -51,25 +51,56 @@ It is not available over MCP.
may ask once to allow that. `--chrome-profile "Profile 1"` picks another Chrome profile (default: the last used). may ask once to allow that. `--chrome-profile "Profile 1"` picks another Chrome profile (default: the last used).
Cookies are never printed, logged or sent anywhere. Cookies are never printed, logged or sent anywhere.
- **profile** (`--fresh-profile`, `--profile <dir>`, `STOREBOUND_CONSOLE_PROFILE`, or when the other two do not - **profile** (`--fresh-profile`, `--profile <dir>`, `STOREBOUND_CONSOLE_PROFILE`, or when the other two do not
work): storebound's own profile (`~/.storebound/console-profile/<store>`). The owner signs in there once; it is work): storebound's own profile (`~/.storebound/console-profile/<store>`, one per store, not per account: every
kept for the next run. studio shares the one login). The owner signs in there once; it is kept for the next run.
If a sign-in page shows, storebound prints "sign in in the browser window, storebound waits" and waits up to 10 Keeping the sign-in: Apple's and Google's sign-in cookies are partly session cookies. storebound launches the copy
minutes. It never types into a sign-in page. and the own profile with `--restore-last-session` (so Chromium loads them again) and always closes the browser
gracefully (window closed or Ctrl+C), so they are written to disk. Apple keeps a long sign-in only with "Keep me
signed in" ticked and "Trust" chosen for the browser; Google with "Stay signed in"; storebound reminds the owner on
the sign-in page. In copy mode the owner's Chrome Cookies file holds the session cookies only while that Chrome
runs, or when Chrome's "On startup: Continue where you left off" is on; otherwise one sign-in in the window is
needed.
Sign-in is detected by URL and by frame (App Store Connect `/login`, a frame from idmsa.apple.com /
appleid.apple.com, accounts.google.com, Google `/signin`), by a visible password field in any frame, and by the
form's own texts ("Sign in with Passkey", "Email or Phone Number", "Keep me signed in" and the Turkish ones):
Apple's form starts with no password field. storebound checks before every navigation step, after each click or
load, and while a step waits. Then it prints "sign in in the browser window; storebound waits" and waits up to
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 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/<apple.appId>/distribution/privacy`, or the app list > the (+)"): New App: Apps > + > New App; App Privacy: `/apps/<apple.appId>/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 app (by name / bundle id) > 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 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 / 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 Başla / Yönet is let through. If a step is not found in time, or two apps match (they are listed: set
`apple.appId` / `play.packageName`), storebound says which step failed, prints what to click, and waits. App `apple.appId` / `play.packageName`), storebound says which step failed, prints what to click, and keeps watching:
a sign-in that finishes restarts navigation at step 1; when the owner moves on by hand (the + button, the New App
item, the app in the list appear) it continues from that step; when the owner opens the form it fills it. Watching
ends when the window is closed. App
Privacy: the owner clicks Get Started (or Edit next to Data Types). When the form appears storebound fills the Privacy: the owner clicks Get Started (or Edit next to Data Types). When the form appears storebound fills the
certain answers, outlines every unproven or unfillable field with a "storebound: check this" label, and lists them certain answers, outlines every unproven or unfillable field with a "storebound: check this" label, and lists them
in the terminal. in the terminal.
5. Multi-page forms: the owner reviews the page and clicks Next; storebound fills the next page when it appears. 5. **One login, many developer accounts or teams.** storebound never asks for a second sign-in; it finds the
6. On the last page storebound prints "review every field and press <Save | Submit | Publish | Create> yourself". The account that has the app and remembers it in `~/.storebound/console-accounts.json` (ids only, never cookies;
shared with the desktop app):
- Play: the app list of one account is `/console/u/0/developers/<id>/app-list`. The id is `play.developerId` in
the config, else the workspace account's `developerId` (`storebound.workspace.json`, passed as
`STOREBOUND_PLAY_DEVELOPER_ID`), else the remembered one; else storebound reads every developer account on the
"Choose a developer account" page and looks for `play.packageName` in each app list ("developer account 4/5:
..."). A package in none of them is said plainly (create the app, or ask to be invited).
- App Store Connect: the team is switched in the account menu at the top right. Order: the remembered team, the
menu entry that names `apple.teamId` (or the workspace account's `teamId`), then every other team. The app is
recognized by its entry in the app list (App Privacy) or, for a new app, by the bundle id in the New App dialog's
Bundle ID list (Cancel closes the dialog in a team without it). App Store Connect has no documented URL
parameter that picks a team, so storebound does not use one.
- Switching only changes what the console shows. Each switch click must be an account name storebound just read
from the chooser or the menu, and never Sign Out or a deny-listed name (a studio called "Next Games" is left
for the owner to pick).
6. Multi-page forms: the owner reviews the page and clicks Next; storebound fills the next page when it appears.
7. On the last page storebound prints "review every field and press <Save | Submit | Publish | Create> yourself". The
command ends when the owner closes the window (`--json` then prints the result with `filled`, `highlighted`, command ends when the owner closes the window (`--json` then prints the result with `filled`, `highlighted`,
`fallback`, `stoppedAt`). `fallback`, `stoppedAt`).
7. If a field cannot be found or matches twice, the console UI changed: storebound stops filling and prints the 8. If a field cannot be found or matches twice (for more than a moment: a page that is still loading does not count), the console UI changed: storebound stops filling and prints the
step-by-step list ("label: answer") for the owner to copy. That is the expected safe behavior, not an error. step-by-step list ("label: answer") for the owner to copy. That is the expected safe behavior, not an error.
## The owner decides ## The owner decides
@ -79,7 +110,7 @@ ages, and pressing the final button (App Privacy Publish, IARC Submit, Target au
## Out of scope ## Out of scope
- Signing in, two-factor codes, accepting agreements, choosing a developer account. - Signing in, two-factor codes, accepting agreements, creating developer accounts or teams.
- Forms with an API: Data safety (`storebound play data-safety`), age rating, categories and content rights - Forms with an API: Data safety (`storebound play data-safety`), age rating, categories and content rights
(`storebound apple appinfo`), export compliance (`storebound apple encryption`). (`storebound apple appinfo`), export compliance (`storebound apple encryption`).
- Recording or reading console data: storebound only fills the visible form. - Recording or reading console data: storebound only fills the visible form.

View file

@ -2,12 +2,16 @@
// sign-in detector, and the engine run headless against MODELED console pages (tests/fixtures/console, written from // sign-in detector, and the engine run headless against MODELED console pages (tests/fixtures/console, written from
// the public help pages, not recorded) served on 127.0.0.1. No network. Browser tests skip when no Chromium launches. // the public help pages, not recorded) served on 127.0.0.1. No network. Browser tests skip when no Chromium launches.
import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path'; import { join } from 'node:path';
import { fillPage, navClick, navigate, run, safeClick, signInPage } from '../cli/console/fill'; import { openAcross, readAccounts, rememberApple, rememberPlay, withAccountIds } from '../cli/console/accounts';
import { fillPage, fillSession, navClick, navigate, resumeAt, run, safeClick, signInPage } from '../cli/console/fill';
import { type ConsoleBrowser, openConsoleBrowser } from '../cli/console/session';
import { parseArgs } from '../cli/lib/args'; import { parseArgs } from '../cli/lib/args';
import { type ShipConfig, validateExtras } from '../cli/lib/config'; import { type ShipConfig, validateExtras } from '../cli/lib/config';
import { AGE_RATING_API, consoleAnswers, consoleResult, fillValue, FORM_IDS, type FormId, formMeta } from '../cli/lib/console-answers'; import { AGE_RATING_API, consoleAnswers, consoleResult, fillValue, FORM_IDS, type FormId, formMeta } from '../cli/lib/console-answers';
import { consoleReached, formDef, FORM_OPENERS, forbiddenControl, hasToken, isSignInUrl, navAllowed, navPlan } from '../cli/lib/console-forms'; import { consoleReached, formDef, FORM_OPENERS, forbiddenControl, hasToken, isSignInText, isSignInUrl, navAllowed, navPlan, playDeveloperId, switchAllowed } from '../cli/lib/console-forms';
const config: ShipConfig = { const config: ShipConfig = {
app: { name: 'Example Game', profile: 'game', privacyPolicyUrl: 'https://example.com/privacy', supportUrl: 'https://example.com/support', website: 'https://example.com', contactEmail: 'support@example.com' }, app: { name: 'Example Game', profile: 'game', privacyPolicyUrl: 'https://example.com/privacy', supportUrl: 'https://example.com/support', website: 'https://example.com', contactEmail: 'support@example.com' },
@ -50,6 +54,18 @@ describe('sign-in and console detection', () => {
expect(consoleReached('play', 'https://play.google.com/console/u/0/developers')).toBe(true); expect(consoleReached('play', 'https://play.google.com/console/u/0/developers')).toBe(true);
expect(consoleReached('play', 'https://accounts.google.com/')).toBe(false); expect(consoleReached('play', 'https://accounts.google.com/')).toBe(false);
expect(consoleReached('play', 'http://127.0.0.1:1234/x.html', 'http://127.0.0.1:1234/')).toBe(true); expect(consoleReached('play', 'http://127.0.0.1:1234/x.html', 'http://127.0.0.1:1234/')).toBe(true);
expect(isSignInUrl('https://appstoreconnect.apple.com/login?targetUrl=%2Fapps')).toBe(true);
expect(isSignInUrl('https://appstoreconnect.apple.com/loginhelp')).toBe(false);
expect(isSignInUrl('https://play.google.com/signin/v2/identifier')).toBe(true);
expect(isSignInUrl('https://www.google.com/accounts/ServiceLogin')).toBe(true);
expect(isSignInUrl('https://play.google.com/console/u/0/developers')).toBe(false);
});
test('sign-in texts (whole text; the weak ones only inside a frame)', () => {
for (const t of ['Sign in with Passkey', ' Email or Phone Number ', 'Keep me signed in', 'Geçiş Anahtarıyla Giriş Yap', 'E-posta veya Telefon Numarası']) expect(isSignInText(t)).toBe(true);
expect(isSignInText('Apple Account')).toBe(false);
expect(isSignInText('Apple Account', true)).toBe(true);
expect(isSignInText('Apple Hesabı', true)).toBe(true);
for (const t of ['Apps', 'New App', 'Email address', 'Contact email', 'Sign in with Passkey to continue later']) expect(isSignInText(t, true)).toBe(false);
}); });
}); });
@ -157,20 +173,25 @@ const FIX = join(import.meta.dir, 'fixtures', 'console');
/** Console URLs of the navigation plans -> modeled pages (bases: asc = <base>asc, play = <base>play). */ /** Console URLs of the navigation plans -> modeled pages (bases: asc = <base>asc, play = <base>play). */
const ROUTES: Record<string, string> = { const ROUTES: Record<string, string> = {
'/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/apps/123/distribution/privacy': 'apple-app-privacy.html', '/play': 'play-apps.html', '/asc/apps/123/distribution/privacy': 'apple-app-privacy.html', '/play': 'play-apps.html', '/teams/apps': 'asc-teams.html',
}; };
let server: ReturnType<typeof Bun.serve> | null = null; let server: ReturnType<typeof Bun.serve> | null = null;
let base = ''; let base = '';
beforeAll(() => { beforeAll(() => {
server = Bun.serve({ hostname: '127.0.0.1', port: 0, fetch: req => { server = Bun.serve({ hostname: '127.0.0.1', port: 0, fetch: req => {
const path = new URL(req.url).pathname; const path = new URL(req.url).pathname;
const name = path.endsWith('/_common.js') ? '_common.js' : ROUTES[path] ?? path.slice(1); // a session cookie (no Expires / Max-Age): it must survive a relaunch of storebound's profile
if (path === '/session-set') return new Response('<p>set</p>', { headers: { 'content-type': 'text/html', 'set-cookie': 'sbsession=example; Path=/; HttpOnly' } });
if (path === '/session-echo') return new Response(`<p id="c">${/(?:^|; )sbsession=example(?:;|$)/.test(req.headers.get('cookie') ?? '') ? 'kept' : 'lost'}</p>`, { headers: { 'content-type': 'text/html' } });
const dev = path.match(/^\/playm\/u\/0\/developers(?:\/(\d+)\/app-list)?$/);
const name = path.endsWith('/_common.js') ? '_common.js' : dev ? (!dev[1] ? 'play-chooser.html' : dev[1] === '4444' ? 'play-apps.html' : 'play-apps-other.html')
: ROUTES[path] ?? path.slice(1);
if (!/^[a-z_-]+\.(html|js)$/.test(name)) return new Response('not found', { status: 404 }); if (!/^[a-z_-]+\.(html|js)$/.test(name)) return new Response('not found', { status: 404 });
return new Response(Bun.file(join(FIX, name))); return new Response(Bun.file(join(FIX, name)));
} }); } });
base = `http://127.0.0.1:${server.port}/`; base = `http://127.0.0.1:${server.port}/`;
}); });
afterAll(async () => { server?.stop(true); await browser?.close(); }); afterAll(async () => { server?.stop(true); await browser?.close(); }, 30_000); // closing every context of the run can take a few seconds
async function open(file: string) { async function open(file: string) {
const page = await browser.newPage(); const page = await browser.newPage();
@ -291,6 +312,9 @@ describe.skipIf(!browser)('engine (headless, modeled pages)', () => {
const signin = await open('signin.html'); const signin = await open('signin.html');
expect(await signInPage(signin)).toBe(true); expect(await signInPage(signin)).toBe(true);
await signin.close(); await signin.close();
const passkey = await open('signin-passkey.html'); // no password field, unknown host: the texts tell
expect(await signInPage(passkey)).toBe(true);
await passkey.close();
const page = await open('apple-app-record.html'); const page = await open('apple-app-record.html');
expect(await signInPage(page)).toBe(false); expect(await signInPage(page)).toBe(false);
expect(await safeClick(page.getByRole('button', { name: 'Create' }), 'Create')).toBe(false); expect(await safeClick(page.getByRole('button', { name: 'Create' }), 'Create')).toBe(false);
@ -350,7 +374,7 @@ describe.skipIf(!browser)('navigation (headless, modeled pages)', () => {
const quiet = { timeoutMs: 1500, say: () => {} }; const quiet = { timeoutMs: 1500, say: () => {} };
const navClicks = (page: any): Promise<string[]> => page.evaluate(() => (window as any).__navClicks()); const navClicks = (page: any): Promise<string[]> => page.evaluate(() => (window as any).__navClicks());
const noneDenied = (names: string[]) => { for (const n of names) expect(navAllowed(n, 'link')).toBe(true); }; const noneDenied = (names: string[]) => { for (const n of names) expect(navAllowed(n, 'link')).toBe(true); };
const fresh = async () => { const p = await browser.newPage(); await p.goto(base + 'signin.html'); await p.evaluate(() => sessionStorage.clear()); return p; }; const fresh = async () => { const p = await browser.newPage(); await p.goto(base + 'blank.html'); await p.evaluate(() => sessionStorage.clear()); return p; };
test('App Store Connect (EN): + > New App opens the dialog and it is filled; Create and Submit for Review never clicked', async () => { test('App Store Connect (EN): + > New App opens the dialog and it is filled; Create and Submit for Review never clicked', async () => {
const page = await fresh(); const page = await fresh();
@ -435,3 +459,216 @@ describe.skipIf(!browser)('navigation (headless, modeled pages)', () => {
await page.close(); await page.close();
}); });
}); });
// ---- sign-in during navigation, watching after the fallback, the session kept across relaunches ----
/** A browser context whose console hosts (appstoreconnect / idmsa / play.google.com) are served from the fixtures. */
async function consoleBrowser(map: (u: URL, cookie: string) => string | null): Promise<ConsoleBrowser> {
const ctx = await browser.newContext();
await ctx.route(/^https?:\/\/(?!127\.0\.0\.1)/, async (route: any) => {
const u = new URL(route.request().url());
const cookie: string = (await route.request().headerValue('cookie')) ?? '';
const name = u.pathname.endsWith('/_common.js') ? '_common.js' : map(u, cookie);
if (!name) return route.abort(); // nothing leaves the machine
return route.fulfill({ path: join(FIX, name), contentType: name.endsWith('.js') ? 'text/javascript' : 'text/html' });
});
const page = await ctx.newPage();
let closed = false;
const done = new Promise<void>(r => ctx.on('close', () => { closed = true; r(); }));
return { mode: 'profile', context: ctx, page, pages: () => ctx.pages(), closed: done, isClosed: () => closed, close: () => ctx.close(), cleanup: () => {} };
}
const until = async (what: string, fn: () => boolean | Promise<boolean>, ms = 20_000, said?: string[]) => {
const end = Date.now() + ms;
while (Date.now() < end) { if (await fn()) return; await Bun.sleep(50); }
throw new Error(`timed out waiting for: ${what}${said ? `\n${said.join("\n")}` : ""}`);
};
const tmpAccounts = () => join(mkdtempSync(join(tmpdir(), 'storebound-accounts-')), 'console-accounts.json');
const fast = (said: string[]) => ({ say: (m: string) => { said.push(m); }, tickMs: 100, navTimeoutMs: 1500, signInWaitMs: 30_000, accountsFile: tmpAccounts(), env: {} });
describe.skipIf(!browser)('sign-in and watching (headless, modeled pages on the real console hosts, routed locally)', () => {
test('ASC /login with an idmsa frame and no password field: detected mid-navigation, never touched; after sign-in navigation restarts at step 1', async () => {
const b = await consoleBrowser((u, cookie) => u.hostname === 'idmsa.apple.com' ? 'idmsa-signin.html'
: u.hostname !== 'appstoreconnect.apple.com' ? null
: u.pathname === '/login' ? 'asc-login.html' : u.pathname === '/apps' ? (cookie.includes('myacinfo=') ? 'asc-apps.html' : 'asc-shell.html') : null);
const said: string[] = [];
const run = fillSession(b, { form: 'apple-app-record', config, ...fast(said) });
await until('the sign-in hint', () => said.some(m => m.startsWith('sign in in the browser window')));
expect(said.some(m => /^a sign-in page appeared at step/.test(m))).toBe(true); // the shell looked signed in, then /login
expect(said.some(m => m.includes('Keep me signed in'))).toBe(true);
expect(new URL(b.page.url()).pathname).toBe('/login');
expect(await signInPage(b.page)).toBe(true);
const frame = b.page.frames().find((f: any) => f.url().startsWith('https://idmsa.apple.com/'));
expect(await frame.evaluate(() => (window as any).__clicks)).toEqual([]); // nothing clicked on the sign-in form
expect(await frame.locator('#acc').inputValue()).toBe(''); // nothing typed
await b.page.evaluate(() => (window as any).__signIn()); // the owner signs in
await until('the New App dialog filled', () => said.some(m => /^New App: filled \d+/.test(m)), 20_000, said);
expect(said).toContain('signed in: opening the form again from step 1');
expect(await b.page.getByRole('textbox', { name: 'Name', exact: true }).inputValue()).toBe('Example Game');
expect(await clicks(b.page)).toEqual(['+']); // never Create / Submit for Review
await b.context.close();
expect((await run).filled).toBeGreaterThan(0);
}, 40_000);
test('after the printed steps storebound keeps watching: the owner opens Apps by hand, navigation resumes at step 2 and fills', async () => {
const b = await consoleBrowser(u => u.hostname === 'appstoreconnect.apple.com' && u.pathname === '/apps' ? (u.search.includes('owner') ? 'asc-apps.html' : 'asc-apps-noplus.html') : null);
const said: string[] = [];
const run = fillSession(b, { form: 'apple-app-record', config, ...fast(said) });
await until('the printed steps', () => said.some(m => m.startsWith('open the form: Apps')));
expect(await clicks(b.page)).toEqual([]);
await b.page.evaluate(() => { location.href = '/apps?owner=1'; }); // the owner navigates
await until('the New App dialog filled', () => said.some(m => /^New App: filled \d+/.test(m)), 20_000, said);
expect(said).toContain('the page changed: storebound opens the form from step 2/4');
expect(await b.page.evaluate(() => (window as any).__navClicks())).toEqual(['Add Apps', 'New App']);
expect(await clicks(b.page)).toEqual(['+']);
await b.context.close();
await run;
}, 40_000);
test('after the printed steps: the owner opens the dialog by hand, storebound sees it and fills it', async () => {
const b = await consoleBrowser(u => u.hostname === 'appstoreconnect.apple.com' && u.pathname === '/apps' ? (u.search.includes('dialog') ? 'apple-app-record.html' : 'asc-apps-noplus.html') : null);
const said: string[] = [];
const run = fillSession(b, { form: 'apple-app-record', config, ...fast(said) });
await until('the printed steps', () => said.some(m => m.startsWith('open the form: Apps')));
await b.page.evaluate(() => { location.href = '/apps?dialog=1'; });
await until('the New App dialog filled', () => said.some(m => /^New App: filled \d+/.test(m)), 20_000, said);
expect(await clicks(b.page)).toEqual([]); // not even + : the dialog was open
await b.context.close();
await run;
}, 40_000);
test('resumeAt: the furthest step visible now, never the initial page load', async () => {
const page = await open('asc-apps.html');
const plan = navPlan('apple-app-record', config, bases());
expect(await resumeAt(page, plan)).toBe(1);
await page.getByRole('button', { name: 'Add Apps' }).click();
expect(await resumeAt(page, plan)).toBe(2);
await page.goto(base + 'asc-apps-noplus.html');
expect(await resumeAt(page, plan)).toBeNull();
await page.close();
});
for (const store of ['apple', 'play'] as const) {
test(`${store}: a session cookie survives closing and relaunching storebound's own profile`, async () => {
const dir = mkdtempSync(join(tmpdir(), `storebound-profile-${store}-`));
const root = join(import.meta.dir, '..');
try {
const opts = { store, profileDir: dir, fresh: true, headless: true, say: () => {} };
let b = await openConsoleBrowser(root, opts);
await b.page.goto(base + 'session-set');
await b.close(); // graceful: Chromium writes its cookie store
await b.closed;
b = await openConsoleBrowser(root, opts);
expect(b.pages()).toHaveLength(1); // the restored tab was closed again
await b.page.goto(base + 'session-echo');
expect(await b.page.textContent('#c')).toBe('kept');
await b.close();
await b.closed;
} finally { rmSync(dir, { recursive: true, force: true }); }
}, 60_000);
}
});
// ---- one login, several developer accounts / teams ----
describe('accounts (pure)', () => {
test('cache: ids only, malformed entries dropped, atomic rewrite', async () => {
const f = tmpAccounts();
expect(readAccounts(f)).toEqual({ version: 1, play: {}, apple: {} });
rememberPlay('com.example.game', { developerId: '4444', account: 'Example Games Ltd' }, f);
rememberApple('com.example.game', { team: 'Example Games Ltd', teamId: 'ABCDE12345' }, f);
const c = readAccounts(f);
expect(c.play['com.example.game']).toMatchObject({ developerId: '4444', account: 'Example Games Ltd' });
expect(c.apple['com.example.game']).toMatchObject({ team: 'Example Games Ltd', teamId: 'ABCDE12345' });
expect(JSON.stringify(c)).not.toMatch(/cookie|myacinfo|session/i);
await Bun.write(f, JSON.stringify({ play: { 'com.x': { developerId: 'abc' }, '../bad': { developerId: '1' } }, apple: { 'com.y': { team: '' } } }));
expect(readAccounts(f)).toEqual({ version: 1, play: {}, apple: {} });
});
test('play developer ids, env ids from a workspace account, and the switch gate', () => {
expect(playDeveloperId('https://play.google.com/console/u/0/developers/4444/app-list')).toBe('4444');
expect(playDeveloperId('https://play.google.com/console/u/0/developers')).toBeNull();
expect(navPlan('play-content-rating', { ...config, play: { ...config.play!, developerId: '4444' } } as ShipConfig)[0])
.toMatchObject({ kind: 'goto', url: 'https://play.google.com/console/u/0/developers/4444/app-list' });
expect(withAccountIds(config, { STOREBOUND_PLAY_DEVELOPER_ID: '4444', STOREBOUND_APPLE_TEAM_ID: 'ABCDE12345' })).toMatchObject({ play: { developerId: '4444' }, apple: { teamId: 'ABCDE12345' } });
expect(withAccountIds(config, { STOREBOUND_PLAY_DEVELOPER_ID: 'x' }).play?.developerId).toBeUndefined();
expect(validateExtras({ play: { packageName: 'com.example.game', developerId: 'abc' } })).toContain('play.developerId: the digits of play.google.com/console/u/0/developers/<id>');
const listed = ['Studio One', 'Example Games Ltd', 'Next Level Games', 'Sign Out'];
expect(switchAllowed('Example Games Ltd', 'menuitemradio', listed)).toBe(true);
expect(switchAllowed('Example Games Ltd', 'link', listed)).toBe(true);
expect(switchAllowed('Other Studio', 'menuitemradio', listed)).toBe(false); // not read from the list
expect(switchAllowed('Sign Out', 'menuitem', listed)).toBe(false);
expect(switchAllowed('Next Level Games', 'menuitemradio', listed)).toBe(false); // the click gate stays absolute
expect(switchAllowed('Edit Profile', 'menuitem', ['Edit Profile'])).toBe(false);
expect(switchAllowed('Example Games Ltd', 'textbox', listed)).toBe(false);
});
});
describe.skipIf(!browser)('accounts (headless, modeled pages)', () => {
const navClicks = (page: any): Promise<string[]> => page.evaluate(() => (window as any).__navClicks());
const fresh = async () => { const p = await browser.newPage(); await p.goto(base + 'blank.html'); await p.evaluate(() => sessionStorage.clear()); return p; };
const DENIED = ['Sign Out', 'Edit Profile', 'Create', 'Submit for Review', 'Create app', 'Create developer account', 'Save', 'Publish'];
test('App Store Connect, 3 teams, the bundle id in the 2nd: switched through the account menu, remembered, then picked first', async () => {
const file = tmpAccounts(), said: string[] = [];
let page = await fresh();
await page.goto(base + 'teams/apps');
const tb = { asc: base + 'teams', play: base + 'play' };
const r = await openAcross(page, { form: 'apple-app-record', config, say: m => { said.push(m); }, bases: tb, navMs: 1500, file, env: {} });
expect(r.nav.ok).toBe(true);
expect(said).toContain('this Apple Account is in 3 teams: looking for com.example.game in each');
expect(readAccounts(file).apple['com.example.game']?.team).toBe('Example Games Ltd');
expect(await page.evaluate(() => document.cookie)).toContain('team=Example%20Games%20Ltd');
const names = await navClicks(page);
expect(names).toContain('Example Games Ltd');
for (const n of DENIED) expect(names).not.toContain(n);
expect(await clicks(page)).toEqual(['+']); // in the right team: + only, never Create
const s = await fillPage(page, formDef('apple-app-record', pageAnswers('apple-app-record')), pageAnswers('apple-app-record'));
expect(s.filled).toContain('bundleId');
await page.close();
// the next run tries the remembered team first
const said2: string[] = [];
page = await fresh();
await page.goto(base + 'teams/apps');
expect((await openAcross(page, { form: 'apple-app-record', config, say: m => { said2.push(m); }, bases: tb, navMs: 1500, file, env: {} })).nav.ok).toBe(true);
expect(said2).toContain('team 1/3: Example Games Ltd');
for (const n of DENIED) expect(await navClicks(page)).not.toContain(n);
await page.close();
}, 60_000);
test('Play, one login in 5 developer accounts, the app in the 4th: found by package name, remembered, then opened directly', async () => {
const file = tmpAccounts(), said: string[] = [];
const pb = { asc: base + 'asc', play: base + 'playm' };
let page = await fresh();
const r = await openAcross(page, { form: 'play-content-rating', config, say: m => { said.push(m); }, bases: pb, navMs: 1500, file, env: {} });
expect(r.nav.ok).toBe(true);
expect(said).toContain('this Google login sees 5 developer accounts: looking for com.example.game in each');
expect(said).toContain('developer account 4/5: Example Games Ltd');
expect(readAccounts(file).play['com.example.game']).toMatchObject({ developerId: '4444', account: 'Example Games Ltd' });
expect(await navClicks(page)).toEqual(['Example Game', 'Policy and programs', 'App content', 'Start']);
expect(await clicks(page)).toEqual([]);
await page.close();
// remembered: straight to that account's app list, no chooser
const said2: string[] = [];
page = await fresh();
expect((await openAcross(page, { form: 'play-content-rating', config, say: m => { said2.push(m); }, bases: pb, navMs: 1500, file, env: {} })).nav.ok).toBe(true);
expect(said2.some(m => m.includes('developer accounts'))).toBe(false);
expect(said2).toContain('opening the form, step 1/6: open the app list of the developer account');
await page.close();
// play.developerId from a workspace account (env): no chooser either, nothing cached needed
const said3: string[] = [];
page = await fresh();
expect((await openAcross(page, { form: 'play-target-audience', config, say: m => { said3.push(m); }, bases: pb, navMs: 1500, file: tmpAccounts(), env: { STOREBOUND_PLAY_DEVELOPER_ID: '4444' } })).nav.ok).toBe(true);
expect(said3.some(m => m.includes('developer accounts'))).toBe(false);
await page.close();
}, 60_000);
test('Play: a package in none of the developer accounts is said plainly; nothing deny-listed clicked', async () => {
const page = await fresh();
const absent = { ...config, play: { packageName: 'com.example.absent' } } as ShipConfig;
const r = await openAcross(page, { form: 'play-content-rating', config: absent, say: () => {}, bases: { asc: base + 'asc', play: base + 'playm' }, navMs: 800, file: tmpAccounts(), env: {} });
expect(r.nav).toMatchObject({ ok: false, failed: 'the developer account' });
expect(r.nav.why).toContain('com.example.absent is in none of the 5 developer accounts');
expect(await clicks(page)).toEqual([]);
for (const n of DENIED) expect(await navClicks(page)).not.toContain(n);
await page.close();
}, 60_000);
});

View file

@ -6,7 +6,7 @@ window.__clicks = [];
const navLog = () => { try { return JSON.parse(sessionStorage.getItem('navClicks') || '[]'); } catch { return []; } }; const navLog = () => { try { return JSON.parse(sessionStorage.getItem('navClicks') || '[]'); } catch { return []; } };
window.__navClicks = navLog; window.__navClicks = navLog;
document.addEventListener('click', e => { document.addEventListener('click', e => {
const b = e.target.closest('button, a, [role="button"], [role="menuitem"], [role="link"], [role="row"], tr'); const b = e.target.closest('button, a, [role="button"], [role="menuitem"], [role="menuitemradio"], [role="option"], [role="link"], [role="row"], tr');
if (!b) return; if (!b) return;
const name = (b.getAttribute('aria-label') || b.textContent).trim().replace(/\s+/g, ' '); const name = (b.getAttribute('aria-label') || b.textContent).trim().replace(/\s+/g, ' ');
if (b.matches('button')) window.__clicks.push(b.textContent.trim()); if (b.matches('button')) window.__clicks.push(b.textContent.trim());

11
tests/fixtures/console/asc-login.html vendored Normal file
View file

@ -0,0 +1,11 @@
<!doctype html>
<!-- MODELED, not recorded: App Store Connect at /login. Apple's sign-in form lives in a frame from idmsa.apple.com and
starts with no password field (Email or Phone Number > Continue > passkey or password). window.__signIn() acts as
the owner finishing sign-in: a session cookie (no expiry), then the app shell at /apps. Placeholder data only. -->
<html lang="en"><head><meta charset="utf-8"><title>App Store Connect</title><script src="/_common.js"></script></head>
<body>
<iframe title="Sign In with your Apple Account" src="https://idmsa.apple.com/appleauth/auth/signin?widgetKey=example" width="480" height="360"></iframe>
<script>
window.__signIn = () => { document.cookie = 'myacinfo=example-session; path=/'; location.href = '/apps'; };
</script>
</body></html>

9
tests/fixtures/console/asc-shell.html vendored Normal file
View file

@ -0,0 +1,9 @@
<!doctype html>
<!-- MODELED, not recorded: App Store Connect's app shell at /apps without a session: it loads at the console URL (it
looks signed in for a moment), then the app sends the browser to /login. The real-console case from a run whose
session had expired. -->
<html lang="en"><head><meta charset="utf-8"><title>App Store Connect</title><script src="/_common.js"></script></head>
<body>
<p>Loading</p>
<script>setTimeout(() => location.replace('/login'), 700);</script>
</body></html>

58
tests/fixtures/console/asc-teams.html vendored Normal file
View file

@ -0,0 +1,58 @@
<!doctype html>
<!-- MODELED, not recorded: App Store Connect > Apps for an Apple Account in three teams. The account menu at the top
right lists the teams (Apple's help "Switch between teams"); picking one reloads the console in that team (here: a
cookie). The New App dialog's Bundle ID list holds only the current team's bundle ids: com.example.game is in the
2nd team. Sign Out, Edit Profile, Create and Submit for Review must never be clicked. Placeholder data only. -->
<html lang="en"><head><meta charset="utf-8"><title>Apps - App Store Connect</title><script src="/_common.js"></script></head>
<body>
<header>
<button type="button" id="acct" aria-label="Account" aria-haspopup="menu">Example Owner</button>
<div role="menu" id="acctmenu" aria-label="Account" hidden></div>
</header>
<h1>Apps</h1>
<button type="button" id="plus" aria-label="Add Apps" aria-haspopup="menu">+</button>
<div role="menu" id="menu" hidden>
<div role="menuitem" tabindex="0" id="newapp">New App</div>
<div role="menuitem" tabindex="0">New App Bundle</div>
</div>
<button type="button">Submit for Review</button>
<div role="dialog" aria-labelledby="t" id="dlg" hidden>
<h2 id="t">New App</h2>
<fieldset><legend>Platforms</legend>
<label><input type="checkbox"> iOS</label> <label><input type="checkbox"> macOS</label>
</fieldset>
<p><label>Name <input type="text" maxlength="30"></label></p>
<p><label>Primary Language <select><option value="">Choose</option><option>English (U.K.)</option><option>English (U.S.)</option></select></label></p>
<p><label>Bundle ID <select id="bundle"><option value="">Choose</option></select></label></p>
<p><label>SKU <input type="text"></label></p>
<fieldset><legend>User Access</legend>
<label><input type="radio" name="access"> Limited Access</label> <label><input type="radio" name="access"> Full Access</label>
</fieldset>
<button type="button" id="cancel">Cancel</button> <button type="button">Create</button>
</div>
<script>
const TEAMS = { 'Alpha Studio': 'com.example.other', 'Example Games Ltd': 'com.example.game', 'Gamma Apps': 'com.example.gamma' };
const team = (document.cookie.match(/(?:^|; )team=([^;]+)/) || [])[1];
const current = team ? decodeURIComponent(team) : 'Alpha Studio';
const menu = document.getElementById('acctmenu');
for (const name of [...Object.keys(TEAMS), 'Edit Profile', 'Sign Out']) {
const it = document.createElement('div');
it.tabIndex = 0;
it.textContent = name;
if (TEAMS[name]) {
it.setAttribute('role', 'menuitemradio');
it.setAttribute('aria-checked', String(name === current));
it.addEventListener('click', () => { document.cookie = 'team=' + encodeURIComponent(name) + '; path=/'; location.reload(); });
} else it.setAttribute('role', 'menuitem');
menu.appendChild(it);
}
document.getElementById('acct').addEventListener('click', () => { menu.hidden = !menu.hidden; });
document.addEventListener('keydown', e => { if (e.key === 'Escape') menu.hidden = true; });
const opt = document.createElement('option');
opt.textContent = 'App - ' + TEAMS[current];
document.getElementById('bundle').appendChild(opt);
document.getElementById('plus').addEventListener('click', () => { document.getElementById('menu').hidden = false; });
document.getElementById('newapp').addEventListener('click', () => { document.getElementById('menu').hidden = true; document.getElementById('dlg').hidden = false; });
document.getElementById('cancel').addEventListener('click', () => { document.getElementById('dlg').hidden = true; });
</script>
</body></html>

3
tests/fixtures/console/blank.html vendored Normal file
View file

@ -0,0 +1,3 @@
<!doctype html>
<!-- An empty page on the fixture origin: navigation tests start here (clean click log, no sign-in page). -->
<html lang="en"><head><meta charset="utf-8"><title>Start</title></head><body></body></html>

View file

@ -0,0 +1,11 @@
<!doctype html>
<!-- MODELED, not recorded: the first page of Apple's sign-in form (the idmsa.apple.com frame): no password field yet.
storebound must detect it, never type into it and never click anything in it. -->
<html lang="en"><head><meta charset="utf-8"><title>Sign In</title><script src="/_common.js"></script></head>
<body>
<h1>Sign in to App Store Connect</h1>
<p><label for="acc">Email or Phone Number</label> <input id="acc" type="text"></p>
<p><label><input type="checkbox"> Keep me signed in</label></p>
<button type="button">Continue</button>
<button type="button">Sign in with Passkey</button>
</body></html>

View file

@ -0,0 +1,13 @@
<!doctype html>
<!-- MODELED, not recorded: Play Console > All apps of a developer account that does not have com.example.game (one
app of the same studio family, a different package). Create app must never be clicked. Placeholder data only. -->
<html lang="en"><head><meta charset="utf-8"><title>All apps - Play Console</title><script src="/_common.js"></script></head>
<body>
<h1>All apps</h1>
<label>Search apps <input type="search"></label>
<button type="button">Create app</button>
<table>
<tr><th>App</th><th>Package</th></tr>
<tr><td><a href="/play-dashboard.html">Other App</a></td><td>com.example.other</td></tr>
</table>
</body></html>

View file

@ -0,0 +1,16 @@
<!doctype html>
<!-- MODELED, not recorded: Play Console's "Choose a developer account" page for one Google login that is an admin of
five developer accounts. Each entry links to that account (/developers/<id>/app-list). The app com.example.game
is in the 4th account (4444). Create developer account must never be clicked. Placeholder data only. -->
<html lang="en"><head><meta charset="utf-8"><title>Choose a developer account - Play Console</title><script src="/_common.js"></script></head>
<body>
<h1>Choose a developer account</h1>
<ul>
<li><a href="./developers/1111/app-list">Studio One</a></li>
<li><a href="./developers/2222/app-list">Studio Two</a></li>
<li><a href="./developers/3333/app-list">Studio Three</a></li>
<li><a href="./developers/4444/app-list">Example Games Ltd</a></li>
<li><a href="./developers/5555/app-list">Studio Five</a></li>
</ul>
<button type="button">Create developer account</button>
</body></html>

View file

@ -0,0 +1,5 @@
<!doctype html>
<!-- MODELED, not recorded: a sign-in form on a host storebound does not know, with no password field: only the texts
tell it is a sign-in page. -->
<html lang="en"><head><meta charset="utf-8"><title>Sign in</title></head>
<body><p><input type="text" placeholder="Email or Phone Number"></p> <button type="button">Sign in with Passkey</button></body></html>

View file

@ -128,6 +128,12 @@ describe('pairing (the desktop rules, shared)', () => {
expect(Object.keys(e.env).sort()).toEqual(['ASC_ISSUER_ID', 'ASC_KEY_ID', 'ASC_P8', 'PLAY_SERVICE_ACCOUNT', 'STOREBOUND_PROFILE']); expect(Object.keys(e.env).sort()).toEqual(['ASC_ISSUER_ID', 'ASC_KEY_ID', 'ASC_P8', 'PLAY_SERVICE_ACCOUNT', 'STOREBOUND_PROFILE']);
expect(e.env.STOREBOUND_PROFILE).toBe(''); expect(e.env.STOREBOUND_PROFILE).toBe('');
expect(e.env.ASC_P8).toBe(join(creds, 'keys', 'acme.p8')); // relative to the profile folder expect(e.env.ASC_P8).toBe(join(creds, 'keys', 'acme.p8')); // relative to the profile folder
// the console ids of the studio's accounts (not secrets) reach console fill as env
const withIds = { ...l.ws, studios: l.ws.studios!.map(s => ({ ...s, accounts: s.accounts?.map(a => (a.store === 'play' ? { ...a, developerId: '4444' } : { ...a, teamId: 'ABCDE12345' })) })) };
const e2 = appEnv(blocks.unified, accountsOf(withIds));
expect([e2.env.STOREBOUND_PLAY_DEVELOPER_ID, e2.env.STOREBOUND_APPLE_TEAM_ID]).toEqual(['4444', 'ABCDE12345']);
expect(checkWorkspace(withIds)).toEqual([]);
expect(checkWorkspace({ accounts: [{ store: 'apple', profile: 'x', developerId: '1' }] }).join()).toContain('developerId');
// an unpair keeps them apart // an unpair keeps them apart
const split = workspaceApps({ ...l, ws: { ...l.ws, overrides: { unpairs: [{ ios: blocks.unified.ios!.key, android: blocks.unified.android!.key }] } } }, summaries); const split = workspaceApps({ ...l, ws: { ...l.ws, overrides: { unpairs: [{ ios: blocks.unified.ios!.key, android: blocks.unified.android!.key }] } } }, summaries);
expect(split.apps.filter(a => a.name === 'Blocks').map(a => a.unified.pairing)).toEqual(['single', 'single']); expect(split.apps.filter(a => a.name === 'Blocks').map(a => a.unified.pairing)).toEqual(['single', 'single']);