console fill: walk the whole form; the owner only reviews and presses the final button

App Privacy stopped at "now click Get Started yourself" and every page
asked the owner to click Next. The owner should not click what
storebound can safely do.

- Every button of every console form is classified (navigation,
  draft-save, final-submit) in FORM_BUTTONS (cli/lib/console-forms.ts),
  citing Apple's and Google's help pages. A scoped flow gate
  (flowAllowed) lets navigation through; the generic click gate stays
  absolute for field clicks.
- App Privacy: Get Started, Edit next to Data Types (never the Privacy
  Policy Edit), each data type / "Set Up <type>", Next, and the Save
  inside the questionnaire dialogs (a draft: Apple publishes only after
  Publish, per "Manage app privacy"). Each type's dialog may be one page
  or purposes > Next > linked > Next > tracking > Save. It ends with
  "review the summary, then press Publish yourself". Publish is never
  clicked.
- Play content rating and target audience: Next by itself. Save draft,
  Submit, the final Save, Create and Create app stay the owner's.
- An uncertain answer stops the walk on its page (outlined, "answer
  needed on ...") until the owner has set it; then it goes on.

Fixture apple-app-privacy-flow.html (first time, ?existing=1, decoys);
tests/console-flow.test.ts with the guardrail that no log line asks the
owner to click a navigation control.
This commit is contained in:
CRTkafa 2026-10-11 22:51:01 +00:00
parent 0c2261cb33
commit 955832af4f
23 changed files with 662 additions and 56 deletions

View file

@ -29,7 +29,7 @@ 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 type { ShipConfig } from '../lib/config';
import { ALL_APPS, consoleReached, CREATE_FORM_FIELD, createAppAllowed, type FieldDef, type FormDef, formDef, FORM_OPENERS, forbiddenControl, hasToken, isSignInText, isSignInUrl, type Name, navAllowed, type NavBases, type NavStep, navPlan } from '../lib/console-forms';
import { ALL_APPS, APP_PRIVACY_HEADING, consoleReached, CREATE_FORM_FIELD, createAppAllowed, DATA_TYPES_HEADING, type FieldDef, FLOW_NAMES, flowAllowed, flowClass, type FlowWhere, type FormDef, formDef, FORM_OPENERS, forbiddenControl, hasToken, isSignInText, isSignInUrl, type Name, navAllowed, type NavBases, type NavStep, navPlan } from '../lib/console-forms';
import { log, printJson, warn } from '../lib/log';
import { openAcross, withAccountIds } from './accounts';
import { appleAppId, withAppleAppId } from './app-id';
@ -122,6 +122,10 @@ export async function highlight(loc: Locator, text = CHECK): Promise<void> {
const box = (el.tagName === 'INPUT' && el.closest('label')) || el;
if (box.getAttribute('data-storebound-check')) return;
box.setAttribute('data-storebound-check', '1');
// the owner answering it (a click, a choice, typing) is what the flow waits for before it moves on
const answered = () => { box.setAttribute('data-storebound-answered', '1'); el.setAttribute('data-storebound-answered', '1'); };
el.addEventListener('change', answered);
el.addEventListener('input', answered);
box.style.outline = '3px solid #d93025';
box.style.outlineOffset = '2px';
const s = el.ownerDocument.createElement('span');
@ -173,6 +177,10 @@ export interface FillStep {
/** Fields of the section that could not be located (UI change) -> fallback. */
missing: string[];
fallback: boolean;
/** A control of the filled section (the flow finds its dialog and its Next / Save from it). */
anchor?: Locator;
/** Per uncertain answer (agreements left out), its outlined controls: the flow waits until the owner set each one. */
pending?: Locator[][];
}
/**
@ -193,24 +201,29 @@ export async function fillPage(page: Page, def: FormDef, answers: Answer[], done
}
const rs: Resolved[] = [];
for (const f of sec.fields) rs.push(await resolve(root, f));
if (!sec.dialog && !rs.some(r => r.seen)) continue;
if ((!sec.dialog || sec.page) && !rs.some(r => r.seen)) continue;
const missing = rs.filter(r => !r.ok).map(r => r.field.id);
// only when no field of the section can be found is it a UI change; otherwise fill what was found and leave the
// missing fields to the owner (reported as "check")
// (a page still loading can also miss a field for a moment: the caller retries before it passes partial = true)
if (missing.length && (!partial || missing.length === rs.length)) return { section: i, title: sec.title, filled: [], highlighted: [], missing, fallback: true };
const filled: string[] = [], highlighted: string[] = [...missing];
const filled: string[] = [], highlighted: string[] = [...missing], pending: Locator[][] = [];
let anchor: Locator | undefined;
for (const r of rs) {
if (!r.ok) continue;
anchor ??= r.loc ?? Object.values(r.options ?? {})[0];
const a = byId.get(r.field.id);
if (!a) continue;
// an agreement is never ticked, whatever the answer says: highlighted for the owner
if (r.field.agreement || a.agreement) { await mark(r, 'storebound: you agree to this, never ticked'); highlighted.push(a.id); continue; }
const set = a.certain && a.value !== null ? await setField(r, a.value) : false;
if (set) { filled.push(a.id); if (a.ownerCheck) await mark(r, 'storebound: owner check'); } else { await mark(r); highlighted.push(a.id); }
if (set) { filled.push(a.id); if (a.ownerCheck) await mark(r, 'storebound: owner check'); } else {
await mark(r); highlighted.push(a.id);
pending.push(r.loc ? [r.loc] : Object.values(r.options ?? {}));
}
}
done.add(i);
return { section: i, title: sec.title, filled, highlighted, missing, fallback: false };
return { section: i, title: sec.title, filled, highlighted, missing, fallback: false, ...(anchor ? { anchor } : {}), pending };
}
return { section: null, filled: [], highlighted: [], missing: [], fallback: false };
}
@ -281,6 +294,66 @@ export async function createAppHere(loc: Locator, name: string, role: string): P
return createAppAllowed(name, role, { appList, formOpen, inForm });
}
// ---- walking a form: Next between pages, App Privacy's openers and its draft Save (console-forms.ts FORM_BUTTONS) ----
/** Where a control sits: in a dialog, in App Privacy's Data Types section, on the App Privacy page. Read-only. */
export async function flowWhere(loc: Locator, dataTypes: string[]): Promise<FlowWhere> {
const page: Page = loc.page();
const privacyPage = (await findAny(page, ['heading'], APP_PRIVACY_HEADING)).state !== 'none';
const dt = DATA_TYPES_HEADING.filter((n): n is string => typeof n === 'string');
const r: { inDialog: boolean; inDataTypes: boolean } = await loc.evaluate((el: any, names: string[]) => {
const inDialog = !!el.closest('[role="dialog"], dialog');
let inDataTypes = false;
// the nearest container around the control that has a heading decides: its first heading is "Data Types"
for (let a = el.parentElement; a && a !== el.ownerDocument.body; a = a.parentElement) {
const h = a.querySelector('h1, h2, h3, h4, h5, h6, [role="heading"]');
if (!h) continue;
inDataTypes = names.includes((h.textContent ?? '').trim().replace(/\s+/g, ' '));
break;
}
return { inDialog, inDataTypes };
}, dt);
return { privacyPage, dataTypes, ...r };
}
/**
* The flow click gate (flowAllowed): a navigation control of the form, or App Privacy's in-dialog Save (a draft, public
* only after the owner's Publish). Reads the real name, role and place of the control; logs the click.
*/
export async function flowClick(loc: Locator, form: FormId, dataTypes: string[], say: (m: string) => void): Promise<boolean> {
const name = await accName(loc), role = await realRole(loc);
const where = await flowWhere(loc, dataTypes);
if (!flowAllowed(form, name, role, where)) { warn(TAG, `not clicking "${name}": only the owner presses it`); return false; }
await loc.click();
say(`clicked "${name}" (${flowClass(form, name, role, where)})`);
return true;
}
/** Visible controls named like `names` (buttons and links) that sit where `ok` says; the one match, or null. */
async function controlWhere(root: Locator, names: Name[], ok: (w: FlowWhere) => boolean, dataTypes: string[]): Promise<Locator | null> {
const hits: Locator[] = [];
for (const role of ['button', 'link']) {
for (const n of names) {
const all = vis(root.getByRole(role, nameOpts(n)));
const c = await all.count();
for (let i = 0; i < c; i++) { const l = all.nth(i); if (ok(await flowWhere(l, dataTypes))) hits.push(l); }
}
}
return hits.length === 1 ? hits[0]! : null;
}
/** Every outlined control of each uncertain answer has been set by the owner (a click, a choice, typing). Read-only. */
async function answered(pending: Locator[][]): Promise<boolean> {
for (const field of pending) {
let any = false;
for (const l of field) {
if (await l.evaluate((el: any) => el.getAttribute('data-storebound-answered') === '1' || (el.closest('label')?.getAttribute('data-storebound-answered') === '1')).catch(() => false)) { any = true; break; }
}
if (!any) return false;
}
return true;
}
export interface NavResult {
ok: boolean;
/** Labels of the steps done (["already open"] when the form was already on the page). */
@ -563,7 +636,9 @@ export interface FillSessionOpts {
* 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.
* 4. fills section by section and moves on by itself: Next (App Privacy: Get Started / Edit next to Data Types, each
* data type, and the draft Save of its dialogs). An uncertain answer stops it on that page until the owner set it.
* The final button (Publish, Submit, Save, Create) and agreements stay the owner's.
*/
export async function fillSession(b: ConsoleBrowser, o: FillSessionOpts): Promise<{ filled: number; highlighted: number; fallback: boolean }> {
const { form, config, say, startUrl } = o;
@ -622,7 +697,7 @@ export async function fillSession(b: ConsoleBrowser, o: FillSessionOpts): Promis
}
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.ok) return; // the form (App Privacy: its page) is open; the flow below goes on from there
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)}`;
@ -646,7 +721,74 @@ export async function fillSession(b: ConsoleBrowser, o: FillSessionOpts): Promis
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));
const privacy = form === 'apple-app-privacy';
/** App Privacy: the data types storebound answers (their entries in the Data Types section open their questions). */
const dataTypes = [...new Set(def.sections.map(x => x.type).filter((t): t is string => !!t))];
/** The page was filled: its Next (App Privacy: Next, else the dialog's draft Save) is clicked when nothing waits. */
let pendingAdvance = false;
/** A control of the last filled section (its dialog / page holds the Next or Save to press). */
let anchor: Locator | undefined;
/** Uncertain answers on the page: storebound stops here until the owner set them (never clicks Next past them). */
let waitFor: { title: string; pending: Locator[][] } | null = null;
/** App Privacy openers clicked (each at most twice: a click that opens nothing is a UI change). */
const opened = new Map<string, number>();
let askedCollects = false;
const finished = () => !pendingAdvance && !waitFor && (done.size === def.sections.length || (!privacy && done.has(last)));
/** The dialog of the last filled section when it is still visible, else null. */
const anchorDialog = async (): Promise<Locator | null> => {
if (!anchor) return null;
const d = vis(anchor.locator('xpath=ancestor-or-self::*[@role="dialog" or local-name()="dialog"][1]'));
return (await d.count().catch(() => 0)) === 1 ? d : null;
};
/** The Next of the page (App Privacy: of the questionnaire dialog). */
const nextControl = async (p: Page): Promise<Locator | null> => {
const d = await anchorDialog();
if (privacy && !d) return null;
return controlWhere(d ?? p, FLOW_NAMES.next, w => !privacy || w.inDialog, dataTypes);
};
/** Moves on after a filled page: Next, else (App Privacy) the dialog's draft Save. true when something was clicked. */
async function advance(p: Page): Promise<boolean> {
const next = await nextControl(p);
if (next) return flowClick(next, form, dataTypes, say);
const d = privacy ? await anchorDialog() : null;
if (!d) return false;
const save = await controlWhere(d, FLOW_NAMES.save, w => w.inDialog && w.privacyPage, dataTypes);
return save ? flowClick(save, form, dataTypes, say) : false;
}
/** App Privacy with no dialog open: opens the next part (Get Started, Edit next to Data Types, the next data type). */
async function privacyStep(p: Page): Promise<void> {
if (await vis(p.getByRole('dialog')).count() > 0) return; // a dialog is open: it is filled, or the owner works in it
if ((await findAny(p, ['heading'], APP_PRIVACY_HEADING)).state === 'none') return;
const open = async (key: string, what: string, loc: Locator | null): Promise<void> => {
if (!loc) return;
const n = opened.get(key) ?? 0;
if (n === 2) { opened.set(key, 3); warn(TAG, `${what} did not open after two clicks: the console UI may have changed. Open it yourself; storebound fills it when it appears`); }
if (n >= 2) return;
opened.set(key, n + 1);
await flowClick(loc, form, dataTypes, say);
};
const editTypes = () => controlWhere(p, FLOW_NAMES.edit, w => w.inDataTypes && !w.inDialog, dataTypes);
if (!done.has(0)) {
const start = await controlWhere(p, FLOW_NAMES.getStarted, w => w.privacyPage && !w.inDialog, dataTypes);
if (start) return open('get-started', 'Get Started', start);
const edit = await editTypes();
if (!edit) return;
const c = pageAnswers.find(x => x.id === 'collects');
if (!(c?.certain && c.value === true)) {
if (!askedCollects) { askedCollects = true; say(`answer needed: ${c?.label ?? 'Data collection'} (the page lists data types, the config does not prove the answer is yes)`); }
return;
}
done.add(0);
say('Data collection was answered before (the page lists data types): storebound opens the data types with Edit');
return open('edit', 'Edit next to Data Types', edit);
}
const typesAt = def.sections.findIndex(x => x.title === 'Data types');
if (typesAt >= 0 && !done.has(typesAt)) return open('edit-types', 'Edit next to Data Types', await editTypes());
const t = def.sections.find((x, i) => x.type && !done.has(i))?.type;
if (t) return open(`type:${t}`, t, await controlWhere(p, [t, `Set Up ${t}`, `${t} ayarla`], w => w.inDataTypes && !w.inDialog, dataTypes));
}
let signedOut = false, misses = 0, firstMiss = 0;
while (!b.isClosed() && !finished()) {
const p = active();
@ -694,11 +836,33 @@ export async function fillSession(b: ConsoleBrowser, o: FillSessionOpts): Promis
}
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');
anchor = s.anchor;
// the last page of a Play / App Store form without a Next ends the run: its button is the owner's (Save, Submit, Create)
const ends = !privacy && s.section === last && !await nextControl(p).catch(() => null);
pendingAdvance = !ends;
const open = ends ? [] : (s.pending ?? []);
waitFor = open.length ? { title: s.title ?? '', pending: open } : null;
if (waitFor) {
const need = s.highlighted.filter(id => !pageAnswers.find(a => a.id === id)?.agreement);
say(`answer needed on "${s.title}": ${need.map(id => labels.get(id) ?? id).join('; ')}. Answer ${need.length === 1 ? 'it' : 'each one'} in the browser (outlined in red); storebound goes on by itself once every outlined answer is set (a box that stays empty: click it twice)`);
}
continue; // more of the form may be on this page
}
if (waitFor) {
if (!await answered(waitFor.pending)) { await Bun.sleep(tick); continue; }
say(`"${waitFor.title}" answered: storebound goes on`);
waitFor = null;
}
if (pendingAdvance) {
pendingAdvance = false;
if (await advance(p).catch(() => false)) { await Bun.sleep(tick); continue; }
}
if (privacy) await privacyStep(p).catch(() => { /* navigating */ });
await Bun.sleep(tick);
}
if (!b.isClosed() && !fallback) say(`review every field and press ${meta.stopBefore} yourself. storebound never saves, submits or publishes. Close the window when done.`);
if (!b.isClosed() && !fallback) say(privacy
? 'review the summary, then press Publish yourself. storebound saved the answers as a draft (Save in each dialog); nothing is public until you press Publish. Close the window when done.'
: `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;
return { filled, highlighted, fallback };