Files
Rosea/apps/rosea-tauri/src/android-privacy.ts
T

181 lines
8.7 KiB
TypeScript

/**
* The Android app's privacy, applied to Tauri's generated project (tauri-platforms.md D6).
*
* `src-tauri/gen/android` is written by `tauri android init` and never committed, so every
* clone starts from Tauri's stock manifest, which asks for `INTERNET` and lets Android copy the
* app's data to the player's cloud backup. What must hold is carried here and applied before
* every Android build; the build fails if anything is missing. The approach and the two rule
* files follow Amicitia's (its `android-privacy.md`, measured there on 2026-11-08):
*
* - **no `INTERNET`**: Rosea has no network feature yet, so the kernel refuses the app any
* socket, the webview's own traffic included. It comes back with the first feature that
* needs the network (Phase 3), and that feature's doc measures the webview first;
* - **no backup and no device transfer**: the care log, the keys and the chosen town stay on
* this device; *Keep her safe* is how a rose moves;
* - the WebView's **metrics** and **Safe Browsing** lookups off, for the day `INTERNET` returns.
*
* Pure functions on strings; the files are read and written by `scripts/android.ts`.
*/
export const BACKUP_RULES = 'rosea_backup_rules';
export const EXTRACTION_RULES = 'rosea_data_extraction_rules';
export const RULE_FILES = [`${BACKUP_RULES}.xml`, `${EXTRACTION_RULES}.xml`] as const;
/** Attributes `<application>` must carry. */
export const APPLICATION_ATTRS: Readonly<Record<string, string>> = {
'android:allowBackup': 'false',
'android:fullBackupContent': `@xml/${BACKUP_RULES}`,
'android:dataExtractionRules': `@xml/${EXTRACTION_RULES}`
};
/** WebView switches read from the manifest (developer.android.com, "Manage WebView objects"). */
export const META_DATA: Readonly<Record<string, string>> = {
'android.webkit.WebView.EnableSafeBrowsing': 'false',
'android.webkit.WebView.MetricsOptOut': 'true'
};
const BEGIN = '<!-- rosea-privacy: begin (apps/rosea-tauri/src/android-privacy.ts) -->';
const END = '<!-- rosea-privacy: end -->';
const INTERNET_LINE = /^[ \t]*<uses-permission\s+android:name="android\.permission\.INTERNET"\s*\/>[ \t]*\n/gm;
const INTERNET_ANY = /android\.permission\.INTERNET/;
const escape = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
/** The one `<application …>` opening tag, or an error naming what is wrong. */
function applicationTag(xml: string): RegExpMatchArray & { index: number } {
const tags = [...xml.matchAll(/<application\b[^>]*>/g)];
if (tags.length !== 1) throw new Error(`expected one <application> tag, found ${tags.length}`);
const tag = tags[0]!;
if (tag[0].endsWith('/>')) throw new Error('<application/> is empty; expected a template with children');
return tag as RegExpMatchArray & { index: number };
}
function setAttribute(tag: string, name: string, value: string): string {
const re = new RegExp(`(\\s${escape(name)}=")[^"]*(")`);
if (re.test(tag)) return tag.replace(re, `$1${value}$2`);
const indent = /\n([ \t]+)android:/.exec(tag)?.[1] ?? ' ';
return tag.replace(/^<application\b/, `<application\n${indent}${name}="${value}"`);
}
/** The manifest with the privacy settings in place. Throws, changing nothing, on an unexpected shape. */
export function patchManifest(xml: string): string {
const eol = xml.includes('\r\n') ? '\r\n' : '\n';
let out = xml.replaceAll('\r\n', '\n');
// 1. <application> attributes.
const tag = applicationTag(out);
let patched = tag[0];
for (const [name, value] of Object.entries(APPLICATION_ATTRS)) patched = setAttribute(patched, name, value);
out = out.slice(0, tag.index) + patched + out.slice(tag.index + tag[0].length);
// 2. The meta-data block, replaced whole on every run, so a second run changes nothing.
const from = out.indexOf(BEGIN);
if (from >= 0) {
const to = out.indexOf(END, from);
if (to < 0) throw new Error('found the begin marker of the privacy block but not its end');
const lineStart = out.lastIndexOf('\n', from) + 1;
const lineEnd = out.indexOf('\n', to);
out = out.slice(0, lineStart) + out.slice(lineEnd + 1);
}
const closes = [...out.matchAll(/^([ \t]*)<\/application>/gm)];
if (closes.length !== 1) throw new Error(`expected one </application>, found ${closes.length}`);
const close = closes[0]!;
const indent = `${close[1] ?? ''} `;
const block = [
BEGIN,
...Object.entries(META_DATA).map(([n, v]) => `<meta-data android:name="${n}" android:value="${v}" />`),
END
]
.map((line) => `${indent}${line}\n`)
.join('');
out = out.slice(0, close.index) + block + out.slice(close.index);
// 3. INTERNET removed. Any other form of asking for it is refused rather than missed.
out = out.replace(INTERNET_LINE, '');
if (INTERNET_ANY.test(out)) throw new Error('INTERNET is requested in a form this patch does not remove');
return out.replaceAll('\n', eol);
}
/** What the manifest lacks, by name; empty when it is in order. */
export function manifestProblems(xml: string): string[] {
const problems: string[] = [];
let tag: string;
try {
tag = applicationTag(xml)[0];
} catch (error) {
return [(error as Error).message];
}
for (const [name, value] of Object.entries(APPLICATION_ATTRS)) {
if (!new RegExp(`\\s${escape(name)}="${escape(value)}"`).test(tag)) problems.push(`<application> lacks ${name}="${value}"`);
}
for (const [name, value] of Object.entries(META_DATA)) {
if (!new RegExp(`<meta-data\\s+android:name="${escape(name)}"\\s+android:value="${escape(value)}"\\s*/>`).test(xml)) {
problems.push(`no meta-data ${name}=${value}`);
}
}
if (INTERNET_ANY.test(xml)) problems.push('android.permission.INTERNET is requested');
return problems;
}
/** Every storage domain Android knows; each must be excluded. */
export const DOMAINS = [
'root', 'file', 'database', 'sharedpref', 'external',
'device_root', 'device_file', 'device_database', 'device_sharedpref'
] as const;
/** Where each rules file must exclude everything: '' is the file's root element. */
export const RULE_SECTIONS: Readonly<Record<(typeof RULE_FILES)[number], readonly string[]>> = {
[`${BACKUP_RULES}.xml`]: [''],
[`${EXTRACTION_RULES}.xml`]: ['cloud-backup', 'device-transfer']
} as Record<(typeof RULE_FILES)[number], readonly string[]>;
/** A rules file must exclude every domain in every section, and include nothing. */
export function ruleProblems(xml: string, sections: readonly string[]): string[] {
const problems: string[] = [];
if (/<include\b/.test(xml)) problems.push('includes something');
for (const section of sections) {
const body = section ? new RegExp(`<${section}\\b[^>]*>([\\s\\S]*?)</${section}>`).exec(xml)?.[1] : xml;
if (body === undefined) {
problems.push(`no <${section}>`);
continue;
}
for (const domain of DOMAINS) {
if (!new RegExp(`<exclude\\s+domain="${domain}"\\s+path="\\."\\s*/>`).test(body)) {
problems.push(`${section || 'root'}: ${domain} is not excluded`);
}
}
}
return problems;
}
/**
* What the BUILT APK says, from `aapt2 dump permissions` and `aapt2 dump xmltree` of its
* manifest: the proof is the artefact, not the source (Amicitia lessons/technical.md).
* The manifest merge can add permissions from libraries; only the APK can tell.
*/
export function apkProblems(permissions: string, manifestTree: string): string[] {
const problems: string[] = [];
const tree = manifestTree.replaceAll('\r\n', '\n');
const pkg = /^package: (\S+)$/m.exec(permissions.replaceAll('\r\n', '\n'))?.[1];
for (const m of permissions.matchAll(/uses-permission: name='([^']+)'/g)) {
const name = m[1]!;
// androidx's receiver guard: a signature permission the app declares for itself, granting nothing.
if (pkg !== undefined && name === `${pkg}.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION`) continue;
// Any other is a review question, not a pass: Rosea asks for no permission yet.
problems.push(`the APK asks for ${name}`);
}
if (!/:allowBackup\(0x[0-9a-f]+\)=false$/m.test(tree)) problems.push('the APK does not set allowBackup=false');
for (const [name, value] of Object.entries(META_DATA)) {
// aapt2 prints a meta-data element's name attribute, then its value attribute on the next line:
// A: http://schemas.android.com/apk/res/android:name(0x01010003)="<name>" (Raw: "<name>")
// A: http://schemas.android.com/apk/res/android:value(0x01010024)=true
const found = new RegExp(
`:name\\(0x[0-9a-f]+\\)="${escape(name)}"[^\\n]*\\n\\s*A: [^\\n]*:value\\(0x[0-9a-f]+\\)=(\\S+)`
).exec(tree);
if (!found) problems.push(`the APK has no meta-data ${name}`);
else if (found[1] !== value && found[1] !== `"${value}"`) problems.push(`the APK's meta-data ${name} is ${found[1]}, not ${value}`);
}
return problems;
}