300 lines
19 KiB
TypeScript
300 lines
19 KiB
TypeScript
// 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.
|
|
// play-app-record (Create app) is a FIRST create: no account has the package yet, so the account is picked, not
|
|
// searched: play.developerId / the workspace's id / the cache, else the one account the login sees, else the
|
|
// chooser entry named exactly play.developerAccount. Ambiguous or not set -> storebound stops and lists them.
|
|
// 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;
|
|
}
|
|
}
|
|
|
|
/** Play account names compare by whole name, spaces and case aside. */
|
|
const sameName = (a: string, b: string) => a.trim().replace(/\s+/g, ' ').toLocaleLowerCase('tr') === b.trim().replace(/\s+/g, ' ').toLocaleLowerCase('tr');
|
|
|
|
/**
|
|
* play-app-record: the developer account to create the app in. Never guessed among several: play.developerId (or the
|
|
* workspace's STOREBOUND_PLAY_DEVELOPER_ID, or the remembered one for this package), else the only account the login
|
|
* sees, else the chooser entry named play.developerAccount. Remembered under play.packageName once the form is open.
|
|
*/
|
|
async function pickPlayAccount(page: Page, config: ShipConfig, o: AcrossOpts, cache: AccountsCache, file: string,
|
|
nav: (plan: NavStep[], ms?: number) => Promise<NavResult>, quick: number, stop: Stop): Promise<{ nav: NavResult; plan: NavStep[] }> {
|
|
const say = o.say, bases = o.bases ?? NAV_BASES, pkg = config.play?.packageName, want = config.play?.developerAccount;
|
|
const planFor = (id?: string) => navPlan(o.form, id ? { ...config, play: { ...config.play!, developerId: id } } : config, bases);
|
|
const go = async (id: string, account?: string) => {
|
|
const plan = planFor(id), r = await nav(plan);
|
|
if (r.ok && pkg) rememberPlay(pkg, { developerId: id, ...(account ? { account } : {}) }, file);
|
|
return { nav: r, plan };
|
|
};
|
|
const known = config.play?.developerId ?? (pkg ? cache.play[pkg]?.developerId : undefined);
|
|
if (known) { say(`creating the app in developer account ${known}${config.play?.developerId ? ' (play.developerId)' : ` (remembered in ${file})`}`); return go(known, pkg ? cache.play[pkg]?.account : undefined); }
|
|
const all = await playAccounts(page, bases.play, quick, stop);
|
|
const list = all.map(a => a.name ? `${a.name} (${a.id})` : a.id).join(', ');
|
|
const stopHere = (why: string) => ({ nav: { ok: false, steps: [], failed: 'the developer account', why, ...(all.length ? { candidates: all.map(a => a.name || a.id) } : {}) } as NavResult, plan: planFor() });
|
|
if (want) {
|
|
const hits = all.filter(a => a.name && sameName(a.name, want));
|
|
if (hits.length === 1) { say(`creating the app in developer account "${hits[0]!.name}" (play.developerAccount)`); return go(hits[0]!.id, hits[0]!.name); }
|
|
return stopHere(hits.length ? `more than one developer account is named "${want}" (${list}): set play.developerId`
|
|
: `no developer account named "${want}" (play.developerAccount) on the chooser${all.length ? `: ${list}` : ''}. Set play.developerAccount to one of them, or play.developerId`);
|
|
}
|
|
if (all.length === 1) { say(`this Google login has one developer account: ${all[0]!.name || all[0]!.id}`); return go(all[0]!.id, all[0]!.name || undefined); }
|
|
if (all.length > 1) return stopHere(`this Google login sees ${all.length} developer accounts (${list}): set play.developerAccount (the name) or play.developerId to pick the one for the new app`);
|
|
return stopHere('could not read the developer accounts on the "Choose a developer account" page: set play.developerId (or play.developerAccount)');
|
|
}
|
|
|
|
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' && o.form === 'play-app-record') return pickPlayAccount(page, config, o, cache, file, nav, quick, stop);
|
|
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 };
|
|
}
|