[tauri] KeepHerSafeApps: App words for Keep her safe, and Android's own save screen through a narrow bridge

This commit is contained in:
2026-11-17 20:31:35 +01:00
parent 0b72ae05a2
commit 3c4463dbdd
9 changed files with 341 additions and 13 deletions
@@ -0,0 +1,87 @@
package cz.mareknovak.domi.rosea
// Rosea's own MainActivity, copied over the one `tauri android init` generates by
// apps/rosea-tauri/scripts/android.ts (gen/ is never committed; `android.ts check` compares it).
// .agents/features/keep-her-safe-apps.md A2–A5.
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.webkit.JavascriptInterface
import android.webkit.WebView
import androidx.activity.enableEdgeToEdge
import androidx.annotation.Keep
class MainActivity : TauriActivity() {
private var webView: WebView? = null
private var busy = false
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
}
// *Save her to a file*: Android WebView does nothing with a blob download, so the game asks
// here instead (window.roseaFile.save), and Android's own save screen lets the player choose
// where the file goes. No permission is needed for it on any Android version.
override fun onWebViewCreate(webView: WebView) {
this.webView = webView
webView.addJavascriptInterface(RoseFile(), "roseaFile")
}
/** Tells the game whether the file was written (A4): true, or false when the player stepped back. */
private fun answer(written: Boolean) {
busy = false
val view = webView ?: return
view.post {
view.evaluateJavascript("window.dispatchEvent(new CustomEvent('rosea-file-saved', { detail: $written }))", null)
}
}
@Keep
inner class RoseFile {
/** Only a rose file: its dated name and a bounded text (A3). One save at a time. */
@Keep
@JavascriptInterface
fun save(name: String, text: String) {
if (!NAME.matches(name) || text.length > MAX_CHARS) {
Log.w(TAG, "refused a file that is not a rose file: ${name.take(64)}, ${text.length} chars")
answer(false)
return
}
runOnUiThread {
if (busy) return@runOnUiThread
busy = true
val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "application/json"
putExtra(Intent.EXTRA_TITLE, name)
}
launchActivityForResult(intent) { result ->
val uri = result?.data?.data
if (result?.resultCode != Activity.RESULT_OK || uri == null) {
answer(false)
return@launchActivityForResult
}
val written = try {
contentResolver.openOutputStream(uri, "wt")?.use { out ->
out.write(text.toByteArray(Charsets.UTF_8))
true
} ?: false
} catch (error: Exception) {
Log.e(TAG, "the rose file could not be written", error)
false
}
answer(written)
}
}
}
}
companion object {
private const val TAG = "RoseaFile"
private val NAME = Regex("^rose-\\d{4}-\\d{2}-\\d{2}\\.json$")
private const val MAX_CHARS = 8 * 1024 * 1024
}
}
+12 -2
View File
@@ -13,7 +13,7 @@
*/
import { spawnSync } from 'node:child_process';
import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { dirname, join } from 'node:path';
import { apkProblems, manifestProblems, patchManifest, RULE_FILES, RULE_SECTIONS, ruleProblems } from '../src/android-privacy.js';
import { PACKAGE, SRC_TAURI, tauri } from './tauri.js';
@@ -22,6 +22,10 @@ const MANIFEST = join(MAIN, 'AndroidManifest.xml');
const RES_FROM = join(PACKAGE, 'android', 'res', 'xml');
const RES_TO = join(MAIN, 'res', 'xml');
const OUTPUTS = join(SRC_TAURI, 'gen', 'android', 'app', 'build', 'outputs', 'apk');
// Rosea's own MainActivity: the save bridge (keep-her-safe-apps.md A2, A5).
const IDENTIFIER = (JSON.parse(readFileSync(join(SRC_TAURI, 'tauri.conf.json'), 'utf8')) as { identifier: string }).identifier;
const ACTIVITY_FROM = join(PACKAGE, 'android', 'java', 'MainActivity.kt');
const ACTIVITY_TO = join(MAIN, 'java', ...IDENTIFIER.split('.'), 'MainActivity.kt');
function fail(problems: readonly string[]): never {
for (const p of problems) console.error(`android: ${p}`);
@@ -36,6 +40,10 @@ function problems(): string[] {
if (!existsSync(at)) found.push(`res/xml/${f} is missing`);
else if (readFileSync(at, 'utf8') !== readFileSync(join(RES_FROM, f), 'utf8')) found.push(`res/xml/${f} differs from android/res/xml/${f}`);
}
if (!existsSync(ACTIVITY_TO)) found.push(`no MainActivity.kt at ${ACTIVITY_TO}`);
else if (readFileSync(ACTIVITY_TO, 'utf8') !== readFileSync(ACTIVITY_FROM, 'utf8')) {
found.push("MainActivity.kt is not Rosea's (android/java/MainActivity.kt): no save bridge");
}
// The launcher icon is Rosea's, not the Tauri logo `init` put there (scripts/icons.ts).
const ours = join(SRC_TAURI, 'icons', 'android', 'mipmap-mdpi', 'ic_launcher.png');
const there = join(MAIN, 'res', 'mipmap-mdpi', 'ic_launcher.png');
@@ -55,12 +63,14 @@ function apply(): void {
const after = patchManifest(before);
mkdirSync(RES_TO, { recursive: true });
for (const f of RULE_FILES) copyFileSync(join(RES_FROM, f), join(RES_TO, f));
if (!existsSync(dirname(ACTIVITY_TO))) fail([`no generated activity folder ${dirname(ACTIVITY_TO)}; the identifier changed?`]);
copyFileSync(ACTIVITY_FROM, ACTIVITY_TO);
if (after !== before) writeFileSync(MANIFEST, after);
const left = problems();
if (left.length > 0) fail(left);
console.log(
`android: privacy ${after === before ? 'already in place' : 'applied'} ` +
'(no INTERNET, no backup or transfer, WebView metrics and Safe Browsing off)'
"(no INTERNET, no backup or transfer, WebView metrics and Safe Browsing off; Rosea's MainActivity)"
);
}
@@ -0,0 +1,58 @@
/**
* The save bridge's contract between the Kotlin side (android/java/MainActivity.kt) and the game
* (apps/rosea/src/App.svelte, packages/ui KeepSafe): keep-her-safe-apps.md A2–A5. A mismatch here
* fails silently on the device — the save screen never opens, or the garden never hears back —
* so the names are read from both sources and compared.
*/
import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';
const HERE = dirname(fileURLToPath(import.meta.url));
const kotlin = readFileSync(join(HERE, '..', 'android', 'java', 'MainActivity.kt'), 'utf8');
const app = readFileSync(join(HERE, '..', '..', 'rosea', 'src', 'App.svelte'), 'utf8');
const keepSafe = readFileSync(join(HERE, '..', '..', '..', 'packages', 'ui', 'src', 'rose', 'KeepSafe.svelte'), 'utf8');
const conf = JSON.parse(readFileSync(join(HERE, '..', 'src-tauri', 'tauri.conf.json'), 'utf8')) as { identifier: string };
const nameRule = new RegExp(/Regex\("(.+?)"\)/.exec(kotlin)?.[1]?.replaceAll('\\\\', '\\') ?? 'missing');
describe('the Android save bridge', () => {
it('lives in the package of the app it is copied into', () => {
expect(kotlin).toMatch(new RegExp(`^package ${conf.identifier.replaceAll('.', '\\.')}$`, 'm'));
expect(kotlin).toMatch(/class MainActivity : TauriActivity\(\)/);
});
it('is found by the game under the name it is registered with', () => {
const registered = /addJavascriptInterface\(RoseFile\(\), "(\w+)"\)/.exec(kotlin)?.[1];
expect(registered).toBe('roseaFile');
expect(app).toContain(`roseaFile?: { save(name: string, text: string): void }`);
expect(app).toContain('.roseaFile');
});
it('answers on the event the game listens for, with true or false', () => {
const event = /new CustomEvent\('([\w-]+)', \{ detail: \$written \}\)/.exec(kotlin)?.[1];
expect(event).toBe('rosea-file-saved');
expect(app.match(/'rosea-file-saved'/g)?.length).toBeGreaterThanOrEqual(2);
expect(app).toContain('.detail === true');
});
it("accepts the file name the garden gives (rose-<day>.json) and nothing else", () => {
expect(keepSafe).toContain('`rose-${today}.json`');
expect(nameRule.test('rose-2026-11-17.json')).toBe(true);
for (const wrong of ['rose.json', '../rose-2026-11-17.json', 'rose-2026-11-17.json.exe', 'rose-2026-11-17.apk', 'evil-2026-11-17.json']) {
expect(nameRule.test(wrong)).toBe(false);
}
});
it('keeps the bridge through a minified release build', () => {
expect(kotlin).toMatch(/@Keep\s+inner class RoseFile/);
expect(kotlin).toMatch(/@JavascriptInterface\s+fun save\(name: String, text: String\)/);
});
it('asks Android for nothing: the save screen needs no permission', () => {
// Asking at run time or naming one; the APK check (aapt2) refuses any declared in the manifest.
expect(kotlin).not.toMatch(/requestPermissions\(|Manifest\.permission|checkSelfPermission/);
expect(kotlin).toContain('Intent.ACTION_CREATE_DOCUMENT');
});
});
+36 -5
View File
@@ -54,15 +54,17 @@
}
// --- Keeping her (keep-her-safe.md) -------------------------------------
// The Android, iOS and desktop apps are installed by being apps (tauri-platforms.md D9):
// they ask to keep the garden after the first care, as an installed PWA does, and never
// show the hint to add the page to the home screen. Keep her safe speaks of the app, not a
// browser (keep-her-safe-apps.md A1).
const inApp = __ROSEA_SHELL__ === 'tauri';
const browserStorage = typeof navigator !== 'undefined' ? navigator.storage : undefined;
const keeping: RoseWiring['keeping'] = {
where: inApp ? 'app' : 'browser',
persisted: async () => (browserStorage?.persisted ? browserStorage.persisted() : null),
persist: async () => (browserStorage?.persist ? browserStorage.persist() : null)
};
// The Android, iOS and desktop apps are installed by being apps (tauri-platforms.md D9):
// they ask to keep the garden after the first care, as an installed PWA does, and never
// show the hint to add the page to the home screen.
const inApp = __ROSEA_SHELL__ === 'tauri';
const installed = (): boolean =>
inApp ||
matchMedia('(display-mode: standalone)').matches ||
@@ -76,7 +78,36 @@
keeping.persist().catch((error: unknown) => console.error('keep: asking the browser to keep the garden failed', error));
}
function saveFile(name: string, text: string): void {
/**
* Android's save screen, through the app's own bridge (keep-her-safe-apps.md A2): present
* only in the Android app, where `<a download>` does nothing. It answers with a window event,
* true when the file was written, false when the player stepped back (A4).
*/
const androidFile = inApp ? (window as Window & { roseaFile?: { save(name: string, text: string): void } }).roseaFile : undefined;
let saving: Promise<boolean> | undefined;
function saveFile(name: string, text: string): void | Promise<boolean> {
if (androidFile) {
// One save at a time: a second tap while the screen is open waits for the first answer.
if (saving) return saving;
saving = new Promise<boolean>((resolve) => {
const answer = (event: Event): void => {
window.removeEventListener('rosea-file-saved', answer);
saving = undefined;
resolve((event as CustomEvent<unknown>).detail === true);
};
window.addEventListener('rosea-file-saved', answer);
try {
androidFile.save(name, text);
} catch (error) {
console.error('keep: the app could not open the save screen', error);
window.removeEventListener('rosea-file-saved', answer);
saving = undefined;
resolve(false);
}
});
return saving;
}
// A file made here and handed over; nothing is sent anywhere.
const url = URL.createObjectURL(new Blob([text], { type: 'application/json' }));
const a = Object.assign(document.createElement('a'), { href: url, download: name });