282 lines
15 KiB
TypeScript
282 lines
15 KiB
TypeScript
// AI-assisted autofill of console forms that have no API, in a visible Chromium the owner signs in to:
|
|
// storebound console fill lists the forms
|
|
// storebound console fill <form> --dry [--json] the answers and the step-by-step guidance; opens no browser
|
|
// storebound console fill <form> [--store apple|play] [--json] [--profile <dir>]
|
|
// Forms: apple-app-record, apple-age-rating (guide only: `storebound apple appinfo` sets it), apple-app-privacy,
|
|
// play-content-rating, play-target-audience. Answers come from the config only (cli/lib/console-answers.ts); anything
|
|
// 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.
|
|
// 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 { log, printJson, warn } from '../lib/log';
|
|
import { launchPersistent } from '../shots/browser';
|
|
|
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
type Page = any;
|
|
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; } };
|
|
const nameOpts = (n: Name) => (typeof n === 'string' ? { name: n, exact: true } : { name: n });
|
|
|
|
type Found = { state: 'ok'; loc: Locator } | { state: 'none' | 'ambiguous' };
|
|
|
|
async function first(tries: Locator[]): Promise<Found> {
|
|
for (const t of tries) {
|
|
const l = vis(t);
|
|
const n = await l.count();
|
|
if (n === 1) return { state: 'ok', loc: l };
|
|
if (n > 1) return { state: 'ambiguous' };
|
|
}
|
|
return { state: 'none' };
|
|
}
|
|
|
|
async function find(root: Locator, role: string, names: Name[], label = false): Promise<Found> {
|
|
for (const n of names) {
|
|
const tries = [root.getByRole(role, nameOpts(n))];
|
|
if (label) tries.push(root.getByLabel(n, typeof n === 'string' ? { exact: true } : {}));
|
|
const f = await first(tries);
|
|
if (f.state !== 'none') return f;
|
|
}
|
|
return { state: 'none' };
|
|
}
|
|
|
|
interface Resolved { field: FieldDef; ok: boolean; seen: boolean; loc?: Locator; options?: Record<string, Locator> }
|
|
|
|
async function resolve(root: Locator, f: FieldDef): Promise<Resolved> {
|
|
if (f.kind !== 'radio') {
|
|
const role = f.kind === 'text' ? 'textbox' : f.kind === 'select' ? 'combobox' : 'checkbox';
|
|
const r = await find(root, role, f.names ?? [], f.kind !== 'checkbox');
|
|
return { field: f, ok: r.state === 'ok', seen: r.state !== 'none', ...(r.state === 'ok' ? { loc: r.loc } : {}) };
|
|
}
|
|
let scope = root, seen = false;
|
|
if (f.names?.length) {
|
|
let g = await find(root, 'radiogroup', f.names);
|
|
if (g.state === 'none') g = await find(root, 'group', f.names);
|
|
if (g.state !== 'ok') return { field: f, ok: false, seen: g.state !== 'none' };
|
|
scope = g.loc; seen = true;
|
|
}
|
|
const options: Record<string, Locator> = {};
|
|
let ok = true;
|
|
for (const [v, names] of Object.entries(f.options ?? {})) {
|
|
const r = await find(scope, 'radio', names);
|
|
if (r.state === 'ok') { options[v] = r.loc; seen = true; } else { ok = false; if (r.state === 'ambiguous') seen = true; }
|
|
}
|
|
return { field: f, ok, seen, ...(f.names?.length ? { loc: scope } : {}), options };
|
|
}
|
|
|
|
/** The accessible name of a control as the page labels it (what the click gate checks). */
|
|
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(' ') : '';
|
|
const labels = el.labels ? [...el.labels].map((l: any) => l.textContent).join(' ') : '';
|
|
return el.getAttribute('aria-label') || ref || labels || el.textContent || '';
|
|
})).trim().replace(/\s+/g, ' ');
|
|
}
|
|
|
|
/**
|
|
* The single click gate: refuses any control whose name says save, submit, publish, create, next ... (English and
|
|
* Turkish). Every click storebound makes, checkboxes and radio buttons included, goes through here.
|
|
*/
|
|
export async function safeClick(loc: Locator, name: string, action: 'click' | 'check' | 'uncheck' = 'click'): Promise<boolean> {
|
|
if (forbiddenControl(name)) { warn(TAG, `not clicking "${name}": storebound never presses save, submit, publish, next or similar`); return false; }
|
|
if (action === 'click') await loc.click();
|
|
else await loc.setChecked(action === 'check');
|
|
return true;
|
|
}
|
|
|
|
/** Outline + a small "storebound: check this" label next to the element (no SVG). */
|
|
export async function highlight(loc: Locator, text = CHECK): Promise<void> {
|
|
await loc.evaluate((el: any, t: string) => {
|
|
const box = (el.tagName === 'INPUT' && el.closest('label')) || el;
|
|
if (box.getAttribute('data-storebound-check')) return;
|
|
box.setAttribute('data-storebound-check', '1');
|
|
box.style.outline = '3px solid #d93025';
|
|
box.style.outlineOffset = '2px';
|
|
const s = el.ownerDocument.createElement('span');
|
|
s.textContent = t;
|
|
s.setAttribute('data-storebound-label', '1');
|
|
s.style.cssText = 'display:inline-block;margin:2px 6px;padding:1px 6px;border-radius:4px;background:#d93025;color:#fff;font:600 12px/18px system-ui,sans-serif';
|
|
box.insertAdjacentElement('afterend', s);
|
|
}, text);
|
|
}
|
|
|
|
async function setField(r: Resolved, v: string | boolean): Promise<boolean> {
|
|
const f = r.field;
|
|
if (f.kind === 'text') { await r.loc.fill(String(v)); return true; }
|
|
if (f.kind === 'checkbox') return safeClick(r.loc, await accName(r.loc), v ? 'check' : 'uncheck');
|
|
if (f.kind === 'radio') {
|
|
const o = r.options?.[String(v)];
|
|
return o ? safeClick(o, await accName(o), 'check') : false;
|
|
}
|
|
// select: only a native <select>; a custom dropdown is left to the owner (highlighted)
|
|
const idx: number = await r.loc.evaluate((el: any, want: string) => {
|
|
if (el.tagName !== 'SELECT') return -1;
|
|
const labels: string[] = [...el.options].map((o: any) => (o.label || o.textContent || '').trim());
|
|
const exact = labels.indexOf(want);
|
|
if (exact >= 0) return exact;
|
|
const near = labels.map((l, i) => [l, i] as const).filter(([l]) => l.endsWith(` - ${want}`) || l.endsWith(`(${want})`) || l.includes(want));
|
|
return near.length === 1 ? near[0]![1] : -1;
|
|
}, String(v));
|
|
if (idx < 0) return false;
|
|
await r.loc.selectOption({ index: idx });
|
|
return true;
|
|
}
|
|
|
|
async function mark(r: Resolved): Promise<void> {
|
|
if (r.loc) return highlight(r.loc);
|
|
for (const o of Object.values(r.options ?? {})) await highlight(o);
|
|
}
|
|
|
|
export interface FillStep {
|
|
/** Index of the section filled (or that triggered the fallback); null when no unfilled section is on the page. */
|
|
section: number | null;
|
|
title?: string;
|
|
filled: string[];
|
|
highlighted: string[];
|
|
/** Fields of the section that could not be located (UI change) -> fallback. */
|
|
missing: string[];
|
|
fallback: boolean;
|
|
}
|
|
|
|
/**
|
|
* Fills the first section of the form that is on the page and not done yet: locate every field first; any missing or
|
|
* ambiguous field -> fallback (nothing of that section is touched). Certain answers are set, the rest is highlighted
|
|
* and left empty. Never clicks Next / Save. `answers` carry the values the page gets (fillValue).
|
|
*/
|
|
export async function fillPage(page: Page, def: FormDef, answers: Answer[], done: Set<number> = new Set()): Promise<FillStep> {
|
|
const byId = new Map(answers.map(a => [a.id, a]));
|
|
for (const [i, sec] of def.sections.entries()) {
|
|
if (done.has(i)) continue;
|
|
let root: Locator = page;
|
|
if (sec.dialog) {
|
|
const d = await find(page, 'dialog', sec.dialog);
|
|
if (d.state === 'none') continue;
|
|
if (d.state !== 'ok') return { section: i, title: sec.title, filled: [], highlighted: [], missing: [`dialog ${sec.title}`], fallback: true };
|
|
root = d.loc;
|
|
}
|
|
const rs: Resolved[] = [];
|
|
for (const f of sec.fields) rs.push(await resolve(root, f));
|
|
if (!sec.dialog && !rs.some(r => r.seen)) continue;
|
|
const missing = rs.filter(r => !r.ok).map(r => r.field.id);
|
|
if (missing.length) return { section: i, title: sec.title, filled: [], highlighted: [], missing, fallback: true };
|
|
const filled: string[] = [], highlighted: string[] = [];
|
|
for (const r of rs) {
|
|
const a = byId.get(r.field.id);
|
|
if (!a) continue;
|
|
const set = a.certain && a.value !== null ? await setField(r, a.value) : false;
|
|
if (set) filled.push(a.id); else { await mark(r); highlighted.push(a.id); }
|
|
}
|
|
done.add(i);
|
|
return { section: i, title: sec.title, 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. */
|
|
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 active = (context: any): Page | undefined => { const ps = context.pages(); return ps[ps.length - 1]; };
|
|
|
|
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}`}`);
|
|
console.log(`\n${res.uncertain} answer(s) to check yourself.\n\nSteps:\n${res.guidance.map(g => ` - ${g}`).join('\n')}`);
|
|
}
|
|
|
|
export async function run(ctx: Ctx): Promise<void> {
|
|
const { config, root } = ctx.loaded;
|
|
const args = ctx.args, json = args.has('json'), dry = args.has('dry');
|
|
const form = args._[0];
|
|
if (!form) {
|
|
const forms = FORM_IDS.map(id => { const m = formMeta(id, config); return { id, store: m.store, title: m.title, fillable: m.fillable }; });
|
|
if (json) return printJson({ forms });
|
|
console.log('storebound console fill <form> [--store apple|play] [--dry] [--json] [--profile <dir>]\n');
|
|
for (const f of forms) console.log(` ${f.id.padEnd(22)} ${f.store.padEnd(6)} ${f.title}${f.fillable ? '' : ' (guide only)'}`);
|
|
return;
|
|
}
|
|
if (!isForm(form)) throw new Error(`console fill: unknown form "${form}" (one of ${FORM_IDS.join(', ')})`);
|
|
const meta = formMeta(form, config);
|
|
const store = args.get('store');
|
|
if (store && store !== 'apple' && store !== 'play') throw new Error('--store: apple | play');
|
|
if (store && store !== meta.store) throw new Error(`console fill: ${form} is a ${meta.store} form, not ${store}`);
|
|
const res = consoleResult(form, config);
|
|
if (dry || !meta.fillable) {
|
|
if (json) return printJson(dry ? res : { ...res, filled: 0, highlighted: 0, fallback: false, stoppedAt: null });
|
|
return printText(res);
|
|
}
|
|
|
|
const say = (m: string) => (json ? console.error(`[${TAG}] ${m}`) : log(TAG, m));
|
|
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 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();
|
|
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);
|
|
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 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}`);
|
|
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);
|
|
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
|
|
if (s.section !== null) {
|
|
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:`);
|
|
for (const g of res.guidance) say(` ${g}`);
|
|
break;
|
|
}
|
|
filled += s.filled.length; highlighted += s.highlighted.length;
|
|
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);
|
|
}
|
|
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 });
|
|
}
|