storebound/tests/machine.test.ts

268 lines
18 KiB
TypeScript

// One product per machine: credential profiles shared by every project and the desktop app (precedence, `accounts
// import` dedup and file modes), the machine's app folder list, and what `storebound desktop` decides and installs.
import { describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { applyImport, planImport, useProfile } from '../cli/lib/accounts';
import { activeProfile, androidSigning, ascKey, defaultPointer, defaultProfile, playServiceAccount, reviewContact, setConfigAccount, setDefaultPointer } from '../cli/lib/credentials';
import { compareVersions, consent, decide, installPlan, isRunning, question, runningCheck } from '../cli/lib/desktop-install';
import { addFolder, folderId, parseRegistry, readRegistry, removeFolder, withFolder, withoutFolder } from '../cli/lib/registry';
import { desktopProjectId } from '../cli/lib/workspace';
const ROOT = join(import.meta.dir, '..');
const PEM = (s: string) => ['-----BEGIN PRIVATE KEY-----', s, '-----END PRIVATE KEY-----', ''].join('\n');
const SA = (email: string) => JSON.stringify({ type: 'service_account', client_email: email, private_key: PEM('play-secret-sentinel'), token_uri: 'https://oauth2.googleapis.com/token' });
/** Runs `fn` with an empty credentials folder and registry, and no store env; restores everything after. */
function machine(fn: (m: { creds: string; base: string }) => void) {
const saved = { ...process.env };
const base = mkdtempSync(join(tmpdir(), 'sb-machine-'));
try {
for (const k of Object.keys(process.env)) if (/^(ASC_|PLAY_SERVICE|STOREBOUND_PROFILE|ANDROID_)/.test(k)) delete process.env[k];
process.env.STOREBOUND_CREDENTIALS_DIR = join(base, 'credentials');
process.env.STOREBOUND_REGISTRY = join(base, 'projects.json');
fn({ creds: join(base, 'credentials'), base });
} finally {
for (const k of Object.keys(process.env)) if (!(k in saved)) delete process.env[k];
Object.assign(process.env, saved);
}
}
/** A project whose .storebound/credentials.json holds the shared store keys (as files in the project) and its own keystore. */
function project(base: string, name: string, o: { keyId?: string; email?: string } = {}): string {
const dir = join(base, name);
mkdirSync(join(dir, '.storebound'), { recursive: true });
writeFileSync(join(dir, 'storebound.config.json'), '{}');
writeFileSync(join(dir, '.storebound', `AuthKey_${o.keyId ?? 'ABCDE12345'}.p8`), PEM('apple-secret-sentinel'));
writeFileSync(join(dir, '.storebound', 'play.json'), SA(o.email ?? 'release@example.com'));
writeFileSync(join(dir, '.storebound', 'credentials.json'), JSON.stringify({
ASC_KEY_ID: o.keyId ?? 'ABCDE12345', ASC_ISSUER_ID: '00000000-0000-0000-0000-000000000000', ASC_P8: join(dir, '.storebound', `AuthKey_${o.keyId ?? 'ABCDE12345'}.p8`),
PLAY_SERVICE_ACCOUNT: join(dir, '.storebound', 'play.json'), ASC_VENDOR_NUMBER: '12345678',
ANDROID_KEYSTORE: `${name}.jks`, ANDROID_KEYSTORE_PASSWORD: `${name}-pw`, ANDROID_KEY_ALIAS: 'upload',
reviewContact: { firstName: 'Ada', lastName: 'Example', phone: '+1 555 0100', email: `review@${name}.example.org` },
}, null, 2));
return dir;
}
describe('credentials: one machine, many projects', () => {
test('accounts default <name>: a pointer file; env > project-named > project file > pointer > single profile', () => machine(({ creds, base }) => {
mkdirSync(creds, { recursive: true });
for (const n of ['teamA', 'teamB']) writeFileSync(join(creds, `${n}.json`), JSON.stringify({ ASC_KEY_ID: `${n.toUpperCase()}00000`.slice(0, 10), ASC_ISSUER_ID: 'iss', ASC_P8: PEM('x') }));
const bare = join(base, 'bare');
mkdirSync(bare);
// two profiles, none named default, no pointer: no default
expect(defaultProfile()).toBeNull();
expect(activeProfile(bare)).toBeNull();
expect(() => setDefaultPointer('nope')).toThrow(/no profile "nope"/);
setDefaultPointer('teamB');
expect(readFileSync(join(creds, 'default-profile'), 'utf8')).toBe('teamB\n');
expect(statSync(join(creds, 'default-profile')).mode & 0o777).toBe(0o600);
expect(defaultPointer()).toBe('teamB');
expect(defaultProfile()).toBe('teamB');
expect(activeProfile(bare)).toEqual({ name: 'teamB', from: 'default' });
expect(ascKey(bare).keyId).toBe('TEAMB00000');
// a pointer beats a profile named "default" and the single-profile rule
writeFileSync(join(creds, 'default.json'), JSON.stringify({ ASC_KEY_ID: 'DEFAULT000', ASC_ISSUER_ID: 'iss', ASC_P8: PEM('x') }));
expect(defaultProfile()).toBe('teamB');
// the project's own keys beat the pointer; a profile the project names beats both; env beats all
const a = project(base, 'star-dash');
expect(ascKey(a).keyId).toBe('ABCDE12345');
const file = join(a, '.storebound', 'credentials.json');
writeFileSync(file, JSON.stringify({ ...JSON.parse(readFileSync(file, 'utf8')), account: 'teamA' }));
expect(ascKey(a).keyId).toBe('TEAMA00000');
process.env.ASC_KEY_ID = 'ENV0000000';
expect(ascKey(a).keyId).toBe('ENV0000000');
delete process.env.ASC_KEY_ID;
// a pointer to a profile that is gone falls back to the old rule
writeFileSync(join(creds, 'default-profile'), 'gone\n');
expect(defaultProfile()).toBe('default');
setDefaultPointer(null);
expect(existsSync(join(creds, 'default-profile'))).toBe(false);
// the pointer file is not a profile
expect(readdirSync(creds).filter(n => n.endsWith('.json')).sort()).toEqual(['default.json', 'teamA.json', 'teamB.json']);
}));
test('project-only values from the project, store keys from the profile, env over everything', () => machine(({ creds, base }) => {
const a = project(base, 'star-dash');
// the project's own keys work without any profile
expect(ascKey(a).keyId).toBe('ABCDE12345');
mkdirSync(creds, { recursive: true });
writeFileSync(join(creds, 'other.json'), JSON.stringify({ ASC_KEY_ID: 'OTHER00000', ASC_ISSUER_ID: 'iss', ASC_P8: PEM('x') }));
// the default profile (the only one) never beats keys the project holds itself
expect(defaultProfile()).toBe('other');
expect(activeProfile(a)).toEqual({ name: 'other', from: 'default' });
expect(ascKey(a).keyId).toBe('ABCDE12345');
// a named profile does ("account" in the project file, then the config, then --account / env)
const file = join(a, '.storebound', 'credentials.json');
writeFileSync(file, JSON.stringify({ ...JSON.parse(readFileSync(file, 'utf8')), account: 'other' }));
expect(activeProfile(a)).toEqual({ name: 'other', from: 'project' });
expect(ascKey(a).keyId).toBe('OTHER00000');
setConfigAccount(a, 'nope');
expect(activeProfile(a)?.from).toBe('config');
setConfigAccount(a, undefined);
process.env.ASC_KEY_ID = 'ENV0000000';
expect(ascKey(a).keyId).toBe('ENV0000000');
delete process.env.ASC_KEY_ID;
// the app's own things never come from a profile
expect(androidSigning(a)?.keyAlias).toBe('upload');
expect(reviewContact(a)?.firstName).toBe('Ada');
// STOREBOUND_PROFILE set but empty: no profile at all
process.env.STOREBOUND_PROFILE = '';
expect(activeProfile(a)).toBeNull();
}));
test('accounts import: two projects with the same Apple key and Play account -> one profile, 0600 files, projects stay valid', () => machine(({ creds, base }) => {
const a = project(base, 'star-dash'), b = project(base, 'demo-game');
const dry = planImport(a);
expect(dry.profile).toBe('default');
expect(dry.reuse).toBe(false);
expect(dry.moved.sort()).toEqual(['ASC_ISSUER_ID', 'ASC_KEY_ID', 'ASC_P8', 'ASC_VENDOR_NUMBER', 'PLAY_SERVICE_ACCOUNT']);
expect(existsSync(creds)).toBe(false); // planning writes nothing
const r = applyImport(dry);
expect(r.backup && existsSync(r.backup)).toBeTruthy();
const files = readdirSync(join(creds, 'default')).sort();
expect(files).toEqual(['app-store-connect.p8', 'play-service-account.json']);
if (process.platform !== 'win32') {
for (const f of files) expect(statSync(join(creds, 'default', f)).mode & 0o777).toBe(0o600);
expect(statSync(join(creds, 'default.json')).mode & 0o777).toBe(0o600);
expect(statSync(join(creds, 'default')).mode & 0o777).toBe(0o700);
expect(statSync(join(a, '.storebound', 'credentials.json')).mode & 0o777).toBe(0o600);
}
// the profile refers to its key files by path; the project file keeps the app's own things and names the profile
const prof = JSON.parse(readFileSync(join(creds, 'default.json'), 'utf8'));
expect(prof.ASC_P8).toBe('default/app-store-connect.p8');
expect(JSON.stringify(prof)).not.toContain('sentinel');
const projA = JSON.parse(readFileSync(join(a, '.storebound', 'credentials.json'), 'utf8'));
expect(projA.account).toBe('default');
expect(projA.ASC_KEY_ID).toBeUndefined();
expect(projA.ANDROID_KEYSTORE).toBe('star-dash.jks');
expect(ascKey(a).pem).toContain('apple-secret-sentinel');
expect(playServiceAccount(a).client_email).toBe('release@example.com');
// the second project with the same account: the same profile, its files unchanged
const second = planImport(b);
expect(second.profile).toBe('default');
expect(second.reuse).toBe(true);
expect(second.writes.filter(w => w.path.startsWith(creds)).map(w => w.action)).toEqual(['same']);
applyImport(second);
expect(JSON.parse(readFileSync(join(b, '.storebound', 'credentials.json'), 'utf8')).ANDROID_KEYSTORE_PASSWORD).toBe('demo-game-pw');
expect(ascKey(b).keyId).toBe('ABCDE12345');
// running it again changes nothing
expect(planImport(b).writes.every(w => w.action === 'same')).toBe(true);
expect(planImport(b).notes[0]).toMatch(/already imported/);
// another team: a profile of its own; --name may not take over an existing profile's account
const c = project(base, 'other-studio', { keyId: 'ZZZZZ99999', email: 'other@example.com' });
expect(() => planImport(c, { name: 'default' })).toThrow(/another App Store Connect key/);
const third = planImport(c);
expect(third.profile).toBe('other-studio');
applyImport(third);
expect(ascKey(c).keyId).toBe('ZZZZZ99999');
expect(ascKey(a).keyId).toBe('ABCDE12345'); // "account": "default" still points star-dash at its own
expect(useProfile(c, 'default')).toContain('credentials.json');
expect(() => useProfile(c, 'missing')).toThrow(/no profile/);
}));
test('the import command prints paths and names, never key values', () => machine(({ base }) => {
const a = project(base, 'star-dash');
const r = Bun.spawnSync(['bun', join(ROOT, 'cli', 'index.ts'), 'accounts', 'import', '--dry', '--dir', a], { env: { ...process.env, STOREBOUND_NO_NETWORK: '1' } });
const out = r.stdout.toString() + r.stderr.toString();
expect(r.exitCode).toBe(0);
expect(out).toContain('profile "default"');
expect(out).not.toContain('sentinel');
expect(out).not.toContain('ABCDE12345');
const no = Bun.spawnSync(['bun', join(ROOT, 'cli', 'index.ts'), 'accounts', 'import', '--dir', a], { stdin: 'ignore', env: { ...process.env, STOREBOUND_NO_NETWORK: '1' } });
expect(no.exitCode).toBe(3); // not a terminal and no --yes
expect(existsSync(join(process.env.STOREBOUND_CREDENTIALS_DIR!, 'default.json'))).toBe(false);
}));
});
describe('the machine\'s app folder list', () => {
test('add, re-add, remove; ids are the desktop export ids; bad entries are dropped', () => machine(({ base }) => {
const r0 = { version: 1 as const, projects: [] };
const { registry, added } = withFolder(r0, '/w/star-dash', 'Star Dash', 't');
expect(added).toBe(true);
expect(registry.projects[0]!.id).toBe(desktopProjectId('/w/star-dash'));
expect(withFolder(registry, '/w/star-dash/', undefined, 't').added).toBe(false);
expect(withoutFolder(registry, folderId('/w/star-dash')).removed?.name).toBe('Star Dash');
expect(parseRegistry('{"projects":[{"path":"relative"},{"path":"/a","id":"zz"},{"path":"/a"}]}').projects.map(p => [p.path, p.id])).toEqual([['/a', folderId('/a')]]);
expect(parseRegistry('not json').projects).toEqual([]);
const dir = project(base, 'demo-game');
expect(addFolder(dir).added).toBe(true);
expect(addFolder(dir).added).toBe(false);
expect(readRegistry().projects.map(p => p.path)).toEqual([dir]);
// `storebound apps folders` reads the same file the desktop does
const out = Bun.spawnSync(['bun', join(ROOT, 'cli', 'index.ts'), 'apps', 'folders', '--json'], { env: { ...process.env, STOREBOUND_NO_NETWORK: '1' } }).stdout.toString();
expect(JSON.parse(out).projects[0].path).toBe(dir);
expect(removeFolder(dir)?.path).toBe(dir);
expect(readRegistry().projects).toEqual([]);
}));
});
describe('storebound desktop: one version with the CLI', () => {
const app = { path: '/Applications/storebound.app', how: 'bundle' as const };
test('versions compare like semver', () => {
expect(compareVersions('0.8.0', '0.8.0')).toBe(0);
expect(compareVersions('0.7.9', '0.8.0')).toBe(-1);
expect(compareVersions('0.10.0', '0.9.1')).toBe(1);
expect(compareVersions('0.8.0-beta.1', '0.8.0')).toBe(-1);
});
test('installed and the same: open; missing: install; older: update; newer: open, downgrade only with --force; nothing published', () => {
expect(decide({ installed: app, installedVersion: '0.8.0', cli: '0.8.0', available: null, force: false }).action).toBe('open');
expect(decide({ installed: null, installedVersion: null, cli: '0.8.0', available: '0.8.0', force: false })).toEqual({ action: 'install', from: null, to: '0.8.0', notes: [] });
const up = decide({ installed: app, installedVersion: '0.7.1', cli: '0.8.0', available: '0.8.0', force: false });
expect([up.action, up.from, up.to]).toEqual(['update', '0.7.1', '0.8.0']);
const newer = decide({ installed: app, installedVersion: '0.9.0', cli: '0.8.0', available: '0.8.0', force: false });
expect(newer.action).toBe('open');
expect(newer.notes[0]).toMatch(/newer than this CLI/);
expect(decide({ installed: app, installedVersion: '0.9.0', cli: '0.8.0', available: '0.8.0', force: true }).action).toBe('downgrade');
// the CLI's own version is not out yet: the newest published one, said so
const lag = decide({ installed: null, installedVersion: null, cli: '0.8.1', available: '0.8.0', force: false });
expect([lag.action, lag.to]).toEqual(['install', '0.8.0']);
expect(lag.notes.join()).toMatch(/0\.8\.0.*0\.8\.1/);
expect(decide({ installed: app, installedVersion: '0.7.0', cli: '0.8.0', available: '0.7.0', force: false }).action).toBe('open');
expect(decide({ installed: null, installedVersion: null, cli: '0.8.0', available: null, unavailableReason: 'offline', force: false })).toEqual({ action: 'unavailable', from: null, to: null, notes: ['offline'] });
});
test('no terminal and no --yes: declined (exit 3, the command printed); the question defaults to yes', () => {
expect(consent(true, false)).toBe('yes');
expect(consent(false, true)).toBe('ask');
expect(consent(false, false)).toBe('declined');
expect(question({ action: 'install', from: null, to: '0.8.0', notes: [] }, 77_000_000, '~/Applications')).toBe('Install storebound desktop 0.8.0 (77 MB) to ~/Applications? [Y/n] ');
});
const base = { file: '/tmp/x/storebound_0.8.0_universal.dmg', version: '0.8.0', home: '/Users/you', tmp: '/tmp/x', env: {}, has: () => false, systemAppsWritable: false };
test('macOS: from the read-only DMG into ~/Applications (or /Applications), no xattr, an update in place', () => {
const p = installPlan({ ...base, platform: 'darwin', kind: 'macos-universal-dmg', existing: null });
expect(p.target).toBe('/Users/you/Applications/storebound.app');
expect(p.place).toBe('~/Applications');
const runs = p.steps.flatMap(s => ('run' in s ? [s.run] : []));
expect(runs[0]).toEqual(['hdiutil', 'attach', '-nobrowse', '-readonly', '-noautoopen', '-mountpoint', '/tmp/x/mnt', base.file]);
expect(runs.some(r => r[0] === 'hdiutil' && r[1] === 'detach')).toBe(true);
expect(JSON.stringify(p.steps)).not.toContain('xattr');
expect(p.steps.some(s => 'expectVersion' in s && s.expectVersion.version === '0.8.0')).toBe(true);
expect(installPlan({ ...base, platform: 'darwin', kind: 'macos-universal-dmg', existing: null, systemAppsWritable: true }).target).toBe('/Applications/storebound.app');
const upd = installPlan({ ...base, platform: 'darwin', kind: 'macos-universal-dmg', existing: app, systemAppsWritable: false });
expect(upd.target).toBe('/Applications/storebound.app');
expect(upd.steps.map(s => Object.keys(s)[1])).toContain('remove');
});
test('Windows: the per-user NSIS installer, silent; Linux: AppImage + .desktop with the link handler; .deb only printed', () => {
const w = installPlan({ ...base, platform: 'win32', kind: 'windows-x86_64-nsis', file: 'C:\\t\\storebound_0.8.0_x64-setup.exe', existing: null, env: { LOCALAPPDATA: 'C:\\Users\\you\\AppData\\Local' } });
expect(w.steps[0]).toMatchObject({ run: ['C:\\t\\storebound_0.8.0_x64-setup.exe', '/S'] });
expect(w.target).toBe('C:\\Users\\you\\AppData\\Local\\storebound\\storebound-desktop.exe');
const l = installPlan({ ...base, platform: 'linux', kind: 'linux-x86_64-appimage', home: '/home/you', file: '/tmp/x/storebound_0.8.0_amd64.AppImage', existing: null, has: t => t === 'xdg-mime' });
expect(l.target).toBe('/home/you/.local/bin/storebound.AppImage');
const entry = l.steps.find(s => 'write' in s) as { write: { path: string; content: string } };
expect(entry.write.path).toBe('/home/you/.local/share/applications/storebound.desktop');
expect(entry.write.content).toContain('MimeType=x-scheme-handler/storebound;');
expect(entry.write.content).toContain('Exec="/home/you/.local/bin/storebound.AppImage" %u');
expect(l.steps.flatMap(s => ('run' in s ? [s.run[0]] : []))).toEqual(['xdg-mime']);
const deb = installPlan({ ...base, platform: 'linux', kind: 'linux-x86_64-deb', home: '/home/you', existing: null });
expect(deb.steps).toEqual([]);
expect(deb.manual).toMatch(/sudo apt install/);
});
test('an update never replaces a running app', () => {
expect(runningCheck('darwin')).toEqual(['pgrep', '-x', 'storebound-desktop']);
expect(isRunning('darwin', 0, '123\n')).toBe(true);
expect(isRunning('linux', 1, '')).toBe(false);
expect(isRunning('win32', 0, 'INFO: No tasks are running which match the specified criteria.')).toBe(false);
expect(isRunning('win32', 0, 'storebound-desktop.exe 4242 Console')).toBe(true);
});
});