storebound/tests/scan.test.ts
CRT 00a38cd305 storebound scan: offline rejection-risk scan of the project itself
Detects the stack (native iOS / Android, React Native, Expo, Capacitor, Cordova,
Flutter, Unity, Godot) and the SDKs from a maintained table with versions,
file:line and each vendor's disclosure page, then reports App Store and Google
Play rejection risks with guideline, evidence, fix, severity and skill: 2.1(a)
demo account and placeholder text, 5.1.1(v) account deletion, 4.8 login
services, 3.1.1 restore and outside payments, 3.1.2 subscription info, 5.1.2(i)
ATT, purpose strings, privacy link, privacy manifest, 2.3.10, 2.3.7, 2.3.8, 4.2
web wrappers, 2.5.1, 2.5.5, ATS, export compliance, 1.3 kids ads, review
prompts, privacy labels vs SDKs; Play target SDK 36, delete-account URL, App
access, foreground services, exact alarms, QUERY_ALL_PACKAGES, SMS / call log,
com.example package name.

Proposes Data safety / App Privacy / ATT / privacy manifest answers (detected
file:line or ask owner) as a diff against the config; --write adds only the
detected ones. scan.ignore records owner-accepted findings. MCP tool scan
(read-only), validate includes open findings, desktop Checks tab shows them.
Fixtures for iOS, Android, Capacitor, Unity, Flutter, clean and teaser.
2026-10-11 15:20:55 +00:00

245 lines
16 KiB
TypeScript

// storebound scan: project detection, every rejection-risk rule on the fixtures (true positives) and the clean
// fixture (no false positives), the declarations proposal and --write, validate / MCP integration, the demo projects.
import { afterAll, beforeEach, describe, expect, test } from 'bun:test';
import { cpSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { FORBIDDEN_ARGS, TOOLS, toArgv } from '../cli/mcp-tools';
import { JSON_TOOLS } from '../cli/serve';
import { scanAsFindings } from '../cli/validate';
import { matchBrace, toTs, upsertBlock } from '../cli/lib/scan/config-edit';
import { runScan } from '../cli/lib/scan';
import { vaguePurpose } from '../cli/lib/scan/permissions';
import { detectProject, parsePlist } from '../cli/lib/scan/project';
import type { ScanFinding } from '../cli/lib/scan/rules';
import { matchesSdk, SDKS, versionAtLeast } from '../cli/lib/scan/sdks';
const ROOT = join(import.meta.dir, '..');
const FX = join(import.meta.dir, 'fixtures', 'scan');
const CLI = join(ROOT, 'cli', 'index.ts');
const saved = { u: process.env.REVIEW_DEMO_USER, p: process.env.REVIEW_DEMO_PASSWORD };
beforeEach(() => { delete process.env.REVIEW_DEMO_USER; delete process.env.REVIEW_DEMO_PASSWORD; });
afterAll(() => { if (saved.u !== undefined) process.env.REVIEW_DEMO_USER = saved.u; if (saved.p !== undefined) process.env.REVIEW_DEMO_PASSWORD = saved.p; });
const scan = async (name: string) => (await runScan(join(FX, name))).report;
const rules = (f: ScanFinding[], store?: 'apple' | 'play') => new Set(f.filter(x => !x.accepted && (!store || x.store === store)).map(x => x.rule));
const find = (f: ScanFinding[], rule: string, store?: 'apple' | 'play') => f.find(x => x.rule === rule && (!store || x.store === store));
describe('project detection', () => {
test('plist reader: values, nested dicts, top-level key lines', () => {
const { value, lines } = parsePlist(readFileSync(join(FX, 'ios-native/Notes/Info.plist'), 'utf8'));
expect(value.NSPhotoLibraryUsageDescription).toBe('');
expect((value.NSAppTransportSecurity as Record<string, unknown>).NSAllowsArbitraryLoads).toBe(true);
expect(lines.get('NSAppTransportSecurity')).toBe(9);
expect(parsePlist('not a plist').value).toEqual({});
});
test('stacks, SDKs with versions and file:line from every ecosystem', () => {
const ios = detectProject(join(FX, 'ios-native'));
expect(ios.stacks).toEqual(['ios-native']);
const admob = ios.sdks.find(s => s.sdk.id === 'admob')!.deps[0]!;
expect([admob.file, admob.line, admob.version]).toEqual(['Podfile.lock', 5, '10.14.0']);
expect(ios.sdks.find(s => s.sdk.id === 'google-signin')!.deps.map(d => d.eco).sort()).toEqual(['cocoapods', 'spm']);
const android = detectProject(join(FX, 'android'));
expect(android.androidInfo.targetSdk).toEqual({ value: 34, at: { file: 'app/build.gradle.kts', line: 12 } });
expect(android.sdks.map(s => s.sdk.id).sort()).toEqual(['admob', 'firebase-auth']);
expect(detectProject(join(FX, 'capacitor')).stacks).toEqual(['capacitor']);
expect(detectProject(join(FX, 'capacitor')).remoteStart?.url).toBe('https://shop.example.com');
expect(detectProject(join(FX, 'capacitor')).androidInfo.targetSdk?.value).toBe(35);
const unity = detectProject(join(FX, 'unity'));
expect(unity.stacks).toEqual(['unity']);
expect(unity.sdks.map(s => s.sdk.id).sort()).toEqual(['admob', 'iap-wrapper', 'levelplay', 'unity-ads']);
expect(unity.plist.get('NSCameraUsageDescription')?.at.file).toBe('ProjectSettings/ProjectSettings.asset');
const flutter = detectProject(join(FX, 'flutter'));
expect(flutter.stacks).toEqual(['flutter']);
expect(flutter.deps.find(d => d.name === 'firebase_auth')?.version).toBe('5.3.1');
expect(flutter.androidInfo.targetSdkFrom).toContain('Flutter');
});
test('SDK table: matchers and version compare', () => {
const admob = SDKS.find(s => s.id === 'admob')!;
expect(matchesSdk({ eco: 'cocoapods', name: 'Google-Mobile-Ads-SDK', version: null, file: '', line: 1 }, admob)).toBe(true);
expect(matchesSdk({ eco: 'gradle', name: 'com.google.android.gms:play-services-ads-lite', version: null, file: '', line: 1 }, admob)).toBe(false);
expect(matchesSdk({ eco: 'gradle', name: 'com.amplitude:analytics-android', version: null, file: '', line: 1 }, SDKS.find(s => s.id === 'amplitude')!)).toBe(true);
expect(matchesSdk({ eco: 'spm', name: 'FirebaseAnalytics', version: null, file: '', line: 1 }, SDKS.find(s => s.id === 'firebase-analytics')!)).toBe(true);
expect(versionAtLeast('10.14.0', '11.2.0')).toBe(false);
expect(versionAtLeast('~> 11.10.0', '11.2.0')).toBe(true);
expect(versionAtLeast('latest', '1.0')).toBeNull();
for (const s of SDKS) expect(s.docs).toMatch(/^https:\/\//);
});
test('purpose strings: empty, vague, fine', () => {
expect(vaguePurpose('')).toBe('empty');
expect(vaguePurpose('TODO')).toBe('empty');
expect(vaguePurpose('Location')).toBe('vague');
expect(vaguePurpose('Allow $(PRODUCT_NAME) to access your camera')).toBe('vague');
expect(vaguePurpose('Scan a paper note with the camera to turn it into text.')).toBeNull();
});
});
describe('rules: planted issues are found', () => {
test('ios-native', async () => {
const r = await scan('ios-native');
for (const id of ['demo-account', 'account-deletion', 'login-services', 'restore-purchases', 'att', 'purpose-strings', 'privacy-manifest', 'other-platforms',
'metadata-keywords', 'placeholder-text', 'deprecated-api', 'private-api', 'ats', 'ipv6', 'export-compliance']) expect(rules(r.findings)).toContain(id);
expect(find(r.findings, 'demo-account')!.severity).toBe('blocker');
expect(find(r.findings, 'login-services')!.guideline).toBe('4.8');
const cam = r.findings.find(f => f.rule === 'purpose-strings' && f.title.includes('NSCameraUsageDescription'))!;
expect(cam.severity).toBe('blocker');
expect(cam.evidence[0]).toMatchObject({ file: 'Notes/ScannerView.swift', line: 9 });
expect(r.findings.some(f => f.rule === 'purpose-strings' && f.title.includes('too vague'))).toBe(true);
expect(find(r.findings, 'other-platforms')!.evidence[0]).toMatchObject({ file: 'store/appstore.md', line: 24 });
expect(find(r.findings, 'deprecated-api')!.evidence[0]!.file).toBe('Notes/LegacyHelp.swift');
expect(r.findings.filter(f => f.title.includes('older than')).length).toBe(3);
for (const f of r.findings) { expect(f.fix.length).toBeGreaterThan(10); expect(f.skill).toBeTruthy(); expect(f.ref).toMatch(/^https:\/\//); expect(f.evidence.length).toBeGreaterThan(0); }
});
test('android', async () => {
const r = await scan('android');
for (const id of ['play-deletion-url', 'play-target-sdk', 'play-package-name', 'play-fgs', 'play-exact-alarm', 'play-query-all-packages', 'play-sms-call-log', 'privacy-labels'])
expect(rules(r.findings, 'play')).toContain(id);
expect(find(r.findings, 'play-target-sdk')!.evidence[0]).toMatchObject({ file: 'app/build.gradle.kts', line: 12 });
expect(find(r.findings, 'play-sms-call-log')!.evidence[0]).toMatchObject({ file: 'app/src/main/AndroidManifest.xml', line: 5 });
expect(rules(r.findings, 'apple').size).toBe(0);
expect(rules(r.findings)).not.toContain('play-app-access');
expect(rules(r.findings)).not.toContain('account-deletion');
});
test('capacitor (no config: project files only)', async () => {
const r = await scan('capacitor');
expect(r.config).toBeNull();
for (const id of ['min-functionality', 'purpose-strings', 'play-target-sdk', 'privacy-manifest', 'att']) expect(rules(r.findings)).toContain(id);
expect(find(r.findings, 'min-functionality')!.evidence[0]).toMatchObject({ file: 'capacitor.config.json', line: 6 });
expect(rules(r.findings)).not.toContain('export-compliance');
});
test('unity', async () => {
const r = await scan('unity');
for (const id of ['purpose-strings', 'play-target-sdk', 'restore-purchases', 'kids-ads', 'review-prompt', 'privacy-manifest']) expect(rules(r.findings)).toContain(id);
expect(find(r.findings, 'kids-ads', 'apple')!.guideline).toBe('1.3');
expect(find(r.findings, 'kids-ads', 'play')).toBeTruthy();
expect(r.findings.find(f => f.rule === 'review-prompt' && f.severity === 'high')).toBeTruthy();
expect(rules(r.findings)).not.toContain('kids-terms');
});
test('flutter', async () => {
const r = await scan('flutter');
for (const id of ['account-deletion', 'play-deletion-url', 'login-services', 'restore-purchases', 'subscription-info', 'att', 'play-fgs', 'play-target-sdk']) expect(rules(r.findings)).toContain(id);
expect(find(r.findings, 'att')!.severity).toBe('blocker');
expect(r.findings.find(f => f.rule === 'subscription-info' && f.severity === 'blocker')!.title).toContain('Terms of Use');
expect(r.findings.find(f => f.rule === 'play-fgs' && f.title.includes('FOREGROUND_SERVICE_LOCATION'))).toBeTruthy();
expect(find(r.findings, 'play-target-sdk')!.severity).toBe('low');
});
test('teaser: exactly the five classic rejections', async () => {
const r = await scan('teaser');
expect([...rules(r.findings)].sort()).toEqual(['account-deletion', 'att', 'demo-account', 'login-services', 'restore-purchases']);
expect(r.findings.map(f => f.guideline)).toEqual(['2.1(a)', '5.1.1(v)', '4.8', '3.1.1', '5.1.2(i)']);
});
});
describe('rules: no false positives', () => {
test('clean fixture has no finding at all', async () => {
process.env.REVIEW_DEMO_USER = 'demo@example.com'; process.env.REVIEW_DEMO_PASSWORD = 'example';
const r = await scan('clean');
expect(r.findings.map(f => `${f.rule}: ${f.title}`)).toEqual([]);
expect(r.declarations.changed).toBe(false);
expect(r.declarations.labelGaps).toEqual([]);
expect(r.stacks.sort()).toEqual(['android-native', 'ios-native']);
});
test('the demo account comes from the environment or .storebound/', async () => {
expect(rules((await scan('clean')).findings)).toContain('demo-account');
});
test('the example projects have no open finding (the fictional ones are accepted in scan.ignore)', async () => {
for (const d of ['demo-app', 'demo-game']) {
const r = (await runScan(join(ROOT, 'examples', d))).report;
expect(r.findings.filter(f => !f.accepted).map(f => f.title)).toEqual([]);
for (const f of r.findings) expect(f.accepted!.length).toBeGreaterThan(10);
}
});
});
describe('declarations proposal', () => {
test('detected SDK data types become additions, owner answers are kept, never removed', async () => {
const d = (await scan('android')).declarations;
expect(d.diff.find(x => x.type === 'PSL_DEVICE_ID')).toMatchObject({ change: 'add', after: { shared: true, collect: ['advertising', 'analytics', 'fraud'], share: ['advertising'] } });
expect(d.diff.find(x => x.type === 'PSL_EMAIL')!.change).toBe('merge');
expect(d.dataSafety!.data.PSL_EMAIL!.collect).toEqual(['account', 'functionality']);
expect(d.items.find(x => x.what === 'encryptedInTransit')!.status).toBe('ask');
expect(d.items.find(x => x.what === 'PSL_DEVICE_ID')!.evidence[0]!.file).toBe('gradle/libs.versions.toml');
expect(d.changed).toBe(true);
});
test('ATT and the privacy manifest', async () => {
const d = (await scan('clean')).declarations;
expect(d.items.find(x => x.area === 'appPrivacy' && x.what === 'tracking')).toMatchObject({ status: 'detected', value: expect.stringContaining('true') });
expect(d.items.find(x => x.area === 'privacyManifest' && x.what === 'NSPrivacyAccessedAPICategoryUserDefaults')).toMatchObject({ status: 'detected', value: 'declared: CA92.1' });
const t = (await scan('teaser')).declarations;
expect(t.items.find(x => x.area === 'att')!.status).toBe('ask');
});
});
describe('config writing', () => {
test('matchBrace skips strings and comments', () => {
const s = "{ a: '}', b: { c: \"{\" }, // }\n d: `}` }";
expect(matchBrace(s, 0)).toBe(s.length - 1);
});
test('toTs writes plain TypeScript', () => {
expect(toTs({ shared: false, collect: ['a', 'b'] })).toBe("{ shared: false, collect: ['a', 'b'] }");
expect(toTs({ PSL_X: { shared: true, collect: ['x'] } }, ' ')).toBe("{\n PSL_X: { shared: true, collect: ['x'] },\n }");
});
test('upsertBlock replaces an existing block and inserts after app', () => {
const src = "export default {\n app: { name: 'X' },\n dataSafety: { collectsData: false, data: {} },\n languages: [],\n};\n";
const a = upsertBlock(src, 'c.ts', 'dataSafety', { collectsData: true, data: {} });
expect(a).toBe("export default {\n app: { name: 'X' },\n dataSafety: {\n collectsData: true,\n data: {},\n },\n languages: [],\n};\n");
const b = upsertBlock(src, 'c.ts', 'appPrivacy', { tracking: true }, 'note');
expect(b).toContain(" app: { name: 'X' },\n // note\n appPrivacy: { tracking: true },\n dataSafety");
expect(JSON.parse(upsertBlock('{"app":{}}', 'c.json', 'appPrivacy', { tracking: false }))).toEqual({ app: {}, appPrivacy: { tracking: false } });
});
test('scan is read-only without --write; --write adds the detected answers and the config still loads', async () => {
const dir = mkdtempSync(join(tmpdir(), 'sb-scan-'));
try {
cpSync(join(FX, 'android'), dir, { recursive: true });
const before = readFileSync(join(dir, 'storebound.config.ts'), 'utf8');
const run = (...a: string[]) => Bun.spawnSync(['bun', CLI, 'scan', '--dir', dir, ...a], { env: { ...process.env, REVIEW_DEMO_USER: '', REVIEW_DEMO_PASSWORD: '' } });
const r1 = run();
expect(r1.exitCode).toBe(1);
expect(r1.stdout.toString()).toContain('+ dataSafety.data.PSL_DEVICE_ID');
expect(readFileSync(join(dir, 'storebound.config.ts'), 'utf8')).toBe(before);
run('--write', '--dry');
expect(readFileSync(join(dir, 'storebound.config.ts'), 'utf8')).toBe(before);
run('--write');
const after = readFileSync(join(dir, 'storebound.config.ts'), 'utf8');
expect(after).toContain("PSL_DEVICE_ID: { shared: true, collect: ['advertising', 'analytics', 'fraud'], share: ['advertising'] }");
expect(after).toContain("PSL_EMAIL: { shared: false, collect: ['account', 'functionality'] }");
expect(after).toContain("accountCreation: ['PSL_ACM_USER_ID_PASSWORD']");
const again = await runScan(dir);
expect(again.report.configError).toBeNull();
expect(again.report.declarations.changed).toBe(false);
expect(rules(again.report.findings)).not.toContain('privacy-labels');
} finally { rmSync(dir, { recursive: true, force: true }); }
});
});
describe('integration', () => {
test('JSON output, --store filter, exit code', () => {
const r = Bun.spawnSync(['bun', CLI, 'scan', '--dir', join(FX, 'teaser'), '--json', '--store', 'apple'], { env: { ...process.env, REVIEW_DEMO_USER: '', REVIEW_DEMO_PASSWORD: '' } });
expect(r.exitCode).toBe(1);
const j = JSON.parse(r.stdout.toString()) as { counts: { blocker: number }; findings: ScanFinding[] };
expect(j.counts.blocker).toBe(2);
expect(j.findings.every(f => f.store === 'apple')).toBe(true);
});
test('scan.ignore marks findings as accepted and they stop blocking', async () => {
const r = (await runScan(join(ROOT, 'examples', 'demo-app'))).report;
expect(r.findings.find(f => f.rule === 'demo-account')!.accepted).toContain('fictional');
expect(r.counts.blocker).toBe(0);
});
test('validate gets the open blockers and risks, not low or accepted ones', async () => {
const r = (await scan('flutter')).findings;
const v = scanAsFindings(r, { apple: true, play: false });
expect(v.every(f => f.store === 'apple' && f.code.startsWith('scan-'))).toBe(true);
expect(v.filter(f => f.level === 'blocker').length).toBe(r.filter(f => f.store === 'apple' && f.severity === 'blocker').length);
expect(v.some(f => f.code === 'scan-subscription-info' && f.msg.startsWith('3.1.2'))).toBe(true);
expect(scanAsFindings([{ ...r[0]!, accepted: 'fine' }], { apple: true, play: true })).toEqual([]);
});
test('MCP tool and desktop method are read-only and cannot write', () => {
const t = TOOLS.find(x => x.name === 'scan')!;
expect(t.write).toBe(false);
expect(t.network).toBe(false);
expect(toArgv(t, { store: 'play' }).argv).toEqual(['scan', '--store', 'play']);
expect(FORBIDDEN_ARGS).toContain('--write');
for (const x of TOOLS) expect(toArgv(x, {}).argv).not.toContain('--write');
expect(JSON_TOOLS.has('scan')).toBe(true);
});
});