[tauri] TauriPlatforms: The shell around the built game, the Android privacy patch, the shell build of the game, and the device check
This commit is contained in:
@@ -31,3 +31,9 @@ Thumbs.db
|
||||
|
||||
# Generated from JSON Schema by packages/schema build
|
||||
packages/schema/src/generated/
|
||||
|
||||
# The Tauri shell (apps/rosea-tauri): the game's copy for it, Tauri's generated mobile
|
||||
# projects and the icons made from apps/rosea/public/icon.svg at build time
|
||||
dist-tauri/
|
||||
apps/rosea-tauri/src-tauri/gen/
|
||||
apps/rosea-tauri/src-tauri/icons/
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Android 11 and earlier: no part of the garden is backed up (tauri-platforms.md D6).
|
||||
Copied into gen/android by scripts/android.ts. -->
|
||||
<full-backup-content>
|
||||
<exclude domain="root" path="." />
|
||||
<exclude domain="file" path="." />
|
||||
<exclude domain="database" path="." />
|
||||
<exclude domain="sharedpref" path="." />
|
||||
<exclude domain="external" path="." />
|
||||
<exclude domain="device_root" path="." />
|
||||
<exclude domain="device_file" path="." />
|
||||
<exclude domain="device_database" path="." />
|
||||
<exclude domain="device_sharedpref" path="." />
|
||||
</full-backup-content>
|
||||
@@ -0,0 +1,30 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Android 12 and later. Nothing of the garden goes into a cloud backup or a device-to-device
|
||||
transfer: the care log, the keys and the chosen town stay on this device (CLAUDE.md §4,
|
||||
tauri-platforms.md D6). A rose moves only by the player's own hand, with Keep her safe.
|
||||
allowBackup="false" alone does not stop every device-transfer tool on Android 12+, so every
|
||||
domain is excluded here as well. Copied into gen/android by scripts/android.ts. -->
|
||||
<data-extraction-rules>
|
||||
<cloud-backup>
|
||||
<exclude domain="root" path="." />
|
||||
<exclude domain="file" path="." />
|
||||
<exclude domain="database" path="." />
|
||||
<exclude domain="sharedpref" path="." />
|
||||
<exclude domain="external" path="." />
|
||||
<exclude domain="device_root" path="." />
|
||||
<exclude domain="device_file" path="." />
|
||||
<exclude domain="device_database" path="." />
|
||||
<exclude domain="device_sharedpref" path="." />
|
||||
</cloud-backup>
|
||||
<device-transfer>
|
||||
<exclude domain="root" path="." />
|
||||
<exclude domain="file" path="." />
|
||||
<exclude domain="database" path="." />
|
||||
<exclude domain="sharedpref" path="." />
|
||||
<exclude domain="external" path="." />
|
||||
<exclude domain="device_root" path="." />
|
||||
<exclude domain="device_file" path="." />
|
||||
<exclude domain="device_database" path="." />
|
||||
<exclude domain="device_sharedpref" path="." />
|
||||
</device-transfer>
|
||||
</data-extraction-rules>
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "@rosea/tauri",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "The Tauri 2 shell: the Android, iOS and desktop apps around apps/rosea's built game (dist-tauri/). Imports no package.",
|
||||
"scripts": {
|
||||
"dev": "tsx scripts/icons.ts && tauri dev",
|
||||
"build:desktop": "tsx scripts/icons.ts && tauri build",
|
||||
"build:android": "tsx scripts/android.ts prepare && tauri android build --debug --apk --target aarch64 && tsx scripts/android.ts verify",
|
||||
"build:ios": "tsx scripts/ios.ts",
|
||||
"android:privacy": "tsx scripts/android.ts apply",
|
||||
"android:verify": "tsx scripts/android.ts verify",
|
||||
"typecheck": "tsc -p tsconfig.json",
|
||||
"test": "vitest run --reporter=verbose"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tauri-apps/cli": "2.12.5",
|
||||
"@types/node": "22.20.1",
|
||||
"tsx": "4.23.12",
|
||||
"typescript": "5.9.3",
|
||||
"vitest": "3.2.7"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* The Android app's privacy on the generated project, and the proof on the built APK
|
||||
* (src/android-privacy.ts; tauri-platforms.md D6).
|
||||
*
|
||||
* tsx scripts/android.ts prepare `tauri android init` if needed, icons, then apply
|
||||
* tsx scripts/android.ts apply patch the manifest, copy the rule files, then check
|
||||
* tsx scripts/android.ts check what the generated project lacks; exit 1 if anything
|
||||
* tsx scripts/android.ts verify [apk] the same, read from the BUILT APK with aapt2
|
||||
*
|
||||
* `apply` runs from tauri.android.conf.json's beforeBuildCommand, so `tauri android build`
|
||||
* cannot make an APK without it. A Gradle build started outside the Tauri CLI skips that hook;
|
||||
* `verify` reads the artefact itself, and `pnpm tauri:android` runs it last.
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
||||
import { 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';
|
||||
|
||||
const MAIN = join(SRC_TAURI, 'gen', 'android', 'app', 'src', 'main');
|
||||
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');
|
||||
|
||||
function fail(problems: readonly string[]): never {
|
||||
for (const p of problems) console.error(`android: ${p}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
function problems(): string[] {
|
||||
if (!existsSync(MANIFEST)) return [`no generated project (${MANIFEST}); run 'pnpm tauri:android'`];
|
||||
const found = manifestProblems(readFileSync(MANIFEST, 'utf8'));
|
||||
for (const f of RULE_FILES) {
|
||||
const at = join(RES_TO, f);
|
||||
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}`);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
function apply(): void {
|
||||
for (const f of RULE_FILES) {
|
||||
const left = ruleProblems(readFileSync(join(RES_FROM, f), 'utf8'), RULE_SECTIONS[f]);
|
||||
if (left.length > 0) fail(left.map((p) => `android/res/xml/${f}: ${p}`));
|
||||
}
|
||||
if (!existsSync(MANIFEST)) fail([`no generated project (${MANIFEST}); run 'pnpm tauri:android'`]);
|
||||
const before = readFileSync(MANIFEST, 'utf8');
|
||||
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 (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)'
|
||||
);
|
||||
}
|
||||
|
||||
function newestApk(dir: string): string | undefined {
|
||||
if (!existsSync(dir)) return undefined;
|
||||
let best: { path: string; at: number } | undefined;
|
||||
const walk = (d: string): void => {
|
||||
for (const name of readdirSync(d)) {
|
||||
const path = join(d, name);
|
||||
const stat = statSync(path);
|
||||
if (stat.isDirectory()) walk(path);
|
||||
else if (name.endsWith('.apk') && (!best || stat.mtimeMs > best.at)) best = { path, at: stat.mtimeMs };
|
||||
}
|
||||
};
|
||||
walk(dir);
|
||||
return best?.path;
|
||||
}
|
||||
|
||||
function aapt2(): string {
|
||||
const sdk = process.env['ANDROID_HOME'] ?? process.env['ANDROID_SDK_ROOT'];
|
||||
if (!sdk) fail(['ANDROID_HOME is not set']);
|
||||
const tools = join(sdk, 'build-tools');
|
||||
const versions = readdirSync(tools).sort((a, b) => b.localeCompare(a, undefined, { numeric: true }));
|
||||
const exe = process.platform === 'win32' ? 'aapt2.exe' : 'aapt2';
|
||||
for (const v of versions) if (existsSync(join(tools, v, exe))) return join(tools, v, exe);
|
||||
return fail([`no aapt2 under ${tools}`]);
|
||||
}
|
||||
|
||||
function verify(apk: string | undefined): void {
|
||||
const file = apk ?? newestApk(OUTPUTS);
|
||||
if (file === undefined || !existsSync(file)) fail([`no APK to verify under ${OUTPUTS}`]);
|
||||
const tool = aapt2();
|
||||
const run = (...args: string[]): string => {
|
||||
const r = spawnSync(tool, args, { encoding: 'utf8' });
|
||||
if (r.status !== 0) fail([`aapt2 ${args.join(' ')} failed: ${r.stderr}`]);
|
||||
return r.stdout;
|
||||
};
|
||||
const left = apkProblems(run('dump', 'permissions', file), run('dump', 'xmltree', '--file', 'AndroidManifest.xml', file));
|
||||
if (left.length > 0) fail(left);
|
||||
console.log(`android: ${file} verified (no permission asked, no backup, WebView metrics and Safe Browsing off)`);
|
||||
}
|
||||
|
||||
const [command, arg] = process.argv.slice(2);
|
||||
try {
|
||||
if (command === 'prepare') {
|
||||
if (!existsSync(MANIFEST)) tauri('android', 'init', '--ci', '--skip-targets-install');
|
||||
await import('./icons.js');
|
||||
apply();
|
||||
} else if (command === 'apply') apply();
|
||||
else if (command === 'check') {
|
||||
const left = problems();
|
||||
if (left.length > 0) fail(left);
|
||||
console.log('android: privacy in place');
|
||||
} else if (command === 'verify') verify(arg);
|
||||
else fail(['usage: android.ts prepare|apply|check|verify [apk]']);
|
||||
} catch (error) {
|
||||
fail([(error as Error).message]);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* The app's icons, made from the PWA's icon (`apps/rosea/public/icon.svg`) before every build
|
||||
* (tauri-platforms.md D8). They are build output, never committed: the only images in git are
|
||||
* the source SVG and optimised art under art/final/ (CLAUDE.md §5.2). The icon is still a
|
||||
* placeholder; the real one comes through the art pipeline (GAP_ANALYSIS G0.21).
|
||||
*
|
||||
* tsx scripts/icons.ts makes them when missing or older than the SVG
|
||||
*/
|
||||
import { existsSync, statSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { PACKAGE, SRC_TAURI, tauri } from './tauri.js';
|
||||
|
||||
const SOURCE = join(PACKAGE, '..', 'rosea', 'public', 'icon.svg');
|
||||
const MARK = join(SRC_TAURI, 'icons', 'icon.ico');
|
||||
const ANDROID = join(SRC_TAURI, 'gen', 'android');
|
||||
const ANDROID_MARK = join(ANDROID, 'app', 'src', 'main', 'res', 'mipmap-mdpi', 'ic_launcher.png');
|
||||
|
||||
const stale = (file: string): boolean => !existsSync(file) || statSync(file).mtimeMs < statSync(SOURCE).mtimeMs;
|
||||
|
||||
// `tauri icon` writes the Android launcher icons into gen/android only when that exists, so it
|
||||
// runs again after `tauri android init` (which puts Tauri's own logo there).
|
||||
if (stale(MARK) || (existsSync(ANDROID) && stale(ANDROID_MARK))) {
|
||||
tauri('icon', SOURCE);
|
||||
console.log('icons: made from apps/rosea/public/icon.svg');
|
||||
} else {
|
||||
console.log('icons: up to date');
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* The iOS app. Tauri can build it only on macOS with Xcode, and putting it on a phone needs an
|
||||
* Apple developer account (free for one's own device; paid for TestFlight and the App Store).
|
||||
* Elsewhere this refuses with that reason instead of failing somewhere deep in the CLI
|
||||
* (CLAUDE.md §8, *iOS cannot be built on Windows*; tauri-platforms.md G-T1).
|
||||
*
|
||||
* tsx scripts/ios.ts on macOS: `tauri ios init` once, icons, then `tauri ios build --debug`
|
||||
*/
|
||||
import { existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { SRC_TAURI, tauri } from './tauri.js';
|
||||
|
||||
if (process.platform !== 'darwin') {
|
||||
console.error(
|
||||
'ios: the iOS app can only be built on macOS with Xcode (and an Apple developer account to run it on a phone).\n' +
|
||||
`ios: this machine is ${process.platform}. Nothing was built. See .agents/features/tauri-platforms.md, G-T1.`
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
if (!existsSync(join(SRC_TAURI, 'gen', 'apple'))) tauri('ios', 'init', '--ci');
|
||||
await import('./icons.js');
|
||||
tauri('ios', 'build', '--debug', ...process.argv.slice(2));
|
||||
@@ -0,0 +1,19 @@
|
||||
/** Runs the Tauri CLI of this package, in this package's folder, and stops the script if it fails. */
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
export const PACKAGE = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
export const SRC_TAURI = join(PACKAGE, 'src-tauri');
|
||||
|
||||
export function tauri(...args: string[]): void {
|
||||
const run = spawnSync('pnpm', ['exec', 'tauri', ...args], {
|
||||
cwd: PACKAGE,
|
||||
stdio: 'inherit',
|
||||
shell: process.platform === 'win32'
|
||||
});
|
||||
if (run.status !== 0) {
|
||||
console.error(`tauri ${args.join(' ')} failed (exit ${String(run.status ?? run.signal)})`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
Generated
+4521
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,27 @@
|
||||
[package]
|
||||
name = "rosea-shell"
|
||||
version = "0.1.0"
|
||||
description = "The Tauri 2 shell of Rosea Domi: a window around the built game, and nothing else."
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
[lib]
|
||||
# The `_lib` suffix avoids a clash between the lib and the bin on Windows (cargo#8519).
|
||||
name = "rosea_shell_lib"
|
||||
crate-type = ["staticlib", "cdylib", "rlib"]
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2.7.5", features = [] }
|
||||
|
||||
# No Tauri plugin and no other crate: the shell opens a window on the built game and does
|
||||
# nothing else. Each plugin that arrives later (notifications, Phase 6) is reviewed for
|
||||
# network access first (.agents/features/tauri-platforms.md D5).
|
||||
[dependencies]
|
||||
tauri = { version = "2.12.6", features = [] }
|
||||
|
||||
[profile.release]
|
||||
codegen-units = 1
|
||||
lto = true
|
||||
opt-level = "s"
|
||||
panic = "abort"
|
||||
strip = true
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() {
|
||||
tauri_build::build()
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
//! The Tauri 2 shell of Rosea Domi (CLAUDE.md §2, *Four versions*).
|
||||
//!
|
||||
//! A window on the built game (`apps/rosea/dist-tauri/`) and nothing else: no command, no
|
||||
//! plugin, no file of its own. The game keeps everything in the webview's IndexedDB, exactly
|
||||
//! as in the PWA. `capabilities/` is absent on purpose, so the page is granted no IPC at all.
|
||||
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
pub fn run() {
|
||||
tauri::Builder::default()
|
||||
.run(tauri::generate_context!())
|
||||
// Nothing to recover from here: without a window there is no garden to show.
|
||||
.expect("Rosea Domi could not open its window");
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// No console window behind the garden in a release build on Windows.
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
fn main() {
|
||||
rosea_shell_lib::run()
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"build": {
|
||||
"beforeBuildCommand": "pnpm --filter @rosea/tauri android:privacy && pnpm --filter @rosea/app build:shell"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Rosea Domi",
|
||||
"version": "../../rosea/package.json",
|
||||
"identifier": "cz.mareknovak.domi.rosea",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm --filter @rosea/app dev:shell",
|
||||
"devUrl": "http://127.0.0.1:5173",
|
||||
"beforeBuildCommand": "pnpm --filter @rosea/app build:shell",
|
||||
"frontendDist": "../../rosea/dist-tauri"
|
||||
},
|
||||
"app": {
|
||||
"windows": [
|
||||
{
|
||||
"label": "main",
|
||||
"title": "Rosea Domi",
|
||||
"width": 480,
|
||||
"height": 800,
|
||||
"minWidth": 320,
|
||||
"minHeight": 480,
|
||||
"useHttpsScheme": true,
|
||||
"additionalBrowserArgs": "--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection,DnsOverHttpsUpgrade,DohProviderGoogle,DohProviderGoogleDns,DohProviderCloudflare,msExperimentationAndConfigurationService,OptimizationHints,AutofillServerCommunication,MediaRouter,Translate --disable-background-networking --disable-component-update --disable-domain-reliability --disable-sync --no-pings --disable-client-side-phishing-detection --dns-prefetch-disable"
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; manifest-src 'self'; worker-src 'self'; object-src 'none'; base-uri 'self'; form-action 'none'"
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"icon": ["icons/32x32.png", "icons/128x128.png", "icons/128x128@2x.png", "icons/icon.icns", "icons/icon.ico"],
|
||||
"category": "Game",
|
||||
"shortDescription": "A rose to tend, a fox to befriend, and the time we give to people.",
|
||||
"windows": { "nsis": { "installMode": "currentUser" } }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{ "$schema": "https://schema.tauri.app/config/2", "bundle": { "targets": ["deb", "appimage"] } }
|
||||
@@ -0,0 +1 @@
|
||||
{ "$schema": "https://schema.tauri.app/config/2", "bundle": { "targets": ["app", "dmg"] } }
|
||||
@@ -0,0 +1 @@
|
||||
{ "$schema": "https://schema.tauri.app/config/2", "bundle": { "targets": ["nsis"] } }
|
||||
@@ -0,0 +1,176 @@
|
||||
/**
|
||||
* 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 asked = [...permissions.matchAll(/uses-permission: name='([^']+)'/g)].map((m) => m[1]!);
|
||||
// Tauri's stock app asks for nothing else today; a new one is a review question, not a pass.
|
||||
const allowed = new Set<string>([]);
|
||||
for (const name of asked) {
|
||||
if (name.endsWith('.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION')) continue; // androidx's own, signature-level
|
||||
if (!allowed.has(name)) problems.push(`the APK asks for ${name}`);
|
||||
}
|
||||
if (!/allowBackup\([^)]*\)=false/.test(manifestTree)) problems.push('the APK does not set allowBackup=false');
|
||||
for (const [name, value] of Object.entries(META_DATA)) {
|
||||
const at = manifestTree.indexOf(`"${name}"`);
|
||||
if (at < 0) problems.push(`the APK has no meta-data ${name}`);
|
||||
else if (!manifestTree.slice(at, at + 300).includes(value === 'true' ? '=true' : '=false') &&
|
||||
!manifestTree.slice(at, at + 300).includes(`"${value}"`)) {
|
||||
problems.push(`the APK's meta-data ${name} is not ${value}`);
|
||||
}
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* The Android privacy patch (tauri-platforms.md D6), on Tauri 2.12.5's stock manifest exactly as
|
||||
* `tauri android init` wrote it (fixtures/AndroidManifest.stock.xml), and on the committed rule files.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
APPLICATION_ATTRS,
|
||||
DOMAINS,
|
||||
manifestProblems,
|
||||
META_DATA,
|
||||
patchManifest,
|
||||
RULE_FILES,
|
||||
RULE_SECTIONS,
|
||||
ruleProblems
|
||||
} from '../src/android-privacy.js';
|
||||
|
||||
const HERE = dirname(fileURLToPath(import.meta.url));
|
||||
const STOCK = readFileSync(join(HERE, 'fixtures', 'AndroidManifest.stock.xml'), 'utf8').replaceAll('\r\n', '\n');
|
||||
const rules = (f: string): string => readFileSync(join(HERE, '..', 'android', 'res', 'xml', f), 'utf8');
|
||||
|
||||
describe('patchManifest', () => {
|
||||
const patched = patchManifest(STOCK);
|
||||
|
||||
it("removes Tauri's INTERNET permission: the kernel then refuses the app any socket", () => {
|
||||
expect(STOCK).toContain('android.permission.INTERNET');
|
||||
expect(patched).not.toContain('android.permission.INTERNET');
|
||||
});
|
||||
|
||||
it('turns backup and device transfer off on <application>', () => {
|
||||
const tag = /<application\b[^>]*>/.exec(patched)?.[0] ?? '';
|
||||
for (const [name, value] of Object.entries(APPLICATION_ATTRS)) expect(tag).toContain(`${name}="${value}"`);
|
||||
// What Tauri set is kept.
|
||||
expect(tag).toContain('android:icon="@mipmap/ic_launcher"');
|
||||
expect(tag).toContain('android:usesCleartextTraffic="${usesCleartextTraffic}"');
|
||||
});
|
||||
|
||||
it("switches the WebView's metrics and Safe Browsing off, inside <application>", () => {
|
||||
const inside = /<application\b[\s\S]*<\/application>/.exec(patched)?.[0] ?? '';
|
||||
for (const [name, value] of Object.entries(META_DATA)) {
|
||||
expect(inside).toContain(`<meta-data android:name="${name}" android:value="${value}" />`);
|
||||
}
|
||||
});
|
||||
|
||||
it('leaves the rest of the manifest as it was', () => {
|
||||
for (const keep of ['android:name=".MainActivity"', 'android.intent.category.LAUNCHER', 'androidx.core.content.FileProvider']) {
|
||||
expect(patched).toContain(keep);
|
||||
}
|
||||
});
|
||||
|
||||
it('changes nothing on a second run', () => {
|
||||
expect(patchManifest(patched)).toBe(patched);
|
||||
});
|
||||
|
||||
it('keeps Windows line endings when the file has them', () => {
|
||||
const crlf = patchManifest(STOCK.replaceAll('\n', '\r\n'));
|
||||
expect(crlf).toBe(patched.replaceAll('\n', '\r\n'));
|
||||
});
|
||||
|
||||
it('overwrites an allowBackup="true" rather than adding a second one', () => {
|
||||
const on = STOCK.replace('<application', '<application android:allowBackup="true"');
|
||||
const out = patchManifest(on);
|
||||
expect(out).toContain('android:allowBackup="false"');
|
||||
expect(out).not.toContain('android:allowBackup="true"');
|
||||
expect(out.match(/android:allowBackup=/g)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('refuses a manifest whose shape it does not know, rather than guessing', () => {
|
||||
expect(() => patchManifest(STOCK.replace('</application>', '</application><application></application>'))).toThrow(/application/);
|
||||
expect(() => patchManifest(STOCK.replace(/<application[\s\S]*<\/application>/, '<application />'))).toThrow();
|
||||
// INTERNET asked for in a form the line pattern does not match.
|
||||
const odd = STOCK.replace(
|
||||
'<uses-permission android:name="android.permission.INTERNET" />',
|
||||
'<uses-permission android:name="android.permission.INTERNET" android:maxSdkVersion="99" />'
|
||||
);
|
||||
expect(() => patchManifest(odd)).toThrow(/INTERNET/);
|
||||
});
|
||||
|
||||
it('removes INTERNET written over two lines too', () => {
|
||||
const split = STOCK.replace(
|
||||
'<uses-permission android:name="android.permission.INTERNET" />',
|
||||
'<uses-permission\n android:name="android.permission.INTERNET" />'
|
||||
);
|
||||
expect(patchManifest(split)).not.toContain('INTERNET');
|
||||
});
|
||||
});
|
||||
|
||||
describe('manifestProblems', () => {
|
||||
it("names everything missing from Tauri's stock manifest", () => {
|
||||
const problems = manifestProblems(STOCK);
|
||||
expect(problems).toContain('android.permission.INTERNET is requested');
|
||||
for (const name of Object.keys(APPLICATION_ATTRS)) expect(problems.join('\n')).toContain(name);
|
||||
for (const name of Object.keys(META_DATA)) expect(problems.join('\n')).toContain(name);
|
||||
expect(problems).toHaveLength(1 + Object.keys(APPLICATION_ATTRS).length + Object.keys(META_DATA).length);
|
||||
});
|
||||
|
||||
it('finds nothing missing once patched', () => {
|
||||
expect(manifestProblems(patchManifest(STOCK))).toEqual([]);
|
||||
});
|
||||
|
||||
it('notices a single switch turned back on', () => {
|
||||
const patched = patchManifest(STOCK);
|
||||
expect(manifestProblems(patched.replace('android:allowBackup="false"', 'android:allowBackup="true"'))).toEqual([
|
||||
'<application> lacks android:allowBackup="false"'
|
||||
]);
|
||||
expect(manifestProblems(patched.replace('android:value="true"', 'android:value="false"'))).toEqual([
|
||||
'no meta-data android.webkit.WebView.MetricsOptOut=true'
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the committed rule files', () => {
|
||||
for (const f of RULE_FILES) {
|
||||
it(`${f} excludes every domain, in every section, and includes nothing`, () => {
|
||||
expect(ruleProblems(rules(f), RULE_SECTIONS[f])).toEqual([]);
|
||||
});
|
||||
}
|
||||
|
||||
it('a file that forgets one domain is caught, by name', () => {
|
||||
const f = 'rosea_data_extraction_rules.xml' as const;
|
||||
const text = rules(f);
|
||||
const firstDb = text.indexOf('<exclude domain="database" path="." />');
|
||||
const broken = text.slice(0, firstDb) + text.slice(firstDb + '<exclude domain="database" path="." />'.length);
|
||||
expect(ruleProblems(broken, RULE_SECTIONS[f])).toEqual(['cloud-backup: database is not excluded']);
|
||||
});
|
||||
|
||||
it('a file that includes something is caught', () => {
|
||||
const f = 'rosea_backup_rules.xml' as const;
|
||||
const broken = rules(f).replace('</full-backup-content>', '<include domain="file" path="." />\n</full-backup-content>');
|
||||
expect(ruleProblems(broken, RULE_SECTIONS[f])).toEqual(['includes something']);
|
||||
});
|
||||
|
||||
it('knows all nine storage domains', () => {
|
||||
expect(DOMAINS).toHaveLength(9);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* The shell's configuration holds what tauri-platforms.md decided (D3–D7, D10, D11). Each of
|
||||
* these is a value that fails silently at runtime, or worse, only after a release: a changed
|
||||
* identifier or origin leaves the player's rose behind in the old app.
|
||||
*/
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { CSP } from '../../rosea/csp.js';
|
||||
import { PRODUCT_NAME } from '../../../packages/schema/src/constants.js';
|
||||
|
||||
const SRC_TAURI = join(dirname(fileURLToPath(import.meta.url)), '..', 'src-tauri');
|
||||
/** The parts of a Tauri config these tests read. */
|
||||
interface TauriConf {
|
||||
productName?: string;
|
||||
identifier?: string;
|
||||
version?: string;
|
||||
build: { frontendDist: string; beforeBuildCommand: string; beforeDevCommand: string; devUrl: string };
|
||||
app: { windows: Record<string, unknown>[]; security: Record<string, unknown> };
|
||||
bundle: { targets?: string[] };
|
||||
plugins?: unknown;
|
||||
}
|
||||
const json = (name: string): TauriConf => JSON.parse(readFileSync(join(SRC_TAURI, name), 'utf8')) as TauriConf;
|
||||
const conf = json('tauri.conf.json');
|
||||
const window = conf.app.windows[0] ?? {};
|
||||
|
||||
describe('tauri.conf.json', () => {
|
||||
it('names the app with the product name, in the bundle and the window title (D3)', () => {
|
||||
expect(conf.productName).toBe(PRODUCT_NAME);
|
||||
expect(window['title']).toBe(PRODUCT_NAME);
|
||||
});
|
||||
|
||||
it('keeps the identifier it was released with: a new one is a different app (D3)', () => {
|
||||
expect(conf.identifier).toBe('cz.mareknovak.domi.rosea');
|
||||
});
|
||||
|
||||
it("reads its version from the game's package.json (D3)", () => {
|
||||
expect(conf.version).toBe('../../rosea/package.json');
|
||||
const pkg = JSON.parse(readFileSync(resolve(SRC_TAURI, String(conf.version)), 'utf8')) as Record<string, string>;
|
||||
expect(pkg['name']).toBe('@rosea/app');
|
||||
expect(pkg['version']).toMatch(/^\d+\.\d+\.\d+$/);
|
||||
});
|
||||
|
||||
it("delivers the PWA's content-security policy, the same string (D4)", () => {
|
||||
expect(conf.app.security['csp']).toBe(CSP);
|
||||
});
|
||||
|
||||
it("wraps the game's shell build and nothing else (D1, D2)", () => {
|
||||
expect(conf.build.frontendDist).toBe('../../rosea/dist-tauri');
|
||||
expect(resolve(SRC_TAURI, conf.build.frontendDist)).toBe(resolve(SRC_TAURI, '..', '..', 'rosea', 'dist-tauri'));
|
||||
expect(conf.build.beforeBuildCommand).toBe('pnpm --filter @rosea/app build:shell');
|
||||
expect(conf.build.beforeDevCommand).toBe('pnpm --filter @rosea/app dev:shell');
|
||||
});
|
||||
|
||||
it('runs its dev server on 127.0.0.1 only (CLAUDE.md §5.7)', () => {
|
||||
expect(new URL(conf.build.devUrl).hostname).toBe('127.0.0.1');
|
||||
const app = JSON.parse(readFileSync(join(SRC_TAURI, '..', '..', 'rosea', 'package.json'), 'utf8')) as { scripts: Record<string, string> };
|
||||
expect(app['scripts']['dev:shell']).toContain('--host 127.0.0.1');
|
||||
expect(app['scripts']['dev:shell']).toContain('--port 5173');
|
||||
expect(conf.build.devUrl).toBe('http://127.0.0.1:5173');
|
||||
});
|
||||
|
||||
it('keeps the https origin it was released with: IndexedDB lives per origin (D10)', () => {
|
||||
expect(window['useHttpsScheme']).toBe(true);
|
||||
});
|
||||
|
||||
it("switches WebView2's own traffic off (D7)", () => {
|
||||
const args = String(window['additionalBrowserArgs']);
|
||||
for (const flag of [
|
||||
'--disable-background-networking',
|
||||
'--disable-component-update',
|
||||
'--disable-domain-reliability',
|
||||
'--disable-sync',
|
||||
'--no-pings',
|
||||
'--disable-client-side-phishing-detection',
|
||||
'--dns-prefetch-disable'
|
||||
]) {
|
||||
expect(args.split(' ')).toContain(flag);
|
||||
}
|
||||
const disabled = /--disable-features=(\S+)/.exec(args)?.[1]?.split(',') ?? [];
|
||||
for (const feature of [
|
||||
// Tauri's own defaults, which a custom list must repeat.
|
||||
'msWebOOUI', 'msPdfOOUI', 'msSmartScreenProtection',
|
||||
'DnsOverHttpsUpgrade', 'msExperimentationAndConfigurationService', 'AutofillServerCommunication', 'OptimizationHints'
|
||||
]) {
|
||||
expect(disabled).toContain(feature);
|
||||
}
|
||||
});
|
||||
|
||||
it('builds only what each system can make (D11)', () => {
|
||||
expect(json('tauri.windows.conf.json').bundle.targets).toEqual(['nsis']);
|
||||
expect(json('tauri.macos.conf.json').bundle.targets).toEqual(['app', 'dmg']);
|
||||
expect(json('tauri.linux.conf.json').bundle.targets).toEqual(['deb', 'appimage']);
|
||||
expect(conf.bundle.targets).toBeUndefined();
|
||||
});
|
||||
|
||||
it('applies the Android privacy patch before the game is built for Android (D6)', () => {
|
||||
const before = json('tauri.android.conf.json').build.beforeBuildCommand;
|
||||
const patch = before.indexOf('pnpm --filter @rosea/tauri android:privacy');
|
||||
expect(patch).toBe(0);
|
||||
expect(before.indexOf('&& pnpm --filter @rosea/app build:shell')).toBeGreaterThan(patch);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the Rust side (D5)', () => {
|
||||
it('depends on tauri alone: no plugin, no SDK', () => {
|
||||
const cargo = readFileSync(join(SRC_TAURI, 'Cargo.toml'), 'utf8');
|
||||
const deps = /\n\[dependencies\]\n([\s\S]*?)(?:\n\[|$)/.exec(cargo)?.[1] ?? '';
|
||||
const names = deps
|
||||
.split('\n')
|
||||
.map((l) => /^([A-Za-z0-9_-]+)\s*=/.exec(l)?.[1])
|
||||
.filter((n): n is string => n !== undefined);
|
||||
expect(names).toEqual(['tauri']);
|
||||
expect(cargo).not.toMatch(/\[target\.[^\]]*dependencies\]/);
|
||||
});
|
||||
|
||||
it('grants the page no IPC: there is no capabilities folder', () => {
|
||||
expect(existsSync(join(SRC_TAURI, 'capabilities'))).toBe(false);
|
||||
expect(conf.app.security['capabilities']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('declares no plugin configuration', () => {
|
||||
expect(conf.plugins).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
|
||||
<!-- AndroidTV support -->
|
||||
<uses-feature android:name="android.software.leanback" android:required="false" />
|
||||
|
||||
<application
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:theme="@style/Theme.rosea_shell"
|
||||
android:usesCleartextTraffic="${usesCleartextTraffic}">
|
||||
<activity
|
||||
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode"
|
||||
android:launchMode="singleTask"
|
||||
android:label="@string/main_activity_title"
|
||||
android:name=".MainActivity"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
<!-- AndroidTV support -->
|
||||
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="${applicationId}.fileprovider"
|
||||
android:exported="false"
|
||||
android:grantUriPermissions="true">
|
||||
<meta-data
|
||||
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||
android:resource="@xml/file_paths" />
|
||||
</provider>
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* The game's build for the shell (`vite build --mode tauri`, tauri-platforms.md D2), made into a
|
||||
* temporary folder and read: no service worker, no manifest, no <meta> policy, assets at the root,
|
||||
* and the shell constant replaced. The PWA's own build is checked by the e2e suites.
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
|
||||
const APP = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'rosea');
|
||||
let out = '';
|
||||
let html = '';
|
||||
let files: string[] = [];
|
||||
let scripts = '';
|
||||
|
||||
beforeAll(() => {
|
||||
out = mkdtempSync(join(tmpdir(), 'rosea-shell-build-'));
|
||||
const build = spawnSync('pnpm', ['exec', 'vite', 'build', '--mode', 'tauri', '--outDir', out, '--emptyOutDir', '--logLevel', 'error'], {
|
||||
cwd: APP,
|
||||
encoding: 'utf8',
|
||||
shell: process.platform === 'win32'
|
||||
});
|
||||
if (build.status !== 0) throw new Error(`vite build --mode tauri failed:\n${build.stdout}\n${build.stderr}`);
|
||||
files = readdirSync(out, { recursive: true, encoding: 'utf8' }).map((f) => f.replaceAll('\\', '/'));
|
||||
html = readFileSync(join(out, 'index.html'), 'utf8');
|
||||
scripts = files.filter((f) => f.endsWith('.js')).map((f) => readFileSync(join(out, f), 'utf8')).join('\n');
|
||||
}, 120_000);
|
||||
|
||||
afterAll(() => {
|
||||
if (out) rmSync(out, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('the game built for the shell', () => {
|
||||
it('has no service worker and no web manifest', () => {
|
||||
expect(files.filter((f) => /(^|\/)(sw|workbox-[^/]*|registerSW)\.js$/.test(f))).toEqual([]);
|
||||
expect(files.filter((f) => f.endsWith('.webmanifest'))).toEqual([]);
|
||||
expect(html).not.toContain('manifest');
|
||||
expect(scripts).not.toContain('navigator.serviceWorker.register');
|
||||
});
|
||||
|
||||
it('carries no <meta> content-security policy: Tauri delivers it (D4)', () => {
|
||||
expect(html).not.toContain('Content-Security-Policy');
|
||||
});
|
||||
|
||||
it('loads its assets from the root of the origin, not /Rosea/', () => {
|
||||
const urls = [...html.matchAll(/(?:src|href)="([^"]+)"/g)].map((m) => m[1]!);
|
||||
const assets = urls.filter((u) => u.includes('assets/'));
|
||||
expect(assets.length).toBeGreaterThanOrEqual(2);
|
||||
for (const u of assets) expect(u.startsWith('/assets/')).toBe(true);
|
||||
expect(html).not.toContain('/Rosea/');
|
||||
});
|
||||
|
||||
it('replaces the shell constant at build time: left in, it would throw in the webview', () => {
|
||||
expect(scripts).not.toContain('__ROSEA_SHELL__');
|
||||
});
|
||||
|
||||
it('ships no source maps', () => {
|
||||
expect(files.filter((f) => f.endsWith('.map'))).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts", "scripts/**/*.ts", "test/**/*.ts"]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* The content-security policy, one string for all four versions (CLAUDE.md §2, *Four versions*).
|
||||
* The PWA carries it in a <meta> tag, because GitHub Pages cannot send headers (CLAUDE.md §8).
|
||||
* The Tauri shell delivers it from `apps/rosea-tauri/src-tauri/tauri.conf.json`
|
||||
* (`app.security.csp`), and the shell's test holds that string equal to this one
|
||||
* (tauri-platforms.md D4).
|
||||
*
|
||||
* `'self'` everywhere and nothing else: no CDN, no font host, no analytics (CLAUDE.md §4).
|
||||
* `frame-ancestors` is ignored in a meta tag and is omitted rather than pretended.
|
||||
*/
|
||||
export const CSP = [
|
||||
"default-src 'self'",
|
||||
"script-src 'self'",
|
||||
"style-src 'self'",
|
||||
"img-src 'self' data:",
|
||||
"font-src 'self'",
|
||||
"connect-src 'self'",
|
||||
"manifest-src 'self'",
|
||||
"worker-src 'self'",
|
||||
"object-src 'none'",
|
||||
"base-uri 'self'",
|
||||
"form-action 'none'"
|
||||
].join('; ');
|
||||
@@ -7,6 +7,8 @@
|
||||
"scripts": {
|
||||
"dev": "vite --host 127.0.0.1 --port 5173 --strictPort",
|
||||
"build": "tsx ../../scripts/validate-library.ts && vite build",
|
||||
"build:shell": "tsx ../../scripts/validate-library.ts && vite build --mode tauri",
|
||||
"dev:shell": "vite --mode tauri --host 127.0.0.1 --port 5173 --strictPort",
|
||||
"typecheck": "svelte-check --threshold error --output human"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -59,8 +59,14 @@
|
||||
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 =>
|
||||
matchMedia('(display-mode: standalone)').matches || (navigator as Navigator & { standalone?: boolean }).standalone === true;
|
||||
inApp ||
|
||||
matchMedia('(display-mode: standalone)').matches ||
|
||||
(navigator as Navigator & { standalone?: boolean }).standalone === true;
|
||||
// An installed app is asked once, after the first care of a visit: by then there is
|
||||
// something to lose, and installed apps are not met with a permission prompt (K5).
|
||||
let askedToKeep = false;
|
||||
@@ -82,7 +88,8 @@
|
||||
|
||||
// --- A new version waiting (calm-refresh.md) ----------------------------
|
||||
// The worker is registered here so the page hears when a new version has installed
|
||||
// and waits. It is offered, never swapped in by itself (U2).
|
||||
// and waits. It is offered, never swapped in by itself (U2). In the apps there is no
|
||||
// worker: this registerSW does nothing, and a new version comes as a new app.
|
||||
let updateReady = $state(false);
|
||||
const updateSW = registerSW({
|
||||
onNeedRefresh: () => (updateReady = true),
|
||||
|
||||
Vendored
+6
@@ -2,6 +2,12 @@
|
||||
/// <reference types="vite/client" />
|
||||
/// <reference types="vite-plugin-pwa/client" />
|
||||
|
||||
/**
|
||||
* Which shell the game was built for (vite.config.ts): `'web'` for the PWA, `'tauri'` for the
|
||||
* Android, iOS and desktop apps. Read in App.svelte only, for wiring (CLAUDE.md §2).
|
||||
*/
|
||||
declare const __ROSEA_SHELL__: 'web' | 'tauri';
|
||||
|
||||
declare module 'virtual:rosea-library' {
|
||||
import type { HopeSentence } from '@rosea/schema';
|
||||
/** The verified hope library, bundled at build time after validate:library passed (day-sentence.md P5). */
|
||||
|
||||
+89
-82
@@ -9,6 +9,18 @@ import { VitePWA } from 'vite-plugin-pwa';
|
||||
// load a workspace package's .ts source, so `vite build` and `svelte-check` both
|
||||
// failed to load this file. The constants module is pure and dependency-free.
|
||||
import { PRODUCT_NAME, PRODUCT_SHORT_NAME } from '../../packages/schema/src/constants.js';
|
||||
import { CSP } from './csp.js';
|
||||
|
||||
/**
|
||||
* Two builds of one game (CLAUDE.md §2, *Four versions*; tauri-platforms.md D2).
|
||||
* - the PWA (default mode): base `/Rosea/`, a service worker, the web manifest, the CSP
|
||||
* in a <meta> tag, into `dist/`;
|
||||
* - the Tauri shell's copy (`--mode tauri`): base `/`, because Tauri serves the game at the
|
||||
* root of its own origin; no worker and no manifest, because the files are already on
|
||||
* the device; no <meta> CSP, because Tauri delivers the same policy and a page that
|
||||
* carries both obeys both; into `dist-tauri/`, so the two can never be mixed up.
|
||||
*/
|
||||
type Shell = 'web' | 'tauri';
|
||||
|
||||
/**
|
||||
* GitHub Pages serves a project site at `/<repo>/`, not `/` (CLAUDE.md §8). Vite
|
||||
@@ -16,45 +28,30 @@ import { PRODUCT_NAME, PRODUCT_SHORT_NAME } from '../../packages/schema/src/cons
|
||||
* derive from this one value, so they cannot disagree. The e2e and offline
|
||||
* suites serve the build under the same prefix.
|
||||
*/
|
||||
const BASE = process.env['ROSEA_BASE'] ?? '/Rosea/';
|
||||
if (!BASE.startsWith('/') || !BASE.endsWith('/')) {
|
||||
throw new Error(`ROSEA_BASE must start and end with '/', got '${BASE}'`);
|
||||
function baseFor(shell: Shell): string {
|
||||
const base = process.env['ROSEA_BASE'] ?? (shell === 'tauri' ? '/' : '/Rosea/');
|
||||
if (!base.startsWith('/') || !base.endsWith('/')) {
|
||||
throw new Error(`ROSEA_BASE must start and end with '/', got '${base}'`);
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
/**
|
||||
* The content-security policy. GitHub Pages cannot send headers, so it lives in
|
||||
* a <meta> tag (CLAUDE.md §8). It is injected into the BUILT page only, because
|
||||
* the dev server injects inline <style> for hot reload and `style-src 'self'`
|
||||
* The content-security policy (`csp.ts`). GitHub Pages cannot send headers, so the PWA
|
||||
* carries it in a <meta> tag (CLAUDE.md §8). It is injected into the BUILT page only,
|
||||
* because the dev server injects inline <style> for hot reload and `style-src 'self'`
|
||||
* would blank it. E2E runs against the build, where the policy is real.
|
||||
*
|
||||
* `'self'` everywhere and nothing else: no CDN, no font host, no analytics
|
||||
* (CLAUDE.md §4). `frame-ancestors` is ignored in a meta tag and is omitted
|
||||
* rather than pretended.
|
||||
*/
|
||||
const CSP = [
|
||||
"default-src 'self'",
|
||||
"script-src 'self'",
|
||||
"style-src 'self'",
|
||||
"img-src 'self' data:",
|
||||
"font-src 'self'",
|
||||
"connect-src 'self'",
|
||||
"manifest-src 'self'",
|
||||
"worker-src 'self'",
|
||||
"object-src 'none'",
|
||||
"base-uri 'self'",
|
||||
"form-action 'none'"
|
||||
].join('; ');
|
||||
|
||||
function contentSecurityPolicy(): Plugin {
|
||||
return {
|
||||
name: 'rosea-csp',
|
||||
apply: 'build',
|
||||
transformIndexHtml: {
|
||||
order: 'post',
|
||||
handler: () => [
|
||||
{ tag: 'meta', attrs: { 'http-equiv': 'Content-Security-Policy', content: CSP }, injectTo: 'head-prepend' }
|
||||
]
|
||||
}
|
||||
name: 'rosea-csp',
|
||||
apply: 'build',
|
||||
transformIndexHtml: {
|
||||
order: 'post',
|
||||
handler: () => [
|
||||
{ tag: 'meta', attrs: { 'http-equiv': 'Content-Security-Policy', content: CSP }, injectTo: 'head-prepend' }
|
||||
]
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -89,54 +86,64 @@ function hopeLibrary(): Plugin {
|
||||
}
|
||||
|
||||
// Nothing binds to anything but 127.0.0.1 (CLAUDE.md §5.7).
|
||||
export default defineConfig({
|
||||
base: BASE,
|
||||
plugins: [
|
||||
svelte(),
|
||||
contentSecurityPolicy(),
|
||||
hopeLibrary(),
|
||||
VitePWA({
|
||||
strategies: 'generateSW',
|
||||
// Never swap a running app silently. A new worker waits until the player
|
||||
// is offered a calm refresh control (CLAUDE.md §8, GAP_ANALYSIS G0.10).
|
||||
registerType: 'prompt',
|
||||
// The app registers the worker itself through virtual:pwa-register, so it hears
|
||||
// when a new version is waiting (calm-refresh.md U1). Bundled, not inline: the
|
||||
// CSP has no 'unsafe-inline' for scripts.
|
||||
injectRegister: false,
|
||||
manifest: {
|
||||
// The web manifest: one of the three places the name lives, built from
|
||||
// the constants in @rosea/schema so the strings exist only there.
|
||||
name: PRODUCT_NAME,
|
||||
short_name: PRODUCT_SHORT_NAME,
|
||||
description: 'A rose to tend, a fox to befriend, and the time we give to people.',
|
||||
id: BASE,
|
||||
start_url: BASE,
|
||||
scope: BASE,
|
||||
display: 'standalone',
|
||||
orientation: 'portrait',
|
||||
background_color: '#fbf6f1',
|
||||
theme_color: '#b4485e',
|
||||
icons: [{ src: 'icon.svg', sizes: 'any', type: 'image/svg+xml', purpose: 'any' }]
|
||||
},
|
||||
workbox: {
|
||||
// The cache name never contains the build hash; Workbox invalidates
|
||||
// per entry from the precache manifest's revisions.
|
||||
cacheId: 'rosea',
|
||||
globPatterns: ['**/*.{js,css,html,svg,webmanifest}'],
|
||||
navigateFallback: 'index.html',
|
||||
// No runtime caching: the app makes no request it was not asked to make.
|
||||
runtimeCaching: [],
|
||||
cleanupOutdatedCaches: true,
|
||||
// The first worker controls the page that registered it, so a player who
|
||||
// opens the link once and loses signal still has the app.
|
||||
clientsClaim: true,
|
||||
skipWaiting: false
|
||||
},
|
||||
devOptions: { enabled: false }
|
||||
})
|
||||
],
|
||||
server: { host: '127.0.0.1', strictPort: true },
|
||||
preview: { host: '127.0.0.1', strictPort: true },
|
||||
build: { target: 'es2022', sourcemap: true }
|
||||
export default defineConfig(({ mode }) => {
|
||||
const shell: Shell = mode === 'tauri' ? 'tauri' : 'web';
|
||||
const BASE = baseFor(shell);
|
||||
return {
|
||||
base: BASE,
|
||||
// The one way the game knows which shell it is in, read in App.svelte only (CLAUDE.md §2).
|
||||
define: { __ROSEA_SHELL__: JSON.stringify(shell) },
|
||||
plugins: [
|
||||
svelte(),
|
||||
...(shell === 'web' ? [contentSecurityPolicy()] : []),
|
||||
hopeLibrary(),
|
||||
VitePWA({
|
||||
// Off in the shell: `virtual:pwa-register` then gives a registerSW that does nothing,
|
||||
// and no worker, manifest or register script is emitted (tauri-platforms.md D2).
|
||||
disable: shell === 'tauri',
|
||||
strategies: 'generateSW',
|
||||
// Never swap a running app silently. A new worker waits until the player
|
||||
// is offered a calm refresh control (CLAUDE.md §8, GAP_ANALYSIS G0.10).
|
||||
registerType: 'prompt',
|
||||
// The app registers the worker itself through virtual:pwa-register, so it hears
|
||||
// when a new version is waiting (calm-refresh.md U1). Bundled, not inline: the
|
||||
// CSP has no 'unsafe-inline' for scripts.
|
||||
injectRegister: false,
|
||||
manifest: {
|
||||
// The web manifest: one of the three places the name lives, built from
|
||||
// the constants in @rosea/schema so the strings exist only there.
|
||||
name: PRODUCT_NAME,
|
||||
short_name: PRODUCT_SHORT_NAME,
|
||||
description: 'A rose to tend, a fox to befriend, and the time we give to people.',
|
||||
id: BASE,
|
||||
start_url: BASE,
|
||||
scope: BASE,
|
||||
display: 'standalone',
|
||||
orientation: 'portrait',
|
||||
background_color: '#fbf6f1',
|
||||
theme_color: '#b4485e',
|
||||
icons: [{ src: 'icon.svg', sizes: 'any', type: 'image/svg+xml', purpose: 'any' }]
|
||||
},
|
||||
workbox: {
|
||||
// The cache name never contains the build hash; Workbox invalidates
|
||||
// per entry from the precache manifest's revisions.
|
||||
cacheId: 'rosea',
|
||||
globPatterns: ['**/*.{js,css,html,svg,webmanifest}'],
|
||||
navigateFallback: 'index.html',
|
||||
// No runtime caching: the app makes no request it was not asked to make.
|
||||
runtimeCaching: [],
|
||||
cleanupOutdatedCaches: true,
|
||||
// The first worker controls the page that registered it, so a player who
|
||||
// opens the link once and loses signal still has the app.
|
||||
clientsClaim: true,
|
||||
skipWaiting: false
|
||||
},
|
||||
devOptions: { enabled: false }
|
||||
})
|
||||
],
|
||||
server: { host: '127.0.0.1', strictPort: true },
|
||||
preview: { host: '127.0.0.1', strictPort: true },
|
||||
// The shell's copy has no source maps: they would ship inside every installer and APK.
|
||||
build: { target: 'es2022', sourcemap: shell === 'web', outDir: shell === 'tauri' ? 'dist-tauri' : 'dist' }
|
||||
};
|
||||
});
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
/**
|
||||
* The garden in a BUILT app, on a real machine or device (tauri-platforms.md §5): it opens,
|
||||
* she is watered, the app is closed and opened again, and she is still watered. Also measured
|
||||
* on the way: the origin, that there is no service worker, what `persisted()` answers, that no
|
||||
* request leaves the origin and no CSP violation is reported, and what *Save her to a file* does.
|
||||
*
|
||||
* tsx e2e/apps/check-garden.ts desktop [path-to-exe]
|
||||
* tsx e2e/apps/check-garden.ts android [device-serial]
|
||||
*
|
||||
* Desktop: runs the release `.exe` with its WebView2 data in a fresh temporary folder (never the
|
||||
* player's own) and its DevTools port on 127.0.0.1 only (CLAUDE.md §5.7), through WebView2's own
|
||||
* environment variables. Those replace the app's `additionalBrowserArgs` for this run, so this
|
||||
* check says nothing about WebView2's own traffic (G-T6).
|
||||
* Android: the installed debug APK (`adb install -r`), driven through Playwright's Android support
|
||||
* over adb; its data is cleared first with `pm clear` (it is the test app, not a player's).
|
||||
* Every app it starts is stopped in `finally`.
|
||||
*/
|
||||
import { expect, _android as android, chromium, type Page } from '@playwright/test';
|
||||
import { PRODUCT_NAME } from '@rosea/schema';
|
||||
import { en } from '@rosea/ui/copy';
|
||||
import { spawn, spawnSync, type ChildProcess } from 'node:child_process';
|
||||
import { existsSync, mkdtempSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { storedCare } from '../stored.js';
|
||||
|
||||
const PACKAGE_ID = 'cz.mareknovak.domi.rosea';
|
||||
const report: Record<string, unknown> = {};
|
||||
|
||||
/** Requests that leave the game's origin, and CSP violations, from now on. */
|
||||
function watch(page: Page): { outside: string[]; csp: string[]; errors: string[] } {
|
||||
const seen = { outside: [] as string[], csp: [] as string[], errors: [] as string[] };
|
||||
const origin = new URL(page.url()).origin;
|
||||
page.on('request', (r) => {
|
||||
const url = r.url();
|
||||
if (!url.startsWith(origin + '/') && !url.startsWith('data:') && !url.startsWith('blob:')) seen.outside.push(url);
|
||||
});
|
||||
page.on('console', (m) => {
|
||||
if (m.type() !== 'error') return;
|
||||
if (/Content Security Policy/i.test(m.text())) seen.csp.push(m.text());
|
||||
else seen.errors.push(m.text());
|
||||
});
|
||||
return seen;
|
||||
}
|
||||
|
||||
async function garden(page: Page): Promise<void> {
|
||||
await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME, { timeout: 20_000 });
|
||||
}
|
||||
|
||||
/** The first visit: skip the town (no town is the private choice), water her, wait for the write. */
|
||||
async function firstVisit(page: Page): Promise<void> {
|
||||
await garden(page);
|
||||
const seen = watch(page);
|
||||
await page.reload();
|
||||
await garden(page);
|
||||
report['origin'] = await page.evaluate(() => location.origin);
|
||||
report['serviceWorkers'] = await page.evaluate(async () =>
|
||||
'serviceWorker' in navigator ? (await navigator.serviceWorker.getRegistrations()).length : 'no API'
|
||||
);
|
||||
report['manifestLink'] = await page.evaluate(() => document.querySelector('link[rel="manifest"]') !== null);
|
||||
report['cspMeta'] = await page.evaluate(() => document.querySelector('meta[http-equiv="Content-Security-Policy"]') !== null);
|
||||
|
||||
const skip = page.getByRole('button', { name: /^Not now/ });
|
||||
if (await skip.isVisible().catch(() => false)) await skip.click();
|
||||
|
||||
const water = page.getByRole('button', { name: en.rose.water });
|
||||
await expect(water).toBeVisible();
|
||||
const box = await water.boundingBox();
|
||||
if (!box) throw new Error('the Water button has no box');
|
||||
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.waitForTimeout(1500);
|
||||
await page.mouse.up();
|
||||
await expect(page.getByText(en.rose.says.thanks)).toBeVisible();
|
||||
await storedCare(page, 1);
|
||||
report['persistedAfterCare'] = await page.evaluate(async () => (navigator.storage?.persisted ? navigator.storage.persisted() : 'no API'));
|
||||
report['firstVisit'] = { outside: seen.outside, csp: seen.csp, errors: seen.errors };
|
||||
}
|
||||
|
||||
/** After the app was closed and opened again: she is still watered. */
|
||||
async function secondVisit(page: Page): Promise<void> {
|
||||
await garden(page);
|
||||
await page.getByRole('button', { name: en.rose.numbers }).click();
|
||||
await expect(page.locator('#rose-numbers')).toContainText(`${en.rose.daysOfCare}1`);
|
||||
await storedCare(page, 1);
|
||||
report['afterRestart'] = 'still watered: 1 day of care, the care log kept';
|
||||
}
|
||||
|
||||
/** What *Save her to a file* does here (G-T4): a download event, or nothing. */
|
||||
async function trySave(page: Page): Promise<void> {
|
||||
const title = page.getByRole('button', { name: en.rose.safe.title });
|
||||
if (!(await title.isVisible().catch(() => false))) {
|
||||
report['saveToFile'] = 'Keep her safe not visible';
|
||||
return;
|
||||
}
|
||||
await title.click();
|
||||
const save = page.getByRole('button', { name: en.rose.safe.save });
|
||||
await expect(save).toBeVisible();
|
||||
const download = page.waitForEvent('download', { timeout: 5_000 }).then(
|
||||
async (d) => {
|
||||
await d.cancel();
|
||||
return `a download started: ${d.suggestedFilename()} (cancelled by the check)`;
|
||||
},
|
||||
() => 'nothing happened within 5 s'
|
||||
);
|
||||
await save.click();
|
||||
report['saveToFile'] = await download;
|
||||
}
|
||||
|
||||
async function desktop(exe: string): Promise<void> {
|
||||
if (!existsSync(exe)) throw new Error(`no app at ${exe}; run pnpm tauri:build first`);
|
||||
const data = mkdtempSync(join(tmpdir(), 'rosea-desktop-check-'));
|
||||
const port = 9333;
|
||||
const env = {
|
||||
...process.env,
|
||||
WEBVIEW2_USER_DATA_FOLDER: data,
|
||||
WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS: `--remote-debugging-port=${port} --remote-debugging-address=127.0.0.1`
|
||||
};
|
||||
const start = (): ChildProcess => spawn(exe, [], { env, stdio: 'ignore' });
|
||||
const attach = async (): Promise<{ page: Page; close: () => Promise<void> }> => {
|
||||
for (let i = 0; i < 60; i++) {
|
||||
try {
|
||||
const browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`);
|
||||
for (let j = 0; j < 40; j++) {
|
||||
const page = browser.contexts().flatMap((c) => c.pages())[0];
|
||||
if (page) return { page, close: () => browser.close() };
|
||||
await new Promise((r) => setTimeout(r, 250));
|
||||
}
|
||||
await browser.close();
|
||||
} catch {
|
||||
// Not listening yet: the app is still starting. Tried again below; a real failure ends in the throw.
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 500));
|
||||
}
|
||||
throw new Error('the app never opened a page on the debugging port');
|
||||
};
|
||||
let app: ChildProcess | undefined;
|
||||
try {
|
||||
app = start();
|
||||
let session = await attach();
|
||||
await firstVisit(session.page);
|
||||
await session.close();
|
||||
app.kill();
|
||||
await new Promise((r) => setTimeout(r, 1500));
|
||||
|
||||
app = start();
|
||||
session = await attach();
|
||||
await secondVisit(session.page);
|
||||
await trySave(session.page);
|
||||
await session.close();
|
||||
report['dataFolder'] = data;
|
||||
} finally {
|
||||
app?.kill();
|
||||
await new Promise((r) => setTimeout(r, 1000));
|
||||
rmSync(data, { recursive: true, force: true, maxRetries: 5, retryDelay: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
async function androidDevice(serial: string | undefined): Promise<void> {
|
||||
const adb = (...args: string[]): string => {
|
||||
const r = spawnSync('adb', [...(serial ? ['-s', serial] : []), ...args], { encoding: 'utf8' });
|
||||
if (r.status !== 0) throw new Error(`adb ${args.join(' ')} failed: ${r.stderr}`);
|
||||
return r.stdout;
|
||||
};
|
||||
const devices = await android.devices();
|
||||
const device = serial ? devices.find((d) => d.serial() === serial) : devices[0];
|
||||
if (!device) throw new Error('no Android device over adb');
|
||||
report['device'] = `${device.model()} (${device.serial()})`;
|
||||
const dump = adb('shell', 'dumpsys', 'package', PACKAGE_ID);
|
||||
report['internetPermission'] = /android\.permission\.INTERNET/.test(dump);
|
||||
report['allowBackupFlag'] = /flags=\[[^\]]*ALLOW_BACKUP/.test(dump);
|
||||
try {
|
||||
adb('shell', 'pm', 'clear', PACKAGE_ID);
|
||||
adb('shell', 'monkey', '-p', PACKAGE_ID, '-c', 'android.intent.category.LAUNCHER', '1');
|
||||
let webView = await device.webView({ pkg: PACKAGE_ID }, { timeout: 30_000 });
|
||||
let page = await webView.page();
|
||||
await firstVisit(page);
|
||||
|
||||
adb('shell', 'am', 'force-stop', PACKAGE_ID);
|
||||
await new Promise((r) => setTimeout(r, 1500));
|
||||
adb('shell', 'monkey', '-p', PACKAGE_ID, '-c', 'android.intent.category.LAUNCHER', '1');
|
||||
webView = await device.webView({ pkg: PACKAGE_ID }, { timeout: 30_000 });
|
||||
page = await webView.page();
|
||||
await secondVisit(page);
|
||||
await trySave(page);
|
||||
} finally {
|
||||
adb('shell', 'am', 'force-stop', PACKAGE_ID);
|
||||
await device.close();
|
||||
}
|
||||
}
|
||||
|
||||
const [target, arg] = process.argv.slice(2);
|
||||
try {
|
||||
if (target === 'desktop') {
|
||||
await desktop(resolve(arg ?? 'apps/rosea-tauri/src-tauri/target/release/rosea-shell.exe'));
|
||||
} else if (target === 'android') {
|
||||
await androidDevice(arg);
|
||||
} else {
|
||||
throw new Error('usage: check-garden.ts desktop [exe] | android [serial]');
|
||||
}
|
||||
console.log(JSON.stringify(report, null, 2));
|
||||
console.log(`check-garden ${target}: PASSED`);
|
||||
} catch (error) {
|
||||
console.log(JSON.stringify(report, null, 2));
|
||||
console.error(`check-garden ${target}: FAILED — ${(error as Error).message}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
+6
-1
@@ -25,6 +25,9 @@ export default [
|
||||
{
|
||||
ignores: [
|
||||
'**/dist/**',
|
||||
'**/dist-tauri/**',
|
||||
'apps/rosea-tauri/src-tauri/gen/**',
|
||||
'apps/rosea-tauri/src-tauri/target/**',
|
||||
'**/node_modules/**',
|
||||
'**/.turbo/**',
|
||||
'**/generated/**',
|
||||
@@ -57,7 +60,9 @@ export default [
|
||||
files: ['**/*.svelte', '**/*.svelte.ts', '**/*.svelte.js'],
|
||||
languageOptions: {
|
||||
parser: svelteParser,
|
||||
parserOptions: { parser: ts.parser }
|
||||
parserOptions: { parser: ts.parser },
|
||||
// The build-time shell constant (apps/rosea/vite.config.ts), read in App.svelte only.
|
||||
globals: { __ROSEA_SHELL__: 'readonly' }
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
+5
-1
@@ -20,7 +20,11 @@
|
||||
"lint:copy": "tsx scripts/lint-copy.ts",
|
||||
"art:board": "tsx tools/art-prep/src/cli-board.ts",
|
||||
"art:accept": "tsx tools/art-prep/src/cli-accept.ts",
|
||||
"guard:cpu": "tsx tools/cpu-guard/src/cli.ts"
|
||||
"guard:cpu": "tsx tools/cpu-guard/src/cli.ts",
|
||||
"tauri:dev": "pnpm --filter @rosea/tauri dev",
|
||||
"tauri:build": "pnpm --filter @rosea/tauri build:desktop",
|
||||
"tauri:android": "pnpm --filter @rosea/tauri build:android",
|
||||
"tauri:ios": "pnpm --filter @rosea/tauri build:ios"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@axe-core/playwright": "4.13.0",
|
||||
|
||||
Generated
+136
@@ -103,6 +103,24 @@ importers:
|
||||
specifier: 7.4.1
|
||||
version: 7.4.1
|
||||
|
||||
apps/rosea-tauri:
|
||||
devDependencies:
|
||||
'@tauri-apps/cli':
|
||||
specifier: 2.12.5
|
||||
version: 2.12.5
|
||||
'@types/node':
|
||||
specifier: 22.20.1
|
||||
version: 22.20.1
|
||||
tsx:
|
||||
specifier: 4.23.12
|
||||
version: 4.23.12
|
||||
typescript:
|
||||
specifier: 5.9.3
|
||||
version: 5.9.3
|
||||
vitest:
|
||||
specifier: 3.2.7
|
||||
version: 3.2.7(@types/node@22.20.1)(jsdom@25.0.1)(terser@5.51.2)(tsx@4.23.12)
|
||||
|
||||
packages/content:
|
||||
dependencies:
|
||||
'@rosea/schema':
|
||||
@@ -1541,6 +1559,77 @@ packages:
|
||||
svelte: ^5.0.0
|
||||
vite: ^6.0.0
|
||||
|
||||
'@tauri-apps/cli-darwin-arm64@2.12.5':
|
||||
resolution: {integrity: sha512-VVvBRBdTFF7BP7RqGeItp9yDiyXj0DI1laRCEN2q6GLrNkw4wrHeWAxHp23PwtQtn/XET+yTN1jOKrq+Yor5PQ==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [darwin]
|
||||
|
||||
'@tauri-apps/cli-darwin-x64@2.12.5':
|
||||
resolution: {integrity: sha512-A84QYNj93kaG06N2mIFBRZM/X3lf9TyAVQeQwOmP2AJZ2wCt1WLDJgHRCvjeJmwJjJ5Ud0jUbIKbXg8NEGvsVQ==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
|
||||
'@tauri-apps/cli-linux-arm-gnueabihf@2.12.5':
|
||||
resolution: {integrity: sha512-tb/5xG5HV6CJR9AZBmTyI2GCi05vcH8XUjUIjBquAx7x+AE4f1vMWngvq7JW2AqYK8nNl79LJH1GR9Hf5QQc5g==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
|
||||
'@tauri-apps/cli-linux-arm64-gnu@2.12.5':
|
||||
resolution: {integrity: sha512-Vb7SlbIWlmIqekfsGYT64wH1cQNg5MET8XFyT6pUlVJ7Y/z6LsOIh4MUal0Z5FCPL83GMuEUNxpYUHpt36teHQ==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
|
||||
'@tauri-apps/cli-linux-arm64-musl@2.12.5':
|
||||
resolution: {integrity: sha512-b/YfVGueoTOtENQHY1STBF9XlU4uZDtOiMUErp2Nao/YrDWCKggjxxBZU3ycbeDWUYxl8U8M9seE4HYag1xjiQ==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
|
||||
'@tauri-apps/cli-linux-riscv64-gnu@2.12.5':
|
||||
resolution: {integrity: sha512-/EXbTfE9FM9GKSSRL9YTRHcMglTVNzbcwegXM0MBR3ozVgoE+pFq46Ej/InJBs1l+sjSpu6jyi38MZ+xyU/3NQ==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
|
||||
'@tauri-apps/cli-linux-x64-gnu@2.12.5':
|
||||
resolution: {integrity: sha512-OIun574QsULxaZ5SmPDX4D8bO95RBmYJshu8yGFy0RSyCMKEs/y+o3BThot4fbCv4ttC1Tq6Hzt0QRHXCIgp7w==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
|
||||
'@tauri-apps/cli-linux-x64-musl@2.12.5':
|
||||
resolution: {integrity: sha512-GDzWcb/6OzJrHnVGQ/n3XndLan67bZ7cu4zJN9+zFmV10nBgKz5jDDm8sRQO4sGb7bu6Ztiy+Al2XY2ptRY0RQ==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
|
||||
'@tauri-apps/cli-win32-arm64-msvc@2.12.5':
|
||||
resolution: {integrity: sha512-61KCX5vo0vex7P/P7sbXdfFhHqs+rFaG+UXK/UBwz/VlLveDx6vgpHkF+rfUIfCqj0VvLArpxR3+rQIzRwxKgw==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [win32]
|
||||
|
||||
'@tauri-apps/cli-win32-ia32-msvc@2.12.5':
|
||||
resolution: {integrity: sha512-mGujjR/MlXwJiQcue4wlXrBYlIEdDCoap0g+GNPlLCb75ilSbWMC8qTsXVuGcLIMumIJvc2v+veDnCHnels/Zg==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [ia32]
|
||||
os: [win32]
|
||||
|
||||
'@tauri-apps/cli-win32-x64-msvc@2.12.5':
|
||||
resolution: {integrity: sha512-o1+EOjvi/nFwKx5XamCXSr+GUr2ko8TH7+0wnWuZjE+lZwE+/VWCbE49HPHa3/V59M3bJ0dlK1yhogGQ15OVPg==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
|
||||
'@tauri-apps/cli@2.12.5':
|
||||
resolution: {integrity: sha512-Dm8s/4aiE52HsBh+Gz3uSrh+fEykRICA1VoAnQA80IqHoTRncPg+q4rGvuhmyNsHUPg3QrPjUrTUSfWmXLVVEw==}
|
||||
engines: {node: '>= 10'}
|
||||
hasBin: true
|
||||
|
||||
'@testing-library/dom@10.4.2':
|
||||
resolution: {integrity: sha512-yzr2S9HyAIdhz2/6qHgbs665Q7PKVcDF05vsOlHPxG1mo36gKVesdYVeDLnXgfjJ03CrKRk08knc6+E/9m8v2Q==}
|
||||
engines: {node: '>=18'}
|
||||
@@ -4596,6 +4685,53 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
'@tauri-apps/cli-darwin-arm64@2.12.5':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-darwin-x64@2.12.5':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-linux-arm-gnueabihf@2.12.5':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-linux-arm64-gnu@2.12.5':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-linux-arm64-musl@2.12.5':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-linux-riscv64-gnu@2.12.5':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-linux-x64-gnu@2.12.5':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-linux-x64-musl@2.12.5':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-win32-arm64-msvc@2.12.5':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-win32-ia32-msvc@2.12.5':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-win32-x64-msvc@2.12.5':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli@2.12.5':
|
||||
optionalDependencies:
|
||||
'@tauri-apps/cli-darwin-arm64': 2.12.5
|
||||
'@tauri-apps/cli-darwin-x64': 2.12.5
|
||||
'@tauri-apps/cli-linux-arm-gnueabihf': 2.12.5
|
||||
'@tauri-apps/cli-linux-arm64-gnu': 2.12.5
|
||||
'@tauri-apps/cli-linux-arm64-musl': 2.12.5
|
||||
'@tauri-apps/cli-linux-riscv64-gnu': 2.12.5
|
||||
'@tauri-apps/cli-linux-x64-gnu': 2.12.5
|
||||
'@tauri-apps/cli-linux-x64-musl': 2.12.5
|
||||
'@tauri-apps/cli-win32-arm64-msvc': 2.12.5
|
||||
'@tauri-apps/cli-win32-ia32-msvc': 2.12.5
|
||||
'@tauri-apps/cli-win32-x64-msvc': 2.12.5
|
||||
|
||||
'@testing-library/dom@10.4.2':
|
||||
dependencies:
|
||||
'@babel/code-frame': 7.29.7
|
||||
|
||||
Reference in New Issue
Block a user