console fill: sign-in detected by URL, frame and text; keeps watching after the fallback; session kept across relaunches; one login across Play developer accounts and App Store Connect teams

This commit is contained in:
CRTkafa 2026-10-11 18:54:48 +00:00
parent fd89724aeb
commit 024964e748
22 changed files with 1101 additions and 110 deletions

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
// 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
// applies the same gate (only a link named exactly Start / Manage / Başla / Yönet is let through). A step not found in
// time -> the printed steps, and storebound waits as before. The owner reviews each page, clicks Next, and presses the
// applies the same gate (only a link named exactly Start / Manage / Başla / Yönet is let through). A sign-in page at
// 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
// (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.
@ -24,19 +27,21 @@ import { homedir } from 'node:os';
import { join } from 'node:path';
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 { 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 { openAcross, withAccountIds } from './accounts';
import { type ConsoleBrowser, openConsoleBrowser } from './session';
/* eslint-disable @typescript-eslint/no-explicit-any */
type Page = any;
type Locator = any;
export type Page = any;
export type Locator = any;
const TAG = 'console';
const CHECK = 'storebound: check this';
/** 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 });
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). */
async function accName(loc: Locator): Promise<string> {
export async function accName(loc: Locator): Promise<string> {
return (await loc.evaluate((el: any) => {
const by = el.getAttribute('aria-labelledby');
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 };
}
/** 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> {
if (isSignInUrl(page.url())) return true;
if (page.frames().some((f: any) => isSignInUrl(f.url()))) return true;
try { return (await page.locator('input[type="password"]').count()) > 0; } catch { return false; }
const frames: any[] = page.frames();
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) ----
/** 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()));
}
@ -230,17 +260,29 @@ export interface NavResult {
why?: string;
/** pickApp: the matching apps when more than one matched (storebound stops and lists them). */
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; }
return { state: 'none' };
}
/** Polls `fn` until it returns a value or the time is up (errors while the page navigates count as "not yet"). */
async function poll<T>(ms: number, fn: () => Promise<T | null>): Promise<T | null> {
/** Thrown by poll when a sign-in page shows up while a navigation step waits (navigate turns it into `signIn`). */
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;
for (;;) {
if (stop && await stop().catch(() => false)) throw new SignInSeen();
try { const r = await fn(); if (r !== null) return r; } catch { /* navigating */ }
if (Date.now() >= end) return null;
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('|')})$`);
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]) {
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]); }
}
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 }[] = [];
for (let i = 0; i < n; i++) {
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;
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) };
}
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 () => {
const found: { loc: Locator; key: string }[] = [];
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 };
return found.length > 1 ? { ambiguous: true } : null;
});
}, stop);
}
/** 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;
}
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
* `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 isSignIn = opts.signIn ?? signInPage;
const stop: Stop = () => isSignIn(page).catch(() => false);
const steps: string[] = [];
const target = plan.at(-1);
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'] };
}
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}`);
if (s.kind === 'goto') {
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]})`); }
} else if (s.kind === 'click') {
if (s.optional && s.unless && (await findAny(page, s.unless.roles, s.unless.names)).state !== 'none') { say(' (not needed)'); continue; }
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 (!f) { if (s.optional) { say(' (not on this page, skipped)'); continue; } return fail(s, 'not found'); }
if (f.state !== 'ok') return fail(s, 'more than one match');
const c = await navClick(f.loc);
if (!c.clicked) return fail(s, `refused to click "${c.name}"`);
} else if (s.kind === 'pickApp') {
if (!s.tokens.length && !s.name) return fail(s, 'no bundle id, package name or app name in the config');
const r = await pickApp(page, s, ms);
if (!r) return fail(s, `no app matching ${[...s.tokens, ...(s.name ? [`"${s.name}"`] : [])].join(' / ')} in the list`);
if (r.candidates) return fail(s, 'more than one app matches', r.candidates);
const c = await navClick(r.loc);
if (!c.clicked) return fail(s, `refused to click "${c.name}"`);
} else if (s.kind === 'formLink') {
const r = await formLink(page, s.entry, ms);
if (!r) return fail(s, 'no Start or Manage link next to it');
if (r.ambiguous) return fail(s, 'more than one Start or Manage link matches');
const c = await navClick(r.loc);
if (!c.clicked) return fail(s, `refused to click "${c.name}"`);
} else {
const f = await poll(ms, async () => ((await present(page, s)) ? true : null));
if (!f) return fail(s, 'did not appear');
try {
if (s.kind === 'goto') {
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]})`); }
} else if (s.kind === 'click') {
if (s.optional && s.unless && (await findAny(page, s.unless.roles, s.unless.names)).state !== 'none') { say(' (not needed)'); continue; }
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) { if (s.optional) { say(' (not on this page, skipped)'); continue; } return fail(s, 'not found'); }
if (f.state !== 'ok') return fail(s, 'more than one match');
const c = await navClick(f.loc);
if (!c.clicked) return fail(s, `refused to click "${c.name}"`);
} else if (s.kind === 'pickApp') {
if (!s.tokens.length && !s.name) return fail(s, 'no bundle id, package name or app name in the config');
const r = await pickApp(page, s, ms, stop);
if (!r) return fail(s, `no app matching ${[...s.tokens, ...(s.name ? [`"${s.name}"`] : [])].join(' / ')} in the list`);
if (r.candidates) return fail(s, 'more than one app matches', r.candidates);
const c = await navClick(r.loc);
if (!c.clicked) return fail(s, `refused to click "${c.name}"`);
} else if (s.kind === 'formLink') {
const r = await formLink(page, s.entry, ms, stop);
if (!r) return fail(s, 'no Start or Manage link next to it');
if (r.ambiguous) return fail(s, 'more than one Start or Manage link matches');
const c = await navClick(r.loc);
if (!c.clicked) return fail(s, `refused to click "${c.name}"`);
} else {
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);
}
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 {
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}`}`);
@ -374,7 +460,6 @@ export async function run(ctx: Ctx): Promise<void> {
return;
}
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 store = args.get('store');
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,
...(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
const bye = () => { b.cleanup(); process.exit(130); };
process.once('SIGINT', bye); process.once('SIGTERM', bye);
try { await fillRun(b); } finally { b.cleanup(); process.off('SIGINT', bye); process.off('SIGTERM', bye); }
// Ctrl+C: close the browser gracefully (Chromium writes its cookies on a clean exit, so the sign-in is kept for the
// next run), then remove the temporary profile of copy mode; that also happens on every other exit path
let stopping = false;
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 page = b.page;
await page.goto(startUrl ?? meta.url).catch(() => { /* the owner can navigate */ });
const isSignIn = (p: Page) => signInPage(p).catch(() => false);
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
const deadline = Date.now() + 10 * 60_000;
let told = false;
while (!b.isClosed() && Date.now() < deadline) {
const p = active();
if (p && !(await signInPage(p).catch(() => false)) && consoleReached(meta.store, p.url(), startUrl)) break;
if (p && !told && await signInPage(p).catch(() => false)) { say('sign in in the browser window, storebound waits'); told = true; }
await Bun.sleep(1000);
/** Waits until the console is open and no sign-in page shows (two rounds in a row). false: window closed or time up. */
async function signedIn(): Promise<boolean> {
const end = Date.now() + signInMs;
let told = false, ok = 0;
while (!b.isClosed() && Date.now() < end) {
const p = active();
if (p && await isSignIn(p)) { ok = 0; if (!told) { signInHint(); told = true; } }
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
const def = formDef(fid, res.answers);
const pageAnswers = res.answers.map(a => ({ ...a, value: fillValue(fid, a, config) }));
let plan = startUrl ? [] : navPlan(form, withAccountIds(config, o.env), o.bases);
const broken = (e: Error): NavResult => ({ ok: false, steps: [], failed: 'navigation', why: e.message.split('\n')[0] });
/**
* 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 done = new Set<number>();
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
const plan = startUrl || b.isClosed() ? [] : navPlan(fid, config);
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;
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`);
let nav: NavResult | null = plan.length && !b.isClosed() ? await openForm(0) : null;
if (nav) report(nav, true);
else for (const s of meta.open) say(`open the form: ${s}`);
const last = def.sections.length - 1;
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()) {
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;
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) {
// 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) {
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:`);
@ -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('; ')}` : ''}`);
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.`);
else if (!b.isClosed()) say('close the browser window when done');
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).
// (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.
// 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
// 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
@ -135,6 +145,8 @@ export interface ConsoleBrowser {
/** Resolves when the owner closed the window (copy / profile) or storebound's tab (attach). */
closed: Promise<void>;
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. */
cleanup: () => void;
/** 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();
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. */
@ -189,7 +220,7 @@ export async function openConsoleBrowser(root: string, o: OpenOpts): Promise<Con
let closed = false;
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');
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) {
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');
@ -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 } : {}) });
const c = await chromiumFor(root);
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
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`
+ `${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');
const page = context.pages()[0] ?? await context.newPage();
const page = await ownTab(context);
const cp = copy;
return { ...wrapContext('copy', context, page, () => cp.cleanup()), tempDir: cp.dir };
} 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
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`);
const page = context.pages()[0] ?? await context.newPage();
const page = await ownTab(context);
return wrapContext('profile', context, page, () => { /* kept on purpose */ });
}