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.
This commit is contained in:
parent
02d90de77a
commit
00a38cd305
109 changed files with 3103 additions and 31 deletions
|
|
@ -304,6 +304,14 @@ export interface ReviewAccess {
|
|||
instructions?: string;
|
||||
}
|
||||
|
||||
/** App Privacy: does the app (or an SDK in it) track users across other companies' apps and websites? true needs
|
||||
* App Tracking Transparency (NSUserTrackingUsageDescription + the prompt) and the privacy manifest's NSPrivacyTracking. */
|
||||
export interface AppPrivacyConfig {
|
||||
tracking?: boolean;
|
||||
/** Domains that receive tracking data (privacy manifest NSPrivacyTrackingDomains). */
|
||||
trackingDomains?: string[];
|
||||
}
|
||||
|
||||
export type SubscriptionPeriod = 'P1W' | 'P1M' | 'P2M' | 'P3M' | 'P6M' | 'P1Y';
|
||||
|
||||
/** Introductory offer for new subscribers. Apple: subscriptionIntroductoryOffers (first-time subscribers of the group,
|
||||
|
|
@ -470,6 +478,11 @@ export interface ShipConfig {
|
|||
baseTerritory?: string;
|
||||
};
|
||||
dataSafety?: DataSafety;
|
||||
/** App Store App Privacy answers storebound cannot derive from dataSafety (App Privacy has no API: the owner enters
|
||||
* them in App Store Connect). `storebound scan` proposes them from the detected SDKs and code. */
|
||||
appPrivacy?: AppPrivacyConfig;
|
||||
/** `storebound scan`: findings the owner has looked at and accepts, by rule id (with the reason, shown in the report). */
|
||||
scan?: { ignore?: { rule: string; store?: 'apple' | 'play'; reason: string }[] };
|
||||
/** Ads: `validate` checks that <app.website>/app-ads.txt is reachable and contains every line listed here. */
|
||||
ads?: { appAdsTxt?: string[] };
|
||||
/** Rendered store graphics dir (<renders>/<languageId>/<size>/NN.png|jpg). Defaults to shots.out. */
|
||||
|
|
@ -549,6 +562,14 @@ export function validateConfig(c: unknown): string[] {
|
|||
if (cfg.apple.screenshotTypes && !cfg.apple.screenshotTypes.every(t => /^APP_[A-Z0-9_]+$/.test(t))) e.push('apple.screenshotTypes: display types like APP_IPHONE_67');
|
||||
e.push(...validateTestflight(cfg.apple.testflight));
|
||||
}
|
||||
if (cfg.appPrivacy) {
|
||||
if (cfg.appPrivacy.tracking !== undefined && typeof cfg.appPrivacy.tracking !== 'boolean') e.push('appPrivacy.tracking: true | false');
|
||||
if (cfg.appPrivacy.trackingDomains && !(Array.isArray(cfg.appPrivacy.trackingDomains) && cfg.appPrivacy.trackingDomains.every(d => typeof d === 'string' && /^[a-z0-9.-]+$/i.test(d))))
|
||||
e.push('appPrivacy.trackingDomains: a list of host names');
|
||||
}
|
||||
for (const [i, x] of (cfg.scan?.ignore ?? []).entries())
|
||||
if (!x || typeof x.rule !== 'string' || !x.rule || typeof x.reason !== 'string' || !x.reason.trim() || (x.store !== undefined && x.store !== 'apple' && x.store !== 'play'))
|
||||
e.push(`scan.ignore[${i}]: { rule: '<rule id from storebound scan>', reason: 'why this is fine', store?: 'apple' | 'play' }`);
|
||||
if (cfg.ads?.appAdsTxt && !cfg.ads.appAdsTxt.every(l => typeof l === 'string' && l.split(',').length >= 3))
|
||||
e.push('ads.appAdsTxt: lines like "example-network.com, pub-123, DIRECT, abc123"');
|
||||
const seen = new Set<string>();
|
||||
|
|
|
|||
|
|
@ -11,6 +11,8 @@ export function profileIssues(config: ShipConfig, o: { demoAccount: boolean }):
|
|||
const err = (msg: string) => out.push({ level: 'error', msg });
|
||||
const warn = (msg: string) => out.push({ level: 'warn', msg });
|
||||
const accounts = !!config.accounts?.enabled;
|
||||
if (config.dataSafety) for (const k of ['collectsData', 'encryptedInTransit', 'deletionRequest'] as const)
|
||||
if (typeof config.dataSafety[k] !== 'boolean') err(`dataSafety.${k}: not answered (true | false; ask the owner, store-declarations skill)`);
|
||||
const acm = config.dataSafety?.accountCreation ?? ['PSL_ACM_NONE'];
|
||||
if (accounts) {
|
||||
if (config.play && !config.accounts!.deletionUrl) err('accounts.enabled: set accounts.deletionUrl (Play asks for a web page to request account deletion; account-deletion skill)');
|
||||
|
|
|
|||
71
cli/lib/scan/config-edit.ts
Normal file
71
cli/lib/scan/config-edit.ts
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
// Writes one top-level block (dataSafety, appPrivacy) into storebound.config.ts / .js / .json text: replaces the
|
||||
// existing `key: { ... }` property, or inserts it after the `app: { ... }` block. Pure text in, text out; the rest of
|
||||
// the file (comments, order, formatting) stays as it is. Used by `storebound scan --write` only.
|
||||
|
||||
/** Index of the brace that closes the one at `open`, skipping strings, template literals and comments. -1 if none. */
|
||||
export function matchBrace(text: string, open: number): number {
|
||||
const pairs: Record<string, string> = { '{': '}', '[': ']', '(': ')' };
|
||||
const stack: string[] = [];
|
||||
for (let i = open; i < text.length; i++) {
|
||||
const ch = text[i]!;
|
||||
if (ch === '/' && text[i + 1] === '/') { i = text.indexOf('\n', i); if (i < 0) return -1; continue; }
|
||||
if (ch === '/' && text[i + 1] === '*') { i = text.indexOf('*/', i + 2); if (i < 0) return -1; i++; continue; }
|
||||
if (ch === '"' || ch === '\'' || ch === '`') {
|
||||
for (i++; i < text.length && text[i] !== ch; i++) if (text[i] === '\\') i++;
|
||||
continue;
|
||||
}
|
||||
if (pairs[ch]) stack.push(pairs[ch]!);
|
||||
else if (ch === '}' || ch === ']' || ch === ')') {
|
||||
if (stack.pop() !== ch) return -1;
|
||||
if (!stack.length) return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
const ID = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
||||
|
||||
/** A plain value as TypeScript source (single quotes, unquoted keys, trailing commas), indented by `ind`. */
|
||||
export function toTs(v: unknown, ind = ''): string {
|
||||
const next = ind + ' ';
|
||||
if (v === null || v === undefined) return 'undefined';
|
||||
if (typeof v === 'string') return `'${v.replace(/\\/g, '\\\\').replace(/'/g, '\\\'')}'`;
|
||||
if (typeof v === 'number' || typeof v === 'boolean') return String(v);
|
||||
if (Array.isArray(v)) {
|
||||
const parts = v.map(x => toTs(x, next));
|
||||
const one = `[${parts.join(', ')}]`;
|
||||
return one.length <= 100 && !one.includes('\n') ? one : `[\n${parts.map(p => `${next}${p},`).join('\n')}\n${ind}]`;
|
||||
}
|
||||
const entries = Object.entries(v as Record<string, unknown>).filter(([, x]) => x !== undefined);
|
||||
if (!entries.length) return '{}';
|
||||
const parts = entries.map(([k, x]) => `${ID.test(k) ? k : `'${k}'`}: ${toTs(x, next)}`);
|
||||
const one = `{ ${parts.join(', ')} }`;
|
||||
return one.length <= 110 && !one.includes('\n') && entries.every(([, x]) => typeof x !== 'object' || Array.isArray(x)) ? one : `{\n${parts.map(p => `${next}${p},`).join('\n')}\n${ind}}`;
|
||||
}
|
||||
|
||||
/** The config text with `key` set to `value` (plus an optional comment line above it). */
|
||||
export function upsertBlock(text: string, file: string, key: string, value: unknown, comment?: string): string {
|
||||
if (file.endsWith('.json')) {
|
||||
const j = JSON.parse(text) as Record<string, unknown>;
|
||||
j[key] = value;
|
||||
return JSON.stringify(j, null, 2) + '\n';
|
||||
}
|
||||
const re = new RegExp(`^([ \\t]*)${key}\\s*:\\s*\\{`, 'm');
|
||||
const m = re.exec(text);
|
||||
if (m) {
|
||||
const ind = m[1]!;
|
||||
const open = m.index + m[0].length - 1;
|
||||
const close = matchBrace(text, open);
|
||||
if (close < 0) throw new Error(`${file}: could not find the end of the ${key} block`);
|
||||
return `${text.slice(0, m.index)}${ind}${key}: ${toTs(value, ind)}${text.slice(close + 1)}`;
|
||||
}
|
||||
const app = /^([ \t]*)app\s*:\s*\{/m.exec(text);
|
||||
if (!app) throw new Error(`${file}: no app block found to insert ${key} after; add it by hand`);
|
||||
const ind = app[1]!;
|
||||
const close = matchBrace(text, app.index + app[0].length - 1);
|
||||
if (close < 0) throw new Error(`${file}: could not find the end of the app block`);
|
||||
let at = close + 1;
|
||||
if (text[at] === ',') at++;
|
||||
const block = `\n${comment ? `${ind}// ${comment}\n` : ''}${ind}${key}: ${toTs(value, ind)},`;
|
||||
return text.slice(0, at) + block + text.slice(at);
|
||||
}
|
||||
155
cli/lib/scan/declare.ts
Normal file
155
cli/lib/scan/declare.ts
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
// Declarations proposal for `storebound scan`: from the detected SDKs, permissions and code, the Play Data safety and
|
||||
// App Store App Privacy answers, App Tracking Transparency and the privacy manifest entries the project needs, each
|
||||
// marked "detected (file:line)" or "ask owner", and a diff against the config's dataSafety / appPrivacy blocks.
|
||||
// Only detected items are ever written (`scan --write`); "ask owner" items stay questions (AGENTS.md rule 5). Pure.
|
||||
import type { AppPrivacyConfig, DataSafety, DataUsage, PlayPurpose, ShipConfig } from '../config';
|
||||
import { APPLE_PRIVACY, applePurpose } from '../declarations';
|
||||
import { REQUIRED_REASON_APIS } from '../privacy-manifest';
|
||||
import { IOS_PERMISSIONS } from './permissions';
|
||||
import { grep, type Hit, lineOf, type ProjectFacts } from './project';
|
||||
import { SIGNALS } from './rules';
|
||||
|
||||
export type DeclArea = 'dataSafety' | 'appPrivacy' | 'att' | 'privacyManifest';
|
||||
export interface DeclItem { area: DeclArea; what: string; value: string; status: 'detected' | 'ask'; evidence: Hit[]; note?: string }
|
||||
export interface DataDiff {
|
||||
type: string;
|
||||
/** App Privacy category / type it maps to. */
|
||||
apple: string;
|
||||
change: 'add' | 'merge' | 'same' | 'kept';
|
||||
before: DataUsage | null;
|
||||
after: DataUsage;
|
||||
evidence: Hit[];
|
||||
}
|
||||
export interface Proposal {
|
||||
items: DeclItem[];
|
||||
diff: DataDiff[];
|
||||
/** The dataSafety block --write would write (null when nothing was detected and the config has none). */
|
||||
dataSafety: Partial<DataSafety> & { data: Record<string, DataUsage> } | null;
|
||||
appPrivacy: AppPrivacyConfig | null;
|
||||
appPrivacyChange: { from: boolean | null; to: boolean } | null;
|
||||
/** Types an SDK collects that the config's dataSafety does not declare (the privacy-labels rule). */
|
||||
labelGaps: { type: string; apple: string; evidence: Hit[] }[];
|
||||
/** --write would change the config. */
|
||||
changed: boolean;
|
||||
}
|
||||
|
||||
const PERMISSION_DATA: Record<string, { type: string; note: string }> = {
|
||||
NSCameraUsageDescription: { type: 'PSL_PHOTOS', note: 'only if photos / videos leave the device (uploaded, sent to an API)' },
|
||||
NSMicrophoneUsageDescription: { type: 'PSL_AUDIO', note: 'only if recordings leave the device' },
|
||||
NSPhotoLibraryUsageDescription: { type: 'PSL_PHOTOS', note: 'only if picked photos leave the device' },
|
||||
NSLocationWhenInUseUsageDescription: { type: 'PSL_APPROX_LOCATION', note: 'approximate or precise (PSL_PRECISE_LOCATION), only if it leaves the device' },
|
||||
NSContactsUsageDescription: { type: 'PSL_CONTACTS', note: 'only if contacts leave the device' },
|
||||
NSHealthShareUsageDescription: { type: 'PSL_HEALTH', note: 'only if health data leaves the device' },
|
||||
NSCalendarsFullAccessUsageDescription: { type: 'PSL_CALENDAR', note: 'only if events leave the device' },
|
||||
};
|
||||
|
||||
const uniq = <T>(a: T[]): T[] => [...new Set(a)];
|
||||
const sorted = (a: readonly string[] | undefined) => [...(a ?? [])].sort().join();
|
||||
const usageEq = (a: DataUsage, b: DataUsage) => a.shared === b.shared && sorted(a.collect) === sorted(b.collect) && sorted(a.share) === sorted(b.share);
|
||||
|
||||
export function proposeDeclarations(p: ProjectFacts, c: ShipConfig | null, configFile?: { path: string; text: string } | null): Proposal {
|
||||
const items: DeclItem[] = [];
|
||||
const detected = new Map<string, { collect: Set<PlayPurpose>; share: Set<PlayPurpose>; evidence: Hit[]; from: string[] }>();
|
||||
for (const s of p.sdks) {
|
||||
const d0 = s.deps[0]!;
|
||||
const ev: Hit = { file: d0.file, line: d0.line, text: `${s.sdk.name}: ${d0.name}${d0.version ? ` ${d0.version}` : ''}` };
|
||||
for (const d of s.sdk.data) {
|
||||
const e = detected.get(d.type) ?? { collect: new Set<PlayPurpose>(), share: new Set<PlayPurpose>(), evidence: [], from: [] };
|
||||
for (const x of d.collect) e.collect.add(x);
|
||||
for (const x of d.share ?? []) e.share.add(x);
|
||||
if (!e.from.includes(s.sdk.name)) { e.from.push(s.sdk.name); e.evidence.push(ev); }
|
||||
detected.set(d.type, e);
|
||||
}
|
||||
}
|
||||
// accounts proven by the config or sign-up code
|
||||
const signUp = grep(p.sources, SIGNALS.signUp, 1);
|
||||
if (c?.accounts?.enabled || signUp.length) {
|
||||
const ev: Hit[] = signUp.length ? signUp : [{ file: configFile?.path ?? 'storebound.config.ts', line: configFile ? lineOf(configFile.text, /accounts\s*:/) : 1, text: 'accounts.enabled' }];
|
||||
for (const t of ['PSL_EMAIL', 'PSL_USER_ACCOUNT']) {
|
||||
const e = detected.get(t) ?? { collect: new Set<PlayPurpose>(), share: new Set<PlayPurpose>(), evidence: [], from: [] };
|
||||
e.collect.add('account'); e.collect.add('functionality'); e.evidence.push(...ev); e.from.push('accounts');
|
||||
detected.set(t, e);
|
||||
}
|
||||
}
|
||||
const have = c?.dataSafety?.data ?? {};
|
||||
const diff: DataDiff[] = [];
|
||||
const out: Record<string, DataUsage> = {};
|
||||
for (const [type, e] of detected) {
|
||||
const share = [...e.share].sort();
|
||||
const det: DataUsage = { shared: share.length > 0, collect: [...e.collect].sort(), ...(share.length ? { share } : {}) };
|
||||
const before = have[type] ?? null;
|
||||
const after: DataUsage = before ? {
|
||||
...before, shared: before.shared || det.shared,
|
||||
collect: uniq([...before.collect, ...det.collect]).sort(),
|
||||
...((before.share?.length || share.length) ? { share: uniq([...(before.share ?? []), ...share]).sort() } : {}),
|
||||
} : det;
|
||||
out[type] = after;
|
||||
const [cat, name] = APPLE_PRIVACY[type] ?? ['Other Data', 'Other Data Types'];
|
||||
diff.push({ type, apple: `${cat} / ${name}`, change: !before ? 'add' : usageEq(before, after) ? 'same' : 'merge', before, after, evidence: e.evidence.slice(0, 3) });
|
||||
items.push({ area: 'dataSafety', what: type, value: `collect: ${after.collect.join(', ')}${after.shared ? `; shared: ${(after.share ?? []).join(', ')}` : ''}`, status: 'detected', evidence: e.evidence.slice(0, 2),
|
||||
note: `from ${e.from.join(', ')}; ephemeral / optional: ask owner` });
|
||||
}
|
||||
for (const [type, u] of Object.entries(have)) if (!detected.has(type)) {
|
||||
out[type] = u;
|
||||
const [cat, name] = APPLE_PRIVACY[type] ?? ['Other Data', 'Other Data Types'];
|
||||
diff.push({ type, apple: `${cat} / ${name}`, change: 'kept', before: u, after: u, evidence: [] });
|
||||
}
|
||||
// permissions that may mean collected data: questions, never written
|
||||
for (const perm of IOS_PERMISSIONS) for (const k of perm.keys) {
|
||||
const e = p.plist.get(k), pd = PERMISSION_DATA[k];
|
||||
if (!e || !pd || out[pd.type]) continue;
|
||||
items.push({ area: 'dataSafety', what: pd.type, value: `collected? ${pd.note}`, status: 'ask', evidence: [{ ...e.at, text: k }] });
|
||||
}
|
||||
const labelGaps = c?.dataSafety ? diff.filter(d => d.change === 'add').map(d => ({ type: d.type, apple: d.apple, evidence: d.evidence })) : [];
|
||||
|
||||
// top-level Data safety answers
|
||||
const anyData = Object.keys(out).length > 0;
|
||||
if (anyData) items.push({ area: 'dataSafety', what: 'collectsData', value: 'true', status: 'detected', evidence: diff.flatMap(d => d.evidence).slice(0, 1) });
|
||||
for (const k of ['encryptedInTransit', 'deletionRequest'] as const)
|
||||
items.push({ area: 'dataSafety', what: k, value: c?.dataSafety ? String(c.dataSafety[k]) : '?', status: 'ask', evidence: [], note: k === 'encryptedInTransit' ? 'all traffic over HTTPS / TLS? (ATS and the SDKs\' own endpoints)' : 'can users ask for their data to be deleted?' });
|
||||
if ((c?.accounts?.enabled || signUp.length) && (c?.dataSafety?.accountCreation ?? ['PSL_ACM_NONE']).includes('PSL_ACM_NONE'))
|
||||
items.push({ area: 'dataSafety', what: 'accountCreation', value: 'which sign-up methods (PSL_ACM_USER_ID_PASSWORD, PSL_ACM_OAUTH, ...)?', status: 'ask', evidence: signUp.slice(0, 1) });
|
||||
|
||||
// App Privacy per type (linked / tracking are owner answers)
|
||||
for (const d of diff) {
|
||||
const shared = d.after.shared ? d.after.share ?? [] : [];
|
||||
// a purpose the data is shared for counts once, as the third party's (AdMob: Third-Party Advertising, not the developer's)
|
||||
const purposes = uniq([...d.after.collect.filter(x => !shared.includes(x)).map(x => applePurpose(x, false)), ...shared.map(x => applePurpose(x, true))]).sort();
|
||||
items.push({ area: 'appPrivacy', what: d.apple, value: purposes.join(', '), status: d.change === 'kept' ? 'ask' : 'detected', evidence: d.evidence.slice(0, 1), note: 'linked to identity? used for tracking? ask owner' });
|
||||
}
|
||||
|
||||
// tracking + ATT
|
||||
const attReq = grep(p.sources, SIGNALS.attRequest, 1);
|
||||
const attStr = p.plist.get('NSUserTrackingUsageDescription');
|
||||
const trackers = p.sdks.filter(s => s.sdk.tracking);
|
||||
let tracking: boolean | null = null;
|
||||
if (attReq.length) { tracking = true; items.push({ area: 'appPrivacy', what: 'tracking', value: 'true (the app asks for App Tracking Transparency)', status: 'detected', evidence: attReq }); }
|
||||
else if (trackers.length) items.push({ area: 'appPrivacy', what: 'tracking', value: `${trackers.map(s => s.sdk.name).join(', ')} can track: personalized ads / attribution on?`, status: 'ask', evidence: trackers.map(s => ({ file: s.deps[0]!.file, line: s.deps[0]!.line, text: s.sdk.name })).slice(0, 2) });
|
||||
if (attStr) items.push({ area: 'att', what: 'NSUserTrackingUsageDescription', value: String(attStr.value).slice(0, 80), status: 'detected', evidence: [{ ...attStr.at, text: 'NSUserTrackingUsageDescription' }] });
|
||||
else if (trackers.length || attReq.length) items.push({ area: 'att', what: 'NSUserTrackingUsageDescription', value: 'needed if anything tracks, e.g. "Your data is used to show ads that fit your interests."', status: 'ask', evidence: [] });
|
||||
if (attReq.length) items.push({ area: 'att', what: 'ATT request', value: 'found', status: 'detected', evidence: attReq });
|
||||
if (trackers.length || attReq.length) items.push({ area: 'appPrivacy', what: 'trackingDomains', value: 'the SDKs\' tracking domains (from each SDK\'s privacy manifest)', status: 'ask', evidence: [] });
|
||||
|
||||
// privacy manifest
|
||||
if (p.ios) {
|
||||
const declared = new Map<string, string[]>();
|
||||
for (const m of p.privacyManifests) for (const [k, v] of Object.entries(m.apis)) declared.set(k, v);
|
||||
const nativeSrc = p.sources.filter(s => /\.(swift|m|mm|h)$/.test(s.path));
|
||||
for (const [cat, def] of Object.entries(REQUIRED_REASON_APIS)) {
|
||||
const h = grep(nativeSrc, def.symbols, 1);
|
||||
if (!h.length) continue;
|
||||
const have = declared.get(cat);
|
||||
items.push({ area: 'privacyManifest', what: cat, value: have?.length ? `declared: ${have.join(', ')}` : `add with a reason: ${def.note}`, status: have?.length ? 'detected' : 'ask', evidence: h });
|
||||
}
|
||||
const m = p.privacyManifests[0];
|
||||
if (tracking !== null || m) items.push({ area: 'privacyManifest', what: 'NSPrivacyTracking', value: tracking ? 'true' : m ? String(m.tracking) : '?', status: tracking ? 'detected' : 'ask', evidence: m ? [{ file: m.path, line: 1, text: 'PrivacyInfo.xcprivacy' }] : [] });
|
||||
if (diff.length) items.push({ area: 'privacyManifest', what: 'NSPrivacyCollectedDataTypes', value: uniq(diff.map(d => d.apple.split(' / ')[1]!)).join(', '), status: 'detected', evidence: diff.flatMap(d => d.evidence).slice(0, 1), note: 'the app\'s own collection; SDKs declare theirs in their manifests' });
|
||||
}
|
||||
|
||||
const dsChanged = diff.some(d => d.change === 'add' || d.change === 'merge') || (anyData && c?.dataSafety?.collectsData === false);
|
||||
const dataSafety = anyData || c?.dataSafety ? { ...(c?.dataSafety ?? {}), collectsData: anyData || !!c?.dataSafety?.collectsData, data: out } : null;
|
||||
const from = c?.appPrivacy?.tracking ?? null;
|
||||
const appPrivacyChange = tracking !== null && from !== tracking ? { from, to: tracking } : null;
|
||||
const appPrivacy = appPrivacyChange ? { ...(c?.appPrivacy ?? {}), tracking: appPrivacyChange.to } : c?.appPrivacy ?? null;
|
||||
return { items, diff, dataSafety, appPrivacy, appPrivacyChange, labelGaps, changed: dsChanged || !!appPrivacyChange };
|
||||
}
|
||||
121
cli/lib/scan/index.ts
Normal file
121
cli/lib/scan/index.ts
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
// `storebound scan` engine: detect the project, run the rejection-risk rules, propose the declarations. Offline and
|
||||
// read-only (the only write is `--write`, done by the command, never here).
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { join, relative } from 'node:path';
|
||||
import { CONFIG_NAMES, loadConfig, type ShipConfig } from '../config';
|
||||
import { reviewDemoAccount } from '../credentials';
|
||||
import { proposeDeclarations, type Proposal } from './declare';
|
||||
import { detectProject, ECO_LABEL, type ProjectFacts, type Stack, where } from './project';
|
||||
import { type ScanFinding, scanRules, type Severity } from './rules';
|
||||
import type { SdkCategory } from './sdks';
|
||||
|
||||
export interface ScanReport {
|
||||
root: string;
|
||||
config: string | null;
|
||||
configError: string | null;
|
||||
stacks: Stack[];
|
||||
platforms: { ios: boolean; android: boolean };
|
||||
sdks: { id: string; name: string; category: SdkCategory; tracking: boolean; deps: { eco: string; name: string; version: string | null; file: string; line: number }[] }[];
|
||||
permissions: { key: string; value: string; file: string; line: number }[];
|
||||
android: { targetSdk: number | null; targetSdkAt: string | null; permissions: string[] };
|
||||
findings: ScanFinding[];
|
||||
counts: Record<Severity, number> & { accepted: number };
|
||||
declarations: Proposal;
|
||||
scanned: number;
|
||||
notes: string[];
|
||||
}
|
||||
|
||||
export interface ScanRun { report: ScanReport; facts: ProjectFacts; config: ShipConfig | null; configPath: string | null }
|
||||
|
||||
/** Find the project's config: --config, else storebound.config.* in `dir` (no upward search: a fixture or a
|
||||
* sub-project must not pick up a parent's config). */
|
||||
async function findConfig(dir: string, explicit?: string): Promise<{ config: ShipConfig | null; path: string | null; error: string | null }> {
|
||||
const path = explicit ? join(dir, explicit) : CONFIG_NAMES.map(n => join(dir, n)).find(existsSync);
|
||||
if (!path) return { config: null, path: null, error: null };
|
||||
try { return { config: (await loadConfig(path)).config, path, error: null }; } catch (e) { return { config: null, path, error: (e as Error).message.split('\n').slice(0, 4).join('; ') }; }
|
||||
}
|
||||
|
||||
export async function runScan(dir: string, o: { config?: string } = {}): Promise<ScanRun> {
|
||||
const facts = detectProject(dir);
|
||||
const { config, path: configPath, error } = await findConfig(dir, o.config);
|
||||
const rel = (p: string) => relative(dir, p) || p;
|
||||
const readRel = (p: string | undefined): { path: string; text: string } | undefined => {
|
||||
if (!p) return undefined;
|
||||
const abs = join(dir, p);
|
||||
try { return existsSync(abs) ? { path: rel(abs), text: readFileSync(abs, 'utf8') } : undefined; } catch { return undefined; }
|
||||
};
|
||||
const listings = {
|
||||
apple: (config ? config.apple : true) ? readRel(config?.apple?.listing ?? 'store/appstore.md') : undefined,
|
||||
play: (config ? config.play : true) ? readRel(config?.play?.listing ?? 'store/listing.md') : undefined,
|
||||
captions: readRel(config?.shots?.copy ?? 'store/shots/copy.json'),
|
||||
};
|
||||
const configFile = configPath ? { path: rel(configPath), text: readFileSync(configPath, 'utf8') } : null;
|
||||
const declarations = proposeDeclarations(facts, config, configFile);
|
||||
const findings = scanRules({ facts, config, configFile, listings, demoAccount: !!reviewDemoAccount(dir), labelGaps: declarations.labelGaps });
|
||||
const counts = { blocker: 0, high: 0, medium: 0, low: 0, accepted: 0 };
|
||||
for (const f of findings) { if (f.accepted) counts.accepted++; else counts[f.severity]++; }
|
||||
const notes: string[] = [];
|
||||
if (facts.android && facts.androidInfo.manifests.length) notes.push('Android: libraries add permissions when the manifest is merged; check the merged manifest (Android Studio > Merged Manifest, or the AAB) too.');
|
||||
if (facts.ios && !facts.plistSources.length) notes.push('iOS: no Info.plist settings found (generated at build time?): purpose string, ATS and export compliance checks were skipped.');
|
||||
if (!facts.sources.length) notes.push('No app source files found: code checks (sign-in, deletion, restore, ATT prompt) could not run.');
|
||||
const report: ScanReport = {
|
||||
root: dir, config: configPath ? rel(configPath) : null, configError: error,
|
||||
stacks: facts.stacks, platforms: { ios: facts.ios, android: facts.android },
|
||||
sdks: facts.sdks.map(s => ({ id: s.sdk.id, name: s.sdk.name, category: s.sdk.category, tracking: s.sdk.tracking, deps: s.deps.map(d => ({ eco: d.eco, name: d.name, version: d.version, file: d.file, line: d.line })) })),
|
||||
permissions: [...facts.plist.values()].filter(e => /UsageDescription$/.test(e.key)).map(e => ({ key: e.key, value: String(e.value ?? ''), file: e.at.file, line: e.at.line })),
|
||||
android: { targetSdk: facts.androidInfo.targetSdk?.value ?? null, targetSdkAt: facts.androidInfo.targetSdk ? where(facts.androidInfo.targetSdk.at) : null, permissions: [...new Set(facts.androidInfo.permissions.map(x => x.name.replace(/^android\.permission\./, '')))] },
|
||||
findings, counts, declarations, scanned: facts.scanned, notes,
|
||||
};
|
||||
return { report, facts, config, configPath };
|
||||
}
|
||||
|
||||
const TAG: Record<Severity, string> = { blocker: 'BLOCKER', high: 'HIGH ', medium: 'MEDIUM ', low: 'low ' };
|
||||
const STACK: Record<Stack, string> = { 'ios-native': 'iOS (native)', 'android-native': 'Android (native)', 'react-native': 'React Native', expo: 'Expo', capacitor: 'Capacitor', cordova: 'Cordova', flutter: 'Flutter', unity: 'Unity', godot: 'Godot', web: 'web' };
|
||||
|
||||
/** The report as plain text (the terminal output of `storebound scan`). */
|
||||
export function formatScan(r: ScanReport, o: { declarations?: boolean } = {}): string {
|
||||
const L: string[] = [];
|
||||
L.push(`storebound scan · ${r.config ? r.config : 'no storebound.config.ts (project files only)'}`);
|
||||
if (r.configError) L.push(`config not loaded: ${r.configError}`);
|
||||
L.push(`stack: ${r.stacks.map(s => STACK[s]).join(', ') || 'unknown'} · targets: ${[r.platforms.ios && 'iOS', r.platforms.android && 'Android'].filter(Boolean).join(', ') || 'none found'} · ${r.scanned} files`);
|
||||
if (r.sdks.length) {
|
||||
L.push('', 'SDKs');
|
||||
for (const s of r.sdks) {
|
||||
const d = s.deps[0]!;
|
||||
L.push(` ${s.name.padEnd(30)} ${s.category}${s.tracking ? ', tracking-capable' : ''} · ${ECO_LABEL[d.eco as keyof typeof ECO_LABEL] ?? d.eco} ${d.name}${d.version ? ` ${d.version}` : ''} (${d.file}:${d.line})${s.deps.length > 1 ? ` +${s.deps.length - 1}` : ''}`);
|
||||
}
|
||||
}
|
||||
if (r.android.targetSdk !== null) L.push(`Android targetSdk ${r.android.targetSdk} (${r.android.targetSdkAt})`);
|
||||
const open = r.findings.filter(f => !f.accepted);
|
||||
L.push('', `Rejection risks: ${r.counts.blocker} blocker, ${r.counts.high} high, ${r.counts.medium} medium, ${r.counts.low} low${r.counts.accepted ? ` (+${r.counts.accepted} accepted by the owner)` : ''}`);
|
||||
if (!open.length) L.push(' none found in the project files and config');
|
||||
r.findings.forEach((f, i) => {
|
||||
L.push(`${String(i + 1).padStart(3)}. ${f.accepted ? 'accepted' : TAG[f.severity]} ${f.guideline} · ${f.store === 'apple' ? 'App Store' : 'Google Play'} · ${f.title}`);
|
||||
for (const e of f.evidence.slice(0, 3)) L.push(` at ${e.file}:${e.line}${e.text ? ` ${e.text}` : ''}`);
|
||||
if (f.accepted) L.push(` owner: ${f.accepted}`);
|
||||
else L.push(` fix: ${f.fix}`, ` skill: ${f.skill} · ${f.ref}`);
|
||||
});
|
||||
if (o.declarations !== false) {
|
||||
const d = r.declarations;
|
||||
L.push('', 'Declarations proposal (detected = proven by a file; ask owner = only the owner knows)');
|
||||
const areas: [string, string][] = [['dataSafety', 'Data safety'], ['appPrivacy', 'App Privacy'], ['att', 'App Tracking Transparency'], ['privacyManifest', 'Privacy manifest']];
|
||||
for (const [a, label] of areas) {
|
||||
const items = d.items.filter(x => x.area === a);
|
||||
if (!items.length) continue;
|
||||
L.push(` ${label}`);
|
||||
for (const x of items) L.push(` ${x.status === 'detected' ? 'detected ' : 'ask owner'} ${x.what}: ${x.value}${x.evidence[0] ? ` (${x.evidence[0].file}:${x.evidence[0].line})` : ''}${x.note ? ` · ${x.note}` : ''}`);
|
||||
}
|
||||
const changes = d.diff.filter(x => x.change === 'add' || x.change === 'merge');
|
||||
if (changes.length || d.appPrivacyChange) {
|
||||
L.push('', ` Diff against ${r.config ?? 'the config'} (written only with --write):`);
|
||||
for (const x of changes) {
|
||||
if (x.change === 'add') L.push(` + dataSafety.data.${x.type}: { shared: ${x.after.shared}, collect: [${x.after.collect.join(', ')}]${x.after.share?.length ? `, share: [${x.after.share.join(', ')}]` : ''} }`);
|
||||
else L.push(` ~ dataSafety.data.${x.type}: collect [${x.before!.collect.join(', ')}] -> [${x.after.collect.join(', ')}]${x.after.shared !== x.before!.shared ? `, shared ${x.before!.shared} -> ${x.after.shared}` : ''}${(x.after.share ?? []).join() !== (x.before!.share ?? []).join() ? `, share [${(x.before!.share ?? []).join(', ')}] -> [${(x.after.share ?? []).join(', ')}]` : ''}`);
|
||||
}
|
||||
if (d.appPrivacyChange) L.push(` ~ appPrivacy.tracking: ${d.appPrivacyChange.from ?? 'unset'} -> ${d.appPrivacyChange.to}`);
|
||||
} else if (r.config) L.push('', ` No changes to ${r.config}: the dataSafety / appPrivacy blocks already cover what was detected.`);
|
||||
}
|
||||
if (r.notes.length) L.push('', ...r.notes.map(n => `note: ${n}`));
|
||||
L.push('', 'Checked at review, not by scan: crashes and bugs on the reviewer\'s device, broken links (storebound validate checks the URLs), screenshots that do not match the app, minimum functionality and spam judgement (4.2, 4.3), local law (5.2). See the review-rejections skill.');
|
||||
return L.join('\n');
|
||||
}
|
||||
55
cli/lib/scan/permissions.ts
Normal file
55
cli/lib/scan/permissions.ts
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
// iOS privacy-sensitive APIs and the Info.plist purpose string each one needs (Apple: "Requesting access to protected
|
||||
// resources"; a missing string makes the app crash on the first request and App Store Connect rejects the upload
|
||||
// with ITMS-90683). `code` finds the API in app sources, `packages` the npm / pub / Unity packages that call it.
|
||||
// Checked 2026-10-11 against developer.apple.com/documentation/bundleresources/information-property-list.
|
||||
export interface PermissionDef {
|
||||
/** Info.plist keys; any one of them satisfies the check (e.g. calendars before / since iOS 17). */
|
||||
keys: string[];
|
||||
what: string;
|
||||
code: RegExp;
|
||||
packages: string[];
|
||||
}
|
||||
|
||||
export const IOS_PERMISSIONS: PermissionDef[] = [
|
||||
{ keys: ['NSCameraUsageDescription'], what: 'camera',
|
||||
code: /\bAVCaptureDevice\b|sourceType\s*=\s*\.camera|UIImagePickerController\.SourceType\.camera|\bWebCamTexture\b|\bVNDocumentCameraViewController\b/,
|
||||
packages: ['expo-camera', 'react-native-vision-camera', 'react-native-camera', '@capacitor/camera', 'image_picker', 'camera', 'mobile_scanner', 'expo-image-picker', 'react-native-image-picker', 'cordova-plugin-camera', '@capacitor-mlkit/barcode-scanning'] },
|
||||
{ keys: ['NSMicrophoneUsageDescription'], what: 'microphone',
|
||||
code: /\bAVAudioRecorder\b|requestRecordPermission|\.record\b.*AVAudioSession|AVAudioApplication\.requestRecordPermission|\bMicrophone\.Start\b|\bAudioEffectRecord\b/,
|
||||
packages: ['expo-av', 'react-native-audio-recorder-player', 'record', 'flutter_sound', 'cordova-plugin-media-capture', '@capacitor-community/voice-recorder'] },
|
||||
{ keys: ['NSPhotoLibraryUsageDescription'], what: 'photo library',
|
||||
code: /\bPHPhotoLibrary\.(requestAuthorization|shared)|\bPHAsset\.fetch|\bALAssetsLibrary\b/,
|
||||
packages: ['expo-media-library', 'photo_manager', '@react-native-camera-roll/camera-roll', 'image_picker', '@capacitor/camera'] },
|
||||
{ keys: ['NSPhotoLibraryAddUsageDescription', 'NSPhotoLibraryUsageDescription'], what: 'saving to the photo library',
|
||||
code: /UIImageWriteToSavedPhotosAlbum|UISaveVideoAtPathToSavedPhotosAlbum|PHAssetChangeRequest|PHAssetCreationRequest/,
|
||||
packages: ['gallery_saver', 'image_gallery_saver'] },
|
||||
{ keys: ['NSLocationWhenInUseUsageDescription', 'NSLocationAlwaysAndWhenInUseUsageDescription'], what: 'location',
|
||||
code: /\bCLLocationManager\b|requestWhenInUseAuthorization|requestAlwaysAuthorization|\bInput\.location\.Start\b|\bCLLocationUpdate\b/,
|
||||
packages: ['expo-location', '@capacitor/geolocation', 'geolocator', 'location', '@react-native-community/geolocation', 'react-native-geolocation-service', 'cordova-plugin-geolocation'] },
|
||||
{ keys: ['NSContactsUsageDescription'], what: 'contacts',
|
||||
code: /\bCNContactStore\b|\bABAddressBook/,
|
||||
packages: ['expo-contacts', 'react-native-contacts', 'flutter_contacts', 'contacts_service', '@capacitor-community/contacts', 'cordova-plugin-contacts'] },
|
||||
{ keys: ['NSCalendarsFullAccessUsageDescription', 'NSCalendarsWriteOnlyAccessUsageDescription', 'NSCalendarsUsageDescription'], what: 'calendars',
|
||||
code: /\bEKEventStore\b/, packages: ['expo-calendar', 'device_calendar', 'react-native-calendar-events'] },
|
||||
{ keys: ['NSRemindersFullAccessUsageDescription', 'NSRemindersUsageDescription'], what: 'reminders', code: /requestFullAccessToReminders|entityType:\s*\.reminder|EKEntityType\.reminder/, packages: [] },
|
||||
{ keys: ['NSBluetoothAlwaysUsageDescription'], what: 'Bluetooth',
|
||||
code: /\bCBCentralManager\b|\bCBPeripheralManager\b/, packages: ['react-native-ble-plx', 'flutter_blue_plus', 'flutter_blue', '@capacitor-community/bluetooth-le', 'cordova-plugin-ble-central'] },
|
||||
{ keys: ['NSFaceIDUsageDescription'], what: 'Face ID',
|
||||
code: /deviceOwnerAuthenticationWithBiometrics|evaluatePolicy\(/, packages: ['expo-local-authentication', 'local_auth', 'react-native-biometrics', '@capgo/capacitor-native-biometric'] },
|
||||
{ keys: ['NSMotionUsageDescription'], what: 'motion and fitness', code: /\bCMMotionActivityManager\b|\bCMPedometer\b|\bCMAltimeter\b/, packages: ['expo-sensors'] },
|
||||
{ keys: ['NSSpeechRecognitionUsageDescription'], what: 'speech recognition', code: /\bSFSpeechRecognizer\b/, packages: ['@react-native-voice/voice', 'speech_to_text', 'expo-speech-recognition'] },
|
||||
{ keys: ['NSHealthShareUsageDescription'], what: 'Health data', code: /\bHKHealthStore\b/, packages: ['react-native-health', 'health', '@kingstinct/react-native-healthkit'] },
|
||||
{ keys: ['NSUserTrackingUsageDescription'], what: 'App Tracking Transparency',
|
||||
code: /requestTrackingAuthorization|ATTrackingStatusBinding\.RequestAuthorizationTracking/,
|
||||
packages: ['expo-tracking-transparency', 'react-native-tracking-transparency', 'app_tracking_transparency', '@capacitor-community/app-tracking-transparency', 'com.unity.ads.ios-support'] },
|
||||
];
|
||||
|
||||
/** A purpose string that says nothing (empty, a placeholder, or a generic template Apple rejects under 5.1.1(ii)). */
|
||||
export function vaguePurpose(s: string): 'empty' | 'vague' | null {
|
||||
const t = s.trim();
|
||||
if (!t) return 'empty';
|
||||
if (/^(todo|tbd|fixme|placeholder|lorem|test|xxx+|\.+|-+|description|usage description|\$\([A-Z_]+\))$/i.test(t)) return 'empty';
|
||||
// Expo / plugin defaults like "Allow $(PRODUCT_NAME) to access your camera" name no reason
|
||||
if (t.length < 20 || /^(allow|let) \$\(PRODUCT_NAME\) to access your [a-z ]+\.?$/i.test(t) || /^(this app|we) (needs?|requires?|uses?) (access to )?(your )?[a-z ]+\.?$/i.test(t)) return 'vague';
|
||||
return null;
|
||||
}
|
||||
430
cli/lib/scan/project.ts
Normal file
430
cli/lib/scan/project.ts
Normal file
|
|
@ -0,0 +1,430 @@
|
|||
// Project detection for `storebound scan`: reads a mobile app or game project (read-only, offline) and works out the
|
||||
// stack, the dependencies (with versions and the file:line they come from), the Info.plist keys (from Info.plist files,
|
||||
// Xcode INFOPLIST_KEY_* build settings, Expo app.json, Unity ProjectSettings and Godot export presets), entitlements,
|
||||
// privacy manifests, the Android manifest (permissions, services, target SDK) and the app's own source files.
|
||||
// Tolerant on purpose: an unreadable or odd file is skipped, never an exception.
|
||||
import { readdirSync, readFileSync, statSync } from 'node:fs';
|
||||
import { basename, extname, join, relative, sep } from 'node:path';
|
||||
import { type Manifest, parseManifest } from '../privacy-manifest';
|
||||
import { type DepRef, type Eco, matchesSdk, SDKS, type SdkDef } from './sdks';
|
||||
|
||||
export interface Loc { file: string; line: number }
|
||||
export interface PlistEntry { key: string; value: unknown; at: Loc }
|
||||
export interface Hit extends Loc { text: string }
|
||||
|
||||
export type Stack = 'ios-native' | 'android-native' | 'react-native' | 'expo' | 'capacitor' | 'cordova' | 'flutter' | 'unity' | 'godot' | 'web';
|
||||
|
||||
export interface DetectedSdk { sdk: SdkDef; deps: DepRef[] }
|
||||
|
||||
export interface ProjectFacts {
|
||||
root: string;
|
||||
stacks: Stack[];
|
||||
/** The project has iOS / Android build files (or a cross-platform engine that targets them). */
|
||||
ios: boolean;
|
||||
android: boolean;
|
||||
deps: DepRef[];
|
||||
sdks: DetectedSdk[];
|
||||
/** Info.plist keys merged from every source; first source wins. */
|
||||
plist: Map<string, PlistEntry>;
|
||||
/** Where Info.plist keys came from (empty = the project has no readable iOS settings: plist rules are skipped). */
|
||||
plistSources: string[];
|
||||
entitlements: Map<string, PlistEntry>;
|
||||
privacyManifests: Manifest[];
|
||||
androidInfo: {
|
||||
manifests: string[];
|
||||
permissions: { name: string; at: Loc }[];
|
||||
services: { name: string; fgsType: string | null; at: Loc }[];
|
||||
targetSdk: { value: number; at: Loc } | null;
|
||||
/** targetSdk is set by a tool we cannot read (Flutter SDK, Expo SDK, Unity "automatic"). */
|
||||
targetSdkFrom: string | null;
|
||||
formFactor: 'phone' | 'wear' | 'tv' | 'automotive';
|
||||
};
|
||||
/** Capacitor server.url / Cordova <content src> pointing at a remote site. */
|
||||
remoteStart: { url: string; at: Loc } | null;
|
||||
/** App source files (Swift, Objective-C, Kotlin, Java, Dart, JS / TS, C#, GDScript, HTML). */
|
||||
sources: { path: string; text: string }[];
|
||||
/** Files looked at, relative to root (for the report). */
|
||||
scanned: number;
|
||||
}
|
||||
|
||||
const SKIP_DIRS = new Set(['.git', 'node_modules', 'Pods', 'build', 'Build', 'DerivedData', '.gradle', '.dart_tool', '.build', 'Library', 'Temp', 'Logs',
|
||||
'obj', 'UserSettings', '.storebound', 'renders', '.idea', '.vscode', '.expo', 'vendor', 'xcuserdata', 'Carthage', '.next', 'coverage', '.godot',
|
||||
'intermediates', 'generated', 'outputs', 'tmp', '.cxx', 'fastlane', 'dist', 'www', 'public', 'clips', 'frames', 'fonts']);
|
||||
const SRC_EXT = new Set(['.swift', '.m', '.mm', '.h', '.kt', '.java', '.dart', '.js', '.jsx', '.ts', '.tsx', '.cs', '.gd', '.html', '.vue', '.svelte']);
|
||||
const MAX_FILES = 25_000;
|
||||
const MAX_TEXT = 1_500_000;
|
||||
|
||||
/** Every file under root (relative paths), skipping build output, dependency folders and VCS data. */
|
||||
export function listFiles(root: string): string[] {
|
||||
const out: string[] = [];
|
||||
const walk = (dir: string, depth: number) => {
|
||||
if (depth > 14 || out.length >= MAX_FILES) return;
|
||||
let names: string[];
|
||||
try { names = readdirSync(dir); } catch { return; }
|
||||
for (const n of names.sort()) {
|
||||
if (SKIP_DIRS.has(n) || n === '.DS_Store') continue;
|
||||
const p = join(dir, n);
|
||||
let st;
|
||||
try { st = statSync(p); } catch { continue; }
|
||||
if (st.isDirectory()) {
|
||||
// compiled frameworks are SDK binaries, not app code
|
||||
if (/\.(xc)?framework$|\.xcassets$|\.bundle$|\.app$|\.dSYM$/.test(n)) continue;
|
||||
walk(p, depth + 1);
|
||||
} else if (st.size <= MAX_TEXT) out.push(relative(root, p).split(sep).join('/'));
|
||||
if (out.length >= MAX_FILES) return;
|
||||
}
|
||||
};
|
||||
walk(root, 0);
|
||||
return out;
|
||||
}
|
||||
|
||||
export const lineAt = (text: string, index: number): number => (index <= 0 ? 1 : text.slice(0, index).split('\n').length);
|
||||
/** Line of the first occurrence of `needle` (1 when not found). */
|
||||
export const lineOf = (text: string, needle: string | RegExp): number => {
|
||||
const i = typeof needle === 'string' ? text.indexOf(needle) : text.search(needle);
|
||||
return i < 0 ? 1 : lineAt(text, i);
|
||||
};
|
||||
|
||||
// ---- plist ----
|
||||
|
||||
type PV = string | number | boolean | PV[] | { [k: string]: PV };
|
||||
|
||||
/** Minimal XML plist reader: the value tree, plus the line of every top-level key. Never throws (bad input -> {}). */
|
||||
export function parsePlist(xml: string): { value: Record<string, PV>; lines: Map<string, number> } {
|
||||
const lines = new Map<string, number>();
|
||||
const re = /<(\/?)(dict|array|key|string|integer|real|true|false|date|data)(\s*\/)?>|<!--[\s\S]*?-->|<\?[\s\S]*?\?>|<!DOCTYPE[^>]*>|<\/?plist[^>]*>/g;
|
||||
const toks: { tag: string; close: boolean; self: boolean; at: number; end: number }[] = [];
|
||||
for (const m of xml.matchAll(re)) if (m[2]) toks.push({ tag: m[2], close: m[1] === '/', self: !!m[3] || m[2] === 'true' || m[2] === 'false', at: m.index!, end: m.index! + m[0].length });
|
||||
let i = 0;
|
||||
const unesc = (s: string) => s.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, '\'').replace(/&/g, '&');
|
||||
const readText = (tag: string): string => {
|
||||
const open = toks[i]!;
|
||||
if (open.self) { i++; return ''; }
|
||||
const close = toks[i + 1];
|
||||
i += 2;
|
||||
return close && close.tag === tag && close.close ? unesc(xml.slice(open.end, close.at)) : '';
|
||||
};
|
||||
const value = (depth: number): PV => {
|
||||
const t = toks[i];
|
||||
if (!t || depth > 30) { i++; return ''; }
|
||||
switch (t.tag) {
|
||||
case 'true': i++; if (toks[i]?.tag === 'true' && toks[i]!.close) i++; return true;
|
||||
case 'false': i++; if (toks[i]?.tag === 'false' && toks[i]!.close) i++; return false;
|
||||
case 'integer': case 'real': return Number(readText(t.tag));
|
||||
case 'string': case 'date': case 'data': return readText(t.tag);
|
||||
case 'array': {
|
||||
i++;
|
||||
const a: PV[] = [];
|
||||
if (t.self) return a;
|
||||
while (i < toks.length && !(toks[i]!.tag === 'array' && toks[i]!.close)) a.push(value(depth + 1));
|
||||
i++;
|
||||
return a;
|
||||
}
|
||||
case 'dict': {
|
||||
i++;
|
||||
const o: Record<string, PV> = {};
|
||||
if (t.self) return o;
|
||||
while (i < toks.length && !(toks[i]!.tag === 'dict' && toks[i]!.close)) {
|
||||
if (toks[i]!.tag !== 'key') { i++; continue; }
|
||||
const at = toks[i]!.at;
|
||||
const k = readText('key');
|
||||
if (depth === 0) lines.set(k, lineAt(xml, at));
|
||||
o[k] = value(depth + 1);
|
||||
}
|
||||
i++;
|
||||
return o;
|
||||
}
|
||||
default: i++; return '';
|
||||
}
|
||||
};
|
||||
while (i < toks.length && toks[i]!.tag !== 'dict') i++;
|
||||
const v = i < toks.length ? value(0) : {};
|
||||
return { value: (v && typeof v === 'object' && !Array.isArray(v) ? v : {}) as Record<string, PV>, lines };
|
||||
}
|
||||
|
||||
// ---- dependency files ----
|
||||
|
||||
function podsLock(file: string, text: string): DepRef[] {
|
||||
const out: DepRef[] = [];
|
||||
const pods = /^PODS:\n([\s\S]*?)(?=\n\S|$(?![\s\S]))/m.exec(text)?.[1] ?? '';
|
||||
const off = text.indexOf(pods);
|
||||
for (const m of pods.matchAll(/^ {2}- "?([A-Za-z0-9_.+\-/]+) \(([^)]+)\)"?:?$/gm))
|
||||
out.push({ eco: 'cocoapods', name: m[1]!, version: m[2]!, file, line: lineAt(text, off + m.index!) });
|
||||
return out;
|
||||
}
|
||||
function podfile(file: string, text: string): DepRef[] {
|
||||
return [...text.matchAll(/^\s*pod\s+['"]([^'"]+)['"](?:\s*,\s*['"]([^'"]+)['"])?/gm)].map(m => ({ eco: 'cocoapods' as const, name: m[1]!, version: m[2] ?? null, file, line: lineAt(text, m.index!) }));
|
||||
}
|
||||
function packageResolved(file: string, text: string): DepRef[] {
|
||||
try {
|
||||
const j = JSON.parse(text) as { pins?: { identity?: string; location?: string; state?: { version?: string } }[]; object?: { pins?: { package?: string; repositoryURL?: string; state?: { version?: string } }[] } };
|
||||
const pins = j.pins ?? j.object?.pins?.map(p => ({ identity: p.package, location: p.repositoryURL, state: p.state })) ?? [];
|
||||
return pins.map(p => ({ eco: 'spm' as const, name: p.location ?? p.identity ?? '', version: p.state?.version ?? null, file, line: lineOf(text, p.location ?? p.identity ?? '') }));
|
||||
} catch { return []; }
|
||||
}
|
||||
function pbxproj(file: string, text: string): DepRef[] {
|
||||
const out: DepRef[] = [];
|
||||
for (const m of text.matchAll(/repositoryURL = "([^"]+)";/g)) out.push({ eco: 'spm', name: m[1]!, version: null, file, line: lineAt(text, m.index!) });
|
||||
for (const m of text.matchAll(/isa = XCSwiftPackageProductDependency;[\s\S]{0,300}?productName = "?([A-Za-z0-9_-]+)"?;/g)) out.push({ eco: 'spm', name: m[1]!, version: null, file, line: lineAt(text, m.index!) });
|
||||
return out;
|
||||
}
|
||||
function cartfile(file: string, text: string): DepRef[] {
|
||||
return [...text.matchAll(/^\s*(?:github|git|binary)\s+"([^"]+)"(?:\s+"?([^"\n]+)"?)?/gm)].map(m => ({ eco: 'carthage' as const, name: m[1]!, version: m[2]?.trim() ?? null, file, line: lineAt(text, m.index!) }));
|
||||
}
|
||||
function gradle(file: string, text: string): DepRef[] {
|
||||
const out: DepRef[] = [];
|
||||
for (const m of text.matchAll(/(?:implementation|api|compileOnly|runtimeOnly|kapt|ksp|annotationProcessor|classpath)\s*\(?\s*(?:platform\(\s*)?["']([A-Za-z0-9_.\-]+):([A-Za-z0-9_.\-]+)(?::([^"'@]+))?/g))
|
||||
out.push({ eco: 'gradle', name: `${m[1]}:${m[2]}`, version: m[3] ?? null, file, line: lineAt(text, m.index!) });
|
||||
return out;
|
||||
}
|
||||
function versionCatalog(file: string, text: string): DepRef[] {
|
||||
const versions = new Map<string, string>();
|
||||
const vsec = /^\[versions\]\n([\s\S]*?)(?=^\[|$(?![\s\S]))/m.exec(text)?.[1] ?? '';
|
||||
for (const m of vsec.matchAll(/^\s*([A-Za-z0-9_.\-]+)\s*=\s*"([^"]+)"/gm)) versions.set(m[1]!, m[2]!);
|
||||
const out: DepRef[] = [];
|
||||
for (const m of text.matchAll(/^\s*[A-Za-z0-9_.\-]+\s*=\s*\{([^}]*)\}/gm)) {
|
||||
const body = m[1]!;
|
||||
const mod = /module\s*=\s*"([^":]+):([^"]+)"/.exec(body);
|
||||
const grp = /group\s*=\s*"([^"]+)"/.exec(body), nm = /name\s*=\s*"([^"]+)"/.exec(body);
|
||||
const name = mod ? `${mod[1]}:${mod[2]}` : grp && nm ? `${grp[1]}:${nm[1]}` : null;
|
||||
if (!name) continue;
|
||||
const ver = /version\.ref\s*=\s*"([^"]+)"/.exec(body)?.[1];
|
||||
out.push({ eco: 'gradle', name, version: ver ? versions.get(ver) ?? null : /version\s*=\s*"([^"]+)"/.exec(body)?.[1] ?? null, file, line: lineAt(text, m.index!) });
|
||||
}
|
||||
for (const m of text.matchAll(/^\s*[A-Za-z0-9_.\-]+\s*=\s*"([A-Za-z0-9_.\-]+):([A-Za-z0-9_.\-]+):([^"]+)"/gm))
|
||||
out.push({ eco: 'gradle', name: `${m[1]}:${m[2]}`, version: m[3]!, file, line: lineAt(text, m.index!) });
|
||||
return out;
|
||||
}
|
||||
function packageJson(file: string, text: string): DepRef[] {
|
||||
try {
|
||||
const j = JSON.parse(text) as { dependencies?: Record<string, string> };
|
||||
return Object.entries(j.dependencies ?? {}).map(([n, v]) => ({ eco: 'npm' as const, name: n, version: v, file, line: lineOf(text, `"${n}"`) }));
|
||||
} catch { return []; }
|
||||
}
|
||||
function pubspec(file: string, text: string): DepRef[] {
|
||||
const sec = /^dependencies:\n([\s\S]*?)(?=^\S|$(?![\s\S]))/m.exec(text);
|
||||
if (!sec) return [];
|
||||
const off = sec.index + 'dependencies:\n'.length;
|
||||
return [...sec[1]!.matchAll(/^ {2}([a-z0-9_]+):\s*([^\n#]*)/gm)].map(m => ({ eco: 'pub' as const, name: m[1]!, version: m[2]!.trim() || null, file, line: lineAt(text, off + m.index!) }));
|
||||
}
|
||||
function pubspecLock(text: string): Map<string, string> {
|
||||
const out = new Map<string, string>();
|
||||
for (const m of text.matchAll(/^ {2}([a-z0-9_]+):\n(?: {4}.*\n)*? {4}version: "([^"]+)"/gm)) out.set(m[1]!, m[2]!);
|
||||
return out;
|
||||
}
|
||||
function unityManifest(file: string, text: string): DepRef[] {
|
||||
try {
|
||||
const j = JSON.parse(text) as { dependencies?: Record<string, string> };
|
||||
return Object.entries(j.dependencies ?? {}).map(([n, v]) => ({ eco: 'unity' as const, name: n, version: v, file, line: lineOf(text, `"${n}"`) }));
|
||||
} catch { return []; }
|
||||
}
|
||||
/** External Dependency Manager (Assets/.../Editor/*Dependencies.xml): the pods and Gradle packages a Unity plugin adds. */
|
||||
function edmXml(file: string, text: string): DepRef[] {
|
||||
const out: DepRef[] = [];
|
||||
for (const m of text.matchAll(/<iosPod\s+name="([^"]+)"(?:\s+version="([^"]+)")?/g)) out.push({ eco: 'cocoapods', name: m[1]!, version: m[2] ?? null, file, line: lineAt(text, m.index!) });
|
||||
for (const m of text.matchAll(/<androidPackage\s+spec="([^":]+):([^":]+)(?::([^"]+))?"/g)) out.push({ eco: 'gradle', name: `${m[1]}:${m[2]}`, version: m[3] ?? null, file, line: lineAt(text, m.index!) });
|
||||
return out;
|
||||
}
|
||||
function cordovaXml(file: string, text: string): DepRef[] {
|
||||
return [...text.matchAll(/<plugin\s+name="([^"]+)"(?:\s+spec="([^"]+)")?/g)].map(m => ({ eco: 'npm' as const, name: m[1]!, version: m[2] ?? null, file, line: lineAt(text, m.index!) }));
|
||||
}
|
||||
|
||||
// ---- Info.plist key sources other than Info.plist ----
|
||||
|
||||
const UNITY_KEYS: Record<string, string> = { cameraUsageDescription: 'NSCameraUsageDescription', locationUsageDescription: 'NSLocationWhenInUseUsageDescription', microphoneUsageDescription: 'NSMicrophoneUsageDescription' };
|
||||
const GODOT_KEYS: Record<string, string> = {
|
||||
'privacy/camera_usage_description': 'NSCameraUsageDescription', 'privacy/microphone_usage_description': 'NSMicrophoneUsageDescription',
|
||||
'privacy/photolibrary_usage_description': 'NSPhotoLibraryUsageDescription',
|
||||
};
|
||||
|
||||
export function detectProject(root: string): ProjectFacts {
|
||||
const files = listFiles(root);
|
||||
const cache = new Map<string, string>();
|
||||
const read = (f: string): string => {
|
||||
if (!cache.has(f)) { try { cache.set(f, readFileSync(join(root, f), 'utf8')); } catch { cache.set(f, ''); } }
|
||||
return cache.get(f)!;
|
||||
};
|
||||
const has = (re: RegExp) => files.some(f => re.test(f));
|
||||
const deps: DepRef[] = [];
|
||||
const plist = new Map<string, PlistEntry>();
|
||||
const plistSources: string[] = [];
|
||||
const entitlements = new Map<string, PlistEntry>();
|
||||
const privacyManifests: Manifest[] = [];
|
||||
const setKey = (m: Map<string, PlistEntry>, key: string, value: unknown, at: Loc) => { if (!m.has(key)) m.set(key, { key, value, at }); };
|
||||
const android: ProjectFacts['androidInfo'] = { manifests: [], permissions: [], services: [], targetSdk: null, targetSdkFrom: null, formFactor: 'phone' };
|
||||
const sdkHits: { value: number; at: Loc; prio: number }[] = [];
|
||||
let remoteStart: ProjectFacts['remoteStart'] = null;
|
||||
const sources: { path: string; text: string }[] = [];
|
||||
const stacks = new Set<Stack>();
|
||||
let pubLock = new Map<string, string>();
|
||||
|
||||
for (const f of files) {
|
||||
const n = basename(f);
|
||||
const testy = /(^|\/)(Tests?|UITests|[A-Za-z]+Tests|test|androidTest|__tests__|Example|Samples?)\//.test(f);
|
||||
if (n === 'Info.plist' && !testy && !/\.(app|appex)\//.test(f)) {
|
||||
const { value, lines } = parsePlist(read(f));
|
||||
if (Object.keys(value).length) plistSources.push(f);
|
||||
for (const [k, v] of Object.entries(value)) setKey(plist, k, v, { file: f, line: lines.get(k) ?? 1 });
|
||||
} else if (n.endsWith('.entitlements')) {
|
||||
const { value, lines } = parsePlist(read(f));
|
||||
for (const [k, v] of Object.entries(value)) setKey(entitlements, k, v, { file: f, line: lines.get(k) ?? 1 });
|
||||
} else if (n === 'PrivacyInfo.xcprivacy') privacyManifests.push(parseManifest(f, read(f)));
|
||||
else if (n === 'project.pbxproj') {
|
||||
const t = read(f);
|
||||
deps.push(...pbxproj(f, t));
|
||||
let found = false;
|
||||
for (const m of t.matchAll(/INFOPLIST_KEY_([A-Za-z]+) = ("(?:[^"\\]|\\.)*"|[^;\n]*);/g)) {
|
||||
found = true;
|
||||
setKey(plist, m[1]!, m[2]!.replace(/^"|"$/g, '').replace(/\\"/g, '"'), { file: f, line: lineAt(t, m.index!) });
|
||||
}
|
||||
if (found) plistSources.push(f);
|
||||
} else if (n === 'Podfile.lock') deps.push(...podsLock(f, read(f)));
|
||||
else if (n === 'Podfile') deps.push(...podfile(f, read(f)));
|
||||
else if (n === 'Package.resolved') deps.push(...packageResolved(f, read(f)));
|
||||
else if (n === 'Cartfile' || n === 'Cartfile.resolved') deps.push(...cartfile(f, read(f)));
|
||||
else if (/^(build\.gradle(\.kts)?|variables\.gradle|settings\.gradle(\.kts)?)$/.test(n)) {
|
||||
const t = read(f);
|
||||
deps.push(...gradle(f, t));
|
||||
for (const m of t.matchAll(/\btargetSdk(?:Version)?\s*(?:=|\s)\s*\(?\s*(\d{2})\b/g))
|
||||
sdkHits.push({ value: Number(m[1]), at: { file: f, line: lineAt(t, m.index!) }, prio: /(^|\/)app\/|variables\.gradle/.test(f) ? 0 : 1 });
|
||||
if (/targetSdk(?:Version)?\s*(?:=|\s)\s*flutter\.targetSdkVersion/.test(t)) android.targetSdkFrom = 'the Flutter SDK (flutter.targetSdkVersion)';
|
||||
} else if (n === 'libs.versions.toml') {
|
||||
const t = read(f);
|
||||
deps.push(...versionCatalog(f, t));
|
||||
for (const m of t.matchAll(/^\s*(?:target-?sdk|targetSdk|android-?target-?sdk)\w*\s*=\s*"(\d{2})"/gim)) sdkHits.push({ value: Number(m[1]), at: { file: f, line: lineAt(t, m.index!) }, prio: 0 });
|
||||
} else if (n === 'AndroidManifest.xml' && /(^|\/)src\/main\/AndroidManifest\.xml$|^AndroidManifest\.xml$|Plugins\/Android\/AndroidManifest\.xml$/.test(f) && !testy) {
|
||||
const t = read(f);
|
||||
android.manifests.push(f);
|
||||
for (const m of t.matchAll(/<uses-permission(?:-sdk-23)?\b([^>]*?)\/?>/g)) {
|
||||
const name = /android:name="([^"]+)"/.exec(m[1]!)?.[1];
|
||||
if (name && !/tools:node="remove"/.test(m[1]!)) android.permissions.push({ name, at: { file: f, line: lineAt(t, m.index!) } });
|
||||
}
|
||||
for (const m of t.matchAll(/<service\b([^>]*?)(\/>|>)/g)) {
|
||||
const name = /android:name="([^"]+)"/.exec(m[1]!)?.[1] ?? '?';
|
||||
android.services.push({ name, fgsType: /android:foregroundServiceType="([^"]+)"/.exec(m[1]!)?.[1] ?? null, at: { file: f, line: lineAt(t, m.index!) } });
|
||||
}
|
||||
if (/android\.hardware\.type\.watch/.test(t)) android.formFactor = 'wear';
|
||||
else if (/android\.software\.leanback"[^>]*android:required="true"|android:required="true"[^>]*android\.software\.leanback/.test(t)) android.formFactor = 'tv';
|
||||
else if (/android\.hardware\.type\.automotive/.test(t)) android.formFactor = 'automotive';
|
||||
} else if (n === 'package.json' && !f.includes('/node_modules/')) {
|
||||
const t = read(f);
|
||||
const d = packageJson(f, t);
|
||||
deps.push(...d);
|
||||
const names = new Set(d.map(x => x.name));
|
||||
if (names.has('react-native')) stacks.add('react-native');
|
||||
if (names.has('expo')) stacks.add('expo');
|
||||
if ([...names].some(x => x.startsWith('@capacitor/'))) stacks.add('capacitor');
|
||||
if (names.has('cordova-android') || names.has('cordova-ios')) stacks.add('cordova');
|
||||
} else if ((n === 'app.json' || n === 'app.config.json') && !f.includes('/')) {
|
||||
const t = read(f);
|
||||
try {
|
||||
const j = JSON.parse(t) as { expo?: { ios?: { infoPlist?: Record<string, unknown>; usesAppleSignIn?: boolean }; android?: { permissions?: string[] }; plugins?: unknown[] } };
|
||||
if (j.expo) {
|
||||
stacks.add('expo');
|
||||
plistSources.push(f);
|
||||
for (const [k, v] of Object.entries(j.expo.ios?.infoPlist ?? {})) setKey(plist, k, v, { file: f, line: lineOf(t, `"${k}"`) });
|
||||
if (j.expo.ios?.usesAppleSignIn) setKey(entitlements, 'com.apple.developer.applesignin', ['Default'], { file: f, line: lineOf(t, '"usesAppleSignIn"') });
|
||||
for (const p of j.expo.android?.permissions ?? []) android.permissions.push({ name: p.includes('.') ? p : `android.permission.${p}`, at: { file: f, line: lineOf(t, `"${p}"`) } });
|
||||
for (const p of j.expo.plugins ?? []) {
|
||||
if (Array.isArray(p) && p[0] === 'expo-build-properties') {
|
||||
const ts = (p[1] as { android?: { targetSdkVersion?: number } } | undefined)?.android?.targetSdkVersion;
|
||||
if (ts) sdkHits.push({ value: ts, at: { file: f, line: lineOf(t, '"targetSdkVersion"') }, prio: 0 });
|
||||
}
|
||||
}
|
||||
if (!android.targetSdkFrom) android.targetSdkFrom = 'the Expo SDK version (expo-build-properties android.targetSdkVersion overrides it)';
|
||||
}
|
||||
} catch { /* not JSON */ }
|
||||
} else if (/^capacitor\.config\.(json|ts|js)$/.test(n)) {
|
||||
stacks.add('capacitor');
|
||||
const t = read(f);
|
||||
const m = /server\s*["']?\s*:\s*\{[\s\S]*?\burl["']?\s*:\s*["'](https?:\/\/[^"']+)["']/.exec(t);
|
||||
if (m && !/^https?:\/\/(localhost|127\.0\.0\.1|10\.0\.2\.2|192\.168\.)/.test(m[1]!)) remoteStart = { url: m[1]!, at: { file: f, line: lineAt(t, m.index! + m[0].indexOf(m[1]!)) } };
|
||||
} else if (n === 'config.xml' && /<widget\b/.test(read(f))) {
|
||||
stacks.add('cordova');
|
||||
const t = read(f);
|
||||
deps.push(...cordovaXml(f, t));
|
||||
const m = /<content\s+src="(https?:\/\/[^"]+)"/.exec(t);
|
||||
if (m && !/localhost|127\.0\.0\.1/.test(m[1]!)) remoteStart = { url: m[1]!, at: { file: f, line: lineAt(t, m.index!) } };
|
||||
} else if (n === 'pubspec.yaml') { stacks.add('flutter'); deps.push(...pubspec(f, read(f))); }
|
||||
else if (n === 'pubspec.lock') pubLock = pubspecLock(read(f));
|
||||
else if (f === 'Packages/manifest.json' || f.endsWith('/Packages/manifest.json')) { stacks.add('unity'); deps.push(...unityManifest(f, read(f))); }
|
||||
else if (/Dependencies\.xml$/.test(n) && /\/Editor\//.test(f)) deps.push(...edmXml(f, read(f)));
|
||||
else if (n === 'ProjectSettings.asset') {
|
||||
stacks.add('unity');
|
||||
const t = read(f);
|
||||
let any = false;
|
||||
for (const [uk, pk] of Object.entries(UNITY_KEYS)) {
|
||||
const m = new RegExp(`^\\s*${uk}:[ \\t]*(.*)$`, 'm').exec(t);
|
||||
if (m) { any = true; setKey(plist, pk, m[1]!.trim().replace(/^'|'$/g, ''), { file: f, line: lineAt(t, m.index) }); }
|
||||
}
|
||||
if (any) plistSources.push(f);
|
||||
const ts = /^\s*AndroidTargetSdkVersion:\s*(\d+)/m.exec(t);
|
||||
if (ts && Number(ts[1]) > 0) sdkHits.push({ value: Number(ts[1]), at: { file: f, line: lineAt(t, ts.index) }, prio: 0 });
|
||||
else if (ts) android.targetSdkFrom = 'Unity "Automatic (highest installed)": the Android SDK the build machine has';
|
||||
} else if (n === 'export_presets.cfg') {
|
||||
stacks.add('godot');
|
||||
const t = read(f);
|
||||
let any = false;
|
||||
for (const [gk, pk] of Object.entries(GODOT_KEYS)) {
|
||||
const m = new RegExp(`^${gk.replace('/', '\\/')}="(.*)"`, 'm').exec(t);
|
||||
if (m) { any = true; setKey(plist, pk, m[1]!, { file: f, line: lineAt(t, m.index) }); }
|
||||
}
|
||||
if (any) plistSources.push(f);
|
||||
const ts = /^gradle_build\/target_sdk="(\d+)"/m.exec(t);
|
||||
if (ts) sdkHits.push({ value: Number(ts[1]), at: { file: f, line: lineAt(t, ts.index) }, prio: 0 });
|
||||
for (const m of t.matchAll(/^permissions\/([a-z_]+)=true/gm)) android.permissions.push({ name: `android.permission.${m[1]!.toUpperCase()}`, at: { file: f, line: lineAt(t, m.index!) } });
|
||||
}
|
||||
// app sources
|
||||
if (SRC_EXT.has(extname(n)) && !testy && !/\.min\.js$|\.d\.ts$|(^|\/)(Plugins|ThirdParty|third_party|Packages|addons)\//.test(f) && !/\.config\.(ts|js)$/.test(n)) {
|
||||
const t = read(f);
|
||||
if (t && !t.includes('\u0000')) sources.push({ path: f, text: t });
|
||||
}
|
||||
}
|
||||
// Unity / Godot plugin folders count as dependencies (a folder under Assets/ or addons/)
|
||||
for (const d of new Set(files.map(f => /^Assets\/([^/]+)\//.exec(f)?.[1]).filter((x): x is string => !!x)))
|
||||
deps.push({ eco: 'unity', name: d, version: null, file: `Assets/${d}/`, line: 1 });
|
||||
for (const d of new Set(files.map(f => /^addons\/([^/]+)\//.exec(f)?.[1]).filter((x): x is string => !!x)))
|
||||
deps.push({ eco: 'godot', name: d, version: null, file: `addons/${d}/`, line: 1 });
|
||||
for (const d of deps) if (d.eco === 'pub' && pubLock.has(d.name)) d.version = pubLock.get(d.name)!;
|
||||
|
||||
if (has(/\.xcodeproj\/project\.pbxproj$/) && !stacks.has('flutter') && !stacks.has('react-native') && !stacks.has('capacitor') && !stacks.has('cordova') && !stacks.has('unity')) stacks.add('ios-native');
|
||||
if (android.manifests.length && !stacks.has('flutter') && !stacks.has('react-native') && !stacks.has('capacitor') && !stacks.has('cordova') && !stacks.has('unity') && !stacks.has('godot')) stacks.add('android-native');
|
||||
if (!stacks.size && has(/(^|\/)index\.html$/)) stacks.add('web');
|
||||
const ios = has(/\.xcodeproj\/project\.pbxproj$/) || plistSources.length > 0 || stacks.has('expo') || stacks.has('unity') || (stacks.has('godot') && /platform="iOS"/.test(read(files.find(f => basename(f) === 'export_presets.cfg') ?? '')));
|
||||
const isAndroid = android.manifests.length > 0 || has(/(^|\/)build\.gradle(\.kts)?$/) || stacks.has('expo') || stacks.has('unity') || (stacks.has('godot') && /platform="Android"/.test(read(files.find(f => basename(f) === 'export_presets.cfg') ?? '')));
|
||||
if (sdkHits.length) {
|
||||
sdkHits.sort((a, b) => a.prio - b.prio || a.value - b.value);
|
||||
android.targetSdk = { value: sdkHits[0]!.value, at: sdkHits[0]!.at };
|
||||
}
|
||||
|
||||
const sdks: DetectedSdk[] = [];
|
||||
for (const s of SDKS) {
|
||||
const hits = deps.filter(d => matchesSdk(d, s));
|
||||
if (hits.length) sdks.push({ sdk: s, deps: hits });
|
||||
}
|
||||
return { root, stacks: [...stacks], ios, android: isAndroid, deps, sdks, plist, plistSources, entitlements, privacyManifests, androidInfo: android, remoteStart, sources, scanned: files.length };
|
||||
}
|
||||
|
||||
const COMMENT = /^\s*(\/\/|#|\*|\/\*|<!--)/;
|
||||
|
||||
/** Source lines matching `re` (comments skipped), at most `max`. */
|
||||
export function grep(sources: { path: string; text: string }[], re: RegExp, max = 5, filter?: (path: string) => boolean): Hit[] {
|
||||
const out: Hit[] = [];
|
||||
for (const s of sources) {
|
||||
if (filter && !filter(s.path)) continue;
|
||||
if (!re.test(s.text)) continue;
|
||||
const lines = s.text.split('\n');
|
||||
for (let i = 0; i < lines.length && out.length < max; i++) {
|
||||
const l = lines[i]!;
|
||||
if (re.test(l) && !COMMENT.test(l)) out.push({ file: s.path, line: i + 1, text: l.trim().slice(0, 160) });
|
||||
}
|
||||
if (out.length >= max) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** "file:line" of a location. */
|
||||
export const where = (l: Loc): string => `${l.file}:${l.line}`;
|
||||
|
||||
/** Ecosystems in a readable order for the report. */
|
||||
export const ECO_LABEL: Record<Eco, string> = { cocoapods: 'CocoaPods', spm: 'SwiftPM', carthage: 'Carthage', gradle: 'Gradle', npm: 'npm', pub: 'pub', unity: 'Unity', godot: 'Godot' };
|
||||
502
cli/lib/scan/rules.ts
Normal file
502
cli/lib/scan/rules.ts
Normal file
|
|
@ -0,0 +1,502 @@
|
|||
// App Review and Google Play rejection-risk rules for `storebound scan`. Pure: they read the detected project facts,
|
||||
// the config (optional) and the listing files, and return findings with the guideline, the evidence (file:line), the
|
||||
// fix, a severity and the skill that covers it. Only what files or the config prove is reported; where a rule cannot
|
||||
// see enough (a sign-in flow behind a custom API, a restore button under another name) its fix says what to check.
|
||||
//
|
||||
// Sources, checked 2026-10-11:
|
||||
// - Apple App Review Guidelines: https://developer.apple.com/app-store/review/guidelines/
|
||||
// 2.1(a) app completeness (demo account, placeholder text), 2.3.7 metadata (names, keywords, no prices or other
|
||||
// apps' names), 2.3.8 ("For Kids" is reserved for the Kids Category), 2.3.10 other mobile platforms, 2.5.1 public
|
||||
// APIs, 2.5.5 IPv6-only networks, 3.1.1 restore mechanism, 3.1.2(c) subscription information (+ Schedule 2 of the
|
||||
// Developer Program License Agreement: Terms of Use and privacy policy links), 4.2 minimum functionality
|
||||
// (repackaged websites), 4.8 Login Services (an equivalent login option), 5.1.1(ii) purpose strings, 5.1.1(v)
|
||||
// account deletion in the app, 5.1.2(i) App Tracking Transparency, 1.3 Kids Category (no third-party ads/analytics),
|
||||
// 5.1.1(i) privacy policy link inside the app, 5.1.1(iv) only the access a feature needs, 5.1.2 privacy labels that
|
||||
// match the SDKs, 3.1.1 calls to action for purchases outside in-app purchase (3.1.3(e): physical goods are fine),
|
||||
// 3.1.2 subscription management, 2.5.1 private settings URL schemes, 5.6.1 system review prompt only, 3.2.2(x) and
|
||||
// 5.6.3 no rewards for ratings.
|
||||
// - The list of common rejections the rules cover was cross-checked with community collections (paraphrased, each item
|
||||
// verified against Apple's guidelines above): github.com/rshankras/claude-code-apple-skills (app-store /
|
||||
// rejection-handler / common-rejections.md), github.com/rorkai/app-store-connect-cli-skills (asc-submission-health)
|
||||
// and ascskill.wiki. Items that only show at review time (crashes, dead links, misleading screenshots, poor UI, 4.3
|
||||
// spam, 5.2 local law) are not file-detectable: the review-rejections skill lists them as "checked at review".
|
||||
// - Apple, upload checks: ITMS-90683 missing purpose string, ITMS-90809 UIWebView, ITMS-91053 / 91061 privacy
|
||||
// manifest (developer.apple.com/documentation/bundleresources/privacy-manifest-files), App Transport Security
|
||||
// (developer.apple.com/documentation/security/preventing-insecure-network-connections), export compliance
|
||||
// (developer.apple.com/documentation/security/complying-with-encryption-export-regulations).
|
||||
// - Google Play: target API level (developer.android.com/google/play/requirements/target-sdk: from 2026-08-31 new apps
|
||||
// and updates target API 36, Wear OS / Android Automotive 35, Android TV / XR 34; extension to 2026-11-01 on request),
|
||||
// account deletion (support.google.com/googleplay/android-developer/answer/13327111), foreground service types
|
||||
// (answer/13392821), Permissions and APIs that Access Sensitive Information (answer/9888170: exact alarm,
|
||||
// QUERY_ALL_PACKAGES, SMS and Call Log), App access for reviewers (answer/9859455), Families policy (answer/9893335),
|
||||
// Metadata (answer/9898842), Data safety (answer/10787469). The reserved com.example package name is an upload
|
||||
// error of Play Console (no policy page; developer.android.com/build/configure-app-module on choosing the id).
|
||||
import type { ShipConfig } from '../config';
|
||||
import { allSubscriptions } from '../subscriptions';
|
||||
import { LISTED_SDKS, REQUIRED_REASON_APIS } from '../privacy-manifest';
|
||||
import { IOS_PERMISSIONS, vaguePurpose } from './permissions';
|
||||
import { grep, type Hit, lineOf, type ProjectFacts } from './project';
|
||||
import { versionAtLeast } from './sdks';
|
||||
|
||||
export type Severity = 'blocker' | 'high' | 'medium' | 'low';
|
||||
export type ScanStore = 'apple' | 'play';
|
||||
|
||||
export interface ScanFinding {
|
||||
/** Stable rule id (config `scan.ignore` uses it). */
|
||||
rule: string;
|
||||
/** Guideline or policy, e.g. "5.1.1(v)" or "Play: Target API level". */
|
||||
guideline: string;
|
||||
store: ScanStore;
|
||||
severity: Severity;
|
||||
title: string;
|
||||
evidence: Hit[];
|
||||
fix: string;
|
||||
skill: string;
|
||||
/** Policy page. */
|
||||
ref: string;
|
||||
/** Owner accepted it (`scan.ignore` in the config) with this reason. */
|
||||
accepted?: string;
|
||||
}
|
||||
|
||||
export interface ScanInput {
|
||||
facts: ProjectFacts;
|
||||
config: ShipConfig | null;
|
||||
/** The config file as text (relative path), for line numbers. */
|
||||
configFile: { path: string; text: string } | null;
|
||||
/** iOS metadata / Play listing / screenshot captions as text (relative paths). */
|
||||
listings: { apple?: { path: string; text: string }; play?: { path: string; text: string }; captions?: { path: string; text: string } };
|
||||
/** A demo account for App Review is stored locally (.storebound/credentials.json or REVIEW_DEMO_*). */
|
||||
demoAccount: boolean;
|
||||
/** Data types the detected SDKs collect that the config's dataSafety does not declare (from the declarations
|
||||
* proposal): privacy label mismatch. */
|
||||
labelGaps?: { type: string; apple: string; evidence: Hit[] }[];
|
||||
}
|
||||
|
||||
export const APPLE_GUIDELINES = 'https://developer.apple.com/app-store/review/guidelines/';
|
||||
const PLAY = 'https://support.google.com/googleplay/android-developer/answer/';
|
||||
export const PLAY_POLICY = 'https://play.google/developer-content-policy/';
|
||||
export const PLAY_TARGET_SDK = { phone: 36, wear: 35, automotive: 35, tv: 34 } as const;
|
||||
export const PLAY_TARGET_SDK_SINCE = '2026-08-31';
|
||||
|
||||
// ---- code signals ----
|
||||
export const SIGNALS = {
|
||||
appleSignIn: /ASAuthorizationAppleIDProvider|SignInWithAppleButton|AppleAuthenticationButton|AppleAuthentication\.signInAsync|appleAuth\.performRequest|SignInWithApple|OAuthProvider\(\s*['"]apple\.com|AppleAuthProvider|signInWithApple|AppleAuthManager/,
|
||||
thirdPartyLogin: /GIDSignIn|GoogleSignin\.signIn|GoogleSignIn\(|GoogleAuthProvider|signInWithGoogle|FacebookAuthProvider|LoginManager\(\)\.logIn|LoginManager\.logInWithPermissions|signInWithFacebook|FacebookLogin|TwitterAuthProvider|GithubAuthProvider|OAuthProvider\(\s*['"](microsoft\.com|yahoo\.com|twitter\.com|github\.com)/,
|
||||
signIn: /signInWithEmailAndPassword|signInWithPassword|signInWithCredential|createUserWithEmailAndPassword|\bsupabase\.auth\.sign|Amplify\.Auth\.signIn|\bAuth0\b|\bloginWithPassword\b|\.signIn\(\s*\{|\/(api\/)?(auth\/)?(login|signin|sign-in)\b['"`]/,
|
||||
signUp: /createUserWithEmailAndPassword|\bsignUp\s*\(|\bsupabase\.auth\.signUp|Amplify\.Auth\.signUp|\/(api\/)?(auth\/)?(register|signup|sign-up)\b['"`]|["'>](Create (an )?account|Sign up)["'<]/,
|
||||
deleteAccount: /deleteUser\b|\buser\.delete\(|currentUser\??\.delete\(|\bdeleteAccount\b|delete_account|DeleteAccount|delete-account|["'>]Delete (my |your )?account|\brevokeToken\b|auth\.admin\.deleteUser|Hesab(ı|ımı) sil/i,
|
||||
restore: /restoreCompletedTransactions|AppStore\.sync\(|restorePurchases|restoreTransactions|RestoreTransactions|getAvailablePurchases|\brestorePurchase\b|\.restore\(\)|Restore Purchases|syncPurchases|Purchases\.shared\.restore|store\.restore\b|queryPurchasesAsync/i,
|
||||
subscriptionCode: /subscriptionPeriod|Product\.SubscriptionInfo|\.autoRenewable\b|entitlements\.active|SubscriptionStoreView|ProductType\.Subscription|ProductType\.SUBS|BillingClient\.ProductType\.SUBS/,
|
||||
attRequest: /requestTrackingAuthorization|requestTrackingPermissionsAsync|requestTrackingPermission\b|AppTrackingTransparency\.requestTrackingAuthorization|ATTrackingStatusBinding\.RequestAuthorizationTracking|TrackingTransparency\.requestPermission/,
|
||||
idfa: /\bASIdentifierManager\b|advertisingIdentifier\b/,
|
||||
uiWebView: /\bUIWebView\b/,
|
||||
wkRemote: /\.load\(\s*URLRequest\(\s*url:\s*URL\(\s*string:\s*"https?:\/\/(?!localhost|127\.0\.0\.1)/,
|
||||
ipv4: /["'`]https?:\/\/(?!127\.0\.0\.1|0\.0\.0\.0|10\.0\.2\.2)(\d{1,3}\.){3}\d{1,3}(?=[:/"'`])/,
|
||||
inAppLegal: /terms|eula|privacy|nutzungsbedingungen|kullanım koşulları|gizlilik/i,
|
||||
privacyLink: /privacy|gizlilik|datenschutz|confidentialit|privacidad/i,
|
||||
manageSubs: /showManageSubscriptions|manageSubscriptionsSheet|apps\.apple\.com\/account\/subscriptions|managementURL|showManageSubscriptions|manageSubscriptions\b/,
|
||||
privateScheme: /["'`](App-Prefs|prefs):root\b/,
|
||||
ratePrompt: /["'`>](Rate (us|this app)|Enjoying [A-Z][\w ]{0,30}\?|Love (this|the) app\?)/,
|
||||
reviewApi: /SKStoreReviewController|requestReview|StoreReview\.requestReview|InAppReview|in_app_review|react-native-rate|requestReviewFlow|ReviewManager/,
|
||||
incentiveRating: /(rate|review)\b[^"'`\n]{0,60}\b(reward|coins?|gems?|bonus|free (lives|spins|coins))|(reward|coins?|gems?|bonus)\b[^"'`\n]{0,40}\b(for|to) (rating|reviewing|rate|review)\b|5[- ]?stars?\b[^"'`\n]{0,40}\b(reward|get|earn)/i,
|
||||
externalBuy: /\b(buy|subscribe|purchase|upgrade|pay)\b[^.\n]{0,40}\b(on|at|via|from) (our )?(website|web ?site|web|site)\b/i,
|
||||
};
|
||||
|
||||
const ATT_SDKS_SHOW_PROMPT = new Set(['applovin', 'levelplay']);
|
||||
const COMPETITORS = ['instagram', 'tiktok', 'whatsapp', 'facebook', 'snapchat', 'youtube', 'netflix', 'spotify', 'telegram', 'messenger', 'twitter', 'pinterest', 'uber', 'airbnb',
|
||||
'amazon', 'chatgpt', 'openai', 'minecraft', 'roblox', 'fortnite', 'pubg', 'candy crush', 'clash of clans', 'pokemon', 'pokémon', 'among us', 'subway surfers', 'temple run',
|
||||
'angry birds', 'tetris', 'wordle', 'duolingo', 'zoom', 'gmail', 'google maps', 'waze', 'shazam', 'tinder', 'notion', 'evernote', 'photoshop', 'canva', 'capcut', 'iphone', 'ipad', 'apple'];
|
||||
const OTHER_PLATFORMS = /\b(Android|Google Play|Play Store|Galaxy Store|AppGallery|Huawei|Windows Phone|BlackBerry|Amazon Appstore)\b/;
|
||||
const PLACEHOLDER = /lorem ipsum|\bTODO\b|\bTBD\b|\bFIXME\b|\bplaceholder\b|\bXXX\b|your app (name|description) here|coming soon|First paragraph:|Short hook under the name|One or two sentences you can change|İsmin altındaki kısa kanca|Yeni sürüm göndermeden istediğin zaman|\bExample (Game|App|Pro|Studio)\b/i;
|
||||
const FGS_PERMISSION: Record<string, string> = {
|
||||
camera: 'CAMERA', connectedDevice: 'CONNECTED_DEVICE', dataSync: 'DATA_SYNC', health: 'HEALTH', location: 'LOCATION', mediaPlayback: 'MEDIA_PLAYBACK',
|
||||
mediaProjection: 'MEDIA_PROJECTION', microphone: 'MICROPHONE', phoneCall: 'PHONE_CALL', remoteMessaging: 'REMOTE_MESSAGING', specialUse: 'SPECIAL_USE',
|
||||
systemExempted: 'SYSTEM_EXEMPTED', mediaProcessing: 'MEDIA_PROCESSING',
|
||||
};
|
||||
const SMS_CALL_LOG = ['READ_SMS', 'RECEIVE_MMS', 'RECEIVE_SMS', 'RECEIVE_WAP_PUSH', 'SEND_SMS', 'WRITE_SMS', 'READ_CALL_LOG', 'WRITE_CALL_LOG', 'PROCESS_OUTGOING_CALLS'];
|
||||
|
||||
/** Text lines (inside fenced blocks of a listing file, or JSON string values) that match `re`. */
|
||||
function listingHits(file: { path: string; text: string } | undefined, re: RegExp, o: { fenced?: boolean; field?: RegExp } = {}): Hit[] {
|
||||
if (!file) return [];
|
||||
const out: Hit[] = [];
|
||||
let inFence = false, heading = '';
|
||||
file.text.split('\n').forEach((l, i) => {
|
||||
if (/^###\s/.test(l)) heading = l.slice(4).trim();
|
||||
if (/^```/.test(l)) { inFence = !inFence; return; }
|
||||
if (o.fenced !== false && !inFence) return;
|
||||
if (o.field && !o.field.test(heading)) return;
|
||||
if (re.test(l)) out.push({ file: file.path, line: i + 1, text: l.trim().slice(0, 160) });
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
export function scanRules(inp: ScanInput): ScanFinding[] {
|
||||
const { facts: p, config: c } = inp;
|
||||
const out: ScanFinding[] = [];
|
||||
const add = (f: Omit<ScanFinding, 'ref'> & { ref?: string }) => out.push({ ref: f.store === 'apple' ? APPLE_GUIDELINES : PLAY_POLICY, ...f });
|
||||
const cfg = (needle: string | RegExp, text?: string): Hit[] => {
|
||||
const f = inp.configFile;
|
||||
if (!f) return [];
|
||||
const i = typeof needle === 'string' ? f.text.indexOf(needle) : f.text.search(needle);
|
||||
if (i < 0) return [];
|
||||
const line = lineOf(f.text, needle);
|
||||
return [{ file: f.path, line, text: text ?? f.text.split('\n')[line - 1]!.trim().slice(0, 160) }];
|
||||
};
|
||||
const dep = (id: string): Hit[] => p.sdks.filter(s => s.sdk.id === id).flatMap(s => s.deps.slice(0, 2).map(d => ({ file: d.file, line: d.line, text: `${d.name}${d.version ? ` ${d.version}` : ''}` })));
|
||||
const sdkHits = (pred: (s: ProjectFacts['sdks'][number]) => boolean): Hit[] => p.sdks.filter(pred).flatMap(s => s.deps.slice(0, 1).map(d => ({ file: d.file, line: d.line, text: `${s.sdk.name}: ${d.name}${d.version ? ` ${d.version}` : ''}` })));
|
||||
const src = (re: RegExp, max = 3) => grep(p.sources, re, max);
|
||||
const native = (path: string) => /\.(swift|m|mm|h)$/.test(path);
|
||||
const apple = c ? !!c.apple : p.ios;
|
||||
const play = c ? !!c.play : p.android;
|
||||
const iosProject = p.ios && p.plistSources.length > 0;
|
||||
const plistVal = (k: string) => p.plist.get(k);
|
||||
|
||||
// ---- accounts, sign-in, demo account, deletion ----
|
||||
const siwa = [...(p.entitlements.has('com.apple.developer.applesignin') ? [{ ...p.entitlements.get('com.apple.developer.applesignin')!.at, text: 'com.apple.developer.applesignin' }] : []),
|
||||
...dep('apple-signin'), ...src(SIGNALS.appleSignIn, 2)];
|
||||
const thirdParty = [...sdkHits(s => s.sdk.login === 'google' || s.sdk.login === 'facebook'), ...src(SIGNALS.thirdPartyLogin, 2)];
|
||||
const authSdk = sdkHits(s => s.sdk.category === 'auth');
|
||||
const signInCode = src(SIGNALS.signIn, 2);
|
||||
const signUpCode = src(SIGNALS.signUp, 2);
|
||||
const accountsCfg = c?.accounts?.enabled ? cfg(/accounts\s*:/) : [];
|
||||
const signIn = [...accountsCfg, ...authSdk, ...signInCode];
|
||||
const creates = [...accountsCfg, ...signUpCode, ...thirdParty, ...siwa, ...sdkHits(s => s.sdk.login === 'firebase')];
|
||||
const deletion = [...(c?.accounts?.inApp ? cfg('inApp') : []), ...src(SIGNALS.deleteAccount, 2)];
|
||||
|
||||
if (signIn.length) {
|
||||
const ra = c?.reviewAccess;
|
||||
const ev = [...cfg(/signInRequired/), ...signIn].slice(0, 4);
|
||||
if (apple) {
|
||||
if (ra?.signInRequired && !inp.demoAccount)
|
||||
add({ rule: 'demo-account', guideline: '2.1(a)', store: 'apple', severity: 'blocker', title: 'Sign-in is required but there is no demo account for App Review', evidence: ev,
|
||||
fix: 'Create a demo account that sees every feature (not a sign-up the reviewer must do), put it in .storebound/credentials.json as reviewDemoAccount (never in the repo), then `storebound apple review-details`.', skill: 'review-access' });
|
||||
else if (!ra)
|
||||
add({ rule: 'demo-account', guideline: '2.1(a)', store: 'apple', severity: 'high', title: 'The app has a sign-in, but the config does not say whether App Review needs a demo account', evidence: ev,
|
||||
fix: 'Set reviewAccess { signInRequired, instructions } in storebound.config.ts. With signInRequired: true add reviewDemoAccount to .storebound/credentials.json; reviewers reject apps they cannot get into (or offer a fully featured demo mode).', skill: 'review-access' });
|
||||
}
|
||||
if (play && ra?.signInRequired && !inp.demoAccount)
|
||||
add({ rule: 'play-app-access', guideline: 'Play: App access', store: 'play', severity: 'high', title: 'Sign-in is required but there are no reviewer credentials for Play App access', evidence: ev,
|
||||
fix: 'Play Console > App content > App access: add the demo account and instructions (keep the credentials in .storebound/credentials.json only).', skill: 'review-access', ref: `${PLAY}9859455` });
|
||||
}
|
||||
if (creates.length) {
|
||||
if (apple && !deletion.length)
|
||||
add({ rule: 'account-deletion', guideline: '5.1.1(v)', store: 'apple', severity: accountsCfg.length || signUpCode.length ? 'blocker' : 'high',
|
||||
title: 'Accounts can be created but no in-app account deletion was found', evidence: creates.slice(0, 4),
|
||||
fix: 'Add "Delete account" in the app (it deletes the account and its data, not only signs out; with Sign in with Apple also revoke the token), then set accounts.inApp to where it starts, e.g. "Settings > Account > Delete account".', skill: 'account-deletion' });
|
||||
if (play && !c?.accounts?.deletionUrl)
|
||||
add({ rule: 'play-deletion-url', guideline: 'Play: Account deletion', store: 'play', severity: c?.accounts?.enabled || signUpCode.length ? 'blocker' : 'high',
|
||||
title: 'Accounts can be created but there is no web page to request account deletion (Data safety asks for it)', evidence: creates.slice(0, 4),
|
||||
fix: 'Publish a page where people request account and data deletion without the app, set accounts.deletionUrl (and dataSafety.deletionRequest: true); Play also wants the in-app path.', skill: 'account-deletion', ref: `${PLAY}13327111` });
|
||||
}
|
||||
if (apple && thirdParty.length && !siwa.length)
|
||||
add({ rule: 'login-services', guideline: '4.8', store: 'apple', severity: 'high', title: 'Third-party login (Google / Facebook / ...) without Sign in with Apple or another equivalent login option', evidence: thirdParty.slice(0, 4),
|
||||
fix: 'Offer Sign in with Apple (Signing & Capabilities > Sign in with Apple, ASAuthorizationAppleIDProvider) or another login that limits data to name and email, lets people hide their email and does not track. Not needed when the app only uses your own account system, or for the exemptions in 4.8 (education / enterprise accounts, government ID, a client for that one service).', skill: 'review-rejections' });
|
||||
|
||||
// ---- purchases ----
|
||||
const subs = c ? allSubscriptions(c.subscriptions) : [];
|
||||
const restorable = [...(c?.products ?? []).filter(x => x.type !== 'consumable').map(x => ({ ...cfg(`'${x.id}'`)[0] ?? cfg(`"${x.id}"`)[0] ?? { file: inp.configFile?.path ?? 'storebound.config.ts', line: 1, text: '' }, text: `${x.id} (${x.type})` })),
|
||||
...subs.slice(0, 2).map(x => ({ ...(cfg(`'${x.sub.id}'`)[0] ?? cfg(`"${x.sub.id}"`)[0] ?? { file: inp.configFile?.path ?? 'storebound.config.ts', line: 1, text: '' }), text: `${x.sub.id} (subscription)` }))];
|
||||
const subCode = src(SIGNALS.subscriptionCode, 2);
|
||||
const paySdk = sdkHits(s => s.sdk.category === 'payments');
|
||||
if (!c && subCode.length && paySdk.length) restorable.push(...subCode);
|
||||
if (apple && restorable.length && !src(SIGNALS.restore, 1).length)
|
||||
add({ rule: 'restore-purchases', guideline: '3.1.1', store: 'apple', severity: 'high', title: 'Restorable purchases (non-consumables or subscriptions) but no Restore Purchases path was found', evidence: [...restorable.slice(0, 3), ...paySdk.slice(0, 1)],
|
||||
fix: 'Add a visible "Restore Purchases" button (StoreKit 2: AppStore.sync(); StoreKit 1: restoreCompletedTransactions; RevenueCat: restorePurchases) on the store / paywall screen or in Settings.', skill: 'store-iap-setup' });
|
||||
const hasSubs = subs.length > 0 || (!c && subCode.length > 0);
|
||||
if (apple && hasSubs) {
|
||||
const ev = subs.length ? cfg(/subscriptions\s*:/) : subCode;
|
||||
if (c && !c.app.termsUrl)
|
||||
add({ rule: 'subscription-info', guideline: '3.1.2(c)', store: 'apple', severity: 'blocker', title: 'Subscriptions without a Terms of Use (EULA) link', evidence: ev,
|
||||
fix: 'Set app.termsUrl (Apple\'s standard EULA URL is fine) and link it in the app\'s purchase screen and in the App Store description (or a custom EULA in App Information).', skill: 'store-subscriptions' });
|
||||
const desc = listingHits(inp.listings.apple, /./, { field: /^description$/ });
|
||||
if (inp.listings.apple && desc.length) {
|
||||
const all = desc.map(d => d.text).join('\n');
|
||||
const termsUrl = c?.app.termsUrl;
|
||||
if (!(termsUrl && all.includes(termsUrl)) && !/terms of use|terms of service|\beula\b|license agreement/i.test(all))
|
||||
add({ rule: 'subscription-info', guideline: '3.1.2(c)', store: 'apple', severity: 'high', title: 'App Store description has no Terms of Use (EULA) link', evidence: desc.slice(0, 1),
|
||||
fix: 'Add a line "Terms of Use: <app.termsUrl>" (and the privacy policy) to the description of every locale, or set a custom EULA in App Store Connect > App Information.', skill: 'store-subscriptions' });
|
||||
if (!/renew|cancel/i.test(all))
|
||||
add({ rule: 'subscription-info', guideline: '3.1.2(c)', store: 'apple', severity: 'medium', title: 'App Store description does not say the subscription renews automatically or how to cancel', evidence: desc.slice(0, 1),
|
||||
fix: 'Describe what the subscription includes, the length and price per period, that it renews automatically unless cancelled at least 24 hours before the end of the period, and where to manage it.', skill: 'store-subscriptions' });
|
||||
}
|
||||
const legal = src(SIGNALS.inAppLegal, 1);
|
||||
if (p.sources.length && !legal.length && !(c?.app.termsUrl && src(new RegExp(c.app.termsUrl.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')), 1).length))
|
||||
add({ rule: 'subscription-info', guideline: '3.1.2(c)', store: 'apple', severity: 'medium', title: 'No Terms of Use / privacy policy link found in the app\'s sources', evidence: ev.slice(0, 2),
|
||||
fix: 'Show functional links to the Terms of Use and the privacy policy on the purchase screen, next to the price and period.', skill: 'store-subscriptions' });
|
||||
}
|
||||
|
||||
// ---- App Tracking Transparency ----
|
||||
if (apple && p.ios) {
|
||||
const trackers = p.sdks.filter(s => s.sdk.tracking);
|
||||
const trackEv = sdkHits(s => s.sdk.tracking);
|
||||
const idfa = grep(p.sources, SIGNALS.idfa, 2, native);
|
||||
const request = [...src(SIGNALS.attRequest, 2), ...p.deps.filter(d => ['expo-tracking-transparency', 'react-native-tracking-transparency', 'app_tracking_transparency', '@capacitor-community/app-tracking-transparency', 'com.unity.ads.ios-support'].includes(d.name)).map(d => ({ file: d.file, line: d.line, text: d.name }))];
|
||||
const str = plistVal('NSUserTrackingUsageDescription');
|
||||
const manifestTracking = p.privacyManifests.find(m => m.tracking);
|
||||
const cfgTracking = c?.appPrivacy?.tracking === true;
|
||||
const sdkPrompts = trackers.some(s => ATT_SDKS_SHOW_PROMPT.has(s.sdk.id));
|
||||
if (request.length && !str && iosProject)
|
||||
add({ rule: 'att', guideline: '5.1.2(i)', store: 'apple', severity: 'blocker', title: 'The app asks for tracking permission but Info.plist has no NSUserTrackingUsageDescription (crash on the prompt)', evidence: request.slice(0, 2),
|
||||
fix: 'Add NSUserTrackingUsageDescription with a specific reason, e.g. "Your data is used to show ads that fit your interests."', skill: 'review-rejections' });
|
||||
else if (str && !request.length && !sdkPrompts && p.sources.length)
|
||||
add({ rule: 'att', guideline: '5.1.2(i)', store: 'apple', severity: 'high', title: 'NSUserTrackingUsageDescription is set but no App Tracking Transparency request was found (reviewers cannot find the prompt)', evidence: [{ ...str.at, text: 'NSUserTrackingUsageDescription' }],
|
||||
fix: 'Call ATTrackingManager.requestTrackingAuthorization (after launch, when the app is active) before any SDK reads the IDFA, or remove the string and declare "no tracking" if no SDK tracks.', skill: 'review-rejections' });
|
||||
if ((trackers.length || idfa.length || cfgTracking || manifestTracking) && !request.length && !str && !sdkPrompts)
|
||||
add({ rule: 'att', guideline: '5.1.2(i)', store: 'apple', severity: idfa.length || cfgTracking || manifestTracking ? 'high' : 'medium',
|
||||
title: `Tracking-capable code without App Tracking Transparency (${[...trackers.map(s => s.sdk.name), ...(idfa.length ? ['IDFA'] : [])].join(', ') || 'App Privacy says tracking'})`,
|
||||
evidence: [...trackEv, ...idfa, ...(cfgTracking ? cfg(/tracking\s*:\s*true/) : []), ...(manifestTracking ? [{ file: manifestTracking.path, line: 1, text: 'NSPrivacyTracking true' }] : [])].slice(0, 4),
|
||||
fix: 'If any SDK tracks (personalized ads, attribution, IDFA): add NSUserTrackingUsageDescription and request ATT before the SDKs start, and answer App Privacy "used for tracking". If nothing tracks: configure the ad SDKs for non-personalized ads and answer "no tracking".', skill: 'ads-mediation-checks' });
|
||||
}
|
||||
|
||||
// ---- purpose strings ----
|
||||
if (apple && iosProject) {
|
||||
for (const perm of IOS_PERMISSIONS) {
|
||||
if (perm.keys.includes('NSUserTrackingUsageDescription')) continue;
|
||||
const used = [...grep(p.sources, perm.code, 2, x => native(x) || /\.(cs|gd)$/.test(x)),
|
||||
...p.deps.filter(d => (d.eco === 'npm' || d.eco === 'pub' || d.eco === 'unity') && perm.packages.includes(d.name)).map(d => ({ file: d.file, line: d.line, text: d.name }))];
|
||||
if (!used.length) continue;
|
||||
const entry = perm.keys.map(k => plistVal(k)).find(Boolean);
|
||||
if (!entry)
|
||||
add({ rule: 'purpose-strings', guideline: '5.1.1(ii)', store: 'apple', severity: 'blocker', title: `${perm.what} is used but Info.plist has no ${perm.keys[0]} (ITMS-90683, crash on first use)`, evidence: used.slice(0, 2),
|
||||
fix: `Add ${perm.keys[0]} to Info.plist (or INFOPLIST_KEY_${perm.keys[0]} in the target's build settings) with a sentence that says why the app needs the ${perm.what}, e.g. "Scan receipts to add them to your budget."`, skill: 'review-rejections' });
|
||||
else {
|
||||
const v = vaguePurpose(String(entry.value ?? ''));
|
||||
if (v) add({ rule: 'purpose-strings', guideline: '5.1.1(ii)', store: 'apple', severity: v === 'empty' ? 'blocker' : 'medium',
|
||||
title: `${entry.key} is ${v === 'empty' ? 'empty or a placeholder' : 'too vague'}: "${String(entry.value ?? '').slice(0, 60)}"`, evidence: [{ ...entry.at, text: `${entry.key}: ${String(entry.value ?? '').slice(0, 80)}` }],
|
||||
fix: `Say what the ${perm.what} is used for and how it helps the user, in one specific sentence (and localize it in InfoPlist.strings).`, skill: 'review-rejections' });
|
||||
}
|
||||
}
|
||||
// declared strings that are empty, even if the code use was not found
|
||||
for (const [k, e] of p.plist) if (/^NS[A-Za-z]+UsageDescription$/.test(k) && vaguePurpose(String(e.value ?? '')) === 'empty' && !out.some(f => f.evidence.some(x => x.file === e.at.file && x.line === e.at.line)))
|
||||
add({ rule: 'purpose-strings', guideline: '5.1.1(ii)', store: 'apple', severity: 'high', title: `${k} is empty or a placeholder`, evidence: [{ ...e.at, text: `${k}: ${String(e.value ?? '')}` }],
|
||||
fix: 'Write a specific reason, or remove the key when the app does not use that permission.', skill: 'review-rejections' });
|
||||
}
|
||||
|
||||
// ---- privacy manifest ----
|
||||
if (apple && iosProject) {
|
||||
const nativeSources = p.sources.filter(s => native(s.path));
|
||||
const declared = new Map<string, string[]>();
|
||||
for (const m of p.privacyManifests) for (const [k, v] of Object.entries(m.apis)) declared.set(k, v);
|
||||
const listed = p.deps.filter(d => (d.eco === 'cocoapods' || d.eco === 'spm') && LISTED_SDKS.some(n => d.name === n || d.name.startsWith(`${n}/`) || d.name.toLowerCase().endsWith(`/${n.toLowerCase()}`) || d.name.toLowerCase().endsWith(`/${n.toLowerCase()}.git`)));
|
||||
const apiHits: Hit[] = [];
|
||||
for (const [cat, def] of Object.entries(REQUIRED_REASON_APIS)) {
|
||||
const h = grep(nativeSources, def.symbols, 1);
|
||||
if (!h.length) continue;
|
||||
if (!declared.has(cat)) apiHits.push({ ...h[0]!, text: `${cat}: ${h[0]!.text}` });
|
||||
}
|
||||
if (!p.privacyManifests.length && (apiHits.length || listed.length || p.sdks.length))
|
||||
add({ rule: 'privacy-manifest', guideline: 'Privacy manifest (ITMS-91053)', store: 'apple', severity: apiHits.length ? 'blocker' : 'high', title: 'No PrivacyInfo.xcprivacy in the app target', evidence: [...apiHits, ...listed.map(d => ({ file: d.file, line: d.line, text: d.name }))].slice(0, 4),
|
||||
fix: 'Xcode > File > New > File > App Privacy, add it to the app target, declare each required-reason API category with its reason (`storebound privacy-manifest --ios <dir>` lists them) and the collected data types.', skill: 'privacy-manifest',
|
||||
ref: 'https://developer.apple.com/documentation/bundleresources/privacy-manifest-files' });
|
||||
else if (apiHits.length)
|
||||
add({ rule: 'privacy-manifest', guideline: 'Privacy manifest (ITMS-91053)', store: 'apple', severity: 'blocker', title: `Required-reason APIs used but not declared in PrivacyInfo.xcprivacy: ${apiHits.map(h => h.text.split(':')[0]).join(', ')}`, evidence: apiHits.slice(0, 4),
|
||||
fix: 'Add each category to NSPrivacyAccessedAPITypes with an approved reason code (for app data in UserDefaults: CA92.1).', skill: 'privacy-manifest', ref: 'https://developer.apple.com/documentation/bundleresources/privacy-manifest-files/describing-use-of-required-reason-api' });
|
||||
for (const s of p.sdks) {
|
||||
if (!s.sdk.manifestSince) continue;
|
||||
for (const d of s.deps.filter(x => (x.eco === 'cocoapods' || x.eco === 'spm') && x.version)) {
|
||||
if (versionAtLeast(d.version!, s.sdk.manifestSince) === false)
|
||||
add({ rule: 'privacy-manifest', guideline: 'Privacy manifest (ITMS-91061)', store: 'apple', severity: 'high', title: `${s.sdk.name} ${d.version} is older than ${s.sdk.manifestSince}, the first version with Apple's privacy manifest`, evidence: [{ file: d.file, line: d.line, text: `${d.name} ${d.version}` }],
|
||||
fix: `Update ${d.name} to ${s.sdk.manifestSince} or newer (the SDK is on Apple's list of commonly used SDKs that need a manifest and a signature).`, skill: 'privacy-manifest', ref: 'https://developer.apple.com/support/third-party-SDK-requirements/' });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- metadata (iOS listing + screenshot captions) ----
|
||||
if (apple) {
|
||||
const other = [...listingHits(inp.listings.apple, OTHER_PLATFORMS), ...listingHits(inp.listings.captions, OTHER_PLATFORMS, { fenced: false })];
|
||||
if (other.length)
|
||||
add({ rule: 'other-platforms', guideline: '2.3.10', store: 'apple', severity: 'high', title: 'Other mobile platforms or stores named in the App Store metadata or screenshot captions', evidence: other.slice(0, 4),
|
||||
fix: 'Remove "Android", "Google Play" and other platforms or stores from the App Store text and screenshots (Play listing text is separate: store/listing.md).', skill: 'aso-basics' });
|
||||
const words = new RegExp(`(^|[\\s,|/–-])(${COMPETITORS.map(w => w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|')})(?=$|[\\s,|/–-])`, 'i');
|
||||
const kw = [...listingHits(inp.listings.apple, words, { field: /^(keywords|name|subtitle)$/ })];
|
||||
if (kw.length)
|
||||
add({ rule: 'metadata-keywords', guideline: '2.3.7', store: 'apple', severity: 'high', title: 'Other apps\' names or trademarks in the name, subtitle or keywords', evidence: kw.slice(0, 4),
|
||||
fix: 'Use only terms that describe your app; popular app names, trademarks and Apple product names in keywords get the metadata rejected.', skill: 'aso-basics' });
|
||||
const price = listingHits(inp.listings.apple, /\b(free|best|#1|no\.? ?1|top|cheap|sale|\d+% off|\$\d)\b/i, { field: /^(name|subtitle|keywords)$/ });
|
||||
if (price.length)
|
||||
add({ rule: 'metadata-keywords', guideline: '2.3.7', store: 'apple', severity: 'medium', title: 'Prices or claims ("free", "best", "#1") in the name, subtitle or keywords', evidence: price.slice(0, 3),
|
||||
fix: 'Keep prices and superlatives out of the name, subtitle and keywords (keywords already match "free" searches only by category).', skill: 'aso-basics' });
|
||||
const stuffed = listingHits(inp.listings.apple, /^([^,|]{1,24}[,|]){5,}/, { field: /^(name|subtitle)$/ });
|
||||
if (stuffed.length)
|
||||
add({ rule: 'metadata-keywords', guideline: '2.3.7', store: 'apple', severity: 'medium', title: 'Keyword list in the name or subtitle', evidence: stuffed.slice(0, 2), fix: 'Name and subtitle are a short phrase; keywords belong in the keywords field.', skill: 'aso-basics' });
|
||||
const kids = [...listingHits(inp.listings.apple, /\bfor (kids|children|toddlers)\b/i), ...listingHits(inp.listings.captions, /\bfor (kids|children|toddlers)\b/i, { fenced: false })];
|
||||
const kidsBand = c?.apple?.info?.ageRating?.kidsAgeBand;
|
||||
if (kids.length && !kidsBand)
|
||||
add({ rule: 'kids-terms', guideline: '2.3.8', store: 'apple', severity: 'medium', title: '"For Kids" / "For Children" in the metadata, but the app is not in the Kids Category', evidence: kids.slice(0, 2),
|
||||
fix: 'Those terms are reserved for the Kids Category: remove them, or set apple.info.ageRating.kidsAgeBand and follow 1.3.', skill: 'store-declarations' });
|
||||
}
|
||||
const placeholder = [...(apple ? listingHits(inp.listings.apple, PLACEHOLDER) : []), ...(play ? listingHits(inp.listings.play, PLACEHOLDER) : [])];
|
||||
for (const store of ['apple', 'play'] as const) {
|
||||
const ev = placeholder.filter(h => h.file === (store === 'apple' ? inp.listings.apple?.path : inp.listings.play?.path));
|
||||
if (ev.length)
|
||||
add({ rule: 'placeholder-text', guideline: store === 'apple' ? '2.1(a)' : 'Play: Metadata', store, severity: store === 'apple' ? 'high' : 'medium', title: 'Placeholder or template text in the store listing', evidence: ev.slice(0, 4),
|
||||
fix: 'Replace the template lines and any lorem ipsum / TODO with the real copy before you push the listing.', skill: 'aso-basics', ref: store === 'apple' ? APPLE_GUIDELINES : `${PLAY}9898842` });
|
||||
}
|
||||
|
||||
// ---- code and build settings ----
|
||||
if (apple && p.remoteStart)
|
||||
add({ rule: 'min-functionality', guideline: '4.2', store: 'apple', severity: 'high', title: `The app loads a remote website as its start page (${p.remoteStart.url})`, evidence: [{ ...p.remoteStart.at, text: p.remoteStart.url }],
|
||||
fix: 'Ship the web app inside the binary (remove server.url / the remote <content src>) and add native value (offline use, push, native navigation, device features); a repackaged website is rejected under 4.2.', skill: 'review-rejections' });
|
||||
else if (apple && iosProject) {
|
||||
const swift = p.sources.filter(s => native(s.path));
|
||||
const remote = grep(swift, SIGNALS.wkRemote, 1);
|
||||
if (remote.length && swift.length <= 6)
|
||||
add({ rule: 'min-functionality', guideline: '4.2', store: 'apple', severity: 'medium', title: 'A few native files that load a remote website in a WKWebView', evidence: remote,
|
||||
fix: 'An app that only shows a website is rejected under 4.2: add native features or bundle the content.', skill: 'review-rejections' });
|
||||
}
|
||||
if (apple) {
|
||||
const uiw = grep(p.sources, SIGNALS.uiWebView, 3, native);
|
||||
if (uiw.length)
|
||||
add({ rule: 'deprecated-api', guideline: '2.5.1 (ITMS-90809)', store: 'apple', severity: 'blocker', title: 'UIWebView is used (deprecated; App Store Connect rejects builds that reference it)', evidence: uiw,
|
||||
fix: 'Replace UIWebView with WKWebView and update any SDK that still links it.', skill: 'review-rejections' });
|
||||
}
|
||||
if (apple && iosProject) {
|
||||
const ats = plistVal('NSAppTransportSecurity');
|
||||
const v = ats?.value as Record<string, unknown> | undefined;
|
||||
if (v && v.NSAllowsArbitraryLoads === true)
|
||||
add({ rule: 'ats', guideline: 'App Transport Security', store: 'apple', severity: 'medium', title: 'NSAllowsArbitraryLoads turns App Transport Security off for every connection', evidence: [{ ...ats!.at, text: 'NSAppTransportSecurity > NSAllowsArbitraryLoads = true' }],
|
||||
fix: 'Use HTTPS, or limit the exception to the domains that need it (NSExceptionDomains); App Review asks for a justification of a global exception.', skill: 'review-rejections',
|
||||
ref: 'https://developer.apple.com/documentation/security/preventing-insecure-network-connections' });
|
||||
const ipv4 = src(SIGNALS.ipv4, 2);
|
||||
if (ipv4.length)
|
||||
add({ rule: 'ipv6', guideline: '2.5.5', store: 'apple', severity: 'medium', title: 'Hard-coded IPv4 address in a server URL (fails on IPv6-only networks, where App Review tests)', evidence: ipv4,
|
||||
fix: 'Use a host name that resolves over IPv6 (DNS64/NAT64 then works) instead of an IPv4 literal.', skill: 'review-rejections' });
|
||||
const enc = plistVal('ITSAppUsesNonExemptEncryption');
|
||||
const cfgEnc = c?.apple?.usesNonExemptEncryption;
|
||||
if (!enc && cfgEnc === undefined)
|
||||
add({ rule: 'export-compliance', guideline: 'Export compliance', store: 'apple', severity: 'medium', title: 'Export compliance is not answered (no ITSAppUsesNonExemptEncryption, no apple.usesNonExemptEncryption)', evidence: p.plistSources.slice(0, 1).map(f => ({ file: f, line: 1, text: 'Info.plist' })),
|
||||
fix: 'Ask the owner and decide it with the export-compliance skill (false only when the app uses no encryption beyond the OS); then set ITSAppUsesNonExemptEncryption in Info.plist and apple.usesNonExemptEncryption. Builds wait in "Missing Compliance" until it is answered.', skill: 'export-compliance',
|
||||
ref: 'https://developer.apple.com/documentation/security/complying-with-encryption-export-regulations' });
|
||||
else if (enc && cfgEnc !== undefined && enc.value !== cfgEnc)
|
||||
add({ rule: 'export-compliance', guideline: 'Export compliance', store: 'apple', severity: 'high', title: `Info.plist says ITSAppUsesNonExemptEncryption ${String(enc.value)} but the config says ${String(cfgEnc)}`, evidence: [{ ...enc.at, text: `ITSAppUsesNonExemptEncryption ${String(enc.value)}` }, ...cfg('usesNonExemptEncryption')],
|
||||
fix: 'Make both the same answer (export-compliance skill).', skill: 'export-compliance' });
|
||||
}
|
||||
|
||||
// ---- kids: ads / third-party analytics ----
|
||||
const kidsBand = c?.apple?.info?.ageRating?.kidsAgeBand;
|
||||
if (kidsBand) {
|
||||
const third = sdkHits(s => s.sdk.category === 'ads' || s.sdk.category === 'attribution' || s.sdk.category === 'analytics');
|
||||
if (third.length) {
|
||||
if (apple) add({ rule: 'kids-ads', guideline: '1.3', store: 'apple', severity: 'high', title: `Kids Category app (${String(kidsBand)}) with third-party ads or analytics SDKs`, evidence: [...cfg('kidsAgeBand'), ...third].slice(0, 4),
|
||||
fix: 'Kids Category apps should not include third-party advertising or analytics (narrow exceptions: contextual ads with human-reviewed creatives, analytics without IDFA or identifiable data). Remove them or configure child-directed mode and document it in the review notes.', skill: 'store-declarations' });
|
||||
if (play) add({ rule: 'kids-ads', guideline: 'Play: Families policy', store: 'play', severity: 'high', title: 'App for children with ad / analytics SDKs: only Families self-certified ad SDKs are allowed', evidence: third.slice(0, 3),
|
||||
fix: 'Use only ad SDKs from the Families Self-Certified Ads SDK list, turn on child-directed treatment, and answer Target audience and content accordingly.', skill: 'store-declarations', ref: `${PLAY}9893335` });
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Google Play manifest and build ----
|
||||
if (play && p.android) {
|
||||
const a = p.androidInfo;
|
||||
const need = PLAY_TARGET_SDK[a.formFactor];
|
||||
if (a.targetSdk && a.targetSdk.value < need)
|
||||
add({ rule: 'play-target-sdk', guideline: 'Play: Target API level', store: 'play', severity: 'blocker', title: `targetSdk ${a.targetSdk.value} is below ${need}, which new apps and updates need since ${PLAY_TARGET_SDK_SINCE}`, evidence: [{ ...a.targetSdk.at, text: `targetSdk ${a.targetSdk.value}` }],
|
||||
fix: `Raise targetSdk (and compileSdk) to ${need}, test the behavior changes of each Android version in between, then upload a new AAB (an extension to 2026-11-01 can be requested in Play Console).`, skill: 'play-first-release',
|
||||
ref: 'https://developer.android.com/google/play/requirements/target-sdk' });
|
||||
else if (!a.targetSdk && a.targetSdkFrom)
|
||||
add({ rule: 'play-target-sdk', guideline: 'Play: Target API level', store: 'play', severity: 'low', title: `targetSdk comes from ${a.targetSdkFrom}: check that the built AAB targets ${need} or higher`, evidence: a.manifests.slice(0, 1).map(f => ({ file: f, line: 1, text: 'AndroidManifest.xml' })),
|
||||
fix: `Check with \`aapt2 dump badging app.aab\` or Play Console > App bundle explorer; Play refuses uploads below ${need}.`, skill: 'play-first-release', ref: 'https://developer.android.com/google/play/requirements/target-sdk' });
|
||||
const perms = new Map(a.permissions.map(x => [x.name.replace(/^android\.permission\./, ''), x] as const));
|
||||
const fgs = perms.get('FOREGROUND_SERVICE');
|
||||
if (fgs && (!a.targetSdk || a.targetSdk.value >= 34)) {
|
||||
const typed = a.services.filter(s => s.fgsType);
|
||||
const untyped = a.services.filter(s => !s.fgsType);
|
||||
if (untyped.length && !typed.length)
|
||||
add({ rule: 'play-fgs', guideline: 'Play: Foreground service types', store: 'play', severity: 'high', title: 'FOREGROUND_SERVICE is requested but no <service> declares android:foregroundServiceType (required when targeting Android 14+)', evidence: [{ ...fgs.at, text: 'FOREGROUND_SERVICE' }, ...untyped.slice(0, 2).map(s => ({ ...s.at, text: `service ${s.name}` }))],
|
||||
fix: 'Give each foreground service a type and its FOREGROUND_SERVICE_<TYPE> permission, then fill App content > Foreground service permissions (description, user impact, video).', skill: 'play-first-release', ref: `${PLAY}13392821` });
|
||||
for (const s of typed) {
|
||||
const types = s.fgsType!.split('|').map(x => x.trim()).filter(Boolean);
|
||||
const missing = types.filter(t => FGS_PERMISSION[t] && !perms.has(`FOREGROUND_SERVICE_${FGS_PERMISSION[t]}`));
|
||||
if (missing.length)
|
||||
add({ rule: 'play-fgs', guideline: 'Play: Foreground service types', store: 'play', severity: 'high', title: `Service ${s.name} has type ${missing.join('|')} without FOREGROUND_SERVICE_${missing.map(t => FGS_PERMISSION[t]).join(' / ')} (SecurityException on Android 14+)`, evidence: [{ ...s.at, text: `foregroundServiceType="${s.fgsType}"` }],
|
||||
fix: `Add <uses-permission android:name="android.permission.FOREGROUND_SERVICE_${FGS_PERMISSION[missing[0]!]}" />.`, skill: 'play-first-release', ref: `${PLAY}13392821` });
|
||||
}
|
||||
if (typed.length)
|
||||
add({ rule: 'play-fgs', guideline: 'Play: Foreground service types', store: 'play', severity: 'medium', title: `Foreground service types need a Play Console declaration: ${[...new Set(typed.flatMap(s => s.fgsType!.split('|')))].join(', ')}`, evidence: typed.slice(0, 3).map(s => ({ ...s.at, text: `${s.name}: ${s.fgsType}` })),
|
||||
fix: 'App content > Foreground service permissions: describe each use, the user impact if it is deferred, and add a short video; shortService needs none.', skill: 'play-first-release', ref: `${PLAY}13392821` });
|
||||
}
|
||||
const exact = perms.get('USE_EXACT_ALARM');
|
||||
if (exact)
|
||||
add({ rule: 'play-exact-alarm', guideline: 'Play: Exact alarm permission', store: 'play', severity: 'high', title: 'USE_EXACT_ALARM is only allowed for alarm clock, timer and calendar apps', evidence: [{ ...exact.at, text: 'USE_EXACT_ALARM' }],
|
||||
fix: 'Remove it (an SDK may add it: check the merged manifest and use tools:node="remove"), or use SCHEDULE_EXACT_ALARM (the user grants it) or inexact alarms / WorkManager; alarm and calendar apps fill the Play Console declaration.', skill: 'play-first-release', ref: `${PLAY}9888170` });
|
||||
const sched = perms.get('SCHEDULE_EXACT_ALARM');
|
||||
if (sched && !exact)
|
||||
add({ rule: 'play-exact-alarm', guideline: 'Play: Exact alarm permission', store: 'play', severity: 'low', title: 'SCHEDULE_EXACT_ALARM: denied by default from Android 14; the app must check canScheduleExactAlarms()', evidence: [{ ...sched.at, text: 'SCHEDULE_EXACT_ALARM' }],
|
||||
fix: 'Keep it only for user-facing, time-critical features and handle the denied case; otherwise use inexact alarms.', skill: 'play-first-release', ref: `${PLAY}9888170` });
|
||||
const qap = perms.get('QUERY_ALL_PACKAGES');
|
||||
if (qap)
|
||||
add({ rule: 'play-query-all-packages', guideline: 'Play: Package visibility', store: 'play', severity: 'high', title: 'QUERY_ALL_PACKAGES needs a core purpose that requires seeing every installed app, and a declaration', evidence: [{ ...qap.at, text: 'QUERY_ALL_PACKAGES' }],
|
||||
fix: 'Replace it with <queries> entries for the packages or intents you need; keep it only for launchers, device search, antivirus, file managers, browsers and similar, and fill the Permissions Declaration Form.', skill: 'play-first-release', ref: `${PLAY}10158779` });
|
||||
const sms = SMS_CALL_LOG.map(x => perms.get(x)).filter((x): x is NonNullable<typeof x> => !!x);
|
||||
if (sms.length)
|
||||
add({ rule: 'play-sms-call-log', guideline: 'Play: SMS and Call Log permissions', store: 'play', severity: 'high', title: `Restricted SMS / Call Log permissions: ${sms.map(x => x.name.replace(/^android\.permission\./, '')).join(', ')}`, evidence: sms.slice(0, 3).map(x => ({ ...x.at, text: x.name })),
|
||||
fix: 'Only the default SMS / Phone / Assistant handler may use them (or a listed exception with a declaration). Remove them; for one-time codes use the SMS Retriever or SMS User Consent API.', skill: 'play-first-release', ref: `${PLAY}10208820` });
|
||||
}
|
||||
|
||||
// ---- privacy policy in the app, privacy labels vs SDKs, unused permissions ----
|
||||
const collects = p.sdks.length > 0 || creates.length > 0;
|
||||
if (apple && collects && p.sources.length && !src(SIGNALS.privacyLink, 1).length && !(c?.app.privacyPolicyUrl && src(new RegExp(c.app.privacyPolicyUrl.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')), 1).length))
|
||||
add({ rule: 'privacy-policy-link', guideline: '5.1.1(i)', store: 'apple', severity: 'medium', title: 'The app collects data (SDKs or accounts) but no privacy policy link was found in its sources', evidence: [...sdkHits(() => true), ...creates].slice(0, 3),
|
||||
fix: 'Link the privacy policy (app.privacyPolicyUrl) somewhere easy to find in the app, e.g. Settings > Privacy policy, and on sign-up / purchase screens.', skill: 'privacy-policy' });
|
||||
for (const g of inp.labelGaps ?? []) {
|
||||
if (apple) add({ rule: 'privacy-labels', guideline: '5.1.2', store: 'apple', severity: 'medium', title: `App Privacy likely misses "${g.apple}": an SDK collects it, the config does not declare it`, evidence: g.evidence.slice(0, 2),
|
||||
fix: 'Run `storebound scan` and read the declarations proposal; confirm with the SDK\'s disclosure, then add the type to dataSafety (`storebound scan --write`) and to App Privacy in App Store Connect.', skill: 'store-declarations' });
|
||||
if (play) add({ rule: 'privacy-labels', guideline: 'Play: User Data (Data safety)', store: 'play', severity: 'medium', title: `Data safety likely misses ${g.type}: an SDK collects it, dataSafety does not declare it`, evidence: g.evidence.slice(0, 2),
|
||||
fix: 'Confirm with the SDK\'s Data safety guidance, add it with `storebound scan --write` (or by hand), then `storebound play data-safety`.', skill: 'store-declarations', ref: `${PLAY}10787469` });
|
||||
}
|
||||
if (apple && iosProject && p.stacks.length === 1 && p.stacks[0] === 'ios-native') {
|
||||
for (const perm of IOS_PERMISSIONS) {
|
||||
const entry = perm.keys.map(k => plistVal(k)).find(Boolean);
|
||||
if (!entry || perm.keys.includes('NSUserTrackingUsageDescription') || perm.keys.includes('NSPhotoLibraryUsageDescription')) continue;
|
||||
if (grep(p.sources, perm.code, 1, native).length || p.sdks.length) continue;
|
||||
add({ rule: 'unused-permission', guideline: '5.1.1(iv)', store: 'apple', severity: 'low', title: `${entry.key} is declared but no ${perm.what} use was found in the app's sources`, evidence: [{ ...entry.at, text: entry.key }],
|
||||
fix: 'Remove purpose strings the app does not need; ask only for the access a feature needs, when it needs it.', skill: 'review-rejections' });
|
||||
}
|
||||
}
|
||||
|
||||
// ---- payments outside in-app purchase, subscription management ----
|
||||
const extPay = sdkHits(s => s.sdk.category === 'external-payments');
|
||||
if (apple && extPay.length && (restorable.length || paySdk.length || (c?.products?.length ?? 0) > 0))
|
||||
add({ rule: 'external-purchase', guideline: '3.1.1', store: 'apple', severity: 'medium', title: 'A card / PayPal payment SDK next to in-app purchases: digital goods and features must be sold with in-app purchase', evidence: [...extPay, ...restorable].slice(0, 3),
|
||||
fix: 'Use the external payment SDK only for physical goods or services used outside the app (3.1.3(e)); sell unlocks, coins and subscriptions through StoreKit.', skill: 'review-rejections' });
|
||||
const buyOutside = apple ? [...listingHits(inp.listings.apple, SIGNALS.externalBuy), ...grep(p.sources, SIGNALS.externalBuy, 2, x => native(x) || /\.(dart|tsx?|jsx?|cs|vue|html)$/.test(x))] : [];
|
||||
if (buyOutside.length)
|
||||
add({ rule: 'external-purchase', guideline: '3.1.1', store: 'apple', severity: 'medium', title: 'A call to action to buy outside the app (website) in the iOS app or its metadata', evidence: buyOutside.slice(0, 3),
|
||||
fix: 'Outside the storefronts and entitlements that allow external purchase links, remove buttons, links and text that send people to buy digital content elsewhere.', skill: 'review-rejections' });
|
||||
if (apple && hasSubs && p.sources.length && !src(SIGNALS.manageSubs, 1).length)
|
||||
add({ rule: 'subscription-info', guideline: '3.1.2', store: 'apple', severity: 'low', title: 'No "Manage subscription" entry found in the app', evidence: (subs.length ? cfg(/subscriptions\s*:/) : subCode).slice(0, 1),
|
||||
fix: 'Offer a way to manage or cancel in the app (StoreKit showManageSubscriptions / SwiftUI manageSubscriptionsSheet, or a link to the App Store subscriptions page).', skill: 'store-subscriptions' });
|
||||
|
||||
// ---- private URL schemes, review prompts ----
|
||||
if (apple) {
|
||||
const priv = grep(p.sources, SIGNALS.privateScheme, 2);
|
||||
if (priv.length)
|
||||
add({ rule: 'private-api', guideline: '2.5.1', store: 'apple', severity: 'high', title: 'Private settings URL scheme (App-Prefs: / prefs:root)', evidence: priv,
|
||||
fix: 'Open your own settings page with UIApplication.openSettingsURLString instead.', skill: 'review-rejections' });
|
||||
const incent = grep(p.sources, SIGNALS.incentiveRating, 2);
|
||||
if (incent.length)
|
||||
add({ rule: 'review-prompt', guideline: '3.2.2(x) / 5.6.3', store: 'apple', severity: 'high', title: 'A reward for rating or reviewing the app', evidence: incent,
|
||||
fix: 'Never reward or gate ratings; ask with the system review prompt only.', skill: 'review-replies' });
|
||||
const custom = grep(p.sources, SIGNALS.ratePrompt, 2);
|
||||
if (custom.length && !src(SIGNALS.reviewApi, 1).length && !p.deps.some(d => /review|rate/i.test(d.name)))
|
||||
add({ rule: 'review-prompt', guideline: '5.6.1', store: 'apple', severity: 'medium', title: 'A custom "rate us" prompt without the system review API', evidence: custom,
|
||||
fix: 'Ask for ratings with SKStoreReviewController / requestReview (StoreKit); custom review prompts are not allowed.', skill: 'review-replies' });
|
||||
}
|
||||
if (play && c?.play && /^com\.example(\.|$)/.test(c.play.packageName))
|
||||
add({ rule: 'play-package-name', guideline: 'Play: Package name', store: 'play', severity: 'blocker', title: `Package name ${c.play.packageName} uses the reserved com.example prefix`, evidence: cfg('packageName'),
|
||||
fix: 'Pick your own reverse-domain package name (it can never change after the first upload) and set it in the Gradle applicationId and play.packageName.', skill: 'play-first-release',
|
||||
ref: 'https://developer.android.com/build/configure-app-module' });
|
||||
|
||||
// ---- owner-accepted findings ----
|
||||
const ignore = c?.scan?.ignore ?? [];
|
||||
for (const f of out) {
|
||||
const hit = ignore.find(i => i.rule === f.rule && (!i.store || i.store === f.store));
|
||||
if (hit) f.accepted = hit.reason;
|
||||
}
|
||||
return sortScan(out);
|
||||
}
|
||||
|
||||
const RANK: Record<Severity, number> = { blocker: 0, high: 1, medium: 2, low: 3 };
|
||||
/** Open findings first (blocker, high, medium, low), owner-accepted ones last; stable inside a level. */
|
||||
export function sortScan(f: ScanFinding[]): ScanFinding[] {
|
||||
return f.map((x, i) => [x, i] as const).sort(([a, i], [b, j]) => Number(!!a.accepted) - Number(!!b.accepted) || RANK[a.severity] - RANK[b.severity] || i - j).map(([x]) => x);
|
||||
}
|
||||
205
cli/lib/scan/sdks.ts
Normal file
205
cli/lib/scan/sdks.ts
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
// The SDK table `storebound scan` detects: which third-party SDKs a mobile app or game ships, from its dependency files
|
||||
// (CocoaPods, Swift Package Manager, Carthage, Gradle and version catalogs, npm, pub, Unity packages and External
|
||||
// Dependency Manager XML, Godot addons, Cordova plugins), and what each one means for the store declarations.
|
||||
//
|
||||
// Maintained by hand. Every entry names the SDK's own data disclosure page (`docs`): that page is the source for the
|
||||
// data types listed in `data`, which are the types the SDK collects by default as its vendor documents them for the
|
||||
// Play Data safety form and Apple's App Privacy. The app's own configuration can change them (for example
|
||||
// non-personalized ads only, analytics collection off), which is why scan proposes and the owner decides.
|
||||
// Checked 2026-10-11. When a vendor changes its disclosure, update the entry and the date.
|
||||
import type { PlayPurpose } from '../config';
|
||||
|
||||
export type SdkCategory = 'ads' | 'analytics' | 'attribution' | 'crash' | 'auth' | 'payments' | 'external-payments' | 'push';
|
||||
export type Eco = 'cocoapods' | 'spm' | 'carthage' | 'gradle' | 'npm' | 'pub' | 'unity' | 'godot';
|
||||
|
||||
export interface SdkData {
|
||||
/** Play Data safety type id (PSL_...). The App Privacy type follows from it (declarations.ts APPLE_PRIVACY). */
|
||||
type: string;
|
||||
collect: PlayPurpose[];
|
||||
/** Sent to the SDK vendor for its own use (Play "shared"; Apple "third-party advertising" when for ads). */
|
||||
share?: PlayPurpose[];
|
||||
}
|
||||
|
||||
export interface SdkDef {
|
||||
id: string;
|
||||
name: string;
|
||||
category: SdkCategory;
|
||||
/** Can track across apps (reads IDFA / the Android advertising id, or links data with other companies' data):
|
||||
* needs App Tracking Transparency on iOS before it does. */
|
||||
tracking: boolean;
|
||||
/** Login provider this SDK adds (4.8 Login Services). */
|
||||
login?: 'google' | 'facebook' | 'apple' | 'firebase';
|
||||
/** Matchers per ecosystem. cocoapods: pod name (or its prefix before "/"); spm: a fragment of the repository URL or
|
||||
* the package identity; gradle: "group:artifact" (or "group:" for any artifact of the group); npm / pub: package
|
||||
* name; unity: UPM package id or a folder under Assets/; godot: a folder under addons/. */
|
||||
match: Partial<Record<Eco, string[]>>;
|
||||
data: SdkData[];
|
||||
/** Vendor's data disclosure / privacy page: the source for `data`. */
|
||||
docs: string;
|
||||
/** iOS: first version that ships Apple's privacy manifest (only where the vendor's release notes say so). */
|
||||
manifestSince?: string;
|
||||
}
|
||||
|
||||
const ADS_DATA: SdkData[] = [
|
||||
{ type: 'PSL_DEVICE_ID', collect: ['advertising', 'analytics', 'fraud'], share: ['advertising'] },
|
||||
{ type: 'PSL_APPROX_LOCATION', collect: ['advertising', 'analytics', 'fraud'], share: ['advertising'] },
|
||||
{ type: 'PSL_USER_INTERACTION', collect: ['advertising', 'analytics'], share: ['advertising'] },
|
||||
{ type: 'PSL_PERFORMANCE_DIAGNOSTICS', collect: ['analytics'] },
|
||||
];
|
||||
const ANALYTICS_DATA: SdkData[] = [
|
||||
{ type: 'PSL_DEVICE_ID', collect: ['analytics'] },
|
||||
{ type: 'PSL_USER_INTERACTION', collect: ['analytics'] },
|
||||
];
|
||||
const CRASH_DATA: SdkData[] = [
|
||||
{ type: 'PSL_CRASH_LOGS', collect: ['analytics'] },
|
||||
{ type: 'PSL_PERFORMANCE_DIAGNOSTICS', collect: ['analytics'] },
|
||||
];
|
||||
const LOGIN_DATA: SdkData[] = [
|
||||
{ type: 'PSL_NAME', collect: ['account'] },
|
||||
{ type: 'PSL_EMAIL', collect: ['account'] },
|
||||
{ type: 'PSL_USER_ACCOUNT', collect: ['account'] },
|
||||
];
|
||||
|
||||
export const SDKS: SdkDef[] = [
|
||||
// ---- ads (tracking-capable: they read the advertising id when the user allows it) ----
|
||||
{ id: 'admob', name: 'Google AdMob', category: 'ads', tracking: true, data: ADS_DATA, manifestSince: '11.2.0',
|
||||
docs: 'https://developers.google.com/admob/android/privacy/play-data-disclosure',
|
||||
match: { cocoapods: ['Google-Mobile-Ads-SDK'], spm: ['swift-package-manager-google-mobile-ads'], gradle: ['com.google.android.gms:play-services-ads'],
|
||||
npm: ['react-native-google-mobile-ads', '@capacitor-community/admob', 'admob-plus-cordova', 'expo-ads-admob'], pub: ['google_mobile_ads'],
|
||||
unity: ['com.google.ads.mobile', 'GoogleMobileAds'], godot: ['admob'] } },
|
||||
{ id: 'applovin', name: 'AppLovin MAX', category: 'ads', tracking: true, data: ADS_DATA,
|
||||
docs: 'https://support.axon.ai/en/max/android/overview/data-and-privacy',
|
||||
match: { cocoapods: ['AppLovinSDK'], spm: ['applovin-ios-sdk'], gradle: ['com.applovin:applovin-sdk'], npm: ['react-native-applovin-max'],
|
||||
pub: ['applovin_max'], unity: ['com.applovin.mediation.ads', 'MaxSdk'] } },
|
||||
{ id: 'levelplay', name: 'Unity LevelPlay (ironSource)', category: 'ads', tracking: true, data: ADS_DATA,
|
||||
docs: 'https://developers.is.com/ironsource-mobile/general/ironsource-mobile-sdk-data-disclosure/',
|
||||
match: { cocoapods: ['IronSourceSDK', 'IronSourcePod'], gradle: ['com.unity3d.ads-mediation:mediation-sdk', 'com.ironsource.sdk:mediationsdk'],
|
||||
npm: ['ironsource-mediation', 'react-native-ironsource-mediation'], pub: ['unity_levelplay_mediation', 'ironsource_mediation'],
|
||||
unity: ['com.unity.services.levelplay', 'IronSource', 'LevelPlay'] } },
|
||||
{ id: 'unity-ads', name: 'Unity Ads', category: 'ads', tracking: true, data: ADS_DATA,
|
||||
docs: 'https://docs.unity.com/en-us/grow/ads/privacy/google-data-safety',
|
||||
match: { cocoapods: ['UnityAds'], gradle: ['com.unity3d.ads:unity-ads'], pub: ['unity_ads_plugin'], unity: ['com.unity.ads'], npm: ['react-native-unity-ads'] } },
|
||||
{ id: 'meta-an', name: 'Meta Audience Network', category: 'ads', tracking: true, data: ADS_DATA,
|
||||
docs: 'https://developers.facebook.com/docs/audience-network/',
|
||||
match: { cocoapods: ['FBAudienceNetwork'], gradle: ['com.facebook.android:audience-network-sdk'], npm: ['react-native-fbads'],
|
||||
pub: ['facebook_audience_network'], unity: ['AudienceNetwork'] } },
|
||||
// ---- attribution (tracking by design) ----
|
||||
{ id: 'appsflyer', name: 'AppsFlyer', category: 'attribution', tracking: true,
|
||||
data: [{ type: 'PSL_DEVICE_ID', collect: ['analytics', 'advertising', 'fraud'], share: ['advertising'] }, { type: 'PSL_USER_INTERACTION', collect: ['analytics', 'advertising'] }],
|
||||
docs: 'https://www.appsflyer.com/legal/services-privacy-policy/',
|
||||
match: { cocoapods: ['AppsFlyerFramework'], spm: ['AppsFlyerFramework'], gradle: ['com.appsflyer:af-android-sdk'], npm: ['react-native-appsflyer', 'cordova-plugin-appsflyer-sdk'],
|
||||
pub: ['appsflyer_sdk'], unity: ['appsflyer-unity-plugin', 'AppsFlyer'] } },
|
||||
{ id: 'adjust', name: 'Adjust', category: 'attribution', tracking: true,
|
||||
data: [{ type: 'PSL_DEVICE_ID', collect: ['analytics', 'advertising', 'fraud'], share: ['advertising'] }, { type: 'PSL_USER_INTERACTION', collect: ['analytics', 'advertising'] }],
|
||||
docs: 'https://help.adjust.com/en/article/google-play-data-safety',
|
||||
match: { cocoapods: ['Adjust'], spm: ['ios_sdk'], gradle: ['com.adjust.sdk:adjust-android'], npm: ['react-native-adjust'], pub: ['adjust_sdk'], unity: ['com.adjust.sdk', 'Adjust'] } },
|
||||
// ---- analytics ----
|
||||
{ id: 'firebase-analytics', name: 'Firebase Analytics', category: 'analytics', tracking: false, manifestSince: '10.22.0',
|
||||
data: [{ type: 'PSL_DEVICE_ID', collect: ['analytics'] }, { type: 'PSL_USER_INTERACTION', collect: ['analytics'] }, { type: 'PSL_APPROX_LOCATION', collect: ['analytics'] }],
|
||||
docs: 'https://firebase.google.com/docs/android/play-data-disclosure',
|
||||
match: { cocoapods: ['FirebaseAnalytics', 'Firebase/Analytics'], spm: ['firebase-ios-sdk#FirebaseAnalytics'], gradle: ['com.google.firebase:firebase-analytics'],
|
||||
npm: ['@react-native-firebase/analytics', '@capacitor-firebase/analytics', '@capacitor-community/firebase-analytics'], pub: ['firebase_analytics'],
|
||||
unity: ['com.google.firebase.analytics', 'FirebaseAnalytics'] } },
|
||||
{ id: 'gameanalytics', name: 'GameAnalytics', category: 'analytics', tracking: false, data: ANALYTICS_DATA,
|
||||
docs: 'https://gameanalytics.com/privacy-policy',
|
||||
match: { cocoapods: ['GA-SDK-IOS', 'GameAnalytics'], gradle: ['com.gameanalytics.sdk:gameanalytics-android'], unity: ['com.gameanalytics.sdk', 'GameAnalytics'],
|
||||
pub: ['gameanalytics_sdk'], npm: ['react-native-gameanalytics'] } },
|
||||
{ id: 'amplitude', name: 'Amplitude', category: 'analytics', tracking: false, data: ANALYTICS_DATA,
|
||||
docs: 'https://amplitude.com/security-and-privacy',
|
||||
match: { cocoapods: ['Amplitude', 'AmplitudeSwift'], spm: ['Amplitude-iOS', 'Amplitude-Swift'], gradle: ['com.amplitude:'], npm: ['@amplitude/analytics-react-native', '@amplitude/react-native'],
|
||||
pub: ['amplitude_flutter'], unity: ['Amplitude'] } },
|
||||
{ id: 'mixpanel', name: 'Mixpanel', category: 'analytics', tracking: false, data: ANALYTICS_DATA,
|
||||
docs: 'https://docs.mixpanel.com/docs/privacy/protecting-user-data',
|
||||
match: { cocoapods: ['Mixpanel', 'Mixpanel-swift'], spm: ['mixpanel-swift', 'mixpanel-iphone'], gradle: ['com.mixpanel.android:mixpanel-android'], npm: ['mixpanel-react-native'],
|
||||
pub: ['mixpanel_flutter'], unity: ['com.mixpanel.unity', 'Mixpanel'] } },
|
||||
// ---- crash reporting ----
|
||||
{ id: 'crashlytics', name: 'Firebase Crashlytics', category: 'crash', tracking: false, data: CRASH_DATA, manifestSince: '10.22.0',
|
||||
docs: 'https://firebase.google.com/docs/android/play-data-disclosure',
|
||||
match: { cocoapods: ['FirebaseCrashlytics', 'Firebase/Crashlytics'], spm: ['firebase-ios-sdk#FirebaseCrashlytics'], gradle: ['com.google.firebase:firebase-crashlytics'],
|
||||
npm: ['@react-native-firebase/crashlytics', '@capacitor-firebase/crashlytics'], pub: ['firebase_crashlytics'], unity: ['com.google.firebase.crashlytics', 'FirebaseCrashlytics'] } },
|
||||
{ id: 'sentry', name: 'Sentry', category: 'crash', tracking: false, data: CRASH_DATA, manifestSince: '8.21.0',
|
||||
docs: 'https://docs.sentry.io/platforms/android/data-management/data-collected/',
|
||||
match: { cocoapods: ['Sentry'], spm: ['sentry-cocoa'], gradle: ['io.sentry:sentry-android'], npm: ['@sentry/react-native', '@sentry/capacitor'], pub: ['sentry_flutter'], unity: ['io.sentry.unity'] } },
|
||||
// ---- sign-in ----
|
||||
{ id: 'google-signin', name: 'Google Sign-In', category: 'auth', tracking: false, login: 'google', data: LOGIN_DATA, manifestSince: '7.1.0',
|
||||
docs: 'https://developers.google.com/identity/sign-in/ios/start-integrating',
|
||||
match: { cocoapods: ['GoogleSignIn'], spm: ['GoogleSignIn-iOS'], gradle: ['com.google.android.gms:play-services-auth', 'com.google.android.libraries.identity.googleid:googleid'],
|
||||
npm: ['@react-native-google-signin/google-signin', '@codetrix-studio/capacitor-google-auth', 'expo-google-sign-in'], pub: ['google_sign_in'], unity: ['com.google.signin', 'GoogleSignIn'] } },
|
||||
{ id: 'facebook-login', name: 'Facebook Login', category: 'auth', tracking: true, login: 'facebook', data: LOGIN_DATA, manifestSince: '17.0.0',
|
||||
docs: 'https://developers.facebook.com/docs/facebook-login/',
|
||||
match: { cocoapods: ['FBSDKLoginKit', 'FacebookLogin'], spm: ['facebook-ios-sdk'], gradle: ['com.facebook.android:facebook-login', 'com.facebook.android:facebook-android-sdk'],
|
||||
npm: ['react-native-fbsdk-next', '@capacitor-community/facebook-login'], pub: ['flutter_facebook_auth'], unity: ['com.facebook.sdk', 'FacebookSDK'] } },
|
||||
{ id: 'apple-signin', name: 'Sign in with Apple', category: 'auth', tracking: false, login: 'apple', data: [{ type: 'PSL_NAME', collect: ['account'] }, { type: 'PSL_EMAIL', collect: ['account'] }],
|
||||
docs: 'https://developer.apple.com/sign-in-with-apple/',
|
||||
match: { npm: ['expo-apple-authentication', '@invertase/react-native-apple-authentication', '@capacitor-community/apple-sign-in', 'cordova-plugin-sign-in-with-apple'],
|
||||
pub: ['sign_in_with_apple', 'the_apple_sign_in'], unity: ['com.lupidan.apple-signin-unity', 'AppleAuth'] } },
|
||||
{ id: 'firebase-auth', name: 'Firebase Authentication', category: 'auth', tracking: false, login: 'firebase', data: LOGIN_DATA, manifestSince: '10.22.0',
|
||||
docs: 'https://firebase.google.com/docs/android/play-data-disclosure',
|
||||
match: { cocoapods: ['FirebaseAuth', 'Firebase/Auth'], spm: ['firebase-ios-sdk#FirebaseAuth'], gradle: ['com.google.firebase:firebase-auth'],
|
||||
npm: ['@react-native-firebase/auth', '@capacitor-firebase/authentication'], pub: ['firebase_auth'], unity: ['com.google.firebase.auth', 'FirebaseAuth'] } },
|
||||
// ---- payments ----
|
||||
{ id: 'play-billing', name: 'Google Play Billing', category: 'payments', tracking: false, data: [{ type: 'PSL_PURCHASE_HISTORY', collect: ['functionality'] }],
|
||||
docs: 'https://developer.android.com/google/play/billing',
|
||||
match: { gradle: ['com.android.billingclient:billing'] } },
|
||||
{ id: 'revenuecat', name: 'RevenueCat', category: 'payments', tracking: false, data: [{ type: 'PSL_PURCHASE_HISTORY', collect: ['functionality', 'analytics'] }, { type: 'PSL_USER_ACCOUNT', collect: ['functionality'] }],
|
||||
docs: 'https://www.revenuecat.com/docs/platform-resources/apple-platform-resources/apple-app-privacy',
|
||||
match: { cocoapods: ['RevenueCat', 'Purchases'], spm: ['purchases-ios'], gradle: ['com.revenuecat.purchases:purchases'], npm: ['react-native-purchases', '@revenuecat/purchases-capacitor', 'cordova-plugin-purchases'],
|
||||
pub: ['purchases_flutter'], unity: ['com.revenuecat.purchases-unity', 'RevenueCat'] } },
|
||||
{ id: 'iap-wrapper', name: 'In-app purchase plugin', category: 'payments', tracking: false, data: [{ type: 'PSL_PURCHASE_HISTORY', collect: ['functionality'] }],
|
||||
docs: 'https://developer.apple.com/storekit/',
|
||||
match: { npm: ['react-native-iap', 'expo-iap', 'expo-in-app-purchases', 'cordova-plugin-purchase', '@capgo/native-purchases'], pub: ['in_app_purchase'], unity: ['com.unity.purchasing'] } },
|
||||
// ---- payments outside the stores (fine for physical goods and services; digital goods need in-app purchase) ----
|
||||
{ id: 'stripe', name: 'Stripe', category: 'external-payments', tracking: false, data: [{ type: 'PSL_CREDIT_DEBIT_BANK_ACCOUNT_NUMBER', collect: ['functionality', 'fraud'] }, { type: 'PSL_PURCHASE_HISTORY', collect: ['functionality'] }],
|
||||
docs: 'https://stripe.com/privacy',
|
||||
match: { cocoapods: ['Stripe', 'StripePaymentSheet'], spm: ['stripe-ios'], gradle: ['com.stripe:stripe-android'], npm: ['@stripe/stripe-react-native', '@capacitor-community/stripe'], pub: ['flutter_stripe'] } },
|
||||
{ id: 'paypal', name: 'PayPal / Braintree', category: 'external-payments', tracking: false, data: [{ type: 'PSL_PURCHASE_HISTORY', collect: ['functionality'] }],
|
||||
docs: 'https://www.paypal.com/us/legalhub/privacy-full',
|
||||
match: { cocoapods: ['Braintree', 'PayPalCheckout', 'PayPal'], spm: ['braintree_ios', 'paypal-ios'], gradle: ['com.braintreepayments.api:', 'com.paypal.checkout:', 'com.paypal.android:'],
|
||||
npm: ['react-native-paypal', 'react-native-braintree-dropin-ui'], pub: ['flutter_braintree', 'flutter_paypal'] } },
|
||||
// ---- push ----
|
||||
{ id: 'fcm', name: 'Firebase Cloud Messaging', category: 'push', tracking: false, data: [{ type: 'PSL_DEVICE_ID', collect: ['functionality'] }], manifestSince: '10.22.0',
|
||||
docs: 'https://firebase.google.com/docs/android/play-data-disclosure',
|
||||
match: { cocoapods: ['FirebaseMessaging', 'Firebase/Messaging'], spm: ['firebase-ios-sdk#FirebaseMessaging'], gradle: ['com.google.firebase:firebase-messaging'],
|
||||
npm: ['@react-native-firebase/messaging', '@capacitor-firebase/messaging'], pub: ['firebase_messaging'], unity: ['com.google.firebase.messaging', 'FirebaseMessaging'] } },
|
||||
{ id: 'onesignal', name: 'OneSignal', category: 'push', tracking: false, data: [{ type: 'PSL_USER_INTERACTION', collect: ['analytics'] }, { type: 'PSL_PURCHASE_HISTORY', collect: ['analytics'] }],
|
||||
docs: 'https://documentation.onesignal.com/docs/google-play-data-safety-requirements',
|
||||
match: { cocoapods: ['OneSignalXCFramework', 'OneSignal'], spm: ['OneSignal-XCFramework'], gradle: ['com.onesignal:OneSignal'], npm: ['react-native-onesignal', 'onesignal-cordova-plugin', 'onesignal-expo-plugin'],
|
||||
pub: ['onesignal_flutter'], unity: ['com.onesignal.unity', 'OneSignal'] } },
|
||||
{ id: 'push-plugin', name: 'Push notifications plugin', category: 'push', tracking: false, data: [],
|
||||
docs: 'https://developer.apple.com/documentation/usernotifications',
|
||||
match: { npm: ['@capacitor/push-notifications', 'expo-notifications', '@react-native-community/push-notification-ios', 'react-native-push-notification'], pub: ['flutter_local_notifications'], unity: ['com.unity.mobile.notifications'] } },
|
||||
];
|
||||
|
||||
export interface DepRef { eco: Eco; name: string; version: string | null; file: string; line: number }
|
||||
|
||||
/** Does a dependency match an SDK? Pods match by name or "Name/Sub"; Gradle by "group:artifact" or a "group:" prefix;
|
||||
* SPM by URL fragment (or "url#Product" for one product of a multi-product repository, matched on the product). */
|
||||
export function matchesSdk(d: DepRef, s: SdkDef): boolean {
|
||||
const list = s.match[d.eco] ?? [];
|
||||
const n = d.name;
|
||||
return list.some(m => {
|
||||
switch (d.eco) {
|
||||
case 'cocoapods': return n === m || n.startsWith(`${m}/`);
|
||||
case 'gradle': return m.endsWith(':') ? n.startsWith(m) : n === m;
|
||||
case 'spm': {
|
||||
const [repo, product] = m.split('#') as [string, string | undefined];
|
||||
if (product) return n.toLowerCase() === product.toLowerCase();
|
||||
return n.toLowerCase().includes(repo.toLowerCase());
|
||||
}
|
||||
case 'unity': return n === m || n.toLowerCase() === m.toLowerCase();
|
||||
default: return n === m;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** "1.2.3" vs "1.10" numerically; non-numeric parts count as 0. Ranges like "^11.2.0" or "~> 11.0" use their numbers. */
|
||||
export function versionAtLeast(v: string, min: string): boolean | null {
|
||||
const nums = (s: string) => (/\d+(\.\d+)*/.exec(s)?.[0] ?? '').split('.').filter(Boolean).map(Number);
|
||||
const a = nums(v), b = nums(min);
|
||||
if (!a.length) return null;
|
||||
for (let i = 0; i < Math.max(a.length, b.length); i++) {
|
||||
const x = a[i] ?? 0, y = b[i] ?? 0;
|
||||
if (x !== y) return x > y;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue