console fill: opens the form itself and reuses the owner's Chrome sign-in

Navigation after sign-in (navPlan + navigate): App Store Connect Apps > + > New App
(EN/TR), App Privacy by /apps/<appId>/distribution/privacy or the app list, Play app
list by package name > Policy and programs > App content > Start / Manage. Every
navigation click goes through navClick: the click gate stays absolute, only a link
named exactly Start / Manage / Başla / Yönet passes. Each step is logged; a step not
found in time or two matching apps -> the printed steps and wait (no crash).
The TR gate now refuses "uygula" (apply) but not "uygulama" (app).

Browser (cli/console/session.ts): attach to a Chrome with remote debugging (--cdp or
DevToolsActivePort), else on macOS a temporary profile with only Local State and the
profile's Cookies filtered to the console hosts, opened in real Chrome and deleted at
the end, else storebound's own profile (--fresh-profile). Cookies are never printed.
Desktop: fresh_profile option, the dialog says it uses the Chrome sign-in.
Tests: navigation fixtures (ASC EN/TR, Play list, App content, missing step,
duplicates, deny-listed decoys), session file selection, host filter, cleanup, and a
real-Chrome copy-mode test on a throwaway profile and a local site.
This commit is contained in:
CRTkafa 2026-10-11 18:21:35 +00:00
parent 761cb11d76
commit 1d2978d0bb
28 changed files with 1034 additions and 63 deletions

View file

@ -7,21 +7,26 @@
// it does not prove stays EMPTY and highlighted (AGENTS.md rule 5).
// Safety: storebound never types passwords, never touches sign-in pages (it waits while the owner signs in), never reads
// cookies or storage, and never clicks Save / Submit / Publish / Create / Next: every click goes through safeClick and
// its gate. 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.
// Profile: ~/.storebound/console-profile/<store> (or --profile / STOREBOUND_CONSOLE_PROFILE), so the sign-in is kept.
// 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
// 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.
// Browser (cli/console/session.ts): the owner's running Chrome (--cdp / remote debugging), else a temporary copy of only
// their Chrome sign-in cookies (macOS; deleted at the end), else storebound's own profile
// (~/.storebound/console-profile/<store>, or --profile / STOREBOUND_CONSOLE_PROFILE / --fresh-profile).
// Sources (checked October 2026): see cli/lib/console-answers.ts; Playwright launchPersistentContext, getByRole,
// getByLabel: https://playwright.dev/docs/api/class-browsertype#browser-type-launch-persistent-context ,
// https://playwright.dev/docs/locators
import { mkdirSync } from 'node:fs';
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, fillValue, formMeta, isForm, valueText } from '../lib/console-answers';
import { consoleReached, type FieldDef, type FormDef, formDef, forbiddenControl, isSignInUrl, type Name } from '../lib/console-forms';
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 { log, printJson, warn } from '../lib/log';
import { launchPersistent } from '../shots/browser';
import { type ConsoleBrowser, openConsoleBrowser } from './session';
/* eslint-disable @typescript-eslint/no-explicit-any */
type Page = any;
@ -196,7 +201,160 @@ export async function signInPage(page: Page): Promise<boolean> {
try { return (await page.locator('input[type="password"]').count()) > 0; } catch { return false; }
}
const active = (context: any): Page | undefined => { const ps = context.pages(); return ps[ps.length - 1]; };
// ---- 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> {
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()));
}
/**
* The navigation click gate: reads the element's real accessible name and role and refuses it unless navAllowed says
* so (the click gate stays absolute: never Save / Submit / Publish / Create / Send / Next ...; only a link named exactly
* Start / Manage / Başla / Yönet is let through). Every navigation click goes through here.
*/
export async function navClick(loc: Locator): Promise<{ clicked: boolean; name: string }> {
const name = await accName(loc), role = await realRole(loc);
if (!navAllowed(name, role)) { warn(TAG, `not clicking "${name}" while opening the form: storebound never presses save, submit, publish, next or similar`); return { clicked: false, name }; }
await loc.click();
return { clicked: true, name };
}
export interface NavResult {
ok: boolean;
/** Labels of the steps done (["already open"] when the form was already on the page). */
steps: string[];
/** The step that could not be done (not found in time, ambiguous, or refused by the gate). */
failed?: string;
why?: string;
/** pickApp: the matching apps when more than one matched (storebound stops and lists them). */
candidates?: string[];
}
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> {
const end = Date.now() + ms;
for (;;) {
try { const r = await fn(); if (r !== null) return r; } catch { /* navigating */ }
if (Date.now() >= end) return null;
await Bun.sleep(200);
}
}
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> {
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; });
if (box) { await box.fill(s.tokens[0]); }
}
return poll(ms, async () => {
for (const role of ['row', 'link']) {
const all = vis(page.getByRole(role));
const n = await all.count();
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));
const byName = role === 'link' && s.name !== undefined && name === s.name;
if (byToken || byName) hits.push({ loc, name });
}
if (hits.length === 1) {
const row = hits[0]!.loc;
if (role === 'row') { const inner = vis(row.getByRole('link')); if (await inner.count() >= 1) return { loc: inner.first() }; }
return { loc: row };
}
if (hits.length > 1) return { candidates: hits.map(h => h.name) };
}
return null;
});
}
async function formLink(page: Page, entry: Name[], ms: number): Promise<{ loc?: Locator; ambiguous?: boolean } | null> {
return poll(ms, async () => {
const found: { loc: Locator; key: string }[] = [];
const add = async (box: Locator) => {
const l = vis(box.getByRole('link', { name: opener }));
if (await l.count() !== 1) return;
const b = await l.boundingBox();
const key = b ? `${Math.round(b.x)},${Math.round(b.y)}` : String(found.length);
if (!found.some(f => f.key === key)) found.push({ loc: l, key });
};
for (const n of entry) {
for (const role of ['region', 'listitem', 'row', 'group', 'article']) {
const boxes = vis(page.getByRole(role, nameOpts(n)));
const c = await boxes.count();
for (let i = 0; i < c; i++) await add(boxes.nth(i));
}
if (found.length) break;
const boxes = vis(page.locator('section, li, tr, article, [role="listitem"], [role="row"], [role="region"]').filter({ hasText: n }));
const c = await boxes.count();
for (let i = 0; i < c; i++) await add(boxes.nth(i));
if (found.length) break;
}
if (found.length === 1) return { loc: found[0]!.loc };
return found.length > 1 ? { ambiguous: true } : null;
});
}
/** The wait target is on the page (a heading of `level` when given). */
async function present(page: Page, s: Extract<NavStep, { kind: 'wait' }>): Promise<boolean> {
if (s.level === undefined) return (await findAny(page, s.roles, s.names)).state !== 'none';
for (const n of s.names) if (await vis(page.getByRole('heading', { ...nameOpts(n), level: s.level })).count() > 0) return true;
return false;
}
/**
* 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.
*/
export async function navigate(page: Page, plan: NavStep[], opts: { timeoutMs?: number; say?: (m: string) => void } = {}): Promise<NavResult> {
const ms = opts.timeoutMs ?? 20_000, say = opts.say ?? ((m: string) => log(TAG, m));
const steps: string[] = [];
const target = plan.at(-1);
if (target?.kind === 'wait' && await present(page, target).catch(() => false)) {
say(`the form is already open (${target.label})`);
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()) {
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');
}
steps.push(s.label);
}
return { ok: true, steps };
}
function printText(res: ConsoleResult): void {
console.log(`${res.title}\n${res.url}\n`);
@ -216,6 +374,7 @@ 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');
@ -230,35 +389,51 @@ export async function run(ctx: Ctx): Promise<void> {
for (const d of DISCLAIMER) say(d);
const startUrl = args.get('start-url');
if (startUrl && !/^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?\//.test(startUrl)) throw new Error('--start-url: only a local test page (http://127.0.0.1:<port>/...)');
const ownProfile = args.has('profile') || !!process.env.STOREBOUND_CONSOLE_PROFILE;
const dir = args.get('profile') ?? process.env.STOREBOUND_CONSOLE_PROFILE ?? join(homedir(), '.storebound', 'console-profile', meta.store);
mkdirSync(dir, { recursive: true });
const context = await launchPersistent(root, dir, { headless: false, viewport: null });
let closed = false;
const closing = new Promise<void>(r => context.on('close', () => { closed = true; r(); }));
const page = context.pages()[0] ?? await context.newPage();
const b = await openConsoleBrowser(root, {
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); }
async function fillRun(b: ConsoleBrowser): Promise<void> {
const active = (): Page | undefined => b.pages().at(-1);
const page = b.page;
await page.goto(startUrl ?? meta.url).catch(() => { /* the owner can navigate */ });
// 1. sign-in: the owner does it; storebound only watches the URL
const deadline = Date.now() + 10 * 60_000;
let told = false;
while (!closed && Date.now() < deadline) {
const p = active(context);
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);
}
// 2. fill section by section as the owner moves through the form
const def = formDef(form, res.answers);
const pageAnswers = res.answers.map(a => ({ ...a, value: fillValue(form, a, config) }));
const def = formDef(fid, res.answers);
const pageAnswers = res.answers.map(a => ({ ...a, value: fillValue(fid, 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;
for (const o of meta.open) say(`open the form: ${o}`);
// 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`);
const last = def.sections.length - 1;
const finished = () => done.size === def.sections.length || (form !== 'apple-app-privacy' && done.has(last));
while (!closed && !finished()) {
const p = active(context);
while (!b.isClosed() && !finished()) {
const p = active();
if (!p || await signInPage(p).catch(() => true)) { await Bun.sleep(1500); continue; }
let s: FillStep;
try { s = await fillPage(p, def, pageAnswers, done); } catch { await Bun.sleep(1500); continue; } // navigating
@ -275,8 +450,9 @@ export async function run(ctx: Ctx): Promise<void> {
}
await Bun.sleep(1500);
}
if (!closed && !fallback) say(`review every field and press ${meta.stopBefore} yourself. storebound never saves, submits or publishes. Close the window when done.`);
else if (!closed) say('close the browser window when done');
await closing;
if (json) printJson({ ...res, filled, highlighted, fallback, stoppedAt: meta.stopBefore });
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 });
}
}

227
cli/console/session.ts Normal file
View file

@ -0,0 +1,227 @@
// The browser `storebound console fill` works in, picked so the owner signs in as rarely as possible (the log says which):
// (a) attach: Chrome already runs with remote debugging (a DevToolsActivePort file in its user data dir, or
// --cdp http://127.0.0.1:<port>): connectOverCDP and one new tab in that session; storebound closes only its tab.
// (b) copy (default on macOS when Google Chrome is installed): a temporary profile with ONLY `Local State` and the
// profile's `Cookies` (+ `Cookies-journal`), filtered down to the cookies App Store Connect and Play Console use
// (apple.com, google.com domains: appstoreconnect / idmsa / play / accounts), opened in real Google Chrome
// (Chrome 136+ refuses automation on its default user data dir, a copy is fine). Chrome decrypts the cookies with
// its own Keychain key ("Chrome Safe Storage"); macOS may ask once to allow that. Never copied: passwords
// (Login Data), history, extensions, anything else. The temporary profile is deleted when the run ends (also on
// an error, Ctrl+C or when the desktop app cancels). `--chrome-profile <dir name>` picks a profile ("Profile 1");
// 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.
// 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
// https://playwright.dev/docs/api/class-browsertype
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { homedir, tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { chromiumFor, launchPersistent } from '../shots/browser';
/* eslint-disable @typescript-eslint/no-explicit-any */
/** Hosts whose cookies the consoles need; a cookie is kept when its domain applies to one of them. */
export const CONSOLE_HOSTS = ['appstoreconnect.apple.com', 'idmsa.apple.com', 'apple.com', 'play.google.com', 'accounts.google.com'];
/** Files of a Chrome profile that are never copied (passwords, history, extensions, form data ...). */
export const NEVER_COPY = /(^|\/)(Login Data|History|Extensions|Web Data|Bookmarks|Sessions|Preferences|Secure Preferences|Local Storage|IndexedDB|Account Web Data)/;
/** Google Chrome's user data dir on this OS. */
export function chromeDataDir(platform: string = process.platform, home: string = homedir(), env: Record<string, string | undefined> = process.env): string {
if (platform === 'darwin') return join(home, 'Library', 'Application Support', 'Google', 'Chrome');
if (platform === 'win32') return join(env.LOCALAPPDATA ?? join(home, 'AppData', 'Local'), 'Google', 'Chrome', 'User Data');
return join(env.XDG_CONFIG_HOME ?? join(home, '.config'), 'google-chrome');
}
/** The profile dir name: --chrome-profile, else Local State's last used profile, else Default. */
export function pickProfile(localState: string | null, requested?: string): string {
if (requested) {
if (!/^[\w .-]+$/.test(requested) || requested.includes('..')) throw new Error('--chrome-profile: a profile folder name such as "Default" or "Profile 1"');
return requested;
}
try { const last = JSON.parse(localState ?? '{}')?.profile?.last_used; if (typeof last === 'string' && /^[\w .-]+$/.test(last) && !last.includes('..')) return last; } catch { /* default */ }
return 'Default';
}
/**
* The files the copy takes, as [source relative to the user data dir, destination relative to the temp dir]: Local
* State and the profile's cookie store (Cookies, or Network/Cookies on newer layouts) with its journal. The profile
* always lands in `Default` of the temp dir. Nothing else, ever.
*/
export function sessionFiles(profile: string, exists: (rel: string) => boolean): [string, string][] {
const out: [string, string][] = [];
if (exists('Local State')) out.push(['Local State', 'Local State']);
for (const sub of ['', 'Network/']) {
const db = `${profile}/${sub}Cookies`;
if (!exists(db)) continue;
out.push([db, `Default/${sub}Cookies`]);
if (exists(`${db}-journal`)) out.push([`${db}-journal`, `Default/${sub}Cookies-journal`]);
}
for (const [s] of out) if (NEVER_COPY.test(s)) throw new Error(`session copy: refusing to copy ${s}`);
return out;
}
/** A cookie stored for `hostKey` (".google.com" or "play.google.com") is sent to one of `hosts`. */
export function cookieApplies(hostKey: string, hosts: string[] = CONSOLE_HOSTS): boolean {
const d = hostKey.replace(/^\./, '').toLowerCase();
if (!d.includes('.')) return false; // never a whole top-level domain
return hosts.some(h => h === d || h.endsWith(`.${d}`));
}
/** Deletes every cookie of the copied DB that the consoles never get. Returns counts only (never values or names). */
export async function filterCookies(dbPath: string, hosts: string[] = CONSOLE_HOSTS): Promise<{ kept: number; removed: number }> {
const { Database } = await import('bun:sqlite');
const db = new Database(dbPath);
try {
const keys = (db.query('SELECT DISTINCT host_key AS h FROM cookies').all() as { h: string }[]).map(r => r.h);
const drop = keys.filter(k => !cookieApplies(k, hosts));
const count = (db.query('SELECT COUNT(*) AS n FROM cookies').get() as { n: number }).n;
const del = db.prepare('DELETE FROM cookies WHERE host_key = ?');
db.transaction(() => { for (const k of drop) del.run(k); })();
const kept = (db.query('SELECT COUNT(*) AS n FROM cookies').get() as { n: number }).n;
db.exec('VACUUM');
return { kept, removed: count - kept };
} finally { db.close(); }
}
export interface SessionCopy { dir: string; profile: string; files: string[]; filtered: boolean; kept?: number; cleanup: () => void }
/**
* Copies the session files of `src` (a Chrome user data dir) into a new temp dir and filters the cookies to `hosts`.
* On any error the temp dir is removed before the error is thrown.
*/
export async function copySession(src: string, opts: { profile?: string; hosts?: string[]; tmpRoot?: string } = {}): Promise<SessionCopy> {
const ls = existsSync(join(src, 'Local State')) ? readFileSync(join(src, 'Local State'), 'utf8') : null;
const profile = pickProfile(ls, opts.profile);
const files = sessionFiles(profile, rel => existsSync(join(src, rel)));
if (!files.some(([s]) => s.endsWith('Cookies'))) throw new Error(`no Chrome cookie store in profile "${profile}"`);
const dir = mkdtempSync(join(opts.tmpRoot ?? tmpdir(), 'storebound-chrome-'));
const cleanup = () => {
// Chrome may still write a file while it exits: retry, and only stop once the folder is gone
for (let i = 0; i < 5 && existsSync(dir); i++) { try { rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 }); } catch { Bun.sleepSync(100); } }
};
try {
for (const [s, d] of files) { mkdirSync(dirname(join(dir, d)), { recursive: true }); copyFileSync(join(src, s), join(dir, d)); }
let filtered = false, kept: number | undefined;
try {
for (const [, d] of files.filter(([, d]) => d.endsWith('Cookies'))) kept = (kept ?? 0) + (await filterCookies(join(dir, d), opts.hosts)).kept;
filtered = true;
} catch { /* the whole cookie store stays (said in the log) */ }
return { dir, profile, files: files.map(([s]) => s), filtered, ...(kept !== undefined ? { kept } : {}), cleanup };
} catch (e) { cleanup(); throw e; }
}
/** The DevTools endpoint of a Chrome running with remote debugging (its DevToolsActivePort file), or null. */
export function devToolsEndpoint(dataDir: string): string | null {
try {
const [port] = readFileSync(join(dataDir, 'DevToolsActivePort'), 'utf8').split('\n');
return port && /^\d+$/.test(port.trim()) ? `http://127.0.0.1:${port.trim()}` : null;
} catch { return null; }
}
const LOCAL_CDP = /^(https?|wss?):\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?(\/|$)/;
export type BrowserMode = 'attach' | 'copy' | 'profile';
export interface ConsoleBrowser {
mode: BrowserMode;
context: any;
/** The tab storebound works in. */
page: any;
/** The tabs storebound may look at (its own tab and the popups it opened; in copy / profile mode every tab). */
pages: () => any[];
/** Resolves when the owner closed the window (copy / profile) or storebound's tab (attach). */
closed: Promise<void>;
isClosed: () => boolean;
/** 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). */
tempDir?: string;
}
export interface OpenOpts {
store: 'apple' | 'play';
/** --cdp: a local DevTools endpoint to attach to. */
cdp?: string;
/** --chrome-profile. */
chromeProfile?: string;
/** --fresh-profile: skip attach and copy. */
fresh?: boolean;
/** storebound's own profile dir (mode c). */
profileDir: string;
/** Overrides for tests: Chrome's user data dir, the hosts kept, headless, the platform. */
chromeDir?: string;
hosts?: string[];
headless?: boolean;
platform?: string;
say: (m: string) => void;
}
function wrapContext(mode: BrowserMode, context: any, page: any, cleanup: () => void): ConsoleBrowser {
let closed = false;
const done = new Promise<void>(r => context.on('close', async () => {
closed = true;
cleanup();
await Bun.sleep(300); // a late write of the exiting browser
cleanup();
r();
}));
return { mode, context, page, pages: () => context.pages(), closed: done, isClosed: () => closed, cleanup };
}
/** Opens the browser in the first mode that works: attach, copy, then storebound's own profile. */
export async function openConsoleBrowser(root: string, o: OpenOpts): Promise<ConsoleBrowser> {
const chromeDir = o.chromeDir ?? chromeDataDir(o.platform);
if (!o.fresh) {
// (a) attach to a running Chrome with remote debugging
if (o.cdp && !LOCAL_CDP.test(o.cdp)) throw new Error('--cdp: only a local DevTools endpoint (http://127.0.0.1:<port>)');
const endpoint = o.cdp ?? devToolsEndpoint(chromeDir);
if (endpoint) {
try {
const c = await chromiumFor(root);
const browser = await c.connectOverCDP(endpoint, { timeout: 5000 });
const context = browser.contexts()[0] ?? await browser.newContext();
const page = await context.newPage();
const own = new Set<any>([page]);
page.on('popup', (p: any) => own.add(p));
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 */ } };
} 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');
}
}
// (b) a copy of only the session files, opened in real Google Chrome
if ((o.platform ?? process.platform) === 'darwin' && existsSync(chromeDir)) {
let copy: SessionCopy | null = null;
try {
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,
// 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 cp = copy;
return { ...wrapContext('copy', context, page, () => cp.cleanup()), tempDir: cp.dir };
} catch (e) {
copy?.cleanup();
o.say(`browser: could not use your Chrome sign-in (${(e as Error).message.split('\n')[0]}); using storebound's own profile`);
}
}
}
// (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 });
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();
return wrapContext('profile', context, page, () => { /* kept on purpose */ });
}