From dcb7be1fe0ea3c7e53896094da07971de67bb84a Mon Sep 17 00:00:00 2001 From: Fokiiiiiii <229531129+Fokiiiiiii@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:56:33 +0900 Subject: [PATCH 1/2] Add Android support (launcher, on-device server, client mods) --- .github/workflows/android-release.yml | 185 +++ .github/workflows/server-ci.yml | 2 +- .gitignore | 4 + AscNet.Common/Database/Account.cs | 5 + AscNet.Common/Util/ClientRegions.cs | 60 +- AscNet.GameServer/Handlers/AccountModule.cs | 15 +- .../Handlers/AndroidNotifyLoginSerializer.cs | 71 ++ AscNet.GameServer/Session.cs | 1 + AscNet.Launcher/src/bundle.rs | 4 +- .../Controllers/AccountController.cs | 58 +- .../Controllers/ConfigController.cs | 20 + AscNet.Test/Program.AndroidCompat.cs | 148 +++ AscNet.Test/Program.GateLoginCompatibility.cs | 50 +- AscNet.Test/Program.RegionTables.cs | 8 + AscNet.Test/Program.cs | 8 + Mods/core/XAscNet/XAscNetPanel.lua | 166 ++- Mods/gm-menu/XAscNet/XAscNetGmMenuBoot.lua | 6 + Mods/gm-menu/XAscNet/XAscNetGmPanel.lua | 14 + Mods/gm-menu/XManager/XGmTestManager.diff | 17 +- Scripts/android/.gitattributes | 3 + Scripts/android/README.md | 104 ++ Scripts/android/launcher/.gitignore | 3 + Scripts/android/launcher/app/build.gradle.kts | 47 + .../launcher/app/src/main/AndroidManifest.xml | 57 + .../app/src/main/assets/update-runtime.sh | 37 + .../main/java/jp/cradle/link/AppUpdater.java | 246 ++++ .../java/jp/cradle/link/ClientPackages.java | 62 + .../java/jp/cradle/link/Dependencies.java | 81 ++ .../jp/cradle/link/GameProxyVpnService.java | 100 ++ .../jp/cradle/link/InstallResultReceiver.java | 69 + .../main/java/jp/cradle/link/LogExport.java | 140 ++ .../java/jp/cradle/link/MainActivity.java | 1122 +++++++++++++++++ .../java/jp/cradle/link/ModSelection.java | 35 + .../java/jp/cradle/link/PlayerAccounts.java | 84 ++ .../main/java/jp/cradle/link/SetupFlow.java | 68 + .../java/jp/cradle/link/UpdateChecker.java | 133 ++ .../main/res/drawable/infinite_loop_icon.png | Bin 0 -> 37178 bytes .../app/src/main/res/values/styles.xml | 6 + .../jp/cradle/link/ClientPackagesTest.java | 53 + .../java/jp/cradle/link/DependenciesTest.java | 102 ++ .../java/jp/cradle/link/LogExportTest.java | 43 + .../java/jp/cradle/link/ModSelectionTest.java | 49 + .../jp/cradle/link/PlayerAccountsTest.java | 51 + .../java/jp/cradle/link/SetupFlowTest.java | 96 ++ .../jp/cradle/link/UpdateCheckerTest.java | 114 ++ Scripts/android/launcher/build.gradle.kts | 3 + Scripts/android/launcher/gradle.properties | 3 + Scripts/android/launcher/settings.gradle.kts | 18 + Scripts/android/moddetect/Cargo.lock | 392 ++++++ Scripts/android/moddetect/Cargo.toml | 23 + Scripts/android/moddetect/src/main.rs | 190 +++ Scripts/android/pack.ps1 | 113 ++ Scripts/android/relay.py | 79 ++ Scripts/android/runtime/modctl.py | 266 ++++ Scripts/android/runtime/requirements.lock | 54 + Scripts/android/runtime/rish/LICENSE | 21 + Scripts/android/runtime/rish/rish | 25 + .../android/runtime/wheels/UnityPy-LICENSE | 21 + Scripts/android/setup.sh | 414 ++++++ .../tests/test_android_release_workflow.py | 60 + Scripts/android/tests/test_distribution.py | 219 ++++ Scripts/android/tests/test_gm_bezel.py | 40 + Scripts/android/tests/test_known_builds.py | 33 + Scripts/android/tests/test_modctl.py | 196 +++ Scripts/android/tests/test_pack_release.py | 110 ++ Scripts/android/tests/test_pgr_gm_bundle.py | 104 ++ Scripts/android/tests/test_relay.py | 132 ++ Scripts/android/tests/test_update_runtime.py | 134 ++ Scripts/pgr_bundles.py | 14 +- Scripts/pgr_gm_bundle.py | 345 +++++ Scripts/test_pgr_bundles.py | 11 + 71 files changed, 6720 insertions(+), 47 deletions(-) create mode 100644 .github/workflows/android-release.yml create mode 100644 AscNet.GameServer/Handlers/AndroidNotifyLoginSerializer.cs create mode 100644 AscNet.Test/Program.AndroidCompat.cs create mode 100644 Mods/gm-menu/XAscNet/XAscNetGmMenuBoot.lua create mode 100644 Scripts/android/.gitattributes create mode 100644 Scripts/android/README.md create mode 100644 Scripts/android/launcher/.gitignore create mode 100644 Scripts/android/launcher/app/build.gradle.kts create mode 100644 Scripts/android/launcher/app/src/main/AndroidManifest.xml create mode 100644 Scripts/android/launcher/app/src/main/assets/update-runtime.sh create mode 100644 Scripts/android/launcher/app/src/main/java/jp/cradle/link/AppUpdater.java create mode 100644 Scripts/android/launcher/app/src/main/java/jp/cradle/link/ClientPackages.java create mode 100644 Scripts/android/launcher/app/src/main/java/jp/cradle/link/Dependencies.java create mode 100644 Scripts/android/launcher/app/src/main/java/jp/cradle/link/GameProxyVpnService.java create mode 100644 Scripts/android/launcher/app/src/main/java/jp/cradle/link/InstallResultReceiver.java create mode 100644 Scripts/android/launcher/app/src/main/java/jp/cradle/link/LogExport.java create mode 100644 Scripts/android/launcher/app/src/main/java/jp/cradle/link/MainActivity.java create mode 100644 Scripts/android/launcher/app/src/main/java/jp/cradle/link/ModSelection.java create mode 100644 Scripts/android/launcher/app/src/main/java/jp/cradle/link/PlayerAccounts.java create mode 100644 Scripts/android/launcher/app/src/main/java/jp/cradle/link/SetupFlow.java create mode 100644 Scripts/android/launcher/app/src/main/java/jp/cradle/link/UpdateChecker.java create mode 100644 Scripts/android/launcher/app/src/main/res/drawable/infinite_loop_icon.png create mode 100644 Scripts/android/launcher/app/src/main/res/values/styles.xml create mode 100644 Scripts/android/launcher/app/src/test/java/jp/cradle/link/ClientPackagesTest.java create mode 100644 Scripts/android/launcher/app/src/test/java/jp/cradle/link/DependenciesTest.java create mode 100644 Scripts/android/launcher/app/src/test/java/jp/cradle/link/LogExportTest.java create mode 100644 Scripts/android/launcher/app/src/test/java/jp/cradle/link/ModSelectionTest.java create mode 100644 Scripts/android/launcher/app/src/test/java/jp/cradle/link/PlayerAccountsTest.java create mode 100644 Scripts/android/launcher/app/src/test/java/jp/cradle/link/SetupFlowTest.java create mode 100644 Scripts/android/launcher/app/src/test/java/jp/cradle/link/UpdateCheckerTest.java create mode 100644 Scripts/android/launcher/build.gradle.kts create mode 100644 Scripts/android/launcher/gradle.properties create mode 100644 Scripts/android/launcher/settings.gradle.kts create mode 100644 Scripts/android/moddetect/Cargo.lock create mode 100644 Scripts/android/moddetect/Cargo.toml create mode 100644 Scripts/android/moddetect/src/main.rs create mode 100644 Scripts/android/pack.ps1 create mode 100644 Scripts/android/relay.py create mode 100644 Scripts/android/runtime/modctl.py create mode 100644 Scripts/android/runtime/requirements.lock create mode 100644 Scripts/android/runtime/rish/LICENSE create mode 100644 Scripts/android/runtime/rish/rish create mode 100644 Scripts/android/runtime/wheels/UnityPy-LICENSE create mode 100644 Scripts/android/setup.sh create mode 100644 Scripts/android/tests/test_android_release_workflow.py create mode 100644 Scripts/android/tests/test_distribution.py create mode 100644 Scripts/android/tests/test_gm_bezel.py create mode 100644 Scripts/android/tests/test_known_builds.py create mode 100644 Scripts/android/tests/test_modctl.py create mode 100644 Scripts/android/tests/test_pack_release.py create mode 100644 Scripts/android/tests/test_pgr_gm_bundle.py create mode 100644 Scripts/android/tests/test_relay.py create mode 100644 Scripts/android/tests/test_update_runtime.py create mode 100644 Scripts/pgr_gm_bundle.py diff --git a/.github/workflows/android-release.yml b/.github/workflows/android-release.yml new file mode 100644 index 00000000..74138564 --- /dev/null +++ b/.github/workflows/android-release.yml @@ -0,0 +1,185 @@ +name: Android release + +# Publishes Infinite Loop for Android as the release android-v. That tag is what the app's updater +# looks for (UpdateChecker.TAG_PREFIX), together with the assets Infinite-Loop.apk and SHA256SUMS. The release also +# carries Infinite-Loop-Android.zip, which the app's "Install server" / "Update Runtime" step downloads. +# +# The maintainer bumps versionName and versionCode in Scripts/android/launcher/app/build.gradle.kts in a commit +# first; this workflow refuses to run when versionName and the input disagree. Run it from the default branch. +# +# Repository secrets (Settings > Secrets and variables > Actions) — the SAME signing key as earlier releases, because +# Android refuses to update an app that is signed with a different key: +# ASCNET_KEYSTORE_BASE64 the release keystore, base64 encoded on one line +# ASCNET_KEYSTORE_PASSWORD +# ASCNET_KEY_ALIAS +# ASCNET_KEY_PASSWORD +on: + workflow_dispatch: + inputs: + version: + description: "Android app version, e.g. 0.4.0 (must equal versionName); the release tag is android-v" + required: true + type: string + notes: + description: "Release notes (optional)" + required: false + type: string + default: "" + +permissions: + contents: read + +concurrency: + group: android-release + cancel-in-progress: false + +env: + VERSION: ${{ inputs.version }} + # The built app updates from the repository that publishes it, so no edit of gradle.properties is needed here or in a fork. + ORG_GRADLE_PROJECT_updateRepository: ${{ github.repository }} + +jobs: + # The two native pieces of the on-device runtime are built here, not committed: the detector as a static musl binary (it + # also runs under Android's shell) and UnityPy's extension for CPython 3.12 on Linux ARM64, which PyPI does not ship. + # Termux's Ubuntu 24.04 guest has the same glibc as this runner image. + arm-runtime: + runs-on: ubuntu-24.04-arm + steps: + - uses: actions/checkout@v5 + + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Build the mod detector + run: | + set -euo pipefail + sudo apt-get update + sudo apt-get install -y --no-install-recommends musl-tools + rustup target add aarch64-unknown-linux-musl + cargo build --release --locked --manifest-path Scripts/android/moddetect/Cargo.toml --target aarch64-unknown-linux-musl + mkdir -p runtime + cp Scripts/android/moddetect/target/aarch64-unknown-linux-musl/release/ascnet-moddetect runtime/moddetect-aarch64 + # Static: no dynamic loader, so it runs wherever the phone's kernel does. + ! readelf -l runtime/moddetect-aarch64 | grep -q INTERP + + - name: Build the UnityPy wheel + run: | + set -euo pipefail + python -m pip install --upgrade pip setuptools wheel + mkdir -p runtime/wheels + python -m pip wheel --no-deps --no-binary UnityPy "UnityPy==1.25.2" -w runtime/wheels + test -s runtime/wheels/unitypy-1.25.2-cp312-cp312-linux_aarch64.whl + + - uses: actions/upload-artifact@v4 + with: + name: android-runtime + path: runtime + if-no-files-found: error + + release: + needs: arm-runtime + # pack.ps1 finds apksigner.bat, so it needs a Windows runner. + runs-on: windows-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v5 + + - name: Check version, branch, tag and secrets + shell: bash + env: + GH_TOKEN: ${{ github.token }} + DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} + KEYSTORE_BASE64: ${{ secrets.ASCNET_KEYSTORE_BASE64 }} + KEYSTORE_PASSWORD: ${{ secrets.ASCNET_KEYSTORE_PASSWORD }} + KEY_ALIAS: ${{ secrets.ASCNET_KEY_ALIAS }} + KEY_PASSWORD: ${{ secrets.ASCNET_KEY_PASSWORD }} + run: | + set -euo pipefail + [[ "$VERSION" =~ ^[0-9]+(\.[0-9]+){1,3}$ ]] || { echo "version must look like 0.4.0"; exit 1; } + [ "$GITHUB_REF_NAME" = "$DEFAULT_BRANCH" ] || { echo "run from $DEFAULT_BRANCH, not $GITHUB_REF_NAME"; exit 1; } + name="$(sed -n 's/^ *versionName = "\(.*\)"$/\1/p' Scripts/android/launcher/app/build.gradle.kts | head -n 1)" + echo "input=$VERSION versionName=$name" + [ "$name" = "$VERSION" ] || { echo "versionName is $name: bump build.gradle.kts in a commit first"; exit 1; } + missing="" + for secret in KEYSTORE_BASE64 KEYSTORE_PASSWORD KEY_ALIAS KEY_PASSWORD; do + [ -n "${!secret}" ] || missing="$missing ASCNET_$secret" + done + [ -z "$missing" ] || { echo "missing repository secrets:$missing (see the comment at the top of this workflow)"; exit 1; } + if gh release view "android-v$VERSION" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then + echo "release android-v$VERSION already exists"; exit 1 + fi + + - uses: actions/download-artifact@v4 + with: + name: android-runtime + path: Scripts/android/runtime + + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: "17" + + - uses: actions/setup-dotnet@v5 + with: + dotnet-version: "8.0.x" + + - name: Build, sign and package + shell: pwsh + env: + KEYSTORE_BASE64: ${{ secrets.ASCNET_KEYSTORE_BASE64 }} + KEYSTORE_PASSWORD: ${{ secrets.ASCNET_KEYSTORE_PASSWORD }} + KEY_ALIAS: ${{ secrets.ASCNET_KEY_ALIAS }} + KEY_PASSWORD: ${{ secrets.ASCNET_KEY_PASSWORD }} + run: | + $keystore = Join-Path $env:RUNNER_TEMP 'release.jks' + [IO.File]::WriteAllBytes($keystore, [Convert]::FromBase64String($env:KEYSTORE_BASE64)) + $env:ASCNET_KEYSTORE = $keystore + $env:ASCNET_KEYSTORE_PASSWORD = $env:KEYSTORE_PASSWORD + $env:ASCNET_KEY_ALIAS = $env:KEY_ALIAS + $env:ASCNET_KEY_PASSWORD = $env:KEY_PASSWORD + try { + & ./Scripts/android/pack.ps1 -OutputDirectory dist + } finally { + Remove-Item -Force -ErrorAction SilentlyContinue $keystore + } + + - name: Check the packaged files + shell: bash + run: | + set -euo pipefail + for f in Infinite-Loop.apk SHA256SUMS Infinite-Loop-Android.zip; do + [ -s "dist/$f" ] || { echo "dist/$f is missing"; exit 1; } + done + # pack.ps1 writes the manifest with CRLF on Windows; the app and update-runtime.sh both accept that. + tr -d '\r' < dist/SHA256SUMS > sums.txt + grep -q ' Infinite-Loop.apk$' sums.txt && grep -q ' Infinite-Loop-Android.zip$' sums.txt \ + || { echo "SHA256SUMS does not list the APK and the zip"; exit 1; } + (cd dist && sha256sum -c ../sums.txt) + + - name: Create the release + shell: bash + env: + GH_TOKEN: ${{ github.token }} + NOTES: ${{ inputs.notes }} + run: | + set -euo pipefail + notes="${NOTES:-Infinite Loop for Android $VERSION}" + # Not "latest": the desktop launcher's release check reads releases/latest. + gh release create "android-v$VERSION" dist/Infinite-Loop.apk dist/SHA256SUMS dist/Infinite-Loop-Android.zip \ + --repo "$GITHUB_REPOSITORY" --target "$GITHUB_SHA" --title "Infinite Loop for Android $VERSION" \ + --notes "$notes" --latest=false + + - name: Verify the release is what the updater expects + shell: bash + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + sleep 5 + gh release view "android-v$VERSION" --repo "$GITHUB_REPOSITORY" --json tagName,isDraft,isPrerelease,assets > release.json + jq -e --arg tag "android-v$VERSION" '.tagName == $tag and .isDraft == false and .isPrerelease == false' release.json + for f in Infinite-Loop.apk SHA256SUMS Infinite-Loop-Android.zip; do + jq -e --arg f "$f" '[.assets[] | select(.name == $f)] | length == 1' release.json + done diff --git a/.github/workflows/server-ci.yml b/.github/workflows/server-ci.yml index 5a2773fa..cdce7fbd 100644 --- a/.github/workflows/server-ci.yml +++ b/.github/workflows/server-ci.yml @@ -99,7 +99,7 @@ jobs: --character-progression-compat-only \ --inventory-equip-compat-only \ --guild-core-compat-only \ - --login-account-compat-only; do + --login-account-compat-only \n --android-compat-only; do echo "::group::AscNet.Test $sw" dotnet AscNet.Test.dll "$sw" echo "::endgroup::" diff --git a/.gitignore b/.gitignore index a1e5061d..155aae8f 100644 --- a/.gitignore +++ b/.gitignore @@ -378,6 +378,10 @@ AscNet.Launcher/target/ AscNet.Patch/target/ AscNet.Patch/VersionShim/bin/ AscNet.Patch/VersionShim/obj/ +Scripts/android/moddetect/target/ +Scripts/android/runtime/moddetect-aarch64 +Scripts/android/runtime/wheels/*.whl +Scripts/android/runtime/rish/rish_shizuku.dex # macOS metadata .DS_Store diff --git a/AscNet.Common/Database/Account.cs b/AscNet.Common/Database/Account.cs index bff34faa..6865aadc 100644 --- a/AscNet.Common/Database/Account.cs +++ b/AscNet.Common/Database/Account.cs @@ -26,6 +26,11 @@ public class Account return collection.AsQueryable().FirstOrDefault(x => x.Username == username); } + public static List Usernames() + { + return collection.AsQueryable().Select(x => x.Username).ToList(); + } + public static Account? FromUsername(string username, string password) { return collection.AsQueryable().FirstOrDefault(x => x.Username == username && x.Password == password); diff --git a/AscNet.Common/Util/ClientRegions.cs b/AscNet.Common/Util/ClientRegions.cs index 3d989ffb..b7443e98 100644 --- a/AscNet.Common/Util/ClientRegions.cs +++ b/AscNet.Common/Util/ClientRegions.cs @@ -1,4 +1,5 @@ using System.Collections.Concurrent; +using System.Text.RegularExpressions; namespace AscNet.Common.Util; @@ -14,26 +15,59 @@ public static class ClientRegions { public const string Default = "en"; public static readonly string[] GateRegions = ["tw", "kr", "jp", "cn"]; - private static readonly ConcurrentDictionary byPlayerToken = new(); + public static IEnumerable AndroidGateRegions => GateRegions.Prepend(Default); + private static readonly ConcurrentDictionary byPlayerToken = new(); - public static void Remember(string playerToken, string region) => byPlayerToken[playerToken] = region; + public static void Remember(string playerToken, string region, bool isAndroid = false) => + byPlayerToken[playerToken] = (region, isAndroid); - public static string? Recall(string playerToken) => byPlayerToken.GetValueOrDefault(playerToken); + public static string? Recall(string playerToken) => byPlayerToken.TryGetValue(playerToken, out var profile) ? profile.Region : null; + public static bool IsAndroid(string playerToken) => byPlayerToken.TryGetValue(playerToken, out var profile) && profile.IsAndroid; + public static bool IsAndroidGatePath(string? path) => AndroidRegionFromGate(path) is not null; + public static string? AndroidRegionFromPackage(string? package) => RegionOfPackage(package); /// The region of an SDK package id; null for EN (and unknown packages, which keep the shared EN tables). - public static string? FromPackage(string? package) => package switch + public static string? FromPackage(string? package) { - "com.kurogame.punishing.grayraven.tw" => "tw", - "com.kurogame.punishing.grayraven.kr" => "kr", - "com.kurogame.punishing.grayraven.jp" => "jp", - "com.kurogame.haru.kuro" or "com.kurogame.haru.hero" => "cn", - _ => null - }; + string? region = RegionOfPackage(package); + return region == Default ? null : region; + } + + // The region is the id's suffix, not a fixed list: store builds of one region differ only in the prefix (Google Play adds + // ".gplay.", JP's uses the herogame publisher). Keep identical to Scripts/android/relay.py and launcher ClientPackages.java. + private static readonly Regex PackagePattern = new( + @"\Acom\.(?:kurogame|herogame)\.(?:gplay\.)?(?:punishing\.grayraven\.(?en|jp|tw|kr)|haru\.(?:kuro|hero))\z", + RegexOptions.CultureInvariant); + + private static string? RegionOfPackage(string? package) + { + if (package is null) return null; + Match match = PackagePattern.Match(package); + if (!match.Success) return null; + return match.Groups["region"].Success ? match.Groups["region"].Value : "cn"; + } /// The gate path's region: /api/Login/Login-tw is "tw", plain /api/Login/Login is EN. - public static string FromGatePath(string? path) => - path is not null && path.StartsWith(GatePrefix, StringComparison.Ordinal) && GateRegions.Contains(path[GatePrefix.Length..]) - ? path[GatePrefix.Length..] : Default; + public static string FromGatePath(string? path) + { + string? suffix = path?.TrimEnd('/'); + string? androidRegion = AndroidRegionFromGate(suffix); + if (androidRegion is not null) return androidRegion; + return suffix is not null && suffix.StartsWith(GatePrefix, StringComparison.Ordinal) && GateRegions.Contains(suffix[GatePrefix.Length..]) + ? suffix[GatePrefix.Length..] : Default; + } + + private static string? AndroidRegionFromGate(string? path) + { + const string platformSuffix = "-android"; + string? route = path?.TrimEnd('/'); + if (route is null || route.Length <= GatePrefix.Length + platformSuffix.Length + || !route.StartsWith(GatePrefix, StringComparison.OrdinalIgnoreCase) + || !route.EndsWith(platformSuffix, StringComparison.OrdinalIgnoreCase)) + return null; + string region = route[GatePrefix.Length..^platformSuffix.Length].ToLowerInvariant(); + return AndroidGateRegions.Contains(region) ? region : null; + } private const string GatePrefix = "/api/Login/Login-"; } diff --git a/AscNet.GameServer/Handlers/AccountModule.cs b/AscNet.GameServer/Handlers/AccountModule.cs index 320e846c..2334f78d 100644 --- a/AscNet.GameServer/Handlers/AccountModule.cs +++ b/AscNet.GameServer/Handlers/AccountModule.cs @@ -262,6 +262,7 @@ public static void LoginRequestHandler(Session session, Packet.Request packet) player.Save(); session.player = player; + session.IsAndroidClient = ClientRegions.IsAndroid(player.Token); session.character = Character.FromUid(player.PlayerData.Id, player.GatherRewards); session.stage = Stage.FromUid(player.PlayerData.Id); session.inventory = Inventory.FromUid(player.PlayerData.Id); @@ -358,6 +359,8 @@ public static void ReconnectRequestHandler(Session session, Packet.Request packe player.Save(); } + if (session.player is null) + session.IsAndroidClient = ClientRegions.IsAndroid(player.Token); session.player = player; session.ContinuePushSequenceFrom(request.LastMsgSeqNo); session.SendResponse(new ReconnectResponse @@ -535,7 +538,7 @@ internal static NotifyBriefStoryData BuildNotifyBriefStoryData(Player player) internal static void SendLoginState(Session session) { - session.SendPush(BuildNotifyLogin(session)); + SendNotifyLogin(session, BuildNotifyLogin(session)); } private static TimeLimitCtrlConfigList MakeTimeLimitControl(long id, long startTime, long endTime) @@ -743,6 +746,14 @@ private static List BuildPurchaseClientInfoLoginData(Player player) .ToList(); } + private static void SendNotifyLogin(Session session, NotifyLogin payload) + { + if (session.IsAndroidClient) + session.SendPush("NotifyLogin", AndroidNotifyLoginSerializer.Serialize(payload, isAndroid: true)); + else + session.SendPush(payload); + } + private static NotifyLogin BuildNotifyLogin(Session session) => BuildNotifyLogin(session, DateTimeOffset.UtcNow.ToUnixTimeSeconds()); @@ -1377,7 +1388,7 @@ static void DoLogin(Session session, bool updateLoginAccounting) NotifyPurchaseRecommendConfig purchaseRecommendConfig = BuildPurchaseRecommendConfig(); // Seed the manual before NotifyLogin fires login-complete; the late full push refreshes Lotto/Purchase after cache initialization. session.SendPush(WheelchairManualModule.BuildPayload(session, DateTimeOffset.UtcNow)); - session.SendPush(notifyLogin); + SendNotifyLogin(session, notifyLogin); if (headTimeout is not null) session.SendPush(headTimeout); session.SendPush(notifyPayInfo); diff --git a/AscNet.GameServer/Handlers/AndroidNotifyLoginSerializer.cs b/AscNet.GameServer/Handlers/AndroidNotifyLoginSerializer.cs new file mode 100644 index 00000000..4a130013 --- /dev/null +++ b/AscNet.GameServer/Handlers/AndroidNotifyLoginSerializer.cs @@ -0,0 +1,71 @@ +using System.Buffers; +using AscNet.Common.MsgPack; +using MessagePack; + +namespace AscNet.GameServer.Handlers; + +[MessagePackObject(true, AllowPrivate = true)] +internal sealed class AndroidSharePlatformConfig +{ + public string Id { get; set; } = string.Empty; + public List SdkId { get; set; } = new(); +} + +internal static class AndroidNotifyLoginSerializer +{ + private static readonly MessagePackSerializerOptions AndroidOptions = MessagePackSerializerOptions.Standard + .WithCompression(MessagePackCompression.None); + + internal static byte[] Serialize(NotifyLogin payload, bool isAndroid, IReadOnlyList? shareRows = null) + { + byte[] canonical = MessagePackSerializer.Serialize(payload, AndroidOptions); + if (!isAndroid) + return canonical; + + ReadOnlySequence input = new(canonical); + MessagePackReader reader = new(input); + int count = reader.ReadMapHeader(); + List> fields = new(count + 2); + bool hasShareRows = false; + bool hasKeyPadSetting = false; + byte[] shareValue = MessagePackSerializer.Serialize(shareRows ?? Array.Empty(), AndroidOptions); + + for (int i = 0; i < count; i++) + { + string key = reader.ReadString()!; + SequencePosition start = reader.Position; + reader.Skip(); + byte[] rawValue = input.Slice(start, reader.Position).ToArray(); + if (key == "SharePlatformConfigList") + { + fields.Add(new(key, shareValue)); + hasShareRows = true; + } + else if (key == "KeyPadSetting") + { + fields.Add(new(key, [0xc0])); + hasKeyPadSetting = true; + } + else + { + fields.Add(new(key, rawValue)); + } + } + + if (!hasShareRows) + fields.Add(new("SharePlatformConfigList", shareValue)); + if (!hasKeyPadSetting) + fields.Add(new("KeyPadSetting", [0xc0])); + + ArrayBufferWriter buffer = new(); + MessagePackWriter writer = new(buffer); + writer.WriteMapHeader(fields.Count); + foreach ((string key, byte[] value) in fields) + { + writer.Write(key); + writer.WriteRaw(value); + } + writer.Flush(); + return buffer.WrittenSpan.ToArray(); + } +} diff --git a/AscNet.GameServer/Session.cs b/AscNet.GameServer/Session.cs index 82419cf7..22930f3a 100644 --- a/AscNet.GameServer/Session.cs +++ b/AscNet.GameServer/Session.cs @@ -22,6 +22,7 @@ public partial class Session internal System.Net.IPAddress? RemoteAddress { get; set; } // A non-loopback peer is on someone else's server (FreeNotice.IsHosted); an unknown address counts as hosted. internal bool IsHosted => FreeNotice.IsHosted(RemoteAddress); + internal bool IsAndroidClient { get; set; } public Player player = default!; public Character character = default!; public Stage stage = default!; diff --git a/AscNet.Launcher/src/bundle.rs b/AscNet.Launcher/src/bundle.rs index 8d757f07..c5859293 100644 --- a/AscNet.Launcher/src/bundle.rs +++ b/AscNet.Launcher/src/bundle.rs @@ -238,7 +238,7 @@ fn search(game: &Path, include_resource: bool) -> Result> { Ok(None) } -fn matches_entry(path: &Path, entry: &Entry) -> Result { +pub(crate) fn matches_entry(path: &Path, entry: &Entry) -> Result { let data = read_bounded(path)?; Ok(data.len() as u64 == entry.size && format!("{:x}", Sha1::digest(&data)).eq_ignore_ascii_case(&entry.sha1)) @@ -714,7 +714,7 @@ fn file_table(payload: &[u8]) -> Result>> { /// `m_Name` of a PGR-protected bundle's AssetBundle object, reading only the LZ4 blocks that cover it. /// `Ok(None)`: not protected, or not a layout this reader knows (serialized version < 22, big endian). -fn bundle_name(path: &Path) -> Result> { +pub(crate) fn bundle_name(path: &Path) -> Result> { let metadata = fs::symlink_metadata(path)?; if metadata.file_type().is_symlink() || !metadata.is_file() || metadata.len() > MAX_BUNDLE_SIZE { bail!("refusing asset: {}", path.display()); diff --git a/AscNet.SDKServer/Controllers/AccountController.cs b/AscNet.SDKServer/Controllers/AccountController.cs index 19385ad3..3c2dc35e 100644 --- a/AscNet.SDKServer/Controllers/AccountController.cs +++ b/AscNet.SDKServer/Controllers/AccountController.cs @@ -10,6 +10,11 @@ namespace AscNet.SDKServer.Controllers public class AccountController : IRegisterable { private const string GateFallbackUsernameEnv = "ASCNET_GATE_FALLBACK_USERNAME"; + // Set by the Android launcher's setup.sh for on-device runs. A reverse proxy in front of a hosted server also + // connects from loopback, so loopback alone must never unlock the account endpoints below. + private const string AndroidLocalModeEnv = "ASCNET_ANDROID_LOCAL_MODE"; + // The account an Android gate login maps to; set from the launcher, so it lasts until the server stops. + private static volatile string? androidPlayUser; public static void Register(WebApplication app) { app.MapPost("/api/AscNet/register", async (HttpContext ctx) => @@ -101,15 +106,16 @@ string HandleGateLogin(HttpContext ctx, [FromQuery] int loginType, [FromQuery] i { Account? account = Account.FromToken(token); - if (account is null && ctx.Request.Path != "/api/Login/Login-cn" + bool androidGate = ClientRegions.IsAndroidGatePath(ctx.Request.Path.Value); + if (account is null && ClientRegions.FromGatePath(ctx.Request.Path.Value) != "cn" && !string.Equals(region, "cn", StringComparison.OrdinalIgnoreCase)) - account = GateFallbackAccount(); + account = GateFallbackAccount(userId, androidGate); if (account is null) return InvalidLoginToken(); Player player = Player.FromPlayerId(account.Uid); - ClientRegions.Remember(player.Token, ClientRegions.FromGatePath(ctx.Request.Path.Value)); + ClientRegions.Remember(player.Token, ClientRegions.FromGatePath(ctx.Request.Path.Value), androidGate); LoginGate gate = new() { @@ -132,8 +138,33 @@ string HandleGateLogin(HttpContext ctx, [FromQuery] int loginType, [FromQuery] i // the client has (ClientRegions). foreach (string gateRegion in ClientRegions.GateRegions) app.MapGet($"/api/Login/Login-{gateRegion}", HandleGateLogin); + foreach (string gateRegion in ClientRegions.AndroidGateRegions) + app.MapGet($"/api/Login/Login-{gateRegion}-android", HandleGateLogin); + + // For the Android launcher on the same phone: plain text, the current account on the first line, then every account. + app.MapGet("/api/AscNet/android/players", (HttpContext ctx) => + { + if (!AndroidLocalMode) return Results.NotFound(); + if (!IsLoopback(ctx)) return Results.StatusCode(StatusCodes.Status403Forbidden); + List users = Account.Usernames(); + string current = androidPlayUser ?? Environment.GetEnvironmentVariable(GateFallbackUsernameEnv) ?? ""; + return Results.Text(string.Join('\n', users.Prepend(current)) + "\n"); + }); + app.MapPost("/api/AscNet/android/player", (HttpContext ctx, [FromQuery] string username) => + { + if (!AndroidLocalMode) return Results.NotFound(); + if (!IsLoopback(ctx)) return Results.StatusCode(StatusCodes.Status403Forbidden); + if (Account.FromUsername(username) is null) return Results.NotFound(); + androidPlayUser = username; + return Results.Ok(); + }); } + private static bool AndroidLocalMode => Environment.GetEnvironmentVariable(AndroidLocalModeEnv) == "1"; + + private static bool IsLoopback(HttpContext ctx) => + ctx.Connection.RemoteIpAddress is { } address && System.Net.IPAddress.IsLoopback(address); + // Engineering limit, not a retail protocol constant: the runner sends only username/password, // and AuthRequest adds only a token (generated as a 36-character GUID). 16 KiB leaves ample // room for escaped/unicode credentials while bounding both known-length and chunked input. @@ -213,17 +244,32 @@ private static string GameServerTcpHost() return host; } - private static Account? GateFallbackAccount() + private static Account? GateFallbackAccount(int userId, bool androidGate) { + if (androidGate && AndroidLocalMode && androidPlayUser is { } chosen && Account.FromUsername(chosen) is { } picked) + return picked; + string? fallbackUsername = Environment.GetEnvironmentVariable(GateFallbackUsernameEnv); if (string.IsNullOrWhiteSpace(fallbackUsername)) return null; Account? account = Account.FromUsername(fallbackUsername); + if (!androidGate || account is not null) + return account; + + string username = $"{fallbackUsername}-android-{userId}"; + account = Account.FromUsername(username); if (account is not null) - SDKServer.log.Warn("Gate login fallback mapped to the configured local account."); + return account; - return account; + try + { + return Account.Create(username, username); + } + catch (ArgumentException) + { + return Account.FromUsername(username); + } } } } diff --git a/AscNet.SDKServer/Controllers/ConfigController.cs b/AscNet.SDKServer/Controllers/ConfigController.cs index 3e51409a..eb2a52c8 100644 --- a/AscNet.SDKServer/Controllers/ConfigController.cs +++ b/AscNet.SDKServer/Controllers/ConfigController.cs @@ -19,6 +19,8 @@ public static void Register(WebApplication app) { app.MapGet("/prod/client/config/{package}/{version}/standalone/config.tab", HandleConfigRequest); app.MapGet("/prod/client/config/{cdnKey}/{package}/{version}/standalone/config.tab", HandleConfigRequest); + app.MapGet("/prod/client/config/{package}/{version}/android/config.tab", HandleConfigRequest); + app.MapGet("/prod/client/config/{cdnKey}/{package}/{version}/android/config.tab", HandleConfigRequest); app.MapGet("/prod/client/notice/config/{package}/{version}/LoginNotice.json", HandleLoginNoticeRequest); app.MapGet("/prod/client/notice/config/{cdnKey}/{package}/{version}/LoginNotice.json", HandleLoginNoticeRequest); @@ -55,6 +57,15 @@ public static void Register(WebApplication app) private static string HandleConfigRequest(HttpContext ctx) { string package = GetRouteValue(ctx, "package"); + bool android = ctx.Request.Path.Value?.EndsWith("/android/config.tab", StringComparison.OrdinalIgnoreCase) == true; + string? androidRegion = android ? ClientRegions.AndroidRegionFromPackage(package) : null; + if (android && androidRegion is null) + { + ctx.Response.StatusCode = StatusCodes.Status404NotFound; + return string.Empty; + } + if (android && package == "com.herogame.gplay.punishing.grayraven.jp") + package = "com.kurogame.punishing.grayraven.jp"; string version = GetRouteValue(ctx, "version"); bool currentClient = IsVersionAtLeast(version, 4, 5, 0); string publicHttpOrigin = PublicHttpOrigin(ctx); @@ -69,6 +80,15 @@ private static string HandleConfigRequest(HttpContext ctx) else AddLegacyClientConfig(remoteConfigs, package, version, versionConfig, publicHttpOrigin); + if (androidRegion is not null) + { + string originGate = $"{publicHttpOrigin}/api/Login/Login"; + string gate = $"{originGate}-{androidRegion}-android"; + foreach (RemoteConfig row in remoteConfigs.Where(row => row.Key is "ServerListStr" or "ChannelServerListStr")) + row.Value = System.Text.RegularExpressions.Regex.Replace(row.Value, + System.Text.RegularExpressions.Regex.Escape(originGate) + @"(?:-[a-z]{2})?(?=$|[|#\s])", gate); + } + // Local research switches (config.json "Client"); the stock rows stay authoritative otherwise. if (Common.Common.config.Client.Debug) remoteConfigs.SetConfig("Debug", true); diff --git a/AscNet.Test/Program.AndroidCompat.cs b/AscNet.Test/Program.AndroidCompat.cs new file mode 100644 index 00000000..338e3ead --- /dev/null +++ b/AscNet.Test/Program.AndroidCompat.cs @@ -0,0 +1,148 @@ +using AscNet.Common.Database; +using AscNet.Common.MsgPack; +using AscNet.GameServer.Handlers; +using MessagePack; +using Microsoft.AspNetCore.Builder; +using MongoDB.Driver; +using Newtonsoft.Json.Linq; +using System.Net; + +namespace AscNet.Test +{ + internal partial class Program + { + private static void ValidateAndroidNotifyLoginSerializer() + { + NotifyLogin payload = new(); + List pc = ReadNotifyLoginKeys(AndroidNotifyLoginSerializer.Serialize(payload, isAndroid: false), out _, out _); + + AndroidSharePlatformConfig[] rows = [new() { Id = "share", SdkId = [1, 2] }]; + List android = ReadNotifyLoginKeys(AndroidNotifyLoginSerializer.Serialize(payload, isAndroid: true, rows), + out int shareRows, out bool keyPadIsNil); + + AssertEqual(1, shareRows, "Android login payload carries the share platform rows"); + AssertEqual(true, keyPadIsNil, "Android login payload has an empty KeyPadSetting"); + AssertEqual(android.Count, android.Distinct().Count(), "Android login payload has no duplicate fields"); + foreach (string key in pc) + if (!android.Contains(key)) + throw new InvalidDataException($"Android login payload lost field '{key}'."); + } + + private static List ReadNotifyLoginKeys(byte[] data, out int shareRows, out bool keyPadIsNil) + { + shareRows = -1; + keyPadIsNil = false; + List keys = new(); + MessagePackReader reader = new(data); + int count = reader.ReadMapHeader(); + for (int i = 0; i < count; i++) + { + string key = reader.ReadString()!; + keys.Add(key); + if (key == "SharePlatformConfigList") + shareRows = new MessagePackReader(data.AsMemory((int)reader.Consumed)).ReadArrayHeader(); + else if (key == "KeyPadSetting") + keyPadIsNil = new MessagePackReader(data.AsMemory((int)reader.Consumed)).TryReadNil(); + reader.Skip(); + } + return keys; + } + + private static async Task ValidateAndroidConfigTab() + { + await using WebApplication app = CreateConfigControllerTestApp(); + await app.StartAsync(); + try + { + using HttpClient client = new() { BaseAddress = new Uri(BoundAddress(app)) }; + foreach (string package in new[] { "com.kurogame.punishing.grayraven.jp", "com.herogame.gplay.punishing.grayraven.jp" }) + { + using HttpResponseMessage response = await client.GetAsync($"/prod/client/config/{package}/4.9.1/android/config.tab"); + AssertEqual(HttpStatusCode.OK, response.StatusCode, $"{package} android config.tab status"); + string body = await response.Content.ReadAsStringAsync(); + if (!body.Contains("/api/Login/Login-jp-android", StringComparison.Ordinal)) + throw new InvalidDataException($"{package} android config.tab does not point at the Android gate."); + } + + using (HttpResponseMessage unknown = await client.GetAsync("/prod/client/config/com.example.other/4.9.1/android/config.tab")) + AssertEqual(HttpStatusCode.NotFound, unknown.StatusCode, "unknown package android config.tab status"); + string standalone = await client.GetStringAsync("/prod/client/config/com.kurogame.punishing.grayraven.jp/4.9.1/standalone/config.tab"); + if (standalone.Contains("-android", StringComparison.Ordinal)) + throw new InvalidDataException("The PC config.tab must not point at the Android gate."); + } + finally + { + await app.StopAsync(); + } + } + + private static async Task ValidateAndroidLocalModeAccounts() + { + string? previousMode = Environment.GetEnvironmentVariable("ASCNET_ANDROID_LOCAL_MODE"); + string? previousFallback = Environment.GetEnvironmentVariable("ASCNET_GATE_FALLBACK_USERNAME"); + string suffix = Guid.NewGuid().ToString("N"); + List accounts = new(); + try + { + Account first = Account.Create($"android-local-a-{suffix}", suffix); + accounts.Add(first); + Account second = Account.Create($"android-local-b-{suffix}", suffix); + accounts.Add(second); + Player firstPlayer = Player.FromPlayerId(first.Uid); + Player secondPlayer = Player.FromPlayerId(second.Uid); + Environment.SetEnvironmentVariable("ASCNET_GATE_FALLBACK_USERNAME", first.Username); + + await using WebApplication app = CreateGateLoginTestApp(); + await app.StartAsync(); + try + { + using HttpClient client = new() { BaseAddress = new Uri(BoundAddress(app)) }; + string select(string name) => $"/api/AscNet/android/player?username={Uri.EscapeDataString(name)}"; + + // Without the opt-in, loopback is not enough: a reverse proxy on a hosted server also connects from 127.0.0.1. + Environment.SetEnvironmentVariable("ASCNET_ANDROID_LOCAL_MODE", null); + using (HttpResponseMessage list = await client.GetAsync("/api/AscNet/android/players")) + AssertEqual(HttpStatusCode.NotFound, list.StatusCode, "account list without local mode"); + using (HttpResponseMessage choose = await client.PostAsync(select(second.Username), null)) + AssertEqual(HttpStatusCode.NotFound, choose.StatusCode, "account choice without local mode"); + + Environment.SetEnvironmentVariable("ASCNET_ANDROID_LOCAL_MODE", "1"); + string[] lines = (await client.GetStringAsync("/api/AscNet/android/players")).Split('\n', StringSplitOptions.RemoveEmptyEntries); + AssertEqual(first.Username, lines[0], "account list starts with the current account"); + foreach (Account account in accounts) + if (!lines.Contains(account.Username)) + throw new InvalidDataException($"Account list lost {account.Username}."); + using (HttpResponseMessage missing = await client.PostAsync(select($"missing-{suffix}"), null)) + AssertEqual(HttpStatusCode.NotFound, missing.StatusCode, "choosing an unknown account"); + + using (HttpResponseMessage choose = await client.PostAsync(select(second.Username), null)) + AssertEqual(HttpStatusCode.OK, choose.StatusCode, "choosing an account"); + await AssertGateLoginCode(client, 1, $"unknown-{suffix}", 0, "Android gate uses the chosen account", + secondPlayer.Token, "/api/Login/Login-jp-android"); + await AssertGateLoginCode(client, 1, $"unknown-{suffix}", 0, "PC gate ignores the chosen account", + firstPlayer.Token, "/api/Login/Login"); + + // Turning local mode off also turns the choice off. + Environment.SetEnvironmentVariable("ASCNET_ANDROID_LOCAL_MODE", null); + await AssertGateLoginCode(client, 1, $"unknown-{suffix}", 0, "Android gate without local mode", + firstPlayer.Token, "/api/Login/Login-jp-android"); + } + finally + { + await app.StopAsync(); + } + } + finally + { + foreach (Account account in accounts) + { + Player.collection.DeleteOne(player => player.PlayerData.Id == account.Uid); + Account.collection.DeleteOne(candidate => candidate.Id == account.Id); + } + + Environment.SetEnvironmentVariable("ASCNET_ANDROID_LOCAL_MODE", previousMode); + Environment.SetEnvironmentVariable("ASCNET_GATE_FALLBACK_USERNAME", previousFallback); + } + } + } +} diff --git a/AscNet.Test/Program.GateLoginCompatibility.cs b/AscNet.Test/Program.GateLoginCompatibility.cs index d24136ab..6d143c24 100644 --- a/AscNet.Test/Program.GateLoginCompatibility.cs +++ b/AscNet.Test/Program.GateLoginCompatibility.cs @@ -35,6 +35,51 @@ private static async Task ValidateGateLoginCompatibility() using (HttpResponseMessage twGate = await client.GetAsync($"/api/Login/Login-tw?loginType=0&userId={account.Uid}&token={Uri.EscapeDataString(account.Token)}")) AssertEqual(HttpStatusCode.OK, twGate.StatusCode, "TW gate status"); AssertEqual("tw", ClientRegions.Recall(player.Token), "TW gate remembers its region"); + using (HttpResponseMessage twAndroidGate = await client.GetAsync($"/api/Login/Login-tw-android?loginType=0&userId={account.Uid}&token={Uri.EscapeDataString(account.Token)}")) + { + AssertEqual(HttpStatusCode.OK, twAndroidGate.StatusCode, "TW Android gate status"); + JObject twAndroidBody = JObject.Parse(await twAndroidGate.Content.ReadAsStringAsync()); + AssertEqual(0, twAndroidBody.Value("code"), "TW Android gate code"); + AssertEqual(player.Token, twAndroidBody.Value("token"), "TW Android gate player token"); + } + AssertEqual("tw", ClientRegions.Recall(player.Token), "TW Android gate remembers its region"); + AssertEqual(true, ClientRegions.IsAndroid(player.Token), "TW Android gate remembers Android profile"); + foreach (string androidRegion in new[] { "en", "kr", "jp", "cn" }) + { + using HttpResponseMessage regionalAndroidGate = await client.GetAsync($"/api/Login/Login-{androidRegion}-android?loginType=0&userId={account.Uid}&token={Uri.EscapeDataString(account.Token)}"); + AssertEqual(HttpStatusCode.OK, regionalAndroidGate.StatusCode, $"{androidRegion} Android gate status"); + JObject regionalAndroidBody = JObject.Parse(await regionalAndroidGate.Content.ReadAsStringAsync()); + AssertEqual(0, regionalAndroidBody.Value("code"), $"{androidRegion} Android gate code"); + AssertEqual(player.Token, regionalAndroidBody.Value("token"), $"{androidRegion} Android gate player token"); + AssertEqual(androidRegion, ClientRegions.Recall(player.Token), $"{androidRegion} Android gate remembers its region"); + AssertEqual(true, ClientRegions.IsAndroid(player.Token), $"{androidRegion} Android gate remembers Android profile"); + } + + Environment.SetEnvironmentVariable("ASCNET_GATE_FALLBACK_USERNAME", account.Username); + await AssertGateLoginCode(client, account.Uid, $"unknown-{suffix}", 0, "PC fallback", player.Token); + string fallbackUsername = $"gate-login-android-{suffix}"; + Environment.SetEnvironmentVariable("ASCNET_GATE_FALLBACK_USERNAME", fallbackUsername); + async Task LoginAndroid(int userId) + { + using HttpResponseMessage response = await client.GetAsync($"/api/Login/Login-jp-android?loginType=0&userId={userId}&token=unknown-{suffix}"); + AssertEqual(HttpStatusCode.OK, response.StatusCode, "Android gate status"); + JObject gate = JObject.Parse(await response.Content.ReadAsStringAsync()); + AssertEqual(0, gate.Value("code"), "Android fallback gate code"); + return gate.Value("token") ?? throw new InvalidOperationException("Android gate token missing"); + } + + string firstAndroidToken = await LoginAndroid(101); + string secondAndroidToken = await LoginAndroid(202); + if (firstAndroidToken == secondAndroidToken) + throw new InvalidOperationException("Android fallback users unexpectedly shared a player token."); + foreach (int userId in new[] { 101, 202 }) + { + Account androidAccount = Account.FromUsername($"{fallbackUsername}-android-{userId}") + ?? throw new InvalidOperationException("Android fallback account was not created."); + Player.collection.DeleteOne(player => player.PlayerData.Id == androidAccount.Uid); + Account.collection.DeleteOne(candidate => candidate.Id == androidAccount.Id); + } + } finally { @@ -67,9 +112,10 @@ private static WebApplication CreateGateLoginTestApp() return app; } - private static async Task AssertGateLoginCode(HttpClient client, long userId, string token, long expectedCode, string name, string? expectedPlayerToken = null) + private static async Task AssertGateLoginCode(HttpClient client, long userId, string token, long expectedCode, string name, + string? expectedPlayerToken = null, string gatePath = "/api/Login/Login") { - string endpoint = $"/api/Login/Login?loginType=0&userId={userId}&token={Uri.EscapeDataString(token)}"; + string endpoint = $"{gatePath}?loginType=0&userId={userId}&token={Uri.EscapeDataString(token)}"; using HttpResponseMessage response = await client.GetAsync(endpoint); string body = await response.Content.ReadAsStringAsync(); if (response.StatusCode != HttpStatusCode.OK) diff --git a/AscNet.Test/Program.RegionTables.cs b/AscNet.Test/Program.RegionTables.cs index a5c1843d..b3397e05 100644 --- a/AscNet.Test/Program.RegionTables.cs +++ b/AscNet.Test/Program.RegionTables.cs @@ -26,6 +26,14 @@ private static void ValidateRegionTablesCompatibility() AssertEqual("en", ClientRegions.FromGatePath("/api/Login/Login-zz"), "unknown gate suffix is EN"); AssertEqual("tw", ClientRegions.FromPackage("com.kurogame.punishing.grayraven.tw"), "TW package region"); AssertEqual(true, ClientRegions.FromPackage("com.kurogame.punishing.grayraven.en") is null, "EN package has no region"); + AssertEqual("en", ClientRegions.AndroidRegionFromPackage("com.kurogame.gplay.punishing.grayraven.en"), "Google Play EN package is EN"); + AssertEqual(true, ClientRegions.FromPackage("com.kurogame.gplay.punishing.grayraven.en") is null, "Google Play EN package has no region"); + AssertEqual("jp", ClientRegions.FromPackage("com.herogame.gplay.punishing.grayraven.jp"), "JP Google Play package region"); + AssertEqual("tw", ClientRegions.FromPackage("com.kurogame.gplay.punishing.grayraven.tw"), "TW Google Play package region"); + AssertEqual("kr", ClientRegions.AndroidRegionFromPackage("com.kurogame.gplay.punishing.grayraven.kr"), "KR Google Play package region"); + AssertEqual("cn", ClientRegions.FromPackage("com.kurogame.haru.hero"), "CN hero package region"); + AssertEqual(true, ClientRegions.AndroidRegionFromPackage("com.kurogame.punishing.grayraven.en\n") is null, "package ids must match in full"); + AssertEqual(true, ClientRegions.FromPackage("com.kurogame.punishing.grayraven.tw.evil") is null, "lookalike package has no region"); HashSet twTasks = TableReaderV2.Parse("tw").Select(row => row.Id) .Concat(TableReaderV2.Parse("tw").Select(row => row.Id)).ToHashSet(); diff --git a/AscNet.Test/Program.cs b/AscNet.Test/Program.cs index 5d5d2f71..2c09ddcc 100644 --- a/AscNet.Test/Program.cs +++ b/AscNet.Test/Program.cs @@ -912,6 +912,14 @@ static void Main(string[] args) ValidateLoginAccountCompatibility(); return; } + if (args.Contains("--android-compat-only")) + { + ValidateAndroidNotifyLoginSerializer(); + ValidateAndroidConfigTab().GetAwaiter().GetResult(); + ValidateAndroidLocalModeAccounts().GetAwaiter().GetResult(); + ValidateGateLoginCompatibility().GetAwaiter().GetResult(); + return; + } if (args.Contains("--gate-login-compat-only")) { ValidateGateLoginCompatibility().GetAwaiter().GetResult(); diff --git a/Mods/core/XAscNet/XAscNetPanel.lua b/Mods/core/XAscNet/XAscNetPanel.lua index 238921fe..95d63e27 100644 --- a/Mods/core/XAscNet/XAscNetPanel.lua +++ b/Mods/core/XAscNet/XAscNetPanel.lua @@ -4,6 +4,7 @@ local XAscNetPanel = {} local U = CS.UnityEngine local UI = U.UI +local ES = U.EventSystems local white = U.Color(1, 1, 1, 1) local font @@ -31,8 +32,15 @@ local function row(go, height) end function XAscNetPanel.New(opts) + if U.Application.platform ~= U.RuntimePlatform.Android and (opts.edge or opts.edgeLabel) then + -- The side drawer is for touch screens; on PC the centered window stays as it was. + local plain = {} + for key, value in pairs(opts) do plain[key] = value end + plain.edge, plain.edgeLabel = nil, nil + opts = plain + end local Panel = {} - local root, body, title, status, current, top, building, scroll, initialized + local root, window, handle, handleRect, handleMoved, body, title, status, current, top, building, scroll, initialized local stack = {} local function translate(value) value = tostring(value or "") @@ -75,7 +83,7 @@ function XAscNetPanel.New(opts) end local function button(parent, name, callback) local go, rect = object(name, parent) - local background = image(go, U.Color(0.16, 0.20, 0.27, 1)) + local background = image(go, opts.edge and U.Color(0.11, 0.12, 0.14, 1) or U.Color(0.16, 0.20, 0.27, 1)) local component = go:AddComponent(typeof(UI.Button)) component.targetGraphic = background text(rect, "TxtName", name) @@ -141,28 +149,127 @@ function XAscNetPanel.New(opts) local scaler = go:AddComponent(typeof(UI.CanvasScaler)) scaler.uiScaleMode = UI.CanvasScaler.ScaleMode.ScaleWithScreenSize scaler.referenceResolution = U.Vector2(1920, 1080) - scaler.matchWidthOrHeight = 0.5 + scaler.matchWidthOrHeight = opts.edge and 1 or 0.5 go:AddComponent(typeof(UI.GraphicRaycaster)) - local window, windowRect = object("Window", rect) - windowRect.anchorMin = U.Vector2(0.5, 0.5) - windowRect.anchorMax = U.Vector2(0.5, 0.5) - windowRect.sizeDelta = U.Vector2(1180, 920) - image(window, U.Color(0.035, 0.045, 0.065, 0.98)) + local windowRect + window, windowRect = object("Window", rect) + if opts.edge == "right" then + windowRect.anchorMin = U.Vector2(1, 0.5) + windowRect.anchorMax = U.Vector2(1, 0.5) + windowRect.pivot = U.Vector2(1, 0.5) + elseif opts.edge == "left" then + windowRect.anchorMin = U.Vector2(0, 0.5) + windowRect.anchorMax = U.Vector2(0, 0.5) + windowRect.pivot = U.Vector2(0, 0.5) + else + windowRect.anchorMin = U.Vector2(0.5, 0.5) + windowRect.anchorMax = U.Vector2(0.5, 0.5) + end + windowRect.sizeDelta = opts.edge and U.Vector2(760, 1080) or U.Vector2(1180, 920) + image(window, opts.edge and U.Color(0.035, 0.037, 0.043, 0.985) + or U.Color(0.035, 0.045, 0.065, 0.98)) + if opts.edgeLabel then + local component + component, handleRect = button(rect, "EdgeHandle", function() + if handleMoved then handleMoved = false else Panel.Open() end + end) + handle = component.gameObject + local label = handle.transform:Find("TxtName"):GetComponent(typeof(UI.Text)) + if opts.edge == "left" or opts.edge == "right" then + local left = opts.edge == "left" + local side = left and 0 or 1 + handleRect.anchorMin = U.Vector2(side, 1) + handleRect.anchorMax = U.Vector2(side, 1) + handleRect.pivot = U.Vector2(side, 1) + handleRect.sizeDelta = U.Vector2(92, 170) + local handleX = left and -46 or 46 + local positionKey = "AscNet." .. opts.name .. ".HandleY" + local function clampY(value) + return math.max(-910, math.min(0, value)) + end + handleRect.anchoredPosition = U.Vector2(handleX, clampY(U.PlayerPrefs.GetFloat(positionKey, -56))) + local background = handle:GetComponent(typeof(UI.Image)) + background.color = U.Color(0.025, 0.027, 0.032, 0.97) + label.text = "" + local grip, gripRect = object("Grip", handleRect) + gripRect.anchorMin = U.Vector2(left and 0.76 or 0.24, 0.5) + gripRect.anchorMax = U.Vector2(left and 0.76 or 0.24, 0.5) + gripRect.sizeDelta = U.Vector2(8, 58) + local gripImage = image(grip, U.Color(0.88, 0.89, 0.90, 1)) + local trigger = handle:AddComponent(typeof(ES.EventTrigger)) + local startY = 0 + local function on(eventType, callback) + local entry = ES.EventTrigger.Entry() + entry.eventID = eventType + listen(entry.callback, callback) + trigger.triggers:Add(entry) + end + on(ES.EventTriggerType.PointerDown, function() + handleMoved = false + startY = U.Input.mousePosition.y + end) + on(ES.EventTriggerType.Drag, function() + local pointerY = U.Input.mousePosition.y + if math.abs(pointerY - startY) > 8 then handleMoved = true end + local canvasY = pointerY / U.Screen.height * 1080 + handleRect.anchoredPosition = U.Vector2(handleX, clampY(canvasY - 995)) + end) + on(ES.EventTriggerType.PointerUp, function() + if handleMoved then + U.PlayerPrefs.SetFloat(positionKey, handleRect.anchoredPosition.y) + U.PlayerPrefs.Save() + end + end) + else + handleRect.anchorMin = U.Vector2(1, 0.5) + handleRect.anchorMax = U.Vector2(1, 0.5) + handleRect.pivot = U.Vector2(1, 0.5) + handleRect.sizeDelta = U.Vector2(64, 180) + handleRect.anchoredPosition = U.Vector2(0, 0) + label.text = translate(opts.edgeLabel) + label.alignment = U.TextAnchor.MiddleCenter + end + handle:SetActive(false) + end local titleRect title, titleRect = text(windowRect, "Path", opts.title, 25) titleRect.anchorMin = U.Vector2(0, 1); titleRect.anchorMax = U.Vector2(1, 1) titleRect.offsetMin = U.Vector2(20, -64); titleRect.offsetMax = U.Vector2(-240, -8) - local _, backRect = button(windowRect, "Back", function() + local backButton, backRect = button(windowRect, "Back", function() if #stack > 0 then show(table.remove(stack)) end end) backRect.anchorMin = U.Vector2(1, 1); backRect.anchorMax = U.Vector2(1, 1) backRect.offsetMin = U.Vector2(-230, -58); backRect.offsetMax = U.Vector2(-125, -8) - local _, closeRect = button(windowRect, "Close", function() Panel.Close() end) + local closeButton, closeRect = button(windowRect, "Close", function() Panel.Close() end) closeRect.anchorMin = U.Vector2(1, 1); closeRect.anchorMax = U.Vector2(1, 1) closeRect.offsetMin = U.Vector2(-115, -58); closeRect.offsetMax = U.Vector2(-10, -8) + if opts.edge then + title.fontSize = 34 + titleRect.offsetMin = U.Vector2(32, -82); titleRect.offsetMax = U.Vector2(-210, -16) + backRect.offsetMin = U.Vector2(-190, -78); backRect.offsetMax = U.Vector2(-110, -12) + closeRect.offsetMin = U.Vector2(-96, -78); closeRect.offsetMax = U.Vector2(-16, -12) + local backLabel = backButton.transform:Find("TxtName"):GetComponent(typeof(UI.Text)) + backLabel.text = "‹"; backLabel.fontSize = 42; backLabel.alignment = U.TextAnchor.MiddleCenter + local closeLabel = closeButton.transform:Find("TxtName"):GetComponent(typeof(UI.Text)) + closeLabel.text = "×"; closeLabel.fontSize = 42; closeLabel.alignment = U.TextAnchor.MiddleCenter + local drawerButton, drawerRect = button(windowRect, "DrawerGrip", function() Panel.Close() end) + local drawerSide = opts.edge == "left" and 1 or 0 + drawerRect.anchorMin = U.Vector2(drawerSide, 1); drawerRect.anchorMax = U.Vector2(drawerSide, 1) + drawerRect.pivot = U.Vector2(0.5, 1) + drawerRect.sizeDelta = U.Vector2(72, 170) + drawerRect.anchoredPosition = U.Vector2(opts.edge == "left" and 36 or -36, -56) + local drawerImage = drawerButton:GetComponent(typeof(UI.Image)) + drawerImage.color = U.Color(0.025, 0.027, 0.032, 0.97) + drawerButton.transform:Find("TxtName"):GetComponent(typeof(UI.Text)).text = "│" + end local viewport, viewportRect = object("Viewport", windowRect) - stretch(viewportRect, 16, 100, 16, 76) - image(viewport, U.Color(0.06, 0.07, 0.09, 1)) + if opts.edge then + stretch(viewportRect, 28, 96, 28, 102) + else + stretch(viewportRect, 16, 100, 16, 76) + end + image(viewport, opts.edge == "left" and U.Color(0.055, 0.057, 0.063, 1) + or U.Color(0.06, 0.07, 0.09, 1)) viewport:AddComponent(typeof(UI.RectMask2D)) body = viewportRect scroll = viewport:AddComponent(typeof(UI.ScrollRect)) @@ -268,21 +375,50 @@ function XAscNetPanel.New(opts) end) end function Panel.IsOpen() - return root ~= nil and root.activeSelf + if root == nil then return false end + if handle then return window.activeSelf end + return root.activeSelf + end + function Panel.ShowHandle() + if not opts.edgeLabel then return false end + if not root then + local ok, failure = pcall(create) + if not ok then + local logger = rawget(_G, "XLog") + if logger and logger.Error then logger.Error("AscNet panel handle failed: " .. tostring(failure)) end + if root then U.Object.Destroy(root) end + root, window, handle, current, top, building, status = nil, nil, nil, nil, nil, nil, nil + return false + end + end + root:SetActive(true) + window:SetActive(false) + handle:SetActive(true) + return true end function Panel.Close() - if root then root:SetActive(false) end + if not root then return end + if handle then + window:SetActive(false) + handle:SetActive(true) + else + root:SetActive(false) + end end function Panel.Open() if Panel.IsOpen() then return end if not root then if not safe(create) then if root then U.Object.Destroy(root) end - root, current, top, building, status = nil, nil, nil, nil, nil + root, window, handle, current, top, building, status = nil, nil, nil, nil, nil, nil, nil return end end root:SetActive(true) + if handle then + handle:SetActive(false) + window:SetActive(true) + end Panel.SetStatus("") if not initialized or opts.rebuild then initialized = true diff --git a/Mods/gm-menu/XAscNet/XAscNetGmMenuBoot.lua b/Mods/gm-menu/XAscNet/XAscNetGmMenuBoot.lua new file mode 100644 index 00000000..98b033c1 --- /dev/null +++ b/Mods/gm-menu/XAscNet/XAscNetGmMenuBoot.lua @@ -0,0 +1,6 @@ +local loaded, failure = pcall(require, "XManager/XGmTestManager") +if not loaded then + XLog.Error("AscNet GM menu failed to load: " .. tostring(failure)) +end + +return loaded diff --git a/Mods/gm-menu/XAscNet/XAscNetGmPanel.lua b/Mods/gm-menu/XAscNet/XAscNetGmPanel.lua index f373e6a6..87ceaa53 100644 --- a/Mods/gm-menu/XAscNet/XAscNetGmPanel.lua +++ b/Mods/gm-menu/XAscNet/XAscNetGmPanel.lua @@ -4,6 +4,8 @@ local XAscNetSubMenu = require("XAscNet/XAscNetSubMenu") local labels = require("XAscNet/XAscNetGmLabels") local U = CS.UnityEngine local watching = false +local bezelReady = U.Application.platform ~= U.RuntimePlatform.Android +local bezelFrames = 0 local init local function translate(value) return labels[value] or value @@ -11,6 +13,7 @@ end local Panel Panel = XAscNetPanel.New{ name = "AscNetGmMenu", title = "GM", tag = "[GM menu]", translate = translate, + edgeLabel = "GM", edge = "right", translateRefreshed = function(value) for _, prefix in ipairs({"当前服务器", "已启动时间", "用户名", "客户端版本", "原版本", "现版本", "未登录"}) do value = value:gsub(prefix, function() return translate(prefix) end) @@ -53,6 +56,17 @@ function Panel.StartWatcher(callback) end watching = true local function poll() + if not bezelReady then + if Panel.IsOpen() then + bezelReady = true + else + bezelFrames = bezelFrames + 1 + if bezelFrames >= 60 then + bezelFrames = 0 + bezelReady = Panel.ShowHandle() + end + end + end local input, key = U.Input, U.KeyCode if input.GetKeyDown(key.D) and (input.GetKey(key.LeftControl) or input.GetKey(key.RightControl)) and (input.GetKey(key.LeftShift) or input.GetKey(key.RightShift)) then Panel.Toggle() end diff --git a/Mods/gm-menu/XManager/XGmTestManager.diff b/Mods/gm-menu/XManager/XGmTestManager.diff index 0409d98d..7a90f49a 100644 --- a/Mods/gm-menu/XManager/XGmTestManager.diff +++ b/Mods/gm-menu/XManager/XGmTestManager.diff @@ -17,7 +17,14 @@ -- Lua 单元测试菜单配色(直接设 Text.color,无需富文本):默认黄、通过转绿、失败转红 local GM_TEST_COLOR_DEFAULT = CS.UnityEngine.Color(1, 0.92, 0, 1) -@@ -1016,8 +1023,7 @@ +@@ -279,3 +286,5 @@ + local function AddArchiveFunction() +- Panel:AddSubMenu("SVN操作\n(beta)", AddSvnFunction) ++ if CS.UnityEngine.Application.platform ~= CS.UnityEngine.RuntimePlatform.Android or type(CS.XDebugManager.ReloadLuaTable) == "function" then ++ Panel:AddSubMenu("SVN操作\n(beta)", AddSvnFunction) ++ end + --Panel:AddSubMenu("萌战相关", AddMoeWar) +@@ -1016,8 +1025,7 @@ end , true) @@ -27,7 +34,7 @@ "播放音频", function() if not cueId then -@@ -1030,13 +1036,9 @@ +@@ -1030,13 +1038,9 @@ XLuaAudioManager.PlayAudioByType(typeId, cueId) end ) @@ -42,7 +49,7 @@ "播放3D音频", function() if not cueId then -@@ -1055,9 +1057,6 @@ +@@ -1055,9 +1059,6 @@ XLuaAudioManager.PlayAudioByType(typeId, cueId, force3dSource.gameObject) end ) @@ -52,7 +59,7 @@ Panel:AddButton( "关闭音频", -@@ -1845,7 +1844,6 @@ +@@ -1845,7 +1846,6 @@ end function XGmTestManager.Init() @@ -60,7 +67,7 @@ Panel:AddSubMenu("本地测试", XGmTestManager.TestFunc) Panel:AddSubMenu("当前信息", AddInfo, true) Panel:AddSubMenu("服务器", AddServerFunction, true) -@@ -2030,3 +2028,8 @@ +@@ -2030,3 +2030,8 @@ return dataList end --endregion diff --git a/Scripts/android/.gitattributes b/Scripts/android/.gitattributes new file mode 100644 index 00000000..7876d0e9 --- /dev/null +++ b/Scripts/android/.gitattributes @@ -0,0 +1,3 @@ +*.sh text eol=lf +*.py text eol=lf +runtime/rish/rish text eol=lf diff --git a/Scripts/android/README.md b/Scripts/android/README.md new file mode 100644 index 00000000..d62db0b0 --- /dev/null +++ b/Scripts/android/README.md @@ -0,0 +1,104 @@ +# Infinite Loop for Android + +Runs the Infinite Loop server on your phone and points the game at it. Needs an ARM64 Android phone with the Punishing: Gray Raven client installed. Root is not required. + +The server runs inside [Termux](https://f-droid.org/packages/com.termux/). Client mods also need [Shizuku](https://shizuku.rikka.app/download/). The app installs both for you; the server's own dependencies (.NET, MongoDB, Python) are installed inside Termux by the **Install server** step. + +## Install with the app + +Install `Infinite-Loop.apk` and open it. The big button at the top always shows the one thing to do next: + +1. **Install Termux** downloads Termux and opens the Android installer. The first time, Android asks you to allow installs from Infinite Loop. Tap Install and come back. +2. **Allow Termux control** asks for the permission that lets this app run commands in Termux. +3. **Copy command and open Termux** copies one short line and opens Termux. Wait for the `$` prompt, long-press, Paste, press Enter, and tap Allow if Android asks for storage access. Termux refuses commands from other apps until this is done, and an app cannot do it for you. +4. **I pasted it — continue** (later **Install server**) downloads the server from this app's release, checks it and installs it. This takes a few minutes. +5. **PLAY** starts the server and the relay and opens the game. The relay redirects the game's traffic through Android's VPN service, so Android asks you once to allow a VPN connection. Tap it again while it is working to cancel. + +The region is chosen from the game build installed on the phone. The list below the big button changes it. + +## Install by hand + +Use this when the app cannot reach Termux. Everything runs in Termux; no app is needed for the server itself. + +1. In Termux, allow storage access and install the tools: + + ```sh + termux-setup-storage + pkg install -y curl unzip + ``` + +2. Download the release archive and its checksums. Replace `1.0.0` with the version you want: + + ```sh + cd ~ + base=https://github.com/reiserFSs/InfiniteLoop/releases/download/android-v1.0.0 + curl -fLO "$base/Infinite-Loop-Android.zip" + curl -fLO "$base/SHA256SUMS" + ``` + +3. Check the archive. The command must print `Infinite-Loop-Android.zip: OK`: + + ```sh + grep ' Infinite-Loop-Android.zip$' SHA256SUMS | tr -d '\r' | sha256sum -c - + ``` + +4. Unpack it and install the server. This takes a few minutes and needs internet access: + + ```sh + unzip -q Infinite-Loop-Android.zip -d infinite-loop-android + bash infinite-loop-android/setup.sh install infinite-loop-android/server-arm64.tar.gz + ``` + +5. Start and stop the server, or check which parts are running: + + ```sh + bash ~/.local/share/infinite-loop/setup.sh start + bash ~/.local/share/infinite-loop/setup.sh stop + bash ~/.local/share/infinite-loop/setup.sh status + ``` + + `start` keeps running in that Termux session. Leave it open, or run it from a second session. `status` prints `127.0.0.1: online` for MongoDB (27017), AscNet (8080 and 2335) and the relay (18084). + +Running step 4 again updates the server. It keeps the database and your own mods. The APK is installed separately like any other app; the app and the server should be the same version. + +## Client mods + +Stop the game, keep the server and the relay running, switch **GM Menu** and/or **Lua Mods** on or off, and tap **Apply Mods**. Turning both off restores the original game files. Restart the game afterwards. + +Mods need Shizuku to be installed and running. The app shows **Install Shizuku** when it is missing. The server also sends the game its debug setting every time it starts; without it the game ignores the mods. + +By hand, with the server and the relay running (use the package name of your region's client): + +```sh +bash ~/.local/share/infinite-loop/setup.sh mod-apply +``` + +## Updates + +**App.** The app checks GitHub Releases each time it is opened. When a newer version exists, a banner appears and **Download and install** fetches the APK, verifies its SHA-256 and opens the Android installer. A release counts when its tag is `android-v` (for example `android-v1.0.0`), it is not a draft or pre-release, and it has `Infinite-Loop.apk` and `SHA256SUMS` attached. `versionName` must increase. The APK must be signed with the same key as the installed app, otherwise Android refuses it and you must uninstall first. The repository to read is `updateRepository` in `Scripts/android/launcher/gradle.properties` (override with `-PupdateRepository=owner/name`). + +**Server.** After the app is updated, **Update server** appears when the installed server is older than the app. It downloads `Infinite-Loop-Android.zip` from the release `android-v`, checks it against that release's `SHA256SUMS`, and runs `setup.sh install` from it, the same as the manual steps above. The database and custom mods are kept, and the server restarts. Termux needs internet access, and the release must have both files attached. + +## Logs + +**Export Logs** saves one text file with the app's recent events and these logs, when they exist: + +- the server log (`start-cradle.log`), kept after a normal stop too +- the relay log (`relay.log`) and the MongoDB log (`mongodb.log`) +- the game's logcat (`client.log`), collected through Shizuku when you tap Export Logs. Export right after the problem, because Android keeps only recent lines. + +The first time, the app asks you to pick `Download/InfiniteLoop`, where the server writes its logs. By hand, find the same files in that folder, or run `bash ~/.local/share/infinite-loop/setup.sh client-log ` to write `client.log`. + +## Publishing a release + +Releases are built by the **Android release** workflow (Actions tab, *Run workflow*), which signs the APK, tags the release `android-v` and attaches `Infinite-Loop.apk`, `SHA256SUMS` and `Infinite-Loop-Android.zip`. The app's updater only offers releases with that tag and those assets. + +1. Raise `versionName` and `versionCode` in `launcher/app/build.gradle.kts`, commit, and merge to the default branch. +2. Once, add these repository secrets: `ASCNET_KEYSTORE_BASE64` (the release keystore on one line: `base64 -w0 release.jks`, or `[Convert]::ToBase64String([IO.File]::ReadAllBytes("release.jks"))`), `ASCNET_KEYSTORE_PASSWORD`, `ASCNET_KEY_ALIAS` and `ASCNET_KEY_PASSWORD`. Use the same keystore as earlier releases, otherwise Android refuses to update installed copies. +3. Run the workflow from the default branch with the same version. It stops if `versionName` differs, the tag exists, or a secret is missing. + +The built app updates from the repository that publishes it, so a fork or upstream needs no change to `gradle.properties`. + +## Build + +Install .NET SDK, Android SDK 35, JDK 17+, and Gradle. Set `ASCNET_KEYSTORE`, `ASCNET_KEYSTORE_PASSWORD`, `ASCNET_KEY_ALIAS`, and `ASCNET_KEY_PASSWORD` in the environment. Run `pwsh Scripts/android/pack.ps1 -OutputDirectory `. The output contains a signed release APK, ZIP, and SHA-256 manifest. Keep the signing key private. diff --git a/Scripts/android/launcher/.gitignore b/Scripts/android/launcher/.gitignore new file mode 100644 index 00000000..8f121e30 --- /dev/null +++ b/Scripts/android/launcher/.gitignore @@ -0,0 +1,3 @@ +/.gradle/ +/local.properties +**/build/ diff --git a/Scripts/android/launcher/app/build.gradle.kts b/Scripts/android/launcher/app/build.gradle.kts new file mode 100644 index 00000000..3c0d68b7 --- /dev/null +++ b/Scripts/android/launcher/app/build.gradle.kts @@ -0,0 +1,47 @@ +plugins { + id("com.android.application") +} + +if (gradle.startParameter.taskNames.any { it.contains("release", ignoreCase = true) }) { + val required = listOf("ASCNET_KEYSTORE", "ASCNET_KEYSTORE_PASSWORD", "ASCNET_KEY_ALIAS", "ASCNET_KEY_PASSWORD") + val missing = required.filter { System.getenv(it).isNullOrBlank() } + if (missing.isNotEmpty()) throw GradleException("Release signing configuration is missing: ${missing.joinToString()}") + if (!file(System.getenv("ASCNET_KEYSTORE")).isFile) throw GradleException("Release signing configuration: keystore file not found.") +} + +android { + namespace = "jp.cradle.link" + compileSdk = 35 + + defaultConfig { + applicationId = "jp.cradle.link" + minSdk = 29 + targetSdk = 35 + versionCode = 7 + versionName = "1.0.0" + // GitHub repository whose Releases the launcher updates from. Set in gradle.properties; override with -PupdateRepository=owner/name. + resValue("string", "update_repository", project.property("updateRepository") as String) + } + buildFeatures { + resValues = true + } + + signingConfigs { + create("release") { + val path = System.getenv("ASCNET_KEYSTORE") + if (!path.isNullOrBlank()) storeFile = file(path) + storePassword = System.getenv("ASCNET_KEYSTORE_PASSWORD") + keyAlias = System.getenv("ASCNET_KEY_ALIAS") + keyPassword = System.getenv("ASCNET_KEY_PASSWORD") + } + } + buildTypes { + getByName("release") { + signingConfig = signingConfigs.getByName("release") + } + } +} + +dependencies { + testImplementation("junit:junit:4.13.2") +} diff --git a/Scripts/android/launcher/app/src/main/AndroidManifest.xml b/Scripts/android/launcher/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000..e118bbf6 --- /dev/null +++ b/Scripts/android/launcher/app/src/main/AndroidManifest.xml @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Scripts/android/launcher/app/src/main/assets/update-runtime.sh b/Scripts/android/launcher/app/src/main/assets/update-runtime.sh new file mode 100644 index 00000000..60337c39 --- /dev/null +++ b/Scripts/android/launcher/app/src/main/assets/update-runtime.sh @@ -0,0 +1,37 @@ +set -Eeuo pipefail +# Run by the launcher inside Termux: update-runtime +# Downloads the release's Infinite-Loop-Android.zip, checks it against the release's SHA256SUMS, unpacks it and +# runs the same `setup.sh install` that a manual update runs. setup.sh needs the files next to it +# (runtime/, Mods/, pgr_*.py), which is why the whole archive is fetched rather than single files. +die() { printf '%s\n' "$*" >&2; exit 1; } + +repo=${1:-} tag=${2:-} +[[ $repo =~ ^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$ && $repo != *..* && $repo != ./* && $repo != */. ]] || die 'Invalid update repository.' +[[ $tag =~ ^android-v[0-9]{1,6}(\.[0-9]{1,6}){0,3}$ ]] || die 'Invalid update release.' +command -v curl >/dev/null || die 'curl is required.' +command -v unzip >/dev/null || pkg install -y unzip +command -v sha256sum >/dev/null || die 'sha256sum is required.' + +archive=Infinite-Loop-Android.zip +base=https://github.com/$repo/releases/download/$tag +work=${HOME:?}/.cache/infinite-loop-update +rm -rf -- "$work" +mkdir -p "$work" +trap 'rm -rf -- "$work"' EXIT + +fetch() { + curl --proto '=https' --proto-redir '=https' --max-redirs 5 --retry 3 --retry-all-errors -fsSL -o "$2" "$base/$1" +} + +fetch SHA256SUMS "$work/SHA256SUMS" +# pack.ps1 writes SHA256SUMS on Windows with CRLF line ends: drop the CR or no file name would match. +expected=$(tr -d '\r' < "$work/SHA256SUMS" | awk -v name="$archive" '$2 == name && $1 ~ /^[0-9a-fA-F]{64}$/ { print tolower($1); exit }') +[[ -n $expected ]] || die "Release has no checksum for $archive." +fetch "$archive" "$work/$archive" +actual=$(sha256sum "$work/$archive" | awk '{ print tolower($1) }') +[[ $actual == "$expected" ]] || die 'Checksum mismatch; the update was not installed.' + +mkdir "$work/package" +unzip -q "$work/$archive" -d "$work/package" +[[ -f $work/package/setup.sh && -f $work/package/server-arm64.tar.gz ]] || die 'Release archive is incomplete.' +bash "$work/package/setup.sh" install "$work/package/server-arm64.tar.gz" diff --git a/Scripts/android/launcher/app/src/main/java/jp/cradle/link/AppUpdater.java b/Scripts/android/launcher/app/src/main/java/jp/cradle/link/AppUpdater.java new file mode 100644 index 00000000..a6a6a29e --- /dev/null +++ b/Scripts/android/launcher/app/src/main/java/jp/cradle/link/AppUpdater.java @@ -0,0 +1,246 @@ +package jp.cradle.link; + +import android.content.Context; +import android.content.pm.PackageInfo; +import android.content.pm.PackageInstaller; +import android.content.pm.PackageManager; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.function.LongConsumer; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +/** + * Checks GitHub Releases for a newer launcher APK, downloads it, verifies it, and hands it to the system installer. + * All selection and trust rules live in {@link UpdateChecker}; this class only does I/O. Nothing is installed without + * the system confirmation dialog, and Android refuses an APK signed with a different key than the installed app. + */ +final class AppUpdater { + private static final int MAX_LIST_BYTES = 1 << 20; + private static final int MAX_SUMS_BYTES = 1 << 16; + private static final long MAX_APK_BYTES = 64L << 20; + private static final int MAX_REDIRECTS = 5; + private static final long MAX_DEPENDENCY_BYTES = 256L << 20; + + private AppUpdater() { } + + /** The tag of a newer release of {@code repository}, or null when the installed version is current. */ + static String check(String repository, String currentVersion) throws IOException, JSONException { + if (!UpdateChecker.validRepository(repository)) throw new IOException("Invalid update repository"); + String body = new String(read("https://api.github.com/repos/" + repository + "/releases?per_page=30", MAX_LIST_BYTES), StandardCharsets.UTF_8); + return UpdateChecker.newest(repository, currentVersion, parse(body)); + } + + private static List parse(String json) throws JSONException { + JSONArray array = new JSONArray(json); + List releases = new ArrayList<>(); + for (int index = 0; index < array.length(); index++) { + JSONObject release = array.getJSONObject(index); + List assets = new ArrayList<>(); + JSONArray listed = release.optJSONArray("assets"); + for (int asset = 0; listed != null && asset < listed.length(); asset++) { + JSONObject entry = listed.getJSONObject(asset); + assets.add(new UpdateChecker.Asset(entry.getString("name"), entry.getString("browser_download_url"))); + } + releases.add(new UpdateChecker.ReleaseInfo(release.getString("tag_name"), + release.optBoolean("draft"), release.optBoolean("prerelease"), assets)); + } + return releases; + } + + /** Downloads the APK of {@code tag} into the app's cache and verifies its hash, package id and version. */ + static File download(Context context, String repository, String tag) throws IOException { + if (!UpdateChecker.validRepository(repository) || UpdateChecker.versionOfTag(tag) == null) throw new IOException("Invalid update release"); + String sums = new String(read(UpdateChecker.assetUrl(repository, tag, UpdateChecker.SUMS), MAX_SUMS_BYTES), StandardCharsets.UTF_8); + String expected = UpdateChecker.expectedHash(sums, UpdateChecker.APK); + if (expected == null) throw new IOException("Release has no checksum for " + UpdateChecker.APK); + + File directory = new File(context.getCacheDir(), "update"); + if (!directory.isDirectory() && !directory.mkdirs()) throw new IOException("Cannot create update folder"); + File apk = new File(directory, UpdateChecker.APK); + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + HttpURLConnection connection = open(UpdateChecker.assetUrl(repository, tag, UpdateChecker.APK)); + try (InputStream in = connection.getInputStream(); OutputStream out = new FileOutputStream(apk)) { + byte[] buffer = new byte[16 * 1024]; + long total = 0; + for (int count; (count = in.read(buffer)) > 0; ) { + total += count; + if (total > MAX_APK_BYTES) throw new IOException("Update is too large"); + digest.update(buffer, 0, count); + out.write(buffer, 0, count); + } + } finally { + connection.disconnect(); + } + if (!hex(digest.digest()).equals(expected)) throw new IOException("Checksum mismatch"); + verifyPackage(context, apk); + return apk; + } catch (NoSuchAlgorithmException exception) { + throw new IOException(exception); + } catch (IOException | RuntimeException exception) { + apk.delete(); + throw exception; + } + } + + /** + * Downloads the latest published APK of a dependency (Termux, Shizuku) from its own GitHub repository. + * Guards: fixed repository and asset name, trusted hosts only, the release's published SHA-256 when it has one + * (Termux does, Shizuku does not), the APK's package id, and the system installer's confirmation. + */ + static File downloadDependency(Context context, Dependencies.Kind kind, LongConsumer progress) throws IOException { + List releases; + try { + releases = parse(new String(read("https://api.github.com/repos/" + kind.repository + "/releases?per_page=10", MAX_LIST_BYTES), + StandardCharsets.UTF_8)); + } catch (JSONException exception) { + throw new IOException(exception); + } + Dependencies.Download choice = Dependencies.pick(kind, releases); + if (choice == null) throw new IOException("No download found for " + kind.title); + UpdateChecker.Asset asset = choice.apk; + String expected = null; + if (choice.checksum != null) { + String sums = new String(read(choice.checksum.url, MAX_SUMS_BYTES), StandardCharsets.UTF_8); + expected = UpdateChecker.expectedHash(sums, asset.name); + if (expected == null) throw new IOException(kind.title + " release has no checksum for its APK"); + } + + File directory = new File(context.getCacheDir(), "update"); + if (!directory.isDirectory() && !directory.mkdirs()) throw new IOException("Cannot create update folder"); + File apk = new File(directory, kind.name().toLowerCase(Locale.ROOT) + ".apk"); + MessageDigest digest; + try { + digest = MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException exception) { + throw new IOException(exception); + } + HttpURLConnection connection = open(asset.url); + try (InputStream in = connection.getInputStream(); OutputStream out = new FileOutputStream(apk)) { + byte[] buffer = new byte[32 * 1024]; + long total = 0; + long reported = 0; + for (int count; (count = in.read(buffer)) > 0; ) { + total += count; + if (total > MAX_DEPENDENCY_BYTES) throw new IOException("Download is too large"); + digest.update(buffer, 0, count); + out.write(buffer, 0, count); + if (total - reported >= (1 << 20)) { + reported = total; + progress.accept(total); + } + } + } catch (IOException | RuntimeException exception) { + apk.delete(); + throw exception; + } finally { + connection.disconnect(); + } + if (expected != null && !hex(digest.digest()).equals(expected)) { + apk.delete(); + throw new IOException("Checksum mismatch"); + } + PackageInfo archive = context.getPackageManager().getPackageArchiveInfo(apk.getPath(), 0); + if (archive == null || !kind.packageName.equals(archive.packageName)) { + apk.delete(); + throw new IOException("Download is not " + kind.title); + } + return apk; + } + + /** The APK must be this app, and newer than what is installed. */ + private static void verifyPackage(Context context, File apk) throws IOException { + PackageManager packages = context.getPackageManager(); + PackageInfo archive = packages.getPackageArchiveInfo(apk.getPath(), 0); + if (archive == null || !context.getPackageName().equals(archive.packageName)) throw new IOException("Update is not this app"); + try { + if (archive.getLongVersionCode() <= packages.getPackageInfo(context.getPackageName(), 0).getLongVersionCode()) { + throw new IOException("Update is not newer"); + } + } catch (PackageManager.NameNotFoundException exception) { + throw new IOException(exception); + } + } + + /** Streams the APK into a package-installer session; the system then asks the user to confirm. */ + static void install(Context context, File apk, android.app.PendingIntent result) throws IOException { + install(context, apk, context.getPackageName(), result); + } + + static void install(Context context, File apk, String packageName, android.app.PendingIntent result) throws IOException { + PackageInstaller installer = context.getPackageManager().getPackageInstaller(); + PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL); + params.setAppPackageName(packageName); + int id = installer.createSession(params); + try (PackageInstaller.Session session = installer.openSession(id)) { + try (InputStream in = new FileInputStream(apk); OutputStream out = session.openWrite("base.apk", 0, apk.length())) { + byte[] buffer = new byte[16 * 1024]; + for (int count; (count = in.read(buffer)) > 0; ) out.write(buffer, 0, count); + session.fsync(out); + } + session.commit(result.getIntentSender()); + } catch (IOException | RuntimeException exception) { + installer.abandonSession(id); + throw exception; + } + } + + private static byte[] read(String url, int limit) throws IOException { + HttpURLConnection connection = open(url); + try (InputStream in = connection.getInputStream()) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buffer = new byte[8 * 1024]; + for (int count; (count = in.read(buffer)) > 0; ) { + if (out.size() + count > limit) throw new IOException("Response is too large"); + out.write(buffer, 0, count); + } + return out.toByteArray(); + } finally { + connection.disconnect(); + } + } + + /** GET with redirects followed by hand, so every hop is checked against the trusted GitHub hosts. */ + private static HttpURLConnection open(String url) throws IOException { + for (int hop = 0; hop <= MAX_REDIRECTS; hop++) { + if (!UpdateChecker.isTrustedUrl(url)) throw new IOException("Untrusted update URL"); + HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); + connection.setInstanceFollowRedirects(false); + connection.setConnectTimeout(8_000); + connection.setReadTimeout(15_000); + connection.setRequestProperty("Accept", "application/vnd.github+json, application/octet-stream"); + connection.setRequestProperty("User-Agent", "InfiniteLoopLauncher"); + int code = connection.getResponseCode(); + if (code == HttpURLConnection.HTTP_OK) return connection; + String location = connection.getHeaderField("Location"); + connection.disconnect(); + if (code >= 301 && code <= 308 && code != 304 && location != null) { + url = new URL(new URL(url), location).toString(); + continue; + } + throw new IOException("HTTP " + code); + } + throw new IOException("Too many redirects"); + } + + private static String hex(byte[] bytes) { + StringBuilder text = new StringBuilder(bytes.length * 2); + for (byte value : bytes) text.append(String.format(Locale.ROOT, "%02x", value)); + return text.toString(); + } +} diff --git a/Scripts/android/launcher/app/src/main/java/jp/cradle/link/ClientPackages.java b/Scripts/android/launcher/app/src/main/java/jp/cradle/link/ClientPackages.java new file mode 100644 index 00000000..e409874a --- /dev/null +++ b/Scripts/android/launcher/app/src/main/java/jp/cradle/link/ClientPackages.java @@ -0,0 +1,62 @@ +package jp.cradle.link; + +import java.util.Collection; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Which PGR region a package id belongs to. Store builds of one region differ only in the id (Google Play adds + * ".gplay.", JP's uses the herogame publisher), so the region is read from the id's suffix instead of a fixed list; + * the launcher picks whichever build is installed. Keep this pattern identical to Scripts/android/relay.py and + * Scripts/android/runtime/modctl.py, which also gate shell commands on it. + */ +final class ClientPackages { + private static final Pattern CLIENT = Pattern.compile( + "com\\.(?:kurogame|herogame)\\.(?:gplay\\.)?(?:punishing\\.grayraven\\.(en|jp|tw|kr)|haru\\.(?:kuro|hero))"); + + /** + * Builds the launcher looks for by name (Android 11+ hides apps that are not declared in the manifest's + * queries, so each must also appear there; tests keep the two in step). com.kurogame.gplay...en is the Google + * Play EN id; the JP herogame id comes from the existing JP support; the rest follow the same naming. + */ + static final String[] KNOWN_BUILDS = { + "com.kurogame.punishing.grayraven.en", + "com.kurogame.gplay.punishing.grayraven.en", + "com.herogame.gplay.punishing.grayraven.jp", + "com.kurogame.punishing.grayraven.jp", + "com.kurogame.punishing.grayraven.tw", + "com.kurogame.punishing.grayraven.kr", + "com.kurogame.haru.kuro", + }; + + private ClientPackages() { } + + /** "EN", "JP", "TW", "KR" or "CN", or null when the id is not a PGR client. */ + static String region(String packageName) { + if (packageName == null) return null; + Matcher match = CLIENT.matcher(packageName); + if (!match.matches()) return null; + String code = match.group(1); + return code == null ? "CN" : code.toUpperCase(java.util.Locale.ROOT); + } + + /** The installed build to use for a region: the canonical id when installed, else the first other build, else the canonical id. */ + static String choose(String region, Collection installed, String canonical) { + if (installed.contains(canonical)) return canonical; + String best = null; + for (String candidate : installed) { + if (region.equals(region(candidate)) && (best == null || candidate.compareTo(best) < 0)) best = candidate; + } + return best != null ? best : canonical; + } + + /** Index of the first region in {@code regions} that has an installed build, or -1. */ + static int detect(String[] regions, Collection installed) { + for (int index = 0; index < regions.length; index++) { + for (String candidate : installed) { + if (regions[index].equals(region(candidate))) return index; + } + } + return -1; + } +} diff --git a/Scripts/android/launcher/app/src/main/java/jp/cradle/link/Dependencies.java b/Scripts/android/launcher/app/src/main/java/jp/cradle/link/Dependencies.java new file mode 100644 index 00000000..7eed048a --- /dev/null +++ b/Scripts/android/launcher/app/src/main/java/jp/cradle/link/Dependencies.java @@ -0,0 +1,81 @@ +package jp.cradle.link; + +import java.util.List; +import java.util.regex.Pattern; + +/** + * The other apps the launcher needs, and how to pick their APK from a GitHub release. Repositories and asset + * names are fixed here (not a setting) so a release can only offer the app it is meant for; the package id of + * whatever is downloaded is checked again before installing. + */ +final class Dependencies { + enum Kind { + /** Runs the server. Only the arm64 GitHub build: the launcher itself needs an ARM64 phone. */ + // The stable release publishes " " lines in termux-app_+github-debug_sha256sums. Pre-releases + // add apt-android-5 (Android 5/6) and apt-android-7 variants; this launcher needs Android 10+, so never apt-android-5. + TERMUX("Termux", "com.termux", "termux/termux-app", + Pattern.compile("(?!.*apt-android-5)termux-app_v[0-9A-Za-z._+-]+github-debug_arm64-v8a\\.apk"), + Pattern.compile("termux-app_v[0-9A-Za-z._+-]+github-debug_sha256sums")), + /** Lets Mod commands run with shell rights; only needed for client mods. */ + // Its releases publish no checksum file, so the APK is only checked for its package id. + SHIZUKU("Shizuku", "moe.shizuku.privileged.api", "RikkaApps/Shizuku", + Pattern.compile("shizuku-v[0-9A-Za-z._-]+-release\\.apk"), null); + + final String title; + final String packageName; + final String repository; + final Pattern asset; + /** Name of the release's checksum file, or null when it publishes none. */ + final Pattern checksum; + + Kind(String title, String packageName, String repository, Pattern asset, Pattern checksum) { + this.title = title; + this.packageName = packageName; + this.repository = repository; + this.asset = asset; + this.checksum = checksum; + } + + /** The page to fall back to when an automatic download is not possible. */ + String releasesPage() { + return "https://github.com/" + repository + "/releases/latest"; + } + } + + private Dependencies() { } + + static final class Download { + final UpdateChecker.Asset apk; + /** From the same release as {@link #apk}; null only for a kind that publishes no checksums. */ + final UpdateChecker.Asset checksum; + + Download(UpdateChecker.Asset apk, UpdateChecker.Asset checksum) { + this.apk = apk; + this.checksum = checksum; + } + } + + /** + * The first published release that has the dependency's APK (and its checksum file, when the kind has one), both + * served from the dependency's own repository; null if none. + */ + static Download pick(Kind kind, List releases) { + String prefix = "https://github.com/" + kind.repository + "/releases/download/"; + for (UpdateChecker.ReleaseInfo release : releases) { + if (release.draft || release.prerelease) continue; + UpdateChecker.Asset apk = find(release, kind.asset, prefix); + if (apk == null) continue; + if (kind.checksum == null) return new Download(apk, null); + UpdateChecker.Asset checksum = find(release, kind.checksum, prefix); + if (checksum != null) return new Download(apk, checksum); + } + return null; + } + + private static UpdateChecker.Asset find(UpdateChecker.ReleaseInfo release, Pattern name, String prefix) { + for (UpdateChecker.Asset asset : release.assets) { + if (name.matcher(asset.name).matches() && asset.url.startsWith(prefix) && UpdateChecker.isTrustedUrl(asset.url)) return asset; + } + return null; + } +} diff --git a/Scripts/android/launcher/app/src/main/java/jp/cradle/link/GameProxyVpnService.java b/Scripts/android/launcher/app/src/main/java/jp/cradle/link/GameProxyVpnService.java new file mode 100644 index 00000000..df494f82 --- /dev/null +++ b/Scripts/android/launcher/app/src/main/java/jp/cradle/link/GameProxyVpnService.java @@ -0,0 +1,100 @@ +package jp.cradle.link; + +import android.app.Notification; +import android.app.NotificationChannel; +import android.app.NotificationManager; +import android.content.Intent; +import android.content.pm.ServiceInfo; +import android.net.ProxyInfo; +import android.net.VpnService; +import android.os.Build; +import android.os.IBinder; +import android.os.ParcelFileDescriptor; + +public final class GameProxyVpnService extends VpnService { + private static final String CHANNEL_ID = "cradle-link"; + private static GameProxyVpnService active; + private static String lastError; + private ParcelFileDescriptor tunnel; + + static boolean isConnected() { return active != null; } + static String takeError() { + String error = lastError; + lastError = null; + return error; + } + + static void disconnect() { + GameProxyVpnService service = active; + if (service == null) return; + service.closeTunnel(); + service.stopForeground(STOP_FOREGROUND_REMOVE); + service.stopSelf(); + } + + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + if (tunnel == null) { + try { + startForeground(1, notification(), ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE); + String gamePackage = intent == null ? "" : intent.getStringExtra("gamePackage"); + if (gamePackage == null || gamePackage.isBlank()) throw new IllegalArgumentException("Game package missing"); + tunnel = new Builder() + .setSession("Infinite Loop") + .addAddress("10.18.0.2", 32) + .addAllowedApplication(gamePackage) + .setHttpProxy(ProxyInfo.buildDirectProxy("127.0.0.1", 18084)) + .establish(); + if (tunnel != null) active = this; + else { + lastError = "RELAY_ESTABLISH: No tunnel returned"; + stopSelf(); + } + } catch (RuntimeException | android.content.pm.PackageManager.NameNotFoundException exception) { + lastError = "RELAY_START: " + exception.getClass().getSimpleName(); + stopSelf(); + } + } + return START_NOT_STICKY; + } + + private Notification notification() { + NotificationManager manager = getSystemService(NotificationManager.class); + manager.createNotificationChannel(new NotificationChannel(CHANNEL_ID, "Infinite Loop", NotificationManager.IMPORTANCE_LOW)); + return new Notification.Builder(this, CHANNEL_ID) + .setContentTitle("Infinite Loop") + .setContentText("Local relay active") + .setSmallIcon(android.R.drawable.stat_sys_warning) + .build(); + } + + @Override + public void onRevoke() { + closeTunnel(); + stopSelf(); + super.onRevoke(); + } + + @Override + public void onDestroy() { + closeTunnel(); + super.onDestroy(); + } + + private void closeTunnel() { + if (active == this) active = null; + if (tunnel != null) { + try { + tunnel.close(); + } catch (java.io.IOException exception) { + lastError = "RELAY_CLOSE: " + exception.getClass().getSimpleName(); + } + tunnel = null; + } + } + + @Override + public IBinder onBind(Intent intent) { + return super.onBind(intent); + } +} diff --git a/Scripts/android/launcher/app/src/main/java/jp/cradle/link/InstallResultReceiver.java b/Scripts/android/launcher/app/src/main/java/jp/cradle/link/InstallResultReceiver.java new file mode 100644 index 00000000..6b89041d --- /dev/null +++ b/Scripts/android/launcher/app/src/main/java/jp/cradle/link/InstallResultReceiver.java @@ -0,0 +1,69 @@ +package jp.cradle.link; + +import android.app.Notification; +import android.app.NotificationChannel; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageInstaller; +import android.widget.Toast; + +/** + * Receives the package installer's result for an app or dependency install. Not exported: only the PendingIntent + * that {@link AppUpdater} hands the installer can reach it, so no other app can make the launcher start an activity. + * + * Android's docs say the confirmation screen may be opened at once only if the user is actively using the app; + * otherwise guide them back with a notification. So: open it now when this app is on screen, else keep it and post a + * notification whose tap (or simply reopening the app) shows it. + */ +public final class InstallResultReceiver extends BroadcastReceiver { + private static final String CHANNEL = "install"; + private static volatile Intent pending; + + /** The confirmation screen that could not be opened while the app was in the background, if any. */ + static Intent takePending() { + Intent waiting = pending; + pending = null; + return waiting; + } + + @Override + @SuppressWarnings("deprecation") + public void onReceive(Context context, Intent intent) { + int status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE); + if (status == PackageInstaller.STATUS_PENDING_USER_ACTION) { + Intent confirm = intent.getParcelableExtra(Intent.EXTRA_INTENT); + if (confirm == null) return; + confirm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + if (MainActivity.foreground) { + context.startActivity(confirm); + } else { + pending = confirm; + notifyUser(context); + } + } else if (status == PackageInstaller.STATUS_FAILURE_INCOMPATIBLE) { + Toast.makeText(context, "Install refused: it is signed with a different key than the copy on this phone. " + + "Uninstall that copy first, then try again.", Toast.LENGTH_LONG).show(); + } else if (status != PackageInstaller.STATUS_SUCCESS && status != PackageInstaller.STATUS_FAILURE_ABORTED) { + String detail = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE); + Toast.makeText(context, "Install failed" + (detail == null ? "" : ": " + detail), Toast.LENGTH_LONG).show(); + } + } + + private static void notifyUser(Context context) { + NotificationManager manager = context.getSystemService(NotificationManager.class); + if (manager == null) return; + manager.createNotificationChannel(new NotificationChannel(CHANNEL, "Installs", NotificationManager.IMPORTANCE_DEFAULT)); + Intent open = new Intent(context, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); + PendingIntent tap = PendingIntent.getActivity(context, 1, open, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE); + manager.notify(2, new Notification.Builder(context, CHANNEL) + .setSmallIcon(android.R.drawable.stat_sys_download_done) + .setContentTitle("Infinite Loop") + .setContentText("Tap to finish installing") + .setContentIntent(tap) + .setAutoCancel(true) + .build()); + } +} diff --git a/Scripts/android/launcher/app/src/main/java/jp/cradle/link/LogExport.java b/Scripts/android/launcher/app/src/main/java/jp/cradle/link/LogExport.java new file mode 100644 index 00000000..e2f34c47 --- /dev/null +++ b/Scripts/android/launcher/app/src/main/java/jp/cradle/link/LogExport.java @@ -0,0 +1,140 @@ +package jp.cradle.link; + +import android.content.ContentResolver; +import android.database.Cursor; +import android.net.Uri; +import android.provider.DocumentsContract; + +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +final class LogExport { + static final int MAX_BYTES = 1 << 20; + + /** Heading, then the file names to look for; when several exist the most recently modified one is used. */ + private static final String[][] SOURCES = { + {"Server log", "start-cradle.log", "start-cradle.log.tmp"}, + {"Relay log", "relay.log"}, + {"MongoDB log", "mongodb.log"}, + {"Client log (logcat)", "client.log"}, + }; + + private LogExport() { } + + static final class Section { + final String title; + /** Null when the log does not exist. */ + final byte[] body; + + Section(String title, byte[] body) { + this.title = title; + this.body = body; + } + } + + static String write(ContentResolver resolver, Uri destination, Uri folder, String appEvents) { + List
sections = new ArrayList<>(); + Map documents = new HashMap<>(); + if (folder != null) { + try { + documents = list(resolver, folder); + } catch (Exception ignored) { } + } + for (String[] source : SOURCES) { + Document chosen = null; + for (int index = 1; index < source.length; index++) { + Document candidate = documents.get(source[index]); + if (candidate != null && (chosen == null || candidate.modified > chosen.modified)) chosen = candidate; + } + byte[] body = null; + if (chosen != null) { + try (InputStream in = resolver.openInputStream(DocumentsContract.buildDocumentUriUsingTree(folder, chosen.id))) { + if (in != null) body = tail(in, MAX_BYTES); + } catch (Exception ignored) { } + } + sections.add(new Section(source[0], body)); + } + + try (OutputStream out = resolver.openOutputStream(destination, "wt")) { + if (out == null) return "Log export failed"; + out.write(compose(appEvents, sections)); + boolean any = false; + for (Section section : sections) any |= section.body != null; + return any ? "Logs exported" : "App log exported"; + } catch (Exception ignored) { + return "Log export failed"; + } + } + + static byte[] compose(String appEvents, List
sections) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + write(out, "Infinite Loop diagnostics\n\nApp events\n" + appEvents + "\n"); + for (Section section : sections) { + write(out, "\n" + section.title + "\n"); + if (section.body == null) { + write(out, "Unavailable.\n"); + } else { + out.write(section.body, 0, section.body.length); + if (section.body.length == 0 || section.body[section.body.length - 1] != '\n') write(out, "\n"); + } + } + return out.toByteArray(); + } + + /** The last {@code max} bytes of the stream. */ + static byte[] tail(InputStream in, int max) throws java.io.IOException { + byte[] buffer = new byte[max * 2]; + int length = 0; + byte[] chunk = new byte[8192]; + int count; + while ((count = in.read(chunk)) != -1) { + if (length + count > buffer.length) { + int keep = Math.min(length, max); + System.arraycopy(buffer, length - keep, buffer, 0, keep); + length = keep; + } + System.arraycopy(chunk, 0, buffer, length, count); + length += count; + } + int size = Math.min(length, max); + byte[] result = new byte[size]; + System.arraycopy(buffer, length - size, result, 0, size); + return result; + } + + private static void write(ByteArrayOutputStream out, String text) { + byte[] bytes = text.getBytes(StandardCharsets.UTF_8); + out.write(bytes, 0, bytes.length); + } + + private static final class Document { + final String id; + final long modified; + + Document(String id, long modified) { + this.id = id; + this.modified = modified; + } + } + + private static Map list(ContentResolver resolver, Uri folder) { + Map documents = new HashMap<>(); + Uri children = DocumentsContract.buildChildDocumentsUriUsingTree(folder, + DocumentsContract.getTreeDocumentId(folder)); + String[] columns = {DocumentsContract.Document.COLUMN_DOCUMENT_ID, + DocumentsContract.Document.COLUMN_DISPLAY_NAME, + DocumentsContract.Document.COLUMN_LAST_MODIFIED}; + try (Cursor cursor = resolver.query(children, columns, null, null, null)) { + while (cursor != null && cursor.moveToNext()) { + documents.put(cursor.getString(1), new Document(cursor.getString(0), cursor.getLong(2))); + } + } + return documents; + } +} diff --git a/Scripts/android/launcher/app/src/main/java/jp/cradle/link/MainActivity.java b/Scripts/android/launcher/app/src/main/java/jp/cradle/link/MainActivity.java new file mode 100644 index 00000000..e839fe99 --- /dev/null +++ b/Scripts/android/launcher/app/src/main/java/jp/cradle/link/MainActivity.java @@ -0,0 +1,1122 @@ +package jp.cradle.link; + +import android.app.Activity; +import android.app.PendingIntent; +import android.content.ClipData; +import android.content.ClipboardManager; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.pm.PackageManager; +import android.content.pm.ResolveInfo; +import android.provider.Settings; +import android.net.VpnService; +import android.net.Uri; +import android.os.Bundle; +import android.os.Handler; +import android.os.Looper; +import android.os.SystemClock; +import android.view.Gravity; +import android.view.View; +import android.widget.Button; +import android.widget.ArrayAdapter; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.Spinner; +import android.widget.Switch; +import android.widget.TextView; +import android.widget.Toast; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +public final class MainActivity extends Activity { + private static final int VPN_REQUEST = 10; + private static final int TERMUX_PERMISSION_REQUEST = 11; + private static final int TERMUX_STOP_PERMISSION_REQUEST = 12; + private static final int LOG_FOLDER_REQUEST = 13; + private static final int EXPORT_LOG_REQUEST = 14; + private static final int TERMUX_MOD_PERMISSION_REQUEST = 15; + private static final int TERMUX_UPDATE_PERMISSION_REQUEST = 16; + private static final String TERMUX_PACKAGE = "com.termux"; + private static final String TERMUX_RUN_PERMISSION = "com.termux.permission.RUN_COMMAND"; + private static final String SETUP_PATH = "/data/data/com.termux/files/home/.local/share/infinite-loop/setup.sh"; + private static final long START_TIMEOUT_MS = 120_000; + private static final long PROBE_INTERVAL_MS = 2_000; + private static final int[] SERVICE_PORTS = {27017, 8080, 2335, 18084}; + private static final String[] SERVICE_NAMES = {"MongoDB", "SDK", "Game", "Relay"}; + private static final RegionProfile[] REGIONS = { + new RegionProfile("EN", "com.kurogame.punishing.grayraven.en"), + new RegionProfile("JP", "com.herogame.gplay.punishing.grayraven.jp"), + new RegionProfile("TW", "com.kurogame.punishing.grayraven.tw"), + new RegionProfile("KR", "com.kurogame.punishing.grayraven.kr"), + new RegionProfile("CN", "com.kurogame.haru.kuro") + }; + private boolean updateChecking; + private final ExecutorService executor = Executors.newSingleThreadExecutor(); + // Network I/O for app updates must not queue behind (or hold up) the service probes on `executor`. + private final ExecutorService updateExecutor = Executors.newSingleThreadExecutor(); + private final Handler ui = new Handler(Looper.getMainLooper()); + private final Runnable probe = this::checkServices; + private final Runnable updateVpnButton = this::refreshVpnButton; + private TextView state; + private TextView errorState; + private Button start; + private Button updateRuntime; + private TextView updateNotice; + private Button updateApp; + private String availableTag; + /** True while the activity is on screen; lets the install receiver decide whether it may open a screen now. */ + static volatile boolean foreground; + private Button wizard; + private Button skipSetup; + private LinearLayout rootLayout; + private LinearLayout mainControls; + private Button installShizuku; + private boolean dependencyBusy; + private String dependencyStatus = ""; + private TextView wizardHint; + private SetupFlow.Step wizardStep = SetupFlow.Step.BUSY; + private int playStep; // 0 idle, 1 waiting for the server, 2 waiting for the relay + private boolean playSawStart; + private static final int WIZARD_PERMISSION_REQUEST = 17; + private int updatePhase; + private Button vpn; + private Switch gmToggle; + private Switch luaToggle; + private Button applyMods; + private ModSelection pendingModSelection; + private boolean collectingClientLog; + private static final long CLIENT_LOG_TIMEOUT_MS = 60_000; + private int selectedRegionIndex = 1; + private Spinner playerSelector; + private final List playerNames = new ArrayList<>(); + private String playerCurrent = ""; + private boolean playerSynced; + private boolean playerSyncing; + private boolean visible; + private boolean probing; + private long startDeadline; + private boolean stopping; + private int onlineServices = -1; + private boolean vpnConnected; + private boolean relayAvailable; + private final ArrayDeque recentLog = new ArrayDeque<>(); + private Uri logFolder; + + private static final class RegionProfile { + final String name; + final String packageName; + RegionProfile(String name, String packageName) { + this.name = name; + this.packageName = packageName; + } + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + if (savedInstanceState != null) { + selectedRegionIndex = savedInstanceState.getInt("region", 1); + startDeadline = savedInstanceState.getLong("startDeadline"); + stopping = savedInstanceState.getBoolean("stopping"); + updatePhase = savedInstanceState.getInt("updatePhase"); + } else { + String[] names = new String[REGIONS.length]; + for (int index = 0; index < REGIONS.length; index++) names[index] = REGIONS[index].name; + int detected = ClientPackages.detect(names, installedClients()); + if (detected >= 0) selectedRegionIndex = detected; + } + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setPadding(48, 56, 48, 48); + root.setGravity(Gravity.CENTER_HORIZONTAL); + rootLayout = root; + + TextView title = text("Infinite Loop", 28); + root.addView(title); + wizard = new Button(this); + wizard.setTextSize(18); + wizard.setOnClickListener(view -> onWizard()); + root.addView(wizard); + wizardHint = text("", 14); + root.addView(wizardHint); + skipSetup = new Button(this); + skipSetup.setText("Skip setup"); + skipSetup.setOnClickListener(view -> { + getSharedPreferences("setup", MODE_PRIVATE).edit().putBoolean("setupSkipped", true).apply(); + refreshWizard(); + }); + root.addView(skipSetup); + errorState = text("", 14); + errorState.setVisibility(View.GONE); + root.addView(errorState); + LinearLayout main = new LinearLayout(this); + main.setOrientation(LinearLayout.VERTICAL); + main.setGravity(Gravity.CENTER_HORIZONTAL); + mainControls = main; + Spinner regionSelector = new Spinner(this); + String[] labels = new String[REGIONS.length]; + for (int index = 0; index < REGIONS.length; index++) labels[index] = REGIONS[index].name; + regionSelector.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, labels)); + regionSelector.setSelection(selectedRegionIndex); + regionSelector.setOnItemSelectedListener(new android.widget.AdapterView.OnItemSelectedListener() { + @Override public void onItemSelected(android.widget.AdapterView parent, View view, int position, long id) { + selectedRegionIndex = position; + if (wizard != null) refreshWizard(); + } + @Override public void onNothingSelected(android.widget.AdapterView parent) { } + }); + main.addView(regionSelector); + playerSelector = new Spinner(this); + playerSelector.setVisibility(View.GONE); + playerSelector.setOnItemSelectedListener(new android.widget.AdapterView.OnItemSelectedListener() { + @Override public void onItemSelected(android.widget.AdapterView parent, View view, int position, long id) { + if (position < 0 || position >= playerNames.size() || playerNames.get(position).equals(playerCurrent)) return; + selectPlayer(playerNames.get(position)); + } + @Override public void onNothingSelected(android.widget.AdapterView parent) { } + }); + main.addView(playerSelector); + state = text("Checking…", 16); + main.addView(state); + updateNotice = text("", 14); + updateNotice.setVisibility(View.GONE); + main.addView(updateNotice); + updateApp = new Button(this); + updateApp.setVisibility(View.GONE); + updateApp.setOnClickListener(view -> installAppUpdate()); + main.addView(updateApp); + updateRuntime = new Button(this); + updateRuntime.setVisibility(View.GONE); + updateRuntime.setOnClickListener(view -> requestRuntimeUpdate()); + main.addView(updateRuntime); + showAvailableUpdate(); + + start = new Button(this); + start.setText("Start Server"); + start.setEnabled(false); + start.setOnClickListener(view -> runTermuxStack(onlineServices > 0)); + main.addView(start); + + vpn = new Button(this); + vpn.setVisibility(View.GONE); + vpn.setOnClickListener(view -> { + if (GameProxyVpnService.isConnected()) { + GameProxyVpnService.disconnect(); + } else { + prepareVpn(); + } + }); + main.addView(vpn); + + LinearLayout mods = new LinearLayout(this); + mods.setOrientation(LinearLayout.VERTICAL); + mods.setPadding(24, 16, 24, 16); + android.graphics.drawable.GradientDrawable frame = new android.graphics.drawable.GradientDrawable(); + frame.setStroke(2, 0x66888888); + frame.setCornerRadius(16); + mods.setBackground(frame); + mods.addView(text("MODs", 14)); + SharedPreferences modPreferences = getSharedPreferences("client-mods", MODE_PRIVATE); + gmToggle = new Switch(this); + gmToggle.setText("GM Menu"); + gmToggle.setChecked(modPreferences.getBoolean("gm", true)); + mods.addView(gmToggle); + luaToggle = new Switch(this); + luaToggle.setText("Lua Mods"); + luaToggle.setChecked(modPreferences.getBoolean("lua", false)); + mods.addView(luaToggle); + View.OnClickListener saveModSelection = view -> { + modPreferences.edit().putBoolean("gm", gmToggle.isChecked()).putBoolean("lua", luaToggle.isChecked()).apply(); + applyMods.setText("Apply Mods"); + }; + gmToggle.setOnClickListener(saveModSelection); + luaToggle.setOnClickListener(saveModSelection); + applyMods = new Button(this); + applyMods.setText("Apply Mods"); + applyMods.setOnClickListener(view -> runTermuxMods(new ModSelection(gmToggle.isChecked(), luaToggle.isChecked()))); + mods.addView(applyMods); + installShizuku = new Button(this); + installShizuku.setText("Install Shizuku (needed for Mods)"); + installShizuku.setOnClickListener(view -> installDependency(Dependencies.Kind.SHIZUKU)); + mods.addView(installShizuku); + main.addView(mods, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.WRAP_CONTENT)); + root.addView(main, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.WRAP_CONTENT)); + + Button exportLogs = new Button(this); + exportLogs.setText("Export Logs"); + exportLogs.setOnClickListener(view -> exportLogs()); + root.addView(exportLogs); + + ScrollView scroll = new ScrollView(this); + scroll.setFillViewport(true); + scroll.addView(root); + setContentView(scroll); + refreshWizard(); + if (updatePhase != 0) refreshServerButton(); + handleTermuxResult(getIntent()); + } + + private TextView text(String value, int size) { + TextView view = new TextView(this); + view.setText(value); + view.setTextSize(size); + view.setPadding(0, 18, 0, 18); + return view; + } + + private void checkServices() { + ui.removeCallbacks(probe); + if (!visible || probing) return; + probing = true; + executor.execute(() -> { + int online = 0; + StringBuilder details = new StringBuilder(); + for (int i = 0; i < SERVICE_PORTS.length; i++) { + boolean up = reachable("127.0.0.1", SERVICE_PORTS[i]); + if (up) online++; + if (i > 0) details.append('\n'); + details.append(SERVICE_NAMES[i]).append(": ").append(up ? "Online" : "Offline"); + } + int count = online; + boolean relay = reachable("127.0.0.1", 18084); + ui.post(() -> { + relayAvailable = relay; + showProgress(count, details.toString()); + }); + }); + } + + private void showProgress(int online, String details) { + probing = false; + if (!visible) return; + if (onlineServices != online) record("Services: " + online + "/" + SERVICE_PORTS.length + " online"); + onlineServices = online; + int total = SERVICE_PORTS.length; + if (online != total) { + playerSynced = false; + playerSelector.setVisibility(View.GONE); + } else if (!playerSynced && !playerSyncing) { + syncPlayers(); + } + if (updatePhase == 1) { + if (online == 0) { dispatchRuntimeUpdate(); return; } + updatePhase = 2; + runTermuxStack(true); + if (startDeadline == 0) finishRuntimeUpdate(false, "Could not stop server"); + return; + } + boolean ready = online == total; + boolean finished = startDeadline != 0 && (stopping ? online == 0 : ready); + boolean timedOut = startDeadline != 0 && !finished && SystemClock.elapsedRealtime() >= startDeadline; + if (timedOut) { + reportError(stopping ? "SERVER_STOP_TIMEOUT" : "SERVER_START_TIMEOUT", details.replace('\n', ';')); + } + if (finished || timedOut) startDeadline = 0; + if (updatePhase == 2 && (finished || timedOut)) { + if (timedOut) finishRuntimeUpdate(false, "Server stop timed out"); + else dispatchRuntimeUpdate(); + return; + } + if (updatePhase == 3) { + state.setText("Updating runtime…"); + return; + } + String label = timedOut ? "Timed out" : startDeadline != 0 ? (stopping ? "Stopping…" : "Starting…") + : ready ? "Running" : online == 0 ? "Stopped" : "Services"; + state.setText(label + " · " + online + "/" + total + " online"); + refreshServerButton(); + advancePlay(); + if (startDeadline != 0) ui.postDelayed(probe, PROBE_INTERVAL_MS); + } + + /** Fills the account list from the running server and switches it to the account chosen earlier. */ + private void syncPlayers() { + playerSyncing = true; + updateExecutor.execute(() -> { + List names = new ArrayList<>(); + String current = ""; + String failure = null; + try { + PlayerAccounts.Listing listing = PlayerAccounts.list(); + String wanted = PlayerAccounts.pending(listing, getSharedPreferences("play", MODE_PRIVATE).getString("user", null)); + if (wanted != null) PlayerAccounts.select(wanted); + names = listing.users; + current = wanted != null ? wanted : listing.current; + } catch (java.io.IOException error) { + failure = String.valueOf(error.getMessage()); + } + List shown = names; + String active = current; + String problem = failure; + ui.post(() -> { + playerSyncing = false; + playerSynced = true; + if (problem != null) { + record("Accounts unavailable: " + problem); + } else { + playerNames.clear(); + playerNames.addAll(shown); + playerCurrent = active; + playerSelector.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, playerNames)); + int index = playerNames.indexOf(active); + if (index >= 0) playerSelector.setSelection(index); + playerSelector.setVisibility(playerNames.size() > 1 ? View.VISIBLE : View.GONE); + } + advancePlay(); + }); + }); + } + + private void selectPlayer(String username) { + playerCurrent = username; + getSharedPreferences("play", MODE_PRIVATE).edit().putString("user", username).apply(); + updateExecutor.execute(() -> { + try { + PlayerAccounts.select(username); + ui.post(() -> record("Account: " + username)); + } catch (java.io.IOException error) { + ui.post(() -> reportError("ACCOUNT_SELECT", String.valueOf(error.getMessage()))); + } + }); + } + + private void refreshServerButton() { + start.setEnabled(startDeadline == 0 && updatePhase == 0); + boolean runtimeOutdated = getSharedPreferences("setup", MODE_PRIVATE).getBoolean("runtimeInstalled", false) + && !currentVersion().equals(getSharedPreferences("setup", MODE_PRIVATE).getString("runtimeVersion", "")); + updateRuntime.setText("Update server to " + currentVersion()); + updateRuntime.setVisibility(runtimeOutdated && updatePhase == 0 ? View.VISIBLE : View.GONE); + updateRuntime.setEnabled(startDeadline == 0 && updatePhase == 0); + applyMods.setEnabled(updatePhase == 0); + start.setText(startDeadline != 0 ? (stopping ? "Stopping…" : "Starting…") + : onlineServices > 0 ? "Stop Server" : "Start Server"); + refreshWizard(); + } + + private void refreshVpnButton() { + String failure = GameProxyVpnService.takeError(); + if (failure != null) reportError("RELAY", failure); + boolean connected = GameProxyVpnService.isConnected(); + if (vpnConnected != connected) record(connected ? "Relay connected" : "Relay stopped"); + vpnConnected = connected; + vpn.setText(connected ? "Stop Relay" : "Start Relay"); + vpn.setVisibility(connected || relayAvailable ? View.VISIBLE : View.GONE); + advancePlay(); + if (visible) ui.postDelayed(updateVpnButton, 500); + } + + private RegionProfile selectedRegion() { + return REGIONS[selectedRegionIndex]; + } + + private boolean reachable(String host, int port) { + try (Socket socket = new Socket()) { + socket.connect(new InetSocketAddress(host, port), 1200); + return true; + } catch (Exception ignored) { + return false; + } + } + + /** Every installed PGR client build: any launchable app whose id looks like one, plus each region's canonical id. */ + private List installedClients() { + List found = new ArrayList<>(); + Intent launcher = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER); + for (ResolveInfo info : getPackageManager().queryIntentActivities(launcher, 0)) { + String name = info.activityInfo.packageName; + if (ClientPackages.region(name) != null && !found.contains(name)) found.add(name); + } + for (String build : ClientPackages.KNOWN_BUILDS) { + if (!found.contains(build) && installed(build)) found.add(build); + } + return found; + } + + /** The package of the build of this region that is installed (Google Play and store builds differ in id). */ + private String clientPackage(RegionProfile region) { + return ClientPackages.choose(region.name, installedClients(), region.packageName); + } + + private String currentVersion() { + try { + String version = getPackageManager().getPackageInfo(getPackageName(), 0).versionName; + return version == null ? "0" : version; + } catch (PackageManager.NameNotFoundException ignored) { + return "0"; + } + } + + /** Shows the update remembered from the last check, if it is still newer than the installed version. */ + private void showAvailableUpdate() { + String tag = getSharedPreferences("app-update", MODE_PRIVATE).getString("availableTag", null); + String version = UpdateChecker.versionOfTag(tag); + String current = currentVersion(); + boolean newer = version != null && UpdateChecker.compare(version, current) > 0; + availableTag = newer ? tag : null; + updateNotice.setVisibility(newer ? View.VISIBLE : View.GONE); + updateApp.setVisibility(newer ? View.VISIBLE : View.GONE); + updateApp.setEnabled(newer); + if (newer) { + updateNotice.setText("Update available: " + version + " (installed " + current + ")"); + updateApp.setText("Download and install " + version); + } + } + + /** Every time the app is opened, asks GitHub Releases whether a newer launcher exists and remembers the answer. */ + private void checkAppUpdate() { + if (updateChecking) return; + updateChecking = true; + SharedPreferences preferences = getSharedPreferences("app-update", MODE_PRIVATE); + String repository = getString(R.string.update_repository); + String current = currentVersion(); + updateExecutor.execute(() -> { + try { + String tag = AppUpdater.check(repository, current); + preferences.edit().putString("availableTag", tag).apply(); + ui.post(() -> { + updateChecking = false; + showAvailableUpdate(); + }); + } catch (Exception exception) { + ui.post(() -> { + updateChecking = false; + record("Update check failed: " + exception.getClass().getSimpleName()); + }); + } + }); + } + + private void installAppUpdate() { + String tag = availableTag; + if (tag == null) return; + if (!getPackageManager().canRequestPackageInstalls()) { + Toast.makeText(this, "Allow installing apps from Infinite Loop, then tap again", Toast.LENGTH_LONG).show(); + startActivity(new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + getPackageName()))); + return; + } + updateApp.setEnabled(false); + updateApp.setText("Downloading…"); + String repository = getString(R.string.update_repository); + updateExecutor.execute(() -> { + try { + File apk = AppUpdater.download(this, repository, tag); + PendingIntent result = PendingIntent.getBroadcast(this, 0, new Intent(this, InstallResultReceiver.class), + PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE); + AppUpdater.install(this, apk, result); + record("Update " + tag + " handed to the installer"); + } catch (Exception exception) { + ui.post(() -> reportError("APP_UPDATE", exception.getClass().getSimpleName() + ": " + exception.getMessage())); + } + ui.post(this::showAvailableUpdate); + }); + } + + /** Recomputes the wizard's single next action from what is installed and granted. */ + private void refreshWizard() { + if (wizard == null) return; + SharedPreferences setup = getSharedPreferences("setup", MODE_PRIVATE); + boolean serverUp = onlineServices > 0; + SetupFlow.State current = new SetupFlow.State(); + current.termuxInstalled = installed(TERMUX_PACKAGE); + current.termuxPermission = checkSelfPermission(TERMUX_RUN_PERMISSION) == PackageManager.PERMISSION_GRANTED; + current.termuxReady = serverUp || setup.getBoolean("termuxReady", false); + current.bootstrapOpened = setup.getBoolean("bootstrapOpened", false); + current.runtimeInstalled = serverUp || setup.getBoolean("runtimeInstalled", false); + current.clientInstalled = installed(clientPackage(selectedRegion())); + current.busy = updatePhase != 0 || startDeadline != 0; + current.playing = playStep != 0; + wizardStep = SetupFlow.next(current); + boolean fullScreen = SetupFlow.setupPending(current) && !setup.getBoolean("setupSkipped", false); + if (mainControls != null) { + mainControls.setVisibility(fullScreen ? View.GONE : View.VISIBLE); + skipSetup.setVisibility(fullScreen ? View.VISIBLE : View.GONE); + skipSetup.setEnabled(updatePhase == 0 && !dependencyBusy); + rootLayout.setGravity(fullScreen ? Gravity.CENTER : Gravity.CENTER_HORIZONTAL); + wizard.setTextSize(fullScreen ? 22 : 18); + } + wizard.setText(wizardStep.label); + wizard.setEnabled(wizardStep.enabled); + wizardHint.setText(wizardStep.hint); + if (dependencyBusy) { + wizardStep = SetupFlow.Step.BUSY; + wizard.setText(dependencyStatus); + wizard.setEnabled(false); + wizardHint.setText(SetupFlow.Step.BUSY.hint); + } + if (installShizuku != null) { + boolean missing = !installed(Dependencies.Kind.SHIZUKU.packageName); + installShizuku.setVisibility(missing ? View.VISIBLE : View.GONE); + installShizuku.setEnabled(!dependencyBusy); + } + } + + /** Downloads Termux or Shizuku and hands it to the system installer, which asks the user to confirm. */ + private void installDependency(Dependencies.Kind kind) { + if (dependencyBusy) return; + if (!getPackageManager().canRequestPackageInstalls()) { + Toast.makeText(this, "Allow installing apps from Infinite Loop, then tap again", Toast.LENGTH_LONG).show(); + startActivity(new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + getPackageName()))); + return; + } + dependencyBusy = true; + dependencyStatus = "Downloading " + kind.title + "…"; + refreshWizard(); + updateExecutor.execute(() -> { + try { + File apk = AppUpdater.downloadDependency(this, kind, bytes -> ui.post(() -> { + dependencyStatus = "Downloading " + kind.title + " · " + (bytes >> 20) + " MB"; + refreshWizard(); + })); + PendingIntent result = PendingIntent.getBroadcast(this, 0, new Intent(this, InstallResultReceiver.class), + PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE); + AppUpdater.install(this, apk, kind.packageName, result); + record(kind.title + " handed to the installer"); + } catch (Exception exception) { + ui.post(() -> { + reportError("DEPENDENCY", kind.title + ": " + exception.getClass().getSimpleName()); + Toast.makeText(this, "Download failed. Opening the " + kind.title + " download page", Toast.LENGTH_LONG).show(); + startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(kind.releasesPage()))); + }); + } + ui.post(() -> { + dependencyBusy = false; + refreshWizard(); + }); + }); + } + + private void onWizard() { + switch (wizardStep) { + case TERMUX_MISSING: + installDependency(Dependencies.Kind.TERMUX); + break; + case TERMUX_PERMISSION: + requestPermissions(new String[] {TERMUX_RUN_PERMISSION}, WIZARD_PERMISSION_REQUEST); + break; + case TERMUX_BOOTSTRAP: { + ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); + clipboard.setPrimaryClip(ClipData.newPlainText("Termux command", SetupFlow.BOOTSTRAP_COMMAND)); + getSharedPreferences("setup", MODE_PRIVATE).edit().putBoolean("bootstrapOpened", true).apply(); + Toast.makeText(this, "Copied. Paste it in Termux and press Enter", Toast.LENGTH_LONG).show(); + Intent termux = getPackageManager().getLaunchIntentForPackage(TERMUX_PACKAGE); + if (termux != null) startActivity(termux); + refreshWizard(); + break; + } + case TERMUX_CONFIRM: + case RUNTIME: + requestRuntimeUpdate(); + break; + case PLAY: + case CANCEL: + togglePlay(); + break; + default: + break; + } + } + + /** PLAY: start the server if needed, then the relay, then open the game; tapping again cancels. */ + private void togglePlay() { + if (playStep != 0) { + playStep = 0; + refreshWizard(); + return; + } + if (updatePhase != 0 || startDeadline != 0) return; + if (onlineServices < 0) { + checkServices(); + return; + } + playStep = 1; + playSawStart = false; + if (onlineServices != SERVICE_PORTS.length) runTermuxStack(false); + refreshWizard(); + advancePlay(); + } + + private void advancePlay() { + if (playStep == 0 || updatePhase != 0) return; + if (startDeadline != 0) { + playSawStart = true; + return; + } + if (playStep == 1) { + if (onlineServices == SERVICE_PORTS.length) { + if (!playerSynced) return; // the chosen account must be in place before the game signs in + playStep = 2; + if (!GameProxyVpnService.isConnected()) { + prepareVpn(); + return; + } + } else if (playSawStart) { + // The start ended without every service online; the error is already on screen. + playStep = 0; + refreshWizard(); + return; + } else { + return; + } + } + if (playStep == 2 && GameProxyVpnService.isConnected()) { + playStep = 0; + launchGame(); + refreshWizard(); + } + } + + private void launchGame() { + Intent launch = getPackageManager().getLaunchIntentForPackage(clientPackage(selectedRegion())); + if (launch == null) { + reportError("LAUNCH", "Game cannot be opened"); + return; + } + record("Launching game"); + startActivity(launch); + } + + private boolean installed(String packageName) { + try { + getPackageManager().getApplicationInfo(packageName, 0); + return true; + } catch (PackageManager.NameNotFoundException ignored) { + return false; + } + } + + private void runTermuxStack(boolean stopRequested) { + if (startDeadline != 0) return; + if (!installed(TERMUX_PACKAGE)) { + reportError("TERMUX_MISSING", "Termux not installed"); + return; + } + if (checkSelfPermission(TERMUX_RUN_PERMISSION) != PackageManager.PERMISSION_GRANTED) { + requestPermissions(new String[] { TERMUX_RUN_PERMISSION }, + stopRequested ? TERMUX_STOP_PERMISSION_REQUEST : TERMUX_PERMISSION_REQUEST); + return; + } + Intent command = new Intent("com.termux.RUN_COMMAND"); + command.setClassName(TERMUX_PACKAGE, "com.termux.app.RunCommandService"); + command.putExtra("com.termux.RUN_COMMAND_PATH", "/data/data/com.termux/files/usr/bin/bash"); + command.putExtra("com.termux.RUN_COMMAND_ARGUMENTS", new String[] { + "/data/data/com.termux/files/home/.local/share/infinite-loop/setup.sh", + stopRequested ? "stop" : "start" + }); + command.putExtra("com.termux.RUN_COMMAND_BACKGROUND", true); + command.putExtra("com.termux.RUN_COMMAND_LABEL", "Infinite Loop"); + command.putExtra("com.termux.RUN_COMMAND_DESCRIPTION", stopRequested ? "Stops the local server." : "Starts the local server."); + try { + if (startForegroundService(command) == null) { + reportError("TERMUX_SERVICE", "Termux service not found"); + return; + } + startDeadline = SystemClock.elapsedRealtime() + START_TIMEOUT_MS; + stopping = stopRequested; + record(stopping ? "Server stop requested" : "Server start requested"); + refreshServerButton(); + state.setText(stopping ? "Stopping…" : "Starting…"); + checkServices(); + } catch (SecurityException exception) { + reportError("TERMUX_PERMISSION", exception.getClass().getSimpleName()); + } catch (IllegalStateException exception) { + reportError("TERMUX_START_BLOCKED", exception.getClass().getSimpleName()); + } + } + + private void requestRuntimeUpdate() { + if (updatePhase != 0 || startDeadline != 0) return; + if (!installed(TERMUX_PACKAGE)) { + reportError("TERMUX_MISSING", "Termux not installed"); + return; + } + if (checkSelfPermission(TERMUX_RUN_PERMISSION) != PackageManager.PERMISSION_GRANTED) { + requestPermissions(new String[] {TERMUX_RUN_PERMISSION}, TERMUX_UPDATE_PERMISSION_REQUEST); + return; + } + updatePhase = 1; + state.setText("Checking server…"); + refreshServerButton(); + checkServices(); + } + + private void dispatchRuntimeUpdate() { + // The runtime ships in the same release as this app, so its tag is derived from the installed version. + String repository = getString(R.string.update_repository); + String tag = UpdateChecker.TAG_PREFIX + currentVersion(); + String[] arguments; + try (InputStream script = getAssets().open("update-runtime.sh")) { + if (!UpdateChecker.validRepository(repository) || UpdateChecker.versionOfTag(tag) == null) { + throw new IOException("Invalid update source"); + } + java.io.ByteArrayOutputStream text = new java.io.ByteArrayOutputStream(); + byte[] buffer = new byte[4096]; + for (int count; (count = script.read(buffer)) > 0; ) text.write(buffer, 0, count); + arguments = ModSelection.runtimeUpdateArguments(new String(text.toByteArray(), StandardCharsets.UTF_8), repository, tag); + } catch (IOException exception) { + updatePhase = 3; + finishRuntimeUpdate(false, exception.getMessage()); + return; + } + updatePhase = 3; + startDeadline = 0; + state.setText("Updating runtime to " + currentVersion() + "…"); + refreshServerButton(); + Intent command = new Intent("com.termux.RUN_COMMAND"); + command.setClassName(TERMUX_PACKAGE, "com.termux.app.RunCommandService"); + command.putExtra("com.termux.RUN_COMMAND_PATH", "/data/data/com.termux/files/usr/bin/bash"); + command.putExtra("com.termux.RUN_COMMAND_ARGUMENTS", arguments); + command.putExtra("com.termux.RUN_COMMAND_BACKGROUND", true); + Intent result = new Intent(this, MainActivity.class); + result.setAction("jp.cradle.link.UPDATE_RESULT"); + PendingIntent pending = PendingIntent.getActivity(this, (int) (SystemClock.elapsedRealtime() & 0x7fffffff), + result, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_MUTABLE); + command.putExtra("com.termux.RUN_COMMAND_PENDING_INTENT", pending); + try { + if (startForegroundService(command) == null) finishRuntimeUpdate(false, "Termux service not found"); + } catch (SecurityException | IllegalStateException exception) { + finishRuntimeUpdate(false, exception.toString()); + } + } + + private void finishRuntimeUpdate(boolean success, String detail) { + updatePhase = 0; + startDeadline = 0; + SharedPreferences setup = getSharedPreferences("setup", MODE_PRIVATE); + if (success) { + setup.edit().putBoolean("termuxReady", true).putBoolean("runtimeInstalled", true) + .putString("runtimeVersion", currentVersion()).apply(); + } else if (!setup.getBoolean("termuxReady", false)) { + // Termux may still refuse commands: send the wizard back to the one-line command. + setup.edit().putBoolean("bootstrapOpened", false).apply(); + } + refreshServerButton(); + if (success) { + errorState.setVisibility(View.GONE); + state.setText("Runtime updated"); + record("Runtime update completed"); + } else { + state.setText("Update failed"); + reportError("UPDATE_FAILED", detail + " · Export Logs"); + } + if (ModSelection.restartAfterRuntimeUpdate(success)) runTermuxStack(false); + else if (success) checkServices(); + } + + private void runTermuxMods(ModSelection selection) { + if ((selection.gm || selection.lua) + && (onlineServices != SERVICE_PORTS.length || !GameProxyVpnService.isConnected())) { + reportError("MOD_SERVER", "Start Server and Relay before applying MODs"); + return; + } + RegionProfile region = selectedRegion(); + String gamePackage = clientPackage(region); + if (!installed(gamePackage)) { + reportError("MOD_CLIENT", region.name + " client not installed"); + return; + } + if (!installed(TERMUX_PACKAGE)) { + reportError("TERMUX_MISSING", "Termux not installed"); + return; + } + if (checkSelfPermission(TERMUX_RUN_PERMISSION) != PackageManager.PERMISSION_GRANTED) { + pendingModSelection = selection; + requestPermissions(new String[] {TERMUX_RUN_PERMISSION}, TERMUX_MOD_PERMISSION_REQUEST); + return; + } + + String[] arguments = selection.setupArguments(SETUP_PATH, gamePackage); + Intent command = new Intent("com.termux.RUN_COMMAND"); + command.setClassName(TERMUX_PACKAGE, "com.termux.app.RunCommandService"); + command.putExtra("com.termux.RUN_COMMAND_PATH", "/data/data/com.termux/files/usr/bin/bash"); + command.putExtra("com.termux.RUN_COMMAND_ARGUMENTS", arguments); + command.putExtra("com.termux.RUN_COMMAND_BACKGROUND", true); + command.putExtra("com.termux.RUN_COMMAND_COMMAND_LABEL", "Infinite Loop MODs"); + command.putExtra("com.termux.RUN_COMMAND_COMMAND_DESCRIPTION", "Builds and applies the selected client MODs."); + Intent result = new Intent(this, MainActivity.class); + result.setAction("jp.cradle.link.MOD_RESULT"); + int requestCode = (int) (SystemClock.elapsedRealtime() & 0x7fffffff); + PendingIntent pendingResult = PendingIntent.getActivity( + this, + requestCode, + result, + PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_MUTABLE); + command.putExtra("com.termux.RUN_COMMAND_PENDING_INTENT", pendingResult); + try { + if (startForegroundService(command) == null) { + reportError("TERMUX_SERVICE", "Termux service not found"); + return; + } + applyMods.setEnabled(false); + applyMods.setText(selection.gm || selection.lua ? "Building…" : "Restoring…"); + record("Client MOD command requested"); + } catch (SecurityException exception) { + applyMods.setEnabled(true); + applyMods.setText("Apply Mods"); + reportError("TERMUX_PERMISSION", exception.getClass().getSimpleName()); + } catch (IllegalStateException exception) { + applyMods.setEnabled(true); + applyMods.setText("Apply Mods"); + reportError("TERMUX_START_BLOCKED", exception.getClass().getSimpleName()); + } + } + + private void handleTermuxResult(Intent intent) { + if (intent == null) return; + if ("jp.cradle.link.UPDATE_RESULT".equals(intent.getAction())) { + intent.setAction(null); + Bundle result = intent.getBundleExtra("result"); + boolean success = result != null && result.getInt("exitCode", -1) == 0 + && result.getInt("err", Activity.RESULT_OK) == Activity.RESULT_OK; + String detail = result == null ? "Termux returned no result" : result.getString("stderr", ""); + if (detail.isEmpty() && result != null) detail = result.getString("errmsg", "exit " + result.getInt("exitCode", -1)); + finishRuntimeUpdate(success, detail); + intent.removeExtra("result"); + return; + } + if ("jp.cradle.link.CLIENT_LOG_RESULT".equals(intent.getAction())) { + intent.setAction(null); + Bundle result = intent.getBundleExtra("result"); + boolean success = result != null && result.getInt("exitCode", -1) == 0 + && result.getInt("err", Activity.RESULT_OK) == Activity.RESULT_OK; + if (collectingClientLog) finishClientLog(success ? "Client log collected" : "Client log failed"); + intent.removeExtra("result"); + return; + } + if (!"jp.cradle.link.MOD_RESULT".equals(intent.getAction())) return; + intent.setAction(null); + applyMods.setEnabled(true); + Bundle result = intent.getBundleExtra("result"); + if (result == null) return; + int exitCode = result.getInt("exitCode", -1); + int errorCode = result.getInt("err", Activity.RESULT_OK); + String stderr = result.getString("stderr", "").trim(); + String errorMessage = result.getString("errmsg", "").trim(); + if (exitCode == 0 && errorCode == Activity.RESULT_OK) { + errorState.setVisibility(View.GONE); + applyMods.setText("Applied · restart PGR"); + record("Client MOD command completed"); + } else { + applyMods.setText("Apply Mods"); + String detail = !stderr.isEmpty() ? stderr : (!errorMessage.isEmpty() ? errorMessage : "exit " + exitCode); + int newline = detail.lastIndexOf('\n'); + reportError("MOD_APPLY", newline >= 0 ? detail.substring(newline + 1) : detail); + } + intent.removeExtra("result"); + } + + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + setIntent(intent); + handleTermuxResult(intent); + } + + @Override + public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + if (requestCode == WIZARD_PERMISSION_REQUEST) { + refreshWizard(); + return; + } + if ((requestCode == TERMUX_PERMISSION_REQUEST || requestCode == TERMUX_STOP_PERMISSION_REQUEST) && grantResults.length == 1 + && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + runTermuxStack(requestCode == TERMUX_STOP_PERMISSION_REQUEST); + } else if (requestCode == TERMUX_UPDATE_PERMISSION_REQUEST && grantResults.length == 1 + && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + requestRuntimeUpdate(); + } else if (requestCode == TERMUX_UPDATE_PERMISSION_REQUEST) { + reportError("TERMUX_PERMISSION", "Permission not granted"); + } else if (requestCode == TERMUX_MOD_PERMISSION_REQUEST && grantResults.length == 1 + && grantResults[0] == PackageManager.PERMISSION_GRANTED && pendingModSelection != null) { + ModSelection selection = pendingModSelection; + pendingModSelection = null; + runTermuxMods(selection); + } else if (requestCode == TERMUX_PERMISSION_REQUEST || requestCode == TERMUX_STOP_PERMISSION_REQUEST) { + reportError("TERMUX_PERMISSION", "Permission not granted"); + } else if (requestCode == TERMUX_MOD_PERMISSION_REQUEST) { + pendingModSelection = null; + reportError("TERMUX_PERMISSION", "Permission not granted"); + } + } + + private void prepareVpn() { + RegionProfile region = selectedRegion(); + if (!installed(clientPackage(region))) { + Toast.makeText(this, region.name + " client not found", Toast.LENGTH_SHORT).show(); + playStep = 0; + refreshWizard(); + return; + } + Intent prepare = VpnService.prepare(this); + if (prepare != null) { + startActivityForResult(prepare, VPN_REQUEST); + } else { + startRelayVpn(); + } + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (requestCode == VPN_REQUEST && resultCode == RESULT_OK) { + startRelayVpn(); + } else if (requestCode == VPN_REQUEST) { + record("Relay permission not granted"); + playStep = 0; + refreshWizard(); + } else if (requestCode == LOG_FOLDER_REQUEST) { + logFolder = resultCode == RESULT_OK && data != null ? data.getData() : null; + if (logFolder != null) { + try { + getContentResolver().takePersistableUriPermission(logFolder, Intent.FLAG_GRANT_READ_URI_PERMISSION); + getPreferences(MODE_PRIVATE).edit().putString("serverLogFolder", logFolder.toString()).apply(); + } catch (SecurityException ignored) { } + } + chooseLogDestination(); + } else if (requestCode == EXPORT_LOG_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { + Uri destination = data.getData(); + Uri folder = logFolder; + String entries = String.join("\n", recentLog); + executor.execute(() -> { + String result = LogExport.write(getContentResolver(), destination, folder, entries); + ui.post(() -> Toast.makeText(this, result, Toast.LENGTH_SHORT).show()); + }); + } + } + + private void record(String event) { + if (recentLog.size() >= 100) recentLog.removeFirst(); + recentLog.addLast(new java.util.Date() + " " + event); + } + + private void reportError(String code, String detail) { + String message = code + " · " + detail; + record("ERROR " + message); + errorState.setText(message); + errorState.setVisibility(View.VISIBLE); + } + + private final Runnable clientLogTimeout = () -> finishClientLog("Client log timed out"); + + /** Collects the game's logcat through Termux and Shizuku first, then asks where to save everything. */ + private void exportLogs() { + if (collectingClientLog) return; + String gamePackage = clientPackage(selectedRegion()); + if (!installed(TERMUX_PACKAGE) || !installed(gamePackage) || !installed(Dependencies.Kind.SHIZUKU.packageName) + || checkSelfPermission(TERMUX_RUN_PERMISSION) != PackageManager.PERMISSION_GRANTED) { + record("Client log skipped"); + chooseLogExport(); + return; + } + Intent command = new Intent("com.termux.RUN_COMMAND"); + command.setClassName(TERMUX_PACKAGE, "com.termux.app.RunCommandService"); + command.putExtra("com.termux.RUN_COMMAND_PATH", "/data/data/com.termux/files/usr/bin/bash"); + command.putExtra("com.termux.RUN_COMMAND_ARGUMENTS", ModSelection.clientLogArguments(SETUP_PATH, gamePackage)); + command.putExtra("com.termux.RUN_COMMAND_BACKGROUND", true); + command.putExtra("com.termux.RUN_COMMAND_COMMAND_LABEL", "Infinite Loop client log"); + Intent result = new Intent(this, MainActivity.class); + result.setAction("jp.cradle.link.CLIENT_LOG_RESULT"); + command.putExtra("com.termux.RUN_COMMAND_PENDING_INTENT", PendingIntent.getActivity(this, + (int) (SystemClock.elapsedRealtime() & 0x7fffffff), result, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_MUTABLE)); + try { + if (startForegroundService(command) == null) { + finishClientLog("Client log skipped: Termux service not found"); + return; + } + collectingClientLog = true; + Toast.makeText(this, "Collecting client log…", Toast.LENGTH_SHORT).show(); + ui.postDelayed(clientLogTimeout, CLIENT_LOG_TIMEOUT_MS); + } catch (SecurityException | IllegalStateException exception) { + finishClientLog("Client log skipped: " + exception.getClass().getSimpleName()); + } + } + + private void finishClientLog(String event) { + ui.removeCallbacks(clientLogTimeout); + collectingClientLog = false; + record(event); + chooseLogExport(); + } + + private void chooseLogExport() { + String savedFolder = getPreferences(MODE_PRIVATE).getString("serverLogFolder", null); + logFolder = savedFolder == null ? null : Uri.parse(savedFolder); + if (logFolder == null) { + Toast.makeText(this, "Select Downloads / InfiniteLoop for server logs", Toast.LENGTH_LONG).show(); + Intent choose = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE); + choose.putExtra(Intent.EXTRA_LOCAL_ONLY, true); + choose.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION); + startActivityForResult(choose, LOG_FOLDER_REQUEST); + } else { + chooseLogDestination(); + } + } + + private void chooseLogDestination() { + Intent save = new Intent(Intent.ACTION_CREATE_DOCUMENT); + save.addCategory(Intent.CATEGORY_OPENABLE); + save.setType("text/plain"); + save.putExtra(Intent.EXTRA_LOCAL_ONLY, true); + save.putExtra(Intent.EXTRA_TITLE, "infinite-loop-log.txt"); + startActivityForResult(save, EXPORT_LOG_REQUEST); + } + + private void startRelayVpn() { + try { + startForegroundService(new Intent(this, GameProxyVpnService.class).putExtra("gamePackage", clientPackage(selectedRegion()))); + record("Relay start requested"); + } catch (RuntimeException exception) { + reportError("RELAY_DISPATCH", exception.getClass().getSimpleName()); + } + } + + @Override + protected void onStart() { + super.onStart(); + visible = true; + foreground = true; + Intent waiting = InstallResultReceiver.takePending(); + if (waiting != null) startActivity(waiting); + refreshVpnButton(); + refreshWizard(); + checkServices(); + checkAppUpdate(); + } + + @Override + protected void onStop() { + visible = false; + foreground = false; + ui.removeCallbacks(probe); + ui.removeCallbacks(updateVpnButton); + super.onStop(); + } + + @Override + protected void onSaveInstanceState(Bundle outState) { + outState.putInt("region", selectedRegionIndex); + outState.putLong("startDeadline", startDeadline); + outState.putBoolean("stopping", stopping); + outState.putInt("updatePhase", updatePhase); + super.onSaveInstanceState(outState); + } + + @Override + protected void onDestroy() { + executor.shutdownNow(); + updateExecutor.shutdownNow(); + super.onDestroy(); + } +} diff --git a/Scripts/android/launcher/app/src/main/java/jp/cradle/link/ModSelection.java b/Scripts/android/launcher/app/src/main/java/jp/cradle/link/ModSelection.java new file mode 100644 index 00000000..1717d555 --- /dev/null +++ b/Scripts/android/launcher/app/src/main/java/jp/cradle/link/ModSelection.java @@ -0,0 +1,35 @@ +package jp.cradle.link; + +final class ModSelection { + final boolean gm; + final boolean lua; + + ModSelection(boolean gm, boolean lua) { + this.gm = gm; + this.lua = lua; + } + + /** bash arguments that run the bundled update script (assets/update-runtime.sh) for one release. */ + static String[] runtimeUpdateArguments(String script, String repository, String tag) { + return new String[] {"-c", script, "update-runtime", repository, tag}; + } + + /** bash arguments that write the game's logcat to Download/InfiniteLoop/client.log. */ + static String[] clientLogArguments(String setup, String packageName) { + return new String[] {setup, "client-log", packageName}; + } + + static boolean restartAfterRuntimeUpdate(boolean success) { + return success; + } + + String[] setupArguments(String setup, String packageName) { + return new String[] { + setup, + "mod-apply", + packageName, + gm ? "1" : "0", + lua ? "1" : "0" + }; + } +} diff --git a/Scripts/android/launcher/app/src/main/java/jp/cradle/link/PlayerAccounts.java b/Scripts/android/launcher/app/src/main/java/jp/cradle/link/PlayerAccounts.java new file mode 100644 index 00000000..85181c90 --- /dev/null +++ b/Scripts/android/launcher/app/src/main/java/jp/cradle/link/PlayerAccounts.java @@ -0,0 +1,84 @@ +package jp.cradle.link; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; + +/** Which account in the server's database the game signs in as; talks to the server on this phone. */ +final class PlayerAccounts { + private static final int PORT = 8080; + private static final int TIMEOUT_MS = 4000; + + private PlayerAccounts() { } + + static final class Listing { + /** The account in use; empty when the server has none chosen. */ + final String current; + final List users; + + Listing(String current, List users) { + this.current = current; + this.users = users; + } + } + + /** The server's answer: the current account on the first line, then every account, one per line. */ + static Listing parse(String body) { + String[] lines = body.replace("\r", "").split("\n", -1); + List users = new ArrayList<>(); + for (int index = 1; index < lines.length; index++) { + if (!lines[index].isEmpty() && !users.contains(lines[index])) users.add(lines[index]); + } + return new Listing(lines[0], users); + } + + /** The account to switch to: the one chosen earlier, when it still exists and is not already in use; otherwise null. */ + static String pending(Listing listing, String saved) { + if (saved == null || saved.isEmpty() || saved.equals(listing.current)) return null; + return listing.users.contains(saved) ? saved : null; + } + + static Listing list() throws IOException { + return parse(send("GET /api/AscNet/android/players")); + } + + static void select(String username) throws IOException { + send("POST /api/AscNet/android/player?username=" + URLEncoder.encode(username, "UTF-8")); + } + + /** One HTTP/1.0 request over a plain socket, which Android's cleartext policy does not apply to. */ + private static String send(String requestLine) throws IOException { + try (Socket socket = new Socket()) { + socket.connect(new InetSocketAddress("127.0.0.1", PORT), TIMEOUT_MS); + socket.setSoTimeout(TIMEOUT_MS); + OutputStream out = socket.getOutputStream(); + String request = requestLine + " HTTP/1.0\r\nHost: 127.0.0.1:" + PORT + "\r\nContent-Length: 0\r\n\r\n"; + out.write(request.getBytes(StandardCharsets.US_ASCII)); + out.flush(); + ByteArrayOutputStream response = new ByteArrayOutputStream(); + InputStream in = socket.getInputStream(); + byte[] chunk = new byte[4096]; + int count; + while ((count = in.read(chunk)) != -1) response.write(chunk, 0, count); + return body(new String(response.toByteArray(), StandardCharsets.UTF_8)); + } + } + + /** The body of a response, or an IOException unless the status is 200. */ + static String body(String response) throws IOException { + int lineEnd = response.indexOf("\r\n"); + String[] status = (lineEnd < 0 ? response : response.substring(0, lineEnd)).split(" "); + if (status.length < 2 || !status[1].equals("200")) { + throw new IOException("Server answered " + (status.length < 2 ? "nothing" : status[1])); + } + int split = response.indexOf("\r\n\r\n"); + return split < 0 ? "" : response.substring(split + 4); + } +} diff --git a/Scripts/android/launcher/app/src/main/java/jp/cradle/link/SetupFlow.java b/Scripts/android/launcher/app/src/main/java/jp/cradle/link/SetupFlow.java new file mode 100644 index 00000000..efc3a06f --- /dev/null +++ b/Scripts/android/launcher/app/src/main/java/jp/cradle/link/SetupFlow.java @@ -0,0 +1,68 @@ +package jp.cradle.link; + +/** + * The first-run wizard: from what is installed and granted, decide the single next action the primary button + * offers. Free of Android types so the order and wording are unit-testable. + */ +final class SetupFlow { + enum Step { + TERMUX_MISSING("1 · Install Termux", "Downloads Termux. Tap Install on the next screen.", true), + TERMUX_PERMISSION("2 · Allow Termux control", "Tap Allow on the next screen.", true), + TERMUX_BOOTSTRAP("3 · Copy command and open Termux", "Wait for the $ prompt, long-press, Paste, Enter. Tap Allow if asked.", true), + TERMUX_CONFIRM("4 · I pasted it — continue", "Installs the server. This takes a few minutes.", true), + RUNTIME("Install server", "Downloads and installs the server. This takes a few minutes.", true), + NO_CLIENT("Install Punishing: Gray Raven first", "No game client was found on this phone.", false), + PLAY("PLAY", "Starts the server and relay, then opens the game.", true), + CANCEL("Cancel", "Starting… tap to cancel.", true), + BUSY("Working…", "Please wait.", false); + + final String label; + final String hint; + final boolean enabled; + + Step(String label, String hint, boolean enabled) { + this.label = label; + this.hint = hint; + this.enabled = enabled; + } + } + + static final class State { + boolean termuxInstalled; + boolean termuxPermission; + /** Termux accepts commands from this app (allow-external-apps is on), proven by a command that worked. */ + boolean termuxReady; + boolean bootstrapOpened; + boolean runtimeInstalled; + boolean clientInstalled; + boolean busy; + boolean playing; + } + + /** + * Termux refuses commands from other apps until allow-external-apps is set, and an app cannot set it for + * Termux, so the user runs this one harmless line once. It also asks for Termux's storage permission, which + * setup.sh needs for /sdcard/Download/InfiniteLoop (logs and Mod staging). Everything after that is done by the launcher. + */ + static final String BOOTSTRAP_COMMAND = + "termux-setup-storage; mkdir -p ~/.termux && { grep -qx 'allow-external-apps=true' ~/.termux/termux.properties 2>/dev/null" + + " || echo 'allow-external-apps=true' >> ~/.termux/termux.properties; }; termux-reload-settings"; + + private SetupFlow() { } + + /** True until Termux, its permission, its command access and the server are all in place: the full-screen wizard. */ + static boolean setupPending(State state) { + return !state.termuxInstalled || !state.termuxPermission || !state.termuxReady || !state.runtimeInstalled; + } + + static Step next(State state) { + if (state.playing) return Step.CANCEL; + if (state.busy) return Step.BUSY; + if (!state.termuxInstalled) return Step.TERMUX_MISSING; + if (!state.termuxPermission) return Step.TERMUX_PERMISSION; + if (!state.termuxReady) return state.bootstrapOpened ? Step.TERMUX_CONFIRM : Step.TERMUX_BOOTSTRAP; + if (!state.runtimeInstalled) return Step.RUNTIME; + if (!state.clientInstalled) return Step.NO_CLIENT; + return Step.PLAY; + } +} diff --git a/Scripts/android/launcher/app/src/main/java/jp/cradle/link/UpdateChecker.java b/Scripts/android/launcher/app/src/main/java/jp/cradle/link/UpdateChecker.java new file mode 100644 index 00000000..7ed10431 --- /dev/null +++ b/Scripts/android/launcher/app/src/main/java/jp/cradle/link/UpdateChecker.java @@ -0,0 +1,133 @@ +package jp.cradle.link; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Release selection and trust rules for the in-app updater, kept free of Android types so they are unit-testable. + * A release counts only when its tag is {@code android-v} and it carries {@link #APK} and {@link #SUMS} + * at exactly the URLs GitHub serves them from, so the repository setting is the only thing that decides who can + * ship an update. The APK is additionally pinned by Android to the installed app's signing key. + */ +final class UpdateChecker { + static final String TAG_PREFIX = "android-v"; + static final String APK = "Infinite-Loop.apk"; + static final String SUMS = "SHA256SUMS"; + + private static final Pattern REPOSITORY = Pattern.compile("[A-Za-z0-9._-]+/[A-Za-z0-9._-]+"); + private static final Pattern VERSION = Pattern.compile("\\d{1,6}(?:\\.\\d{1,6}){0,3}"); + private static final Pattern SUM_LINE = Pattern.compile("([0-9a-fA-F]{64}) {2}(\\S.*)"); + private static final Set HOSTS = new HashSet<>(Arrays.asList( + "api.github.com", "github.com", "objects.githubusercontent.com", "release-assets.githubusercontent.com")); + + private UpdateChecker() { } + + static final class Asset { + final String name; + final String url; + + Asset(String name, String url) { + this.name = name; + this.url = url; + } + } + + static final class ReleaseInfo { + final String tag; + final boolean draft; + final boolean prerelease; + final List assets; + + ReleaseInfo(String tag, boolean draft, boolean prerelease, List assets) { + this.tag = tag; + this.draft = draft; + this.prerelease = prerelease; + this.assets = assets; + } + } + + /** {@code owner/name} with no path tricks. */ + static boolean validRepository(String repository) { + if (repository == null || !REPOSITORY.matcher(repository).matches()) return false; + for (String part : repository.split("/")) { + if (part.equals(".") || part.equals("..")) return false; + } + return true; + } + + /** The version in an {@code android-v} tag, or null for any other tag. */ + static String versionOfTag(String tag) { + if (tag == null || !tag.startsWith(TAG_PREFIX)) return null; + String version = tag.substring(TAG_PREFIX.length()); + return VERSION.matcher(version).matches() ? version : null; + } + + /** Numeric, dot-separated comparison; missing parts count as 0, so "0.2" equals "0.2.0". */ + static int compare(String left, String right) { + String[] a = left.split("\\."); + String[] b = right.split("\\."); + for (int index = 0; index < Math.max(a.length, b.length); index++) { + int x = index < a.length ? Integer.parseInt(a[index]) : 0; + int y = index < b.length ? Integer.parseInt(b[index]) : 0; + if (x != y) return Integer.compare(x, y); + } + return 0; + } + + static String assetUrl(String repository, String tag, String name) { + return "https://github.com/" + repository + "/releases/download/" + tag + "/" + name; + } + + /** The tag of the newest published release that is newer than {@code current}, or null. */ + static String newest(String repository, String current, List releases) { + if (!validRepository(repository) || !VERSION.matcher(current).matches()) return null; + String bestVersion = current; + String bestTag = null; + for (ReleaseInfo release : releases) { + if (release.draft || release.prerelease) continue; + String version = versionOfTag(release.tag); + if (version == null || compare(version, bestVersion) <= 0) continue; + if (!hasAsset(release, APK, assetUrl(repository, release.tag, APK))) continue; + if (!hasAsset(release, SUMS, assetUrl(repository, release.tag, SUMS))) continue; + bestVersion = version; + bestTag = release.tag; + } + return bestTag; + } + + private static boolean hasAsset(ReleaseInfo release, String name, String expectedUrl) { + for (Asset asset : release.assets) { + if (asset.name.equals(name) && asset.url.equals(expectedUrl)) return true; + } + return false; + } + + /** The lower-case SHA-256 listed for {@code name} in a {@code sha256sum}-style manifest, or null. */ + static String expectedHash(String sums, String name) { + for (String line : sums.split("\\r?\\n")) { + Matcher match = SUM_LINE.matcher(line); + if (match.matches() && match.group(2).equals(name)) return match.group(1).toLowerCase(Locale.ROOT); + } + return null; + } + + /** https on a GitHub API/release host only; every redirect hop is checked against this. */ + static boolean isTrustedUrl(String url) { + try { + URI uri = new URI(url); + String host = uri.getHost(); + return "https".equals(uri.getScheme()) && uri.getUserInfo() == null + && (uri.getPort() == -1 || uri.getPort() == 443) + && host != null && HOSTS.contains(host.toLowerCase(Locale.ROOT)); + } catch (URISyntaxException exception) { + return false; + } + } +} diff --git a/Scripts/android/launcher/app/src/main/res/drawable/infinite_loop_icon.png b/Scripts/android/launcher/app/src/main/res/drawable/infinite_loop_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..ba8efe5c7b0b5baa3426ffc9628a2517ce39d4f7 GIT binary patch literal 37178 zcmY&gcOca7ALlydXq=r=&K}t#BjrNboRExUg_My}3c2fRMZ?}J387?UL|mj0Qj|it ztdKH_WZdulIhB6jfAr!6u0{g;(ZHMSO3+b>VOGeaTOlOX?eLsb2c2o5B8rjrl&*prxD_V_4T{4gIFQ7th>J1M%Ziz`v=y4H!FqB z+TT`Oply~we9MZ%;}~7(P*(&0Y=vetv$Xr!qd?c7s3yFA%d>D~BlDR{=)+9Dhu6;N zI*#8!Sdb_GLhh8g8+8=UCUwH0o!HfX_;ZLP-#eq2EH5*}Uy9(-_Tk?Ft{c(mg*ivty0dupKF!$(2sr z>ex$unImNR--nPhi5u-Yo*J)hXGmYb58H7Aaq@UIq4jGqkY?Ux(r-6@KKYlIXmQa@ z`aC-m$!laC`d5G0@(sAuUpyT~6N;HW*$w_669Q*!W|wC9ds`h#yR1G%I<|4&Tffx< zPsBH(73etj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PBSKe@Vp*TSRY(I9c}R-gn{CiW*d z1Hs@~uQ8f5Lxx=Zv3(pVRc{c8Adp@aDiJ zp6mDl0C^S_c%o4L9B4av<3F2{h4+C&UayAnNaci)!p3%ri2HAJ6uKT2Oz=&ELGQV) zol)N2M&?MWVN+^{5A0BbZ!ZTy@_W#=Qvr{5r-jBBz;|fiwh7H4NlZ?V$u_X{YlNZ| z)L<563DCD5Adj`vS*Trkt5IgP5uG~RL)dNb1C>MajX$znISNSvT!a~Y2i;W;*O`75{Hxr0&@~1ue_X}ti9No}dzx+;)L!a1>utX{mKSKBo z!ki0E*9K`d^w0@(rYR{gY^N=tQ`3(BvDdWT1g_y;;Q2akb1p~h)Q1kP&yZ-6P_h@>+C+;u&ujB9#Izr;lV*$j;5rnOEhYEZ<8v2vx1@5;tQg7eY zt`GbOJIZw#6>^Fw;pH;w-%rFSa*#QlP;4Xl06&Ms_U{BVVDNL0LBx9yLwNQv2W(mU zV)ogc#t@=Y9^eyY8wTvof8%F_?NU45_Z6DMk(ijEBULagegl2VZBI6pk_BRjMbMk3 z^v{gD0R{^l%LihX2R(as8zbQdjr*u6BIpC#)kDJ6gh4o@onOebZLy=6?I93YM7*Db z8Xe_-`p_%rEppK7tMT$9yz1iL1+-1*h@Q5}u|GLpJ7#ncIua)QnH1jK3cI${%4>* z=9OgZjUS=|p5dM5;`hRY9%N{vBUk0`CE6Z-{2BPIJ+%D-zU`8m#OdIc$%3|R-nRYm zPui!MB)W(i!RN+5#e8KWnTUw!k+R%*ZG78}NIpP<8PtP{knU*EKZJAqq`4@Tz^*xl zcxYB#sd%1L{FJ{(8EL(5yf^rY;AA0c@B~#%{1I-pB1;0j5Y}B}6-2dAMsdy($!A + + diff --git a/Scripts/android/launcher/app/src/test/java/jp/cradle/link/ClientPackagesTest.java b/Scripts/android/launcher/app/src/test/java/jp/cradle/link/ClientPackagesTest.java new file mode 100644 index 00000000..3429d619 --- /dev/null +++ b/Scripts/android/launcher/app/src/test/java/jp/cradle/link/ClientPackagesTest.java @@ -0,0 +1,53 @@ +package jp.cradle.link; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.util.Arrays; +import java.util.Collections; +import org.junit.Test; + +public final class ClientPackagesTest { + private static final String[] REGIONS = {"EN", "JP", "TW", "KR", "CN"}; + + @Test + public void everyRegionAndStoreBuildIsRecognised() { + assertEquals("EN", ClientPackages.region("com.kurogame.punishing.grayraven.en")); + assertEquals("EN", ClientPackages.region("com.kurogame.gplay.punishing.grayraven.en")); + assertEquals("JP", ClientPackages.region("com.herogame.gplay.punishing.grayraven.jp")); + assertEquals("JP", ClientPackages.region("com.kurogame.punishing.grayraven.jp")); + assertEquals("TW", ClientPackages.region("com.kurogame.gplay.punishing.grayraven.tw")); + assertEquals("KR", ClientPackages.region("com.kurogame.gplay.punishing.grayraven.kr")); + assertEquals("CN", ClientPackages.region("com.kurogame.haru.kuro")); + assertEquals("CN", ClientPackages.region("com.kurogame.haru.hero")); + } + + @Test + public void otherPackagesAreNotClients() { + assertNull(ClientPackages.region(null)); + assertNull(ClientPackages.region("")); + assertNull(ClientPackages.region("com.termux")); + assertNull(ClientPackages.region("com.kurogame.punishing.grayraven.en.evil")); + assertNull(ClientPackages.region("evil.com.kurogame.punishing.grayraven.en")); + assertNull(ClientPackages.region("com.kurogame.punishing.grayraven.xx")); + assertNull(ClientPackages.region("com.kurogame.punishing.grayraven.EN")); + } + + @Test + public void installedStoreBuildIsUsedWhenTheCanonicalIdIsMissing() { + String canonical = "com.kurogame.punishing.grayraven.en"; + String play = "com.kurogame.gplay.punishing.grayraven.en"; + assertEquals(play, ClientPackages.choose("EN", Arrays.asList(play, "com.termux"), canonical)); + assertEquals(canonical, ClientPackages.choose("EN", Arrays.asList(play, canonical), canonical)); + assertEquals(canonical, ClientPackages.choose("EN", Collections.emptyList(), canonical)); + assertEquals(canonical, ClientPackages.choose("EN", Collections.singletonList("com.herogame.gplay.punishing.grayraven.jp"), canonical)); + } + + @Test + public void firstRegionWithAnInstalledBuildIsDetected() { + assertEquals(0, ClientPackages.detect(REGIONS, Collections.singletonList("com.kurogame.gplay.punishing.grayraven.en"))); + assertEquals(2, ClientPackages.detect(REGIONS, Arrays.asList("com.termux", "com.kurogame.punishing.grayraven.tw"))); + assertEquals(-1, ClientPackages.detect(REGIONS, Collections.singletonList("com.termux"))); + assertEquals(-1, ClientPackages.detect(REGIONS, Collections.emptyList())); + } +} diff --git a/Scripts/android/launcher/app/src/test/java/jp/cradle/link/DependenciesTest.java b/Scripts/android/launcher/app/src/test/java/jp/cradle/link/DependenciesTest.java new file mode 100644 index 00000000..bbcfed77 --- /dev/null +++ b/Scripts/android/launcher/app/src/test/java/jp/cradle/link/DependenciesTest.java @@ -0,0 +1,102 @@ +package jp.cradle.link; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import org.junit.Test; + +/** Asset names and the checksum file are copied from the real termux/termux-app v0.118.3 and RikkaApps/Shizuku v13.6.0 releases. */ +public final class DependenciesTest { + private static final String TERMUX_BASE = "https://github.com/termux/termux-app/releases/download/v0.118.3/"; + private static final String TERMUX_ARM64 = "termux-app_v0.118.3+github-debug_arm64-v8a.apk"; + private static final String TERMUX_SUMS = "termux-app_v0.118.3+github-debug_sha256sums"; + private static final String REAL_SUMS = + "7600078440c3c34ef050bc009b00fc3215cb87ec4a449e01a696f74cf4249db2 termux-app_v0.118.3+github-debug_universal.apk\n" + + "72fdb596045116bf5ba1b5bdf5b26fddb9acc0bd074ad9f2da9eb0ae85e83a4e termux-app_v0.118.3+github-debug_arm64-v8a.apk\n" + + "89416397b70f9ff67a0044e8abe6ef82487cd48fcf543e2d23e02688cc541cf0 termux-app_v0.118.3+github-debug_armeabi-v7a.apk\n" + + "3550e61f4d9eb49b712fd1bd9519dc37085a4d8eb597c57a340f0a64859b7144 termux-app_v0.118.3+github-debug_x86_64.apk\n" + + "b6a980ac2fbda1c61edc7be389ce69da9a90af8444d27164b5e20b7a22442570 termux-app_v0.118.3+github-debug_x86.apk\n"; + + private static UpdateChecker.Asset asset(String name, String base) { + return new UpdateChecker.Asset(name, base + name.replace("+", "%2B")); + } + + private static UpdateChecker.ReleaseInfo release(String tag, boolean prerelease, UpdateChecker.Asset... assets) { + return new UpdateChecker.ReleaseInfo(tag, false, prerelease, Arrays.asList(assets)); + } + + private static UpdateChecker.ReleaseInfo stableTermux() { + return release("v0.118.3", false, + asset("termux-app_v0.118.3+github-debug_universal.apk", TERMUX_BASE), + asset("termux-app_v0.118.3+github-debug_armeabi-v7a.apk", TERMUX_BASE), + asset(TERMUX_ARM64, TERMUX_BASE), + asset(TERMUX_SUMS, TERMUX_BASE)); + } + + @Test + public void termuxPicksTheArm64BuildAndItsChecksumFile() { + Dependencies.Download pick = Dependencies.pick(Dependencies.Kind.TERMUX, Collections.singletonList(stableTermux())); + assertEquals(TERMUX_ARM64, pick.apk.name); + assertEquals(TERMUX_SUMS, pick.checksum.name); + } + + @Test + public void theRealTermuxChecksumFileYieldsTheArm64Hash() { + assertEquals("72fdb596045116bf5ba1b5bdf5b26fddb9acc0bd074ad9f2da9eb0ae85e83a4e", UpdateChecker.expectedHash(REAL_SUMS, TERMUX_ARM64)); + assertNull(UpdateChecker.expectedHash(REAL_SUMS, "termux-app_v0.118.3+github-debug_arm64-v8a.apk.exe")); + } + + @Test + public void betaReleasesAreSkippedAndAndroid5BuildsNeverPicked() { + String five = "termux-app_v0.119.0-beta.3+apt-android-5-github-debug_arm64-v8a.apk"; + String seven = "termux-app_v0.119.0-beta.3+apt-android-7-github-debug_arm64-v8a.apk"; + String base = "https://github.com/termux/termux-app/releases/download/v0.119.0-beta.3/"; + UpdateChecker.ReleaseInfo beta = release("v0.119.0-beta.3", true, asset(five, base), asset(seven, base)); + assertEquals(TERMUX_ARM64, Dependencies.pick(Dependencies.Kind.TERMUX, Arrays.asList(beta, stableTermux())).apk.name); + // Even a stable release must not offer the Android 5/6 build. + UpdateChecker.ReleaseInfo stable = release("v0.119.0", false, asset(five, base), + asset("termux-app_v0.119.0+apt-android-7-github-debug_sha256sums", base)); + assertNull(Dependencies.pick(Dependencies.Kind.TERMUX, Collections.singletonList(stable))); + } + + @Test + public void termuxWithoutAChecksumFileIsNotOffered() { + UpdateChecker.ReleaseInfo noSums = release("v0.118.3", false, asset(TERMUX_ARM64, TERMUX_BASE)); + assertNull(Dependencies.pick(Dependencies.Kind.TERMUX, Collections.singletonList(noSums))); + assertNotNull(Dependencies.pick(Dependencies.Kind.TERMUX, Collections.singletonList(stableTermux()))); + } + + @Test + public void shizukuPicksTheRealReleaseApkWithoutAChecksum() { + String name = "shizuku-v13.6.0.r1086.2650830c-release.apk"; + String base = "https://github.com/RikkaApps/Shizuku/releases/download/v13.6.0/"; + Dependencies.Download pick = Dependencies.pick(Dependencies.Kind.SHIZUKU, Collections.singletonList(release("v13.6.0", false, asset(name, base)))); + assertEquals(name, pick.apk.name); + assertNull(pick.checksum); + } + + @Test + public void assetsFromAnotherRepositoryOrHostAreRejected() { + for (String url : new String[] { + "https://github.com/evil/termux-app/releases/download/v1/" + TERMUX_ARM64, + "https://evil.example/termux/termux-app/releases/download/v1/" + TERMUX_ARM64, + "http://github.com/termux/termux-app/releases/download/v1/" + TERMUX_ARM64}) { + UpdateChecker.ReleaseInfo forged = release("v1", false, new UpdateChecker.Asset(TERMUX_ARM64, url), + new UpdateChecker.Asset(TERMUX_SUMS, TERMUX_BASE + TERMUX_SUMS)); + assertNull(url, Dependencies.pick(Dependencies.Kind.TERMUX, Collections.singletonList(forged))); + } + } + + @Test + public void lookalikeAssetNamesAreRejected() { + UpdateChecker.ReleaseInfo fake = release("v1", false, + asset("evil-termux-app_v1+github-debug_arm64-v8a.apk", TERMUX_BASE), + asset("termux-app_v1+github-debug_arm64-v8a.apk.exe", TERMUX_BASE), + asset(TERMUX_SUMS, TERMUX_BASE)); + assertNull(Dependencies.pick(Dependencies.Kind.TERMUX, Collections.singletonList(fake))); + } +} diff --git a/Scripts/android/launcher/app/src/test/java/jp/cradle/link/LogExportTest.java b/Scripts/android/launcher/app/src/test/java/jp/cradle/link/LogExportTest.java new file mode 100644 index 00000000..fa357e2f --- /dev/null +++ b/Scripts/android/launcher/app/src/test/java/jp/cradle/link/LogExportTest.java @@ -0,0 +1,43 @@ +package jp.cradle.link; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; + +import org.junit.Test; + +public final class LogExportTest { + private static byte[] bytes(String text) { + return text.getBytes(StandardCharsets.UTF_8); + } + + @Test + public void tailKeepsTheLastBytesOfALongStream() throws Exception { + byte[] data = new byte[100_000]; + for (int index = 0; index < data.length; index++) data[index] = (byte) (index % 251); + byte[] tail = LogExport.tail(new ByteArrayInputStream(data), 30_000); + assertArrayEquals(Arrays.copyOfRange(data, 70_000, 100_000), tail); + } + + @Test + public void tailReturnsAShortStreamUnchanged() throws Exception { + assertArrayEquals(bytes("short"), LogExport.tail(new ByteArrayInputStream(bytes("short")), 1000)); + assertEquals(0, LogExport.tail(new ByteArrayInputStream(new byte[0]), 1000).length); + } + + @Test + public void composeWritesEverySectionAndMarksMissingOnes() { + String text = new String(LogExport.compose("event one", Arrays.asList( + new LogExport.Section("Server log", bytes("line a")), + new LogExport.Section("Relay log", null), + new LogExport.Section("MongoDB log", bytes("line b\n")))), StandardCharsets.UTF_8); + assertTrue(text.startsWith("Infinite Loop diagnostics\n\nApp events\nevent one\n")); + assertTrue(text.contains("\nServer log\nline a\n")); + assertTrue(text.contains("\nRelay log\nUnavailable.\n")); + assertTrue(text.endsWith("\nMongoDB log\nline b\n")); + } +} diff --git a/Scripts/android/launcher/app/src/test/java/jp/cradle/link/ModSelectionTest.java b/Scripts/android/launcher/app/src/test/java/jp/cradle/link/ModSelectionTest.java new file mode 100644 index 00000000..c3934263 --- /dev/null +++ b/Scripts/android/launcher/app/src/test/java/jp/cradle/link/ModSelectionTest.java @@ -0,0 +1,49 @@ +package jp.cradle.link; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public final class ModSelectionTest { + private static final String SETUP = "/home/infinite-loop/setup.sh"; + private static final String PACKAGE = "com.herogame.gplay.punishing.grayraven.jp"; + + @Test + public void runtimeUpdateRunsTheBundledScriptForOneRelease() { + assertArrayEquals(new String[] {"-c", "echo hi", "update-runtime", "owner/repo", "android-v0.3.0"}, + ModSelection.runtimeUpdateArguments("echo hi", "owner/repo", "android-v0.3.0")); + } + + @Test + public void clientLogRunsSetupWithTheGamePackage() { + assertArrayEquals(new String[] {SETUP, "client-log", PACKAGE}, ModSelection.clientLogArguments(SETUP, PACKAGE)); + } + + @Test + public void successfulRuntimeUpdateRestartsTheSingleServerStack() { + assertTrue(ModSelection.restartAfterRuntimeUpdate(true)); + assertFalse(ModSelection.restartAfterRuntimeUpdate(false)); + } + + @Test + public void bothOffRestoresOriginalBundle() { + assertArrayEquals( + new String[] {SETUP, "mod-apply", PACKAGE, "0", "0"}, + new ModSelection(false, false).setupArguments(SETUP, PACKAGE)); + } + + @Test + public void enabledModesKeepIndependentFlags() { + assertArrayEquals( + new String[] {SETUP, "mod-apply", PACKAGE, "1", "0"}, + new ModSelection(true, false).setupArguments(SETUP, PACKAGE)); + assertArrayEquals( + new String[] {SETUP, "mod-apply", PACKAGE, "0", "1"}, + new ModSelection(false, true).setupArguments(SETUP, PACKAGE)); + assertArrayEquals( + new String[] {SETUP, "mod-apply", PACKAGE, "1", "1"}, + new ModSelection(true, true).setupArguments(SETUP, PACKAGE)); + } +} diff --git a/Scripts/android/launcher/app/src/test/java/jp/cradle/link/PlayerAccountsTest.java b/Scripts/android/launcher/app/src/test/java/jp/cradle/link/PlayerAccountsTest.java new file mode 100644 index 00000000..4fa8d191 --- /dev/null +++ b/Scripts/android/launcher/app/src/test/java/jp/cradle/link/PlayerAccountsTest.java @@ -0,0 +1,51 @@ +package jp.cradle.link; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.util.Arrays; + +import org.junit.Test; + +public class PlayerAccountsTest { + @Test + public void theFirstLineIsTheCurrentAccountAndTheRestAreTheChoices() { + PlayerAccounts.Listing listing = PlayerAccounts.parse("foki\r\nfoki\nsecond\n\nsecond\n"); + assertEquals("foki", listing.current); + assertEquals(Arrays.asList("foki", "second"), listing.users); + } + + @Test + public void aServerWithNoAccountsYieldsAnEmptyListing() { + PlayerAccounts.Listing listing = PlayerAccounts.parse("\n"); + assertEquals("", listing.current); + assertEquals(0, listing.users.size()); + } + + @Test + public void onlyAnExistingAccountThatIsNotAlreadyInUseIsSwitchedTo() { + PlayerAccounts.Listing listing = PlayerAccounts.parse("foki\nfoki\nsecond\n"); + assertEquals("second", PlayerAccounts.pending(listing, "second")); + assertNull(PlayerAccounts.pending(listing, "foki")); + assertNull(PlayerAccounts.pending(listing, "gone")); + assertNull(PlayerAccounts.pending(listing, null)); + assertNull(PlayerAccounts.pending(listing, "")); + } + + @Test + public void theBodyFollowsTheHeadersOfASuccessfulResponse() throws IOException { + assertEquals("foki\nsecond\n", PlayerAccounts.body("HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nfoki\nsecond\n")); + } + + @Test + public void anyOtherStatusIsAFailure() { + try { + PlayerAccounts.body("HTTP/1.1 404 Not Found\r\n\r\n"); + fail(); + } catch (IOException expected) { + assertEquals("Server answered 404", expected.getMessage()); + } + } +} diff --git a/Scripts/android/launcher/app/src/test/java/jp/cradle/link/SetupFlowTest.java b/Scripts/android/launcher/app/src/test/java/jp/cradle/link/SetupFlowTest.java new file mode 100644 index 00000000..62568ce3 --- /dev/null +++ b/Scripts/android/launcher/app/src/test/java/jp/cradle/link/SetupFlowTest.java @@ -0,0 +1,96 @@ +package jp.cradle.link; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public final class SetupFlowTest { + private static SetupFlow.State ready() { + SetupFlow.State state = new SetupFlow.State(); + state.termuxInstalled = true; + state.termuxPermission = true; + state.termuxReady = true; + state.runtimeInstalled = true; + state.clientInstalled = true; + return state; + } + + @Test + public void freshPhoneIsWalkedThroughEveryStepInOrder() { + SetupFlow.State state = new SetupFlow.State(); + assertEquals(SetupFlow.Step.TERMUX_MISSING, SetupFlow.next(state)); + state.termuxInstalled = true; + assertEquals(SetupFlow.Step.TERMUX_PERMISSION, SetupFlow.next(state)); + state.termuxPermission = true; + assertEquals(SetupFlow.Step.TERMUX_BOOTSTRAP, SetupFlow.next(state)); + state.bootstrapOpened = true; + assertEquals(SetupFlow.Step.TERMUX_CONFIRM, SetupFlow.next(state)); + state.termuxReady = true; + assertEquals(SetupFlow.Step.RUNTIME, SetupFlow.next(state)); + state.runtimeInstalled = true; + assertEquals(SetupFlow.Step.NO_CLIENT, SetupFlow.next(state)); + state.clientInstalled = true; + assertEquals(SetupFlow.Step.PLAY, SetupFlow.next(state)); + } + + @Test + public void theFullScreenWizardShowsUntilTheServerIsInstalled() { + SetupFlow.State state = new SetupFlow.State(); + assertTrue(SetupFlow.setupPending(state)); + state.termuxInstalled = true; + state.termuxPermission = true; + assertTrue(SetupFlow.setupPending(state)); + state.termuxReady = true; + assertTrue(SetupFlow.setupPending(state)); + state.runtimeInstalled = true; + assertFalse(SetupFlow.setupPending(state)); + state.clientInstalled = false; + assertFalse(SetupFlow.setupPending(state)); + } + + @Test + public void everythingSetUpGoesStraightToPlay() { + assertEquals(SetupFlow.Step.PLAY, SetupFlow.next(ready())); + } + + @Test + public void busyAndPlayingOverrideTheOtherSteps() { + SetupFlow.State state = ready(); + state.busy = true; + assertEquals(SetupFlow.Step.BUSY, SetupFlow.next(state)); + state.playing = true; + assertEquals(SetupFlow.Step.CANCEL, SetupFlow.next(state)); + assertTrue(SetupFlow.Step.CANCEL.enabled); + assertFalse(SetupFlow.Step.BUSY.enabled); + assertFalse(SetupFlow.Step.NO_CLIENT.enabled); + } + + @Test + public void aTermuxThatStoppedWorkingSendsTheUserBackToTheCommand() { + SetupFlow.State state = ready(); + state.termuxReady = false; + assertEquals(SetupFlow.Step.TERMUX_BOOTSTRAP, SetupFlow.next(state)); + } + + @Test + public void bootstrapCommandIsOneHarmlessLine() { + String command = SetupFlow.BOOTSTRAP_COMMAND; + assertFalse(command.contains("\n")); + assertTrue(command.contains("allow-external-apps=true")); + assertTrue(command.contains("termux-reload-settings")); + assertTrue(command.contains("termux-setup-storage")); + for (String forbidden : new String[] {"curl", "wget", "sudo", "rm ", "|bash", "| bash", "sh -c"}) { + assertFalse(forbidden, command.contains(forbidden)); + } + } + + @Test + public void everyStepHasShortText() { + for (SetupFlow.Step step : SetupFlow.Step.values()) { + assertTrue(step.name(), step.label.length() > 0 && step.label.length() <= 40); + assertTrue(step.name(), step.hint.length() > 0 && step.hint.length() <= 80); + } + } +} diff --git a/Scripts/android/launcher/app/src/test/java/jp/cradle/link/UpdateCheckerTest.java b/Scripts/android/launcher/app/src/test/java/jp/cradle/link/UpdateCheckerTest.java new file mode 100644 index 00000000..e8c9a8b4 --- /dev/null +++ b/Scripts/android/launcher/app/src/test/java/jp/cradle/link/UpdateCheckerTest.java @@ -0,0 +1,114 @@ +package jp.cradle.link; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import org.junit.Test; + +public final class UpdateCheckerTest { + private static final String REPO = "owner/repo"; + + private static UpdateChecker.ReleaseInfo release(String tag, boolean draft, boolean prerelease, String... assetNames) { + List assets = new ArrayList<>(); + for (String name : assetNames) assets.add(new UpdateChecker.Asset(name, UpdateChecker.assetUrl(REPO, tag, name))); + return new UpdateChecker.ReleaseInfo(tag, draft, prerelease, assets); + } + + private static UpdateChecker.ReleaseInfo good(String tag) { + return release(tag, false, false, UpdateChecker.APK, UpdateChecker.SUMS); + } + + @Test + public void versionsCompareNumerically() { + assertTrue(UpdateChecker.compare("0.10.0", "0.9.0") > 0); + assertTrue(UpdateChecker.compare("0.2.1", "0.2.0") > 0); + assertEquals(0, UpdateChecker.compare("0.2", "0.2.0")); + assertTrue(UpdateChecker.compare("0.2.0", "1") < 0); + } + + @Test + public void onlyAndroidTagsCarryAVersion() { + assertEquals("0.3.0", UpdateChecker.versionOfTag("android-v0.3.0")); + assertNull(UpdateChecker.versionOfTag("4.9.1")); + assertNull(UpdateChecker.versionOfTag("android-v")); + assertNull(UpdateChecker.versionOfTag("android-v0.3.0-rc1")); + assertNull(UpdateChecker.versionOfTag("android-v0.3.0/../x")); + assertNull(UpdateChecker.versionOfTag(null)); + } + + @Test + public void newestPublishedReleaseWins() { + List releases = Arrays.asList(good("android-v0.2.1"), good("android-v0.4.0"), good("android-v0.3.0")); + assertEquals("android-v0.4.0", UpdateChecker.newest(REPO, "0.2.0", releases)); + } + + @Test + public void nothingIsOfferedWhenNotNewer() { + assertNull(UpdateChecker.newest(REPO, "0.2.0", Collections.singletonList(good("android-v0.2.0")))); + assertNull(UpdateChecker.newest(REPO, "0.3.0", Collections.singletonList(good("android-v0.2.9")))); + assertNull(UpdateChecker.newest(REPO, "0.2.0", Collections.emptyList())); + } + + @Test + public void unusableReleasesAreSkipped() { + List releases = Arrays.asList( + release("android-v9.0.0", true, false, UpdateChecker.APK, UpdateChecker.SUMS), + release("android-v8.0.0", false, true, UpdateChecker.APK, UpdateChecker.SUMS), + release("android-v7.0.0", false, false, UpdateChecker.APK), + release("android-v6.0.0", false, false, UpdateChecker.SUMS), + release("5.0.0", false, false, UpdateChecker.APK, UpdateChecker.SUMS), + good("android-v0.3.0")); + assertEquals("android-v0.3.0", UpdateChecker.newest(REPO, "0.2.0", releases)); + } + + @Test + public void assetsMustBeServedFromTheConfiguredRepository() { + List assets = Arrays.asList( + new UpdateChecker.Asset(UpdateChecker.APK, "https://github.com/evil/repo/releases/download/android-v0.3.0/Infinite-Loop.apk"), + new UpdateChecker.Asset(UpdateChecker.SUMS, UpdateChecker.assetUrl(REPO, "android-v0.3.0", UpdateChecker.SUMS))); + UpdateChecker.ReleaseInfo forged = new UpdateChecker.ReleaseInfo("android-v0.3.0", false, false, assets); + assertNull(UpdateChecker.newest(REPO, "0.2.0", Collections.singletonList(forged))); + } + + @Test + public void repositorySettingIsValidated() { + assertTrue(UpdateChecker.validRepository("reiserFSs/InfiniteLoop")); + assertTrue(UpdateChecker.validRepository("Fokiiiiiii/Cradle")); + for (String bad : new String[] {null, "", "owner", "owner/", "/repo", "a/b/c", "../x", "owner/..", "owner/re po", "owner/repo?x=1"}) { + assertFalse(bad, UpdateChecker.validRepository(bad)); + } + assertNull(UpdateChecker.newest("../x", "0.2.0", Collections.singletonList(good("android-v0.3.0")))); + } + + @Test + public void hashIsReadFromTheManifestByExactName() { + String hash = "0123456789abcdef0123456789abcdef0123456789ABCDEF0123456789abcdef"; + String sums = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff Infinite-Loop-Android.zip\r\n" + + hash + " Infinite-Loop.apk\n" + + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa runtime/Infinite-Loop.apk\n"; + assertEquals(hash.toLowerCase(), UpdateChecker.expectedHash(sums, "Infinite-Loop.apk")); + assertNull(UpdateChecker.expectedHash(sums, "missing.apk")); + assertNull(UpdateChecker.expectedHash("not-a-hash Infinite-Loop.apk\n", "Infinite-Loop.apk")); + assertNull(UpdateChecker.expectedHash("", "Infinite-Loop.apk")); + } + + @Test + public void onlyGithubHttpsUrlsAreTrusted() { + assertTrue(UpdateChecker.isTrustedUrl("https://github.com/o/r/releases/download/t/a")); + assertTrue(UpdateChecker.isTrustedUrl("https://release-assets.githubusercontent.com/x?y=1")); + assertTrue(UpdateChecker.isTrustedUrl("https://api.github.com/repos/o/r/releases")); + assertFalse(UpdateChecker.isTrustedUrl("http://github.com/o/r")); + assertFalse(UpdateChecker.isTrustedUrl("https://github.com.evil.example/o/r")); + assertFalse(UpdateChecker.isTrustedUrl("https://evil.example/github.com")); + assertFalse(UpdateChecker.isTrustedUrl("https://user@github.com/o/r")); + assertFalse(UpdateChecker.isTrustedUrl("https://github.com:8443/o/r")); + assertFalse(UpdateChecker.isTrustedUrl("file:///sdcard/x")); + assertFalse(UpdateChecker.isTrustedUrl("not a url")); + } +} diff --git a/Scripts/android/launcher/build.gradle.kts b/Scripts/android/launcher/build.gradle.kts new file mode 100644 index 00000000..c854c839 --- /dev/null +++ b/Scripts/android/launcher/build.gradle.kts @@ -0,0 +1,3 @@ +plugins { + id("com.android.application") version "8.8.2" apply false +} diff --git a/Scripts/android/launcher/gradle.properties b/Scripts/android/launcher/gradle.properties new file mode 100644 index 00000000..dfd0e183 --- /dev/null +++ b/Scripts/android/launcher/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 +android.useAndroidX=true +updateRepository=reiserFSs/InfiniteLoop diff --git a/Scripts/android/launcher/settings.gradle.kts b/Scripts/android/launcher/settings.gradle.kts new file mode 100644 index 00000000..85c311e1 --- /dev/null +++ b/Scripts/android/launcher/settings.gradle.kts @@ -0,0 +1,18 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "CradleLink" +include(":app") diff --git a/Scripts/android/moddetect/Cargo.lock b/Scripts/android/moddetect/Cargo.lock new file mode 100644 index 00000000..9969329b --- /dev/null +++ b/Scripts/android/moddetect/Cargo.lock @@ -0,0 +1,392 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "anyhow" +version = "1.0.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902" + +[[package]] +name = "ascnet-moddetect" +version = "0.1.0" +dependencies = [ + "aes", + "anyhow", + "ctr", + "lz4_flex", + "serde_json", + "sha1", + "uuid", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "js-sys" +version = "0.3.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce57d20d1ea864ce2ac172ab472d409214f4fd359f0b2a2775abdf522e2af99e" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "lz4_flex" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13591d77a9b6d941f7e6fcade7f9dfd9e801308752bde50c0a9bb5852778c22c" +dependencies = [ + "twox-hash", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "twox-hash" +version = "2.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "uuid" +version = "1.29.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bed99139f7dac9b5cfe5f17be4d66dc7079a34dee1d74bcc77217119240e267c" +dependencies = [ + "getrandom", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-bindgen" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Scripts/android/moddetect/Cargo.toml b/Scripts/android/moddetect/Cargo.toml new file mode 100644 index 00000000..7596200f --- /dev/null +++ b/Scripts/android/moddetect/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "ascnet-moddetect" +version = "0.1.0" +edition = "2021" +license = "GPL-3.0-only" + +[dependencies] +aes = "0.8" +anyhow = "1" +ctr = "0.9" +lz4_flex = "0.11" +serde_json = "1" +sha1 = "0.10" + +[dev-dependencies] +uuid = { version = "1", features = ["v4"] } + +[profile.release] +strip = true +lto = true +opt-level = "z" +codegen-units = 1 +panic = "abort" diff --git a/Scripts/android/moddetect/src/main.rs b/Scripts/android/moddetect/src/main.rs new file mode 100644 index 00000000..162fcef3 --- /dev/null +++ b/Scripts/android/moddetect/src/main.rs @@ -0,0 +1,190 @@ +use anyhow::{bail, Context, Result}; +use sha1::{Digest, Sha1}; +use std::{env, fs, path::{Path, PathBuf}}; + +#[allow(dead_code)] +mod local { + pub fn root() -> anyhow::Result { + Ok(std::env::temp_dir().join("ascnet-moddetect")) + } +} + +#[path = "../../../../AscNet.Launcher/src/bundle.rs"] +#[allow(dead_code)] +mod bundle; + +const LOGICAL: &str = "assets/temp/lua/matrix.ab"; + +fn verify(path: &Path) -> Result<()> { + let name = bundle::bundle_name(path).with_context(|| format!("read bundle {}", path.display()))?; + if name.as_deref() != Some(LOGICAL) { + bail!("unexpected bundle logical name in {}: {:?}", path.display(), name); + } + Ok(()) +} + +fn fingerprint(data: &[u8]) -> String { format!("{:x}", Sha1::digest(data)) } + +fn load_index(root: &Path) -> Result<(Vec, String)> { + let mut errors = Vec::new(); + for name in ["index", "InPkgIndex"] { + let path = root.join(name); + if !path.exists() { continue; } + match bundle::read_bounded(&path).and_then(|data| { + let entries = bundle::index_table(&data)?; + Ok((entries, fingerprint(&data))) + }) { + Ok(index) => return Ok(index), + Err(error) => errors.push(format!("{}: {error:#}", path.display())), + } + } + bail!("no readable matrix index: {}", if errors.is_empty() { "index and InPkgIndex missing".into() } else { errors.join("; ") }) +} + +fn safe_name(name: &str) -> bool { + let bytes = name.as_bytes(); + bytes.len() == 20 && &bytes[16..] == b".uab" && bytes[..16].iter().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(c)) +} + +fn state(path: &Path, entry: &bundle::Entry) -> Result<&'static str> { + if bundle::matches_entry(path, entry).with_context(|| format!("hash {}", path.display()))? { + return Ok("original"); + } + let backup = PathBuf::from(format!("{}.ascnet-backup", path.display())); + if !bundle::matches_entry(&backup, entry).with_context(|| format!("verify original backup {}", backup.display()))? { + bail!("bundle and backup do not match index: {}", path.display()); + } + Ok("modified") +} + +fn scan_state_is_eligible(state: &str) -> bool { + matches!(state, "original" | "modified") +} + +fn detect(root: &Path, cache: Option<&Path>) -> Result { + let root = fs::canonicalize(root).with_context(|| format!("matrix directory {}", root.display()))?; + let (entries, index_hash) = load_index(&root)?; + if let Some(cache) = cache { + if let Ok(data) = fs::read_to_string(cache) { + let fields: Vec<_> = data.lines().collect(); + if fields.len() == 4 && safe_name(fields[0]) && fields[1] == index_hash { + if let Some(entry) = entries.iter().find(|entry| entry.file == fields[0]) { + let path = root.join(fields[0]); + let result = (|| -> Result { + verify(&path)?; + let current = state(&path, entry)?; + let digest = fingerprint(&bundle::read_bounded(&path)?); + Ok(fields[2] == current && fields[3] == digest) + })(); + match result { + Ok(true) => { write_cache(cache, &path, &index_hash, state(&path, entry)?)?; return Ok(path); } + Ok(false) => eprintln!("cached bundle state changed; scanning"), + Err(error) => eprintln!("cached bundle rejected: {error:#}"), + } + } + } + } + } + let mut candidates = Vec::new(); + for entry in &entries { + if !safe_name(&entry.file) { continue; } + let path = root.join(&entry.file); + if let Ok(meta) = fs::metadata(&path) { candidates.push((meta.len(), path, entry)); } + } + candidates.sort_by_key(|(size, ..)| std::cmp::Reverse(*size)); + eprintln!("Scanning {} bundle candidates", candidates.len()); + let mut hits = Vec::new(); + let mut errors = Vec::new(); + let total = candidates.len(); + for (number, (_, path, entry)) in candidates.into_iter().enumerate() { + if number % 1000 == 0 { eprintln!("Scanning {}/{}", number + 1, total); } + match bundle::bundle_name(&path) { + Ok(Some(name)) if name == LOGICAL => match state(&path, entry) { + Ok(status) if scan_state_is_eligible(status) => hits.push((path, status)), + Ok(status) => errors.push(format!("unsupported bundle state {status}: {}", path.display())), + Err(error) => errors.push(format!("{error:#}")), + }, + Ok(_) => {}, + Err(error) => { if errors.len() < 5 { errors.push(format!("{}: {error:#}", path.display())); } }, + } + } + if hits.len() != 1 { bail!("expected one valid Lua Matrix bundle, found {}; errors: {}", hits.len(), errors.join("; ")); } + let (path, state) = hits.remove(0); + if let Some(cache) = cache { write_cache(cache, &path, &index_hash, state)?; } + Ok(path) +} + +fn write_cache(cache: &Path, path: &Path, index_hash: &str, state: &str) -> Result<()> { + let name = path.file_name().context("bundle name missing")?.to_string_lossy(); + let hash = fingerprint(&bundle::read_bounded(path).with_context(|| format!("hash {}", path.display()))?); + if let Some(parent) = cache.parent() { fs::create_dir_all(parent)?; } + fs::write(cache, format!("{name}\n{index_hash}\n{state}\n{hash}\n")).with_context(|| format!("write cache {}", cache.display())) +} + +fn run() -> Result<()> { + let mut args = env::args_os().skip(1); + let first = args.next().context("usage: ascnet-moddetect [cache-file] | --verify ")?; + if first == "--verify" { + let path = args.next().map(PathBuf::from).context("missing bundle path")?; + if args.next().is_some() { bail!("too many arguments"); } + return verify(&path); + } + if first == "--record" { + let root = args.next().map(PathBuf::from).context("missing matrix directory")?; + let cache = args.next().map(PathBuf::from).context("missing cache path")?; + let name = args.next().context("missing bundle name")?.into_string().map_err(|_| anyhow::anyhow!("invalid bundle name"))?; + if args.next().is_some() || !safe_name(&name) { bail!("invalid record arguments"); } + let (entries, index_hash) = load_index(&root)?; + let entry = entries.iter().find(|entry| entry.file == name).context("bundle absent from index")?; + let path = root.join(name); + verify(&path)?; + return write_cache(&cache, &path, &index_hash, state(&path, entry)?); + } + let root = PathBuf::from(first); + let cache = args.next().map(PathBuf::from); + if args.next().is_some() { bail!("too many arguments"); } + let path = detect(&root, cache.as_deref())?; + println!("{}", path.file_name().context("bundle name missing")?.to_string_lossy()); + Ok(()) +} + +fn main() { + if let Err(error) = run() { eprintln!("moddetect: {error:#}"); std::process::exit(1); } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn validates_original_and_modified_against_index() -> Result<()> { + let dir = std::env::temp_dir().join(format!("ascnet-detect-{}", uuid::Uuid::new_v4())); + fs::create_dir(&dir)?; + let path = dir.join("0123456789abcdef.uab"); + let original = b"original"; + let entry = bundle::Entry { file: "0123456789abcdef.uab".into(), sha1: fingerprint(original), size: original.len() as u64, svn: 0, flag: 0 }; + fs::write(&path, original)?; + assert_eq!(state(&path, &entry)?, "original"); + fs::write(&path, b"modified")?; + assert!(state(&path, &entry).is_err()); + fs::write(format!("{}.ascnet-backup", path.display()), original)?; + assert_eq!(state(&path, &entry)?, "modified"); + fs::write(format!("{}.ascnet-backup", path.display()), b"wrong")?; + assert!(state(&path, &entry).is_err()); + fs::remove_dir_all(dir)?; + Ok(()) + } + + #[test] + fn rejects_invalid_names_without_panicking() { + assert!(safe_name("0123456789abcdef.uab")); + assert!(!safe_name("../../invalid.uab")); + assert!(!safe_name("ああああああ.uab")); + } + + #[test] + fn accepts_verified_modified_bundle_during_cache_recovery() { + assert!(scan_state_is_eligible("original")); + assert!(scan_state_is_eligible("modified")); + } +} diff --git a/Scripts/android/pack.ps1 b/Scripts/android/pack.ps1 new file mode 100644 index 00000000..359ce222 --- /dev/null +++ b/Scripts/android/pack.ps1 @@ -0,0 +1,113 @@ +param([Parameter(Mandatory)][string] $OutputDirectory, [string] $Gradle = 'gradle') +$ErrorActionPreference = 'Stop' + +$signingNames = @('ASCNET_KEYSTORE', 'ASCNET_KEYSTORE_PASSWORD', 'ASCNET_KEY_ALIAS', 'ASCNET_KEY_PASSWORD') +$missing = @($signingNames | Where-Object { [string]::IsNullOrWhiteSpace([Environment]::GetEnvironmentVariable($_)) }) +if ($missing.Count -gt 0) { throw "Release signing configuration is missing: $($missing -join ', ')" } +if (-not (Test-Path -LiteralPath $env:ASCNET_KEYSTORE -PathType Leaf)) { throw 'Release signing configuration: keystore file not found.' } + +function Invoke-Checked([string] $Tool, [string[]] $Arguments) { + & $Tool @Arguments + if ($LASTEXITCODE -ne 0) { throw "$Tool exited with $LASTEXITCODE" } +} + +function Copy-Runtime([string] $Source, [string] $Destination) { + $sourcePath = (Resolve-Path -LiteralPath $Source).Path.TrimEnd([IO.Path]::DirectorySeparatorChar) + foreach ($file in Get-ChildItem -LiteralPath $sourcePath -Recurse -Force -File) { + $relative = $file.FullName.Substring($sourcePath.Length + 1) + if ($relative -match '(^|[\\/])__pycache__([\\/]|$)' -or $file.Extension -in '.pyc', '.pyo') { continue } + $target = Join-Path $Destination $relative + $null = New-Item -ItemType Directory -Force -Path (Split-Path $target -Parent) + Copy-Item -LiteralPath $file.FullName -Destination $target + } +} + +$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent +$null = New-Item -ItemType Directory -Force -Path $OutputDirectory +$out = (Resolve-Path -LiteralPath $OutputDirectory).Path +if (@(Get-ChildItem -LiteralPath $out -Force).Count -ne 0) { throw 'Output directory must be empty.' } +$stage = (New-Item -ItemType Directory (Join-Path $out ('.infinite-loop-' + [guid]::NewGuid()))).FullName +$publish = Join-Path $stage 'server' +$package = Join-Path $stage 'package' +$null = New-Item -ItemType Directory -Path $publish, $package + +try { + +Invoke-Checked dotnet @('publish', (Join-Path $root 'AscNet/AscNet.csproj'), '-c', 'Release', '-r', 'linux-arm64', + '--self-contained', 'false', '-o', $publish, '--nologo') +Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'relay.py') -Destination (Join-Path $publish 'relay.py') +if (Get-ChildItem -LiteralPath $publish -Recurse -Force -File | Where-Object { + $_.Extension -in '.pcap','.pcapng','.wt','.bson','.log','.apk' +}) { throw "Unexpected runtime material in $publish" } +Invoke-Checked tar @('-czf', (Join-Path $package 'server-arm64.tar.gz'), '-C', $publish, '.') + +$launcher = Join-Path $PSScriptRoot 'launcher' +Invoke-Checked $Gradle @('-p', $launcher, ':app:assembleRelease', '--console=plain', '--no-daemon') +Copy-Item -LiteralPath (Join-Path $launcher 'app/build/outputs/apk/release/app-release.apk') -Destination (Join-Path $package 'Infinite-Loop.apk') +$sdk = if ($env:ANDROID_HOME) { $env:ANDROID_HOME } elseif ($env:ANDROID_SDK_ROOT) { $env:ANDROID_SDK_ROOT } else { Join-Path $env:LOCALAPPDATA 'Android/Sdk' } +$signer = Get-ChildItem -LiteralPath (Join-Path $sdk 'build-tools') -Directory | Sort-Object { [version]($_.Name -replace '-.*$','') } -Descending | ForEach-Object { Join-Path $_.FullName 'apksigner.bat' } | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 +if (-not $signer) { throw 'Android SDK apksigner not found.' } +Invoke-Checked $signer @('verify', '--verbose', (Join-Path $package 'Infinite-Loop.apk')) +$setup = [IO.File]::ReadAllText((Join-Path $PSScriptRoot 'setup.sh')).Replace("`r`n", "`n") +[IO.File]::WriteAllText((Join-Path $package 'setup.sh'), $setup, [Text.UTF8Encoding]::new($false)) +Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'README.md') -Destination $package +Copy-Runtime (Join-Path $PSScriptRoot 'runtime') (Join-Path $package 'runtime') + +# These three are not in the repository. The Android release workflow builds the first two on an ARM64 runner and puts them +# in Scripts/android/runtime before this script runs; the third comes from the pinned Shizuku release, checked by hash. +$packageRuntime = Join-Path $package 'runtime' +$detector = Join-Path $packageRuntime 'moddetect-aarch64' +$wheel = Join-Path $packageRuntime 'wheels/unitypy-1.25.2-cp312-cp312-linux_aarch64.whl' +foreach ($built in $detector, $wheel) { + if (-not (Test-Path -LiteralPath $built -PathType Leaf)) { throw "Missing $(Split-Path $built -Leaf): build it first (see .github/workflows/android-release.yml)." } +} +$shizukuApk = 'shizuku-v13.6.0.r1086.2650830c-release.apk' +$shizukuSha256 = '6e273ab0e991c4e79bc8b1bbb9b9dd739ccac1a8712a541a214078886b7b790f' +$rishDexSha256 = '1953c1fd9708904f8fc1f67774843b4cc3d03e5f2a578ff4d654d0625456bc28' +$apkPath = Join-Path $stage $shizukuApk +Invoke-WebRequest -Uri "https://github.com/RikkaApps/Shizuku/releases/download/v13.6.0/$shizukuApk" -OutFile $apkPath +if ((Get-FileHash -LiteralPath $apkPath -Algorithm SHA256).Hash.ToLowerInvariant() -ne $shizukuSha256) { throw 'Shizuku release APK does not match its pinned hash.' } +Add-Type -AssemblyName System.IO.Compression.FileSystem +$apk = [IO.Compression.ZipFile]::OpenRead($apkPath) +try { + $dexPath = Join-Path $packageRuntime 'rish/rish_shizuku.dex' + $null = New-Item -ItemType Directory -Force -Path (Split-Path $dexPath -Parent) + [IO.Compression.ZipFileExtensions]::ExtractToFile($apk.GetEntry('assets/rish_shizuku.dex'), $dexPath, $true) +} finally { + $apk.Dispose() +} +if ((Get-FileHash -LiteralPath $dexPath -Algorithm SHA256).Hash.ToLowerInvariant() -ne $rishDexSha256) { throw 'rish_shizuku.dex does not match its pinned hash.' } +# The wheel is built per release, so its hash goes into the lock that ships with it. +$lockPath = Join-Path $packageRuntime 'requirements.lock' +$wheelSha256 = (Get-FileHash -LiteralPath $wheel -Algorithm SHA256).Hash.ToLowerInvariant() +$lock = [IO.File]::ReadAllText($lockPath) +if (-not $lock.Contains('@UNITYPY_SHA256@')) { throw 'requirements.lock lost its UnityPy hash placeholder.' } +[IO.File]::WriteAllText($lockPath, $lock.Replace('@UNITYPY_SHA256@', $wheelSha256), [Text.UTF8Encoding]::new($false)) +Copy-Item -LiteralPath (Join-Path $root 'Scripts/pgr_gm_bundle.py') -Destination $package +Copy-Item -LiteralPath (Join-Path $root 'Scripts/pgr_bundles.py') -Destination $package +Copy-Item -LiteralPath (Join-Path $root 'Mods') -Destination (Join-Path $package 'Mods') -Recurse + +function Write-Manifest([string] $Directory, [string] $Path, [string[]] $Extra = @()) { + $files = @(Get-ChildItem -LiteralPath $Directory -File -Recurse | Where-Object { + $_.Name -ne 'SHA256SUMS' -and ($Directory -ne $out -or -not $_.FullName.StartsWith($stage + [IO.Path]::DirectorySeparatorChar)) + }) + @($Extra | ForEach-Object { Get-Item -LiteralPath $_ }) + $lines = foreach ($file in ($files | Sort-Object FullName)) { + $name = if ($file.FullName.StartsWith($Directory + [IO.Path]::DirectorySeparatorChar)) { $file.FullName.Substring($Directory.Length + 1).Replace('\','/') } else { $file.Name } + "$( (Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash.ToLowerInvariant() ) $name" + } + [IO.File]::WriteAllLines($Path, [string[]]$lines, [Text.UTF8Encoding]::new($false)) +} +Write-Manifest $package (Join-Path $package 'SHA256SUMS') +$zip = Join-Path $stage 'Infinite-Loop-Android.zip' +Compress-Archive -Path (Join-Path $package '*') -DestinationPath $zip +foreach ($item in Get-ChildItem -LiteralPath $package) { + if (Test-Path -LiteralPath (Join-Path $out $item.Name)) { throw "Output already exists: $($item.Name)" } +} +if (Test-Path -LiteralPath (Join-Path $out 'Infinite-Loop-Android.zip')) { throw 'Output already exists: Infinite-Loop-Android.zip' } +Copy-Item -Path (Join-Path $package '*') -Destination $out -Recurse +Copy-Item -LiteralPath $zip -Destination $out +Write-Manifest $out (Join-Path $out 'SHA256SUMS') +Write-Output "Release package: $(Join-Path $out 'Infinite-Loop-Android.zip')" +} finally { + if (Test-Path -LiteralPath $stage) { Remove-Item -LiteralPath $stage -Recurse -Force } +} diff --git a/Scripts/android/relay.py b/Scripts/android/relay.py new file mode 100644 index 00000000..9e8e864a --- /dev/null +++ b/Scripts/android/relay.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +import re +import sys +from mitmproxy import http + +# The region comes from the package id in the config path, not from a fixed package list: store builds of the same +# region (Google Play adds ".gplay.", JP's uses the herogame publisher) differ only in the id's prefix, and an +# exact match silently left those clients on the official servers. The host only has to be a Kuro CDN domain. +DOMAINS = ("pgr-game.com", "kurogame.com") +PACKAGE = ( + r"com\.(?:kurogame|herogame)\.(?:gplay\.)?" + r"(?:punishing\.grayraven\.(?Pen|jp|tw|kr)|haru\.(?Pkuro|hero))" +) +VERSION = r"\d+(?:\.\d+)+" +PATH = re.compile( + rf"^/prod/client/config/(?:[A-Za-z0-9_-]+/)?(?P{PACKAGE})/{VERSION}/android/config\.tab$" +) +# Same request shape with any package id: lets us report clients we did not recognise instead of ignoring them. +CONFIG_PATH = re.compile( + rf"^/prod/client/config/(?:[A-Za-z0-9_-]+/)?(?P[^/]+)/{VERSION}/android/config\.tab$" +) +KEY = re.compile(r"^(?:Channel)?ServerListStr(?:[._-]\d+(?:[._]\d+)*)?$") +URL = re.compile(r"https?://[^\s#|;\t\r\n]+") +reported: set[str] = set() + + +def _config_request(request: http.Request) -> re.Match[str] | None: + if request.scheme.lower() != "http" or request.method.upper() != "GET": + return None + host = request.host.rstrip(".").lower() + if not any(host == domain or host.endswith("." + domain) for domain in DOMAINS): + return None + return CONFIG_PATH.fullmatch(request.path.split("?", 1)[0]) + + +def region(request: http.Request) -> str | None: + if _config_request(request) is None: + return None + match = PATH.fullmatch(request.path.split("?", 1)[0]) + if match is None: + return None + return match.group("region") or "cn" + + +def report_unrecognised(request: http.Request) -> None: + """A PGR config request whose package id is not a known region: log it once so relay.log shows why nothing was redirected.""" + match = _config_request(request) + if match is None or region(request) is not None or match.group("package") in reported: + return + reported.add(match.group("package")) + print(f"relay: unrecognised client package {match.group('package')!r} on {request.host}; not redirected", file=sys.stderr, flush=True) + + +def response(flow: http.HTTPFlow) -> None: + name = region(flow.request) + if name is None: + report_unrecognised(flow.request) + return + if flow.response is None or not 200 <= flow.response.status_code < 300: + return + try: + lines = flow.response.get_content(strict=True).decode("utf-8").splitlines(keepends=True) + except UnicodeDecodeError: + return + gate = f"http://127.0.0.1:8080/api/Login/Login-{name}-android" + changed = False + output: list[str] = [] + for line in lines: + content = line.rstrip("\r\n") + suffix = line[len(content):] + columns = content.split("\t", 3) + if len(columns) >= 3 and KEY.fullmatch(columns[0]) and URL.search(columns[2]): + columns[2] = URL.sub(gate, columns[2]) + line = "\t".join(columns) + suffix + changed = True + output.append(line) + if changed: + flow.response.content = "".join(output).encode("utf-8") diff --git a/Scripts/android/runtime/modctl.py b/Scripts/android/runtime/modctl.py new file mode 100644 index 00000000..d195d4af --- /dev/null +++ b/Scripts/android/runtime/modctl.py @@ -0,0 +1,266 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import os +import re +import shlex +import shutil +import subprocess +import sys +from pathlib import Path + + +# Full match only: the package id is interpolated into shell commands (including rm -rf), so it must stay a +# closed pattern. Keep it identical to launcher ClientPackages.java and relay.py. +PACKAGE = re.compile( + r"com\.(?:kurogame|herogame)\.(?:gplay\.)?(?:punishing\.grayraven\.(?:en|jp|tw|kr)|haru\.(?:kuro|hero))" +) +STAGING = "/sdcard/Download/InfiniteLoop/mod-staging/Lua/Matrix" +BUNDLE_STAGING = "/sdcard/Download/InfiniteLoop/mod-staging/bundles" +SOURCE_STAGING = "/sdcard/Download/InfiniteLoop/mod-staging/source" +DETECTOR_SHARED = "/sdcard/Download/InfiniteLoop/moddetect-aarch64" +DETECTOR_EXECUTABLE = "/data/local/tmp/infinite-loop-moddetect" + + +def target_root(package_name: str) -> str: + if not PACKAGE.fullmatch(package_name): + raise ValueError(f"unsupported package: {package_name}") + return f"/sdcard/Android/data/{package_name}/files/Lua/Matrix" + + +def probe_script(package_name: str) -> str: + root = target_root(package_name) + marker = f"{root}/.ascnet-shizuku-probe" + return ( + "set -eu; " + f"mkdir -p '{root}'; " + f"printf '%s\\n' ascnet-shizuku > '{marker}'; " + f"cat '{marker}'; " + f"rm -f '{marker}'" + ) + + +def install_script(package_name: str) -> str: + root = target_root(package_name) + backup = root + ".ascnet-backup" + return ( + "set -eu; " + f"test -d '{STAGING}'; " + f"if [ ! -d '{backup}' ] && [ -d '{root}' ]; then mv '{root}' '{backup}'; else rm -rf '{root}'; fi; " + f"mkdir -p '{root}'; " + f"cp -R '{STAGING}/.' '{root}/'" + ) + + +def remove_script(package_name: str) -> str: + root = target_root(package_name) + backup = root + ".ascnet-backup" + return ( + "set -eu; " + f"rm -rf '{root}'; " + f"if [ -d '{backup}' ]; then mv '{backup}' '{root}'; fi" + ) + + +def bundle_target(package_name: str, bundle_name: str) -> str: + if not PACKAGE.fullmatch(package_name): + raise ValueError(f"unsupported package: {package_name}") + if not re.fullmatch(r"[0-9a-f]{16}\.uab", bundle_name): + raise ValueError(f"invalid bundle name: {bundle_name}") + return f"/sdcard/Android/data/{package_name}/files/document/matrix/{bundle_name}" + + +def stopped_script(package_name: str) -> str: + if not PACKAGE.fullmatch(package_name): + raise ValueError(f"unsupported package: {package_name}") + return ( + f"if pidof '{package_name}' >/dev/null 2>&1; then " + "echo 'Close PGR before changing MODs.' >&2; exit 20; fi; " + ) + + +def detector_script(package_name: str) -> str: + if not PACKAGE.fullmatch(package_name): + raise ValueError(f"unsupported package: {package_name}") + root = f"/sdcard/Android/data/{package_name}/files/document/matrix" + cache = f"/sdcard/Download/InfiniteLoop/moddetect-{package_name}.txt" + return ( + "set -eu; " + stopped_script(package_name) + + f"test -f '{DETECTOR_SHARED}'; " + + f"cp -f '{DETECTOR_SHARED}' '{DETECTOR_EXECUTABLE}'; " + + f"chmod 0755 '{DETECTOR_EXECUTABLE}'; " + + f"'{DETECTOR_EXECUTABLE}' '{root}' '{cache}'" + ) + + +def detected_bundle(output: str) -> str: + matches = [ + line.strip() + for line in output.splitlines() + if re.fullmatch(r"[0-9a-f]{16}\.uab", line.strip()) + ] + if len(matches) != 1: + raise ValueError(f"invalid detector output: {output.strip()!r}") + return matches[0] + + +def install_bundle_script(package_name: str, bundle_name: str) -> str: + source = f"{BUNDLE_STAGING}/{bundle_name}" + target = bundle_target(package_name, bundle_name) + backup = target + ".ascnet-backup" + temporary = target + ".ascnet-tmp" + rollback = target + ".ascnet-rollback" + root = f"/sdcard/Android/data/{package_name}/files/document/matrix" + cache = f"/sdcard/Download/InfiniteLoop/moddetect-{package_name}.txt" + return ( + "set -eu; " + stopped_script(package_name) + + f"test -f '{source}'; " + f"test -f '{target}'; " + f"test -x '{DETECTOR_EXECUTABLE}'; " + f"rm -f '{temporary}' '{rollback}'; " + f"cp -f '{source}' '{temporary}'; " + f"'{DETECTOR_EXECUTABLE}' --verify '{temporary}'; " + f"cp -p '{target}' '{rollback}'; " + f"trap \"code=\\$?; rm -f '{temporary}'; " + f"if [ \\$code -ne 0 ] && [ -f '{rollback}' ]; then mv -f '{rollback}' '{target}'; " + f"else rm -f '{rollback}'; fi; exit \\$code\" EXIT; " + f"if [ ! -f '{backup}' ]; then cp -p '{target}' '{backup}'; fi; " + f"mv -f '{temporary}' '{target}'; " + f"'{DETECTOR_EXECUTABLE}' --record '{root}' '{cache}' '{bundle_name}'; " + f"rm -f '{rollback}'; trap - EXIT" + ) + + +def stage_bundle_script(package_name: str, bundle_name: str) -> str: + target = bundle_target(package_name, bundle_name) + backup = target + ".ascnet-backup" + staged = f"{SOURCE_STAGING}/{bundle_name}" + return ( + "set -eu; " + stopped_script(package_name) + + f"test -f '{target}'; " + f"mkdir -p '{SOURCE_STAGING}'; " + f"if [ -f '{backup}' ]; then cp -f '{backup}' '{staged}'; else cp -f '{target}' '{staged}'; fi" + ) + + +def remove_bundle_script(package_name: str, bundle_name: str) -> str: + target = bundle_target(package_name, bundle_name) + backup = target + ".ascnet-backup" + return ( + "set -eu; " + stopped_script(package_name) + + f"test -f '{backup}'; " + f"mv -f '{backup}' '{target}'" + ) + + +CLIENT_LOG = "/sdcard/Download/InfiniteLoop/client.log" + + +def logcat_script(package_name: str) -> str: + package = shlex.quote(package_name) + return ( + f"pid=$(pidof {package} | cut -d' ' -f1); " + "if [ -n \"$pid\" ]; then logcat -d -v threadtime --pid=\"$pid\" -t 5000; " + f"else logcat -d -v threadtime -t 20000 | grep -E {package}'|Unity|AndroidRuntime|DEBUG'; fi" + ) + + +class RishClient: + def __init__(self, executable: str): + self.executable = executable + + def run(self, script: str) -> str: + env = os.environ.copy() + env["RISH_APPLICATION_ID"] = "com.termux" + try: + result = subprocess.run( + [self.executable, "-c", script], + check=False, + capture_output=True, + text=True, + env=env, + timeout=300, + ) + except subprocess.TimeoutExpired as error: + raise RuntimeError(f"rish timed out after {error.timeout}s; stdout: {error.stdout!r}; stderr: {error.stderr!r}") from error + if result.stderr: + print(result.stderr, file=sys.stderr, end="") + if result.returncode != 0: + details = [f"rish exit {result.returncode}"] + if result.stdout.strip(): + details.append("stdout:\n" + result.stdout.strip()) + if result.stderr.strip(): + details.append("stderr:\n" + result.stderr.strip()) + raise RuntimeError("\n".join(details)) + return "\n".join(part for part in (result.stdout.strip(), result.stderr.strip()) if part) + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--rish", default=os.path.expanduser("~/.local/share/infinite-loop/rish/rish")) + subcommands = parser.add_subparsers(dest="command", required=True) + probe = subcommands.add_parser("probe") + probe.add_argument("--package", required=True) + install = subcommands.add_parser("install") + install.add_argument("--package", required=True) + install.add_argument("--bundle") + remove = subcommands.add_parser("remove") + remove.add_argument("--package", required=True) + remove.add_argument("--bundle") + stage = subcommands.add_parser("stage") + stage.add_argument("--package", required=True) + stage.add_argument("--bundle", required=True) + logcat = subcommands.add_parser("logcat") + logcat.add_argument("--package", required=True) + discover = subcommands.add_parser("discover") + discover.add_argument("--package", required=True) + discover.add_argument("--plain", action="store_true") + args = parser.parse_args() + + try: + if args.command == "probe": + output = RishClient(args.rish).run(probe_script(args.package)) + print(json.dumps({"ok": True, "package": args.package, "output": output})) + return 0 + if args.command == "install": + script = install_bundle_script(args.package, args.bundle) if args.bundle else install_script(args.package) + RishClient(args.rish).run(script) + print(json.dumps({"ok": True, "package": args.package, "bundle": args.bundle, "installed": True})) + return 0 + if args.command == "remove": + script = remove_bundle_script(args.package, args.bundle) if args.bundle else remove_script(args.package) + RishClient(args.rish).run(script) + print(json.dumps({"ok": True, "package": args.package, "bundle": args.bundle, "installed": False})) + return 0 + if args.command == "stage": + RishClient(args.rish).run(stage_bundle_script(args.package, args.bundle)) + print(json.dumps({"ok": True, "package": args.package, "bundle": args.bundle, "staged": True})) + return 0 + if args.command == "logcat": + output = RishClient(args.rish).run(logcat_script(args.package)) + Path(CLIENT_LOG).parent.mkdir(parents=True, exist_ok=True) + Path(CLIENT_LOG).write_text(output + "\n", encoding="utf-8") + print(json.dumps({"ok": True, "package": args.package, "lines": output.count("\n") + 1})) + return 0 + if args.command == "discover": + detector = Path(__file__).with_name("moddetect-aarch64") + if not detector.is_file(): + raise ValueError(f"MOD detector missing: {detector}") + Path(DETECTOR_SHARED).parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(detector, DETECTOR_SHARED) + bundle_name = detected_bundle(RishClient(args.rish).run(detector_script(args.package))) + if args.plain: + print(bundle_name) + else: + print(json.dumps({"ok": True, "package": args.package, "bundle": bundle_name})) + return 0 + except (OSError, RuntimeError, ValueError) as error: + print(json.dumps({"ok": False, "error": str(error)})) + return 1 + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/Scripts/android/runtime/requirements.lock b/Scripts/android/runtime/requirements.lock new file mode 100644 index 00000000..73f4c7e2 --- /dev/null +++ b/Scripts/android/runtime/requirements.lock @@ -0,0 +1,54 @@ +# CPython 3.12 on Linux ARM64; install with pip --require-hashes. +aioquic==1.2.0 --hash=sha256:2466499759b31ea4f1d17f4aeb1f8d4297169e05e3c1216d618c9757f4dd740d +archspec==0.2.8 --hash=sha256:86bddef275d9660fe4dee2cee969b946eccfbece19aab77341e6c1d674960d5c +asgiref==3.8.1 --hash=sha256:3e1e3ecc849832fe52ccf2cb6686b7a55f82bb1d6aee72a58826471390335e47 +astc-encoder-py==0.1.12 --hash=sha256:feada45aea860f0e6db9c0bcec2010efe86ae4a97a04a7b9e649c3f5da5b9723 +attrs==26.1.0 --hash=sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309 +blinker==1.9.0 --hash=sha256:ba0efaa9080b619ff2f3459d1d500c57bddea4a6b424b60a91141db6fd2f08bc +Brotli==1.1.0 --hash=sha256:70051525001750221daa10907c77830bc889cb6d865cc0b813d9db7fefc21451 +certifi==2026.11.20 --hash=sha256:7422df25243767b9877031a2248cb14d09ddac9beee846f4cef3d5c9191d488f +cffi==2.1.1 --hash=sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890 +click==8.5.1 --hash=sha256:8bb5376d2006950386f8c6427613334a2acadc5f559cb80e638d00b4df957e37 +cryptography==44.0.3 --hash=sha256:ab0b005721cc0039e885ac3503825661bd9810b15d4f374e473f8c89b7d5460c +etcpak==0.9.15 --hash=sha256:a5c4c6ebe3a5aaf907afa14619071cd5bc60857f175491d04cbacedbba561d5c +Flask==3.1.0 --hash=sha256:d667207822eb83f1c4b50949b1623c8fc8d51f2341d65f72e1a1815397551136 +fmod_toolkit==0.1.3 --hash=sha256:5abeadaba90a7620fa1cf49bde0566545dc9aac644136536c642e1dd8f039fde +fsspec==2026.9.0 --hash=sha256:8dd6e646e99ea382bd85f97a45e6b526a442d79423a7dc673f1e2756d05fcb5f +h11==0.14.0 --hash=sha256:e3fe4ac4b851c468cc8363d500db52c2ead036020723024a109d37346efaa761 +h2==4.1.0 --hash=sha256:03a46bcf682256c95b5fd9e9a99c1323584c3eec6440d379b9903d709476bc6d +hpack==4.2.0 --hash=sha256:858ac0b02280fa582b5080d68db0899c62a80375e0e5413a74970c5e518b6986 +hyperframe==6.0.1 --hash=sha256:0ec6bafd80d8ad2195c4f03aacba3a8265e57bc4cff261e802bf39970ed02a15 +itsdangerous==2.2.0 --hash=sha256:c6242fc49e35958c8b15141343aa660db5fc54d4f13a1db01a3f5891b98700ef +Jinja2==3.1.6 --hash=sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67 +kaitaistruct==0.10 --hash=sha256:a97350919adbf37fda881f75e9365e2fb88d04832b7a4e57106ec70119efb235 +ldap3==2.9.1 --hash=sha256:5869596fc4948797020d3f03b7939da938778a0f9e2009f7a072ccf92b8e8d70 +lz4==4.4.5 --hash=sha256:2c3ea562c3af274264444819ae9b14dbbf1ab070aff214a05e97db6896c7597e +MarkupSafe==3.0.4 --hash=sha256:6a45c3d514f2436064db00d7fc8778d888f0236ebfed649b53d13a59e69ad51b +mitmproxy==11.0.2 --hash=sha256:95db7b57b21320a0c76e59e1d6644daaa431291cdf89419608301424651199b4 +mitmproxy_rs==0.10.7 --hash=sha256:bb648320f9007378f67d70479727db862faa2b7832dddaa4eef376d8c94d8388 +msgpack==1.1.0 --hash=sha256:4676e5be1b472909b2ee6356ff425ebedf5142427842aa06b4dfd5117d1ca8a2 +passlib==1.7.4 --hash=sha256:aa6bca462b8d8bda89c70b382f0c298a20b5560af6cbfa2dce410c0a2fb669f1 +pillow==13.0.0 --hash=sha256:8bf295fe459343bc6093c8e5e0df60bfa189e0fcb775a22e2c2488fdeccc6c0d +publicsuffix2==2.20191221 --hash=sha256:786b5e36205b88758bd3518725ec8cfe7a8173f5269354641f581c6b80a99893 +pyasn1==0.6.5 --hash=sha256:4017b0fce125096b8573b39c989fdb1a4b19cf761e683398184550fea0e66587 +pyasn1_modules==0.4.2 --hash=sha256:29253a9207ce32b64c3ac6600edc75368f98473906e8fd1043bd6b5b1de2c14a +pycparser==3.12 --hash=sha256:a076f3f489b39b43ed13563a1dafe42447445bec2e294154ec5c57fcdda4c85e +pycryptodome==3.23.0 --hash=sha256:67bd81fcbe34f43ad9422ee8fd4843c8e7198dd88dd3d40e6de42ee65fbe1490 +pyfmodex==0.7.2 --hash=sha256:1c42112b788e80ee7b4b57ae25bbbc0a98eb1e32a8e7c9e1246698cdf72efa9d +pylsqpack==0.3.24 --hash=sha256:e3f977d419c60c1d6c2240e6d7a52df820d37eb8c36b4057113bcd7859f53e2c +pyOpenSSL==24.3.0 --hash=sha256:e474f5a473cd7f92221cc04976e48f4d11502804657a08a989fb3be5514c904a +pyparsing==3.2.0 --hash=sha256:93d9577b88da0bbea8cc8334ee8b918ed014968fd2ec383e868fb8afb1ccef84 +pyperclip==1.9.0 --hash=sha256:b7de0142ddc81bfc5c7507eea19da920b92252b548b96186caf94a5e2527d310 +ruamel.yaml==0.18.6 --hash=sha256:57b53ba33def16c4f3d807c0ccbc00f8a6081827e81ba2491691b76882d0c636 +ruamel.yaml.clib==0.2.15 --hash=sha256:71845d377c7a47afc6592aacfea738cc8a7e876d586dfba814501d8c53c1ba60 +service-identity==24.2.0 --hash=sha256:6b047fbd8a84fd0bb0d55ebce4031e400562b9196e1e0d3e0fe2b8a59f6d4a85 +sortedcontainers==2.4.0 --hash=sha256:a163dcaede0f1c021485e957a39245190e74249897e2ae4b2aa38595db237ee0 +texture2ddecoder==1.0.6 --hash=sha256:e83343e9ec30e2c9a5c83c1ae39ff6ec3010bf92b00ddb612f764066528f02bf +tornado==6.4.2 --hash=sha256:1a017d239bd1bb0919f72af256a970624241f070496635784d9bf0db640d3fec +typing_extensions==4.16.0 --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 +UnityPy @ file:///mnt/mod-builder/wheels/unitypy-1.25.2-cp312-cp312-linux_aarch64.whl --hash=sha256:@UNITYPY_SHA256@ +urwid==2.6.16 --hash=sha256:de14896c6df9eb759ed1fd93e0384a5279e51e0dde8f621e4083f7a8368c0797 +wcwidth==0.9.5 --hash=sha256:a631629c8a131f7fa58c99bc0630f7011bcdc385146b1ebac9d74becba2b6a90 +Werkzeug==3.1.9 --hash=sha256:6392e50c78460ba618e5b21f08a71f59c99ce99cdc6cf6e3dd7e6ccca8754fab +wsproto==1.2.0 --hash=sha256:b9acddd652b585d75b20477888c56642fdade28bdfd3579aa24a4d2c037dd736 +zstandard==0.23.0 --hash=sha256:b0e166f698c5a3e914947388c162be2583e0c638a4703fc6a543e23a88dea3c1 diff --git a/Scripts/android/runtime/rish/LICENSE b/Scripts/android/runtime/rish/LICENSE new file mode 100644 index 00000000..2a779796 --- /dev/null +++ b/Scripts/android/runtime/rish/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 RikkaW + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Scripts/android/runtime/rish/rish b/Scripts/android/runtime/rish/rish new file mode 100644 index 00000000..ccf6eb59 --- /dev/null +++ b/Scripts/android/runtime/rish/rish @@ -0,0 +1,25 @@ +#!/system/bin/sh +BASEDIR=$(dirname "$0") +DEX="$BASEDIR"/rish_shizuku.dex + +if [ ! -f "$DEX" ]; then + echo "Cannot find $DEX, please check the tutorial in Shizuku app" + exit 1 +fi + +if [ $(getprop ro.build.version.sdk) -ge 34 ]; then + if [ -w $DEX ]; then + echo "On Android 14+, app_process cannot load writable dex." + echo "Attempting to remove the write permission..." + chmod 400 $DEX + fi + if [ -w $DEX ]; then + echo "Cannot remove the write permission of $DEX." + echo "You can copy to file to terminal app's private directory (/data/data/, so that remove write permission is possible" + exit 1 + fi +fi + +# Replace "PKG" with the application id of your terminal app +[ -z "$RISH_APPLICATION_ID" ] && export RISH_APPLICATION_ID="PKG" +/system/bin/app_process -Djava.class.path="$DEX" /system/bin --nice-name=rish rikka.shizuku.shell.ShizukuShellLoader "$@" diff --git a/Scripts/android/runtime/wheels/UnityPy-LICENSE b/Scripts/android/runtime/wheels/UnityPy-LICENSE new file mode 100644 index 00000000..6bc7be1f --- /dev/null +++ b/Scripts/android/runtime/wheels/UnityPy-LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019-2021 K0lb3 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Scripts/android/setup.sh b/Scripts/android/setup.sh new file mode 100644 index 00000000..393ea259 --- /dev/null +++ b/Scripts/android/setup.sh @@ -0,0 +1,414 @@ +#!/usr/bin/env bash +set -Eeuo pipefail + +current_phase=initializing +failure() { + printf 'phase=%s status=failed exit=%s line=%s command=%s\n' \ + "$current_phase" "$1" "$2" "$3" >&2 +} +die() { printf '%s\n' "$*" >&2; failure 1 "${BASH_LINENO[0]}" die; exit 1; } +listening() { timeout 1 bash -c ': /dev/null; } +process_alive() { + local state + kill -0 "$1" 2>/dev/null || return 1 + state=$(ps -o stat= -p "$1" 2>/dev/null | awk '{print $1}') + [[ -n $state && $state != Z* ]] +} +service_exited() { + local name=$1 pid=$2 code=0 + wait "$pid" || code=$? + die "$name exited unexpectedly (exit $code)." +} +phase() { current_phase=$1; printf 'phase=%s status=%s\n' "$1" "${2:-ok}"; } +trap 'code=$?; failure "$code" "$LINENO" "$BASH_COMMAND"' ERR +script_dir=$(cd -- "$(dirname -- "$0")" && pwd) + +ensure_distro() { + local login_error listing + if login_error=$(proot-distro login "$distro" -- /usr/bin/true 2>&1); then + return 0 + fi + if ! listing=$(proot-distro list); then + printf '%s\n' "$login_error" >&2 + printf '%s\n' 'Could not list PRoot distributions.' >&2 + return 1 + fi + if printf '%s\n' "$listing" | grep -Fq "$distro"; then + printf '%s\n' "$login_error" >&2 + return 1 + fi + proot-distro install ubuntu:24.04 --name "$distro" +} + +cleanup_runtime_venvs() { + local link=$1 active candidate + active=$(readlink -f -- "$link") || return 1 + for candidate in "$base"/venvs/runtime.*; do + [[ -e $candidate || -L $candidate ]] || continue + [[ $(readlink -f -- "$candidate") == "$active" ]] && continue + if [[ -L $candidate ]]; then + unlink "$candidate" + elif [[ -d $candidate ]]; then + rm -rf -- "$candidate" + fi + done +} + +install_python_runtime() { + local venv=$1 + python3 -c 'import platform, sys; assert sys.version_info[:2] == (3, 12) and platform.machine() in ("aarch64", "arm64"), "Python 3.12 ARM64 is required"' + [[ -s /mnt/mod-builder/wheels/unitypy-1.25.2-cp312-cp312-linux_aarch64.whl ]] || die 'UnityPy ARM64 wheel is missing.' + [[ -s /mnt/mod-builder/requirements.lock ]] || die 'Python dependency lock is missing.' + python3 -m venv "$venv" + "$venv/bin/python" -m pip install --require-hashes -r /mnt/mod-builder/requirements.lock +} + +verify_runtime() { + local target=$1 venv=${2:-$1/.venv} + [[ -s $target/AscNet.dll && -f $target/relay.py && -d $target/Configs && -d $target/table ]] \ + || die 'Server runtime is incomplete.' + [[ -x $target/mongo/usr/bin/mongod ]] || die 'MongoDB runtime is missing.' + "$target/mongo/usr/bin/mongod" --version >/dev/null + "$venv/bin/python" -c 'import platform, sys, importlib.metadata; import Crypto, UnityPy, mitmproxy; assert sys.version_info[:2] == (3, 12) and platform.machine() in ("aarch64", "arm64"), "Python 3.12 ARM64 is required"; assert importlib.metadata.version("UnityPy") == "1.25.2", "Incorrect UnityPy version"' + "$venv/bin/python" -m pip check + dotnet --list-runtimes | grep -q '^Microsoft.AspNetCore.App 10\.' || die '.NET 10 ASP.NET runtime is missing.' +} + +guest_install() { + local payload=$1 stage= new_venv= replaced_app= + mkdir -p "$base" + phase 'Installing all dependencies' running + apt-get -o Acquire::Retries=3 update + DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=3 install -y --no-install-recommends \ + curl ca-certificates gnupg aspnetcore-runtime-10.0 python3 python3-venv + stage=$(mktemp -d "$base/.setup.XXXXXXXX") + cleanup_guest_install() { + local code=$? + set +e + [[ -z $new_venv ]] || rm -rf -- "$new_venv" + if [[ -n $replaced_app && -e $replaced_app && ! -e $app ]]; then + mv -T "$replaced_app" "$app" + fi + [[ -z $stage ]] || rm -rf -- "$stage" + return "$code" + } + trap cleanup_guest_install EXIT + + if [[ -x $app/mongo/usr/bin/mongod ]]; then + cp -a "$app/mongo" "$stage/mongo" + else + curl --retry 3 --retry-all-errors -fsSL https://pgp.mongodb.com/server-7.0.asc \ + | gpg --batch --dearmor > "$stage/mongodb-7.gpg" + install -m 0644 "$stage/mongodb-7.gpg" /usr/share/keyrings/infinite-loop-mongodb-7.gpg + printf '%s\n' 'deb [arch=arm64 signed-by=/usr/share/keyrings/infinite-loop-mongodb-7.gpg] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse' \ + > /etc/apt/sources.list.d/infinite-loop-mongodb-7.list + apt-get -o Acquire::Retries=3 update + + local version deb dependencies + version=$(apt-cache policy mongodb-org-server | awk '/Candidate:/ { print $2 }') + [[ $version == 7.0.* ]] || die 'MongoDB 7 package unavailable.' + (cd "$stage" && apt-get download "mongodb-org-server=$version") + local -a packages=("$stage"/mongodb-org-server_*_arm64.deb) + deb=${packages[0]} + [[ -f $deb ]] || die 'MongoDB ARM64 package missing.' + dependencies=$(dpkg-deb -f "$deb" Depends) + if [[ -n $dependencies ]]; then + DEBIAN_FRONTEND=noninteractive apt-get satisfy -y "$dependencies" + fi + dpkg-deb -x "$deb" "$stage/mongo" + fi + mkdir "$stage/server" + tar -xzf "$payload" --no-same-owner -C "$stage/server" + [[ -s $stage/server/AscNet.dll && -f $stage/server/relay.py && -d $stage/server/Configs && -d $stage/server/table ]] \ + || die 'Server build is incomplete.' + mv "$stage/mongo" "$stage/server/mongo" + mkdir -p "$base/venvs" + new_venv=$(mktemp -d "$base/venvs/runtime.XXXXXXXX") + if ! (install_python_runtime "$new_venv" && verify_runtime "$stage/server" "$new_venv"); then + die 'Could not build the Python runtime.' + fi + ln -s "$new_venv" "$stage/server/.venv" + phase 'Dependencies installed' + phase 'Runtime verified' + if [[ -e $app || -L $app ]]; then + replaced_app=$(mktemp -d "$base/.replaced.XXXXXXXX") + rmdir "$replaced_app" + mv -T "$app" "$replaced_app" + fi + mv -T "$stage/server" "$app" + [[ -z $replaced_app ]] || rm -rf -- "$replaced_app" + replaced_app= + new_venv= + cleanup_runtime_venvs "$app/.venv" + phase 'Setup complete' +} + +enable_client_debug() { + "$app/.venv/bin/python" - "$1" <<'PY' +import json, sys +path = sys.argv[1] +with open(path, encoding='utf-8-sig') as source: + config = json.load(source) +config.setdefault('Client', {})['Debug'] = True +with open(path, 'w', encoding='utf-8', newline='\n') as target: + json.dump(config, target, indent=2) +PY +} + +guest_start() { + control=/mnt/infinite-loop-control + logs=/mnt/infinite-loop-logs + [[ -d $logs ]] || logs=$base + [[ -f $app/AscNet.dll ]] || die 'Run install first.' + verify_runtime "$app" + mkdir -p "$base/db" + exec 9>"$base/run.lock" + flock -n 9 || die 'Already running.' + if [[ -e $control/stop ]]; then unlink "$control/stop"; fi + for port in 27017 8080 2335 18084; do + if listening "$port"; then die "Port $port is already in use."; fi + done + + fifo=$(mktemp -d "$base/.run.XXXXXXXX") + mkfifo -m 600 "$fifo/commands" + exec 3<> "$fifo/commands" + db_pid= game_pid= relay_pid= + cleanup() { + local result=$? + trap - EXIT INT TERM HUP + if [[ -n $game_pid ]] && kill -0 "$game_pid" 2>/dev/null; then + printf 'shutdown\n' >&3 + wait "$game_pid" || true + fi + if [[ -n $db_pid ]]; then + kill -TERM "$db_pid" 2>/dev/null || true + wait "$db_pid" || true + fi + if [[ -n $relay_pid ]]; then + kill -TERM "$relay_pid" 2>/dev/null || true + wait "$relay_pid" || true + fi + exec 3>&- + unlink "$fifo/commands" + rmdir "$fifo" + if [[ -e $control/stop ]]; then unlink "$control/stop"; fi + } + trap cleanup EXIT + trap 'exit 0' INT TERM HUP + + phase 'Starting MongoDB' running + "$app/mongo/usr/bin/mongod" --bind_ip 127.0.0.1 --port 27017 \ + --dbpath "$base/db" --nounixsocket 3>&- 9>&- > "$logs/mongodb.log" 2>&1 & + db_pid=$! + for _ in {1..20}; do + if listening 27017; then break; fi + process_alive "$db_pid" || service_exited MongoDB "$db_pid" + sleep 1 + done + listening 27017 || die "MongoDB did not start. See $logs/mongodb.log." + phase 'MongoDB online' + phase 'Starting relay' running + "$app/.venv/bin/mitmdump" --quiet --mode regular --listen-host 127.0.0.1 --listen-port 18084 \ + --ignore-hosts '.*' --scripts "$app/relay.py" 3>&- 9>&- > "$logs/relay.log" 2>&1 & + relay_pid=$! + for _ in {1..20}; do + if listening 18084; then break; fi + process_alive "$relay_pid" || service_exited Relay "$relay_pid" + sleep 1 + done + listening 18084 || die "Relay did not start. See $logs/relay.log." + phase 'Relay online' + export DOTNET_ROLL_FORWARD=Major ASCNET_GAME_BIND_ADDRESS=127.0.0.1 ASCNET_MANAGED_STDIN=1 + export ASCNET_GATE_FALLBACK_USERNAME='player' ASCNET_ANDROID_LOCAL_MODE=1 ASCNET_PUBLIC_HTTP_ORIGIN=http://127.0.0.1:8080 + enable_client_debug "$app/Configs/config.json" + cd "$app" + phase 'Starting AscNet' running + dotnet ./AscNet.dll --urls http://127.0.0.1:8080 <&3 3>&- 9>&- & + game_pid=$! + for _ in {1..30}; do + if listening 8080 && listening 2335; then break; fi + process_alive "$game_pid" || service_exited AscNet "$game_pid" + sleep 1 + done + listening 8080 && listening 2335 || die 'AscNet did not start. See start-cradle.log.' + phase 'AscNet online' + while [[ ! -e $control/stop ]]; do + for service in "MongoDB:$db_pid:27017" "Relay:$relay_pid:18084" "AscNet:$game_pid:8080"; do + IFS=: read -r name pid port <<< "$service" + process_alive "$pid" || service_exited "$name" "$pid" + listening "$port" || die "$name port $port stopped listening." + done + listening 2335 || die 'AscNet port 2335 stopped listening.' + sleep .5 + done +} + +if [[ ${1:-} == --guest ]]; then + shift + base="$HOME/.local/share/infinite-loop" + app="$base/server" + case "$1" in + install) shift; guest_install "$@" ;; + start) guest_start ;; + *) die 'Unknown container command.' ;; + esac + exit +fi + +distro=infinite-loop +termux_dir="$HOME/.local/share/infinite-loop" +control="$termux_dir/control" + +if [[ ${INFINITE_LOOP_LOGGED:-0} != 1 ]]; then + case ${1:-} in + install|start|client-log|mod-probe|mod-install|mod-remove|mod-apply) + log_name=$1 + [[ $log_name != start ]] || log_name=start-cradle + mkdir -p /sdcard/Download/InfiniteLoop + log=/sdcard/Download/InfiniteLoop/$log_name.log + tmp=$log.tmp + set +e + INFINITE_LOOP_LOGGED=1 bash "$0" "$@" 2>&1 | tee "$tmp" + code=${PIPESTATUS[0]} + set -e + if (( code == 0 )) && [[ $log_name != start-cradle ]]; then rm -f "$tmp" "$log"; else mv -f "$tmp" "$log"; fi + exit "$code" + ;; + esac +fi + +apply_mods() { + local package=$1 gm=$2 lua=$3 bundle detect_output + for port in 27017 8080 2335 18084; do + listening "$port" || die 'Start Infinite Loop Server and VPN before applying MODs.' + done + mkdir -p /sdcard/Download/InfiniteLoop/mod-staging/{source,bundles} + phase 'Detecting client Lua bundle' running + if ! detect_output=$(python3 "$termux_dir/runtime/modctl.py" --rish "$termux_dir/rish/rish" \ + discover --plain --package "$package"); then + printf '%s\n' "$detect_output" >&2 + return 1 + fi + bundle=$detect_output + if [[ $gm == 0 && $lua == 0 ]]; then + python3 "$termux_dir/runtime/modctl.py" --rish "$termux_dir/rish/rish" \ + remove --package "$package" --bundle "$bundle" + return + fi + phase 'Staging original Lua bundle' running + python3 "$termux_dir/runtime/modctl.py" --rish "$termux_dir/rish/rish" \ + stage --package "$package" --bundle "$bundle" + phase 'Building selected MODs' running + proot-distro login "$distro" \ + --bind "$termux_dir/builder:/mnt/mod-builder" \ + --bind "$termux_dir/Mods:/mnt/mods" \ + --bind "/sdcard/Download/InfiniteLoop/mod-staging:/mnt/mod-staging" \ + -- env ASCNET_MOD_GM="$gm" ASCNET_MOD_LUA="$lua" ASCNET_MOD_BUNDLE="$bundle" /bin/bash -lc ' + python=/root/.local/share/infinite-loop/server/.venv/bin/python + [[ -x $python ]] || { echo "Start the server once before applying MODs." >&2; exit 1; } + "$python" -c "import UnityPy, Crypto" + "$python" /mnt/mod-builder/pgr_gm_bundle.py \ + "/mnt/mod-staging/source/$ASCNET_MOD_BUNDLE" \ + "/mnt/mod-staging/bundles/$ASCNET_MOD_BUNDLE" \ + --mods /mnt/mods --gm "$ASCNET_MOD_GM" --lua "$ASCNET_MOD_LUA" + ' + phase 'Installing selected MODs' running + python3 "$termux_dir/runtime/modctl.py" --rish "$termux_dir/rish/rish" \ + install --package "$package" --bundle "$bundle" +} + +case ${1:-} in + install) + [[ $# == 2 && -f $2 ]] || die 'Usage: bash setup.sh install ' + [[ $(uname -m) == aarch64 ]] || die 'Install requires an ARM64 device.' + command -v pkg >/dev/null || die 'Run this in Termux.' + [[ -f $script_dir/runtime/modctl.py && -f $script_dir/runtime/rish/rish \ + && -f $script_dir/runtime/rish/rish_shizuku.dex && -f $script_dir/runtime/moddetect-aarch64 \ + && -f $script_dir/pgr_gm_bundle.py \ + && -f $script_dir/pgr_bundles.py && -d $script_dir/Mods \ + && -f $script_dir/runtime/wheels/unitypy-1.25.2-cp312-cp312-linux_aarch64.whl \ + && -f $script_dir/runtime/requirements.lock ]] \ + || die 'Android runtime files are missing.' + mkdir -p "$control" "$termux_dir/runtime" "$termux_dir/rish" "$termux_dir/builder/wheels" \ + /sdcard/Download/InfiniteLoop + if [[ $(realpath -- "$0") != "$(realpath -m -- "$termux_dir/setup.sh")" ]]; then + install -m 0700 "$0" "$termux_dir/setup.sh" + fi + install -m 0700 "$script_dir/runtime/modctl.py" "$termux_dir/runtime/modctl.py" + install -m 0700 "$script_dir/runtime/moddetect-aarch64" "$termux_dir/runtime/moddetect-aarch64" + install -m 0700 "$script_dir/runtime/rish/rish" "$termux_dir/rish/rish" + install -m 0600 "$script_dir/runtime/rish/rish_shizuku.dex" "$termux_dir/rish/rish_shizuku.dex" + install -m 0600 "$script_dir/runtime/rish/LICENSE" "$termux_dir/rish/LICENSE" + install -m 0700 "$script_dir/pgr_gm_bundle.py" "$termux_dir/builder/pgr_gm_bundle.py" + install -m 0600 "$script_dir/pgr_bundles.py" "$termux_dir/builder/pgr_bundles.py" + install -m 0600 "$script_dir/runtime/wheels/unitypy-1.25.2-cp312-cp312-linux_aarch64.whl" \ + "$termux_dir/builder/wheels/unitypy-1.25.2-cp312-cp312-linux_aarch64.whl" + install -m 0600 "$script_dir/runtime/wheels/UnityPy-LICENSE" "$termux_dir/builder/wheels/UnityPy-LICENSE" + install -m 0600 "$script_dir/runtime/requirements.lock" "$termux_dir/builder/requirements.lock" + mkdir -p "$termux_dir/Mods" + for managed_mod in core gm-menu ascnet-menu; do + if [[ -d $script_dir/Mods/$managed_mod ]]; then + rm -rf -- "$termux_dir/Mods/$managed_mod" + mkdir -p "$termux_dir/Mods/$managed_mod" + cp -R "$script_dir/Mods/$managed_mod/." "$termux_dir/Mods/$managed_mod/" + fi + done + command -v proot-distro >/dev/null || pkg install -y proot-distro + ensure_distro + payload=$(realpath -- "$2") + proot-distro login "$distro" \ + --bind "$payload:/tmp/server-arm64.tar.gz" \ + --bind "$termux_dir/builder:/mnt/mod-builder" \ + -- /bin/bash -s -- --guest install /tmp/server-arm64.tar.gz < "$0" + ;; + start) + command -v proot-distro >/dev/null || die 'Run install first.' + mkdir -p "$control" /sdcard/Download/InfiniteLoop + proot-distro login "$distro" --bind "$control:/mnt/infinite-loop-control" \ + --bind /sdcard/Download/InfiniteLoop:/mnt/infinite-loop-logs \ + -- /bin/bash -s -- --guest start < "$0" + ;; + stop) + [[ -d $control ]] || die 'Run install first.' + : > "$control/stop" + ;; + status) + failed=0 + for port in 27017 8080 2335 18084; do + if listening "$port"; then + printf '127.0.0.1:%s online\n' "$port" + else + printf '127.0.0.1:%s offline\n' "$port" + failed=1 + fi + done + exit "$failed" + ;; + mod-probe) + [[ $# == 2 ]] || die 'Usage: bash setup.sh mod-probe ' + mkdir -p /sdcard/Download/InfiniteLoop + python3 "$termux_dir/runtime/modctl.py" --rish "$termux_dir/rish/rish" \ + probe --package "$2" + ;; + client-log) + [[ $# == 2 ]] || die 'Usage: bash setup.sh client-log ' + mkdir -p /sdcard/Download/InfiniteLoop + python3 "$termux_dir/runtime/modctl.py" --rish "$termux_dir/rish/rish" \ + logcat --package "$2" + ;; + mod-install|mod-remove) + [[ $# == 2 || $# == 3 ]] || die "Usage: bash setup.sh ${1} [bundle-name]" + mkdir -p /sdcard/Download/InfiniteLoop + action=${1#mod-} + bundle_args=() + [[ $# == 3 ]] && bundle_args=(--bundle "$3") + python3 "$termux_dir/runtime/modctl.py" --rish "$termux_dir/rish/rish" \ + "$action" --package "$2" "${bundle_args[@]}" + ;; + mod-apply) + [[ $# == 4 && $3 =~ ^[01]$ && $4 =~ ^[01]$ ]] \ + || die 'Usage: bash setup.sh mod-apply ' + apply_mods "$2" "$3" "$4" + ;; + *) die 'Usage: bash setup.sh {install |start|stop|status|mod-probe |mod-install|mod-remove [bundle-name]|mod-apply }' ;; +esac diff --git a/Scripts/android/tests/test_android_release_workflow.py b/Scripts/android/tests/test_android_release_workflow.py new file mode 100644 index 00000000..daec32c3 --- /dev/null +++ b/Scripts/android/tests/test_android_release_workflow.py @@ -0,0 +1,60 @@ +import re +import unittest +from pathlib import Path + +import yaml + +ROOT = Path(__file__).parents[3] +WORKFLOW = ROOT / ".github/workflows/android-release.yml" +UPDATE_CHECKER = ROOT / "Scripts/android/launcher/app/src/main/java/jp/cradle/link/UpdateChecker.java" +GRADLE = ROOT / "Scripts/android/launcher/app/build.gradle.kts" + + +class AndroidReleaseWorkflowTests(unittest.TestCase): + def setUp(self): + self.text = WORKFLOW.read_text(encoding="utf-8") + self.workflow = yaml.safe_load(self.text) + + def test_it_is_a_manual_dispatch_with_a_version_input(self): + trigger = self.workflow.get("on", self.workflow.get(True)) + self.assertIn("version", trigger["workflow_dispatch"]["inputs"]) + + def test_the_tag_prefix_is_the_one_the_updater_looks_for(self): + java = UPDATE_CHECKER.read_text(encoding="utf-8") + prefix = re.search(r'TAG_PREFIX = "([^"]+)"', java).group(1) + self.assertIn(f'"{prefix}$VERSION"', self.text) + self.assertNotIn("android-v$VERSION", self.text.replace(f"{prefix}$VERSION", "")) + + def test_the_release_carries_the_assets_the_app_downloads(self): + java = UPDATE_CHECKER.read_text(encoding="utf-8") + for name in (re.search(r'APK = "([^"]+)"', java).group(1), re.search(r'SUMS = "([^"]+)"', java).group(1), "Infinite-Loop-Android.zip"): + with self.subTest(name=name): + self.assertIn(f"dist/{name}", self.text) + + def test_it_never_becomes_the_latest_release(self): + self.assertIn("--latest=false", self.text) + + def test_only_the_release_job_can_write_and_it_runs_on_windows(self): + self.assertEqual({"contents": "read"}, self.workflow["permissions"]) + job = self.workflow["jobs"]["release"] + self.assertEqual({"contents": "write"}, job["permissions"]) + self.assertEqual("windows-latest", job["runs-on"]) + + def test_all_four_signing_secrets_are_required_and_the_keystore_is_deleted(self): + for secret in ("ASCNET_KEYSTORE_BASE64", "ASCNET_KEYSTORE_PASSWORD", "ASCNET_KEY_ALIAS", "ASCNET_KEY_PASSWORD"): + self.assertIn(f"secrets.{secret}", self.text) + self.assertIn("Remove-Item -Force -ErrorAction SilentlyContinue $keystore", self.text) + self.assertNotRegex(self.text, r"echo[^\n]*\$\{?KEYSTORE|echo[^\n]*PASSWORD") + + def test_the_version_check_reads_the_same_field_as_gradle(self): + gradle = GRADLE.read_text(encoding="utf-8") + self.assertRegex(gradle, r'(?m)^\s*versionName = "[0-9.]+"$', "build.gradle.kts must keep versionName on its own line") + sed = re.search(r"sed -n '([^']+)' Scripts/android/launcher/app/build.gradle.kts", self.text).group(1) + self.assertEqual("s/^ *versionName = \"\\(.*\\)\"$/\\1/p", sed) + + def test_the_updater_points_at_the_repository_that_publishes(self): + self.assertEqual("${{ github.repository }}", self.workflow["env"]["ORG_GRADLE_PROJECT_updateRepository"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/Scripts/android/tests/test_distribution.py b/Scripts/android/tests/test_distribution.py new file mode 100644 index 00000000..9cee9240 --- /dev/null +++ b/Scripts/android/tests/test_distribution.py @@ -0,0 +1,219 @@ +import unittest +import subprocess +import shutil +import re +from pathlib import Path + + +ANDROID = Path(__file__).parents[1] + + +class DistributionTests(unittest.TestCase): + def run_setup_helper(self, name, body): + bash = str(Path("C:/Program Files/Git/bin/bash.exe")) if Path("C:/Program Files/Git/bin/bash.exe").exists() else shutil.which("bash") + if not bash: + self.skipTest("bash is unavailable") + setup = (ANDROID / "setup.sh").read_text(encoding="utf-8") + match = re.search(r"(?ms)^" + name + r"\(\) \{\n.*?^\}", setup) + self.assertIsNotNone(match, f"missing {name} helper") + helpers = match.group() + if name == "guest_install": + cleanup = re.search(r"(?ms)^cleanup_runtime_venvs\(\) \{\n.*?^\}", setup) + self.assertIsNotNone(cleanup) + helpers = cleanup.group() + "\n" + helpers + return subprocess.run([bash, "-c", "set -e\n" + helpers + "\n" + body], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=15) + + def test_existing_proot_is_reused_or_reported_broken(self): + for scenario in ("usable", "broken", "missing"): + with self.subTest(scenario=scenario): + result = self.run_setup_helper("ensure_distro", f'''distro=infinite-loop +proot-distro() {{ + case "$1" in + login) [[ {scenario} == usable ]] || {{ echo original-login-error >&2; return 1; }} ;; + list) [[ {scenario} == missing ]] || printf ' * infinite-loop\\n * ubuntu\\n' ;; + install) echo "INSTALL:$2:$4" ;; + esac +}} +ensure_distro +''') + if scenario == "broken": + self.assertNotEqual(result.returncode, 0) + self.assertIn("original-login-error", result.stderr) + self.assertNotIn("INSTALL:", result.stdout) + else: + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual("INSTALL:ubuntu:24.04:infinite-loop" in result.stdout, scenario == "missing") + + def test_runtime_cleanup_preserves_active_and_external_data(self): + self.require_real_symlinks() + result = self.run_setup_helper("cleanup_runtime_venvs", '''root=$(mktemp -d) +trap 'rm -rf -- "$root"' EXIT +base=$root/base; app=$root/app +mkdir -p "$base/venvs/runtime.old" "$base/venvs/runtime.current" "$base/venvs/runtime.stale" "$base/db" "$base/Mods" +touch "$base/db/save" "$base/Mods/custom" +ln -s "$base/venvs/runtime.current" "$app" +cleanup_runtime_venvs "$app" +test -d "$base/venvs/runtime.current" +test ! -e "$base/venvs/runtime.old" +test ! -e "$base/venvs/runtime.stale" +test -f "$base/db/save" && test -f "$base/Mods/custom" +''') + self.assertEqual(result.returncode, 0, result.stderr) + + def test_runtime_replacement_and_failed_build(self): + self.require_real_symlinks() + for scenario in ("success", "failed", "switch-failed"): + with self.subTest(scenario=scenario): + result = self.run_setup_helper("guest_install", f'''root=$(mktemp -d) +trap 'rm -rf -- "$root"' EXIT +base=$root/base; app=$base/app +mkdir -p "$app/mongo/usr/bin" "$base/venvs/runtime.old" "$base/venvs/runtime.stale" "$base/db" "$base/Mods" +printf old > "$base/venvs/runtime.old/marker" +touch "$app/AscNet.dll" "$base/db/save" "$base/Mods/custom" +printf x > "$app/AscNet.dll" +touch "$app/mongo/usr/bin/mongod"; chmod +x "$app/mongo/usr/bin/mongod" +ln -s "$base/venvs/runtime.old" "$app/.venv" +apt-get() {{ :; }} +phase() {{ :; }} +die() {{ echo "$*" >&2; exit 1; }} +install_python_runtime() {{ [[ {scenario} != failed ]]; }} +verify_runtime() {{ :; }} +if [[ {scenario} == switch-failed ]]; then ln() {{ return 1; }}; fi +if (guest_install unused); then status=0; else status=$?; fi +test -f "$base/db/save" && test -f "$base/Mods/custom" +if [[ {scenario} == success ]]; then + test "$status" = 0 && test ! -e "$base/venvs/runtime.old" && test ! -e "$base/venvs/runtime.stale" + test -d "$(readlink -f "$app/.venv")" +else + test "$status" != 0 && test -f "$app/.venv/marker" + test "$(readlink -f "$app/.venv")" = "$base/venvs/runtime.old" +fi +''') + self.assertEqual(result.returncode, 0, result.stderr) + + def require_real_symlinks(self): + bash = str(Path("C:/Program Files/Git/bin/bash.exe")) if Path("C:/Program Files/Git/bin/bash.exe").exists() else shutil.which("bash") + if not bash: + self.skipTest("bash is unavailable") + probe = subprocess.run([bash, "-c", 'd=$(mktemp -d); mkdir "$d/target"; ln -s "$d/target" "$d/link"; test -L "$d/link"; result=$?; rm -rf "$d"; exit "$result"'], capture_output=True) + if probe.returncode: + self.skipTest("bash does not provide real symlinks") + + def test_install_always_replaces_the_server_payload(self): + setup = (ANDROID / "setup.sh").read_text(encoding="utf-8") + install = setup[setup.index("guest_install() {"):setup.index("enable_client_debug() {")] + self.assertNotIn("if [[ -s $app/AscNet.dll && -x $app/mongo/usr/bin/mongod ]]", install) + self.assertIn('tar -xzf "$payload" --no-same-owner -C "$stage/server"', install) + self.assertIn('cp -a "$app/mongo" "$stage/mongo"', install) + + def test_setup_installs_and_runs_modctl(self): + setup = (ANDROID / "setup.sh").read_text(encoding="utf-8") + self.assertIn('runtime/modctl.py', setup) + self.assertIn('runtime/rish/rish_shizuku.dex', setup) + self.assertIn('mod-probe)', setup) + self.assertIn('mod-install|mod-remove)', setup) + self.assertIn('mod-apply)', setup) + self.assertIn('bundle_args=(--bundle "$3")', setup) + self.assertIn('pgr_gm_bundle.py', setup) + self.assertIn('"$termux_dir/Mods"', setup) + self.assertIn("ASCNET_GATE_FALLBACK_USERNAME='player' ASCNET_ANDROID_LOCAL_MODE=1", setup) + self.assertIn("unitypy-1.25.2-cp312-cp312-linux_aarch64.whl", setup) + self.assertIn("requirements.lock", setup) + self.assertIn("--require-hashes", setup) + self.assertIn("pip check", setup) + self.assertNotIn("pip install --upgrade pip", setup) + self.assertIn("moddetect-aarch64", setup) + self.assertNotIn("build-essential", setup) + self.assertNotIn("python3-dev", setup) + self.assertNotIn("e6b53fac297abd1a.uab", setup) + + def test_pack_includes_runtime(self): + pack = (ANDROID / "pack.ps1").read_text(encoding="utf-8") + self.assertIn("runtime", pack) + self.assertIn("pgr_gm_bundle.py", pack) + self.assertIn("'Mods'", pack) + self.assertIn("runtime", pack) + + def test_setup_phase_order_is_stable(self): + setup = (ANDROID / "setup.sh").read_text(encoding="utf-8") + phases = [ + "Dependencies installed", + "Runtime verified", + "Setup complete", + "MongoDB online", + "Relay online", + "AscNet online", + ] + positions = [setup.index(phase) for phase in phases] + self.assertEqual(sorted(positions), positions) + + def test_setup_and_start_failures_are_logged(self): + setup = (ANDROID / "setup.sh").read_text(encoding="utf-8") + self.assertNotIn("local control=/mnt/infinite-loop-control", setup) + self.assertIn("status=failed", setup) + self.assertIn("line=%s", setup) + self.assertIn("command=%s", setup) + self.assertIn('MongoDB:$db_pid:27017', setup) + self.assertIn('Relay:$relay_pid:18084', setup) + self.assertIn('AscNet:$game_pid:8080', setup) + self.assertIn('$name exited unexpectedly (exit $code)', setup) + self.assertIn('install|start|client-log|mod-probe|mod-install|mod-remove|mod-apply)', setup) + self.assertIn('rm -f "$tmp" "$log"', setup) + self.assertIn('[[ $log_name != start-cradle ]]', setup) + self.assertIn('--bind /sdcard/Download/InfiniteLoop:/mnt/infinite-loop-logs', setup) + self.assertIn('> "$logs/relay.log"', setup) + self.assertIn('> "$logs/mongodb.log"', setup) + self.assertIn('client-log)', setup) + self.assertIn('mv -f "$tmp" "$log"', setup) + self.assertIn('if ! detect_output=$(python3', setup) + self.assertIn('printf \'%s\\n\' "$detect_output" >&2', setup) + + def test_runtime_recovery_contract(self): + setup = (ANDROID / "setup.sh").read_text(encoding="utf-8") + self.assertNotIn('rm -rf "$termux_dir/Mods"', setup) + self.assertIn('for managed_mod in core gm-menu ascnet-menu', setup) + self.assertIn('rm -rf -- "$termux_dir/Mods/$managed_mod"', setup) + self.assertNotIn('Incomplete runtime exists at $app', setup) + self.assertIn('replaced_app=', setup) + self.assertIn('new_venv=', setup) + self.assertIn('sys.version_info[:2] == (3, 12)', setup) + self.assertIn('platform.machine() in ("aarch64", "arm64")', setup) + self.assertIn('verify_runtime "$app"', setup[setup.index('guest_start()'):]) + self.assertNotIn('mongodb.log.tmp', setup) + self.assertNotIn('relay.log.tmp', setup) + self.assertIn('[[ -d $logs ]] || logs=$base', setup) + self.assertIn('BASH_LINENO[0]', setup) + self.assertNotIn('login "$distro" -- /usr/bin/true 2>/dev/null', setup) + + def test_service_exit_reports_status(self): + git_bash = Path("C:/Program Files/Git/bin/bash.exe") + bash = str(git_bash) if git_bash.exists() else shutil.which("bash") + if not bash: + self.skipTest("bash is unavailable") + setup = (ANDROID / "setup.sh").read_text(encoding="utf-8") + helpers = setup[setup.index("failure() {"):setup.index("phase() {")] + script = "current_phase=test\n" + helpers + "\nbash -c 'exit 7' & pid=$!\nwaited=0\nwhile process_alive $pid; do sleep 0.01; done\nservice_exited TestService $pid\n" + result = subprocess.run([bash, "-c", script], text=True, encoding="utf-8", errors="replace", capture_output=True, timeout=10) + self.assertEqual(1, result.returncode) + self.assertIn("TestService exited unexpectedly (exit 7)", result.stderr) + + def test_start_enables_client_debug_for_mods(self): + import json, sys, tempfile + with tempfile.TemporaryDirectory() as directory: + app = Path(directory) + (app / ".venv" / "bin").mkdir(parents=True) + (app / "Configs").mkdir() + python = app / ".venv" / "bin" / "python" + python.write_text('#!/bin/sh\nexec "' + Path(sys.executable).as_posix() + '" "$@"\n', encoding="utf-8", newline="\n") + config = app / "Configs" / "config.json" + config.write_bytes(b'{\r\n "SkipCommonGuides": true,\r\n "VerboseLevel": 1\r\n}\r\n') + call = 'enable_client_debug "' + config.as_posix() + '"\n' + result = self.run_setup_helper("enable_client_debug", 'app="' + app.as_posix() + '"\n' + call + call) + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual({"SkipCommonGuides": True, "VerboseLevel": 1, "Client": {"Debug": True}}, json.loads(config.read_text(encoding="utf-8"))) + setup = (ANDROID / "setup.sh").read_text(encoding="utf-8") + self.assertLess(setup.index('enable_client_debug "$app/Configs/config.json"'), setup.index("phase 'Starting AscNet' running")) + + +if __name__ == "__main__": + unittest.main() diff --git a/Scripts/android/tests/test_gm_bezel.py b/Scripts/android/tests/test_gm_bezel.py new file mode 100644 index 00000000..9018a95f --- /dev/null +++ b/Scripts/android/tests/test_gm_bezel.py @@ -0,0 +1,40 @@ +import unittest +from pathlib import Path + + +ROOT = Path(__file__).parents[3] + + +class GmBezelTests(unittest.TestCase): + def test_shared_panel_has_optional_bezel_handle(self): + panel = (ROOT / "Mods/core/XAscNet/XAscNetPanel.lua").read_text(encoding="utf-8") + self.assertIn("opts.edgeLabel", panel) + self.assertIn("function Panel.ShowHandle()", panel) + self.assertIn("handle:SetActive(true)", panel) + self.assertIn("handle:SetActive(false)", panel) + self.assertIn('object("Grip", handleRect)', panel) + self.assertIn("local side = left and 0 or 1", panel) + self.assertIn("handleRect.anchorMin = U.Vector2(side, 1)", panel) + self.assertIn("scaler.matchWidthOrHeight = opts.edge and 1 or 0.5", panel) + self.assertIn("background.color = U.Color(0.025, 0.027, 0.032, 0.97)", panel) + self.assertIn("ES.EventTriggerType.Drag", panel) + self.assertIn("U.PlayerPrefs.SetFloat", panel) + self.assertIn("AscNet panel handle failed", panel) + + def test_gm_menu_enables_upper_right_bezel_handle(self): + gm = (ROOT / "Mods/gm-menu/XAscNet/XAscNetGmPanel.lua").read_text(encoding="utf-8") + self.assertIn('edgeLabel = "GM"', gm) + self.assertIn('edge = "right"', gm) + self.assertIn("Panel.ShowHandle()", gm) + + def test_gm_diff_hides_unavailable_svn_reload(self): + patch = (ROOT / "Mods/gm-menu/XManager/XGmTestManager.diff").read_text(encoding="utf-8") + self.assertIn('type(CS.XDebugManager.ReloadLuaTable) == "function"', patch) + + def test_gm_menu_has_catalog_boot_module(self): + boot = (ROOT / "Mods/gm-menu/XAscNet/XAscNetGmMenuBoot.lua").read_text(encoding="utf-8") + self.assertIn('pcall(require, "XManager/XGmTestManager")', boot) + + +if __name__ == "__main__": + unittest.main() diff --git a/Scripts/android/tests/test_known_builds.py b/Scripts/android/tests/test_known_builds.py new file mode 100644 index 00000000..0d9b3cdb --- /dev/null +++ b/Scripts/android/tests/test_known_builds.py @@ -0,0 +1,33 @@ +import re +import unittest +from pathlib import Path + +ANDROID = Path(__file__).parents[1] +LAUNCHER = ANDROID / "launcher/app/src/main" +CLIENT = re.compile(r"com\.(?:kurogame|herogame)\.(?:gplay\.)?(?:punishing\.grayraven\.(?:en|jp|tw|kr)|haru\.(?:kuro|hero))") + + +def known_builds(): + java = (LAUNCHER / "java/jp/cradle/link/ClientPackages.java").read_text(encoding="utf-8") + block = re.search(r"KNOWN_BUILDS = \{(.*?)\};", java, re.S).group(1) + return set(re.findall(r'"([^"]+)"', block)) + + +class KnownBuildsTests(unittest.TestCase): + def test_every_known_build_is_declared_in_the_manifest_queries(self): + manifest = (LAUNCHER / "AndroidManifest.xml").read_text(encoding="utf-8") + queried = {name for name in re.findall(r' in step") + + def test_every_known_build_is_accepted_by_the_client_patterns(self): + for build in known_builds(): + with self.subTest(build=build): + self.assertRegex(build, CLIENT) + self.assertRegex((ANDROID / "relay.py").read_text(encoding="utf-8"), r"kurogame\|herogame") + + def test_the_confirmed_google_play_en_build_is_known(self): + self.assertIn("com.kurogame.gplay.punishing.grayraven.en", known_builds()) + + +if __name__ == "__main__": + unittest.main() diff --git a/Scripts/android/tests/test_modctl.py b/Scripts/android/tests/test_modctl.py new file mode 100644 index 00000000..c73e437b --- /dev/null +++ b/Scripts/android/tests/test_modctl.py @@ -0,0 +1,196 @@ +import os +import subprocess +import sys +import unittest +from pathlib import Path +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).parents[1] / "runtime")) + +from modctl import ( + RishClient, + bundle_target, + install_bundle_script, + install_script, + logcat_script, + probe_script, + remove_bundle_script, + remove_script, + detected_bundle, + detector_script, + stage_bundle_script, + target_root, +) + + +class ModControlTests(unittest.TestCase): + def test_logcat_follows_the_game_process_or_filters_by_package(self): + script = logcat_script("com.kurogame.punishing.grayraven.en") + self.assertIn('pidof com.kurogame.punishing.grayraven.en', script) + self.assertIn('--pid="$pid"', script) + self.assertIn("grep -E com.kurogame.punishing.grayraven.en'|Unity", script) + self.assertIn('logcat -d', script) + + def test_target_root_supports_five_regions(self): + packages = ( + "com.kurogame.punishing.grayraven.en", + "com.herogame.gplay.punishing.grayraven.jp", + "com.kurogame.punishing.grayraven.tw", + "com.kurogame.punishing.grayraven.kr", + "com.kurogame.haru.kuro", + ) + for package_name in packages: + self.assertEqual( + target_root(package_name), + f"/sdcard/Android/data/{package_name}/files/Lua/Matrix", + ) + + def test_target_root_rejects_unknown_package(self): + with self.assertRaises(ValueError): + target_root("example.invalid") + + def test_probe_uses_fixed_target_and_removes_marker(self): + script = probe_script("com.herogame.gplay.punishing.grayraven.jp") + self.assertIn("/files/Lua/Matrix/.ascnet-shizuku-probe", script) + self.assertIn("rm -f", script) + self.assertNotIn("../", script) + + def test_rish_client_passes_command_without_shell_expansion(self): + client = RishClient("/data/data/com.termux/files/home/rish/rish") + with patch("modctl.subprocess.run") as run: + run.return_value.returncode = 0 + run.return_value.stdout = "ok\n" + run.return_value.stderr = "" + result = client.run("id") + + self.assertEqual(result, "ok") + args, kwargs = run.call_args + self.assertEqual(args[0], [client.executable, "-c", "id"]) + self.assertEqual(kwargs["env"]["RISH_APPLICATION_ID"], "com.termux") + + def test_rish_failure_keeps_exit_stdout_and_stderr(self): + client = RishClient("rish") + with patch("modctl.subprocess.run") as run: + run.return_value.returncode = 20 + run.return_value.stdout = "phase=stage status=running\n" + run.return_value.stderr = "Close PGR before changing MODs.\n" + with self.assertRaises(RuntimeError) as raised: + client.run("id") + message = str(raised.exception) + self.assertIn("exit 20", message) + self.assertIn("phase=stage", message) + self.assertIn("Close PGR", message) + + def test_install_and_remove_use_one_generation_backup(self): + package_name = "com.herogame.gplay.punishing.grayraven.jp" + install = install_script(package_name) + remove = remove_script(package_name) + self.assertIn("/sdcard/Download/InfiniteLoop/mod-staging/Lua/Matrix", install) + self.assertIn("Matrix.ascnet-backup", install) + self.assertIn("Matrix.ascnet-backup", remove) + self.assertIn("mv", remove) + self.assertNotIn("rm -rf '/sdcard/Android/data/com.herogame.gplay.punishing.grayraven.jp/files/Lua/Matrix.ascnet-backup'", install) + + def test_bundle_install_preserves_original_until_remove(self): + package_name = "com.herogame.gplay.punishing.grayraven.jp" + bundle_name = "e6b53fac297abd1a.uab" + target = bundle_target(package_name, bundle_name) + install = install_bundle_script(package_name, bundle_name) + remove = remove_bundle_script(package_name, bundle_name) + self.assertIn(f"/mod-staging/bundles/{bundle_name}", install) + self.assertIn(f"pidof '{package_name}'", install) + self.assertIn(f"if [ ! -f '{target}.ascnet-backup' ]", install) + self.assertIn(f"mv -f '{target}.ascnet-backup' '{target}'", remove) + self.assertIn(f"pidof '{package_name}'", remove) + with self.assertRaises(ValueError): + bundle_target(package_name, "../bad.uab") + + def test_bundle_stage_prefers_original_backup(self): + package_name = "com.herogame.gplay.punishing.grayraven.jp" + bundle_name = "e6b53fac297abd1a.uab" + script = stage_bundle_script(package_name, bundle_name) + self.assertIn(f"pidof '{package_name}'", script) + self.assertIn(".ascnet-backup' ]; then cp -f", script) + self.assertIn("mod-staging/source/e6b53fac297abd1a.uab", script) + + def test_detector_uses_selected_package_and_validates_output(self): + package_name = "com.herogame.gplay.punishing.grayraven.jp" + script = detector_script(package_name) + self.assertIn(f"/Android/data/{package_name}/files/document/matrix", script) + self.assertIn("/data/local/tmp/infinite-loop-moddetect", script) + self.assertEqual("e6b53fac297abd1a.uab", detected_bundle("e6b53fac297abd1a.uab\n")) + self.assertEqual( + "e6b53fac297abd1a.uab", + detected_bundle( + "On Android 14+, app_process cannot load writable dex.\n" + "Attempting to remove the write permission...\n" + "e6b53fac297abd1a.uab\n" + ), + ) + with self.assertRaises(ValueError): + detected_bundle("../bad.uab\n") + + def test_store_builds_of_every_region_are_supported(self): + for package in ( + "com.kurogame.gplay.punishing.grayraven.en", + "com.kurogame.gplay.punishing.grayraven.jp", + "com.kurogame.gplay.punishing.grayraven.tw", + "com.kurogame.gplay.punishing.grayraven.kr", + "com.kurogame.haru.hero", + ): + with self.subTest(package=package): + self.assertEqual(f"/sdcard/Android/data/{package}/files/Lua/Matrix", target_root(package)) + + def test_package_ids_that_could_reach_the_shell_are_rejected(self): + for package in ( + "com.kurogame.punishing.grayraven.en\n", + "com.kurogame.punishing.grayraven.en'; rm -rf /sdcard; '", + "com.kurogame.punishing.grayraven.en/../../x", + "com.kurogame.punishing.grayraven.en.evil", + "evil.com.kurogame.punishing.grayraven.en", + "com.kurogame.punishing.grayraven.EN", + "com.kurogame.punishing.grayraven.xx", + "com.kurogame.wutheringwaves.global", + "", + ): + with self.subTest(package=package): + with self.assertRaises(ValueError): + target_root(package) + + def test_detector_covers_each_region(self): + for package in ("com.kurogame.punishing.grayraven.en", "com.herogame.gplay.punishing.grayraven.jp", "com.kurogame.punishing.grayraven.tw", "com.kurogame.punishing.grayraven.kr", "com.kurogame.haru.kuro"): + with self.subTest(package=package): + self.assertIn(f"/Android/data/{package}/files/document/matrix", detector_script(package)) + + def test_rish_timeout_has_context(self): + with patch("modctl.subprocess.run", side_effect=subprocess.TimeoutExpired("rish", 300)): + with self.assertRaisesRegex(RuntimeError, "timed out"): + RishClient("rish").run("id") + + def test_rish_success_combines_android_warning_and_child_output(self): + client = RishClient("rish") + with patch("modctl.subprocess.run") as run: + run.return_value.returncode = 0 + run.return_value.stdout = "Android 14 dex warning\n" + run.return_value.stderr = "e6b53fac297abd1a.uab\n" + output = client.run("id") + self.assertIn("Android 14 dex warning", output) + self.assertIn("e6b53fac297abd1a.uab", output) + + def test_install_validates_temporary_bundle_before_rename(self): + script = install_bundle_script("com.herogame.gplay.punishing.grayraven.jp", "e6b53fac297abd1a.uab") + self.assertIn("--verify", script) + self.assertIn(".ascnet-tmp", script) + self.assertIn(".ascnet-rollback", script) + self.assertIn("code=\\$?", script) + self.assertIn("mv -f", script) + self.assertLess(script.index("--verify"), script.rindex("mv ")) + + def test_remove_restores_backup_with_one_atomic_rename(self): + script = remove_bundle_script("com.herogame.gplay.punishing.grayraven.jp", "e6b53fac297abd1a.uab") + self.assertNotIn("rm -f '/sdcard/Android/data", script) + self.assertIn("mv -f", script) + + +if __name__ == "__main__": + unittest.main() diff --git a/Scripts/android/tests/test_pack_release.py b/Scripts/android/tests/test_pack_release.py new file mode 100644 index 00000000..98193bc8 --- /dev/null +++ b/Scripts/android/tests/test_pack_release.py @@ -0,0 +1,110 @@ +import os +import subprocess +import tempfile +import unittest +import zipfile +from pathlib import Path + + +class ReleasePackagingTest(unittest.TestCase): + def test_android_release_version_is_incremented(self): + gradle = (Path(__file__).resolve().parents[1] / 'launcher/app/build.gradle.kts').read_text(encoding='utf-8') + self.assertIn('versionCode = 7', gradle) + self.assertIn('versionName = "1.0.0"', gradle) + + def test_runtime_cache_is_excluded_from_archive_and_manifest(self): + script = Path(__file__).resolve().parents[1] / 'pack.ps1' + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + source = root / 'source' + package = root / 'package' + for name in ('modctl.py', 'wheels/example.whl', 'nested/keep.py', + '__pycache__/modctl.cpython-312.pyc', 'nested/__pycache__/junk', + 'nested/old.pyc', 'nested/old.pyo'): + path = source / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b'fixture') + package.mkdir() + env = os.environ.copy() + env.update(TEST_PACK_SCRIPT=str(script), TEST_RUNTIME=str(source), TEST_PACKAGE=str(package)) + command = r''' + $ErrorActionPreference = 'Stop' + $tokens = $null; $errors = $null + $ast = [System.Management.Automation.Language.Parser]::ParseFile($env:TEST_PACK_SCRIPT, [ref]$tokens, [ref]$errors) + $calls = $ast.FindAll({ param($node) $node -is [System.Management.Automation.Language.CommandAst] -and $node.GetCommandName() -eq 'Copy-Runtime' }, $true) + if (-not $calls) { throw 'Runtime packaging does not use Copy-Runtime' } + function Copy-Runtime($source, $destination) { Copy-Item -LiteralPath $source -Destination $destination -Recurse } + foreach ($name in 'Copy-Runtime', 'Write-Manifest') { + $function = $ast.Find({ param($node) $node -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $node.Name -eq $name }, $true) + if ($function) { Invoke-Expression $function.Extent.Text } + } + $out = ''; $stage = '' + Copy-Runtime $env:TEST_RUNTIME (Join-Path $env:TEST_PACKAGE 'runtime') + Write-Manifest $env:TEST_PACKAGE (Join-Path $env:TEST_PACKAGE 'SHA256SUMS') + Compress-Archive -Path (Join-Path $env:TEST_PACKAGE '*') -DestinationPath (Join-Path $env:TEST_PACKAGE 'test.zip') + ''' + result = subprocess.run(['pwsh', '-NoProfile', '-Command', command], env=env, + capture_output=True, text=True, encoding='utf-8', errors='replace') + self.assertEqual(result.returncode, 0, result.stderr) + manifest = (package / 'SHA256SUMS').read_text(encoding='utf-8') + with zipfile.ZipFile(package / 'test.zip') as archive: + names = set(archive.namelist()) + for name in ('runtime/modctl.py', 'runtime/wheels/example.whl', 'runtime/nested/keep.py'): + self.assertIn(name, names) + self.assertIn(name, manifest) + for name in names: + self.assertNotIn('__pycache__', name) + self.assertFalse(name.endswith(('.pyc', '.pyo')), name) + self.assertNotIn('__pycache__', manifest) + self.assertNotIn('.pyc', manifest) + self.assertNotIn('.pyo', manifest) + + def test_prebuilt_binaries_are_built_or_fetched_not_committed(self): + android = Path(__file__).resolve().parents[1] + pack = (android / 'pack.ps1').read_text(encoding='utf-8') + workflow = (android.parents[1] / '.github/workflows/android-release.yml').read_text(encoding='utf-8') + lock = (android / 'runtime/requirements.lock').read_text(encoding='utf-8') + self.assertIn('@UNITYPY_SHA256@', lock) + self.assertIn('@UNITYPY_SHA256@', pack) + self.assertIn('6e273ab0e991c4e79bc8b1bbb9b9dd739ccac1a8712a541a214078886b7b790f', pack) + self.assertIn('1953c1fd9708904f8fc1f67774843b4cc3d03e5f2a578ff4d654d0625456bc28', pack) + for text in ('runs-on: ubuntu-24.04-arm', 'aarch64-unknown-linux-musl', '--no-binary UnityPy', + 'needs: arm-runtime', 'name: android-runtime'): + self.assertIn(text, workflow) + tracked = subprocess.run(['git', 'ls-files', 'Scripts/android/runtime'], cwd=android.parents[1], + capture_output=True, text=True, encoding='utf-8').stdout + for name in ('moddetect-aarch64', 'rish_shizuku.dex', '.whl'): + self.assertNotIn(name, tracked) + + def test_missing_signing_configuration_fails_before_build(self): + script = Path(__file__).resolve().parents[1] / 'pack.ps1' + env = os.environ.copy() + for name in ('ASCNET_KEYSTORE', 'ASCNET_KEYSTORE_PASSWORD', + 'ASCNET_KEY_ALIAS', 'ASCNET_KEY_PASSWORD'): + env.pop(name, None) + with tempfile.TemporaryDirectory() as output: + result = subprocess.run( + ['pwsh', '-NoProfile', '-File', str(script), '-OutputDirectory', output], + capture_output=True, text=True, env=env, timeout=30, + ) + self.assertNotEqual(result.returncode, 0) + self.assertIn('Release signing configuration', result.stderr) + + def test_nonexistent_keystore_fails_before_build(self): + script = Path(__file__).resolve().parents[1] / 'pack.ps1' + with tempfile.TemporaryDirectory() as output: + env = os.environ.copy() + env.update(ASCNET_KEYSTORE=str(Path(output) / 'missing.jks'), + ASCNET_KEYSTORE_PASSWORD='unused', ASCNET_KEY_ALIAS='unused', + ASCNET_KEY_PASSWORD='unused') + result = subprocess.run( + ['pwsh', '-NoProfile', '-File', str(script), '-OutputDirectory', output], + capture_output=True, text=True, encoding='utf-8', errors='replace', + env=env, timeout=30, + ) + self.assertNotEqual(result.returncode, 0) + self.assertIn('keystore file not found', result.stderr) + + +if __name__ == '__main__': + unittest.main() diff --git a/Scripts/android/tests/test_pgr_gm_bundle.py b/Scripts/android/tests/test_pgr_gm_bundle.py new file mode 100644 index 00000000..14611abd --- /dev/null +++ b/Scripts/android/tests/test_pgr_gm_bundle.py @@ -0,0 +1,104 @@ +import unittest +import os +import tempfile +from unittest.mock import patch +from pathlib import Path + +from Scripts.pgr_gm_bundle import _transform_lz4, _write_verified, apply_diff, build, build_preload_runtime, selected_mod_ids +from Scripts.pgr_bundles import _untransform_lz4, payload + + +MODS = Path(__file__).parents[3] / "Mods" + + +class GmBundleTests(unittest.TestCase): + @unittest.skipUnless(os.environ.get("PGR_TEST_BUNDLE"), "requires original PGR bundle") + def test_build_all_four_selections_from_original(self): + import UnityPy + + with tempfile.TemporaryDirectory(dir=os.environ.get("PGR_TEST_TEMP")) as directory: + for gm in (False, True): + for lua in (False, True): + with self.subTest(gm=gm, lua=lua): + output = Path(directory) / f"{int(gm)}-{int(lua)}.uab" + build(Path(os.environ["PGR_TEST_BUNDLE"]), output, MODS, gm=gm, lua=lua) + assets = {} + for obj in UnityPy.load(payload(output)).objects: + if obj.type.name == "TextAsset": + asset = obj.parse_as_object() + if asset.m_Name in ("XLoginManager.lua", "XGmTestManager.lua"): + assets[asset.m_Name] = asset.m_Script + login = assets["XLoginManager.lua"] + self.assertEqual(gm, '__ascnetPreload["XAscNet/XAscNetGmPanel"]' in login) + self.assertEqual(lua, 'pcall(require, "XAscNet/XAscNetModList")' in login) + self.assertEqual(gm, assets["XGmTestManager.lua"] == "return XGmTestManager\n") + + def test_verified_write_preserves_existing_output_on_failure(self): + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) / "output.uab" + output.write_bytes(b"original") + def reject(path): + self.assertEqual(b"candidate", path.read_bytes()) + raise ValueError("verification failed") + with self.assertRaisesRegex(ValueError, "verification failed"): + _write_verified(output, b"candidate", reject) + self.assertEqual(b"original", output.read_bytes()) + self.assertEqual([output], list(output.parent.iterdir())) + + def test_verified_write_replaces_after_readback(self): + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) / "output.uab" + output.write_bytes(b"original") + _write_verified(output, b"candidate", lambda path: self.assertEqual(b"candidate", path.read_bytes())) + self.assertEqual(b"candidate", output.read_bytes()) + self.assertEqual([output], list(output.parent.iterdir())) + + def test_failed_replace_keeps_output_and_removes_temporary_file(self): + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) / "output.uab" + output.write_bytes(b"original") + with patch("Scripts.pgr_gm_bundle.os.replace", side_effect=OSError("replace failed")): + with self.assertRaisesRegex(OSError, "replace failed"): + _write_verified(output, b"candidate", lambda path: None) + self.assertEqual(b"original", output.read_bytes()) + self.assertEqual([output], list(output.parent.iterdir())) + + def test_unified_diff_is_strict(self): + original = "one\ntwo\nthree\n" + patch = "--- a.lua\n+++ b.lua\n@@ -2,1 +2,2 @@\n-two\n+second\n+extra\n" + self.assertEqual("one\nsecond\nextra\nthree\n", apply_diff(original, patch)) + with self.assertRaisesRegex(ValueError, "does not match"): + apply_diff("one\nwrong\nthree\n", patch) + + def test_four_mod_selections_are_independent(self): + self.assertEqual([], selected_mod_ids(MODS, gm=False, lua=False)) + self.assertEqual(["core", "gm-menu"], selected_mod_ids(MODS, gm=True, lua=False)) + self.assertEqual(["ascnet-menu", "core"], selected_mod_ids(MODS, gm=False, lua=True)) + self.assertEqual(["ascnet-menu", "core", "gm-menu"], selected_mod_ids(MODS, gm=True, lua=True)) + + def test_preload_runtime_contains_only_selected_modules(self): + gm = build_preload_runtime(MODS, gm=True, lua=False) + lua = build_preload_runtime(MODS, gm=False, lua=True) + both = build_preload_runtime(MODS, gm=True, lua=True) + self.assertIn('__ascnetPreload["XAscNet/XAscNetGmPanel"]', gm) + self.assertNotIn('__ascnetPreload["XAscNet/XAscNetMenuBoot"]', gm) + self.assertNotIn('pcall(require, "XAscNet/XAscNetGmMenuBoot")', gm) + self.assertIn('__ascnetPreload["XAscNet/XAscNetMenuBoot"]', lua) + self.assertNotIn('__ascnetPreload["XAscNet/XAscNetGmPanel"]', lua) + self.assertIn('pcall(require, "XAscNet/XAscNetModList")', lua) + self.assertIn('XLog.Debug("AscNet Lua MODs loaded")', lua) + self.assertIn('__ascnetPreload["XAscNet/XAscNetGmPanel"]', both) + self.assertIn('__ascnetPreload["XAscNet/XAscNetMenuBoot"]', both) + + def test_protected_lz4_transform_round_trips(self): + import lz4.block + + packed = lz4.block.compress((b"matrix-lua-" * 1000), store_size=False) + context = list(range(16)) + [7] * 16 + protected = _transform_lz4(packed, context, 0) + self.assertNotEqual(packed, protected) + self.assertEqual(packed, _untransform_lz4(protected, context, 0)) + + +if __name__ == "__main__": + unittest.main() diff --git a/Scripts/android/tests/test_relay.py b/Scripts/android/tests/test_relay.py new file mode 100644 index 00000000..8d36ef9b --- /dev/null +++ b/Scripts/android/tests/test_relay.py @@ -0,0 +1,132 @@ +import contextlib +import importlib.util +import io +import sys +import types +import unittest +from pathlib import Path +from types import SimpleNamespace + + +RELAY = Path(__file__).parents[1] / "relay.py" + + +def load_relay(): + # relay.py only needs mitmproxy's types for annotations, so tests run without mitmproxy installed. + if "mitmproxy" not in sys.modules: + try: + import mitmproxy.http # noqa: F401 + except ImportError: + package = types.ModuleType("mitmproxy") + package.http = types.ModuleType("mitmproxy.http") + sys.modules["mitmproxy"] = package + sys.modules["mitmproxy.http"] = package.http + spec = importlib.util.spec_from_file_location("relay_under_test", RELAY) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +relay = load_relay() + + +def request(package, host="prod-encdn-ak.pgr-game.com", version="4.9.0", cdn_key="abc123", scheme="http", method="GET", query=""): + middle = f"{cdn_key}/" if cdn_key else "" + path = f"/prod/client/config/{middle}{package}/{version}/android/config.tab{query}" + return SimpleNamespace(scheme=scheme, method=method, host=host, path=path) + + +# (package id, CDN host, region). Store-build ids other than EN-gplay and JP-gplay are presumed from the +# naming pattern, not captured from a device. +CLIENTS = [ + ("com.kurogame.punishing.grayraven.en", "prod-encdn-ak.pgr-game.com", "en"), + ("com.kurogame.gplay.punishing.grayraven.en", "prod-encdn-ak.pgr-game.com", "en"), + ("com.kurogame.punishing.grayraven.jp", "prod-jpcdn-ak.pgr-game.com", "jp"), + ("com.herogame.gplay.punishing.grayraven.jp", "prod-jpcdn-ak.pgr-game.com", "jp"), + ("com.kurogame.gplay.punishing.grayraven.jp", "prod-jpcdn-ak.pgr-game.com", "jp"), + ("com.kurogame.punishing.grayraven.tw", "prod-twcdn-ak.pgr-game.com", "tw"), + ("com.kurogame.gplay.punishing.grayraven.tw", "prod-twcdn-ak.pgr-game.com", "tw"), + ("com.kurogame.punishing.grayraven.kr", "prod-krcdn-ak.pgr-game.com", "kr"), + ("com.kurogame.gplay.punishing.grayraven.kr", "prod-krcdn-ak.pgr-game.com", "kr"), + ("com.kurogame.haru.kuro", "prod-zspns-txcdn.kurogame.com", "cn"), + ("com.kurogame.haru.hero", "prod-zspns-txcdn.kurogame.com", "cn"), +] + + +class RegionTests(unittest.TestCase): + def test_every_region_and_store_build_is_recognised(self): + for package, host, expected in CLIENTS: + for version in ("4.9.0", "4.9.1", "4.10.0"): + for cdn_key in ("abc123", ""): + with self.subTest(package=package, version=version, cdn_key=cdn_key): + self.assertEqual(expected, relay.region(request(package, host, version, cdn_key))) + + def test_query_string_and_host_forms_are_accepted(self): + self.assertEqual("en", relay.region(request("com.kurogame.gplay.punishing.grayraven.en", query="?t=1"))) + self.assertEqual("en", relay.region(request("com.kurogame.punishing.grayraven.en", host="PROD-ENCDN-AK.PGR-GAME.COM."))) + + def test_non_matching_requests_are_ignored(self): + package = "com.kurogame.punishing.grayraven.en" + cases = { + "https": request(package, scheme="https"), + "post": request(package, method="POST"), + "lookalike host": request(package, host="prod-encdn-ak.pgr-game.com.evil.example"), + "other host": request(package, host="example.com"), + "other game": request("com.kurogame.wutheringwaves.global"), + "suffix smuggling": request(package + ".evil"), + "prefix smuggling": request("evil." + package), + "unknown region": request("com.kurogame.punishing.grayraven.xx"), + "bad version": request(package, version="latest"), + } + for name, case in cases.items(): + with self.subTest(name): + self.assertIsNone(relay.region(case)) + + +class ReportTests(unittest.TestCase): + def setUp(self): + relay.reported.clear() + + def report(self, case): + stderr = io.StringIO() + with contextlib.redirect_stderr(stderr): + relay.report_unrecognised(case) + return stderr.getvalue() + + def test_unknown_package_on_a_kuro_host_is_reported_once(self): + case = request("com.kurogame.punishing.grayraven.xx") + first = self.report(case) + self.assertIn("com.kurogame.punishing.grayraven.xx", first) + self.assertIn("not redirected", first) + self.assertEqual("", self.report(case)) + + def test_known_clients_and_foreign_hosts_are_not_reported(self): + self.assertEqual("", self.report(request("com.kurogame.gplay.punishing.grayraven.en"))) + self.assertEqual("", self.report(request("com.example.game", host="example.com"))) + + +class RewriteTests(unittest.TestCase): + def test_gplay_en_server_list_is_pointed_at_the_local_gate(self): + body = b"ServerListStr\t1\thttps://official.example/api/Login/Login\nOther\t1\thttps://keep.example/x\n" + case = request("com.kurogame.gplay.punishing.grayraven.en") + response = SimpleNamespace(status_code=200, content=body, get_content=lambda strict=True: body) + relay.response(SimpleNamespace(request=case, response=response)) + text = response.content.decode("utf-8") + self.assertIn("http://127.0.0.1:8080/api/Login/Login-en-android", text) + self.assertIn("https://keep.example/x", text) + + def test_unmatched_and_failed_responses_are_left_alone(self): + body = b"ServerListStr\t1\thttps://official.example/api/Login/Login\n" + for case, status in ( + (request("com.example.game", host="example.com"), 200), + (request("com.kurogame.gplay.punishing.grayraven.en"), 404), + ): + with self.subTest(status=status): + response = SimpleNamespace(status_code=status, content=body, get_content=lambda strict=True: body) + with contextlib.redirect_stderr(io.StringIO()): + relay.response(SimpleNamespace(request=case, response=response)) + self.assertEqual(body, response.content) + + +if __name__ == "__main__": + unittest.main() diff --git a/Scripts/android/tests/test_update_runtime.py b/Scripts/android/tests/test_update_runtime.py new file mode 100644 index 00000000..8c723d53 --- /dev/null +++ b/Scripts/android/tests/test_update_runtime.py @@ -0,0 +1,134 @@ +import hashlib +import os +import shutil +import stat +import subprocess +import tempfile +import unittest +import zipfile +from pathlib import Path + + +SCRIPT = Path(__file__).parents[1] / "launcher/app/src/main/assets/update-runtime.sh" +REPO = "owner/repo" +TAG = "android-v0.3.0" +ARCHIVE = "Infinite-Loop-Android.zip" + +# A stand-in curl: serves files from $FAKE_RELEASE by the URL's last segment and logs every URL it is asked for. +FAKE_CURL = """#!/usr/bin/env bash +out= +url= +while [[ $# -gt 0 ]]; do + case $1 in + -o) out=$2; shift 2 ;; + --proto|--proto-redir|--max-redirs|--retry) shift 2 ;; + -*) shift ;; + *) url=$1; shift ;; + esac +done +printf '%s\\n' "$url" >> "$FAKE_LOG" +src="$FAKE_RELEASE/${url##*/}" +[[ -f $src ]] || exit 22 +cp "$src" "$out" +""" + + +class UpdateRuntimeScriptTests(unittest.TestCase): + def setUp(self): + for tool in ("bash", "unzip", "sha256sum", "awk"): + if shutil.which(tool) is None: + self.skipTest(f"{tool} is unavailable") + self.root = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.root, ignore_errors=True) + self.release = self.root / "release" + self.bin = self.root / "bin" + self.home = self.root / "home" + self.marker = self.root / "setup-ran" + for folder in (self.release, self.bin, self.home): + folder.mkdir() + curl = self.bin / "curl" + curl.write_text(FAKE_CURL, encoding="utf-8") + curl.chmod(curl.stat().st_mode | stat.S_IEXEC) + + def publish(self, sums_hash=None, with_sums=True, files=("setup.sh", "server-arm64.tar.gz"), newline="\n"): + archive = self.release / ARCHIVE + with zipfile.ZipFile(archive, "w") as bundle: + if "setup.sh" in files: + bundle.writestr("setup.sh", f'#!/usr/bin/env bash\nprintf "%s\\n" "$*" > "{self.marker}"\n') + if "server-arm64.tar.gz" in files: + bundle.writestr("server-arm64.tar.gz", "archive") + digest = sums_hash or hashlib.sha256(archive.read_bytes()).hexdigest() + if with_sums: + (self.release / "SHA256SUMS").write_bytes( + f"{'f' * 64} Infinite-Loop.apk{newline}{digest.upper()} {ARCHIVE}{newline}".encode("utf-8")) + + def run_script(self, repo=REPO, tag=TAG): + environment = dict(os.environ, PATH=f"{self.bin}:{os.environ['PATH']}", HOME=str(self.home), + FAKE_RELEASE=str(self.release), FAKE_LOG=str(self.root / "curl.log")) + return subprocess.run(["bash", "-c", SCRIPT.read_text(encoding="utf-8"), "update-runtime", repo, tag], + capture_output=True, text=True, env=environment, timeout=30) + + def urls(self): + log = self.root / "curl.log" + return log.read_text(encoding="utf-8").split() if log.exists() else [] + + def test_verified_release_is_installed_with_the_manual_install_command(self): + self.publish() + result = self.run_script() + self.assertEqual(0, result.returncode, result.stderr) + base = f"https://github.com/{REPO}/releases/download/{TAG}" + self.assertEqual([f"{base}/SHA256SUMS", f"{base}/{ARCHIVE}"], self.urls()) + ran = self.marker.read_text(encoding="utf-8").split() + self.assertEqual("install", ran[0]) + self.assertTrue(ran[1].endswith("/package/server-arm64.tar.gz")) + self.assertFalse((self.home / ".cache/infinite-loop-update").exists(), "work folder is cleaned up") + + def test_a_windows_made_manifest_with_crlf_line_ends_is_read(self): + # pack.ps1 writes SHA256SUMS with the platform newline, which is CRLF when the release is built on Windows. + self.publish(newline="\r\n") + result = self.run_script() + self.assertEqual(0, result.returncode, result.stderr) + self.assertTrue(self.marker.exists()) + + def test_checksum_mismatch_installs_nothing(self): + self.publish(sums_hash="0" * 64) + result = self.run_script() + self.assertNotEqual(0, result.returncode) + self.assertIn("Checksum mismatch", result.stderr) + self.assertFalse(self.marker.exists()) + + def test_release_without_a_checksum_for_the_archive_installs_nothing(self): + self.publish(with_sums=False) + (self.release / "SHA256SUMS").write_text(f"{'a' * 64} Infinite-Loop.apk\n", encoding="utf-8") + result = self.run_script() + self.assertNotEqual(0, result.returncode) + self.assertIn("no checksum", result.stderr) + self.assertFalse(self.marker.exists()) + + def test_incomplete_archive_installs_nothing(self): + self.publish(files=("server-arm64.tar.gz",)) + result = self.run_script() + self.assertNotEqual(0, result.returncode) + self.assertIn("incomplete", result.stderr) + self.assertFalse(self.marker.exists()) + + def test_missing_release_fails(self): + result = self.run_script() + self.assertNotEqual(0, result.returncode) + self.assertFalse(self.marker.exists()) + + def test_bad_arguments_are_rejected_before_any_download(self): + self.publish() + for repo, tag in ( + ("../x", TAG), ("owner", TAG), ("owner/repo extra", TAG), ("owner/..", TAG), ("owner/repo;rm -rf ~", TAG), + (REPO, "4.9.1"), (REPO, "android-v"), (REPO, "android-v0.3.0/../../x"), (REPO, "android-v0.3.0;id"), ("", ""), + ): + with self.subTest(repo=repo, tag=tag): + result = self.run_script(repo, tag) + self.assertNotEqual(0, result.returncode) + self.assertEqual([], self.urls()) + self.assertFalse(self.marker.exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/Scripts/pgr_bundles.py b/Scripts/pgr_bundles.py index d902b5ca..86e4bd18 100755 --- a/Scripts/pgr_bundles.py +++ b/Scripts/pgr_bundles.py @@ -189,6 +189,9 @@ def __init__(self, path: Path): _, off = _cstr(head, off) file_size, info_comp, info_plain, flags = struct.unpack_from(">QIII", head, off) header_size = off + 20 + self.header_fields = off + self.flags = flags + self.header_size = header_size if file_size != size or not info_comp or flags & 0x80: raise ValueError("unsupported UnityFS layout") self.context = None @@ -213,6 +216,7 @@ def __init__(self, path: Path): except Exception: # noqa: BLE001 - try next alignment skip continue self.cursor = _align16(start + skip + info_comp) if self.context or flags & 0x200 else start + skip + info_comp + self.info_offset = start + skip break else: raise ValueError("cannot locate UnityFS directory") @@ -268,6 +272,14 @@ def payload(source) -> bytes: bundle.close() +def _assetbundle(value): + if isinstance(value, list): + if len(value) != 1: + raise ValueError(f"expected one AssetBundle object, got {len(value)}") + return value[0] + return value + + def read_container(path: Path) -> dict: """Decode just enough of one bundle to read its AssetBundle object: {name, assets[]} (or kind != 'unity').""" try: @@ -302,7 +314,7 @@ def read_container(path: Path) -> dict: if obj is None: return {"kind": "error", "error": "no AssetBundle object"} sf = SerializedFile(EndianBinaryReader(bundle.prefix(base + data_offset + obj.byte_start + obj.byte_size)[base:]), name="x") - data = sf.assetbundle + data = _assetbundle(sf.assetbundle) return {"kind": "unity", "name": data.m_Name, "assets": sorted(k for k, _ in data.m_Container)} except Exception as error: # noqa: BLE001 return {"kind": "error", "error": f"{type(error).__name__}: {error}"} diff --git a/Scripts/pgr_gm_bundle.py b/Scripts/pgr_gm_bundle.py new file mode 100644 index 00000000..183cfbfb --- /dev/null +++ b/Scripts/pgr_gm_bundle.py @@ -0,0 +1,345 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import struct +import tempfile +from pathlib import Path + + +def _transform_lz4(data: bytes, context: list[int], initial: int) -> bytes: + try: + from Scripts.pgr_bundles import _transform_tables + except ModuleNotFoundError: + from pgr_bundles import _transform_tables + + inverse = [] + for table in _transform_tables(context): + values = [0] * 256 + for encoded, plain in enumerate(table): + values[plain] = encoded + inverse.append(values) + output = bytearray(data) + size = len(output) + offset = 0 + sequence = initial + while offset < size: + token = output[offset] + output[offset] = inverse[sequence & 255][token] + offset += 1 + sequence += 1 + control = sequence + literals = token >> 4 + if literals == 15: + while True: + if offset >= size: + raise ValueError("truncated LZ4 literal length") + value = output[offset] + output[offset] = inverse[control & 255][value] + offset += 1 + control += 1 + literals += value + if value != 255: + break + offset += literals + if offset > size: + raise ValueError("LZ4 literal overruns block") + if offset == size: + break + if offset + 2 > size: + raise ValueError("truncated LZ4 match offset") + for _ in range(2): + output[offset] = inverse[control & 255][output[offset]] + offset += 1 + control += 1 + if token & 15 == 15: + while True: + if offset >= size: + raise ValueError("truncated LZ4 match length") + value = output[offset] + output[offset] = inverse[control & 255][value] + offset += 1 + control += 1 + if value != 255: + break + return bytes(output) + + +def _protected_bundle(original: bytes, serialized: bytes) -> bytes: + import lz4.block + + try: + from Scripts.pgr_bundles import Bundle, payload + except ModuleNotFoundError: + from pgr_bundles import Bundle, payload + + parsed = Bundle(original) + try: + if parsed.context is None: + raise ValueError("only PGR-protected bundles can be rebuilt") + if len(parsed.nodes) != 1 or not parsed.blocks: + raise ValueError("expected one serialized file in the Lua bundle") + base = parsed.base + fields = parsed.header_fields + flags = parsed.flags + info_offset = parsed.info_offset + context = parsed.context + block_flags = parsed.blocks[0][2] + _, _, node_flags, node_name = parsed.nodes[0] + finally: + parsed.close() + + packed = lz4.block.compress(serialized, mode="high_compression", compression=9, store_size=False) + protected = _transform_lz4(packed, context, 0) + directory = bytearray(16) + directory.extend(struct.pack(">I", 1)) + directory.extend(struct.pack(">IIH", len(serialized), len(protected), block_flags)) + directory.extend(struct.pack(">I", 1)) + directory.extend(struct.pack(">QQI", 0, len(serialized), node_flags)) + directory.extend(node_name.encode("utf-8") + b"\0") + info = lz4.block.compress(bytes(directory), mode="high_compression", compression=9, store_size=False) + + unity = bytearray(original[base:base + info_offset]) + unity.extend(info) + unity.extend(b"\0" * ((-len(unity)) & 15)) + unity.extend(protected) + unity[fields:fields + 8] = len(unity).to_bytes(8, "big") + unity[fields + 8:fields + 12] = len(info).to_bytes(4, "big") + unity[fields + 12:fields + 16] = len(directory).to_bytes(4, "big") + unity[fields + 16:fields + 20] = flags.to_bytes(4, "big") + result = original[:base] + bytes(unity) + if payload(result) != serialized: + raise ValueError("generated protected bundle failed verification") + return result + + +def apply_diff(original: str, patch: str) -> str: + source = original.splitlines(keepends=True) + lines = patch.splitlines(keepends=True) + index = 0 + while index < len(lines): + if lines[index].startswith("\\ No newline at end of file"): + if index == 0 or not lines[index - 1].startswith((" ", "+", "-")): + raise ValueError("misplaced newline marker") + lines[index - 1] = lines[index - 1].removesuffix("\n") + lines.pop(index) + else: + index += 1 + if len(lines) < 3 or not lines[0].startswith("--- ") or not lines[1].startswith("+++ "): + raise ValueError("expected unified diff headers") + + output: list[str] = [] + cursor = 0 + position = 2 + hunks = 0 + while position < len(lines): + match = re.match(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@", lines[position]) + if not match: + raise ValueError("invalid hunk header") + old_line, old_count, new_line, new_count = ( + int(match.group(1)), + int(match.group(2) or 1), + int(match.group(3)), + int(match.group(4) or 1), + ) + source_at = old_line if old_count == 0 else old_line - 1 + output_at = new_line if new_count == 0 else new_line - 1 + if source_at < cursor or source_at > len(source): + raise ValueError("overlapping or out-of-range hunk") + output.extend(source[cursor:source_at]) + cursor = source_at + if output_at != len(output): + raise ValueError("new hunk position mismatch") + + position += 1 + removed = 0 + added = 0 + while position < len(lines) and not lines[position].startswith("@@"): + line = lines[position] + if not line or line[0] not in " +-": + raise ValueError("invalid patch line or multiple-file diff") + kind, body = line[0], line[1:] + if kind != "+": + if cursor >= len(source) or source[cursor] != body: + raise ValueError(f"diff does not match shipped module at line {cursor + 1}") + cursor += 1 + removed += 1 + if kind != "-": + output.append(body) + added += 1 + position += 1 + if removed != old_count or added != new_count: + raise ValueError("hunk line counts differ") + hunks += 1 + if not hunks: + raise ValueError("diff has no hunks") + output.extend(source[cursor:]) + return "".join(output) + + +def selected_mod_ids(mods: Path, gm: bool, lua: bool) -> list[str]: + if not (gm or lua): + return [] + selected = {"core"} + if gm: + selected.add("gm-menu") + if lua: + selected.update( + path.name + for path in mods.iterdir() + if path.is_dir() and (path / "mod.json").is_file() and path.name not in {"core", "gm-menu"} + ) + return sorted(selected) + + +def _lua_string(value: str) -> str: + return json.dumps(value, ensure_ascii=False) + + +def _catalog(mods: Path, selected: list[str], modules: dict[str, str]) -> str: + lines = ["-- Generated by the AscNet Android bundle builder; do not edit.", "return {"] + for mod_id in selected: + metadata = json.loads((mods / mod_id / "mod.json").read_text(encoding="utf-8")) + prefix = mod_id + "/" + mod_modules = sorted(name for key, name in modules.items() if key.startswith(prefix)) + rendered = ", ".join(_lua_string(name) for name in mod_modules) + lines.append( + " { id = %s, name = %s, description = %s, core = %s, modules = {%s}, tables = {} }," + % ( + _lua_string(mod_id), + _lua_string(metadata.get("name", mod_id)), + _lua_string(metadata.get("description", "")), + "true" if metadata.get("core", False) else "false", + rendered, + ) + ) + lines.extend(("}", "")) + return "\n".join(lines) + + +def build_preload_runtime(mods: Path, gm: bool, lua: bool) -> str: + selected = selected_mod_ids(mods, gm=gm, lua=lua) + if not selected: + return "" + sources: dict[str, str] = {} + module_names: dict[str, str] = {} + for mod_id in selected: + root = mods / mod_id + for path in sorted(root.rglob("*.lua")): + module = path.relative_to(root).with_suffix("").as_posix() + source = path.read_text(encoding="utf-8") + if module in sources and sources[module] != source: + raise ValueError(f"conflicting Lua module: {module}") + sources[module] = source + module_names[f"{mod_id}/{module}"] = module + sources["XAscNet/XAscNetModCatalog"] = _catalog(mods, selected, module_names) + + lines = ["-- AscNet embedded modules", "local __ascnetPreload = package.preload"] + for module, source in sorted(sources.items()): + lines.append(f"__ascnetPreload[{_lua_string(module)}] = function(...)\n{source}\nend") + if lua: + lines.extend( + ( + 'local __ascnetOk, __ascnetError = pcall(require, "XAscNet/XAscNetModList")', + 'if not __ascnetOk then XLog.Error("AscNet MOD bootstrap failed: " .. tostring(__ascnetError)) end', + 'if __ascnetOk then XLog.Debug("AscNet Lua MODs loaded") end', + "", + ) + ) + return "\n".join(lines) + + +def _write_verified(output: Path, data: bytes, verify) -> None: + output.parent.mkdir(parents=True, exist_ok=True) + name = None + try: + with tempfile.NamedTemporaryFile(dir=output.parent, prefix=f".{output.name}.", suffix=".tmp", delete=False) as stream: + name = Path(stream.name) + stream.write(data) + stream.flush() + os.fsync(stream.fileno()) + reread = name.read_bytes() + if len(reread) != len(data) or hashlib.sha256(reread).digest() != hashlib.sha256(data).digest(): + raise ValueError("rebuilt bundle size or hash mismatch") + verify(name) + os.replace(name, output) + finally: + if name is not None: + name.unlink(missing_ok=True) + + +def build(source: Path, output: Path, mods: Path, gm: bool = True, lua: bool = False) -> None: + import UnityPy + + try: + from Scripts.pgr_bundles import payload + except ModuleNotFoundError: + from pgr_bundles import payload + + original = source.read_bytes() + env = UnityPy.load(payload(source)) + assets = {} + for reader in env.file.objects.values(): + if reader.type.name != "TextAsset": + continue + asset = reader.parse_as_object() + if asset.m_Name in {"XLoginManager.lua", "XGmTestManager.lua"}: + assets[asset.m_Name] = asset + if assets.keys() != {"XLoginManager.lua", "XGmTestManager.lua"}: + raise ValueError("Lua bundle is missing XLoginManager.lua or XGmTestManager.lua") + + login = assets["XLoginManager.lua"].m_Script + runtime = build_preload_runtime(mods, gm=gm, lua=lua) + gm_manager = "" + if gm: + gm_manager = apply_diff( + assets["XGmTestManager.lua"].m_Script, + (mods / "gm-menu/XManager/XGmTestManager.diff").read_text(encoding="utf-8"), + ) + assets["XLoginManager.lua"].m_Script = login + ("\n" + runtime if runtime else "") + ("\n" + gm_manager if gm_manager else "") + assets["XLoginManager.lua"].save() + if gm: + assets["XGmTestManager.lua"].m_Script = "return XGmTestManager\n" + assets["XGmTestManager.lua"].save() + + serialized = env.file.save() + rebuilt = _protected_bundle(original, serialized) + expected = {name: asset.m_Script for name, asset in assets.items()} + + def verify(path: Path) -> None: + decoded = payload(path) + if decoded != serialized: + raise ValueError("rebuilt bundle payload mismatch") + check = UnityPy.load(decoded) + found = {} + for obj in check.objects: + if obj.type.name == "TextAsset": + asset = obj.parse_as_object() + if asset.m_Name in expected: + if asset.m_Name in found: + raise ValueError("duplicate Lua asset in rebuilt bundle") + found[asset.m_Name] = asset.m_Script + if found != expected: + raise ValueError("rebuilt bundle MOD selection mismatch") + + _write_verified(output, rebuilt, verify) + + +def main() -> None: + parser = argparse.ArgumentParser(description="Embed the AscNet GM menu into a PGR Android Lua AssetBundle.") + parser.add_argument("source", type=Path) + parser.add_argument("output", type=Path) + parser.add_argument("--mods", type=Path, default=Path(__file__).parents[1] / "Mods") + parser.add_argument("--gm", choices=("0", "1"), default="1") + parser.add_argument("--lua", choices=("0", "1"), default="0") + args = parser.parse_args() + build(args.source, args.output, args.mods, gm=args.gm == "1", lua=args.lua == "1") + print(args.output) + + +if __name__ == "__main__": + main() diff --git a/Scripts/test_pgr_bundles.py b/Scripts/test_pgr_bundles.py index b3fa933a..c081ba9a 100644 --- a/Scripts/test_pgr_bundles.py +++ b/Scripts/test_pgr_bundles.py @@ -10,6 +10,17 @@ from Scripts import pgr_bundles as pb +class AssetBundleShapeTests(unittest.TestCase): + def test_unwraps_unitypy_assetbundle_list(self): + bundle = object() + self.assertIs(pb._assetbundle(bundle), bundle) + self.assertIs(pb._assetbundle([bundle]), bundle) + with self.assertRaises(ValueError): + pb._assetbundle([]) + with self.assertRaises(ValueError): + pb._assetbundle([bundle, object()]) + + class ClaimsTests(unittest.TestCase): def test_single_asset_and_folder_claims(self): self.assertEqual(pb.container_claims(["assets/a/b/c.png"]), From 2a684ae960bb4e44d58b80e449747f57ae90624e Mon Sep 17 00:00:00 2001 From: Fokiiiiiii <229531129+Fokiiiiiii@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:23:52 +0900 Subject: [PATCH 2/2] Fix CI switch loop and give the install test a real payload The android-compat-only switch was joined with a literal "\n", so bash passed "n" to the test harness. The install test now builds a payload tarball because guest_install always extracts it. --- .github/workflows/server-ci.yml | 3 ++- Scripts/android/tests/test_distribution.py | 5 ++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/workflows/server-ci.yml b/.github/workflows/server-ci.yml index cdce7fbd..4c7cef01 100644 --- a/.github/workflows/server-ci.yml +++ b/.github/workflows/server-ci.yml @@ -99,7 +99,8 @@ jobs: --character-progression-compat-only \ --inventory-equip-compat-only \ --guild-core-compat-only \ - --login-account-compat-only \n --android-compat-only; do + --login-account-compat-only \ + --android-compat-only; do echo "::group::AscNet.Test $sw" dotnet AscNet.Test.dll "$sw" echo "::endgroup::" diff --git a/Scripts/android/tests/test_distribution.py b/Scripts/android/tests/test_distribution.py index 9cee9240..e72ffecb 100644 --- a/Scripts/android/tests/test_distribution.py +++ b/Scripts/android/tests/test_distribution.py @@ -73,13 +73,16 @@ def test_runtime_replacement_and_failed_build(self): printf x > "$app/AscNet.dll" touch "$app/mongo/usr/bin/mongod"; chmod +x "$app/mongo/usr/bin/mongod" ln -s "$base/venvs/runtime.old" "$app/.venv" +mkdir -p "$root/src/Configs" "$root/src/table" +printf new > "$root/src/AscNet.dll"; touch "$root/src/relay.py" +tar -czf "$root/payload.tgz" -C "$root/src" . apt-get() {{ :; }} phase() {{ :; }} die() {{ echo "$*" >&2; exit 1; }} install_python_runtime() {{ [[ {scenario} != failed ]]; }} verify_runtime() {{ :; }} if [[ {scenario} == switch-failed ]]; then ln() {{ return 1; }}; fi -if (guest_install unused); then status=0; else status=$?; fi +if (guest_install "$root/payload.tgz"); then status=0; else status=$?; fi test -f "$base/db/save" && test -f "$base/Mods/custom" if [[ {scenario} == success ]]; then test "$status" = 0 && test ! -e "$base/venvs/runtime.old" && test ! -e "$base/venvs/runtime.stale"