From 71d90b7a93db279eeee05f3f0b38f5918381569f Mon Sep 17 00:00:00 2001 From: Ajit Kumar Date: Sat, 28 Nov 2026 13:43:47 +0530 Subject: [PATCH 1/6] feat(ios): run Node WebAssembly, add sponsor purchases and privacy signals - run Node with per-version V8 flags and WebAssembly support, and add read-only NETLINK_ROUTE dumps for os.networkInterfaces()/Vite - expose UMP IAB consent signals and ATT progress, and harden App Store origin/cookie handling - add sponsor purchases and restart recovery on iOS and Android, including StoreKit products and rejected-detail repair - open terminal loopback links in an isolated in-app preview and supply iOS npm defaults - follow the System theme for dialog dimming and bump the release to 1.13.7 --- .github/workflows/ci.yml | 5 + .github/workflows/native-tests.yml | 20 +- CHANGELOG.md | 1311 +++++++++-------- package.json | 4 +- .../app/src/main/assets/init-alpine.sh | 19 + platforms/ios/Alpine/README.md | 55 +- platforms/ios/Alpine/Tests/netlink-route.c | 102 ++ platforms/ios/Alpine/Tests/node-flags.c | 127 ++ platforms/ios/Alpine/Tests/node-runtime.c | 144 ++ .../ios/Alpine/Vendor/ios-linuxkit/fs/fd.h | 2 + .../Alpine/Vendor/ios-linuxkit/fs/netlink.c | 83 ++ .../Alpine/Vendor/ios-linuxkit/fs/netlink.h | 53 + .../Vendor/ios-linuxkit/fs/netlink_route.c | 212 +++ .../ios/Alpine/Vendor/ios-linuxkit/fs/sock.c | 38 +- .../Alpine/Vendor/ios-linuxkit/kernel/exec.c | 26 +- .../Alpine/Vendor/ios-linuxkit/kernel/node.c | 92 ++ .../Alpine/Vendor/ios-linuxkit/kernel/node.h | 17 + .../Vendor/ios-linuxkit/kernel/node_binary.c | 159 ++ .../Vendor/ios-linuxkit/kernel/node_flags.c | 33 + .../Alpine/Vendor/ios-linuxkit/meson.build | 5 + .../Alpine/Vendor/ios-linuxkit/xX_main_Xx.h | 19 +- platforms/ios/ads/AMBPlugin.swift | 4 +- platforms/ios/ads/AMBPrivacy.swift | 27 +- platforms/ios/ads/AMBPrivacyProgress.swift | 41 + .../ios/ads/AMBTrackingAuthorization.swift | 9 + .../ios/runner.xcodeproj/project.pbxproj | 8 +- .../runner/lib/network/AppAPIHandler.swift | 8 +- .../runner/lib/preview/BrowserService.swift | 2 +- .../lib/preview/PreviewViewController.swift | 4 +- .../lib/security/AppAuthentication.swift | 41 +- .../runner/lib/terminal/AlpineRuntime.swift | 1 + .../ios/runnerTests/AlpineNodeTests.swift | 144 ++ .../ios/runnerTests/AlpinePackageTests.swift | 2 +- .../ios/runnerTests/AuthenticationTests.swift | 37 + platforms/ios/runnerTests/Iap.storekit | 90 ++ .../ios/runnerTests/PreviewBrowserTests.swift | 10 + .../ios/runnerTests/PrivacySignalsTests.swift | 75 + .../runnerTests/SponsorPurchaseTests.swift | 215 +++ .../TrackingAuthorizationTests.swift | 55 +- src/components/terminal/openTerminalLink.js | 43 + src/components/terminal/terminal.js | 14 +- src/lib/platform.js | 3 +- src/main.js | 6 + src/native/admob/privacy.ts | 11 + src/native/bridge.ts | 26 +- src/native/browser.ts | 25 +- src/native/iap.ts | 82 +- src/native/types/iap.d.ts | 4 + src/pages/sponsor/details.js | 157 ++ src/pages/sponsor/pending.js | 77 + src/pages/sponsor/purchases.js | 151 ++ src/pages/sponsor/recovery.js | 130 ++ src/pages/sponsor/sponsor.js | 249 +--- src/pages/sponsors/sponsors.js | 5 +- src/platforms/ios/api.ts | 6 +- src/platforms/ios/index.ts | 11 +- src/theme/preInstalled.js | 2 +- tests/helpers/sponsorPage.js | 117 ++ tests/helpers/sponsorPurchases.js | 78 + tests/unit/alpineNative.test.js | 111 ++ tests/unit/alpineSetup.test.js | 101 +- tests/unit/browser.test.ts | 32 + tests/unit/iap.test.ts | 123 +- tests/unit/iosApi.test.ts | 8 +- tests/unit/iosMarketplace.test.js | 36 - tests/unit/nativeBridge.test.js | 28 + tests/unit/sponsorPage.test.js | 238 +++ tests/unit/sponsorPurchases.test.js | 170 +++ tests/unit/sponsorRecovery.test.js | 236 +++ tests/unit/sponsorRecoveryPurchases.test.js | 235 +++ tests/unit/systemTheme.test.js | 32 + tests/unit/terminalLinks.test.js | 79 + 72 files changed, 4946 insertions(+), 979 deletions(-) create mode 100644 platforms/ios/Alpine/Tests/netlink-route.c create mode 100644 platforms/ios/Alpine/Tests/node-flags.c create mode 100644 platforms/ios/Alpine/Tests/node-runtime.c create mode 100644 platforms/ios/Alpine/Vendor/ios-linuxkit/fs/netlink.c create mode 100644 platforms/ios/Alpine/Vendor/ios-linuxkit/fs/netlink.h create mode 100644 platforms/ios/Alpine/Vendor/ios-linuxkit/fs/netlink_route.c create mode 100644 platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/node.c create mode 100644 platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/node.h create mode 100644 platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/node_binary.c create mode 100644 platforms/ios/Alpine/Vendor/ios-linuxkit/kernel/node_flags.c create mode 100644 platforms/ios/ads/AMBPrivacyProgress.swift create mode 100644 platforms/ios/runnerTests/AlpineNodeTests.swift create mode 100644 platforms/ios/runnerTests/PrivacySignalsTests.swift create mode 100644 platforms/ios/runnerTests/SponsorPurchaseTests.swift create mode 100644 src/components/terminal/openTerminalLink.js create mode 100644 src/pages/sponsor/details.js create mode 100644 src/pages/sponsor/pending.js create mode 100644 src/pages/sponsor/purchases.js create mode 100644 src/pages/sponsor/recovery.js create mode 100644 tests/helpers/sponsorPage.js create mode 100644 tests/helpers/sponsorPurchases.js create mode 100644 tests/unit/alpineNative.test.js create mode 100644 tests/unit/browser.test.ts create mode 100644 tests/unit/sponsorPage.test.js create mode 100644 tests/unit/sponsorPurchases.test.js create mode 100644 tests/unit/sponsorRecovery.test.js create mode 100644 tests/unit/sponsorRecoveryPurchases.test.js create mode 100644 tests/unit/systemTheme.test.js create mode 100644 tests/unit/terminalLinks.test.js diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d4d3ecf27b..cbd3bbbcd3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -65,6 +65,11 @@ jobs: distribution: temurin java-version: '26' + - name: Install native unit test dependencies + run: | + sudo apt-get update + sudo apt-get install --no-install-recommends -y clang libsqlite3-dev + - name: Run unit tests run: npm run test diff --git a/.github/workflows/native-tests.yml b/.github/workflows/native-tests.yml index 4daba8ab7d..ed65f19292 100644 --- a/.github/workflows/native-tests.yml +++ b/.github/workflows/native-tests.yml @@ -24,6 +24,15 @@ on: schedule: - cron: "0 5 * * *" workflow_dispatch: + inputs: + alpine_node_tests: + description: 'Run Alpine Node/Vite integration tests (npm access; may hit hosted-runner process exits)' + type: boolean + default: false + sponsor_privacy_tests: + description: 'Run StoreKit sponsorship and privacy bridge UI integration tests' + type: boolean + default: false permissions: contents: read @@ -152,13 +161,17 @@ jobs: } JS - name: Build and run simulator tests with SSH and FTP fixtures + env: + RUN_ALPINE_NODE_TESTS: ${{ inputs.alpine_node_tests || false }} + RUN_SPONSOR_PRIVACY_TESTS: ${{ inputs.sponsor_privacy_tests || false }} run: | python3 -m venv .ios-build/ssh-fixture-venv .ios-build/ssh-fixture-venv/bin/pip install -r tests/fixtures/ssh/requirements.txt # Temporarily exclude Alpine process exits on hosted runners (run 41789669396). # Local runs retain these tests; InAppRunnerTests also starts Alpine. skips=() - for test in AlpineInteractionTests AlpineLspTests AlpinePackageTests AlpineSignalTests AlpineSimdTests AlpineTerminalServerTests AlpineTerminalTests InAppRunnerTests; do + for test in AlpineInteractionTests AlpineLspTests AlpineNodeTests AlpinePackageTests AlpineSignalTests AlpineSimdTests AlpineTerminalServerTests AlpineTerminalTests InAppRunnerTests; do + if [[ "$test" == AlpineNodeTests && "$RUN_ALPINE_NODE_TESTS" == true ]]; then continue; fi skips+=("-skip-testing:runnerTests/$test") done # StoreKit test sessions and these web UI interactions fail on every hosted run @@ -174,6 +187,11 @@ jobs: runnerUITests/WebContextMenuUITests; do skips+=("-skip-testing:$test") done + if [[ "$RUN_SPONSOR_PRIVACY_TESTS" != true ]]; then + skips+=("-skip-testing:runnerTests/SponsorPurchaseTests") + skips+=("-skip-testing:runnerTests/AdsBridgeTests/testPrivacyBridgeReturnsOnlyCurrentIabSignals") + skips+=("-skip-testing:runnerTests/AdsBridgeTests/testPrivacySnapshotReflectsWithdrawalAndRemovedSignals") + fi .ios-build/ssh-fixture-venv/bin/python tests/fixtures/ssh/server.py -- npm run test:ios -- --target=${{ steps.simulator.outputs.id }} "${skips[@]}" - name: Run iPad startup and native UI checks run: | diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a24337a29..e8c7e94e7f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,634 +1,649 @@ # Change Log -## Unreleased +## v1.13.7 -* Ad-free pass redemption is discontinued; previously earned time remains valid until expiry. The `system.redeemReward` wrapper and native action have been removed. Plugins using that action must stop offering redemption. Internal pass-offer helpers and the `isWatchingRewardedAd` export were also removed. +- Sponsorship supports iOS StoreKit purchases and recovers unfinished purchases on iOS and Android after restart, requesting missing sponsor details without another charge. +- iOS terminal: npm shows fetch and install-script activity by default while retaining security audits. Local server links open in an isolated in-app preview, with visible errors if the preview cannot open. +- System theme: dialog dimming now follows the current light or dark appearance. +- iOS: expose current UMP IAB consent signals through the privacy API so plugins can check advertising consent and respond to changed choices. +- iOS terminal: Node.js can run WebAssembly, so Vite, React and other WebAssembly-based tools work in Alpine. `os.networkInterfaces()` and `vite --host` now see the device's network interfaces. Older Node versions installed in the terminal keep starting, because only the engine settings they support are applied. + If a custom Node binary's V8 version cannot be detected, compatibility flags leave Sparkplug and Maglev at their defaults; that binary may miss the stability workarounds used for recognized versions. +- Ad-free pass redemption is discontinued; previously earned time remains valid until expiry. The `system.redeemReward` wrapper and native action have been removed. Plugins using that action must stop offering redemption. Internal pass-offer helpers and the `isWatchingRewardedAd` export were also removed. ## v1.13.5 -* fix(terminal): stop proot "can't sanitize binding" fd warnings by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2878 -* fix(editor): preserve indentation on soft-wrapped lines by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2880 -* feat(editor): add context menu for closing file tabs by @TonyGeez in https://github.com/Acode-Foundation/Acode/pull/2863 -* perf(editor): index language modes instead of sorting on every lookup by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2881 -* feat: improve console virtualisation by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2882 -* fix(search): prevent discovery restarts and stream results efficiently by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2883 -* feat(editor): add configurable word wrap indentation by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2886 -* fix: API calls throwing internal server errors by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2888 -* fix(editor): add monaco-style punctuation wrap opportunities by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2890 +- fix(terminal): stop proot "can't sanitize binding" fd warnings by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2878 +- fix(editor): preserve indentation on soft-wrapped lines by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2880 +- feat(editor): add context menu for closing file tabs by @TonyGeez in https://github.com/Acode-Foundation/Acode/pull/2863 +- perf(editor): index language modes instead of sorting on every lookup by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2881 +- feat: improve console virtualisation by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2882 +- fix(search): prevent discovery restarts and stream results efficiently by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2883 +- feat(editor): add configurable word wrap indentation by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2886 +- fix: API calls throwing internal server errors by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2888 +- fix(editor): add monaco-style punctuation wrap opportunities by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2890 ## v1.13.4 -* fix: prevent native execution startup race by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2851 -* fix(editor): improve selection contrast on active lines by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2852 -* fix(editor): treat missing write capability as editable by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2853 -* fix: race condition when moving to exact line/col by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2856 -* Add GitHub Actions workflow for congratulating Community PRs by @UnschooledGamer in https://github.com/Acode-Foundation/Acode/pull/2855 -* Shortcut For Opening Welcome Tab by @Game-Dev-Shubham in https://github.com/Acode-Foundation/Acode/pull/2773 -* chore: Add Lingala (ln) translation by @Degrace15 in https://github.com/Acode-Foundation/Acode/pull/2775 -* feat: added icons and api by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2732 -* feat: httpStream api by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2841 -* fix: app icon picker and banner hide on reload by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2867 -* fix: settings category for app icon and theme by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2872 -* fix(devcontainer): update docker base image from bullseye to bookworm by @maaz7409 in https://github.com/Acode-Foundation/Acode/pull/2870 +- fix: prevent native execution startup race by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2851 +- fix(editor): improve selection contrast on active lines by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2852 +- fix(editor): treat missing write capability as editable by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2853 +- fix: race condition when moving to exact line/col by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2856 +- Add GitHub Actions workflow for congratulating Community PRs by @UnschooledGamer in https://github.com/Acode-Foundation/Acode/pull/2855 +- Shortcut For Opening Welcome Tab by @Game-Dev-Shubham in https://github.com/Acode-Foundation/Acode/pull/2773 +- chore: Add Lingala (ln) translation by @Degrace15 in https://github.com/Acode-Foundation/Acode/pull/2775 +- feat: added icons and api by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2732 +- feat: httpStream api by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2841 +- fix: app icon picker and banner hide on reload by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2867 +- fix: settings category for app icon and theme by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2872 +- fix(devcontainer): update docker base image from bullseye to bookworm by @maaz7409 in https://github.com/Acode-Foundation/Acode/pull/2870 ## v1.13.3 -* refactor(file-browser): Replace plain object directory cache with `Map` by @AuDevTist1C in https://github.com/Acode-Foundation/Acode/pull/2831 -* fix(editor): stabilize selection menu sizing and transitions by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2833 -* fix(editor): keep fullscreen controls above bottom pane tabs by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2834 -* chore(community-release-notifier): Change sed parsing - TG release notes by @UnschooledGamer in https://github.com/Acode-Foundation/Acode/pull/2832 -* fix(editor): restore cursor state and prevent tab-switch flash by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2835 -* feat(lsp): improve actions, navigation, and position handling by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2837 -* fix(editor): highlight all visible search matches by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2838 -* Translation: Update hu-hu.json by @summoner001 in https://github.com/Acode-Foundation/Acode/pull/2828 -* chore(deps): bump actions/setup-java from 5 to 6 by @dependabot[bot] in https://github.com/Acode-Foundation/Acode/pull/2821 -* feat: improved pluginContext by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2806 -* fix(webview): retain instance when destroy fails by @azamkassim in https://github.com/Acode-Foundation/Acode/pull/2836 -* fix(sftp): recover from failed profile migration by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2840 +- refactor(file-browser): Replace plain object directory cache with `Map` by @AuDevTist1C in https://github.com/Acode-Foundation/Acode/pull/2831 +- fix(editor): stabilize selection menu sizing and transitions by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2833 +- fix(editor): keep fullscreen controls above bottom pane tabs by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2834 +- chore(community-release-notifier): Change sed parsing - TG release notes by @UnschooledGamer in https://github.com/Acode-Foundation/Acode/pull/2832 +- fix(editor): restore cursor state and prevent tab-switch flash by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2835 +- feat(lsp): improve actions, navigation, and position handling by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2837 +- fix(editor): highlight all visible search matches by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2838 +- Translation: Update hu-hu.json by @summoner001 in https://github.com/Acode-Foundation/Acode/pull/2828 +- chore(deps): bump actions/setup-java from 5 to 6 by @dependabot[bot] in https://github.com/Acode-Foundation/Acode/pull/2821 +- feat: improved pluginContext by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2806 +- fix(webview): retain instance when destroy fails by @azamkassim in https://github.com/Acode-Foundation/Acode/pull/2836 +- fix(sftp): recover from failed profile migration by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2840 ## v1.13.2 -* feat: stabilize SFTP and add secure SSH terminal integration by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2694 -* fix(lsp): correct workspace and document color capabilities and add tailwind lsp by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2736 -* refactor: Standardize DOM element dataset attributes across file browser component by @AuDevTist1C in https://github.com/Acode-Foundation/Acode/pull/2543 -* fix(lsp): preserve websocket clients across tab switches by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2764 -* feat(plugins): expose static CodeMirror highlighter by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2769 -* refactor(loader): Extract `tailSpin` SVG component and dynamic gradient logic by @AuDevTist1C in https://github.com/Acode-Foundation/Acode/pull/2776 -* fix(quick-tools): prevent scrollbars during editor gestures by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2777 -* fix: fall back to internal storage when external storage is unavailable by @ulite-Amr in https://github.com/Acode-Foundation/Acode/pull/2781 -* fix(theme): prevent freeze when switching to system theme by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2790 -* fix(sftp): cancel stalled connections and prevent delayed errors by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2791 -* fix: admob issues by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2800 -* fix(android): avoid splash surface crash on realme Android 13 by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2805 -* fix(session): restore picker documents and skip intent files tab by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2809 -* feat(console): isolate execution and improve mobile REPL UX by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2808 -* feat(console): follow active Acode theme by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2814 -* chore: improve Indonesian (id) language translations by @MatrixTM26 in https://github.com/Acode-Foundation/Acode/pull/2798 -* fix: preserve MIME type for plugin icons on plugin details page by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2818 -* fix(console): run JavaScript files in isolated worker by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2819 -* feat: plugin review by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2826 -* Improve selection menu UX and plugin action overflow by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2813 -* fix(search): include restored files in global search by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2830 +- feat: stabilize SFTP and add secure SSH terminal integration by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2694 +- fix(lsp): correct workspace and document color capabilities and add tailwind lsp by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2736 +- refactor: Standardize DOM element dataset attributes across file browser component by @AuDevTist1C in https://github.com/Acode-Foundation/Acode/pull/2543 +- fix(lsp): preserve websocket clients across tab switches by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2764 +- feat(plugins): expose static CodeMirror highlighter by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2769 +- refactor(loader): Extract `tailSpin` SVG component and dynamic gradient logic by @AuDevTist1C in https://github.com/Acode-Foundation/Acode/pull/2776 +- fix(quick-tools): prevent scrollbars during editor gestures by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2777 +- fix: fall back to internal storage when external storage is unavailable by @ulite-Amr in https://github.com/Acode-Foundation/Acode/pull/2781 +- fix(theme): prevent freeze when switching to system theme by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2790 +- fix(sftp): cancel stalled connections and prevent delayed errors by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2791 +- fix: admob issues by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2800 +- fix(android): avoid splash surface crash on realme Android 13 by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2805 +- fix(session): restore picker documents and skip intent files tab by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2809 +- feat(console): isolate execution and improve mobile REPL UX by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2808 +- feat(console): follow active Acode theme by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2814 +- chore: improve Indonesian (id) language translations by @MatrixTM26 in https://github.com/Acode-Foundation/Acode/pull/2798 +- fix: preserve MIME type for plugin icons on plugin details page by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2818 +- fix(console): run JavaScript files in isolated worker by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2819 +- feat: plugin review by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2826 +- Improve selection menu UX and plugin action overflow by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2813 +- fix(search): include restored files in global search by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2830 ## v1.12.9 -* fix(admob): remove the policy-prohibited interstitial shown while exiting the app +- fix(admob): remove the policy-prohibited interstitial shown while exiting the app ## v1.12.8 -* fix(terminal): close tab on process end and speed up long-press select by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2587 -* fix(editor): prevent false language mode recommendations by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2621 -* fix(lsp): send workspace folders during initialization by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2623 -* fix(admob): harden consent, banners, and variant builds by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2553 -* feat(lsp): add multi-server support to CodeMirror LSP client by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2627 +- fix(terminal): close tab on process end and speed up long-press select by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2587 +- fix(editor): prevent false language mode recommendations by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2621 +- fix(lsp): send workspace folders during initialization by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2623 +- fix(admob): harden consent, banners, and variant builds by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2553 +- feat(lsp): add multi-server support to CodeMirror LSP client by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2627 ## v1.12.7 -* fix: scroll shift when tab switching by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2329 -* Fixes several small querks and inconsistencies to improve UI/UX by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2331 -* feat: add setting to toggle emmet by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2332 -* feat: add a ui to manage running Terminal (Executor) processes by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2333 -* fix(settings): preserve scroll state and avoid full rerenders by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2348 -* fix: removed annoying terminal dialog by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2349 -* Better regex by @Palloxin in https://github.com/Acode-Foundation/Acode/pull/2325 -* fix(lsp): hover tooltip code highlighting by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2353 -* fix(lsp): scope cache fallback by runtime provider by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2354 -* feat: dont invoke acode service when uninstalling terminal by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2350 -* fix: run new files even if marked saved by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2360 -* perf(settings): lazy load sub-settings pages to optimize load time by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2358 -* fix: ignore files to be treated as plugin in src/plugins by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2362 -* feat: add setting to toggle `language package completion` by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2361 -* feat(performance): removed double memory usage when reading/writing text files by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2359 -* feat: add language-mode plugin recommendation system by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2368 -* feat(keybind): add code folds keybinds by @UnschooledGamer in https://github.com/Acode-Foundation/Acode/pull/2369 -* fix(editor): apply plugin language modes after restore (for plugin modes) by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2375 -* fix: Use inline themed SVG for loader spinner by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2379 -* fix: wait for plugin load before recommendation trigger by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2383 -* fix: don't check for app updates from github when app is from playstore by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2385 -* feat: improved ux by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2382 -* fix: Fixes bug in settings UI by @claycuy in https://github.com/Acode-Foundation/Acode/pull/2388 -* feat: lazy load things which are low-risk from main by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2386 -* fix(quicktools): preserve editor focus during rapid taps and stale issue by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2408 -* feat: new 'SEL' Command for Quick Tools by @Elitex07 in https://github.com/Acode-Foundation/Acode/pull/2414 -* feat(ui): use motion for page, tab, switch and press gestures animation by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2406 -* refactor(core): centralize plugin unmount error boundary and fix console telemetry by @AuDevTist1C in https://github.com/Acode-Foundation/Acode/pull/2422 -* fix: language mode mapping to add maps for paths which doesnt exists by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2430 -* fix(editor): preserve restored tab editability while loading by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2431 -* fix(quicktools): prevent editor blur when tapping toolbar immediately after typing by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2432 -* feat: add native app auth code login flow by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2440 -* feat: improve CodeMirror quick tools modifier support by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2435 -* fix(security) critical security issue by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2442 -* fix: skip recommendation for binary file by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2446 -* feat(editor): implement multi-pane split layout by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2416 -* fix: plugin page ui for big screen by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2448 -* fix(editor): prevent styling loss flash on custom page tabs when splitting/closing panes by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2449 -* feat(lsp): group language servers into built-in, plugin, and custom categories by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2452 -* refactor(ui): improved toast and notification animations using motion by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2453 -* feat: added native crash handler by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2450 -* feat: make the clear command behave as reset by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2458 -* feat: Add hover and long press tooltips to quicktools items by @gahanad in https://github.com/Acode-Foundation/Acode/pull/2456 -* fix: add missing autoclosebracket keymap(paired bracket deletion) by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2472 -* fix: implement editor tab history navigation (#1819) by @Elitex07 in https://github.com/Acode-Foundation/Acode/pull/2459 -* fix(lsp): refresh installation status on the correct settings page by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2482 -* fix(editor): sync replacement untitled file state by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2483 -* feat: add cobalt editor theme by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2484 -* fix: zip project import by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2473 -* chore: update the xtermjs to v6 and fix session creation by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2487 -* fix(editor): improve wrapped line indentation and keep text wrap off by default by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2507 -* fix(editor): prevent syntax highlight color flicker on state recreation (#2304) by @Elitex07 in https://github.com/Acode-Foundation/Acode/pull/2457 -* Make line commands aware of folded blocks by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2508 -* fix: move bashrc sourcing to bottom of initrc so bashrc can override … by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2523 -* fix(settings): sync global search switch behavior and animation by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2527 -* refactor(editor): centralize CodeMirror commands and keybindings by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2516 -* feat(lsp): add document color chips with regex fallback by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2533 -* feat(lsp): add pull diagnostics and native TypeScript 7 by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2537 -* feat(lsp): add web worker language servers as defaults by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2531 -* fix: system theme by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2524 -* feat(editor): add indentation folding for legacy modes(as fallback) by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2538 -* feat: add WebView Plugin API by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2525 -* feat(files): move workspace indexing and search to native for saf/files by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2529 -* fix: upgrade tar to 7.5.19 (CVE-2026-59873) by @anupamme in https://github.com/Acode-Foundation/Acode/pull/2544 -* fix(fileBrowser): exclude non-selectable system utility tiles from batch selection operations by @AuDevTist1C in https://github.com/Acode-Foundation/Acode/pull/2545 -* refactor(file-browser): extract reusable deletion logic and abstract Termux URI validation by @AuDevTist1C in https://github.com/Acode-Foundation/Acode/pull/2548 -* feat(file-browser): integrate selection mode state with `actionStack` for back navigation by @AuDevTist1C in https://github.com/Acode-Foundation/Acode/pull/2546 -* feat(files): skip excluded paths during copy operations by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2555 -* fix: the processutils in ProcessUtils.java by @anupamme in https://github.com/Acode-Foundation/Acode/pull/2557 -* fix: sanitize input hints to prevent XSS by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2559 -* feat: proot debug toggle by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2563 -* Improve recent dialog path readability by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2567 -* Fix CodeMirror theme colors and add Catppuccin variants by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2568 -* feat(editor): add configurable horizontal scroll margin to CodeMirror by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2569 -* fix(quick-tools): add visible close button to search when toggler is off by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2570 -* i18n: update Hungarian translations by @summoner001 in https://github.com/Acode-Foundation/Acode/pull/2207, https://github.com/Acode-Foundation/Acode/pull/2387, https://github.com/Acode-Foundation/Acode/pull/2429, https://github.com/Acode-Foundation/Acode/pull/2478, https://github.com/Acode-Foundation/Acode/pull/2485, https://github.com/Acode-Foundation/Acode/pull/2542, https://github.com/Acode-Foundation/Acode/pull/2558 -* i18n: update Indonesian translations and localization strings by @claycuy in https://github.com/Acode-Foundation/Acode/pull/2330, https://github.com/Acode-Foundation/Acode/pull/2372, https://github.com/Acode-Foundation/Acode/pull/2417, https://github.com/Acode-Foundation/Acode/pull/2479 -* i18n: update Simplified and Traditional Chinese translations by @LaunchLee in https://github.com/Acode-Foundation/Acode/pull/2468, https://github.com/Acode-Foundation/Acode/pull/2571 -* i18n: update Yemeni Arabic translations by @mohamedElneser in https://github.com/Acode-Foundation/Acode/pull/2480 -* i18n: update Indonesian translations by @Elderellerser in https://github.com/Acode-Foundation/Acode/pull/2491 +- fix: scroll shift when tab switching by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2329 +- Fixes several small querks and inconsistencies to improve UI/UX by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2331 +- feat: add setting to toggle emmet by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2332 +- feat: add a ui to manage running Terminal (Executor) processes by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2333 +- fix(settings): preserve scroll state and avoid full rerenders by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2348 +- fix: removed annoying terminal dialog by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2349 +- Better regex by @Palloxin in https://github.com/Acode-Foundation/Acode/pull/2325 +- fix(lsp): hover tooltip code highlighting by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2353 +- fix(lsp): scope cache fallback by runtime provider by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2354 +- feat: dont invoke acode service when uninstalling terminal by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2350 +- fix: run new files even if marked saved by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2360 +- perf(settings): lazy load sub-settings pages to optimize load time by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2358 +- fix: ignore files to be treated as plugin in src/plugins by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2362 +- feat: add setting to toggle `language package completion` by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2361 +- feat(performance): removed double memory usage when reading/writing text files by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2359 +- feat: add language-mode plugin recommendation system by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2368 +- feat(keybind): add code folds keybinds by @UnschooledGamer in https://github.com/Acode-Foundation/Acode/pull/2369 +- fix(editor): apply plugin language modes after restore (for plugin modes) by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2375 +- fix: Use inline themed SVG for loader spinner by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2379 +- fix: wait for plugin load before recommendation trigger by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2383 +- fix: don't check for app updates from github when app is from playstore by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2385 +- feat: improved ux by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2382 +- fix: Fixes bug in settings UI by @claycuy in https://github.com/Acode-Foundation/Acode/pull/2388 +- feat: lazy load things which are low-risk from main by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2386 +- fix(quicktools): preserve editor focus during rapid taps and stale issue by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2408 +- feat: new 'SEL' Command for Quick Tools by @Elitex07 in https://github.com/Acode-Foundation/Acode/pull/2414 +- feat(ui): use motion for page, tab, switch and press gestures animation by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2406 +- refactor(core): centralize plugin unmount error boundary and fix console telemetry by @AuDevTist1C in https://github.com/Acode-Foundation/Acode/pull/2422 +- fix: language mode mapping to add maps for paths which doesnt exists by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2430 +- fix(editor): preserve restored tab editability while loading by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2431 +- fix(quicktools): prevent editor blur when tapping toolbar immediately after typing by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2432 +- feat: add native app auth code login flow by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2440 +- feat: improve CodeMirror quick tools modifier support by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2435 +- fix(security) critical security issue by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2442 +- fix: skip recommendation for binary file by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2446 +- feat(editor): implement multi-pane split layout by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2416 +- fix: plugin page ui for big screen by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2448 +- fix(editor): prevent styling loss flash on custom page tabs when splitting/closing panes by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2449 +- feat(lsp): group language servers into built-in, plugin, and custom categories by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2452 +- refactor(ui): improved toast and notification animations using motion by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2453 +- feat: added native crash handler by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2450 +- feat: make the clear command behave as reset by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2458 +- feat: Add hover and long press tooltips to quicktools items by @gahanad in https://github.com/Acode-Foundation/Acode/pull/2456 +- fix: add missing autoclosebracket keymap(paired bracket deletion) by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2472 +- fix: implement editor tab history navigation (#1819) by @Elitex07 in https://github.com/Acode-Foundation/Acode/pull/2459 +- fix(lsp): refresh installation status on the correct settings page by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2482 +- fix(editor): sync replacement untitled file state by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2483 +- feat: add cobalt editor theme by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2484 +- fix: zip project import by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2473 +- chore: update the xtermjs to v6 and fix session creation by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2487 +- fix(editor): improve wrapped line indentation and keep text wrap off by default by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2507 +- fix(editor): prevent syntax highlight color flicker on state recreation (#2304) by @Elitex07 in https://github.com/Acode-Foundation/Acode/pull/2457 +- Make line commands aware of folded blocks by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2508 +- fix: move bashrc sourcing to bottom of initrc so bashrc can override … by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2523 +- fix(settings): sync global search switch behavior and animation by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2527 +- refactor(editor): centralize CodeMirror commands and keybindings by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2516 +- feat(lsp): add document color chips with regex fallback by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2533 +- feat(lsp): add pull diagnostics and native TypeScript 7 by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2537 +- feat(lsp): add web worker language servers as defaults by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2531 +- fix: system theme by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2524 +- feat(editor): add indentation folding for legacy modes(as fallback) by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2538 +- feat: add WebView Plugin API by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2525 +- feat(files): move workspace indexing and search to native for saf/files by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2529 +- fix: upgrade tar to 7.5.19 (CVE-2026-59873) by @anupamme in https://github.com/Acode-Foundation/Acode/pull/2544 +- fix(fileBrowser): exclude non-selectable system utility tiles from batch selection operations by @AuDevTist1C in https://github.com/Acode-Foundation/Acode/pull/2545 +- refactor(file-browser): extract reusable deletion logic and abstract Termux URI validation by @AuDevTist1C in https://github.com/Acode-Foundation/Acode/pull/2548 +- feat(file-browser): integrate selection mode state with `actionStack` for back navigation by @AuDevTist1C in https://github.com/Acode-Foundation/Acode/pull/2546 +- feat(files): skip excluded paths during copy operations by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2555 +- fix: the processutils in ProcessUtils.java by @anupamme in https://github.com/Acode-Foundation/Acode/pull/2557 +- fix: sanitize input hints to prevent XSS by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2559 +- feat: proot debug toggle by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2563 +- Improve recent dialog path readability by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2567 +- Fix CodeMirror theme colors and add Catppuccin variants by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2568 +- feat(editor): add configurable horizontal scroll margin to CodeMirror by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2569 +- fix(quick-tools): add visible close button to search when toggler is off by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2570 +- i18n: update Hungarian translations by @summoner001 in https://github.com/Acode-Foundation/Acode/pull/2207, https://github.com/Acode-Foundation/Acode/pull/2387, https://github.com/Acode-Foundation/Acode/pull/2429, https://github.com/Acode-Foundation/Acode/pull/2478, https://github.com/Acode-Foundation/Acode/pull/2485, https://github.com/Acode-Foundation/Acode/pull/2542, https://github.com/Acode-Foundation/Acode/pull/2558 +- i18n: update Indonesian translations and localization strings by @claycuy in https://github.com/Acode-Foundation/Acode/pull/2330, https://github.com/Acode-Foundation/Acode/pull/2372, https://github.com/Acode-Foundation/Acode/pull/2417, https://github.com/Acode-Foundation/Acode/pull/2479 +- i18n: update Simplified and Traditional Chinese translations by @LaunchLee in https://github.com/Acode-Foundation/Acode/pull/2468, https://github.com/Acode-Foundation/Acode/pull/2571 +- i18n: update Yemeni Arabic translations by @mohamedElneser in https://github.com/Acode-Foundation/Acode/pull/2480 +- i18n: update Indonesian translations by @Elderellerser in https://github.com/Acode-Foundation/Acode/pull/2491 ## v1.12.6 -* Refactor boot script and add editor interaction handler by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2216 -* fix(touchSelectionMenu): prevent menu overlap with cm-tooltips by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2220 -* fix: suppressed startup auth related toast instead just log it by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2222 -* feat: add option to control scrollbar height by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2223 -* feat: add astro mode (with lezer parser and grammar) by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2224 -* fix: improve cursor and quicktoolbar by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2225 -* feat(editor): make scroll-past-end bottom margin configurable by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2226 -* feat: Improve binary file skipping in sidebar search by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2229 -* fix(editor): preserve selected theme after sidebar file moves by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2230 -* ux improvements by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2231 -* feat(terminal): add custom touch scrolling with momentum physics by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2232 -* feat(terminal): add terminal theme picker to Theme Settings page by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2234 -* fix(lsp): show dynamic install status label with loader feedback by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2235 -* i18n(id-id): update strings by @hyperz111 in https://github.com/Acode-Foundation/Acode/pull/2228 -* feat: Improve LSP server reuse check with bridge status endpoint by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2238 -* i18n(lang.js): Update Indonesian language name to Bahasa Indonesia by @claycuy in https://github.com/Acode-Foundation/Acode/pull/2236 -* feat(color-picker): add format dropdown, cancel button, and cancellat… by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2240 -* fix: pro detection by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2248 -* i18n(id): refine translations for a more natural and accurate phrasing by @claycuy in https://github.com/Acode-Foundation/Acode/pull/2239 -* refactor(lsp): decouple runtime execution from built-in Alpine & support custom runtime providers by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2241 -* feat: improve the indexing and search UI/UX and few fallbacks stuff by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2256 -* fix: version parsing failure on nightly tags by @AuDevTist1C in https://github.com/Acode-Foundation/Acode/pull/2249 -* feat: added config proxy by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2246 -* fix: disable CodeMirror EditContext by default by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2258 -* fix(lsp): check Terminal installation before installing server for builtin Alpine by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2259 -* fix(sidebar): preserve state across orientation changes by @Elitex07 in https://github.com/Acode-Foundation/Acode/pull/2219 -* fix: make indent guide stable and close to vscode one by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2266 -* fix(editor): prevent cursor snap after scrollbar drag by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2263 -* feat(quickTools): replace checkbox with height select & dynamic toggler by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2278 -* chore(deps): bump markdown-it from 14.1.1 to 14.2.0 by @dependabot[bot] in https://github.com/Acode-Foundation/Acode/pull/2286 -* chore(deps): bump dompurify from 3.4.3 to 3.4.10 by @dependabot[bot] in https://github.com/Acode-Foundation/Acode/pull/2271 -* chote(i18n): update german translation by @Mythryl-dev in https://github.com/Acode-Foundation/Acode/pull/2293 -* feat: do file-listing and index on java for file:/// and saf locations by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2283 -* improve vscode editor theme -* add few more popular editor themes like nord, AyuDark, GruvboxDark, MaterialPalenight. -* enable jsx in js mode +- Refactor boot script and add editor interaction handler by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2216 +- fix(touchSelectionMenu): prevent menu overlap with cm-tooltips by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2220 +- fix: suppressed startup auth related toast instead just log it by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2222 +- feat: add option to control scrollbar height by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2223 +- feat: add astro mode (with lezer parser and grammar) by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2224 +- fix: improve cursor and quicktoolbar by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2225 +- feat(editor): make scroll-past-end bottom margin configurable by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2226 +- feat: Improve binary file skipping in sidebar search by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2229 +- fix(editor): preserve selected theme after sidebar file moves by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2230 +- ux improvements by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2231 +- feat(terminal): add custom touch scrolling with momentum physics by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2232 +- feat(terminal): add terminal theme picker to Theme Settings page by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2234 +- fix(lsp): show dynamic install status label with loader feedback by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2235 +- i18n(id-id): update strings by @hyperz111 in https://github.com/Acode-Foundation/Acode/pull/2228 +- feat: Improve LSP server reuse check with bridge status endpoint by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2238 +- i18n(lang.js): Update Indonesian language name to Bahasa Indonesia by @claycuy in https://github.com/Acode-Foundation/Acode/pull/2236 +- feat(color-picker): add format dropdown, cancel button, and cancellat… by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2240 +- fix: pro detection by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2248 +- i18n(id): refine translations for a more natural and accurate phrasing by @claycuy in https://github.com/Acode-Foundation/Acode/pull/2239 +- refactor(lsp): decouple runtime execution from built-in Alpine & support custom runtime providers by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2241 +- feat: improve the indexing and search UI/UX and few fallbacks stuff by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2256 +- fix: version parsing failure on nightly tags by @AuDevTist1C in https://github.com/Acode-Foundation/Acode/pull/2249 +- feat: added config proxy by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2246 +- fix: disable CodeMirror EditContext by default by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2258 +- fix(lsp): check Terminal installation before installing server for builtin Alpine by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2259 +- fix(sidebar): preserve state across orientation changes by @Elitex07 in https://github.com/Acode-Foundation/Acode/pull/2219 +- fix: make indent guide stable and close to vscode one by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2266 +- fix(editor): prevent cursor snap after scrollbar drag by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2263 +- feat(quickTools): replace checkbox with height select & dynamic toggler by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2278 +- chore(deps): bump markdown-it from 14.1.1 to 14.2.0 by @dependabot[bot] in https://github.com/Acode-Foundation/Acode/pull/2286 +- chore(deps): bump dompurify from 3.4.3 to 3.4.10 by @dependabot[bot] in https://github.com/Acode-Foundation/Acode/pull/2271 +- chote(i18n): update german translation by @Mythryl-dev in https://github.com/Acode-Foundation/Acode/pull/2293 +- feat: do file-listing and index on java for file:/// and saf locations by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2283 +- improve vscode editor theme +- add few more popular editor themes like nord, AyuDark, GruvboxDark, MaterialPalenight. +- enable jsx in js mode ## v1.12.5 -* fix: custom fonts by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2192 -* fix(editor): stabilize restored tab highlighting by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2193 -* feat(terminal): bundle everything into the apk by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2197 -* improve the lsp message and ace to codemirror related clarrification by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2203 -* fix(terminal): handle axs symlink runtime checks by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2204 -* fix(i18n): Improve Indonesian translation naturalness and fix missing entries by @claycuy in https://github.com/Acode-Foundation/Acode/pull/2190 -* fix(lsp): add dont ask again for missing terminal prompt by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2208 +- fix: custom fonts by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2192 +- fix(editor): stabilize restored tab highlighting by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2193 +- feat(terminal): bundle everything into the apk by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2197 +- improve the lsp message and ace to codemirror related clarrification by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2203 +- fix(terminal): handle axs symlink runtime checks by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2204 +- fix(i18n): Improve Indonesian translation naturalness and fix missing entries by @claycuy in https://github.com/Acode-Foundation/Acode/pull/2190 +- fix(lsp): add dont ask again for missing terminal prompt by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2208 ## v1.12.4 -* chore(i18n): update strings in hu_hu.json by @summoner001 in https://github.com/Acode-Foundation/Acode/pull/2171 -* fix: Executor arguments getting ignored by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2176 -* fix: allow subdomain of acode.app by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2179 -* fix: highlighting issue happening due to state reuse by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2180 -* i18n(id-id): update strings by @hyperz111 in https://github.com/Acode-Foundation/Acode/pull/2178 -* feat: polish welcome tab with dynamic shortcuts, dismiss tracking, an… by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2182 -* fix: revert customtabs for plugins by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2183 -* fix: error when terminating terminal + fixed build by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2184 +- chore(i18n): update strings in hu_hu.json by @summoner001 in https://github.com/Acode-Foundation/Acode/pull/2171 +- fix: Executor arguments getting ignored by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2176 +- fix: allow subdomain of acode.app by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2179 +- fix: highlighting issue happening due to state reuse by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2180 +- i18n(id-id): update strings by @hyperz111 in https://github.com/Acode-Foundation/Acode/pull/2178 +- feat: polish welcome tab with dynamic shortcuts, dismiss tracking, an… by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2182 +- fix: revert customtabs for plugins by @deadlyjack in https://github.com/Acode-Foundation/Acode/pull/2183 +- fix: error when terminating terminal + fixed build by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2184 ## v1.12.0 (970) ### Important -* important(editor): Acode has migrated from Ace to CodeMirror. This is a major editor engine change and some plugins that depend on Ace internals may need updates for full compatibility. + +- important(editor): Acode has migrated from Ace to CodeMirror. This is a major editor engine change and some plugins that depend on Ace internals may need updates for full compatibility. ### Features -* feat(file-browser): add Copy Relative Path context menu option by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1854 -* feat(plugin-api): add PluginContext by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/1867 -* feat(ui): improve splash screen by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/1888 -* feat(shortcuts): pin file shortcuts to the home screen by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/1889 -* feat(plugin-api): expose `isCodeMirror` flag on editor manager by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1892 -* feat(plugin-api): add Ace compatibility shims for plugins by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1893 -* feat(codemirror): support `shift` + click selection by @AuDevTist1C in https://github.com/Acode-Foundation/Acode/pull/1899 -* feat(terminal): add touch selection More menu API and select dialog wiring by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1905 -* feat(settings): add sponsor sidebar icon visibility toggle by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1906 -* feat(plugin-api): add secrets plugin API by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/1902 -* feat(ads): add rewarded ads so free users can earn ad-free time by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1918 -* feat(plugin-api): expose CodeMirror packages for plugins by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1924 -* feat(editor): add Luau mode by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1927 -* feat(themes): add premium themes and overhaul legacy themes by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1930 -* feat(settings): add swatch previews to theme settings by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1931 -* feat(settings): redesign settings UI and localize help text by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1933 -* feat(native): move `checksumText` to native by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/1942 -* feat(plugins): limit plugin installation load by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/1951 -* feat(executor): add spawn stream support by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/1972 -* feat(codemirror): improve teardrop handles, scrolling, and selection quality by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1971 -* feat(tabs): add pin and unpin support for editor and non-editor tabs by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1984 -* feat(native): improve `launchApp` by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/1987 -* feat(fonts): add target-based font assignments and app font option by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1994 -* feat(tabs): add close left, close right, and close other tab commands by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2026 -* feat(storage): add public directory and merge `/home` with `/public` by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2049 -* feat(editor): add setting to disable HTML tag auto closing by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2051 -* feat(editor): select line on CodeMirror line number gutter click by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2052 -* feat(settings): add editor and UI zoom commands by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2058 -* feat(commands): restore `formatCode` command in CodeMirror 6 by @UnschooledGamer in https://github.com/Acode-Foundation/Acode/pull/2063 + +- feat(file-browser): add Copy Relative Path context menu option by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1854 +- feat(plugin-api): add PluginContext by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/1867 +- feat(ui): improve splash screen by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/1888 +- feat(shortcuts): pin file shortcuts to the home screen by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/1889 +- feat(plugin-api): expose `isCodeMirror` flag on editor manager by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1892 +- feat(plugin-api): add Ace compatibility shims for plugins by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1893 +- feat(codemirror): support `shift` + click selection by @AuDevTist1C in https://github.com/Acode-Foundation/Acode/pull/1899 +- feat(terminal): add touch selection More menu API and select dialog wiring by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1905 +- feat(settings): add sponsor sidebar icon visibility toggle by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1906 +- feat(plugin-api): add secrets plugin API by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/1902 +- feat(ads): add rewarded ads so free users can earn ad-free time by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1918 +- feat(plugin-api): expose CodeMirror packages for plugins by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1924 +- feat(editor): add Luau mode by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1927 +- feat(themes): add premium themes and overhaul legacy themes by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1930 +- feat(settings): add swatch previews to theme settings by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1931 +- feat(settings): redesign settings UI and localize help text by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1933 +- feat(native): move `checksumText` to native by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/1942 +- feat(plugins): limit plugin installation load by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/1951 +- feat(executor): add spawn stream support by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/1972 +- feat(codemirror): improve teardrop handles, scrolling, and selection quality by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1971 +- feat(tabs): add pin and unpin support for editor and non-editor tabs by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1984 +- feat(native): improve `launchApp` by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/1987 +- feat(fonts): add target-based font assignments and app font option by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1994 +- feat(tabs): add close left, close right, and close other tab commands by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2026 +- feat(storage): add public directory and merge `/home` with `/public` by @RohitKushvaha01 in https://github.com/Acode-Foundation/Acode/pull/2049 +- feat(editor): add setting to disable HTML tag auto closing by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2051 +- feat(editor): select line on CodeMirror line number gutter click by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2052 +- feat(settings): add editor and UI zoom commands by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/2058 +- feat(commands): restore `formatCode` command in CodeMirror 6 by @UnschooledGamer in https://github.com/Acode-Foundation/Acode/pull/2063 ### Fixes -* fix(terminal): normalize `acode open` paths so folder name is not `.` by @bajrangCoder in https://github.com/Acode-Foundation/Acode/pull/1864 -* fix(plugin): prevent plugin `'); + fs.writeFileSync(dir + '/main.jsx', "import React from 'react'; import {createRoot} from 'react-dom/client'; import {Clock} from 'lucide-react'; createRoot(document.getElementById('root')).render(
vite-probe
);"); + const options = {cwd: dir, encoding: 'utf8', timeout: 180000}; + child.execFileSync('npm', ['install', '--no-audit', '--no-fund'], options); + const port = await freePort(); + server = child.spawn('npm', ['run', 'dev', '--', '--port', String(port), '--strictPort'], {cwd: dir, detached: true, env: {...process.env, NO_COLOR: '1'}}); + const record = data => { log = (log + data).slice(-8000); }; + server.stdout.on('data', record); + server.stderr.on('data', record); + const url = 'http://127.0.0.1:' + port + '/'; + const page = await waitForServer(url, Date.now() + 120000); + assert.match(page, /@vite\/client/); + const module = await fetch(url + 'main.jsx'); + assert.equal(module.status, 200); + assert.match(await module.text(), /vite-probe/); + child.execFileSync('npm', ['run', 'build'], options); + assert.match(fs.readFileSync(dir + '/dist/index.html', 'utf8'), /assets\//); + console.log('VITE_REACT_PASS'); + })().catch(error => { console.error(error, log); process.exitCode = 1; }).finally(() => { + if (server?.pid) { try { process.kill(-server.pid, 'SIGTERM'); } catch {} } + fs.rmSync(dir, {recursive: true, force: true}); + }); + + function freePort() { + return new Promise((resolve, reject) => { + const probe = net.createServer().once('error', reject); + probe.listen(0, '127.0.0.1', () => { + const {port} = probe.address(); + probe.close(() => resolve(port)); + }); + }); + } + + async function waitForServer(url, deadline) { + for (;;) { + const remaining = deadline - Date.now(); + assert(remaining > 0, 'Vite did not start: ' + log); + assert.equal(server.exitCode, null, 'Vite exited: ' + log); + try { + const response = await fetch(url, {signal: AbortSignal.timeout(Math.min(10000, remaining))}); + if (response.status === 200) { + const page = await response.text(); + if (Date.now() < deadline) return page; + } + await response.body?.cancel(); + } catch {} + assert(Date.now() < deadline, 'Vite did not start: ' + log); + await new Promise(resolve => setTimeout(resolve, Math.min(500, deadline - Date.now()))); + } + } + """#) + XCTAssertEqual(result, "VITE_REACT_PASS") + } + + func testWebAssemblyWorkersAndLoopbackFetch() async throws { + let result = try await runNode("acode-node-runtime-probe.js", #""" + const assert = require('node:assert/strict'); + const http = require('node:http'); + const { MessageChannel, Worker } = require('node:worker_threads'); + (async () => { + const interfaces = Object.values(require('node:os').networkInterfaces()).flat(); + assert(interfaces.some(address => address.internal && address.address === '127.0.0.1' && address.netmask === '255.0.0.0')); + const bytes = Uint8Array.from([0,97,115,109,1,0,0,0,1,7,1,96,2,127,127,1,127,3,2,1,0,7,7,1,3,97,100,100,0,0,10,9,1,7,0,32,0,32,1,106,11]); + const { instance } = await WebAssembly.instantiate(bytes); + assert.equal(instance.exports.add(19, 23), 42); + console.log('WASM_PASS'); + const { port1, port2 } = new MessageChannel(); + await new Promise(resolve => { + port1.addEventListener('message', event => { + assert.equal(event.data, 42); + port1.close(); port2.close(); resolve(); + }, {once: true}); + port1.start(); port2.postMessage(42); + }); + const worker = new Worker("require('node:worker_threads').parentPort.postMessage(typeof WebAssembly + ':' + 6 * 7)", {eval: true}); + const [message] = await require('node:events').once(worker, 'message'); + assert.equal(message, 'object:42'); + await worker.terminate(); + console.log('WORKER_PASS'); + const server = http.createServer((req, res) => res.end('loopback π')); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + try { + const response = await fetch('http://127.0.0.1:' + server.address().port); + assert.equal(await response.text(), 'loopback π'); + } finally { server.closeAllConnections(); server.close(); } + console.log('FETCH_PASS'); + })().catch(error => { console.error(error); process.exitCode = 1; }); + """#) + XCTAssertEqual(result, "WASM_PASS\nWORKER_PASS\nFETCH_PASS") + } + + func testNodeNamedDeviceFailsWithoutScanning() async throws { + let webView = try await editorWebView() + let result = try await webView.callAsyncJavaScript(#""" + if (!await Terminal.isInstalled() && !await Terminal.install()) throw new Error(Terminal.lastInstallError); + return await Executor.execute(`dir=$(mktemp -d /tmp/acode-node-device.XXXXXX) + ln -s /dev/zero "$dir/node" + "$dir/node" 2>/dev/null + status=$? + rm -rf "$dir" + printf "exit=%s" "$status"`, true); + """#, arguments: [:], in: nil, contentWorld: .page) as? String + XCTAssertEqual(result, "exit=126") + } + + private func runNode(_ name: String, _ code: String) async throws -> String? { + let webView = try await editorWebView() + return try await webView.callAsyncJavaScript(#""" + if (!await Terminal.isInstalled() && !await Terminal.install()) throw new Error(Terminal.lastInstallError); + if (!await Executor.execute('command -v npm || true', true)) await Executor.execute('apk add --no-cache nodejs npm', true); + const fs = acode.require('fs'); + const path = 'alpine://localhost/tmp/' + name; + if (await fs(path).exists()) await fs(path).delete(); + await fs('alpine://localhost/tmp').createFile(name, code); + try { + return await Executor.execute('node /tmp/' + name, true); + } finally { + await fs(path).delete(); + } + """#, arguments: ["name": name, "code": code], in: nil, contentWorld: .page) as? String + } +} diff --git a/platforms/ios/runnerTests/AlpinePackageTests.swift b/platforms/ios/runnerTests/AlpinePackageTests.swift index 518d6a7fce..d20ba36442 100644 --- a/platforms/ios/runnerTests/AlpinePackageTests.swift +++ b/platforms/ios/runnerTests/AlpinePackageTests.swift @@ -77,7 +77,7 @@ final class AlpinePackageTests: BridgeTestCase { const child = require('node:child_process'); const startup = child.spawnSync(process.execPath, ['-e', 'process.stdout.write(typeof WebAssembly)'], {encoding:'utf8'}); assert.equal(startup.status, 0); - assert.equal(startup.stdout, 'undefined'); + assert.equal(startup.stdout, 'object'); assert.equal(startup.stderr, ''); assert.equal(1 + 2, 3); fs.writeFileSync('/tmp/acode-node-utf8', 'hello π'); diff --git a/platforms/ios/runnerTests/AuthenticationTests.swift b/platforms/ios/runnerTests/AuthenticationTests.swift index 3ee015d858..2a2d4638e4 100644 --- a/platforms/ios/runnerTests/AuthenticationTests.swift +++ b/platforms/ios/runnerTests/AuthenticationTests.swift @@ -113,6 +113,24 @@ final class AuthenticationTests: XCTestCase { XCTAssertEqual(try auth.token(for: development), "") } + func testAccountServicesUseTheProductionAccountWithoutBecomingSignInHosts() throws { + let academy = URL(string: "https://academy.acode.app")! + try auth.save("production-token") + try auth.save("development-token", for: URL(string: "https://dev.acode.app")!) + XCTAssertEqual(try auth.token(for: academy), "production-token") + XCTAssertThrowsError(try auth.save("academy-token", for: academy)) + XCTAssertThrowsError(try auth.begin(baseURL: academy.absoluteString, version: 0)) + XCTAssertThrowsError(try AppAuthentication.apiOrigin("https://academy.acode.app.evil.test")) + var source = URLRequest(url: URL(string: "acode://localhost/__api__/v1/user/login")!) + source.setValue(academy.absoluteString, forHTTPHeaderField: "X-Acode-API-Origin") + source.setValue("include", forHTTPHeaderField: "X-Acode-Credentials") + let request = try AppAPIHandler(auth: auth).request(for: source) + XCTAssertEqual(request.url?.absoluteString, "https://academy.acode.app/api/v1/user/login") + let tokens = (request.value(forHTTPHeaderField: "Cookie") ?? "").components(separatedBy: ";").map { $0.trimmingCharacters(in: .whitespaces) }.filter { $0.hasPrefix("token=") } + XCTAssertEqual(tokens, ["token=production-token"]) + try auth.logout() + } + func testExchangeErrorsExplainRetryTimingAndExpiredSignIn() { let url = URL(string: "https://dev.acode.app/api/user/app-token/exchange")! let limited = HTTPURLResponse(url: url, statusCode: 429, httpVersion: nil, headerFields: ["Retry-After": "61"])! @@ -166,4 +184,23 @@ final class AuthenticationTests: XCTestCase { AppAPIHandler.storeCookies(from: response, credentials: true) XCTAssertFalse((HTTPCookieStorage.shared.cookies ?? []).contains { $0.name == name }) } + + func testAccountServicesOnlyStoreTheirOwnCookies() { + let name = "academy-fixture-" + UUID().uuidString + defer { + for cookie in HTTPCookieStorage.shared.cookies ?? [] where cookie.name == name { + HTTPCookieStorage.shared.deleteCookie(cookie) + } + } + let academy = URL(string: "https://academy.acode.app/api/cookie")! + let parent = HTTPURLResponse(url: academy, statusCode: 200, httpVersion: nil, headerFields: ["Set-Cookie": "\(name)=parent; Domain=.acode.app; Path=/; Secure"])! + AppAPIHandler.storeCookies(from: parent, credentials: true) + XCTAssertFalse((HTTPCookieStorage.shared.cookies ?? []).contains { $0.name == name }) + let own = HTTPURLResponse(url: academy, statusCode: 200, httpVersion: nil, headerFields: ["Set-Cookie": "\(name)=own; Path=/; Secure"])! + AppAPIHandler.storeCookies(from: own, credentials: true) + XCTAssertEqual((HTTPCookieStorage.shared.cookies(for: academy) ?? []).first { $0.name == name }?.value, "own") + XCTAssertFalse((HTTPCookieStorage.shared.cookies(for: URL(string: "https://acode.app/api/cookie")!) ?? []).contains { $0.name == name }) + XCTAssertTrue(AppAuthentication.acceptsCookie(for: "acode.app", from: "dev.acode.app")) + XCTAssertFalse(AppAuthentication.acceptsCookie(for: "acode.app", from: "academy.acode.app")) + } } diff --git a/platforms/ios/runnerTests/Iap.storekit b/platforms/ios/runnerTests/Iap.storekit index 1e52f516f9..258a710619 100644 --- a/platforms/ios/runnerTests/Iap.storekit +++ b/platforms/ios/runnerTests/Iap.storekit @@ -46,6 +46,96 @@ "productID": "ios_test_tip", "referenceName": "Tip test", "type": "Consumable" + }, + { + "displayPrice": "0.99", + "familyShareable": false, + "internalID": "200", + "localizations": [ + { + "description": "30 days of sponsorship (local test only)", + "displayName": "Crystal", + "locale": "en_US" + } + ], + "productID": "crystal", + "referenceName": "Crystal sponsor test", + "type": "Consumable" + }, + { + "displayPrice": "1.99", + "familyShareable": false, + "internalID": "201", + "localizations": [ + { + "description": "30 days of sponsorship (local test only)", + "displayName": "Bronze", + "locale": "en_US" + } + ], + "productID": "bronze", + "referenceName": "Bronze sponsor test", + "type": "Consumable" + }, + { + "displayPrice": "4.99", + "familyShareable": false, + "internalID": "202", + "localizations": [ + { + "description": "30 days of sponsorship (local test only)", + "displayName": "Silver", + "locale": "en_US" + } + ], + "productID": "silver", + "referenceName": "Silver sponsor test", + "type": "Consumable" + }, + { + "displayPrice": "9.99", + "familyShareable": false, + "internalID": "203", + "localizations": [ + { + "description": "30 days of sponsorship (local test only)", + "displayName": "Gold", + "locale": "en_US" + } + ], + "productID": "gold", + "referenceName": "Gold sponsor test", + "type": "Consumable" + }, + { + "displayPrice": "19.99", + "familyShareable": false, + "internalID": "204", + "localizations": [ + { + "description": "30 days of sponsorship (local test only)", + "displayName": "Platinum", + "locale": "en_US" + } + ], + "productID": "platinum", + "referenceName": "Platinum sponsor test", + "type": "Consumable" + }, + { + "displayPrice": "49.99", + "familyShareable": false, + "internalID": "205", + "localizations": [ + { + "description": "30 days of sponsorship (local test only)", + "displayName": "Titanium", + "locale": "en_US" + } + ], + "productID": "titanium", + "referenceName": "Titanium sponsor test", + "type": "Consumable" } ], "settings": { diff --git a/platforms/ios/runnerTests/PreviewBrowserTests.swift b/platforms/ios/runnerTests/PreviewBrowserTests.swift index 5c60eded92..b299438f0d 100644 --- a/platforms/ios/runnerTests/PreviewBrowserTests.swift +++ b/platforms/ios/runnerTests/PreviewBrowserTests.swift @@ -4,6 +4,16 @@ import WebKit @MainActor final class PreviewBrowserTests: BridgeTestCase { + func testTerminalPreviewsUseSeparateEphemeralStorage() throws { + let url = try XCTUnwrap(URL(string: "http://localhost:3000")) + let first = PreviewViewController(url: url, theme: [:], console: false, ephemeral: true) + let second = PreviewViewController(url: url, theme: [:], console: false, ephemeral: true) + let regular = PreviewViewController(url: url, theme: [:], console: false) + XCTAssertFalse(first.webView.configuration.websiteDataStore.isPersistent) + XCTAssertFalse(first.webView.configuration.websiteDataStore === second.webView.configuration.websiteDataStore) + XCTAssertTrue(regular.webView.configuration.websiteDataStore.isPersistent) + } + func testConsoleFocusKeepsScaleAndFitsAboveKeyboard() async throws { let app = try await editorWebView() var responder: UIResponder? = app diff --git a/platforms/ios/runnerTests/PrivacySignalsTests.swift b/platforms/ios/runnerTests/PrivacySignalsTests.swift new file mode 100644 index 0000000000..7574985b0e --- /dev/null +++ b/platforms/ios/runnerTests/PrivacySignalsTests.swift @@ -0,0 +1,75 @@ +import UserMessagingPlatform +import XCTest +@testable import runner + +extension AdsBridgeTests { + func testPrivacyBridgeReturnsOnlyCurrentIabSignals() async throws { + let (controller, plugin) = try await host() + let suite = "acode.privacy-test.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + let original = plugin.privacy + defer { plugin.privacy = original; defaults.removePersistentDomain(forName: suite) } + let expected: [String: Any] = [ + "IABTCF_gdprApplies": 1, "IABTCF_TCString": "test-tc", + "IABTCF_AddtlConsent": "2~1.2", "IABGPP_HDR_GppString": "test-gpp", + "IABGPP_GppSID": "7_8", "IABTCF_PurposeConsents": "11000010000", + "IABTCF_PurposeLegitimateInterests": "01000010000" + ] + for (key, value) in expected { defaults.set(value, forKey: key) } + defaults.set("private", forKey: "unrelated-setting") + plugin.privacy = AMBPrivacy(plugin: plugin, information: PrivacySignalsFixture(), defaults: defaults) + let state = try await controller.webView.callAsyncJavaScript( + "return await admob.privacy.getState();", arguments: [:], in: nil, contentWorld: .page) as? [String: Any] + XCTAssertEqual(state?["consentStatus"] as? String, "obtained") + XCTAssertEqual(state?["canRequestAds"] as? Bool, true) + XCTAssertEqual(state?["iabSignals"] as? NSDictionary, expected as NSDictionary) + } + + func testPrivacySnapshotReflectsWithdrawalAndRemovedSignals() async throws { + let (controller, plugin) = try await host() + let suite = "acode.privacy-test.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + let original = plugin.privacy + defer { plugin.privacy = original; defaults.removePersistentDomain(forName: suite) } + plugin.privacy = AMBPrivacy(plugin: plugin, information: PrivacySignalsFixture(), defaults: defaults) + defaults.set(1, forKey: "IABTCF_gdprApplies") + defaults.set("accepted-tc", forKey: "IABTCF_TCString") + defaults.set("11000010000", forKey: "IABTCF_PurposeConsents") + for purposes in ["11000010000", "00000000000", "11000010000"] { + defaults.set(purposes, forKey: "IABTCF_PurposeConsents") + let state = try await controller.webView.callAsyncJavaScript( + "return await admob.privacy.getState();", arguments: [:], in: nil, contentWorld: .page) as? [String: Any] + XCTAssertEqual(state?["canRequestAds"] as? Bool, true) + let signals = try XCTUnwrap(state?["iabSignals"] as? [String: Any]) + XCTAssertEqual(signals["IABTCF_PurposeConsents"] as? String, purposes) + } + defaults.removeObject(forKey: "IABTCF_TCString") + defaults.removeObject(forKey: "IABTCF_PurposeConsents") + let state = try await controller.webView.callAsyncJavaScript( + "return await admob.privacy.showOptions();", arguments: [:], in: nil, contentWorld: .page) as? [String: Any] + let signals = try XCTUnwrap(state?["iabSignals"] as? [String: Any]) + XCTAssertNil(signals["IABTCF_TCString"]) + XCTAssertEqual(signals["IABTCF_PurposeConsents"] as? String, "") + } + + func testPrivacySnapshotPreservesBitStringsAndMarksInvalidPurposeUnknown() throws { + let suite = "acode.privacy-test.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let plugin = AMBPlugin(bridge: Bridge()) + let privacy = AMBPrivacy(plugin: plugin, information: PrivacySignalsFixture(), defaults: defaults) + defaults.set("0", forKey: "IABTCF_gdprApplies") + defaults.set("01000010000", forKey: "IABTCF_PurposeLegitimateInterests") + defaults.set(1100001, forKey: "IABTCF_PurposeConsents") + let signals = try XCTUnwrap(privacy.state["iabSignals"] as? [String: Any]) + XCTAssertEqual(signals["IABTCF_gdprApplies"] as? String, "0") + XCTAssertEqual(signals["IABTCF_PurposeLegitimateInterests"] as? String, "01000010000") + XCTAssertEqual(signals["IABTCF_PurposeConsents"] as? String, "") + } +} + +private final class PrivacySignalsFixture: ConsentInformation { + override var consentStatus: ConsentStatus { .obtained } + override var canRequestAds: Bool { true } + override var privacyOptionsRequirementStatus: PrivacyOptionsRequirementStatus { .notRequired } +} diff --git a/platforms/ios/runnerTests/SponsorPurchaseTests.swift b/platforms/ios/runnerTests/SponsorPurchaseTests.swift new file mode 100644 index 0000000000..a02b85bc7c --- /dev/null +++ b/platforms/ios/runnerTests/SponsorPurchaseTests.swift @@ -0,0 +1,215 @@ +import StoreKitTest +import WebKit +import XCTest + +@MainActor +final class SponsorPurchaseTests: BridgeTestCase { + private var session: SKTestSession! + private var scripts: WKUserContentController? + private var originalScripts: [WKUserScript] = [] + + override func setUp() async throws { + let url = try XCTUnwrap(Bundle(for: Self.self).url(forResource: "Iap", withExtension: "storekit")) + session = try SKTestSession(contentsOf: url) + session.resetToDefaultState() + session.clearTransactions() + session.disableDialogs = true + let webView = try await appWebView() + let scripts = webView.configuration.userContentController + self.scripts = scripts + originalScripts = scripts.userScripts + // The app protects fetch after startup, and the iOS transport rewrites API URLs. + scripts.addUserScript(WKUserScript(source: """ + window.sponsorRequests=[];window.sponsorReject=true;window.sponsorFailureStatus=503; + const originalFetch=window.fetch.bind(window); + window.fetch=async(input,options)=>{ + const request=new Request(input,options); + const path=new URL(request.url).pathname; + if(['/api/sponsors','/__api__/sponsors'].includes(path))return new Response('[]'); + if(['/api/sponsor','/__api__/sponsor'].includes(path)) { + sponsorRequests.push(await request.json()); + return new Response(JSON.stringify(sponsorReject?{error:'Test registration failure'}:{}),{status:sponsorReject?sponsorFailureStatus:201}); + } + return originalFetch(input,options); + }; + """, injectionTime: .atDocumentStart, forMainFrameOnly: true)) + _ = try await webView.evaluateJavaScript("localStorage.removeItem('sponsor_pending_app.acode');localStorage.removeItem('sponsor_crystal')") + try await super.setUp() + try await reloadWebView(webView) + _ = try await editorWebView() + } + + override func tearDownWithError() throws { + scripts?.removeAllUserScripts() + for script in originalScripts { scripts?.addUserScript(script) } + scripts = nil + originalScripts = [] + session?.clearTransactions() + session?.resetToDefaultState() + session = nil + } + + func testSponsorPurchaseRetriesRegistrationBeforeFinishingAndCanBeBoughtAgain() async throws { + let webView = try await prepare() + try await openSponsor(webView) + let count = try await webView.evaluateJavaScript("document.querySelectorAll('#sponsor-page .tier').length") as? Int + XCTAssertEqual(count, 6) + try await selectCrystal(webView) + try await wait(webView, "sponsorRequests.length===1") + let unfinished = try await purchases(webView) + XCTAssertEqual(unfinished.count, 1) + let request = try await webView.evaluateJavaScript("sponsorRequests[0]") as? [String: Any] + XCTAssertEqual(request?["tier"] as? String, "crystal") + XCTAssertEqual(request?["packageName"] as? String, "app.acode") + XCTAssertEqual((request?["purchaseToken"] as? String)?.split(separator: ".").count, 3) + let retained = try await webView.evaluateJavaScript("!!localStorage.getItem('sponsor_crystal')") as? Bool + XCTAssertEqual(retained, true) + // Reopening the page recovers the unfinished transaction after a network failure. + _ = try await webView.evaluateJavaScript("sponsorReject=false;document.querySelectorAll('.prompt:not(.hide) button').forEach(button=>button.click());document.querySelector('#sponsor-page').closest('wc-page').hide()") + try await openSponsor(webView, waitForProducts: false) + try await wait(webView, "sponsorRequests.length===2&&!localStorage.getItem('sponsor_crystal')") + let remaining = try await purchases(webView) + XCTAssertTrue(remaining.isEmpty) + _ = try await webView.evaluateJavaScript("document.querySelectorAll('.prompt:not(.hide) button').forEach(button=>button.click())") + try await openSponsor(webView) + try await selectCrystal(webView) + try await wait(webView, "sponsorRequests.length===3&&!localStorage.getItem('sponsor_crystal')") + XCTAssertEqual(session.allTransactions().filter { $0.productIdentifier == "crystal" }.count, 2) + let finished = try await purchases(webView) + XCTAssertTrue(finished.isEmpty) + } + + func testCancelledAndPendingSponsorPurchasesDoNotRegisterUntilApproved() async throws { + let webView = try await prepare() + _ = try await webView.evaluateJavaScript("sponsorReject=false") + try await openSponsor(webView) + try await session.setSimulatedError(.generic(.userCancelled), forAPI: StoreKitPurchaseAPI()) + try await selectCrystal(webView) + try await wait(webView, "sponsorErrors.includes(1)&&app.classList.contains('title-loading-hide')") + let cancelledCount = try await webView.evaluateJavaScript("sponsorRequests.length") as? Int + XCTAssertEqual(cancelledCount, 0) + try await session.setSimulatedError(nil, forAPI: StoreKitPurchaseAPI()) + session.askToBuyEnabled = true + try await selectCrystal(webView) + for _ in 0..<100 { + if session.allTransactions().contains(where: { $0.state == .deferred }) { break } + try await Task.sleep(for: .milliseconds(100)) + } + let pending = try XCTUnwrap(session.allTransactions().first { $0.state == .deferred }) + let pendingCount = try await webView.evaluateJavaScript("sponsorRequests.length") as? Int + XCTAssertEqual(pendingCount, 0) + try session.approveAskToBuyTransaction(identifier: pending.identifier) + try await wait(webView, "sponsorRequests.length===1&&!localStorage.getItem('sponsor_crystal')") + } + + func testPaidSponsorRecoversAfterReloadWithoutOpeningSponsorPage() async throws { + let webView = try await prepare() + // Keep fulfillment pending, then lose the WebView and its local purchase context. + _ = try await session.buyProduct(identifier: "crystal") + _ = try await webView.evaluateJavaScript("localStorage.removeItem('sponsor_crystal');localStorage.removeItem('sponsor_pending_app.acode')") + let scripts = webView.configuration.userContentController + let originalScripts = scripts.userScripts.map { $0 } + defer { + scripts.removeAllUserScripts() + originalScripts.forEach(scripts.addUserScript) + } + scripts.addUserScript(WKUserScript(source: """ + window.sponsorReject=false; + """, injectionTime: .atDocumentStart, forMainFrameOnly: true)) + try await reloadWebView(webView) + _ = try await editorWebView() + try await wait(webView, "!!document.querySelector('.prompt.multi:not(.hide) input')") + let page = try await webView.evaluateJavaScript("!!document.querySelector('#sponsor-page')") as? Bool + XCTAssertEqual(page, false) + _ = try await webView.evaluateJavaScript("document.querySelector('.prompt.multi:not(.hide) .help').click()") + let message = try await webView.evaluateJavaScript("document.querySelector('.prompt.alert:not(.hide)').textContent") as? String + XCTAssertTrue(message?.contains("not be charged again") == true) + _ = try await webView.evaluateJavaScript(""" + document.querySelector('.prompt.alert:not(.hide) button').click(); + const input=document.querySelector('.prompt.multi:not(.hide) input'); + input.value='Recovered Sponsor';input.dispatchEvent(new Event('input',{bubbles:true})); + document.querySelector('.prompt.multi:not(.hide) button[type="submit"]').click(); + """) + try await wait(webView, "sponsorRequests.length===1&&!localStorage.getItem('sponsor_pending_app.acode')") + let request = try await webView.evaluateJavaScript("sponsorRequests[0]") as? [String: Any] + XCTAssertEqual(request?["name"] as? String, "Recovered Sponsor") + XCTAssertEqual(request?["tier"] as? String, "crystal") + XCTAssertEqual(session.allTransactions().filter { $0.productIdentifier == "crystal" }.count, 1) + let remaining = try await purchases(webView) + XCTAssertTrue(remaining.isEmpty) + } + + func testRejectedDetailsCanBeCorrectedWithoutAnotherCharge() async throws { + let webView = try await prepare() + _ = try await webView.evaluateJavaScript("sponsorFailureStatus=400") + try await openSponsor(webView) + try await selectCrystal(webView) + try await wait(webView, "sponsorRequests.length===1&&!localStorage.getItem('sponsor_crystal')") + let unfinished = try await purchases(webView) + XCTAssertEqual(unfinished.count, 1) + let details = try await webView.evaluateJavaScript("JSON.parse(localStorage.getItem('sponsor_pending_app.acode'))[0].details===null") as? Bool + XCTAssertEqual(details, true) + _ = try await webView.evaluateJavaScript("sponsorReject=false;document.querySelectorAll('.prompt:not(.hide) button').forEach(button=>button.click());document.querySelector('#sponsor-page').closest('wc-page').hide()") + try await openSponsor(webView) + try await wait(webView, "!!document.querySelector('.prompt.multi:not(.hide) input')") + _ = try await webView.evaluateJavaScript(""" + const input=document.querySelector('.prompt.multi:not(.hide) input'); + input.value='Corrected Sponsor';input.dispatchEvent(new Event('input',{bubbles:true})); + document.querySelector('.prompt.multi:not(.hide) button[type="submit"]').click(); + """) + try await wait(webView, "sponsorRequests.length===2&&!localStorage.getItem('sponsor_pending_app.acode')") + let name = try await webView.evaluateJavaScript("sponsorRequests[1].name") as? String + XCTAssertEqual(name, "Corrected Sponsor") + XCTAssertEqual(session.allTransactions().filter { $0.productIdentifier == "crystal" }.count, 1) + let remaining = try await purchases(webView) + XCTAssertTrue(remaining.isEmpty) + } + + private func prepare() async throws -> WKWebView { + let webView = try await editorWebView() + _ = try await webView.evaluateJavaScript(""" + window.sponsorRequests=[];window.sponsorErrors=[];window.sponsorReject=true;window.sponsorFailureStatus=503; + const originalPurchase=iap.purchase; + iap.purchase=(product,success,failure,updateError)=>originalPurchase(product,success, + error=>{sponsorErrors.push(error);failure?.(error)}, + updateError?error=>{sponsorErrors.push(error);updateError(error)}:undefined); + localStorage.removeItem('sponsor_crystal'); + null; + """) + _ = try await webView.callAsyncJavaScript(""" + await acode.exec('open','settings'); + acode.require('settings').uiSettings['main-settings'].getListElement().querySelector('[data-key="sponsors"]').click(); + """, arguments: [:], in: nil, contentWorld: .page) + try await wait(webView, "!!document.querySelector('#sponsors-page .cta-button')") + return webView + } + + private func openSponsor(_ webView: WKWebView, waitForProducts: Bool = true) async throws { + // A closing page remains in the DOM until its fade-out finishes. + try await wait(webView, "!document.querySelector('#sponsor-page')&&!!document.querySelector('#sponsors-page .cta-button')") + _ = try await webView.evaluateJavaScript("document.querySelector('#sponsors-page .cta-button').click()") + if waitForProducts { try await wait(webView, "!!document.querySelector('#sponsor-page .crystal .purchase-btn')") } + } + + private func selectCrystal(_ webView: WKWebView) async throws { + _ = try await webView.evaluateJavaScript("document.querySelector('#sponsor-page .crystal .purchase-btn').click()") + try await wait(webView, "!!document.querySelector('.prompt.multi:not(.hide) input')") + _ = try await webView.callAsyncJavaScript(""" + const input=document.querySelector('.prompt.multi:not(.hide) input');input.value='Simulator Sponsor';input.dispatchEvent(new Event('input',{bubbles:true})); + document.querySelector('.prompt.multi:not(.hide) button[type="submit"]').click(); + """, arguments: [:], in: nil, contentWorld: .page) + } + + private func purchases(_ webView: WKWebView) async throws -> [[String: Any]] { + try await webView.callAsyncJavaScript("return await new Promise((resolve,reject)=>iap.getPurchases(resolve,reject))", arguments: [:], in: nil, contentWorld: .page) as? [[String: Any]] ?? [] + } + + private func wait(_ webView: WKWebView, _ expression: String) async throws { + for _ in 0..<150 { + if try await webView.evaluateJavaScript(expression) as? Bool == true { return } + try await Task.sleep(for: .milliseconds(100)) + } + let details = try await webView.evaluateJavaScript("JSON.stringify({errors:window.sponsorErrors,requests:window.sponsorRequests?.map(({purchaseToken,...details})=>details),details:localStorage.getItem('sponsor_crystal'),dialogs:[...document.querySelectorAll('.prompt:not(.hide)')].map(element=>element.textContent)})") + throw NSError(domain: "SponsorTests", code: 1, userInfo: [NSLocalizedDescriptionKey: "Timed out: \(expression); scene=\(String(describing: webView.window?.windowScene?.activationState)); \(details ?? "")"]) + } +} diff --git a/platforms/ios/runnerTests/TrackingAuthorizationTests.swift b/platforms/ios/runnerTests/TrackingAuthorizationTests.swift index 30b77978ec..0b2fb9ba24 100644 --- a/platforms/ios/runnerTests/TrackingAuthorizationTests.swift +++ b/platforms/ios/runnerTests/TrackingAuthorizationTests.swift @@ -13,8 +13,12 @@ final class TrackingAuthorizationTests: XCTestCase { var callback: ((ATTrackingManager.AuthorizationStatus) -> Void)? let notifications = NotificationCenter() let requested = expectation(description: "ATT requested in foreground") + var progressShown = 0 + var progressHidden = 0 let tracking = AMBTrackingAuthorization(status: { .notDetermined }, isActive: { self.appActive }, - notifications: notifications, request: { calls += 1; callback = $0; requested.fulfill() }) + notifications: notifications, + showProgress: { progressShown += 1; return { progressHidden += 1 } }, + request: { calls += 1; callback = $0; requested.fulfill() }) let finished = expectation(description: "Both callers receive the decision") finished.expectedFulfillmentCount = 2 for _ in 0..<2 { @@ -24,17 +28,23 @@ final class TrackingAuthorizationTests: XCTestCase { } } XCTAssertEqual(calls, 0) + XCTAssertEqual(progressShown, 1) + XCTAssertEqual(progressHidden, 0) appActive = true notifications.post(name: UIApplication.didBecomeActiveNotification, object: nil) await fulfillment(of: [requested], timeout: 2) XCTAssertEqual(calls, 1) callback?(.denied) await fulfillment(of: [finished], timeout: 2) + XCTAssertEqual(progressHidden, 1) } func testExistingTrackingDecisionsDoNotPromptAgain() { for status: ATTrackingManager.AuthorizationStatus in [.denied, .restricted, .authorized] { - let tracking = AMBTrackingAuthorization(status: { status }, isActive: { false }, request: { _ in + let tracking = AMBTrackingAuthorization(status: { status }, isActive: { false }, showProgress: { + XCTFail("A decided permission must not show loading feedback") + return {} + }, request: { _ in XCTFail("A decided permission must not prompt again") }) var result: ATTrackingManager.AuthorizationStatus? @@ -45,7 +55,11 @@ final class TrackingAuthorizationTests: XCTestCase { func testUndeterminedResultCannotStartAdsAndAllowsRetry() async { var calls = 0 - let tracking = AMBTrackingAuthorization(status: { .notDetermined }, isActive: { true }, request: { + var progressVisible = false + let tracking = AMBTrackingAuthorization(status: { .notDetermined }, isActive: { true }, showProgress: { + progressVisible = true + return { progressVisible = false } + }, request: { calls += 1 $0(calls == 1 ? .notDetermined : .authorized) }) @@ -55,6 +69,7 @@ final class TrackingAuthorizationTests: XCTestCase { failed.fulfill() } await fulfillment(of: [failed], timeout: 2) + XCTAssertFalse(progressVisible) let retried = expectation(description: "Retry succeeds") tracking.authorize { result in XCTAssertEqual(try? result.get(), .authorized) @@ -62,12 +77,17 @@ final class TrackingAuthorizationTests: XCTestCase { } await fulfillment(of: [retried], timeout: 2) XCTAssertEqual(calls, 2) + XCTAssertFalse(progressVisible) } func testResetCancelsCallerWithoutStartingAnOverlappingTrackingRequest() async { var requests = 0 + var progressVisible = false var reply: (@Sendable (ATTrackingManager.AuthorizationStatus) -> Void)? - let tracking = AMBTrackingAuthorization(status: { .notDetermined }, isActive: { true }, request: { + let tracking = AMBTrackingAuthorization(status: { .notDetermined }, isActive: { true }, showProgress: { + progressVisible = true + return { progressVisible = false } + }, request: { requests += 1 reply = $0 }) @@ -77,14 +97,17 @@ final class TrackingAuthorizationTests: XCTestCase { } tracking.cancel() XCTAssertTrue(cancelled) + XCTAssertFalse(progressVisible) let completed = expectation(description: "New caller receives the outstanding OS decision") tracking.authorize { result in XCTAssertEqual(try? result.get(), .denied) completed.fulfill() } XCTAssertEqual(requests, 1) + XCTAssertTrue(progressVisible) reply?(.denied) await fulfillment(of: [completed], timeout: 2) + XCTAssertFalse(progressVisible) } func testDeadlineFailsWaitersWithoutOverlappingOSRequestAndLateReplyCanRecover() async { @@ -144,8 +167,12 @@ final class TrackingAuthorizationTests: XCTestCase { func testInactiveWaitIsBoundedAndCanRetryWhenActive() async { appActive = false var calls = 0 + var progressVisible = false let tracking = AMBTrackingAuthorization(status: { .notDetermined }, isActive: { self.appActive }, - timeout: .milliseconds(25), request: { calls += 1; $0(.denied) }) + timeout: .milliseconds(25), showProgress: { + progressVisible = true + return { progressVisible = false } + }, request: { calls += 1; $0(.denied) }) let timedOut = expectation(description: "Inactive wait times out") tracking.authorize { result in if case .success = result { XCTFail("Inactive timeout must not start ads") } @@ -153,6 +180,7 @@ final class TrackingAuthorizationTests: XCTestCase { } await fulfillment(of: [timedOut], timeout: 2) XCTAssertEqual(calls, 0) + XCTAssertFalse(progressVisible) appActive = true let completed = expectation(description: "Active retry succeeds") tracking.authorize { result in @@ -190,4 +218,21 @@ final class TrackingAuthorizationTests: XCTestCase { replies[1](.restricted) await fulfillment(of: [completed], timeout: 2) } + + func testProgressFitsCompactScreenWithoutBlockingTouchesAndCleansUp() throws { + let container = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 568)) + let existingContent = UIView(frame: container.bounds) + container.addSubview(existingContent) + let hide = AMBPrivacyProgress.show(in: container) + container.layoutIfNeeded() + let panel = try XCTUnwrap(container.subviews.last as? UIVisualEffectView) + XCTAssertFalse(panel.isUserInteractionEnabled) + XCTAssertFalse(panel.hasAmbiguousLayout) + XCTAssertGreaterThan(panel.frame.height, 0) + XCTAssertGreaterThanOrEqual(panel.frame.minX, 20) + XCTAssertLessThanOrEqual(panel.frame.maxX, 300) + hide() + hide() + XCTAssertEqual(container.subviews, [existingContent]) + } } diff --git a/src/components/terminal/openTerminalLink.js b/src/components/terminal/openTerminalLink.js new file mode 100644 index 0000000000..9758411fab --- /dev/null +++ b/src/components/terminal/openTerminalLink.js @@ -0,0 +1,43 @@ +import confirm from "dialogs/confirm"; +import browser from "native/browser"; +import helpers from "utils/helpers"; + +export default async function openTerminalLink(uri, isRemote = false) { + if (globalThis.Bridge?.platformId === "ios" && !isRemote) { + const local = localPreviewUrl(uri); + if (local) { + try { + browser.open(local, false, { + ephemeral: true, + onError: (error) => helpers.error(error), + }); + } catch (error) { + helpers.error(error); + } + return; + } + } + if (await confirm("Terminal", `Do you want to open ${uri} in browser?`)) { + system.openInBrowser(uri); + } +} + +function localPreviewUrl(uri) { + try { + const url = new URL(uri); + if (!["http:", "https:"].includes(url.protocol)) return null; + const host = url.hostname.toLowerCase().replace(/\.$/, ""); + if (host === "0.0.0.0") url.hostname = "127.0.0.1"; + else if (host === "[::]") url.hostname = "[::1]"; + else if ( + host !== "localhost" && + host !== "[::1]" && + !/^127\.\d+\.\d+\.\d+$/.test(host) + ) { + return null; + } + return url.href; + } catch { + return null; + } +} diff --git a/src/components/terminal/terminal.js b/src/components/terminal/terminal.js index eab8c117ad..b89ee191a1 100644 --- a/src/components/terminal/terminal.js +++ b/src/components/terminal/terminal.js @@ -16,11 +16,11 @@ import { getEffectiveKeyBindings, getResolvedKeyBindingsVersion, } from "cm/commandRegistry"; -import confirm from "dialogs/confirm"; import fonts from "lib/fonts"; import appSettings from "lib/settings"; import { quotePosixShellArg } from "utils/shell"; import LigaturesAddon from "./ligatures"; +import openTerminalLink from "./openTerminalLink"; import { DEFAULT_TERMINAL_SETTINGS, getTerminalSettings, @@ -100,15 +100,9 @@ export default class TerminalComponent { this.fitAddon = new FitAddon(); this.unicode11Addon = new Unicode11Addon(); this.searchAddon = new SearchAddon(); - this.webLinksAddon = new WebLinksAddon(async (event, uri) => { - const linkOpenConfirm = await confirm( - "Terminal", - `Do you want to open ${uri} in browser?`, - ); - if (linkOpenConfirm) { - system.openInBrowser(uri); - } - }); + this.webLinksAddon = new WebLinksAddon((event, uri) => + openTerminalLink(uri, Boolean(this.remoteSsh)), + ); this.webglAddon = null; // Load addons diff --git a/src/lib/platform.js b/src/lib/platform.js index 18cef2e5ae..f305ce584d 100644 --- a/src/lib/platform.js +++ b/src/lib/platform.js @@ -7,7 +7,6 @@ export default Object.freeze({ androidIntents: !isIOS, appExit: !isIOS, apkUpdates: !isIOS, - // The account backend does not yet verify App Store plugin or sponsor orders. + // The account backend does not yet verify App Store plugin orders. pluginPurchases: !isIOS, - sponsorPurchases: !isIOS, }); diff --git a/src/main.js b/src/main.js index 1a609388dd..deef8da021 100644 --- a/src/main.js +++ b/src/main.js @@ -477,6 +477,12 @@ async function getAndroidSdkInt() { async function onAppRendered(proPurchaseCheck) { document.body.removeAttribute("data-small-msg"); app.classList.remove("loading", "splash"); + if (typeof iap !== "undefined") { + void proPurchaseCheck + .then(() => import("pages/sponsor/recovery")) + .then(({ default: startSponsorRecovery }) => startSponsorRecovery()) + .catch(console.error); + } if (settings.value.developerMode) setTimeout(startDevTools); // load plugins diff --git a/src/native/admob/privacy.ts b/src/native/admob/privacy.ts index 2569f2f85e..e566b9b0b1 100644 --- a/src/native/admob/privacy.ts +++ b/src/native/admob/privacy.ts @@ -6,10 +6,21 @@ export type PrivacyConsentStatus = | "notRequired" | "obtained"; +export type PrivacyIabSignals = { + IABTCF_gdprApplies?: string | number; + IABTCF_TCString?: string; + IABTCF_AddtlConsent?: string; + IABGPP_HDR_GppString?: string; + IABGPP_GppSID?: string; + IABTCF_PurposeConsents?: string; + IABTCF_PurposeLegitimateInterests?: string; +}; + export type PrivacyConsentState = { consentStatus: PrivacyConsentStatus; canRequestAds: boolean; privacyOptionsRequired: boolean; + iabSignals?: PrivacyIabSignals; }; export type ConsentDebugGeography = "disabled" | "eea" | "notEea"; diff --git a/src/native/bridge.ts b/src/native/bridge.ts index 0031a4ac3d..e32f4c3b77 100644 --- a/src/native/bridge.ts +++ b/src/native/bridge.ts @@ -7,6 +7,7 @@ export type NativeExec = ( service: string, action: string, args?: unknown[], + onRelease?: () => void, ) => void; export interface NativeReply { id: number; @@ -28,7 +29,11 @@ export default function bridge(service: string) { error: NativeCallback, action: string, args: unknown[] = [], - ) => Bridge.exec(success, error, service, action, args); + onRelease?: () => void, + ) => + onRelease + ? Bridge.exec(success, error, service, action, args, onRelease) + : Bridge.exec(success, error, service, action, args); const call = (action: string, args: unknown[] = []): Promise => new Promise((resolve, reject) => exec(resolve, reject, action, args)); return Object.assign(call, { exec }); @@ -37,12 +42,19 @@ export default function bridge(service: string) { export function createTransport(send: NativeSender) { const callbacks = new Map< number, - { success: NativeCallback; error: NativeCallback } + { success: NativeCallback; error: NativeCallback; onRelease?: () => void } >(); let callbackId = 0; - const exec: NativeExec = (success, error, service, action, args = []) => { + const exec: NativeExec = ( + success, + error, + service, + action, + args = [], + onRelease, + ) => { const id = ++callbackId; - callbacks.set(id, { success, error }); + callbacks.set(id, { success, error, onRelease }); try { const encoded = args.map((value) => Object.prototype.toString.call(value) === "[object ArrayBuffer]" @@ -53,6 +65,7 @@ export function createTransport(send: NativeSender) { throw new Error(`Native service rejected ${service}.${action}`); } catch (exception) { callbacks.delete(id); + onRelease?.(); if (error) error( exception instanceof Error ? exception.message : String(exception), @@ -63,7 +76,10 @@ export function createTransport(send: NativeSender) { const receive = ({ id, keep, status, data }: NativeReply) => { const callback = callbacks.get(id); if (!callback) return; - if (!keep) callbacks.delete(id); + if (!keep) { + callbacks.delete(id); + callback.onRelease?.(); + } if (status === 0) return; const listener = status === 1 ? callback.success : callback.error; const payload = data as { kind?: string; data?: unknown[] } | undefined; diff --git a/src/native/browser.ts b/src/native/browser.ts index 38bb18dbcd..a3a60705a2 100644 --- a/src/native/browser.ts +++ b/src/native/browser.ts @@ -3,13 +3,26 @@ import themes from "theme/list"; import type { NativeCallback } from "./bridge"; const SERVICE = "Browser"; -function open(url: string, isConsole: boolean = false) { +interface BrowserOptions { + ephemeral?: boolean; + onError?: NativeCallback; +} + +export default { open }; + +function open( + url: string, + isConsole: boolean = false, + options: BrowserOptions = {}, +) { const ACTION = "open"; const success = () => {}; - const error = () => {}; + const error = options.onError ?? console.error; const theme = themes.get(settings.value.appTheme).toJSON("hex"); - Bridge.exec(success, error, SERVICE, ACTION, [url, theme, isConsole]); + Bridge.exec(success, error, SERVICE, ACTION, [ + url, + theme, + isConsole, + options.ephemeral === true, + ]); } -export default { - open, -}; diff --git a/src/native/iap.ts b/src/native/iap.ts index ddfd5f3eea..87a69337b2 100644 --- a/src/native/iap.ts +++ b/src/native/iap.ts @@ -4,6 +4,13 @@ import bridge from "./bridge"; const { exec } = bridge("Iap"); let available = true; +let listening = false; +let purchaseListener: NativeCallback; +let purchaseError: NativeCallback; +const purchaseObservers = new Set<(purchases: Object[]) => void>(); +let purchaseErrorOwner: + | { productId: string; handler: NativeCallback } + | undefined; const api = { getProducts( productIds: string[], @@ -16,7 +23,14 @@ const api = { onSuccess: (purchase: Object) => void, onFail: NativeCallback, ) { - exec(onSuccess, onFail, "setPurchaseUpdatedListener", []); + purchaseListener = onSuccess; + purchaseError = onFail; + listen(); + }, + addPurchaseUpdatedListener(onSuccess: (purchases: Object[]) => void) { + purchaseObservers.add(onSuccess); + listen(); + return () => purchaseObservers.delete(onSuccess); }, startConnection( onSuccess: (responseCode: number) => void, @@ -25,6 +39,7 @@ const api = { exec( (responseCode: number) => { available = true; + if (purchaseObservers.size || purchaseListener) listen(); onSuccess?.(responseCode); }, function (error: number) { @@ -42,12 +57,31 @@ const api = { ) { exec(onSuccess, onFail, "consume", [purchaseToken]); }, + /** Launch a purchase; onUpdateError owns store outcomes instead of the legacy listener. */ purchase( productId: string, onSuccess: (responseCode: number) => void, onFail: NativeCallback, + onUpdateError?: NativeCallback, ) { - exec(onSuccess, onFail, "purchase", [productId]); + if (purchaseErrorOwner) { + onFail?.(api.DEVELOPER_ERROR); + return; + } + // Only the flow that launches this purchase owns its asynchronous errors. + const owner = onUpdateError + ? { productId, handler: onUpdateError } + : undefined; + purchaseErrorOwner = owner; + const fail = (error: unknown) => { + if (purchaseErrorOwner === owner) purchaseErrorOwner = undefined; + onFail?.(error); + }; + try { + exec(onSuccess, fail, "purchase", [productId]); + } catch (error) { + fail(error); + } }, getPurchases( onSuccess: (purchaseList: Object[]) => void, @@ -90,3 +124,47 @@ const api = { }; export default api; + +function listen() { + if (listening) return; + listening = true; + try { + exec( + (purchases: { productIds?: string[] }[]) => { + if ( + purchaseErrorOwner && + purchases.some((purchase) => + purchase.productIds?.includes(purchaseErrorOwner!.productId), + ) + ) + purchaseErrorOwner = undefined; + for (const observer of purchaseObservers) { + try { + observer(purchases); + } catch (error) { + console.error("Purchase observer failed", error); + } + } + purchaseListener?.(purchases); + }, + (error: unknown) => { + if (!listening) { + console.warn("Purchase listener unavailable", error); + return; + } + const handler = purchaseErrorOwner?.handler ?? purchaseError; + purchaseErrorOwner = undefined; + if (handler) handler(error); + else console.warn("Unclaimed purchase error", error); + }, + "setPurchaseUpdatedListener", + [], + () => { + listening = false; + }, + ); + } catch (error) { + listening = false; + console.warn("Purchase listener unavailable", error); + } +} diff --git a/src/native/types/iap.d.ts b/src/native/types/iap.d.ts index c873c18ce1..d3de4a894a 100644 --- a/src/native/types/iap.d.ts +++ b/src/native/types/iap.d.ts @@ -1,4 +1,7 @@ interface Iap { + addPurchaseUpdatedListener( + onSuccess: (purchases: Array) => void, + ): () => boolean; getProducts( skuList: Array, onSuccess: (skuList: Array) => void, @@ -21,6 +24,7 @@ interface Iap { skuId: string, onSuccess: (responseCode: number) => void, onError: (err: string) => void, + onUpdateError?: (error: unknown) => void, ): void; getPurchases( onSuccess: (purchaseList: Array) => void, diff --git a/src/pages/sponsor/details.js b/src/pages/sponsor/details.js new file mode 100644 index 0000000000..e6df1bacc3 --- /dev/null +++ b/src/pages/sponsor/details.js @@ -0,0 +1,157 @@ +import multiPrompt from "dialogs/multiPrompt"; +import platform from "lib/platform"; +import helpers from "utils/helpers"; + +export default async function sponsorDetails( + productId, + title = productId, + recovering = false, +) { + let image; + let result; + let pendingImage; + const pickerController = new AbortController(); + const extraFields = []; + + if (["silver", "gold", "platinum", "titanium"].includes(productId)) { + extraFields.push({ + placeholder: "Website", + required: false, + id: "website", + type: "url", + }); + } + + if (productId === "titanium") { + extraFields.push({ + placeholder: "Tagline", + required: false, + id: "tagline", + type: "text", + }); + } + + if (["gold", "platinum", "titanium"].includes(productId)) { + extraFields.push({ + placeholder: "Logo/Image (500KB max)", + required: false, + type: "text", + id: "image", + readOnly: true, + onclick() { + if (!pendingImage) { + pendingImage = selectImage(this).finally(() => { + pendingImage = null; + }); + } + }, + }); + } + + // multiPrompt rejects when the dialog is cancelled. + result = await multiPrompt( + title === productId + ? productId[0].toUpperCase() + productId.slice(1) + : title, + [ + { + placeholder: "Name *", + required: true, + id: "name", + }, + { + placeholder: "Email", + required: false, + id: "email", + type: "email", + match: + /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|.(".+?"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, + }, + ...extraFields, + { + placeholder: "Show in sponsors list", + required: false, + id: "public", + type: "checkbox", + value: true, + }, + ], + recovering + ? "Your purchase is already paid. Add your sponsor details to finish registration; you will not be charged again." + : undefined, + ).catch(() => null); + + // Some WebViews never emit cancel. Closing the form ends any unselected picker, + // but a selected file must still finish reading before we save the profile. + pickerController.abort(); + if (!result) { + return; + } + + await pendingImage; + if (image) { + result.image = image; + } + + localStorage.setItem(`sponsor_${productId}`, JSON.stringify(result)); + return result; + + async function selectImage(field) { + try { + const file = await pickImage(pickerController.signal); + if (!file) return; + if (file.size > 500000) { + field.setError("File size exceeds 500KB"); + return; + } + const dataUrl = await new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => resolve(reader.result); + reader.onerror = () => reject(reader.error); + reader.onabort = () => reject(new Error("Image read cancelled")); + reader.readAsDataURL(file); + }); + image = dataUrl; + field.value = file.name; + field.setError(""); + } catch (error) { + helpers.error(error); + } + } +} + +function pickImage(signal) { + return new Promise((resolve, reject) => { + if (signal.aborted) return resolve(null); + const input = document.createElement("input"); + input.type = "file"; + input.accept = "image/*"; + input.style.cssText = + "position:fixed;left:-10000px;width:1px;height:1px;opacity:0;pointer-events:none"; + // Android's chooser adds the camera only with capture; iOS offers all sources without it. + if (!platform.isIOS) input.setAttribute("capture", "environment"); + const cancel = () => finish(null); + input.onchange = () => finish(input.files?.[0] || null); + input.oncancel = cancel; + signal.addEventListener("abort", cancel, { once: true }); + document.body.append(input); + try { + input.click(); + } catch (error) { + cleanup(); + reject(error); + } + + function finish(file) { + cleanup(); + resolve(file); + } + + function cleanup() { + signal.removeEventListener("abort", cancel); + input.onchange = null; + input.oncancel = null; + input.remove(); + } + }); +} diff --git a/src/pages/sponsor/pending.js b/src/pages/sponsor/pending.js new file mode 100644 index 0000000000..cc5f4f2a5c --- /dev/null +++ b/src/pages/sponsor/pending.js @@ -0,0 +1,77 @@ +import config from "lib/config"; +import helpers from "utils/helpers"; + +export default { list, remember, save, remove, identity }; + +function storageKey() { + return `sponsor_pending_${BuildInfo.packageName}`; +} + +function identity(purchase) { + return purchase.store === "appstore" && purchase.transactionId + ? `appstore:${purchase.environment}:${purchase.transactionId}` + : purchase.purchaseToken; +} + +function list() { + const records = helpers.parseJSON(localStorage.getItem(storageKey())); + // Only supported tiers can be registered; the next journal write prunes others. + return Array.isArray(records) + ? records.filter((record) => isSponsorPurchase(record?.purchase)) + : []; +} + +function isSponsorPurchase(purchase) { + return ( + config.SKU_LIST.includes(purchase?.productIds?.[0]) && + purchase.purchaseState === iap.PURCHASE_STATE_PURCHASED && + typeof purchase.purchaseToken === "string" && + Boolean(purchase.purchaseToken) + ); +} + +function remember(purchases, completed) { + const records = list(); + for (const purchase of purchases || []) { + if (!isSponsorPurchase(purchase) || completed.has(identity(purchase))) + continue; + const existing = records.find( + (record) => identity(record.purchase) === identity(purchase), + ); + if (existing) { + existing.purchase = purchase; + } else { + const [productId] = purchase.productIds; + records.push({ + purchase, + details: helpers.parseJSON( + localStorage.getItem(`sponsor_${productId}`), + ), + registered: false, + }); + } + } + write(records); +} + +function save(record) { + const records = list(); + const index = records.findIndex( + (item) => identity(item.purchase) === identity(record.purchase), + ); + if (index < 0) records.push(record); + else records[index] = record; + write(records); +} + +function remove(purchase) { + write( + list().filter((record) => identity(record.purchase) !== identity(purchase)), + ); +} + +function write(records) { + if (records.length) + localStorage.setItem(storageKey(), JSON.stringify(records)); + else localStorage.removeItem(storageKey()); +} diff --git a/src/pages/sponsor/purchases.js b/src/pages/sponsor/purchases.js new file mode 100644 index 0000000000..7dd47ecdf1 --- /dev/null +++ b/src/pages/sponsor/purchases.js @@ -0,0 +1,151 @@ +import config from "lib/config"; +import sponsorDetails from "./details"; +import pending from "./pending"; + +export default function sponsorPurchases(onSuccess, onError, onSettled) { + const completed = new Set(); + const deferred = new Set(); + let active = null; + let rerun = false; + return receive; + + async function receive(purchases = [], retryCancelled = true) { + try { + // Persist the whole batch before any network call or recovery prompt. + pending.remember(purchases, completed); + if (retryCancelled) deferred.clear(); + if (active) { + rerun = true; + return await active; + } + active = Promise.resolve().then(process); + await active; + } catch (error) { + onError(error); + } finally { + onSettled(); + } + } + + async function process() { + const attempted = new Set(); + try { + do { + rerun = false; + for (const record of pending.list()) { + const { purchase } = record; + const id = pending.identity(purchase); + if (completed.has(id) || deferred.has(id) || attempted.has(id)) + continue; + attempted.add(id); + try { + if (record.registered !== config.API_BASE) { + if ( + typeof record.details?.name !== "string" || + !record.details.name.trim() + ) { + const [productId] = purchase.productIds; + record.details = await sponsorDetails( + productId, + productId, + true, + ); + if (!record.details) { + deferred.add(id); + continue; + } + } + pending.save(record); + await register(record); + record.registered = config.API_BASE; + pending.save(record); + } + // The durable server receipt precedes finishing on either store. + await finish(purchase); + pending.remove(purchase); + completed.add(id); + clearDraft(record); + onSuccess(); + } catch (error) { + if (error.status === 400) { + clearDraft(record); + record.details = null; + pending.save(record); + } + onError(error); + } + } + } while (rerun); + } finally { + active = null; + } + } +} + +function clearDraft({ purchase, details }) { + const key = `sponsor_${purchase.productIds[0]}`; + if (localStorage.getItem(key) === JSON.stringify(details)) + localStorage.removeItem(key); +} + +async function register({ purchase, details }) { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), 15000); + try { + const response = await fetch(`${config.API_BASE}/sponsor`, { + method: "POST", + signal: controller.signal, + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + ...details, + tier: purchase.productIds[0], + packageName: BuildInfo.packageName, + purchaseToken: purchase.purchaseToken, + }), + }); + // Only the sponsor endpoint's JSON acknowledgement can authorize finishing. + if (response.redirected) + throw new Error("Sponsorship registration was redirected. Please retry."); + const result = await response.json().catch(() => null); + if (!result || typeof result !== "object" || Array.isArray(result)) + throw new Error( + "Invalid sponsorship response. Your purchase is saved for retry.", + ); + if (!response.ok || result.error) { + const message = String( + result.error || "Unable to register sponsorship", + ).trim(); + throw Object.assign( + new Error( + response.status === 400 + ? `${message.replace(/[.!?]+$/, "")}. Reopen Sponsorship to correct your details. Your purchase is saved.` + : message, + ), + { status: response.status }, + ); + } + } finally { + clearTimeout(timer); + } +} + +function finish(purchase) { + return new Promise((resolve, reject) => { + const timer = setTimeout( + () => reject(new Error("Finishing purchase timed out")), + 5000, + ); + const settle = (code) => { + clearTimeout(timer); + // A restart can happen after consume succeeds but before local cleanup. + if (code === iap.OK || code === iap.ITEM_NOT_OWNED) resolve(); + else reject(new Error(`Unable to finish purchase: ${code}`)); + }; + try { + iap.consume(purchase.purchaseToken, settle, settle); + } catch (error) { + clearTimeout(timer); + reject(error); + } + }); +} diff --git a/src/pages/sponsor/recovery.js b/src/pages/sponsor/recovery.js new file mode 100644 index 0000000000..824bc704c7 --- /dev/null +++ b/src/pages/sponsor/recovery.js @@ -0,0 +1,130 @@ +import dialog from "dialogs/dialog"; +import helpers from "utils/helpers"; +import pending from "./pending"; +import sponsorPurchases from "./purchases"; + +const listeners = new Set(); +let started = false; +let observing = false; +let receiver; +let checking; +let checkingProducts; +let retryRequested = false; + +export default function startSponsorRecovery(retryCancelled = false) { + if (typeof iap === "undefined") return Promise.resolve(null); + if (!started) { + started = true; + document.addEventListener("resume", retry); + window.addEventListener("online", retry); + } + return recoverSponsorPurchases(retryCancelled); +} + +export function subscribeSponsorPurchases(listener) { + listeners.add(listener); + return () => listeners.delete(listener); +} + +export function recoverSponsorPurchases(retryCancelled = false) { + if (typeof iap === "undefined") return Promise.resolve(null); + if (!observing) { + try { + iap.addPurchaseUpdatedListener(receivePurchases); + observing = true; + } catch (error) { + console.warn("Unable to observe sponsor purchases", error); + } + } + retryRequested ||= retryCancelled; + if (checking) return checking; + checkingProducts = new Set(); + checking = check(checkingProducts).finally(() => { + checking = null; + checkingProducts = null; + }); + return checking; +} + +async function check(products) { + let purchases = []; + let queried = false; + try { + purchases = await queryPurchases(); + queried = true; + } catch (error) { + console.warn("Unable to query sponsor purchases", error); + } + rememberProducts(products, [ + ...pending.list().map(({ purchase }) => purchase), + ...purchases, + ]); + do { + const retryCancelled = retryRequested; + retryRequested = false; + await getReceiver()(purchases, retryCancelled); + purchases = []; + } while (retryRequested); + // Do not start another charge when the store could not check ownership. + return queried ? products : null; +} + +function queryPurchases() { + return new Promise((resolve, reject) => { + const timer = setTimeout( + () => reject(new Error("Purchase query timed out")), + 5000, + ); + const fail = (error) => { + clearTimeout(timer); + reject(error); + }; + const query = () => + iap.getPurchases((purchases) => { + clearTimeout(timer); + resolve(purchases || []); + }, fail); + try { + // Restrictions on new payments must not block existing StoreKit receipts. + iap.startConnection(query, query); + } catch (error) { + fail(error); + } + }); +} + +function retry() { + void recoverSponsorPurchases().catch(console.error); +} + +function receivePurchases(purchases) { + // Keep delivered tiers even when processing finishes and removes their journal. + if (checkingProducts) rememberProducts(checkingProducts, purchases); + return getReceiver()(purchases, false); +} + +function rememberProducts(products, purchases) { + for (const purchase of purchases || []) { + for (const id of purchase.productIds || []) products.add(id); + } +} + +function getReceiver() { + if (!receiver) + receiver = sponsorPurchases( + () => { + dialog(strings.info, "

Thank you for supporting Acode!

"); + emit("success"); + }, + (error) => { + helpers.error(error); + emit("error"); + }, + () => emit("settled"), + ); + return receiver; +} + +function emit(event) { + for (const listener of listeners) listener(event); +} diff --git a/src/pages/sponsor/sponsor.js b/src/pages/sponsor/sponsor.js index 0c7f178041..94b4059fea 100644 --- a/src/pages/sponsor/sponsor.js +++ b/src/pages/sponsor/sponsor.js @@ -1,29 +1,34 @@ import "./style.scss"; -import fsOperation from "fileSystem"; import Logo from "components/logo"; import Page from "components/page"; -import alert from "dialogs/alert"; -import dialog from "dialogs/dialog"; import loader from "dialogs/loader"; -import multiPrompt from "dialogs/multiPrompt"; import actionStack from "lib/actionStack"; import config from "lib/config"; -import platform from "lib/platform"; import helpers from "utils/helpers"; - -//TODO: fix (-1 means, user is not logged in to any google account) +import sponsorDetails from "./details"; +import startSponsorRecovery, { + recoverSponsorPurchases, + subscribeSponsorPurchases, +} from "./recovery"; /** * Sponsor page * @param {() => void} onclose */ export default function Sponsor(onclose) { - if (!platform.sponsorPurchases) { - alert(strings.info, strings["product not available"]); + if (!helpers.isIapAvailable()) { + helpers.error(strings["product not available"]); return; } const $page = Page(strings.sponsor); let cancel = false; + let selecting = false; + let ownsLoader = false; + const unsubscribe = subscribeSponsorPurchases((event) => { + if (cancel) return; + hideLoader(); + if (event === "success") $page.hide(); + }); actionStack.push({ id: "sponsor_page", @@ -31,107 +36,25 @@ export default function Sponsor(onclose) { }); $page.onhide = function () { - onclose?.(); + unsubscribe(); + hideLoader(); cancel = true; + onclose?.(); actionStack.remove("sponsor_page"); }; app.append($page); - iap.setPurchaseUpdatedListener( - (purchases) => { - if (Array.isArray(purchases)) { - (async function () { - const promises = []; - for (let purchase of purchases) { - promises.push( - new Promise((resolve, reject) => { - iap.consume( - purchase.purchaseToken, - (resCode) => { - purchase.consumed = resCode === iap.OK ? true : false; - purchase.consumeCode = resCode; - resolve(purchase); - }, - (err) => { - reject(err); - }, - ); - }), - ); - } - - const settledPromises = await Promise.allSettled(promises); - const rejectedPromise = settledPromises.find( - (promise) => promise.status === "rejected", - ); - let msg = ""; - if (rejectedPromise) { - msg = "Something went wrong.\n"; - msg += `Error: ${rejectedPromise.reason}\n`; - msg += `Code: ${rejectedPromise.value.resCode}`; - } else { - const res = await fetch(`${config.BASE_URL}/res/6.jpeg`); - - if (res.ok) { - const url = URL.createObjectURL(await res.blob()); - msg = ``; - } + showLoader(); + void startSponsorRecovery(true).catch(onPurchaseError); - msg += "

Thank you for supporting Acode!

"; - } - - const order = settledPromises[0].value; - const [productId] = order.productIds; - const sponsorDetails = JSON.parse( - localStorage.getItem(`sponsor_${productId}`), - ); - - try { - const res = await fetch(`${config.API_BASE}/sponsor`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify({ - ...sponsorDetails, - tier: productId, - packageName: BuildInfo.packageName, - purchaseToken: order.purchaseToken, - }), - }); - if (res.error) { - helpers.error(res.error); - } else { - dialog(strings.info, msg); - localStorage.removeItem(`sponsor_${productId}`); - $page.hide(); - } - } catch (error) { - helpers.error(error); - } finally { - loader.removeTitleLoader(); - } - })(); - } - }, - (err) => { - if (err !== iap.USER_CANCELED) { - alert(strings.error, err); - } - loader.removeTitleLoader(); - }, - ); - - loader.showTitleLoader(); render() .catch((error) => { + if (cancel) return; actionStack.pop(); helpers.error(error); }) - .finally(() => { - loader.removeTitleLoader(); - }); + .finally(hideLoader); async function render() { let products = await new Promise((resolve, reject) => { @@ -147,11 +70,12 @@ export default function Sponsor(onclose) { }); if (cancel) return; + if (!products.length) throw new Error(strings["product not available"]); products = products.sort((a, b) => { const aPrice = Number.parseFloat(a.price.replace(/[^0-9.]/g, "")); const bPrice = Number.parseFloat(b.price.replace(/[^0-9.]/g, "")); - return bPrice - aPrice; + return (b.priceAmountMicros ?? bPrice) - (a.priceAmountMicros ?? aPrice); }); $page.body = ( @@ -169,7 +93,7 @@ export default function Sponsor(onclose) { {onlyTitle(product.title)} -
{product.price}/Month
+
{product.price} / 30 days
); } -} - -async function handlePurchase(productId, title) { - let image; - let result; - const extraFields = []; - if (["silver", "gold", "platinum", "titanium"].includes(productId)) { - extraFields.push({ - placeholder: "Website", - required: false, - id: "website", - type: "url", - }); - } - - if (productId === "titanium") { - extraFields.push({ - placeholder: "Tagline", - required: false, - id: "tagline", - type: "text", - }); + async function handlePurchase(productId, title) { + if (cancel || selecting) return; + selecting = true; + try { + showLoader(); + const recovered = await recoverSponsorPurchases(true); + if (cancel) return; + hideLoader(); + if (!recovered) + throw new Error( + "Unable to check existing purchases. Please try again.", + ); + if (recovered.has(productId)) + throw new Error( + "An earlier purchase for this tier was found. No new charge was started.", + ); + const details = await sponsorDetails(productId, onlyTitle(title)); + if (cancel || !details) return; + showLoader(); + iap.purchase(productId, undefined, onPurchaseError, onPurchaseError); + } catch (error) { + onPurchaseError(error); + } finally { + selecting = false; + } } - if (["gold", "platinum", "titanium"].includes(productId)) { - extraFields.push({ - placeholder: "Logo/Image (500KB max)", - required: false, - type: "text", - id: "image", - onclick() { - sdcard.openDocumentFile(async (res) => { - if (res.length > 500000) { - this.setError("File size exceeds 500KB"); - return; - } - - this.setError(""); - this.value = res.filename; - const arraybuffer = await fsOperation(res.uri).readFile(); - const blob = new Blob([arraybuffer], { type: res.type }); - const reader = new FileReader(); - reader.onload = () => { - image = reader.result; - - if (result && typeof result === "object") { - result.image = image; - localStorage.setItem( - `sponsor_${productId}`, - JSON.stringify(result), - ); - } - }; - reader.readAsDataURL(blob); - }, "image/*"); - }, - }); + function onPurchaseError(error) { + if (cancel) return; + if (error !== iap.USER_CANCELED) helpers.error(error); + hideLoader(); } - // multiPrompt rejects when the dialog is cancelled. - result = await multiPrompt(onlyTitle(title), [ - { - placeholder: "Name", - required: true, - id: "name", - }, - { - placeholder: "Email", - required: false, - id: "email", - type: "email", - match: - /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|.(".+?"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, - }, - ...extraFields, - { - placeholder: "Show in sponsors list", - required: false, - id: "public", - type: "checkbox", - value: true, - }, - ]).catch(() => null); - - if (!result) { - return; + function showLoader() { + if (cancel) return; + ownsLoader = true; + loader.showTitleLoader(); } - if (image) { - result.image = image; + function hideLoader() { + if (cancel || !ownsLoader) return; + ownsLoader = false; + loader.removeTitleLoader(); } - - localStorage.setItem(`sponsor_${productId}`, JSON.stringify(result)); - loader.showTitleLoader(); - iap.purchase(productId); } function onlyTitle(title) { diff --git a/src/pages/sponsors/sponsors.js b/src/pages/sponsors/sponsors.js index 3ac79dffea..2851b69ec5 100644 --- a/src/pages/sponsors/sponsors.js +++ b/src/pages/sponsors/sponsors.js @@ -4,7 +4,6 @@ import toast from "components/toast"; import Ref from "html-tag-js/ref"; import actionStack from "lib/actionStack"; import config from "lib/config"; -import platform from "lib/platform"; import Sponsor from "pages/sponsor"; import helpers from "utils/helpers"; @@ -30,7 +29,7 @@ export default function Sponsors() { page.body = (
- {platform.sponsorPurchases ? ( + {helpers.isIapAvailable() && (

Join our community of supporters and help shape the future of mobile @@ -40,7 +39,7 @@ export default function Sponsors() { Become a Sponsor

- ) : null} + )}

Acode's Sponsors

diff --git a/src/platforms/ios/api.ts b/src/platforms/ios/api.ts index 868bd749e5..6daff3ded6 100644 --- a/src/platforms/ios/api.ts +++ b/src/platforms/ios/api.ts @@ -53,7 +53,11 @@ function localURL(value: string) { try { const url = new URL(value, location.href); if ( - !["https://acode.app", "https://dev.acode.app"].includes(url.origin) || + ![ + "https://acode.app", + "https://dev.acode.app", + "https://academy.acode.app", + ].includes(url.origin) || url.username || url.password || !(url.pathname === "/api" || url.pathname.startsWith("/api/")) diff --git a/src/platforms/ios/index.ts b/src/platforms/ios/index.ts index 360440ad1d..85f1059430 100644 --- a/src/platforms/ios/index.ts +++ b/src/platforms/ios/index.ts @@ -41,10 +41,17 @@ export default function setup() { }); }, }; - const exec: NativeExec = (success, error, service, action, args = []) => { + const exec: NativeExec = ( + success, + error, + service, + action, + args = [], + onRelease, + ) => { const handler = proxy[service]?.[action]; if (handler) handler(success, error, args); - else transport.exec(success, error, service, action, args); + else transport.exec(success, error, service, action, args, onRelease); }; installFullscreen( (active) => diff --git a/src/theme/preInstalled.js b/src/theme/preInstalled.js index 76120a1b16..122511a846 100644 --- a/src/theme/preInstalled.js +++ b/src/theme/preInstalled.js @@ -231,6 +231,7 @@ light.preferredEditorTheme = getSystemEditorTheme(false); light.preferredTerminalTheme = "light"; const system = createBuiltInTheme("System", "dark", "free"); +system.autoDarkened = true; export function getSystemEditorTheme(darkTheme) { if (darkTheme) { @@ -250,7 +251,6 @@ export function updateSystemTheme(darkTheme, applyTheme = true) { system.type = "dark"; system.primaryColor = "rgb(35, 39, 42)"; system.primaryTextColor = "rgb(245, 245, 245)"; - system.darkenedPrimaryColor = "rgb(24, 27, 30)"; system.secondaryColor = "rgb(45, 49, 52)"; system.secondaryTextColor = "rgb(228, 228, 228)"; system.activeColor = "rgb(66, 133, 244)"; diff --git a/tests/helpers/sponsorPage.js b/tests/helpers/sponsorPage.js new file mode 100644 index 0000000000..ef0e36beb6 --- /dev/null +++ b/tests/helpers/sponsorPage.js @@ -0,0 +1,117 @@ +import { createRequire } from "node:module"; +import tag from "html-tag-js"; +import Ref from "html-tag-js/ref"; +import { vi } from "vitest"; +import { loadSourceModule } from "./loadSourceModule"; + +createRequire(import.meta.url)("html-tag-js/polyfill"); + +export default function setup(available = true, isIOS = true) { + const loader = { + showTitleLoader: vi.fn(() => document.body.classList.add("loading")), + removeTitleLoader: vi.fn(() => document.body.classList.remove("loading")), + }; + const helpers = { + isIapAvailable: () => available, + error: vi.fn(), + parseJSON: JSON.parse, + }; + const prompt = vi.fn(async () => ({ name: "Sponsor" })); + const recover = vi.fn(async () => new Set()); + const iap = { + USER_CANCELED: 1, + addPurchaseUpdatedListener: vi.fn(() => vi.fn()), + setPurchaseUpdatedListener: vi.fn(), + getPurchases: vi.fn((success) => success([])), + getProducts: vi.fn((ids, success) => + success([ + { + productId: "gold", + title: "Gold", + price: "$10", + description: "Sponsor", + }, + ]), + ), + purchase: vi.fn(), + }; + const globals = { + tag, + app: document.body, + localStorage, + document, + Blob, + FileReader, + AbortController, + strings: { + sponsor: "Sponsor", + "product not available": "product not available", + }, + fetch: vi.fn(async () => ({ ok: true, json: async () => [] })), + ...(available ? { iap } : {}), + }; + const shared = { + "./style.scss": {}, + "components/page": () => { + const page = document.createElement("section"); + Object.defineProperty(page, "body", { + set: (body) => page.replaceChildren(body), + }); + page.hide = () => { + page.onhide?.(); + page.remove(); + }; + return page; + }, + "lib/actionStack": { push: vi.fn(), remove: vi.fn(), pop: vi.fn() }, + "lib/config": { SKU_LIST: ["gold"], API_BASE: "https://example.test/api" }, + "utils/helpers": helpers, + }; + const details = loadSourceModule( + "src/pages/sponsor/details.js", + { + "lib/platform": { isIOS }, + "dialogs/multiPrompt": prompt, + "utils/helpers": helpers, + }, + globals, + ).default; + const Sponsor = loadSourceModule( + "src/pages/sponsor/sponsor.js", + { + ...shared, + "components/logo": () => document.createElement("span"), + "dialogs/loader": loader, + "./details": details, + "./recovery": { + __esModule: true, + default: async () => { + await new Promise((resolve) => iap.getPurchases(resolve)); + }, + recoverSponsorPurchases: recover, + subscribeSponsorPurchases: () => vi.fn(), + }, + }, + globals, + ).default; + const Sponsors = loadSourceModule( + "src/pages/sponsors/sponsors.js", + { + ...shared, + "components/toast": vi.fn(), + "html-tag-js/ref": Ref, + "pages/sponsor": Sponsor, + }, + globals, + ).default; + return { + Sponsor, + Sponsors, + helpers, + loader, + prompt, + iap, + details, + recover, + }; +} diff --git a/tests/helpers/sponsorPurchases.js b/tests/helpers/sponsorPurchases.js new file mode 100644 index 0000000000..687e859f4a --- /dev/null +++ b/tests/helpers/sponsorPurchases.js @@ -0,0 +1,78 @@ +import { vi } from "vitest"; +import { loadSourceModule } from "./loadSourceModule"; + +export default function setupSponsorPurchases(packageName = "app.acode") { + localStorage.clear(); + localStorage.setItem( + "sponsor_crystal", + JSON.stringify({ name: "Sponsor", public: true }), + ); + const iap = { + OK: 0, + PURCHASE_STATE_PURCHASED: 1, + ITEM_NOT_OWNED: 8, + consume: vi.fn((token, resolve) => resolve(0)), + }; + const fetch = vi.fn(async () => ({ ok: true, json: async () => ({}) })); + const success = vi.fn(); + const error = vi.fn(); + const settled = vi.fn(); + const recoverDetails = vi.fn(async (productId) => { + const details = { name: "Recovered Sponsor", public: false }; + localStorage.setItem(`sponsor_${productId}`, JSON.stringify(details)); + return details; + }); + const config = { + SKU_LIST: ["crystal", "gold"], + API_BASE: "https://example.test/api", + }; + const helpers = { + parseJSON(value) { + try { + return JSON.parse(value); + } catch { + return null; + } + }, + }; + const globals = { + iap, + fetch, + localStorage, + AbortController, + setTimeout, + clearTimeout, + BuildInfo: { packageName }, + }; + const pending = loadSourceModule( + "src/pages/sponsor/pending.js", + { + "lib/config": config, + "utils/helpers": helpers, + }, + globals, + ).default; + const createProcessor = (onSuccess, onError, onSettled) => + loadSourceModule( + "src/pages/sponsor/purchases.js", + { + "lib/config": config, + "./details": recoverDetails, + "./pending": pending, + }, + globals, + ).default(onSuccess, onError, onSettled); + const createReceiver = () => createProcessor(success, error, settled); + return { + receive: createReceiver(), + createReceiver, + createProcessor, + pending, + iap, + fetch, + success, + error, + settled, + recoverDetails, + }; +} diff --git a/tests/unit/alpineNative.test.js b/tests/unit/alpineNative.test.js new file mode 100644 index 0000000000..79c8c3df07 --- /dev/null +++ b/tests/unit/alpineNative.test.js @@ -0,0 +1,111 @@ +import { spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, test } from "vitest"; + +const kernel = "platforms/ios/Alpine/Vendor/ios-linuxkit"; +const hasClang = spawnSync("clang", ["--version"]).status === 0; +const nativeTest = test.skipIf(!hasClang && !process.env.CI); +const sanitizers = hasClang ? sanitizerFlags() : []; + +nativeTest( + "Alpine encodes Linux interface dumps and rejects unsupported requests", + () => { + const result = runNative( + [ + "platforms/ios/Alpine/Tests/netlink-route.c", + `${kernel}/fs/netlink_route.c`, + ], + [], + ); + expect(result.stdout.trim()).toBe("NETLINK_ROUTE_PASS"); + }, +); + +nativeTest("Alpine only passes V8 flags the installed Node accepts", () => { + const result = runNative( + [ + "platforms/ios/Alpine/Tests/node-flags.c", + `${kernel}/kernel/node_flags.c`, + `${kernel}/kernel/node_binary.c`, + ], + [process.execPath, process.versions.v8], + ); + const [status, ...args] = result.stdout.trim().split("\n"); + expect(status).toBe("NODE_FLAGS_PASS"); + if (Number.parseInt(process.versions.v8, 10) >= 11) { + expect(args).toContain("--no-maglev"); + } + const node = spawnSync( + process.execPath, + [...args, "-e", "process.stdout.write(typeof WebAssembly)"], + { encoding: "utf8", timeout: 10000 }, + ); + expect(node.stderr).toBe(""); + expect(node.stdout).toBe("object"); +}); + +nativeTest("Alpine guards Node scans and caches only successful reads", () => { + const result = runNative( + [ + "platforms/ios/Alpine/Tests/node-runtime.c", + `${kernel}/kernel/node.c`, + `${kernel}/kernel/node_flags.c`, + `${kernel}/kernel/node_binary.c`, + ], + [], + ); + expect(result.stdout.trim()).toBe("NODE_RUNTIME_PASS"); +}); + +function runNative(sources, args) { + const directory = mkdtempSync(join(tmpdir(), "acode-alpine-native-")); + try { + const executable = join(directory, "native-test"); + const build = spawnSync( + "clang", + [ + "-Wall", + "-Wextra", + "-Werror", + "-DGUEST_ARM64", + "-D_GNU_SOURCE", + "-pthread", + ...sanitizers, + `-I${kernel}`, + ...sources, + "-o", + executable, + ], + { encoding: "utf8" }, + ); + expect(build.status, build.stderr).toBe(0); + const result = spawnSync(executable, args, { + encoding: "utf8", + timeout: 30000, + }); + expect(result.status, result.stderr).toBe(0); + return result; + } finally { + rmSync(directory, { recursive: true, force: true }); + } +} + +function sanitizerFlags() { + const flags = ["-fsanitize=address,undefined"]; + const directory = mkdtempSync(join(tmpdir(), "acode-sanitizer-")); + try { + const executable = join(directory, "probe"); + const build = spawnSync( + "clang", + [...flags, "-x", "c", "-", "-o", executable], + { input: "int main(void) { return 0; }" }, + ); + if (build.status === 0 && spawnSync(executable).status === 0) return flags; + console.warn("Sanitizer runtime unavailable; native tests run without it."); + return []; + } finally { + rmSync(directory, { recursive: true, force: true }); + } +} diff --git a/tests/unit/alpineSetup.test.js b/tests/unit/alpineSetup.test.js index 24895ede71..65f067176b 100644 --- a/tests/unit/alpineSetup.test.js +++ b/tests/unit/alpineSetup.test.js @@ -1,5 +1,12 @@ import { spawnSync } from "node:child_process"; -import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { expect, test } from "vitest"; @@ -10,7 +17,9 @@ const source = readFileSync( import.meta.url, ), "utf8", -); +) + .replaceAll('"/etc/npmrc"', '"$LEGACY_NPM_CONFIG"') + .replaceAll('"/usr/etc/npmrc"', '"$PREFIX_NPM_CONFIG"'); // Preparation tests stop before unrelated writes to guest-only filesystem paths. const setup = source.slice( 0, @@ -82,6 +91,67 @@ test("command execution bypasses Alpine package setup", () => { expect(result.configured).toBe(false); }); +test("iOS npm defaults also reach existing installations during preparation", () => { + const result = runSetup({ flag: "--prepare", installed: iosPackages }); + expect(result.status).toBe(0); + expect(result.npmConfig).toBe("\nloglevel=info\n\nforeground-scripts=true\n"); + expect(runSetup({ ios: false }).npmConfig).toBe(null); +}); + +test("iOS preserves existing npm choices without duplicating defaults", () => { + const npmConfig = "audit=true\nloglevel=warn\nforeground-scripts=false\n"; + const result = runSetup({ npmConfig }); + expect(result.npmConfig).toBe(npmConfig); +}); + +test("iOS migrates Alpine's global npm settings before adding missing defaults", () => { + const result = runSetup({ + legacyNpmConfig: " audit = true\n# loglevel=warn", + }); + expect(result.npmConfig).toBe( + " audit = true\n# loglevel=warn\nloglevel=info\n\nforeground-scripts=true\n", + ); +}); + +test.each([ + "--prepare", + "--installing", +])("%s continues when optional npm defaults cannot be written", (flag) => { + const result = runSetup({ flag, blockConfig: true, errexit: true }); + expect(result.status).toBe(0); + expect(result.stderr).toContain("Unable to configure optional npm defaults"); + expect(result.calls).toContain("add curl libstdc++ procps-ng tar gzip"); +}); + +test.each([ + "--prepare", + "--installing", +])("%s continues when legacy npm migration fails", (flag) => { + const result = runSetup({ + flag, + copyFails: true, + legacyNpmConfig: "audit=true\n", + errexit: true, + }); + expect(result.status).toBe(0); + expect(result.stderr).toContain("Unable to configure optional npm defaults"); + expect(result.npmConfig).toBeNull(); +}); + +test("migrates prefix-global npm settings once, preferring Alpine's system config", () => { + const prefixNpmConfig = "registry=https://example.test\n"; + expect(runSetup({ prefixNpmConfig }).npmConfig).toContain(prefixNpmConfig); + expect( + runSetup({ prefixNpmConfig, legacyNpmConfig: "audit=true\n" }).npmConfig, + ).not.toContain("registry="); + expect( + runSetup({ + prefixNpmConfig, + npmConfig: "loglevel=warn\nforeground-scripts=false\n", + }).npmConfig, + ).not.toContain("registry="); +}); + function runSetup({ ios = true, installed = "bash command-not-found tzdata wget", @@ -89,15 +159,35 @@ function runSetup({ addMode = "success", updateFails = false, args = flag ? [flag] : [], + npmConfig, + legacyNpmConfig, + prefixNpmConfig, + blockConfig = false, + copyFails = false, + errexit = false, } = {}) { const directory = mkdtempSync(join(tmpdir(), "acode-alpine-setup-")); const log = join(directory, "apk.log"); + const config = join(directory, "npmrc"); + const legacyConfig = join(directory, "legacy-npmrc"); + const prefixConfig = join(directory, "prefix-npmrc"); try { + if (blockConfig) mkdirSync(config); + if (npmConfig !== undefined) writeFileSync(config, npmConfig); + if (prefixNpmConfig !== undefined) + writeFileSync(prefixConfig, prefixNpmConfig); + if (legacyNpmConfig !== undefined) + writeFileSync(legacyConfig, legacyNpmConfig); const result = spawnSync( "/bin/sh", [ "-c", ` +${errexit ? "set -e" : ""} +cp() { + [ "$COPY_FAILS" != true ] || return 1 + command cp "$@" +} apk() { printf '%s\\n' "$*" >> "$APK_LOG" case "$1" in @@ -142,6 +232,9 @@ ${flag === "--installing" ? source : setup} PREFIX: directory, ALPINE_ROOT: ios ? "/" : join(directory, "alpine"), APK_LOG: log, + LEGACY_NPM_CONFIG: legacyConfig, + PREFIX_NPM_CONFIG: prefixConfig, + COPY_FAILS: String(copyFails), INSTALLED_PACKAGES: installed, ADD_MODE: addMode, UPDATE_FAILS: String(updateFails), @@ -154,6 +247,10 @@ ${flag === "--installing" ? source : setup} ...result, configured: existsSync(join(directory, ".configured")), calls: existsSync(log) ? readFileSync(log, "utf8") : "", + npmConfig: + !blockConfig && existsSync(config) + ? readFileSync(config, "utf8") + : null, }; } finally { rmSync(directory, { recursive: true, force: true }); diff --git a/tests/unit/browser.test.ts b/tests/unit/browser.test.ts new file mode 100644 index 0000000000..54f94ca776 --- /dev/null +++ b/tests/unit/browser.test.ts @@ -0,0 +1,32 @@ +import browser from "native/browser"; +import { afterEach, expect, test, vi } from "vitest"; + +vi.mock("lib/settings", () => ({ default: { value: { appTheme: "system" } } })); +vi.mock("theme/list", () => ({ + default: { get: () => ({ toJSON: () => ({ type: "dark" }) }) }, +})); + +afterEach(() => vi.unstubAllGlobals()); + +test.each([ + false, + true, +])("forwards preview isolation and errors to the native bridge (ephemeral: %s)", (ephemeral) => { + const exec = vi.fn(); + const onError = vi.fn(); + vi.stubGlobal("Bridge", { exec }); + if (ephemeral) + browser.open("http://localhost:3000", false, { ephemeral, onError }); + else browser.open("http://localhost:3000"); + expect(exec).toHaveBeenCalledWith( + expect.any(Function), + ephemeral ? onError : console.error, + "Browser", + "open", + ["http://localhost:3000", { type: "dark" }, false, ephemeral], + ); + if (ephemeral) { + exec.mock.calls[0][1]("Unable to present"); + expect(onError).toHaveBeenCalledWith("Unable to present"); + } +}); diff --git a/tests/unit/iap.test.ts b/tests/unit/iap.test.ts index 02ff16915e..3f7f34ebec 100644 --- a/tests/unit/iap.test.ts +++ b/tests/unit/iap.test.ts @@ -1,9 +1,12 @@ -import iap from "native/iap"; +let iap: typeof import("native/iap").default; + import { afterEach, beforeEach, expect, test, vi } from "vitest"; const exec = vi.fn(); -beforeEach(() => { +beforeEach(async () => { + vi.resetModules(); + iap = (await import("native/iap")).default; exec.mockReset(); vi.stubGlobal("Bridge", { platformId: "ios", exec }); }); @@ -41,3 +44,119 @@ test("billing availability is current inside callbacks and recovers after restri iap.startConnection(connected, vi.fn()); expect(connected).toHaveBeenCalledWith(0); }); + +test("purchase observers survive legacy listener replacement without replacing the native listener", () => { + const observer = vi.fn(); + const remove = iap.addPurchaseUpdatedListener(observer); + const first = vi.fn(); + const second = vi.fn(); + const failure = vi.fn(); + iap.setPurchaseUpdatedListener(first, failure); + iap.setPurchaseUpdatedListener(second, failure); + expect(exec).toHaveBeenCalledOnce(); + const [receive, onError] = exec.mock.calls[0]; + const purchases = [{ productIds: ["crystal"], purchaseState: 1 }]; + receive(purchases); + expect(observer).toHaveBeenCalledWith(purchases); + expect(first).not.toHaveBeenCalled(); + expect(second).toHaveBeenCalledWith(purchases); + onError(1); + expect(failure).toHaveBeenCalledWith(1); + remove(); + receive(purchases); + expect(observer).toHaveBeenCalledOnce(); +}); + +test.each([ + false, + true, +])("reconnect retries failed purchase observation (throws: %s)", (throws) => { + const observer = vi.fn(); + const warning = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + exec.mockImplementationOnce( + (success, failure, service, action, args, release) => { + if (throws) throw new Error("Bridge unavailable"); + release(); + failure("Bridge unavailable"); + }, + ); + iap.addPurchaseUpdatedListener(observer); + exec.mockImplementation((success, failure, service, action) => { + if (action === "startConnection") success(0); + }); + iap.startConnection(vi.fn(), vi.fn()); + const registrations = exec.mock.calls.filter( + (call) => call[3] === "setPurchaseUpdatedListener", + ); + expect(registrations).toHaveLength(2); + const purchases = [{ productIds: ["crystal"], purchaseState: 1 }]; + registrations[1][0](purchases); + expect(observer).toHaveBeenCalledOnce(); + expect(observer).toHaveBeenCalledWith(purchases); + } finally { + warning.mockRestore(); + } +}); + +test.each([ + -1, 1, 2, 6, +])("billing outcome %s preserves the subscription and reaches only the purchasing flow", (code) => { + const observer = vi.fn(); + const error = vi.fn(); + const legacyError = vi.fn(); + const remove = iap.addPurchaseUpdatedListener(observer); + iap.setPurchaseUpdatedListener(vi.fn(), legacyError); + const [receive, onError] = exec.mock.calls[0]; + iap.purchase("crystal", vi.fn(), vi.fn(), error); + onError(code); + expect(error).toHaveBeenCalledWith(code); + expect(legacyError).not.toHaveBeenCalled(); + exec.mockImplementation((success, failure, service, action) => { + if (action === "startConnection") success(0); + }); + iap.startConnection(vi.fn(), vi.fn()); + expect( + exec.mock.calls.filter((call) => call[3] === "setPurchaseUpdatedListener"), + ).toHaveLength(1); + receive([]); + expect(observer).toHaveBeenCalledOnce(); + remove(); + iap.purchase("acode_pro_new", vi.fn(), vi.fn()); + onError(code); + expect(error).toHaveBeenCalledOnce(); + expect(legacyError).toHaveBeenCalledOnce(); +}); + +test("registration failure does not become a purchase error and the released subscription retries", () => { + const failure = vi.fn(); + const warning = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + iap.setPurchaseUpdatedListener(vi.fn(), failure); + const [, onError, , , , release] = exec.mock.calls[0]; + release(); + onError(-1); + expect(failure).not.toHaveBeenCalled(); + iap.addPurchaseUpdatedListener(vi.fn()); + expect(exec).toHaveBeenCalledTimes(2); + } finally { + warning.mockRestore(); + } +}); + +test("purchase updates release scoped error ownership while unrelated updates do not", () => { + const scoped = vi.fn(); + const legacy = vi.fn(); + const blocked = vi.fn(); + iap.setPurchaseUpdatedListener(vi.fn(), legacy); + const [receive, onError] = exec.mock.calls[0]; + iap.purchase("gold", vi.fn(), vi.fn(), scoped); + receive([{ productIds: ["unrelated"], purchaseState: 1 }]); + iap.purchase("acode_pro_new", vi.fn(), blocked); + expect(blocked).toHaveBeenCalledWith(iap.DEVELOPER_ERROR); + receive([{ productIds: ["gold"], purchaseState: 2 }]); + iap.purchase("acode_pro_new", vi.fn(), vi.fn()); + onError(1); + expect(scoped).not.toHaveBeenCalled(); + expect(legacy).toHaveBeenCalledWith(1); +}); diff --git a/tests/unit/iosApi.test.ts b/tests/unit/iosApi.test.ts index cf54bc3e4b..ec5dcf46c3 100644 --- a/tests/unit/iosApi.test.ts +++ b/tests/unit/iosApi.test.ts @@ -80,12 +80,18 @@ test("only routes Acode HTTPS API requests through the iOS transport", async () "https://dev.acode.app.evil.test/api/login", "http://dev.acode.app/api/login", "https://dev.acode.app:8443/api/login", + "https://academy.acode.app.evil.test/api/login", + "https://academy.acode.app/cc/1", "acode://localhost/__cdvfile_cache__/file.txt", ]) { await window.fetch(url); expect(transport.mock.calls.at(-1)?.[0]).toBe(url); } - for (const origin of ["https://acode.app", "https://dev.acode.app"]) { + for (const origin of [ + "https://acode.app", + "https://dev.acode.app", + "https://academy.acode.app", + ]) { await window.fetch(`${origin}/api/login?test=one%20two`, { credentials: "include", headers: { "X-Acode-API-Origin": "https://example.com" }, diff --git a/tests/unit/iosMarketplace.test.js b/tests/unit/iosMarketplace.test.js index 1a74b40656..9445a1150e 100644 --- a/tests/unit/iosMarketplace.test.js +++ b/tests/unit/iosMarketplace.test.js @@ -13,7 +13,6 @@ it("hides unfulfillable iOS plugin purchases without offering Google Play billin expect(view.textContent).toContain("product not available"); expect(view.textContent).not.toContain("iap-plugin-purchase-warning"); expect(fixture.platform.pluginPurchases).toBe(false); - expect(fixture.platform.sponsorPurchases).toBe(false); }); it.each([ @@ -60,7 +59,6 @@ it("retains Android purchase and refund actions", async () => { }); ownedView.querySelector(".more-info-small .link").click(); expect(refund).toHaveBeenCalledOnce(); - expect(fixture.platform.sponsorPurchases).toBe(true); }); it.each([ @@ -81,40 +79,6 @@ it.each([ } }); -it("blocks direct iOS sponsorship entry before querying products or registering a purchase listener", () => { - const fixture = setup("ios"); - const page = vi.fn(); - const iap = { - getProducts: vi.fn(), - setPurchaseUpdatedListener: vi.fn(), - purchase: vi.fn(), - }; - const Sponsor = loadSourceModule( - "src/pages/sponsor/sponsor.js", - { - "./style.scss": {}, - fileSystem: {}, - "components/logo": {}, - "components/page": page, - "dialogs/alert": fixture.alert, - "dialogs/dialog": {}, - "dialogs/loader": {}, - "dialogs/multiPrompt": {}, - "lib/actionStack": {}, - "lib/config": {}, - "lib/platform": fixture.platform, - "utils/helpers": {}, - }, - { ...fixture.globals, iap }, - ).default; - Sponsor(); - expect(page).not.toHaveBeenCalled(); - expect(iap.getProducts).not.toHaveBeenCalled(); - expect(iap.setPurchaseUpdatedListener).not.toHaveBeenCalled(); - expect(iap.purchase).not.toHaveBeenCalled(); - expect(fixture.alert).toHaveBeenCalledWith("info", "product not available"); -}); - function setup(platformId) { const platform = loadSourceModule( "src/lib/platform.js", diff --git a/tests/unit/nativeBridge.test.js b/tests/unit/nativeBridge.test.js index 18a9c8f5b0..29fd0899aa 100644 --- a/tests/unit/nativeBridge.test.js +++ b/tests/unit/nativeBridge.test.js @@ -72,6 +72,34 @@ afterEach(() => { }); describe("Acode bridge", () => { + test.each([ + "android", + "ios", + ])("%s reports native callback release independently of a kept billing error", async (platform) => { + const { window, pending } = await createBridge("paid", false, platform); + const events = []; + window.Bridge.exec( + null, + (error) => events.push(error), + "Iap", + "setPurchaseUpdatedListener", + [], + () => events.push("released"), + ); + const { id } = pending.at(-1); + const reply = (keep, status, data) => { + if (platform === "android") + window.Android.callback({ id, keep, status, data }); + else window.iOS.callback({ id, keep, status, error: data }); + }; + reply(true, 9, -1); + expect(events).toEqual([-1]); + reply(false, 9, -1); + expect(events).toEqual([-1, "released", -1]); + reply(false, 9, -1); + expect(events).toEqual([-1, "released", -1]); + }); + test("defers cold and listening intents until startup is visible, then delivers warm intents synchronously", async () => { const { window, pending } = await createBridge(); window.document.body.classList.add("loading"); diff --git a/tests/unit/sponsorPage.test.js b/tests/unit/sponsorPage.test.js new file mode 100644 index 0000000000..713e10b383 --- /dev/null +++ b/tests/unit/sponsorPage.test.js @@ -0,0 +1,238 @@ +// @vitest-environment happy-dom +import { afterEach, expect, it, vi } from "vitest"; +import setup from "../helpers/sponsorPage"; + +afterEach(() => { + document.body.replaceChildren(); + localStorage.clear(); +}); + +it("hides the sponsor CTA and safely rejects direct entry when IAP is absent", () => { + const fixture = setup(false); + fixture.Sponsors(); + expect(document.querySelector(".cta-button")).toBeNull(); + expect(() => fixture.Sponsor()).not.toThrow(); + expect(fixture.helpers.error).toHaveBeenCalledWith("product not available"); + expect(fixture.loader.showTitleLoader).not.toHaveBeenCalled(); +}); + +it("keeps the CTA with IAP and shows the loader before synchronous purchase callbacks", async () => { + const fixture = setup(); + fixture.iap.getPurchases.mockImplementation((success) => { + expect(fixture.loader.showTitleLoader).toHaveBeenCalledOnce(); + success([]); + }); + fixture.Sponsors(); + document.querySelector(".cta-button").click(); + await vi.waitFor(() => + expect(document.querySelector(".purchase-btn")).not.toBeNull(), + ); + expect(fixture.loader.removeTitleLoader).toHaveBeenCalled(); + expect(document.body.classList.contains("loading")).toBe(false); +}); + +it.each([ + true, + false, +])("opens the native image chooser with all sources on iOS=%s", async (isIOS) => { + const fixture = setup(true, isIOS); + const { result, field, finish } = openDetails(fixture); + expect(field.readOnly).toBe(true); + field.onclick(); + const picker = document.querySelector('input[type="file"]'); + expect(picker.accept).toBe("image/*"); + expect(picker.multiple).toBe(false); + expect(picker.hasAttribute("capture")).toBe(!isIOS); + field.onclick(); + expect(document.querySelectorAll('input[type="file"]')).toHaveLength(1); + picker.dispatchEvent(new Event("cancel")); + finish({ name: "Sponsor" }); + expect(await result).toEqual({ name: "Sponsor" }); + expect(picker.isConnected).toBe(false); + expect(fixture.helpers.error).not.toHaveBeenCalled(); +}); + +it("waits for the selected image before saving details and returning them for purchase", async () => { + const fixture = setup(); + const { result, field, finish } = openDetails(fixture); + field.onclick(); + const picker = document.querySelector('input[type="file"]'); + Object.defineProperty(picker, "files", { + value: [new File(["logo"], "logo.png", { type: "image/png" })], + }); + picker.dispatchEvent(new Event("change")); + finish({ name: "Sponsor", image: "" }); + expect(await result).toEqual({ + name: "Sponsor", + image: "data:image/png;base64,bG9nbw==", + }); + expect(JSON.parse(localStorage.getItem("sponsor_gold")).image).toBe( + "data:image/png;base64,bG9nbw==", + ); + expect(field.value).toBe("logo.png"); + expect(picker.isConnected).toBe(false); + expect(field.setError).toHaveBeenLastCalledWith(""); +}); + +it.each([ + false, + true, +])("settles the form without a picker cancel event (form cancelled: %s)", async (cancelled) => { + const fixture = setup(); + const { result, field, finish } = openDetails(fixture); + field.onclick(); + const picker = document.querySelector('input[type="file"]'); + finish(cancelled ? null : { name: "Sponsor" }); + expect(await result).toEqual(cancelled ? undefined : { name: "Sponsor" }); + expect(picker.isConnected).toBe(false); + expect(picker.onchange).toBeNull(); + expect(picker.oncancel).toBeNull(); + expect(localStorage.getItem("sponsor_gold")).toBe( + cancelled ? null : '{"name":"Sponsor"}', + ); + expect(fixture.helpers.error).not.toHaveBeenCalled(); +}); + +it("owns purchase errors without replacing legacy listeners and ignores late errors after close", async () => { + const fixture = setup(); + fixture.Sponsor(); + await vi.waitFor(() => + expect(document.querySelector(".purchase-btn")).not.toBeNull(), + ); + document.querySelector(".purchase-btn").click(); + await vi.waitFor(() => expect(fixture.iap.purchase).toHaveBeenCalledOnce()); + expect(fixture.iap.setPurchaseUpdatedListener).not.toHaveBeenCalled(); + expect(fixture.iap.addPurchaseUpdatedListener).not.toHaveBeenCalled(); + const onError = fixture.iap.purchase.mock.calls[0][3]; + onError(1); + expect(fixture.helpers.error).not.toHaveBeenCalled(); + expect(document.body.classList.contains("loading")).toBe(false); + onError(6); + expect(fixture.helpers.error).toHaveBeenCalledWith(6); + document.querySelector("section").hide(); + fixture.loader.showTitleLoader(); + fixture.loader.removeTitleLoader.mockClear(); + fixture.helpers.error.mockClear(); + onError(6); + fixture.iap.purchase.mock.calls[0][2](6); + expect(fixture.helpers.error).not.toHaveBeenCalled(); + expect(fixture.loader.removeTitleLoader).not.toHaveBeenCalled(); + expect(document.body.classList.contains("loading")).toBe(true); +}); + +it.each([ + "recovery", + "details", + "products", +])("closing the page prevents late %s callbacks from changing UI or charging", async (phase) => { + const fixture = setup(); + let settle; + if (phase === "products") + fixture.iap.getProducts.mockImplementationOnce((ids, success) => { + settle = () => success([]); + }); + else if (phase === "recovery") + fixture.recover.mockImplementationOnce( + () => + new Promise((resolve) => { + settle = () => resolve(new Set()); + }), + ); + else + fixture.prompt.mockImplementationOnce( + () => + new Promise((resolve) => { + settle = () => resolve({ name: "Sponsor" }); + }), + ); + fixture.Sponsor(); + if (phase !== "products") { + await vi.waitFor(() => + expect(document.querySelector(".purchase-btn")).not.toBeNull(), + ); + document.querySelector(".purchase-btn").click(); + await vi.waitFor(() => expect(settle).toEqual(expect.any(Function))); + } + document.querySelector("section").hide(); + fixture.loader.showTitleLoader(); + fixture.loader.removeTitleLoader.mockClear(); + settle(); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(fixture.iap.purchase).not.toHaveBeenCalled(); + expect(fixture.helpers.error).not.toHaveBeenCalled(); + expect(fixture.loader.removeTitleLoader).not.toHaveBeenCalled(); + expect(document.body.classList.contains("loading")).toBe(true); +}); + +it("keeps the 500KB limit and allows reopening the picker after rejecting a large image", async () => { + const fixture = setup(); + const { result, field, finish } = openDetails(fixture); + field.onclick(); + const picker = document.querySelector('input[type="file"]'); + Object.defineProperty(picker, "files", { + value: [ + new File([new Uint8Array(500001)], "large.jpg", { type: "image/jpeg" }), + ], + }); + picker.dispatchEvent(new Event("change")); + await vi.waitFor(() => + expect(field.setError).toHaveBeenCalledWith("File size exceeds 500KB"), + ); + expect(field.value).toBe(""); + field.onclick(); + const replacement = document.querySelector('input[type="file"]'); + expect(replacement).not.toBeNull(); + expect(replacement).not.toBe(picker); + replacement.dispatchEvent(new Event("cancel")); + finish({ name: "Sponsor" }); + expect(await result).toEqual({ name: "Sponsor" }); +}); + +it("explains recovery, stores the supplied profile and does not start another purchase", async () => { + const fixture = setup(); + await fixture.details("gold", "gold", true); + expect(fixture.prompt.mock.calls[0][0]).toBe("Gold"); + expect(fixture.prompt.mock.calls[0][2]).toContain("already paid"); + expect(fixture.prompt.mock.calls[0][2]).toContain("not be charged again"); + expect(JSON.parse(localStorage.getItem("sponsor_gold"))).toEqual({ + name: "Sponsor", + }); + expect(fixture.iap.purchase).not.toHaveBeenCalled(); + fixture.prompt.mockRejectedValueOnce(new Error("Cancelled")); + expect(await fixture.details("crystal", "crystal", true)).toBeUndefined(); + expect(localStorage.getItem("sponsor_crystal")).toBeNull(); +}); + +it.each([ + new Set(["gold"]), + null, +])("does not start a second charge when recovery finds an existing purchase or cannot query ownership", async (recovered) => { + const fixture = setup(); + fixture.recover.mockResolvedValue(recovered); + fixture.Sponsor(); + await vi.waitFor(() => + expect(document.querySelector(".purchase-btn")).not.toBeNull(), + ); + document.querySelector(".purchase-btn").click(); + await vi.waitFor(() => expect(fixture.recover).toHaveBeenCalledOnce()); + await vi.waitFor(() => expect(fixture.helpers.error).toHaveBeenCalledOnce()); + expect(fixture.prompt).not.toHaveBeenCalled(); + expect(fixture.iap.purchase).not.toHaveBeenCalled(); +}); + +function openDetails(fixture) { + let finish; + fixture.prompt.mockImplementationOnce( + () => + new Promise((resolve) => { + finish = resolve; + }), + ); + const result = fixture.details("gold"); + const field = fixture.prompt.mock.calls[0][1].find( + (field) => field.id === "image", + ); + field.value = ""; + field.setError = vi.fn(); + return { result, field, finish }; +} diff --git a/tests/unit/sponsorPurchases.test.js b/tests/unit/sponsorPurchases.test.js new file mode 100644 index 0000000000..ebc1954aa1 --- /dev/null +++ b/tests/unit/sponsorPurchases.test.js @@ -0,0 +1,170 @@ +// @vitest-environment happy-dom +import { beforeEach, expect, it, vi } from "vitest"; +import setupSponsorPurchases from "../helpers/sponsorPurchases"; + +let receive; +let iap; +let fetch; +let success; +let error; +let settled; +let recoverDetails; +const purchase = { + productIds: ["crystal"], + purchaseState: 1, + purchaseToken: "signed-transaction", +}; + +beforeEach(() => { + ({ receive, iap, fetch, success, error, settled, recoverDetails } = + setupSponsorPurchases()); +}); + +it("registers the signed transaction before finishing it and clears details only on success", async () => { + iap.consume.mockImplementation((token, resolve) => { + expect(fetch).toHaveBeenCalledOnce(); + expect(localStorage.getItem("sponsor_crystal")).not.toBeNull(); + resolve(0); + }); + await receive([purchase]); + expect(JSON.parse(fetch.mock.calls[0][1].body)).toMatchObject({ + name: "Sponsor", + tier: "crystal", + packageName: "app.acode", + purchaseToken: "signed-transaction", + }); + expect(iap.consume).toHaveBeenCalledOnce(); + expect(localStorage.getItem("sponsor_crystal")).toBeNull(); + expect(success).toHaveBeenCalledOnce(); + expect(error).not.toHaveBeenCalled(); +}); + +it.each([ + false, + true, +])("retains an unfinished purchase on HTTP or JSON failure (HTTP ok: %s) and retries", async (ok) => { + fetch.mockResolvedValueOnce({ + ok, + json: async () => ({ error: "Purchase not valid" }), + }); + await receive([purchase]); + expect(iap.consume).not.toHaveBeenCalled(); + expect(success).not.toHaveBeenCalled(); + expect(error.mock.calls[0][0].message).toBe("Purchase not valid"); + expect(localStorage.getItem("sponsor_crystal")).not.toBeNull(); + await receive([purchase]); + expect(iap.consume).toHaveBeenCalledOnce(); + expect(success).toHaveBeenCalledOnce(); +}); + +it.each([ + "empty", + "html", + "null", + "array", + "redirect", +])("retains paid purchases after an unverified %s response and allows retry", async (kind) => { + fetch.mockResolvedValueOnce({ + ok: true, + redirected: kind === "redirect", + json: async () => { + if (kind === "empty" || kind === "html") + throw new SyntaxError("Invalid JSON"); + return kind === "null" ? null : kind === "array" ? [] : {}; + }, + }); + await receive([purchase]); + expect(iap.consume).not.toHaveBeenCalled(); + expect(error).toHaveBeenCalledOnce(); + expect(localStorage.getItem("sponsor_pending_app.acode")).toContain( + purchase.purchaseToken, + ); + await receive([]); + expect(iap.consume).toHaveBeenCalledOnce(); + expect(success).toHaveBeenCalledOnce(); +}); + +it("ignores pending, revoked and unrelated purchases and duplicate deliveries", async () => { + await receive([ + { ...purchase, purchaseState: 2 }, + { ...purchase, purchaseState: 0 }, + { ...purchase, productIds: ["acode_pro_new"] }, + ]); + expect(fetch).not.toHaveBeenCalled(); + await Promise.all([receive([purchase]), receive([purchase])]); + await receive([purchase]); + expect(fetch).toHaveBeenCalledOnce(); + expect(iap.consume).toHaveBeenCalledOnce(); +}); + +it("retains details when StoreKit finishing fails, then retries idempotent registration", async () => { + iap.consume.mockImplementationOnce((token, resolve, reject) => reject(6)); + await receive([purchase]); + expect(success).not.toHaveBeenCalled(); + expect(localStorage.getItem("sponsor_crystal")).not.toBeNull(); + await receive([purchase]); + expect(success).toHaveBeenCalledOnce(); + expect(settled).toHaveBeenCalledTimes(2); +}); + +it.each([ + null, + "broken JSON", + "{}", + '"invalid details"', +])("recovers a paid transaction with missing or invalid details (%s) before finishing", async (stored) => { + localStorage.removeItem("sponsor_crystal"); + if (stored !== null) localStorage.setItem("sponsor_crystal", stored); + await Promise.all([receive([purchase]), receive([purchase])]); + await receive([purchase]); + expect(recoverDetails).toHaveBeenCalledExactlyOnceWith( + "crystal", + "crystal", + true, + ); + expect(JSON.parse(fetch.mock.calls[0][1].body)).toMatchObject({ + name: "Recovered Sponsor", + public: false, + purchaseToken: purchase.purchaseToken, + }); + expect(fetch).toHaveBeenCalledOnce(); + expect(iap.consume).toHaveBeenCalledOnce(); +}); + +it("leaves a cancelled recovery unfinished and offers recovery again", async () => { + localStorage.clear(); + recoverDetails.mockResolvedValueOnce(null); + await receive([purchase]); + expect(fetch).not.toHaveBeenCalled(); + expect(iap.consume).not.toHaveBeenCalled(); + expect(success).not.toHaveBeenCalled(); + await receive([purchase]); + expect(recoverDetails).toHaveBeenCalledTimes(2); + expect(iap.consume).toHaveBeenCalledOnce(); +}); + +it("retains recovered details after a server failure and retries without prompting again", async () => { + localStorage.clear(); + fetch.mockRejectedValueOnce(new Error("Offline")); + await receive([purchase]); + expect(iap.consume).not.toHaveBeenCalled(); + expect(localStorage.getItem("sponsor_crystal")).not.toBeNull(); + await receive([purchase]); + expect(recoverDetails).toHaveBeenCalledOnce(); + expect(iap.consume).toHaveBeenCalledOnce(); +}); + +it("continues the batch when one transaction cannot be registered", async () => { + fetch.mockRejectedValueOnce(new Error("Offline")); + await receive([ + purchase, + { ...purchase, productIds: ["gold"], purchaseToken: "gold-token" }, + ]); + expect(error).toHaveBeenCalledOnce(); + expect(iap.consume).toHaveBeenCalledExactlyOnceWith( + "gold-token", + expect.any(Function), + expect.any(Function), + ); + expect(localStorage.getItem("sponsor_crystal")).not.toBeNull(); +}); diff --git a/tests/unit/sponsorRecovery.test.js b/tests/unit/sponsorRecovery.test.js new file mode 100644 index 0000000000..21bc79cb2f --- /dev/null +++ b/tests/unit/sponsorRecovery.test.js @@ -0,0 +1,236 @@ +// @vitest-environment happy-dom +import { expect, it, vi } from "vitest"; +import { loadSourceModule } from "../helpers/loadSourceModule"; +import setupSponsorPurchases from "../helpers/sponsorPurchases"; + +const purchase = { + productIds: ["crystal"], + purchaseState: 1, + purchaseToken: "paid-token", +}; + +it.each([ + "app.acode", + "com.foxdebug.acodefree", +])("recovers unfinished %s sponsorship on startup without visiting the page", async (packageName) => { + const f = setup(packageName); + localStorage.clear(); + const recovered = await f.service.default(); + expect(recovered.has("crystal")).toBe(true); + expect(f.recoverDetails).toHaveBeenCalledOnce(); + expect(f.fetch).toHaveBeenCalledOnce(); + expect(f.iap.consume).toHaveBeenCalledOnce(); + expect(f.iap.purchase).not.toHaveBeenCalled(); + expect(f.pending.list()).toEqual([]); +}); + +it.each([ + "resume", + "online", +])("retries a failed registration on %s, preserving the original profile", async (event) => { + const f = setup(); + f.fetch.mockRejectedValueOnce(new Error("Offline")); + await f.service.default(); + expect(f.pending.list()).toHaveLength(1); + (event === "resume" ? f.document : f.window).dispatchEvent(new Event(event)); + await vi.waitFor(() => expect(f.pending.list()).toEqual([])); + expect(f.recoverDetails).not.toHaveBeenCalled(); + expect(f.iap.consume).toHaveBeenCalledOnce(); +}); + +it("handles delayed approval through the persistent observer while the sponsor page is closed", async () => { + const f = setup(); + f.iap.getPurchases.mockImplementation((success) => success([])); + await f.service.default(); + await f.iap.addPurchaseUpdatedListener.mock.calls[0][0]([purchase]); + expect(f.iap.consume).toHaveBeenCalledOnce(); + expect(f.dialog).toHaveBeenCalledOnce(); +}); + +it("shares one recovery operation and one observer across startup and page entry", async () => { + const f = setup(); + await Promise.all([ + f.service.default(), + f.service.default(true), + f.service.recoverSponsorPurchases(true), + ]); + expect(f.iap.addPurchaseUpdatedListener).toHaveBeenCalledOnce(); + expect(f.iap.getPurchases).toHaveBeenCalledOnce(); + expect(f.fetch).toHaveBeenCalledOnce(); +}); + +it("keeps cancellation quiet on resume, but offers the form again on explicit page entry", async () => { + const f = setup(); + localStorage.clear(); + f.recoverDetails.mockResolvedValueOnce(null); + await f.service.default(); + await f.service.recoverSponsorPurchases(); + expect(f.recoverDetails).toHaveBeenCalledOnce(); + await f.service.recoverSponsorPurchases(true); + expect(f.recoverDetails).toHaveBeenCalledTimes(2); + expect(f.iap.consume).toHaveBeenCalledOnce(); +}); + +it("retries a durable transaction when store lookup fails, and blocks a new charge", async () => { + const f = setup(); + f.fetch.mockRejectedValueOnce(new Error("Offline")); + await f.service.default(); + f.iap.startConnection.mockImplementation((success, failure) => failure(2)); + f.iap.getPurchases.mockImplementation((success, failure) => failure(2)); + const recovered = await f.service.recoverSponsorPurchases(true); + expect(recovered).toBeNull(); + expect(f.iap.consume).toHaveBeenCalledOnce(); + expect(f.pending.list()).toEqual([]); +}); + +it("does nothing when the app has no IAP service", async () => { + const f = setup(undefined, false); + expect(await f.service.default()).toBeNull(); + expect(f.iap.startConnection).not.toHaveBeenCalled(); + expect(f.iap.addPurchaseUpdatedListener).not.toHaveBeenCalled(); +}); + +it("recovers existing StoreKit receipts even when new payments are restricted", async () => { + const f = setup(); + f.iap.startConnection.mockImplementation((success, failure) => failure(3)); + await f.service.default(); + expect(f.iap.getPurchases).toHaveBeenCalledOnce(); + expect(f.iap.consume).toHaveBeenCalledOnce(); +}); + +it("honors explicit recovery while a background store query is in flight", async () => { + const f = setup(); + localStorage.clear(); + f.recoverDetails.mockResolvedValueOnce(null); + await f.service.default(); + let finishQuery; + f.iap.getPurchases.mockImplementationOnce((success) => { + finishQuery = success; + }); + const background = f.service.recoverSponsorPurchases(); + const explicit = f.service.recoverSponsorPurchases(true); + finishQuery([purchase]); + await Promise.all([background, explicit]); + expect(f.recoverDetails).toHaveBeenCalledTimes(2); + expect(f.iap.getPurchases).toHaveBeenCalledTimes(2); + expect(f.iap.consume).toHaveBeenCalledOnce(); +}); + +it("honors an explicit retry arriving while the background recovery form is open", async () => { + const f = setup(); + localStorage.clear(); + let cancel; + f.recoverDetails.mockImplementationOnce( + () => + new Promise((resolve) => { + cancel = resolve; + }), + ); + const background = f.service.default(); + await vi.waitFor(() => expect(f.recoverDetails).toHaveBeenCalledOnce()); + const explicit = f.service.recoverSponsorPurchases(true); + cancel(null); + await Promise.all([background, explicit]); + expect(f.recoverDetails).toHaveBeenCalledTimes(2); + expect(f.iap.getPurchases).toHaveBeenCalledOnce(); + expect(f.iap.consume).toHaveBeenCalledOnce(); +}); + +it("retries observer registration after a bridge failure without duplicating lifecycle listeners", async () => { + const f = setup(); + f.iap.addPurchaseUpdatedListener.mockImplementationOnce(() => { + throw new Error("Bridge unavailable"); + }); + await f.service.default(); + await f.service.default(); + expect(f.iap.addPurchaseUpdatedListener).toHaveBeenCalledTimes(2); + f.document.dispatchEvent(new Event("resume")); + await vi.waitFor(() => expect(f.iap.getPurchases).toHaveBeenCalledTimes(3)); +}); + +it("times out an unresponsive store so later resume can query again", async () => { + vi.useFakeTimers(); + try { + const f = setup(); + f.iap.startConnection.mockImplementationOnce(() => {}); + const stalled = f.service.default(); + await vi.advanceTimersByTimeAsync(5000); + expect(await stalled).toBeNull(); + await f.service.recoverSponsorPurchases(); + expect(f.iap.consume).toHaveBeenCalledOnce(); + } finally { + vi.useRealTimers(); + } +}); + +it("includes a purchase delivered and finished while the store query is pending", async () => { + const f = setup(); + let finishQuery; + f.iap.getPurchases.mockImplementationOnce((success) => { + finishQuery = success; + }); + const recovery = f.service.default(); + await f.iap.addPurchaseUpdatedListener.mock.calls[0][0]([purchase]); + expect(f.pending.list()).toEqual([]); + finishQuery([]); + expect((await recovery).has("crystal")).toBe(true); + f.iap.getPurchases.mockImplementationOnce((success) => success([])); + expect((await f.service.recoverSponsorPurchases()).size).toBe(0); +}); + +it.each([ + false, + true, +])("includes a purchase delivered during processing (registration succeeds: %s)", async (succeeds) => { + const f = setup(); + let finishRegistration; + f.fetch.mockImplementationOnce( + () => + new Promise((resolve) => { + finishRegistration = resolve; + }), + ); + const recovery = f.service.default(); + await vi.waitFor(() => expect(f.fetch).toHaveBeenCalledOnce()); + if (!succeeds) f.fetch.mockRejectedValueOnce(new Error("Offline")); + const delivery = f.iap.addPurchaseUpdatedListener.mock.calls[0][0]([ + { ...purchase, productIds: ["gold"], purchaseToken: "gold-token" }, + ]); + finishRegistration({ ok: true, json: async () => ({}) }); + const [products] = await Promise.all([recovery, delivery]); + expect([...products]).toEqual(["crystal", "gold"]); + expect(f.pending.list()).toHaveLength(succeeds ? 0 : 1); + expect(f.iap.consume).toHaveBeenCalledTimes(succeeds ? 2 : 1); +}); + +function setup(packageName = "app.acode", available = true) { + const fixture = setupSponsorPurchases(packageName); + const document = new EventTarget(); + const window = new EventTarget(); + const dialog = vi.fn(); + Object.assign(fixture.iap, { + startConnection: vi.fn((success) => success(0)), + getPurchases: vi.fn((success) => success([purchase])), + addPurchaseUpdatedListener: vi.fn(), + purchase: vi.fn(), + }); + const service = loadSourceModule( + "src/pages/sponsor/recovery.js", + { + "dialogs/dialog": dialog, + "utils/helpers": { error: fixture.error }, + "./pending": fixture.pending, + "./purchases": fixture.createProcessor, + }, + { + document, + window, + setTimeout, + clearTimeout, + strings: { info: "Info" }, + console: { warn: vi.fn(), error: vi.fn() }, + ...(available ? { iap: fixture.iap } : {}), + }, + ); + return { ...fixture, document, window, dialog, service }; +} diff --git a/tests/unit/sponsorRecoveryPurchases.test.js b/tests/unit/sponsorRecoveryPurchases.test.js new file mode 100644 index 0000000000..506f470ba5 --- /dev/null +++ b/tests/unit/sponsorRecoveryPurchases.test.js @@ -0,0 +1,235 @@ +// @vitest-environment happy-dom +import { expect, it, vi } from "vitest"; +import setupSponsorPurchases from "../helpers/sponsorPurchases"; + +const purchase = { + productIds: ["crystal"], + purchaseState: 1, + purchaseToken: "paid-token", +}; + +it.each([ + "app.acode", + "com.foxdebug.acodefree", +])("lets a paid %s purchase correct rejected details after reopening", async (packageName) => { + const f = setupSponsorPurchases(packageName); + localStorage.setItem( + "sponsor_crystal", + JSON.stringify({ name: "x".repeat(201), public: true }), + ); + f.fetch.mockResolvedValueOnce({ + ok: false, + status: 400, + json: async () => ({ error: "Invalid sponsor name. ", field: "name" }), + }); + await f.receive([purchase]); + expect(f.iap.consume).not.toHaveBeenCalled(); + expect(f.pending.list()[0].purchase.purchaseToken).toBe( + purchase.purchaseToken, + ); + expect(f.pending.list()[0].details).toBeNull(); + expect(localStorage.getItem("sponsor_crystal")).toBeNull(); + expect(f.error.mock.calls[0][0].message).toBe( + "Invalid sponsor name. Reopen Sponsorship to correct your details. Your purchase is saved.", + ); + await f.createReceiver()([]); + expect(f.recoverDetails).toHaveBeenCalledOnce(); + expect(JSON.parse(f.fetch.mock.calls[1][1].body)).toMatchObject({ + name: "Recovered Sponsor", + purchaseToken: purchase.purchaseToken, + }); + expect(f.iap.consume).toHaveBeenCalledOnce(); + expect(f.pending.list()).toEqual([]); +}); + +it("keeps the paid transaction when correction is cancelled and offers it again", async () => { + const f = setupSponsorPurchases(); + f.fetch.mockResolvedValueOnce({ + ok: false, + status: 400, + json: async () => ({ error: "Invalid sponsor website", field: "website" }), + }); + await f.receive([purchase]); + f.recoverDetails.mockResolvedValueOnce(null); + await f.createReceiver()([]); + expect(f.iap.consume).not.toHaveBeenCalled(); + expect(f.pending.list()).toHaveLength(1); + await f.createReceiver()([]); + expect(f.iap.consume).toHaveBeenCalledOnce(); +}); + +it("preserves a newer draft when an earlier profile is rejected", async () => { + const f = setupSponsorPurchases(); + const corrected = JSON.stringify({ name: "Updated Sponsor", public: false }); + f.fetch.mockImplementationOnce(async () => { + localStorage.setItem("sponsor_crystal", corrected); + return { + ok: false, + status: 400, + json: async () => ({ error: "Invalid name" }), + }; + }); + await f.receive([purchase]); + expect(localStorage.getItem("sponsor_crystal")).toBe(corrected); + expect(f.pending.list()[0].details).toBeNull(); + expect(f.iap.consume).not.toHaveBeenCalled(); +}); + +it.each([ + "app.acode", + "com.foxdebug.acodefree", +])("recovers a paid %s purchase after restart without another purchase or lost details", async (packageName) => { + const f = setupSponsorPurchases(packageName); + f.fetch.mockRejectedValueOnce(new Error("Connection lost during restart")); + await f.receive([purchase]); + expect(f.pending.list()).toHaveLength(1); + localStorage.removeItem("sponsor_crystal"); + const restarted = f.createReceiver(); + await restarted([]); + expect(f.recoverDetails).not.toHaveBeenCalled(); + expect(JSON.parse(f.fetch.mock.calls[1][1].body)).toMatchObject({ + name: "Sponsor", + packageName, + purchaseToken: "paid-token", + }); + expect(f.iap.consume).toHaveBeenCalledOnce(); + expect(f.pending.list()).toEqual([]); +}); + +it("persists all paid transactions before opening a recovery prompt", async () => { + const f = setupSponsorPurchases(); + localStorage.clear(); + f.recoverDetails.mockImplementationOnce(() => new Promise(() => {})); + void f.receive([ + purchase, + { ...purchase, productIds: ["gold"], purchaseToken: "gold-token" }, + ]); + expect(f.pending.list()).toHaveLength(2); + const restarted = f.createReceiver(); + await restarted([]); + expect(f.iap.consume).toHaveBeenCalledTimes(2); + expect(f.pending.list()).toEqual([]); +}); + +it("retains server registration across a restart after finishing, even when the store no longer owns it", async () => { + const f = setupSponsorPurchases(); + f.iap.consume.mockImplementationOnce((token, resolve, reject) => reject(6)); + await f.receive([purchase]); + expect(f.pending.list()[0].registered).toBe("https://example.test/api"); + f.iap.consume.mockImplementationOnce((token, resolve, reject) => reject(8)); + await f.createReceiver()([]); + expect(f.fetch).toHaveBeenCalledOnce(); + expect(f.success).toHaveBeenCalledOnce(); + expect(f.pending.list()).toEqual([]); +}); + +it("does not finish a purchase that the server rejected, even if it is no longer owned", async () => { + const f = setupSponsorPurchases(); + f.fetch.mockResolvedValue({ + ok: false, + json: async () => ({ error: "Invalid purchase" }), + }); + await f.receive([purchase]); + await f.createReceiver()([]); + expect(f.iap.consume).not.toHaveBeenCalled(); + expect(f.pending.list()).toHaveLength(1); +}); + +it("deduplicates re-signed StoreKit transactions using their transaction identity", async () => { + const f = setupSponsorPurchases(); + const apple = { + ...purchase, + store: "appstore", + transactionId: "42", + environment: "Sandbox", + }; + await Promise.all([ + f.receive([apple]), + f.receive([{ ...apple, purchaseToken: "new-signature" }]), + ]); + await f.receive([{ ...apple, purchaseToken: "another-signature" }]); + expect(f.fetch).toHaveBeenCalledOnce(); + expect(f.iap.consume).toHaveBeenCalledOnce(); +}); + +it("keeps each transaction's profile separate from later drafts for the same tier", async () => { + const f = setupSponsorPurchases(); + f.fetch.mockRejectedValueOnce(new Error("Offline")); + await f.receive([purchase]); + localStorage.setItem( + "sponsor_crystal", + JSON.stringify({ name: "Later Sponsor" }), + ); + await f.createReceiver()([]); + expect(JSON.parse(f.fetch.mock.calls[1][1].body).name).toBe("Sponsor"); + expect(JSON.parse(localStorage.getItem("sponsor_crystal")).name).toBe( + "Later Sponsor", + ); +}); + +it("does not repeatedly prompt after cancellation on resume, but allows explicit recovery and restart", async () => { + const f = setupSponsorPurchases(); + localStorage.clear(); + f.recoverDetails.mockResolvedValueOnce(null); + await f.receive([purchase], false); + await f.receive([purchase], false); + expect(f.recoverDetails).toHaveBeenCalledOnce(); + await f.receive([], true); + expect(f.recoverDetails).toHaveBeenCalledTimes(2); + expect(f.pending.list()).toEqual([]); +}); + +it("does not process another app's saved purchases", async () => { + const f = setupSponsorPurchases("app.acode"); + f.fetch.mockRejectedValueOnce(new Error("Offline")); + await f.receive([purchase]); + localStorage.setItem( + "sponsor_pending_com.foxdebug.acodefree", + JSON.stringify(f.pending.list()), + ); + localStorage.removeItem("sponsor_pending_app.acode"); + await f.createReceiver()([]); + expect(f.iap.consume).not.toHaveBeenCalled(); +}); + +it("retains a server-confirmed purchase if the finish callback is lost, then recovers it after restart", async () => { + vi.useFakeTimers(); + try { + const f = setupSponsorPurchases(); + f.iap.consume.mockImplementationOnce(() => {}); + const stalled = f.receive([purchase]); + await vi.advanceTimersByTimeAsync(5000); + await stalled; + expect(f.pending.list()[0].registered).toBe("https://example.test/api"); + f.iap.consume.mockImplementationOnce((token, resolve, reject) => reject(8)); + await f.createReceiver()([]); + expect(f.fetch).toHaveBeenCalledOnce(); + expect(f.pending.list()).toEqual([]); + } finally { + vi.useRealTimers(); + } +}); + +it("aborts stalled registration without finishing the purchase, and retries later", async () => { + vi.useFakeTimers(); + try { + const f = setupSponsorPurchases(); + f.fetch.mockImplementationOnce( + (url, { signal }) => + new Promise((resolve, reject) => { + signal.addEventListener("abort", () => + reject(new Error("Request timed out")), + ); + }), + ); + const stalled = f.receive([purchase]); + await vi.advanceTimersByTimeAsync(15000); + await stalled; + expect(f.iap.consume).not.toHaveBeenCalled(); + expect(f.pending.list()).toHaveLength(1); + await f.receive([]); + expect(f.pending.list()).toEqual([]); + } finally { + vi.useRealTimers(); + } +}); diff --git a/tests/unit/systemTheme.test.js b/tests/unit/systemTheme.test.js new file mode 100644 index 0000000000..b0f5be194f --- /dev/null +++ b/tests/unit/systemTheme.test.js @@ -0,0 +1,32 @@ +import { afterEach, expect, it, vi } from "vitest"; + +vi.mock("lib/settings", () => ({ default: { value: {} } })); +vi.mock("theme/list", () => ({ apply: vi.fn() })); +vi.mock("utils/color", () => ({ default: vi.fn() })); + +import themes, { updateSystemTheme } from "theme/preInstalled"; +import Color from "utils/color"; + +afterEach(() => vi.resetAllMocks()); + +it("recalculates dialog dimming when the System theme changes appearance", () => { + const theme = themes.find(({ id }) => id === "system"); + const darken = vi.fn(); + Color.mockReturnValue({ darken }); + + for (const [isDark, primary, dimmed] of [ + [true, "rgb(35, 39, 42)", "#151719"], + [false, "rgb(255, 255, 255)", "#999999"], + [true, "rgb(35, 39, 42)", "#151719"], + ]) { + darken.mockReturnValue({ hex: { toString: () => dimmed } }); + vi.clearAllMocks(); + + updateSystemTheme(isDark, false); + + expect(Color).toHaveBeenCalledExactlyOnceWith(primary); + expect(darken).toHaveBeenCalledExactlyOnceWith(0.4); + expect(theme.primaryColor).toBe(primary); + expect(theme.darkenedPrimaryColor).toBe(dimmed); + } +}); diff --git a/tests/unit/terminalLinks.test.js b/tests/unit/terminalLinks.test.js new file mode 100644 index 0000000000..fa7b15334f --- /dev/null +++ b/tests/unit/terminalLinks.test.js @@ -0,0 +1,79 @@ +import openTerminalLink from "components/terminal/openTerminalLink"; +import confirm from "dialogs/confirm"; +import browser from "native/browser"; +import helpers from "utils/helpers"; +import { afterEach, beforeEach, expect, test, vi } from "vitest"; + +vi.mock("dialogs/confirm", () => ({ default: vi.fn() })); +vi.mock("native/browser", () => ({ default: { open: vi.fn() } })); +vi.mock("utils/helpers", () => ({ default: { error: vi.fn() } })); + +beforeEach(() => { + vi.clearAllMocks(); + browser.open.mockReset(); + helpers.error.mockReset(); + vi.stubGlobal("Bridge", { platformId: "ios" }); + vi.stubGlobal("system", { openInBrowser: vi.fn() }); + confirm.mockResolvedValue(true); +}); +afterEach(() => vi.unstubAllGlobals()); + +test.each([ + [ + "http://localhost:3000/path?q=1#section", + "http://localhost:3000/path?q=1#section", + ], + ["http://127.0.0.1:3000", "http://127.0.0.1:3000/"], + ["http://0.0.0.0:3000", "http://127.0.0.1:3000/"], + ["http://[::1]:3000", "http://[::1]:3000/"], + ["http://[::]:3000", "http://[::1]:3000/"], + ["https://localhost:3000", "https://localhost:3000/"], + ["http://LOCALHOST.:3000", "http://localhost.:3000/"], + ["http://user:pass@localhost:3000", "http://user:pass@localhost:3000/"], +])("iOS previews local server %s without leaving Acode", async (uri, target) => { + await openTerminalLink(uri); + expect(browser.open).toHaveBeenCalledWith(target, false, { + ephemeral: true, + onError: expect.any(Function), + }); + expect(system.openInBrowser).not.toHaveBeenCalled(); + expect(confirm).not.toHaveBeenCalled(); +}); + +test.each([ + ["ios", "https://localhost.example.com", false], + ["ios", "http://localhost@evil.example", false], + ["ios", "http://127.0.0.1.evil.example", false], + ["ios", "http://notlocalhost", false], + ["ios", "http://localhost:3000", true], + ["android", "http://localhost:3000", false], +])("preserves external routing for %s %s (remote: %s)", async (platform, uri, remote) => { + Bridge.platformId = platform; + await openTerminalLink(uri, remote); + expect(browser.open).not.toHaveBeenCalled(); + expect(system.openInBrowser).toHaveBeenCalledWith(uri); +}); + +test("cancelled external navigation does not open a browser", async () => { + confirm.mockResolvedValue(false); + await openTerminalLink("https://example.com"); + expect(browser.open).not.toHaveBeenCalled(); + expect(system.openInBrowser).not.toHaveBeenCalled(); +}); + +test.each([ + false, + true, +])("reports preview failures without leaving Acode (throws: %s)", async (throws) => { + const error = new Error("A browser cannot be presented right now"); + helpers.error.mockImplementation(function () { + expect(this).toBe(helpers); + }); + browser.open.mockImplementation((url, isConsole, options) => { + if (throws) throw error; + options.onError(error); + }); + await openTerminalLink("http://localhost:3000"); + expect(helpers.error).toHaveBeenCalledWith(error); + expect(system.openInBrowser).not.toHaveBeenCalled(); +}); From 791e2a964edc97f8769470fb2aa37374958d8492 Mon Sep 17 00:00:00 2001 From: Ajit Kumar Date: Sat, 28 Nov 2026 14:10:27 +0530 Subject: [PATCH 2/6] fix(dialogs): settle prompts on back, cancel and bulk clear - reject multi-prompts and resolve single prompts to null when dismissed by the Back gesture - use unique action ids so nested prompts remove only their own entry - run optional onClear cleanup when actionStack.clearFromMark removes marked entries - restore the keyboard input mode only when no visible prompt remains - add shared prompt dialog and action-stack cleanup tests --- src/dialogs/multiPrompt.js | 24 ++-- src/dialogs/prompt.js | 54 ++++---- src/dialogs/restorePromptInput.js | 6 + src/lib/actionStack.js | 15 ++- tests/helpers/promptDialogs.js | 96 +++++++++++++++ tests/unit/actionStackCleanup.test.js | 49 ++++++++ tests/unit/promptDialogs.test.js | 170 ++++++++++++++++++++++++++ 7 files changed, 381 insertions(+), 33 deletions(-) create mode 100644 src/dialogs/restorePromptInput.js create mode 100644 tests/helpers/promptDialogs.js create mode 100644 tests/unit/actionStackCleanup.test.js create mode 100644 tests/unit/promptDialogs.test.js diff --git a/src/dialogs/multiPrompt.js b/src/dialogs/multiPrompt.js index 538702e6c2..b02ff55016 100644 --- a/src/dialogs/multiPrompt.js +++ b/src/dialogs/multiPrompt.js @@ -3,8 +3,10 @@ import Checkbox from "components/checkbox"; import inputhints from "components/inputhints"; import actionStack from "lib/actionStack"; import restoreTheme from "lib/restoreTheme"; -import appSettings from "lib/settings"; import alert from "./alert"; +import restorePromptInput from "./restorePromptInput"; + +let nextPromptId = 0; /** * @typedef {object} Input @@ -33,6 +35,7 @@ import alert from "./alert"; * @returns {Promise} */ export default function multiPrompt(message, inputs, help) { + const actionId = `multi-prompt-${++nextPromptId}`; return new Promise((resolve, reject) => { const $title = tag("div", { className: "title", @@ -76,8 +79,8 @@ export default function multiPrompt(message, inputs, help) { textContent: strings.cancel, type: "button", onclick: function () { - reject(); - hide(); + actionStack.remove(actionId); + cancel(); }, }); const $errorMessage = ( @@ -129,8 +132,9 @@ export default function multiPrompt(message, inputs, help) { }); actionStack.push({ - id: "prompt", - action: hidePrompt, + id: actionId, + action: cancel, + onClear: cancel, }); restoreTheme(true); @@ -139,9 +143,16 @@ export default function multiPrompt(message, inputs, help) { const $focusEl = [...$body.getAll("input[autofocus]")].pop(); if ($focusEl) $focusEl.focus(); + function cancel() { + reject(); + hidePrompt(); + } + function hidePrompt() { + if ($promptDiv.classList.contains("hide")) return; clearSensitiveInputs(); $promptDiv.classList.add("hide"); + restorePromptInput(); restoreTheme(); setTimeout(() => { if ($promptDiv.isConnected) $promptDiv.remove(); @@ -150,8 +161,7 @@ export default function multiPrompt(message, inputs, help) { } function hide() { - actionStack.remove("prompt"); - system.setInputType(appSettings.value.keyboardMode); + actionStack.remove(actionId); hidePrompt(); } diff --git a/src/dialogs/prompt.js b/src/dialogs/prompt.js index 3c4407f1fb..a37035905f 100644 --- a/src/dialogs/prompt.js +++ b/src/dialogs/prompt.js @@ -2,7 +2,9 @@ import autosize from "autosize"; import actionStack from "lib/actionStack"; import platform from "lib/platform"; import restoreTheme from "lib/restoreTheme"; -import appSettings from "lib/settings"; +import restorePromptInput from "./restorePromptInput"; + +let nextPromptId = 0; /** * @typedef {Object} PromptOptions @@ -28,6 +30,7 @@ export default function prompt( type = "text", options = {}, ) { + const actionId = `single-prompt-${++nextPromptId}`; // CodeMirror doesn't use commands.exec like ACE, so we store a reference to the editor // to potentially disable keymaps if needed in the future const editor = editorManager.editor; @@ -58,24 +61,13 @@ export default function prompt( type: "submit", textContent: strings.ok, disabled: !defaultValue, - onclick: function () { - if (options.required && !input.value) { - errorMessage.textContent = strings.required; - return; - } - hide(); - let { value } = input; - if (type === "number") value = +value; - - resolve(value); - }, }); const cancelBtn = tag("button", { textContent: strings.cancel, type: "button", onclick: function () { - hide(); - resolve(null); + actionStack.remove(actionId); + cancel(); }, }); const errorMessage = tag("span", { @@ -84,12 +76,7 @@ export default function prompt( const promptDiv = tag("form", { action: "#", className: "prompt", - onsubmit: (e) => { - e.preventDefault(); - if (!okBtn.disabled) { - resolve(input.value); - } - }, + onsubmit: submit, children: [ messageSpan, input, @@ -140,8 +127,9 @@ export default function prompt( }; actionStack.push({ - id: "prompt", - action: hidePrompt, + id: actionId, + action: cancel, + onClear: cancel, }); system.setInputType("NORMAL"); @@ -162,8 +150,27 @@ export default function prompt( } if (inputType === "textarea") autosize(input); + function submit(event) { + event.preventDefault(); + if (okBtn.disabled || promptDiv.classList.contains("hide")) return; + if (options.required && !input.value) { + errorMessage.textContent = strings.required; + return; + } + const value = type === "number" ? +input.value : input.value; + hide(); + resolve(value); + } + + function cancel() { + resolve(null); + hidePrompt(); + } + function hidePrompt() { + if (promptDiv.classList.contains("hide")) return; promptDiv.classList.add("hide"); + restorePromptInput(); restoreTheme(); setTimeout(() => { if (promptDiv.isConnected) promptDiv.remove(); @@ -173,8 +180,7 @@ export default function prompt( function hide() { // CodeMirror keymaps are handled differently - no need to restore commands.exec - actionStack.remove("prompt"); - system.setInputType(appSettings.value.keyboardMode); + actionStack.remove(actionId); hidePrompt(); } }); diff --git a/src/dialogs/restorePromptInput.js b/src/dialogs/restorePromptInput.js new file mode 100644 index 0000000000..8d2723daac --- /dev/null +++ b/src/dialogs/restorePromptInput.js @@ -0,0 +1,6 @@ +import appSettings from "lib/settings"; + +export default function restorePromptInput() { + const activePrompt = document.querySelector("form.prompt:not(.hide)"); + system.setInputType(activePrompt ? "NORMAL" : appSettings.value.keyboardMode); +} diff --git a/src/lib/actionStack.js b/src/lib/actionStack.js index 62ba740eb7..6323653785 100644 --- a/src/lib/actionStack.js +++ b/src/lib/actionStack.js @@ -50,6 +50,7 @@ export default { * @param {object} fun * @param {string} fun.id * @param {Function} fun.action + * @param {() => void} [fun.onClear] Synchronous cleanup on bulk removal; must not return a Promise. */ push(fun) { stack.push(fun); @@ -133,12 +134,22 @@ export default { mark = stack.length; }, /** - * Remove all actions that are pushed after marked positions (using `setMark()`) + * Remove the marked entries, reset the mark, then run onClear callbacks top-first. + * Cleanup must be synchronous: returned Promises are neither awaited nor caught. + * Callbacks should avoid stack mutations unless deliberate; newly pushed entries + * and new marks survive this clear. */ clearFromMark() { if (mark === null) return; - stack.splice(mark); + const removed = stack.splice(mark); mark = null; + for (const entry of removed.reverse()) { + try { + entry.onClear?.(); + } catch (error) { + console.error(error); + } + } }, freeze() { freeze = true; diff --git a/tests/helpers/promptDialogs.js b/tests/helpers/promptDialogs.js new file mode 100644 index 0000000000..5a6f2e69ba --- /dev/null +++ b/tests/helpers/promptDialogs.js @@ -0,0 +1,96 @@ +import { createRequire } from "node:module"; +import tag from "html-tag-js"; +import { vi } from "vitest"; +import { loadSourceModule } from "./loadSourceModule"; +import setupSponsorPurchases from "./sponsorPurchases"; + +createRequire(import.meta.url)("html-tag-js/polyfill"); + +export default function setup() { + // happy-dom does not bind `this` for VM-created focus handlers. + vi.spyOn(HTMLInputElement.prototype, "focus").mockImplementation(() => {}); + const f = setupSponsorPurchases("com.foxdebug.acodefree"); + localStorage.clear(); + const settings = { value: { keyboardMode: "CODE" } }; + const actionStack = loadSourceModule("src/lib/actionStack.js", { + "dialogs/confirm": vi.fn(), + "lib/platform": { appExit: false }, + "lib/settings": settings, + }).default; + const system = { setInputType: vi.fn() }; + const globals = { + tag, + document, + localStorage, + system, + AbortController, + strings: { ok: "OK", cancel: "Cancel", info: "Info", required: "Required" }, + }; + const restorePromptInput = loadSourceModule( + "src/dialogs/restorePromptInput.js", + { + "lib/settings": settings, + }, + globals, + ).default; + const prompt = loadSourceModule( + "src/dialogs/multiPrompt.js", + { + autosize: vi.fn(), + "components/checkbox": (text, checked, name, id, type) => + tag("input", { checked, name, id, type }), + "components/inputhints": vi.fn(), + "lib/actionStack": actionStack, + "lib/restoreTheme": vi.fn(), + "./restorePromptInput": restorePromptInput, + "./alert": vi.fn(), + }, + globals, + ).default; + const singlePrompt = loadSourceModule( + "src/dialogs/prompt.js", + { + autosize: vi.fn(), + "lib/actionStack": actionStack, + "lib/platform": { isIOS: false }, + "lib/restoreTheme": vi.fn(), + "./restorePromptInput": restorePromptInput, + }, + { ...globals, app: document.body, editorManager: { editor: {} } }, + ).default; + const details = loadSourceModule( + "src/pages/sponsor/details.js", + { + "dialogs/multiPrompt": prompt, + "lib/platform": { isIOS: false }, + "utils/helpers": { error: f.error }, + }, + globals, + ).default; + f.recoverDetails.mockImplementation(details); + Object.assign(f.iap, { + startConnection: vi.fn((success) => success(0)), + getPurchases: vi.fn((success) => + success([ + { + productIds: ["crystal"], + purchaseState: 1, + purchaseToken: "paid-token", + }, + ]), + ), + addPurchaseUpdatedListener: vi.fn(), + purchase: vi.fn(), + }); + const recovery = loadSourceModule( + "src/pages/sponsor/recovery.js", + { + "dialogs/dialog": vi.fn(), + "utils/helpers": { error: f.error }, + "./pending": f.pending, + "./purchases": f.createProcessor, + }, + { ...globals, iap: f.iap }, + ); + return { ...f, actionStack, system, prompt, singlePrompt, service: recovery }; +} diff --git a/tests/unit/actionStackCleanup.test.js b/tests/unit/actionStackCleanup.test.js new file mode 100644 index 0000000000..f3d2b16ace --- /dev/null +++ b/tests/unit/actionStackCleanup.test.js @@ -0,0 +1,49 @@ +import { expect, it, vi } from "vitest"; +import { loadSourceModule } from "../helpers/loadSourceModule"; + +it("cleans marked entries top-first without running Back actions or discarding new entries", () => { + const errors = vi.fn(); + const stack = loadSourceModule( + "src/lib/actionStack.js", + { + "dialogs/confirm": vi.fn(), + "lib/platform": { appExit: false }, + "lib/settings": { value: {} }, + }, + { console: { error: errors } }, + ).default; + const back = vi.fn(); + const order = []; + const failure = new Error("Cleanup failed"); + stack.push({ id: "preserved", action: back }); + stack.setMark(); + stack.push({ id: "page", action: back }); + stack.push({ id: "outer", action: back, onClear: () => order.push("outer") }); + stack.push({ + id: "broken", + action: back, + onClear: () => { + throw failure; + }, + }); + stack.push({ + id: "inner", + action: back, + onClear: () => { + order.push("inner"); + stack.clearFromMark(); + stack.setMark(); + stack.push({ id: "new", action: back }); + }, + }); + stack.clearFromMark(); + expect(order).toEqual(["inner", "outer"]); + expect(errors).toHaveBeenCalledExactlyOnceWith(failure); + expect(back).not.toHaveBeenCalled(); + expect(stack.has("preserved")).toBe(true); + expect(stack.has("new")).toBe(true); + expect(stack.length).toBe(2); + stack.clearFromMark(); + expect(stack.length).toBe(1); + expect(stack.has("preserved")).toBe(true); +}); diff --git a/tests/unit/promptDialogs.test.js b/tests/unit/promptDialogs.test.js new file mode 100644 index 0000000000..8dd6a768a9 --- /dev/null +++ b/tests/unit/promptDialogs.test.js @@ -0,0 +1,170 @@ +// @vitest-environment happy-dom +import { afterEach, expect, it, vi } from "vitest"; +import setup from "../helpers/promptDialogs"; + +afterEach(() => { + vi.restoreAllMocks(); + document.body.replaceChildren(); + localStorage.clear(); +}); + +it.each([ + "back", + "cancel", + "clear", +])("retries a saved paid purchase after %s dismisses the real recovery form", async (dismissal) => { + const f = setup(); + const underlyingAction = vi.fn(); + f.actionStack.push({ id: "sponsor-page", action: underlyingAction }); + f.actionStack.setMark(); + const recovery = f.service.recoverSponsorPurchases(true); + let settled = false; + void recovery.then(() => { + settled = true; + }); + await vi.waitFor(() => + expect(document.querySelector(".prompt.multi")).not.toBeNull(), + ); + if (dismissal === "back") await f.actionStack.pop(); + else if (dismissal === "clear") f.actionStack.clearFromMark(); + else document.querySelector(".prompt.multi button[type=button]").click(); + await vi.waitFor(() => expect(settled).toBe(true)); + expect(f.pending.list()).toHaveLength(1); + expect(f.fetch).not.toHaveBeenCalled(); + expect(f.iap.consume).not.toHaveBeenCalled(); + expect(f.system.setInputType).toHaveBeenLastCalledWith("CODE"); + expect(f.actionStack.length).toBe(1); + expect(underlyingAction).not.toHaveBeenCalled(); + + const retry = f.service.recoverSponsorPurchases(true); + await vi.waitFor(() => + expect(document.querySelector(".prompt.multi:not(.hide)")).not.toBeNull(), + ); + const form = document.querySelector(".prompt.multi:not(.hide)"); + form.querySelector("#name").value = "Recovered Sponsor"; + form.querySelector("button[type=submit]").click(); + await retry; + expect(f.fetch).toHaveBeenCalledOnce(); + expect(JSON.parse(f.fetch.mock.calls[0][1].body)).toMatchObject({ + name: "Recovered Sponsor", + purchaseToken: "paid-token", + }); + expect(f.iap.consume).toHaveBeenCalledOnce(); + expect(f.pending.list()).toEqual([]); + expect(f.iap.purchase).not.toHaveBeenCalled(); +}); + +it.each([ + ["multi", "single", "back"], + ["single", "multi", "cancel"], + ["single", "single", "submit"], + ["multi", "multi", "submit"], + ["checkbox", "single", "back"], + ["empty", "single", "back"], +])("preserves the outer %s prompt and keyboard after inner %s %s", async (outerType, innerType, dismissal) => { + const f = setup(); + const open = (type) => + type === "single" + ? f.singlePrompt("Name", "Sponsor") + : f.prompt( + "Name", + type === "empty" + ? [] + : type === "checkbox" + ? [{ id: "public", type: "checkbox", value: true }] + : [{ id: "name", value: "Sponsor" }], + ); + let outerSettled = false; + const outer = open(outerType) + .catch((error) => { + expect(error).toBeUndefined(); + }) + .then(() => { + outerSettled = true; + }); + let innerResult; + let innerSettled = false; + const inner = open(innerType) + .catch((error) => { + expect(error).toBeUndefined(); + return null; + }) + .then((result) => { + innerResult = result; + innerSettled = true; + }); + const forms = document.querySelectorAll(".prompt"); + if (dismissal === "back") await f.actionStack.pop(); + else + forms[1] + .querySelector( + `button[type=${dismissal === "submit" ? "submit" : "button"}]`, + ) + .click(); + await vi.waitFor(() => expect(innerSettled).toBe(true)); + await inner; + if (dismissal === "back") expect(innerResult).toBeNull(); + expect(outerSettled).toBe(false); + expect(f.actionStack.length).toBe(1); + expect(f.system.setInputType).toHaveBeenLastCalledWith("NORMAL"); + await f.actionStack.pop(); + await vi.waitFor(() => expect(outerSettled).toBe(true)); + await outer; + expect(forms[0].classList.contains("hide")).toBe(true); + expect(f.actionStack.length).toBe(0); + expect(f.system.setInputType).toHaveBeenLastCalledWith("CODE"); +}); + +it("settles both prompt types when their marked stack is cleared", async () => { + const f = setup(); + f.actionStack.setMark(); + const multi = f.prompt("Outer", []).then( + () => "submitted", + () => "cancelled", + ); + const single = f.singlePrompt("Inner", "Sponsor"); + let results; + void Promise.all([multi, single]).then((values) => { + results = values; + }); + f.actionStack.clearFromMark(); + await vi.waitFor(() => expect(results).toEqual(["cancelled", null])); + expect(document.querySelector("form.prompt:not(.hide)")).toBeNull(); + expect(f.actionStack.length).toBe(0); + expect(f.system.setInputType).toHaveBeenLastCalledWith("CODE"); +}); + +it.each([ + "click", + "submit", +])("validates required fields and cleans up numeric prompts on %s", async (method) => { + const f = setup(); + let settled = false; + const result = f.singlePrompt("Amount", "5", "number", { required: true }); + void result.then(() => { + settled = true; + }); + const form = document.querySelector(".prompt"); + const input = form.querySelector("input"); + const submit = () => + method === "click" + ? form.querySelector("button[type=submit]").click() + : form.dispatchEvent( + new Event("submit", { bubbles: true, cancelable: true }), + ); + input.value = ""; + input.dispatchEvent(new Event("input", { bubbles: true })); + submit(); + await Promise.resolve(); + expect(settled).toBe(false); + expect(form.querySelector(".error-msg").textContent).toBe("Required"); + expect(form.classList.contains("hide")).toBe(false); + expect(f.actionStack.length).toBe(1); + input.value = "7"; + input.dispatchEvent(new Event("input", { bubbles: true })); + submit(); + expect(await result).toBe(7); + expect(form.classList.contains("hide")).toBe(true); + expect(f.actionStack.length).toBe(0); + expect(f.system.setInputType).toHaveBeenLastCalledWith("CODE"); +}); From 775ba71b157a8981c487e063e00619cdd4b91c0a Mon Sep 17 00:00:00 2001 From: Ajit Kumar Date: Mon, 30 Nov 2026 00:29:44 +0530 Subject: [PATCH 3/6] feat(ios): share the account across Acode subdomain APIs Any acode.app subdomain is now trusted with the Keychain account token on HTTPS API calls, so dev, academy and future services share one sign-in. Only acode.app and dev.acode.app remain sign-in hosts and may set parent-domain cookies. Host validation now mirrors a single rule in src/lib/acodeApi.js so the JavaScript and native transports agree on lookalikes, malformed hosts, ports and non-API paths. Stored cookies can no longer override the Keychain token, and legacy dev tokens are not adopted silently. --- CHANGELOG.md | 1 + .../runner/lib/network/AppAPIHandler.swift | 2 +- .../lib/security/AppAuthentication.swift | 56 +++---- .../ios/runnerTests/AcodeAPIOrigins.json | 110 +++++++++++++ .../ios/runnerTests/AuthenticationTests.swift | 81 +++++++--- src/lib/acodeApi.js | 27 ++++ src/lib/apiFetch.js | 34 ++++ src/lib/polyfill.js | 24 +-- src/main.js | 3 +- src/platforms/ios/api.ts | 22 +-- tests/unit/boot.test.js | 12 +- tests/unit/fetchProtection.test.js | 145 ++++++++++++++++-- tests/unit/iosApi.test.ts | 24 ++- 13 files changed, 425 insertions(+), 116 deletions(-) create mode 100644 platforms/ios/runnerTests/AcodeAPIOrigins.json create mode 100644 src/lib/acodeApi.js create mode 100644 src/lib/apiFetch.js diff --git a/CHANGELOG.md b/CHANGELOG.md index e8c7e94e7f..527145df86 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## v1.13.7 +- iOS sign-in now shares one account across Acode subdomain APIs. Existing production sessions stay signed in; users with only a legacy development session need to sign in again. - Sponsorship supports iOS StoreKit purchases and recovers unfinished purchases on iOS and Android after restart, requesting missing sponsor details without another charge. - iOS terminal: npm shows fetch and install-script activity by default while retaining security audits. Local server links open in an isolated in-app preview, with visible errors if the preview cannot open. - System theme: dialog dimming now follows the current light or dark appearance. diff --git a/platforms/ios/runner/lib/network/AppAPIHandler.swift b/platforms/ios/runner/lib/network/AppAPIHandler.swift index 5b8d6b22ed..26696e12a5 100644 --- a/platforms/ios/runner/lib/network/AppAPIHandler.swift +++ b/platforms/ios/runner/lib/network/AppAPIHandler.swift @@ -96,7 +96,7 @@ final class AppAPIHandler { request.httpShouldHandleCookies = credentials && !trusted request.setValue(nil, forHTTPHeaderField: "Cookie") if credentials, trusted { - // A parent-domain cookie must not override the token for the selected environment. + // A stored cookie must not override the Keychain account token. var cookies = (HTTPCookieStorage.shared.cookies(for: url) ?? []).filter { $0.name != "token" } let token = try auth.token(for: url) if !token.isEmpty, let cookie = HTTPCookie(properties: [.name: "token", .value: token, .domain: url.host!, .path: "/", .secure: "TRUE"]) { cookies.append(cookie) } diff --git a/platforms/ios/runner/lib/security/AppAuthentication.swift b/platforms/ios/runner/lib/security/AppAuthentication.swift index bb2b54669f..c694fccf79 100644 --- a/platforms/ios/runner/lib/security/AppAuthentication.swift +++ b/platforms/ios/runner/lib/security/AppAuthentication.swift @@ -4,24 +4,21 @@ import WebKit struct AppAuthentication { static let origin = "https://acode.app" - static let hosts = ["acode.app", "dev.acode.app"] - // Services that share the acode.app sign-in without being sign-in hosts, mapped to their account host. - // Academy is a trusted production-only consumer of the production account token. - // Do not substitute a development account when the editor uses a dev API. - static let accountServices = ["academy.acode.app": "acode.app"] - static let apiHosts = hosts + accountServices.keys + static let signInHosts = ["acode.app", "dev.acode.app"] let secrets: SecretStore init(namespace: String = "acode_auth_secure") { secrets = SecretStore(namespace: namespace) } - static func accepts(_ url: URL) -> Bool { accepts(url, hosts: hosts) } + static func accepts(_ url: URL) -> Bool { accepts(url, allowSubdomains: false) } - static func acceptsAPI(_ url: URL) -> Bool { accepts(url, hosts: apiHosts) } + static func acceptsAPI(_ url: URL) -> Bool { accepts(url, allowSubdomains: true) } - // Account services may only set cookies for themselves, never for the shared parent domain. + // Only sign-in hosts may set parent-domain cookies; other services may set only their own. static func acceptsCookie(for domain: String, from host: String) -> Bool { - guard apiHosts.contains(domain) else { return false } - return host == domain || (hosts.contains(host) && host.hasSuffix("." + domain)) + let domain = domain.lowercased() + let host = host.lowercased() + guard isAPIHost(domain), isAPIHost(host) else { return false } + return host == domain || (signInHosts.contains(host) && host.hasSuffix("." + domain)) } func begin(baseURL: String, version: Int) throws -> URL { @@ -58,8 +55,8 @@ struct AppAuthentication { func token(for url: URL) throws -> String { guard Self.acceptsAPI(url) else { throw SecretFailure("Unsupported sign-in URL") } - let account = Self.accountServices[url.host!].flatMap { URL(string: "https://" + $0) } ?? url - return try secrets.get(Self.tokenKey(for: account)) + // Legacy dev tokens are not adopted: their issuer may differ from acode.app. + return try secrets.get("auth_token") } static func accountURL(baseURL: String) throws -> URL { @@ -70,10 +67,11 @@ struct AppAuthentication { } func save(_ token: String, for url: URL = URL(string: Self.origin)!) throws { + guard Self.accepts(url) else { throw SecretFailure("Unsupported sign-in URL") } guard !token.isEmpty, token.utf8.allSatisfy({ $0 == 0x21 || (0x23...0x2b).contains($0) || (0x2d...0x3a).contains($0) || (0x3c...0x5b).contains($0) || (0x5d...0x7e).contains($0) }) else { throw SecretFailure("Invalid sign-in token") } - try secrets.set(Self.tokenKey(for: url), value: token) + try secrets.set("auth_token", value: token) } func cancel() throws { try secrets.remove("pending_login") } @@ -81,13 +79,13 @@ struct AppAuthentication { @MainActor func synchronizeCookies(_ store: WKHTTPCookieStore) async throws { - for cookie in HTTPCookieStorage.shared.cookies ?? [] where cookie.name == "token" && Self.hosts.contains(cookie.domain.trimmingCharacters(in: CharacterSet(charactersIn: "."))) { + for cookie in HTTPCookieStorage.shared.cookies ?? [] where cookie.name == "token" && Self.signInHosts.contains(cookie.domain.trimmingCharacters(in: CharacterSet(charactersIn: "."))) { HTTPCookieStorage.shared.deleteCookie(cookie) } - for cookie in await store.allCookies() where cookie.name == "token" && Self.hosts.contains(cookie.domain.trimmingCharacters(in: CharacterSet(charactersIn: "."))) { + for cookie in await store.allCookies() where cookie.name == "token" && Self.signInHosts.contains(cookie.domain.trimmingCharacters(in: CharacterSet(charactersIn: "."))) { await store.deleteCookie(cookie) } - for host in Self.hosts { + for host in Self.signInHosts { let token = try token(for: URL(string: "https://" + host)!) if !token.isEmpty, let cookie = HTTPCookie(properties: [.name: "token", .value: token, .domain: host, .path: "/", .secure: "TRUE", .expires: Date.distantFuture, HTTPCookiePropertyKey("HttpOnly"): "TRUE", HTTPCookiePropertyKey("SameSite"): "None"]) { await store.setCookie(cookie) @@ -96,9 +94,9 @@ struct AppAuthentication { } } - static func baseURL(_ value: String) throws -> URL { try origin(value, hosts: hosts) } + static func baseURL(_ value: String) throws -> URL { try origin(value, allowSubdomains: false) } - static func apiOrigin(_ value: String) throws -> URL { try origin(value, hosts: apiHosts) } + static func apiOrigin(_ value: String) throws -> URL { try origin(value, allowSubdomains: true) } static func exchangeFailure(_ response: HTTPURLResponse) -> SecretFailure { if response.statusCode == 429 { @@ -112,19 +110,23 @@ struct AppAuthentication { return SecretFailure("The sign-in service is unavailable. Please try again later.") } - private static func accepts(_ url: URL, hosts: [String]) -> Bool { - url.scheme == "https" && hosts.contains(url.host ?? "") && (url.port == nil || url.port == 443) && url.user == nil && url.password == nil + private static func accepts(_ url: URL, allowSubdomains: Bool) -> Bool { + let host = url.host?.lowercased() ?? "" + let allowed = allowSubdomains ? isAPIHost(host) : signInHosts.contains(host) + return url.scheme == "https" && allowed && (url.port == nil || url.port == 443) && url.user == nil && url.password == nil } - private static func origin(_ value: String, hosts: [String]) throws -> URL { - guard let url = URL(string: value), accepts(url, hosts: hosts), ["", "/"].contains(url.path), url.query == nil, url.fragment == nil else { + private static func origin(_ value: String, allowSubdomains: Bool) throws -> URL { + guard let url = URL(string: value), accepts(url, allowSubdomains: allowSubdomains), ["", "/"].contains(url.path), url.query == nil, url.fragment == nil else { throw SecretFailure("Unsupported sign-in URL") } - return URL(string: "https://" + url.host!)! + return URL(string: "https://" + url.host!.lowercased())! } - private static func tokenKey(for url: URL) throws -> String { - guard accepts(url) else { throw SecretFailure("Unsupported sign-in URL") } - return url.host == "acode.app" ? "auth_token" : "auth_token_dev" + // Adding an Acode subdomain grants it the account token on HTTPS API calls. + // Keep this boundary aligned with src/lib/acodeApi.js. + private static func isAPIHost(_ host: String) -> Bool { + let host = host.lowercased() + return !host.hasPrefix(".") && !host.contains("..") && (host == "acode.app" || host.hasSuffix(".acode.app")) } } diff --git a/platforms/ios/runnerTests/AcodeAPIOrigins.json b/platforms/ios/runnerTests/AcodeAPIOrigins.json new file mode 100644 index 0000000000..d40cb4df09 --- /dev/null +++ b/platforms/ios/runnerTests/AcodeAPIOrigins.json @@ -0,0 +1,110 @@ +[ + { + "origin": "https://acode.app", + "accepted": true + }, + { + "origin": "https://dev.acode.app", + "accepted": true + }, + { + "origin": "https://academy.acode.app", + "accepted": true + }, + { + "origin": "https://service.acode.app", + "accepted": true + }, + { + "origin": "https://nested.service.acode.app", + "accepted": true + }, + { + "origin": "https://SERVICE.ACODE.APP", + "accepted": true + }, + { + "origin": "https://service.acode.app:443", + "accepted": true + }, + { + "origin": "https://example.com", + "accepted": false + }, + { + "origin": "https://evilacode.app", + "accepted": false + }, + { + "origin": "https://.acode.app", + "accepted": false + }, + { + "origin": "https://.service.acode.app", + "accepted": false + }, + { + "origin": "https://service..acode.app", + "accepted": false + }, + { + "origin": "https://service.acode.app.", + "accepted": false + }, + { + "origin": "http://service.acode.app", + "accepted": false + }, + { + "origin": "https://service.acode.app:8443", + "accepted": false + }, + { + "origin": "https://user:password@service.acode.app", + "accepted": false + }, + { + "origin": "https://acode.app.evil.test", + "accepted": false + }, + { + "origin": "http://acode.app", + "accepted": false + }, + { + "origin": "https://acode.app:8443", + "accepted": false + }, + { + "origin": "https://dev.acode.app.evil.test", + "accepted": false + }, + { + "origin": "http://dev.acode.app", + "accepted": false + }, + { + "origin": "https://dev.acode.app:8443", + "accepted": false + }, + { + "origin": "https://academy.acode.app.evil.test", + "accepted": false + }, + { + "origin": "https://service%2eacode.app", + "accepted": true + }, + { + "origin": "https://acode%2Eapp", + "accepted": true + }, + { + "origin": "https://acode.app%2Eevil.test", + "accepted": false + }, + { + "origin": "https://evil%2Etest%2Eacode.app", + "accepted": true + } +] diff --git a/platforms/ios/runnerTests/AuthenticationTests.swift b/platforms/ios/runnerTests/AuthenticationTests.swift index 2a2d4638e4..27a8e26817 100644 --- a/platforms/ios/runnerTests/AuthenticationTests.swift +++ b/platforms/ios/runnerTests/AuthenticationTests.swift @@ -69,30 +69,31 @@ final class AuthenticationTests: XCTestCase { } @MainActor - func testAPIRoutingKeepsDevelopmentAndProductionCredentialsSeparate() async throws { + func testAPIRoutingSharesTheAccountAcrossSignInHosts() async throws { let production = URL(string: "https://acode.app")! let development = URL(string: "https://dev.acode.app")! - let previous = (HTTPCookieStorage.shared.cookies ?? []).filter { $0.name == "token" && AppAuthentication.hosts.contains($0.domain.trimmingCharacters(in: CharacterSet(charactersIn: "."))) } + let previous = (HTTPCookieStorage.shared.cookies ?? []).filter { $0.name == "token" && AppAuthentication.signInHosts.contains($0.domain.trimmingCharacters(in: CharacterSet(charactersIn: "."))) } let unrelated = HTTPCookie(properties: [.name: "review-fixture-" + UUID().uuidString, .value: "other", .domain: "acode.app", .path: "/"])! HTTPCookieStorage.shared.setCookie(unrelated) defer { HTTPCookieStorage.shared.deleteCookie(unrelated) - for cookie in HTTPCookieStorage.shared.cookies ?? [] where cookie.name == "token" && AppAuthentication.hosts.contains(cookie.domain.trimmingCharacters(in: CharacterSet(charactersIn: "."))) { + for cookie in HTTPCookieStorage.shared.cookies ?? [] where cookie.name == "token" && AppAuthentication.signInHosts.contains(cookie.domain.trimmingCharacters(in: CharacterSet(charactersIn: "."))) { HTTPCookieStorage.shared.deleteCookie(cookie) } previous.forEach(HTTPCookieStorage.shared.setCookie) } try auth.save("production-token") - try auth.save("development-token", for: development) + try auth.save("shared-token", for: development) + XCTAssertEqual(try auth.token(for: production), "shared-token") let dataStore = WKWebsiteDataStore.nonPersistent() try await auth.synchronizeCookies(dataStore.httpCookieStore) let webCookies = await dataStore.httpCookieStore.allCookies().filter { $0.name == "token" } - XCTAssertEqual(Set(webCookies.map(\.domain)), Set(AppAuthentication.hosts)) + XCTAssertEqual(Set(webCookies.map(\.domain)), Set(AppAuthentication.signInHosts)) let api = AppAPIHandler(auth: auth) var source = URLRequest(url: URL(string: "acode://localhost/__api__/login?test=one%20two")!) source.setValue("include", forHTTPHeaderField: "X-Acode-Credentials") source.setValue("token=untrusted", forHTTPHeaderField: "Cookie") - for (origin, token) in [(production, "production-token"), (development, "development-token")] { + for (origin, token) in [(production, "shared-token"), (development, "shared-token")] { XCTAssertEqual((HTTPCookieStorage.shared.cookies(for: origin) ?? []).filter { $0.name == "token" }.map(\.value), [token]) source.setValue(origin.absoluteString, forHTTPHeaderField: "X-Acode-API-Origin") let request = try api.request(for: source) @@ -113,22 +114,46 @@ final class AuthenticationTests: XCTestCase { XCTAssertEqual(try auth.token(for: development), "") } - func testAccountServicesUseTheProductionAccountWithoutBecomingSignInHosts() throws { - let academy = URL(string: "https://academy.acode.app")! - try auth.save("production-token") - try auth.save("development-token", for: URL(string: "https://dev.acode.app")!) - XCTAssertEqual(try auth.token(for: academy), "production-token") - XCTAssertThrowsError(try auth.save("academy-token", for: academy)) - XCTAssertThrowsError(try auth.begin(baseURL: academy.absoluteString, version: 0)) - XCTAssertThrowsError(try AppAuthentication.apiOrigin("https://academy.acode.app.evil.test")) + func testAPIOriginsMatchSharedJavaScriptCases() throws { + let fixture = try XCTUnwrap(Bundle(for: Self.self).url(forResource: "AcodeAPIOrigins", withExtension: "json")) + let cases = try JSONDecoder().decode([APIOriginCase].self, from: Data(contentsOf: fixture)) + for item in cases { + if item.accepted { XCTAssertNoThrow(try AppAuthentication.apiOrigin(item.origin), item.origin) } + else { XCTAssertThrowsError(try AppAuthentication.apiOrigin(item.origin), item.origin) } + } + } + + func testSubdomainsShareTheAccountWithoutBecomingSignInHosts() throws { + let api = AppAPIHandler(auth: auth) var source = URLRequest(url: URL(string: "acode://localhost/__api__/v1/user/login")!) - source.setValue(academy.absoluteString, forHTTPHeaderField: "X-Acode-API-Origin") source.setValue("include", forHTTPHeaderField: "X-Acode-Credentials") - let request = try AppAPIHandler(auth: auth).request(for: source) - XCTAssertEqual(request.url?.absoluteString, "https://academy.acode.app/api/v1/user/login") - let tokens = (request.value(forHTTPHeaderField: "Cookie") ?? "").components(separatedBy: ";").map { $0.trimmingCharacters(in: .whitespaces) }.filter { $0.hasPrefix("token=") } - XCTAssertEqual(tokens, ["token=production-token"]) + try auth.save("account-token") + // Ignore tokens left by older builds that kept a separate dev account. + try auth.secrets.set("auth_token_dev", value: "legacy-development-token") + for host in ["acode.app", "dev.acode.app", "academy.acode.app", "service.acode.app", "nested.service.acode.app"] { + let origin = URL(string: "https://" + host)! + XCTAssertEqual(try auth.token(for: origin), "account-token") + source.setValue(origin.absoluteString, forHTTPHeaderField: "X-Acode-API-Origin") + let request = try api.request(for: source) + XCTAssertEqual(request.url?.absoluteString, origin.absoluteString + "/api/v1/user/login") + let tokens = (request.value(forHTTPHeaderField: "Cookie") ?? "").components(separatedBy: ";").map { $0.trimmingCharacters(in: .whitespaces) }.filter { $0.hasPrefix("token=") } + XCTAssertEqual(tokens, ["token=account-token"]) + if !AppAuthentication.signInHosts.contains(host) { + XCTAssertThrowsError(try auth.save("other-token", for: origin)) + XCTAssertThrowsError(try auth.begin(baseURL: origin.absoluteString, version: 0)) + } + } + source.setValue("omit", forHTTPHeaderField: "X-Acode-Credentials") + XCTAssertNil(try api.request(for: source).value(forHTTPHeaderField: "Cookie")) + for value in ["https://.acode.app", "https://service..acode.app", "https://evilacode.app", "https://service.acode.app.evil.test", "http://service.acode.app", "https://service.acode.app:8443", "https://user:pass@service.acode.app", "https://service.acode.app/path", "https://service.acode.app?host=other"] { + source.setValue(value, forHTTPHeaderField: "X-Acode-API-Origin") + XCTAssertThrowsError(try api.request(for: source)) + } + try auth.secrets.remove("auth_token") + XCTAssertEqual(try auth.token(for: URL(string: "https://dev.acode.app")!), "", "A legacy dev token is not silently promoted to the shared account") try auth.logout() + XCTAssertEqual(try auth.token(for: URL(string: "https://service.acode.app")!), "") + XCTAssertEqual(try auth.secrets.get("auth_token_dev"), "") } func testExchangeErrorsExplainRetryTimingAndExpiredSignIn() { @@ -146,7 +171,7 @@ final class AuthenticationTests: XCTestCase { HTTPCookieStorage.shared.deleteCookie(cookie) } } - for host in AppAuthentication.hosts { + for host in AppAuthentication.signInHosts { let origin = URL(string: "https://" + host)! let url = origin.appendingPathComponent("api/cookie") try auth.save("account-token", for: origin) @@ -185,14 +210,14 @@ final class AuthenticationTests: XCTestCase { XCTAssertFalse((HTTPCookieStorage.shared.cookies ?? []).contains { $0.name == name }) } - func testAccountServicesOnlyStoreTheirOwnCookies() { + func testAccountServicesOnlyStoreTheirOwnCookies() throws { let name = "academy-fixture-" + UUID().uuidString defer { for cookie in HTTPCookieStorage.shared.cookies ?? [] where cookie.name == name { HTTPCookieStorage.shared.deleteCookie(cookie) } } - let academy = URL(string: "https://academy.acode.app/api/cookie")! + let academy = URL(string: "https://NESTED.Service.ACODE.APP/api/cookie")! let parent = HTTPURLResponse(url: academy, statusCode: 200, httpVersion: nil, headerFields: ["Set-Cookie": "\(name)=parent; Domain=.acode.app; Path=/; Secure"])! AppAPIHandler.storeCookies(from: parent, credentials: true) XCTAssertFalse((HTTPCookieStorage.shared.cookies ?? []).contains { $0.name == name }) @@ -201,6 +226,16 @@ final class AuthenticationTests: XCTestCase { XCTAssertEqual((HTTPCookieStorage.shared.cookies(for: academy) ?? []).first { $0.name == name }?.value, "own") XCTAssertFalse((HTTPCookieStorage.shared.cookies(for: URL(string: "https://acode.app/api/cookie")!) ?? []).contains { $0.name == name }) XCTAssertTrue(AppAuthentication.acceptsCookie(for: "acode.app", from: "dev.acode.app")) - XCTAssertFalse(AppAuthentication.acceptsCookie(for: "acode.app", from: "academy.acode.app")) + XCTAssertTrue(AppAuthentication.acceptsCookie(for: "AcOdE.App", from: "DEV.ACODE.APP")) + XCTAssertTrue(AppAuthentication.acceptsCookie(for: "nested.service.acode.app", from: "NESTED.Service.ACODE.APP")) + XCTAssertEqual(try AppAuthentication.apiOrigin("https://SERVICE.ACODE.APP"), URL(string: "https://service.acode.app")) + XCTAssertFalse(AppAuthentication.acceptsCookie(for: "acode.app", from: "nested.service.acode.app")) + XCTAssertFalse(AppAuthentication.acceptsCookie(for: "service.acode.app", from: "nested.service.acode.app")) + XCTAssertFalse(AppAuthentication.acceptsCookie(for: "other.acode.app", from: "nested.service.acode.app")) } } + +private struct APIOriginCase: Decodable { + let origin: String + let accepted: Bool +} diff --git a/src/lib/acodeApi.js b/src/lib/acodeApi.js new file mode 100644 index 0000000000..4253ba531d --- /dev/null +++ b/src/lib/acodeApi.js @@ -0,0 +1,27 @@ +/** + * Every Acode subdomain is trusted with the account token on HTTPS API calls. + * Adding a subdomain grants that trust; mirror this rule in AppAuthentication.swift. + * @param {string | URL} value + * @param {string} [baseURL] + * @returns {URL | null} + */ +export default function parseAcodeAPIURL(value, baseURL) { + try { + const url = new URL(String(value), baseURL); + const host = url.hostname; + if ( + url.protocol !== "https:" || + (host !== "acode.app" && !host.endsWith(".acode.app")) || + host.startsWith(".") || + host.includes("..") || + url.port || + url.username || + url.password || + !(url.pathname === "/api" || url.pathname.startsWith("/api/")) + ) + return null; + return url; + } catch { + return null; + } +} diff --git a/src/lib/apiFetch.js b/src/lib/apiFetch.js new file mode 100644 index 0000000000..7803708955 --- /dev/null +++ b/src/lib/apiFetch.js @@ -0,0 +1,34 @@ +import parseAcodeAPIURL from "./acodeApi"; + +export default function installAPIFetch(target) { + if ( + Object.getOwnPropertyDescriptor(target, "fetch")?.configurable === false + ) { + target.console.warn( + "Acode left the existing fetch unchanged because it is non-configurable.", + ); + return; + } + const transport = target.fetch.bind(target); + const appFetch = function (input, options) { + // Preserve Acode's legacy credential behavior for string URLs only. + if ( + typeof input === "string" && + parseAcodeAPIURL(input, target.location.href) + ) { + options = { ...options, credentials: "include" }; + } + return transport(input, options); + }; + Object.defineProperty(target, "fetch", { + configurable: false, + enumerable: true, + get: () => appFetch, + // Warn instead of throwing so legacy wrappers do not break startup. + set() { + target.console.warn( + "Acode blocked an attempt to replace window.fetch. Use a local fetch wrapper instead.", + ); + }, + }); +} diff --git a/src/lib/polyfill.js b/src/lib/polyfill.js index d95c40808d..74af005909 100644 --- a/src/lib/polyfill.js +++ b/src/lib/polyfill.js @@ -1,24 +1,6 @@ -// automatically include credentials for acode.app API requests -(function () { - const transport = window.fetch.bind(window); - const appFetch = function (url, options) { - if (typeof url === "string" && url.includes("acode.app/api")) { - options = { ...options, credentials: "include" }; - } - return transport(url, options); - }; - Object.defineProperty(window, "fetch", { - configurable: false, - enumerable: true, - get: () => appFetch, - // Warn instead of throwing so legacy wrappers do not break startup. - set() { - console.warn( - "Acode blocked an attempt to replace window.fetch. Use a local fetch wrapper instead.", - ); - }, - }); -})(); +import installAPIFetch from "./apiFetch"; + +installAPIFetch(window); // polyfill for prepend diff --git a/src/main.js b/src/main.js index deef8da021..69b47d2f9e 100644 --- a/src/main.js +++ b/src/main.js @@ -44,6 +44,7 @@ import keyboardHandler, { keydownState } from "handlers/keyboard"; import quickToolsInit from "handlers/quickToolsInit"; import windowResize from "handlers/windowResize"; import acode from "lib/acode"; +import parseAcodeAPIURL from "lib/acodeApi"; import actionStack from "lib/actionStack"; import adRewards from "lib/adRewards"; import ajax from "lib/ajax"; @@ -99,7 +100,7 @@ ajax.response = (xhr) => { }; ajax.configure = (xhr, url) => { - if (url.includes("acode.app/api")) { + if (parseAcodeAPIURL(url, window.location.href)) { xhr.withCredentials = true; } }; diff --git a/src/platforms/ios/api.ts b/src/platforms/ios/api.ts index 6daff3ded6..e83605c417 100644 --- a/src/platforms/ios/api.ts +++ b/src/platforms/ios/api.ts @@ -1,3 +1,4 @@ +import parseAcodeAPIURL from "../../lib/acodeApi"; import installAPIXHR from "./apiXHR"; const responseURLHeader = "X-Acode-Response-URL"; @@ -50,21 +51,8 @@ function withRemoteURL( } function localURL(value: string) { - try { - const url = new URL(value, location.href); - if ( - ![ - "https://acode.app", - "https://dev.acode.app", - "https://academy.acode.app", - ].includes(url.origin) || - url.username || - url.password || - !(url.pathname === "/api" || url.pathname.startsWith("/api/")) - ) - return null; - return `acode://localhost/__api__/${url.pathname.slice(5)}${url.search}`; - } catch { - return null; - } + const url = parseAcodeAPIURL(value, location.href); + return url + ? `acode://localhost/__api__/${url.pathname.slice(5)}${url.search}` + : null; } diff --git a/tests/unit/boot.test.js b/tests/unit/boot.test.js index 097ea06527..907f2ae50d 100644 --- a/tests/unit/boot.test.js +++ b/tests/unit/boot.test.js @@ -29,13 +29,17 @@ test.each([ return { ok: response }; }); const sockets = []; - await vm.runInNewContext(source, { + let finishNative; + const nativeReady = new Promise((resolve) => { + finishNative = resolve; + }); + const boot = vm.runInNewContext(source, { __DEV_MODE__: dev, __DEV_HOST__: "192.168.1.2", __DEV_PORT__: "4000", __DEV_PROTO__: "https", location, - window: { location, nativeReady: Promise.resolve() }, + window: { location, nativeReady }, fetch, AbortController, console: { error: vi.fn() }, @@ -57,6 +61,10 @@ test.each([ }, }); await new Promise((resolve) => setImmediate(resolve)); + expect(loaded).toEqual([`${assetOrigin}/build/native.js`]); + finishNative(); + await boot; + await new Promise((resolve) => setImmediate(resolve)); expect(location.replace).not.toHaveBeenCalled(); expect(location.origin).toBe("https://localhost"); expect(loaded).toEqual( diff --git a/tests/unit/fetchProtection.test.js b/tests/unit/fetchProtection.test.js index 2a8dbb3185..d593edf13c 100644 --- a/tests/unit/fetchProtection.test.js +++ b/tests/unit/fetchProtection.test.js @@ -1,12 +1,9 @@ -import { readFileSync } from "node:fs"; import { Window } from "happy-dom"; import { afterEach, beforeEach, expect, test, vi } from "vitest"; +import parseAcodeAPIURL from "../../src/lib/acodeApi"; +import installAPIFetch from "../../src/lib/apiFetch"; import installAPITransport from "../../src/platforms/ios/api"; -const source = readFileSync( - new URL("../../src/lib/polyfill.js", import.meta.url), - "utf8", -); let window; let transport; let warning; @@ -15,6 +12,7 @@ beforeEach(() => { window = new Window({ url: "https://localhost/" }); transport = vi.fn(async () => new Response("authenticated")); window.fetch = transport; + vi.stubGlobal("location", window.location); warning = vi.spyOn(window.console, "warn").mockImplementation(() => {}); }); @@ -25,8 +23,13 @@ afterEach(async () => { }); test("plugins cannot replace, redefine or delete the host fetch transport", async () => { - window.eval(source); + installAPIFetch(window); const fetch = window.fetch; + installAPIFetch(window); + expect(warning).toHaveBeenCalledExactlyOnceWith( + "Acode left the existing fetch unchanged because it is non-configurable.", + ); + warning.mockClear(); // Legacy wrappers also assign in strict mode; they must not break startup. window.eval( '"use strict"; window.fetch = () => { throw Error("replaced"); };', @@ -60,18 +63,28 @@ test("plugins cannot replace, redefine or delete the host fetch transport", asyn }); }); -test("protects the already installed iOS transport and preserves authenticated API routing", async () => { +test("polyfill module protects the installed iOS transport and preserves API routing", async () => { for (const [name, value] of Object.entries({ window, location: window.location, XMLHttpRequest: window.XMLHttpRequest, Request: window.Request, Headers: window.Headers, + Element: window.Element, + Document: window.Document, + DocumentFragment: window.DocumentFragment, + CharacterData: window.CharacterData, + DocumentType: window.DocumentType, })) vi.stubGlobal(name, value); installAPITransport(); - window.eval(source); - for (const origin of ["https://acode.app", "https://dev.acode.app"]) { + await import("../../src/lib/polyfill"); + for (const origin of [ + "https://acode.app", + "https://dev.acode.app", + "https://service.acode.app", + "https://nested.service.acode.app", + ]) { const response = await window.fetch(`${origin}/api/login`, { cache: "no-store", }); @@ -81,4 +94,118 @@ test("protects the already installed iOS transport and preserves authenticated A expect(options.headers.get("X-Acode-Credentials")).toBe("include"); expect(await response.text()).toBe("authenticated"); } + const request = new window.Request("https://service.acode.app/api/login"); + await window.fetch(request); + expect( + transport.mock.calls.at(-1)[1].headers.get("X-Acode-Credentials"), + ).toBe("same-origin"); + await window.fetch(request, { credentials: "include" }); + expect( + transport.mock.calls.at(-1)[1].headers.get("X-Acode-Credentials"), + ).toBe("include"); + await window.fetch(request, { credentials: "omit" }); + expect( + transport.mock.calls.at(-1)[1].headers.get("X-Acode-Credentials"), + ).toBe("omit"); + await window.fetch(request.url, { credentials: "omit" }); + expect( + transport.mock.calls.at(-1)[1].headers.get("X-Acode-Credentials"), + ).toBe("include"); +}); + +test("does not force credentials on lookalikes, malformed hosts or non-API URLs", async () => { + installAPIFetch(window); + for (const url of [ + "https://evil.example/?next=acode.app/api", + "https://evilacode.app/api/login", + "https://.acode.app/api/login", + "https://service..acode.app/api/login", + "https://service.acode.app/api-other", + "http://service.acode.app/api/login", + "https://service.acode.app:8443/api/login", + ]) { + await window.fetch(url, { cache: "no-store" }); + expect(transport).toHaveBeenLastCalledWith(url, { cache: "no-store" }); + } + await window.fetch("https://SERVICE.ACODE.APP/api/login"); + expect(transport).toHaveBeenLastCalledWith( + "https://SERVICE.ACODE.APP/api/login", + { credentials: "include" }, + ); +}); + +test("preserves legacy Request and URL passthrough and forced credentials for strings", async () => { + installAPIFetch(window); + const request = new window.Request("https://service.acode.app/api/send", { + method: "POST", + body: "message", + headers: { "X-Test": "value" }, + }); + await window.fetch(request); + expect(transport).toHaveBeenLastCalledWith(request, undefined); + expect(await request.text()).toBe("message"); + expect(request.headers.get("X-Test")).toBe("value"); + + const anonymous = new window.Request("https://service.acode.app/api/login", { + credentials: "omit", + }); + await window.fetch(anonymous); + expect(transport).toHaveBeenLastCalledWith(anonymous, undefined); + await window.fetch(anonymous, { credentials: "include" }); + expect(transport).toHaveBeenLastCalledWith(anonymous, { + credentials: "include", + }); + await window.fetch(anonymous.url, { credentials: "omit" }); + expect(transport).toHaveBeenLastCalledWith(anonymous.url, { + credentials: "include", + }); + const url = new window.URL(anonymous.url); + await window.fetch(url, { credentials: "omit" }); + expect(transport).toHaveBeenLastCalledWith(url, { credentials: "omit" }); +}); + +test("relative API URLs require an explicit trusted base", () => { + expect(parseAcodeAPIURL("/api/login")).toBeNull(); + expect( + parseAcodeAPIURL("/api/login", "https://service.acode.app/")?.origin, + ).toBe("https://service.acode.app"); + expect(parseAcodeAPIURL("/api/login", "https://example.test/")).toBeNull(); +}); + +test("keeps fetching strings and URLs when the target has no Request constructor", async () => { + const target = { + fetch: transport, + location: window.location, + console: window.console, + }; + installAPIFetch(target); + for (const input of [ + "https://service.acode.app/api/login", + new window.URL("https://service.acode.app/api/login"), + ]) { + await target.fetch(input); + expect(transport).toHaveBeenLastCalledWith( + input, + typeof input === "string" ? { credentials: "include" } : undefined, + ); + } + await target.fetch("https://example.test/api/login", { credentials: "omit" }); + expect(transport).toHaveBeenLastCalledWith("https://example.test/api/login", { + credentials: "omit", + }); +}); + +test("warns and preserves an externally locked fetch", async () => { + const target = { console: window.console }; + Object.defineProperty(target, "fetch", { + value: transport, + configurable: false, + }); + installAPIFetch(target); + expect(target.fetch).toBe(transport); + expect(warning).toHaveBeenCalledExactlyOnceWith( + "Acode left the existing fetch unchanged because it is non-configurable.", + ); + await target.fetch("https://acode.app/api/login"); + expect(transport).toHaveBeenLastCalledWith("https://acode.app/api/login"); }); diff --git a/tests/unit/iosApi.test.ts b/tests/unit/iosApi.test.ts index ec5dcf46c3..b23499d783 100644 --- a/tests/unit/iosApi.test.ts +++ b/tests/unit/iosApi.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, expect, test, vi } from "vitest"; +import apiOrigins from "../../platforms/ios/runnerTests/AcodeAPIOrigins.json"; import installAPITransport from "../../src/platforms/ios/api"; let transport: ReturnType; @@ -72,26 +73,17 @@ afterEach(() => vi.unstubAllGlobals()); test("only routes Acode HTTPS API requests through the iOS transport", async () => { for (const url of [ - "https://example.com/api/login", - "https://acode.app.evil.test/api/login", - "http://acode.app/api/login", - "https://acode.app:8443/api/login", + ...apiOrigins + .filter(({ accepted }) => !accepted) + .map(({ origin }) => `${origin}/api/login`), "https://acode.app/plugins", - "https://dev.acode.app.evil.test/api/login", - "http://dev.acode.app/api/login", - "https://dev.acode.app:8443/api/login", - "https://academy.acode.app.evil.test/api/login", "https://academy.acode.app/cc/1", "acode://localhost/__cdvfile_cache__/file.txt", ]) { await window.fetch(url); expect(transport.mock.calls.at(-1)?.[0]).toBe(url); } - for (const origin of [ - "https://acode.app", - "https://dev.acode.app", - "https://academy.acode.app", - ]) { + for (const { origin } of apiOrigins.filter(({ accepted }) => accepted)) { await window.fetch(`${origin}/api/login?test=one%20two`, { credentials: "include", headers: { "X-Acode-API-Origin": "https://example.com" }, @@ -99,7 +91,9 @@ test("only routes Acode HTTPS API requests through the iOS transport", async () const [url, options] = transport.mock.calls.at(-1)!; expect(url).toBe("acode://localhost/__api__/login?test=one%20two"); expect(options.headers.get("X-Acode-Credentials")).toBe("include"); - expect(options.headers.get("X-Acode-API-Origin")).toBe(origin); + expect(options.headers.get("X-Acode-API-Origin")).toBe( + new URL(origin).origin, + ); const xhr = new XMLHttpRequest(); xhr.open("GET", `${origin}/api/login`); xhr.withCredentials = true; @@ -109,7 +103,7 @@ test("only routes Acode HTTPS API requests through the iOS transport", async () headers: Record; }; expect(state.openArgs[1]).toBe("acode://localhost/__api__/login"); - expect(state.headers["X-Acode-API-Origin"]).toBe(origin); + expect(state.headers["X-Acode-API-Origin"]).toBe(new URL(origin).origin); expect(state.headers["X-Acode-Credentials"]).toBe("include"); } }); From f8d630f297260c05e656f330e04ca908913a6c67 Mon Sep 17 00:00:00 2001 From: Ajit Kumar Date: Tue, 1 Dec 2026 13:38:07 +0530 Subject: [PATCH 4/6] fix: apply review findings across sponsorship, prompts and iOS - multiPrompt: validate on both click and Enter, include textareas in validation, value collection, sensitive clearing and autofocus, and add an optional description shown above the inputs - file browser: ignore a cancelled add-path prompt instead of raising an unhandled rejection or showing an empty error - sponsorship: map billing codes to localized messages, report a confirmed registration whose store finalization failed as pending instead of an error, and keep only the receipt fields needed for recovery - iap: claim asynchronous purchase errors only after the native store accepts the launch, so a failed launch cannot take over an active purchase - android: serialize purchase attempts in a synchronized state machine and reconcile a lost outcome after returning to the app - ios: open sign-in and account pages on https://acode.app only, so a legacy development session cannot replace the production account - ios: clear preview caches from an epoch cutoff and await shadow editor navigation instead of polling - add the new strings to every language file and cover the fixes with unit, UI and store-flavor tests --- .../src/store/java/com/foxdebug/iap/Iap.java | 102 +++++++--- .../java/com/foxdebug/iap/PurchaseFlow.kt | 70 +++++++ .../java/com/foxdebug/iap/PurchaseFlowTest.kt | 187 ++++++++++++++++++ .../lib/preview/PreviewViewController.swift | 3 +- .../lib/security/AppAuthentication.swift | 25 ++- .../ios/runnerTests/AuthenticationTests.swift | 37 ++-- .../ios/runnerTests/PlatformUITests.swift | 34 ++++ .../runnerTests/SponsorPurchaseTests.swift | 4 +- .../ios/runnerTests/WebShadowCaretTests.swift | 32 ++- src/dialogs/multiPrompt.js | 186 +++++++++-------- src/lang/ar-ye.json | 16 +- src/lang/az-az.json | 16 +- src/lang/be-by.json | 16 +- src/lang/bn-bd.json | 16 +- src/lang/cs-cz.json | 16 +- src/lang/de-de.json | 16 +- src/lang/en-us.json | 16 +- src/lang/es-sv.json | 16 +- src/lang/fr-fr.json | 16 +- src/lang/he-il.json | 16 +- src/lang/hi-in.json | 16 +- src/lang/hu-hu.json | 16 +- src/lang/id-id.json | 16 +- src/lang/index.d.ts | 14 ++ src/lang/ir-fa.json | 16 +- src/lang/it-it.json | 16 +- src/lang/ja-jp.json | 16 +- src/lang/ko-kr.json | 16 +- src/lang/ln-ln.json | 16 +- src/lang/ml-in.json | 16 +- src/lang/mm-unicode.json | 16 +- src/lang/mm-zawgyi.json | 16 +- src/lang/pl-pl.json | 16 +- src/lang/pt-br.json | 16 +- src/lang/pu-in.json | 16 +- src/lang/ru-ru.json | 16 +- src/lang/tl-ph.json | 16 +- src/lang/tr-tr.json | 16 +- src/lang/uk-ua.json | 16 +- src/lang/uz-uz.json | 16 +- src/lang/vi-vn.json | 16 +- src/lang/zh-cn.json | 16 +- src/lang/zh-hant.json | 16 +- src/lang/zh-tw.json | 16 +- src/native/iap.ts | 28 +-- src/native/types/iap.d.ts | 4 +- src/pages/fileBrowser/fileBrowser.js | 29 ++- src/pages/sponsor/billingError.js | 21 ++ src/pages/sponsor/details.js | 1 + src/pages/sponsor/pending.js | 31 ++- src/pages/sponsor/purchases.js | 15 +- src/pages/sponsor/recovery.js | 7 +- src/pages/sponsor/sponsor.js | 23 ++- tests/helpers/promptDialogs.js | 2 +- tests/helpers/sponsorPage.js | 13 +- tests/helpers/sponsorPurchases.js | 2 + tests/unit/iap.test.ts | 72 ++++++- tests/unit/promptDialogs.test.js | 71 +++++++ tests/unit/sponsorPage.test.js | 71 ++++++- tests/unit/sponsorRecovery.test.js | 35 +++- tests/unit/sponsorRecoveryPurchases.test.js | 55 ++++++ 61 files changed, 1468 insertions(+), 234 deletions(-) create mode 100644 platforms/android/app/src/store/java/com/foxdebug/iap/PurchaseFlow.kt create mode 100644 platforms/android/app/src/testStore/java/com/foxdebug/iap/PurchaseFlowTest.kt create mode 100644 src/pages/sponsor/billingError.js diff --git a/platforms/android/app/src/store/java/com/foxdebug/iap/Iap.java b/platforms/android/app/src/store/java/com/foxdebug/iap/Iap.java index 1172a3b083..3b93fe77b4 100644 --- a/platforms/android/app/src/store/java/com/foxdebug/iap/Iap.java +++ b/platforms/android/app/src/store/java/com/foxdebug/iap/Iap.java @@ -39,6 +39,7 @@ public class Iap extends Service { private WeakReference contextRef; private WeakReference activityRef; private Callback purchaseUpdated; + private final PurchaseFlow purchaseFlow = new PurchaseFlow(); public void initialize(BridgeContext bridgeContext) { super.initialize(bridgeContext); @@ -47,6 +48,16 @@ public void initialize(BridgeContext bridgeContext) { billingClient = getBillingClient(); } + @Override + public void onPause(boolean multitasking) { + purchaseFlow.onPause(); + } + + @Override + public void onResume(boolean multitasking) { + purchaseFlow.onResume(); + } + @Override public boolean execute( String action, @@ -113,12 +124,20 @@ public void onPurchasesUpdated( BillingResult billingResult, List purchases ) { + List updatedProducts = null; try { int responseCode = billingResult.getResponseCode(); + if (responseCode == BillingResponseCode.OK && (purchases == null || purchases.isEmpty())) { + responseCode = BillingResponseCode.ERROR; + } if (responseCode == BillingResponseCode.OK) { + updatedProducts = new ArrayList<>(); JSONArray result = new JSONArray(); - for (Purchase purchase : purchases) { - result.put(purchaseToJson(purchase)); + if (purchases != null) { + for (Purchase purchase : purchases) { + updatedProducts.addAll(purchase.getProducts()); + result.put(purchaseToJson(purchase)); + } } sendPurchasePluginResult( new Payload(Payload.Status.OK, result) @@ -129,9 +148,13 @@ public void onPurchasesUpdated( ); } } catch (JSONException e) { + updatedProducts = null; sendPurchasePluginResult( new Payload(Payload.Status.ERROR, e.getMessage()) ); + } finally { + // Queue the outcome before allowing another flow to own JS errors. + purchaseFlow.finishUpdate(updatedProducts); } } } @@ -258,11 +281,17 @@ public void onProductDetailsResponse( } private void purchase(String productIdOrJson, Callback callbackContext) { + if (productIdOrJson == null || productIdOrJson.trim().isEmpty()) { + callbackContext.error("Product ID cannot be null or empty"); + return; + } + Activity activity = activityRef.get(); + final PurchaseFlow.Attempt attempt = purchaseFlow.begin(productIdOrJson, activity != null && activity.hasWindowFocus()); + if (attempt == null) { + callbackContext.error(BillingResponseCode.DEVELOPER_ERROR); + return; + } try { - if (productIdOrJson == null || productIdOrJson.trim().isEmpty()) { - callbackContext.error("Product ID cannot be null or empty"); - return; - } final String productId = productIdOrJson; @@ -284,37 +313,50 @@ public void onProductDetailsResponse( BillingResult billingResult, QueryProductDetailsResult queryProductDetailsResult ) { - if (billingResult.getResponseCode() == BillingResponseCode.OK) { - List productDetailsList = queryProductDetailsResult.getProductDetailsList(); - if (!productDetailsList.isEmpty()) { - ProductDetails productDetails = productDetailsList.get(0); - BillingResult result = billingClient.launchBillingFlow( - activityRef.get(), - BillingFlowParams.newBuilder().setProductDetailsParamsList( - Arrays.asList( - BillingFlowParams.ProductDetailsParams.newBuilder() - .setProductDetails(productDetails) - .build() - ) - ).build() - ); - int responseCode = result.getResponseCode(); - if (responseCode == BillingResponseCode.OK) { - callbackContext.success(); + boolean launched = false; + try { + if (billingResult.getResponseCode() == BillingResponseCode.OK) { + List productDetailsList = queryProductDetailsResult.getProductDetailsList(); + if (!productDetailsList.isEmpty()) { + ProductDetails productDetails = productDetailsList.get(0); + if (!purchaseFlow.launch(attempt)) { + callbackContext.error(BillingResponseCode.ERROR); + return; + } + BillingResult result = billingClient.launchBillingFlow( + activityRef.get(), + BillingFlowParams.newBuilder().setProductDetailsParamsList( + Arrays.asList( + BillingFlowParams.ProductDetailsParams.newBuilder() + .setProductDetails(productDetails) + .build() + ) + ).build() + ); + int responseCode = result.getResponseCode(); + if (responseCode == BillingResponseCode.OK) { + launched = true; + callbackContext.success(); + } else { + callbackContext.error(responseCode); + } } else { - callbackContext.error(responseCode); + callbackContext.error("No product details found for: " + productId); } } else { - callbackContext.error("No product details found for: " + productId); + callbackContext.error(billingResult.getResponseCode()); } - } else { - callbackContext.error(billingResult.getResponseCode()); + } catch (Exception e) { + callbackContext.error("Purchase error: " + e.getMessage()); + } finally { + if (!launched) purchaseFlow.finish(attempt); } } } ); } catch (Exception e) { callbackContext.error("Purchase error: " + e.getMessage()); + purchaseFlow.finish(attempt); } } @@ -325,6 +367,7 @@ private void getPurchases(Callback callbackContext) { return; } + final PurchaseFlow.Attempt recoveryAttempt = purchaseFlow.recoveryAttempt(); QueryPurchasesParams params = QueryPurchasesParams.newBuilder() .setProductType(BillingClient.ProductType.INAPP) .build(); @@ -342,6 +385,11 @@ public void onQueryPurchasesResponse( for (Purchase purchase : purchasesList) { purchases.put(purchaseToJson(purchase)); } + Activity activity = activityRef.get(); + // Reconcile a lost outcome only after returning from the store UI. + if (recoveryAttempt != null) { + purchaseFlow.finishRecovery(recoveryAttempt, activity != null && activity.hasWindowFocus()); + } callbackContext.success(purchases); } else { callbackContext.error(responseCode); diff --git a/platforms/android/app/src/store/java/com/foxdebug/iap/PurchaseFlow.kt b/platforms/android/app/src/store/java/com/foxdebug/iap/PurchaseFlow.kt new file mode 100644 index 0000000000..08464c5300 --- /dev/null +++ b/platforms/android/app/src/store/java/com/foxdebug/iap/PurchaseFlow.kt @@ -0,0 +1,70 @@ +package com.foxdebug.iap + +class PurchaseFlow(private val now: () -> Long = { System.nanoTime() / 1_000_000 }) { + class Attempt(val productId: String, val startedAt: Long) + + private enum class Stage { QUERYING, LAUNCHED, LEFT_APP, RETURNED } + + private var active: Attempt? = null + private var reconciled: Attempt? = null + private var stage = Stage.QUERYING + + @Synchronized + fun begin(productId: String, hasWindowFocus: Boolean = false): Attempt? { + if (hasWindowFocus && stage == Stage.RETURNED && reconciled === active) active = null + if (lookupExpired()) active = null + if (active != null) return null + reconciled = null + stage = Stage.QUERYING + return Attempt(productId, now()).also { active = it } + } + + @Synchronized + fun isActive(attempt: Attempt): Boolean = active === attempt + + @Synchronized + fun launch(attempt: Attempt): Boolean { + if (active !== attempt) return false + if (lookupExpired()) { + active = null + return false + } + stage = Stage.LAUNCHED + return true + } + + @Synchronized + fun onPause() { + reconciled = null + if (stage == Stage.LAUNCHED || stage == Stage.RETURNED) stage = Stage.LEFT_APP + } + + @Synchronized + fun onResume() { + if (stage == Stage.LEFT_APP) stage = Stage.RETURNED + } + + @Synchronized + fun recoveryAttempt(): Attempt? = active?.takeIf { stage == Stage.RETURNED } + + @Synchronized + fun finishRecovery(attempt: Attempt, hasWindowFocus: Boolean) { + if (active !== attempt || stage != Stage.RETURNED) return + if (hasWindowFocus) active = null + else reconciled = attempt + } + + @Synchronized + fun finish(attempt: Attempt) { + if (active === attempt) active = null + } + + @Synchronized + fun finishUpdate(productIds: List?) { + if (productIds.isNullOrEmpty() || active?.productId in productIds) active = null + } + + // A lookup can expire; an open store sheet must never be unlocked by a timer. + private fun lookupExpired(): Boolean = + stage == Stage.QUERYING && active?.let { now() - it.startedAt >= 30_000 } == true +} diff --git a/platforms/android/app/src/testStore/java/com/foxdebug/iap/PurchaseFlowTest.kt b/platforms/android/app/src/testStore/java/com/foxdebug/iap/PurchaseFlowTest.kt new file mode 100644 index 0000000000..cc76f0887b --- /dev/null +++ b/platforms/android/app/src/testStore/java/com/foxdebug/iap/PurchaseFlowTest.kt @@ -0,0 +1,187 @@ +package com.foxdebug.iap + +import java.util.concurrent.Callable +import java.util.concurrent.Executors +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class PurchaseFlowTest { + @Test + fun concurrentRequestsHaveOnlyOneOwner() { + val flow = PurchaseFlow() + val pool = Executors.newFixedThreadPool(2) + try { + val attempts = pool.invokeAll(listOf( + Callable { flow.begin("gold") }, + Callable { flow.begin("crystal") } + )).mapNotNull { it.get() } + assertEquals(1, attempts.size) + assertTrue(flow.isActive(attempts.single())) + assertNull(flow.begin("acode_pro_new")) + } finally { + pool.shutdownNow() + } + } + + @Test + fun failedLookupOrLaunchReleasesOnlyItsOwnAttempt() { + val flow = PurchaseFlow() + val first = requireNotNull(flow.begin("gold")) + flow.finish(first) + val second = requireNotNull(flow.begin("gold")) + flow.finish(first) + assertFalse(flow.isActive(first)) + assertTrue(flow.isActive(second)) + assertNull(flow.begin("crystal")) + flow.finish(second) + assertNotNull(flow.begin("crystal")) + } + + @Test + fun onlyMatchingPurchaseUpdatesReleaseTheActiveFlow() { + val flow = PurchaseFlow() + val attempt = requireNotNull(flow.begin("gold")) + assertTrue(flow.launch(attempt)) + flow.finishUpdate(listOf("unrelated")) + assertTrue(flow.isActive(attempt)) + assertNull(flow.begin("crystal")) + // Purchased and pending approvals both deliver product IDs. + flow.finishUpdate(listOf("gold")) + assertFalse(flow.isActive(attempt)) + assertNotNull(flow.begin("crystal")) + } + + @Test + fun cancellationOrStoreErrorAllowsAnotherPurchase() { + val flow = PurchaseFlow() + val attempt = requireNotNull(flow.begin("gold")) + flow.finishUpdate(null) + assertFalse(flow.isActive(attempt)) + assertNotNull(flow.begin("crystal")) + } + + @Test + fun emptyPurchaseUpdateReleasesTheFlow() { + val flow = PurchaseFlow() + val attempt = requireNotNull(flow.begin("gold")) + assertTrue(flow.launch(attempt)) + flow.finishUpdate(emptyList()) + assertFalse(flow.isActive(attempt)) + assertNotNull(flow.begin("crystal")) + } + + @Test + fun stalledLookupCanBeRetriedWithoutLaunchingItsLateResponse() { + var time = 0L + val flow = PurchaseFlow { time } + val first = requireNotNull(flow.begin("gold")) + time = 29_999 + assertNull(flow.begin("crystal")) + time = 30_000 + val second = requireNotNull(flow.begin("crystal")) + assertFalse(flow.launch(first)) + flow.finish(first) + assertTrue(flow.isActive(second)) + assertTrue(flow.launch(second)) + } + + @Test + fun expiredLookupCannotLaunchEvenBeforeAnotherAttemptStarts() { + var time = 0L + val flow = PurchaseFlow { time } + val attempt = requireNotNull(flow.begin("gold")) + time = 30_000 + assertFalse(flow.launch(attempt)) + assertNotNull(flow.begin("gold")) + } + + @Test + fun launchedSheetWaitsForReturnAndReconciliationInsteadOfExpiring() { + var time = 0L + val flow = PurchaseFlow { time } + val attempt = requireNotNull(flow.begin("gold")) + assertTrue(flow.launch(attempt)) + time = 60_000 + assertNull(flow.begin("crystal")) + flow.onResume() + assertNull(flow.recoveryAttempt()) + flow.onPause() + assertNull(flow.recoveryAttempt()) + flow.finishRecovery(attempt, true) + assertTrue(flow.isActive(attempt)) + flow.onResume() + assertEquals(attempt, flow.recoveryAttempt()) + assertNull(flow.begin("crystal")) + flow.finishRecovery(attempt, true) + assertNotNull(flow.begin("crystal")) + } + + @Test + fun oldReconciliationCannotReleaseANewerFlow() { + val flow = PurchaseFlow() + val first = requireNotNull(flow.begin("gold")) + flow.launch(first) + flow.onPause() + flow.onResume() + val snapshot = requireNotNull(flow.recoveryAttempt()) + flow.finishUpdate(null) + val second = requireNotNull(flow.begin("gold")) + flow.launch(second) + flow.onPause() + flow.onResume() + flow.finishRecovery(snapshot, true) + assertTrue(flow.isActive(second)) + assertNull(flow.begin("crystal")) + } + + @Test + fun recoveryBeforeWindowFocusAllowsTheNextFocusedPurchase() { + val flow = PurchaseFlow() + val attempt = requireNotNull(flow.begin("gold")) + flow.launch(attempt) + flow.onPause() + flow.onResume() + flow.finishRecovery(requireNotNull(flow.recoveryAttempt()), false) + assertTrue(flow.isActive(attempt)) + assertNull(flow.begin("crystal", false)) + assertNotNull(flow.begin("crystal", true)) + } + + @Test + fun leavingAgainRequiresFreshReconciliation() { + val flow = PurchaseFlow() + val attempt = requireNotNull(flow.begin("gold")) + flow.launch(attempt) + flow.onPause() + flow.onResume() + flow.finishRecovery(attempt, false) + flow.onPause() + flow.onResume() + assertNull(flow.begin("crystal", true)) + flow.finishRecovery(attempt, true) + assertNotNull(flow.begin("crystal", true)) + } + + @Test + fun deferredReconciliationCannotReleaseANewerSheet() { + val flow = PurchaseFlow() + val first = requireNotNull(flow.begin("gold")) + flow.launch(first) + flow.onPause() + flow.onResume() + flow.finishRecovery(first, false) + flow.finishUpdate(null) + val second = requireNotNull(flow.begin("gold", true)) + flow.launch(second) + flow.onPause() + flow.onResume() + flow.finishRecovery(first, false) + assertNull(flow.begin("crystal", true)) + assertTrue(flow.isActive(second)) + } + +} diff --git a/platforms/ios/runner/lib/preview/PreviewViewController.swift b/platforms/ios/runner/lib/preview/PreviewViewController.swift index 97d5d3ce25..6b5629945f 100644 --- a/platforms/ios/runner/lib/preview/PreviewViewController.swift +++ b/platforms/ios/runner/lib/preview/PreviewViewController.swift @@ -116,7 +116,8 @@ final class PreviewViewController: UIViewController { func prepareNavigation(_ action: @escaping @MainActor @Sendable () -> Void) { guard !isClosed else { return } if disableCache { - webView.configuration.websiteDataStore.removeData(ofTypes: [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache, WKWebsiteDataTypeFetchCache], modifiedSince: .distantPast) { [weak self] in + // iOS 18 can retain cached responses when the cutoff is .distantPast. + webView.configuration.websiteDataStore.removeData(ofTypes: [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache, WKWebsiteDataTypeFetchCache], modifiedSince: Date(timeIntervalSince1970: 0)) { [weak self] in guard let self, !self.isClosed else { return } action() } diff --git a/platforms/ios/runner/lib/security/AppAuthentication.swift b/platforms/ios/runner/lib/security/AppAuthentication.swift index c694fccf79..b0940434b1 100644 --- a/platforms/ios/runner/lib/security/AppAuthentication.swift +++ b/platforms/ios/runner/lib/security/AppAuthentication.swift @@ -4,7 +4,7 @@ import WebKit struct AppAuthentication { static let origin = "https://acode.app" - static let signInHosts = ["acode.app", "dev.acode.app"] + static let accountHosts = ["acode.app", "dev.acode.app"] let secrets: SecretStore init(namespace: String = "acode_auth_secure") { secrets = SecretStore(namespace: namespace) } @@ -13,16 +13,16 @@ struct AppAuthentication { static func acceptsAPI(_ url: URL) -> Bool { accepts(url, allowSubdomains: true) } - // Only sign-in hosts may set parent-domain cookies; other services may set only their own. + // Only account hosts may set parent-domain cookies; other services may set only their own. static func acceptsCookie(for domain: String, from host: String) -> Bool { let domain = domain.lowercased() let host = host.lowercased() guard isAPIHost(domain), isAPIHost(host) else { return false } - return host == domain || (signInHosts.contains(host) && host.hasSuffix("." + domain)) + return host == domain || (accountHosts.contains(host) && host.hasSuffix("." + domain)) } func begin(baseURL: String, version: Int) throws -> URL { - let base = try Self.baseURL(baseURL) + let base = try Self.accountOrigin(baseURL) let state = try SecureToken.generate(bytes: 24) let verifier = try SecureToken.generate() let challenge = SHA256.hash(data: Data(verifier.utf8)).map { String(format: "%02x", $0) }.joined() @@ -60,7 +60,7 @@ struct AppAuthentication { } static func accountURL(baseURL: String) throws -> URL { - let base = try Self.baseURL(baseURL) + let base = try Self.accountOrigin(baseURL) var url = URLComponents(url: base.appendingPathComponent("profile/edit"), resolvingAgainstBaseURL: false)! url.queryItems = [URLQueryItem(name: "src", value: "ios")] return url.url! @@ -79,13 +79,13 @@ struct AppAuthentication { @MainActor func synchronizeCookies(_ store: WKHTTPCookieStore) async throws { - for cookie in HTTPCookieStorage.shared.cookies ?? [] where cookie.name == "token" && Self.signInHosts.contains(cookie.domain.trimmingCharacters(in: CharacterSet(charactersIn: "."))) { + for cookie in HTTPCookieStorage.shared.cookies ?? [] where cookie.name == "token" && Self.accountHosts.contains(cookie.domain.trimmingCharacters(in: CharacterSet(charactersIn: "."))) { HTTPCookieStorage.shared.deleteCookie(cookie) } - for cookie in await store.allCookies() where cookie.name == "token" && Self.signInHosts.contains(cookie.domain.trimmingCharacters(in: CharacterSet(charactersIn: "."))) { + for cookie in await store.allCookies() where cookie.name == "token" && Self.accountHosts.contains(cookie.domain.trimmingCharacters(in: CharacterSet(charactersIn: "."))) { await store.deleteCookie(cookie) } - for host in Self.signInHosts { + for host in Self.accountHosts { let token = try token(for: URL(string: "https://" + host)!) if !token.isEmpty, let cookie = HTTPCookie(properties: [.name: "token", .value: token, .domain: host, .path: "/", .secure: "TRUE", .expires: Date.distantFuture, HTTPCookiePropertyKey("HttpOnly"): "TRUE", HTTPCookiePropertyKey("SameSite"): "None"]) { await store.setCookie(cookie) @@ -110,9 +110,16 @@ struct AppAuthentication { return SecretFailure("The sign-in service is unavailable. Please try again later.") } + private static func accountOrigin(_ value: String) throws -> URL { + let requested = try apiOrigin(value) + guard accountHosts.contains(requested.host!) else { throw SecretFailure("Unsupported sign-in URL") } + // All account entry points use the same issuer as the shared Keychain token. + return URL(string: origin)! + } + private static func accepts(_ url: URL, allowSubdomains: Bool) -> Bool { let host = url.host?.lowercased() ?? "" - let allowed = allowSubdomains ? isAPIHost(host) : signInHosts.contains(host) + let allowed = allowSubdomains ? isAPIHost(host) : host == "acode.app" return url.scheme == "https" && allowed && (url.port == nil || url.port == 443) && url.user == nil && url.password == nil } diff --git a/platforms/ios/runnerTests/AuthenticationTests.swift b/platforms/ios/runnerTests/AuthenticationTests.swift index 27a8e26817..fea057b070 100644 --- a/platforms/ios/runnerTests/AuthenticationTests.swift +++ b/platforms/ios/runnerTests/AuthenticationTests.swift @@ -29,7 +29,8 @@ final class AuthenticationTests: XCTestCase { let url = try auth.begin(baseURL: origin, version: 1011) let items = try XCTUnwrap(URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems) let values = Dictionary(uniqueKeysWithValues: items.map { ($0.name, $0.value!) }) - XCTAssertEqual(url.host, URL(string: origin)?.host) + XCTAssertEqual(url.host, "acode.app") + XCTAssertEqual(try AppAuthentication.accountURL(baseURL: origin).absoluteString, "https://acode.app/profile/edit?src=ios") XCTAssertEqual(url.path, "/login") XCTAssertEqual(values["authFlow"], "app-code") XCTAssertEqual(values["redirect"], "app") @@ -39,7 +40,7 @@ final class AuthenticationTests: XCTestCase { let callback = URL(string: "acode://auth/callback?state=\(values["state"]!)&code=test-code")! let request = try auth.consume(callback) let payload = try XCTUnwrap(JSONSerialization.jsonObject(with: request.httpBody!) as? [String: String]) - XCTAssertEqual(request.url?.absoluteString, origin + "/api/user/app-token/exchange") + XCTAssertEqual(request.url?.absoluteString, AppAuthentication.origin + "/api/user/app-token/exchange") XCTAssertEqual(request.httpMethod, "POST") XCTAssertEqual(payload["code"], "test-code") XCTAssertEqual(payload["state"], values["state"]) @@ -51,6 +52,16 @@ final class AuthenticationTests: XCTestCase { } } + func testLegacyDevelopmentExchangeCannotReplaceTheSharedAccount() throws { + try auth.save("production-token") + let pending = try JSONSerialization.data(withJSONObject: ["state": "fixture-state", "verifier": "fixture-verifier", "origin": "https://dev.acode.app"]) + try auth.secrets.set("pending_login", value: String(decoding: pending, as: UTF8.self)) + let callback = URL(string: "acode://auth/callback?state=fixture-state&code=development-code")! + XCTAssertThrowsError(try auth.consume(callback)) + XCTAssertEqual(try auth.token(for: URL(string: AppAuthentication.origin)!), "production-token") + XCTAssertNoThrow(try auth.begin(baseURL: "https://dev.acode.app", version: 1)) + } + func testRejectsForgedCallbacksUntrustedOriginsAndInvalidCookieTokens() throws { for value in ["http://acode.app", "https://acode.app.evil.test", "https://acode.app:8443", "https://user@acode.app", "https://acode.app/path", "http://dev.acode.app", "https://dev.acode.app.evil.test", "https://dev.acode.app:8443", "https://dev.acode.app?next=other"] { XCTAssertThrowsError(try auth.begin(baseURL: value, version: 1)) @@ -69,31 +80,31 @@ final class AuthenticationTests: XCTestCase { } @MainActor - func testAPIRoutingSharesTheAccountAcrossSignInHosts() async throws { + func testAPIRoutingSharesTheAccountAcrossAccountHosts() async throws { let production = URL(string: "https://acode.app")! let development = URL(string: "https://dev.acode.app")! - let previous = (HTTPCookieStorage.shared.cookies ?? []).filter { $0.name == "token" && AppAuthentication.signInHosts.contains($0.domain.trimmingCharacters(in: CharacterSet(charactersIn: "."))) } + let previous = (HTTPCookieStorage.shared.cookies ?? []).filter { $0.name == "token" && AppAuthentication.accountHosts.contains($0.domain.trimmingCharacters(in: CharacterSet(charactersIn: "."))) } let unrelated = HTTPCookie(properties: [.name: "review-fixture-" + UUID().uuidString, .value: "other", .domain: "acode.app", .path: "/"])! HTTPCookieStorage.shared.setCookie(unrelated) defer { HTTPCookieStorage.shared.deleteCookie(unrelated) - for cookie in HTTPCookieStorage.shared.cookies ?? [] where cookie.name == "token" && AppAuthentication.signInHosts.contains(cookie.domain.trimmingCharacters(in: CharacterSet(charactersIn: "."))) { + for cookie in HTTPCookieStorage.shared.cookies ?? [] where cookie.name == "token" && AppAuthentication.accountHosts.contains(cookie.domain.trimmingCharacters(in: CharacterSet(charactersIn: "."))) { HTTPCookieStorage.shared.deleteCookie(cookie) } previous.forEach(HTTPCookieStorage.shared.setCookie) } try auth.save("production-token") - try auth.save("shared-token", for: development) - XCTAssertEqual(try auth.token(for: production), "shared-token") + XCTAssertThrowsError(try auth.save("development-token", for: development)) + XCTAssertEqual(try auth.token(for: production), "production-token") let dataStore = WKWebsiteDataStore.nonPersistent() try await auth.synchronizeCookies(dataStore.httpCookieStore) let webCookies = await dataStore.httpCookieStore.allCookies().filter { $0.name == "token" } - XCTAssertEqual(Set(webCookies.map(\.domain)), Set(AppAuthentication.signInHosts)) + XCTAssertEqual(Set(webCookies.map(\.domain)), Set(AppAuthentication.accountHosts)) let api = AppAPIHandler(auth: auth) var source = URLRequest(url: URL(string: "acode://localhost/__api__/login?test=one%20two")!) source.setValue("include", forHTTPHeaderField: "X-Acode-Credentials") source.setValue("token=untrusted", forHTTPHeaderField: "Cookie") - for (origin, token) in [(production, "shared-token"), (development, "shared-token")] { + for (origin, token) in [(production, "production-token"), (development, "production-token")] { XCTAssertEqual((HTTPCookieStorage.shared.cookies(for: origin) ?? []).filter { $0.name == "token" }.map(\.value), [token]) source.setValue(origin.absoluteString, forHTTPHeaderField: "X-Acode-API-Origin") let request = try api.request(for: source) @@ -138,8 +149,10 @@ final class AuthenticationTests: XCTestCase { XCTAssertEqual(request.url?.absoluteString, origin.absoluteString + "/api/v1/user/login") let tokens = (request.value(forHTTPHeaderField: "Cookie") ?? "").components(separatedBy: ";").map { $0.trimmingCharacters(in: .whitespaces) }.filter { $0.hasPrefix("token=") } XCTAssertEqual(tokens, ["token=account-token"]) - if !AppAuthentication.signInHosts.contains(host) { + if host != "acode.app" { XCTAssertThrowsError(try auth.save("other-token", for: origin)) + } + if !AppAuthentication.accountHosts.contains(host) { XCTAssertThrowsError(try auth.begin(baseURL: origin.absoluteString, version: 0)) } } @@ -171,10 +184,10 @@ final class AuthenticationTests: XCTestCase { HTTPCookieStorage.shared.deleteCookie(cookie) } } - for host in AppAuthentication.signInHosts { + for host in AppAuthentication.accountHosts { let origin = URL(string: "https://" + host)! let url = origin.appendingPathComponent("api/cookie") - try auth.save("account-token", for: origin) + try auth.save("account-token") var source = URLRequest(url: URL(string: "acode://localhost/__api__/cookie")!) source.setValue(origin.absoluteString, forHTTPHeaderField: "X-Acode-API-Origin") source.setValue("include", forHTTPHeaderField: "X-Acode-Credentials") diff --git a/platforms/ios/runnerTests/PlatformUITests.swift b/platforms/ios/runnerTests/PlatformUITests.swift index 11e424522a..d396c62422 100644 --- a/platforms/ios/runnerTests/PlatformUITests.swift +++ b/platforms/ios/runnerTests/PlatformUITests.swift @@ -4,6 +4,40 @@ import WebKit @MainActor final class PlatformUITests: BridgeTestCase { + func testMultiPromptTextareaValidationValuesAndDismissal() async throws { + let webView = try await editorWebView() + let result = try await webView.callAsyncJavaScript(#""" + const stack=acode.require('actionStack'); + const initialDepth=stack.length; + const results=[]; + for(const method of ['click','submit','cancel','back','clear']) { + stack.setMark(); + let settled=false; + const pending=acode.multiPrompt('Textarea regression', [{id:'note',type:'textarea',required:true,sensitive:true,autofocus:true}]).then(value=>{settled=true;return value},()=>{settled=true;return null}); + const form=document.querySelector('.prompt.multi:not(.hide)'); + const field=form.querySelector('textarea'); + if(document.activeElement!==field)throw Error('Textarea did not receive focus'); + const submit=()=>method==='click'?form.querySelector('button[type=submit]').click():form.dispatchEvent(new Event('submit',{bubbles:true,cancelable:true})); + submit(); + await Promise.resolve(); + if(settled||!form.querySelector('.error-msg')?.textContent||form.classList.contains('hide'))throw Error('Required textarea accepted empty input'); + field.value='Private\ntext'; + if(method==='click'||method==='submit')submit(); + else if(method==='cancel')form.querySelector('button[type=button]').click(); + else if(method==='back')await stack.pop(); + else stack.clearFromMark(); + const value=await Promise.race([pending,new Promise((resolve,reject)=>setTimeout(()=>reject(Error('Unsettled '+method)),2000))]); + if((method==='click'||method==='submit')&&value?.note!=='Private\ntext')throw Error('Textarea value was lost'); + if(field.value!==''||stack.length!==initialDepth)throw Error('Dialog cleanup failed: '+method); + results.push(method); + stack.clearFromMark(); + await new Promise(resolve=>setTimeout(resolve,350)); + } + return results; + """#, arguments: [:], in: nil, contentWorld: .page) as? [String] + XCTAssertEqual(result, ["click", "submit", "cancel", "back", "clear"]) + } + func testCoveredEditorReturnsWithItsDocumentAndScrollPosition() async throws { let webView = try await editorWebView() let result = try await webView.callAsyncJavaScript(""" diff --git a/platforms/ios/runnerTests/SponsorPurchaseTests.swift b/platforms/ios/runnerTests/SponsorPurchaseTests.swift index a02b85bc7c..8b2cf81713 100644 --- a/platforms/ios/runnerTests/SponsorPurchaseTests.swift +++ b/platforms/ios/runnerTests/SponsorPurchaseTests.swift @@ -121,11 +121,9 @@ final class SponsorPurchaseTests: BridgeTestCase { try await wait(webView, "!!document.querySelector('.prompt.multi:not(.hide) input')") let page = try await webView.evaluateJavaScript("!!document.querySelector('#sponsor-page')") as? Bool XCTAssertEqual(page, false) - _ = try await webView.evaluateJavaScript("document.querySelector('.prompt.multi:not(.hide) .help').click()") - let message = try await webView.evaluateJavaScript("document.querySelector('.prompt.alert:not(.hide)').textContent") as? String + let message = try await webView.evaluateJavaScript("document.querySelector('.prompt.multi:not(.hide) .message > p').textContent") as? String XCTAssertTrue(message?.contains("not be charged again") == true) _ = try await webView.evaluateJavaScript(""" - document.querySelector('.prompt.alert:not(.hide) button').click(); const input=document.querySelector('.prompt.multi:not(.hide) input'); input.value='Recovered Sponsor';input.dispatchEvent(new Event('input',{bubbles:true})); document.querySelector('.prompt.multi:not(.hide) button[type="submit"]').click(); diff --git a/platforms/ios/runnerTests/WebShadowCaretTests.swift b/platforms/ios/runnerTests/WebShadowCaretTests.swift index 83b560a72f..c96d9cead5 100644 --- a/platforms/ios/runnerTests/WebShadowCaretTests.swift +++ b/platforms/ios/runnerTests/WebShadowCaretTests.swift @@ -24,11 +24,17 @@ final class WebShadowCaretTests: BridgeTestCase { configuration.websiteDataStore = .nonPersistent() WebShadowCaret.install(on: configuration.userContentController) let view = WKWebView(frame: CGRect(x: 0, y: 0, width: 400, height: 600), configuration: configuration) + let loaded = expectation(description: "Shadow editor fixture finished loading") + let navigation = ShadowCaretNavigation(loaded: loaded) + view.navigationDelegate = navigation + defer { view.navigationDelegate = nil; view.stopLoading() } view.loadHTMLString("", baseURL: nil) - for _ in 0..<100 { - if !view.isLoading, - (try? await view.evaluateJavaScript("document.querySelector('iframe')?.contentDocument?.readyState === 'complete'")) as? Bool == true { break } - try await Task.sleep(for: .milliseconds(50)) + await fulfillment(of: [loaded], timeout: 30) + guard let navigationResult = navigation.result else { return } + try navigationResult.get() + guard (try await view.evaluateJavaScript("document.querySelector('iframe')?.contentDocument?.readyState === 'complete'")) as? Bool == true else { + XCTFail("Shadow editor iframe did not finish loading") + return } let script = """ (() => { @@ -88,3 +94,21 @@ final class WebShadowCaretTests: BridgeTestCase { XCTAssertEqual(result, true) } } + +@MainActor +private final class ShadowCaretNavigation: NSObject, WKNavigationDelegate { + let loaded: XCTestExpectation + private(set) var result: Result? + + init(loaded: XCTestExpectation) { self.loaded = loaded } + + func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { finish(.success(())) } + func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { finish(.failure(error)) } + func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { finish(.failure(error)) } + + private func finish(_ result: Result) { + guard self.result == nil else { return } + self.result = result + loaded.fulfill() + } +} diff --git a/src/dialogs/multiPrompt.js b/src/dialogs/multiPrompt.js index b02ff55016..5b84793610 100644 --- a/src/dialogs/multiPrompt.js +++ b/src/dialogs/multiPrompt.js @@ -32,97 +32,57 @@ let nextPromptId = 0; * @param {string} message Message * @param {Array>} inputs Inputs * @param {String} help Help text + * @param {string} [description] Text shown above the inputs * @returns {Promise} */ -export default function multiPrompt(message, inputs, help) { +export default function multiPrompt(message, inputs, help, description) { const actionId = `multi-prompt-${++nextPromptId}`; return new Promise((resolve, reject) => { - const $title = tag("div", { - className: "title", - child: tag("span", { - textContent: message, - }), - style: { - justifyContent: "space-between", - }, - }); - const $body = tag("div", { - className: "message scroll", - style: { - fontSize: "1rem", - }, - }); - const okBtn = tag("button", { - type: "submit", - textContent: strings.ok, - onclick: function (e) { - e.preventDefault(); - e.stopPropagation(); - const inputAr = [...$body.getAll("input")]; - - for (let $input of inputAr) { - if ($input.isRequired && !$input.value) { - $errorMessage.textContent = strings.required.capitalize(); - const $sibling = $input.nextElementSibling; - const $parent = $input.parentElement; - if ($sibling) $parent.insertBefore($errorMessage, $sibling); - else $parent.append($errorMessage); - return; - } - } - const values = getValue(); - hide(); - resolve(values); - }, - }); - const cancelBtn = tag("button", { - textContent: strings.cancel, - type: "button", - onclick: function () { - actionStack.remove(actionId); - cancel(); - }, - }); + const $title = ( +
+ +
+ ); + const $body = ( +
+ ); + if (description) $body.append(

); + const okBtn = ( + + ); const $errorMessage = ( ); const $mask = ; - const $promptDiv = tag("form", { - action: "#", - className: "prompt multi", - onsubmit: (e) => { - e.preventDefault(); - if (!okBtn.disabled) { - const values = getValue(); - hide(); - resolve(values); - } - }, - children: [ - $title, - $body, - tag("div", { - className: "button-container", - children: [cancelBtn, okBtn], - }), - ], - }); + const $promptDiv = ( +

+ {$title} + {$body} +
+ + {okBtn} +
+
+ ); if (/^https?:/.test(help)) { - $title.append( - tag("a", { - href: help, - className: "icon help", - }), - ); + $title.append(); } else if (typeof help === "string") { $title.append( - tag("span", { - className: "icon help", - onclick: () => { - alert(strings.info, help); - }, - }), + alert(strings.info, help)} + />, ); } @@ -140,9 +100,30 @@ export default function multiPrompt(message, inputs, help) { restoreTheme(true); system.setInputType("NORMAL"); document.body.append($promptDiv, $mask); - const $focusEl = [...$body.getAll("input[autofocus]")].pop(); + const $focusEl = [ + ...$body.getAll("input[autofocus], textarea[autofocus]"), + ].pop(); if ($focusEl) $focusEl.focus(); + function submit(event) { + event.preventDefault(); + event.stopPropagation(); + if (okBtn.disabled || $promptDiv.classList.contains("hide")) return; + for (const $input of $body.getAll("input, textarea")) { + if ($input.isRequired && !$input.value) { + $errorMessage.textContent = strings.required; + const $sibling = $input.nextElementSibling; + const $parent = $input.parentElement; + if ($sibling) $parent.insertBefore($errorMessage, $sibling); + else $parent.append($errorMessage); + return; + } + } + const values = getValue(); + hide(); + resolve(values); + } + function cancel() { reject(); hidePrompt(); @@ -167,7 +148,7 @@ export default function multiPrompt(message, inputs, help) { function getValue() { const values = {}; - const inputAr = [...$body.getAll("input")]; + const inputAr = [...$body.getAll("input, textarea")]; inputAr.map(($input) => { if ($input.type === "checkbox" || $input.type === "radio") values[$input.id] = $input.checked; @@ -178,7 +159,9 @@ export default function multiPrompt(message, inputs, help) { return values; } - function clearSensitiveInputs(inputs = [...$body.getAll("input")]) { + function clearSensitiveInputs( + inputs = [...$body.getAll("input, textarea")], + ) { for (const $input of inputs) { if ($input.type === "password" || $input.isSensitive) { $input.value = ""; @@ -191,13 +174,8 @@ export default function multiPrompt(message, inputs, help) { * @param {Array} inputs Array of inputs */ function createGroup(inputs) { - const $text = tag("span", { - className: "hero", - }); - const $group = tag("div", { - className: "input-group", - child: $text, - }); + const $text = ; + const $group =
{$text}
; inputs.map((input) => { let $input; @@ -239,27 +217,41 @@ export default function multiPrompt(message, inputs, help) { } = input; const inputType = type === "textarea" ? "textarea" : "input"; - let _type = type === "filename" ? "text" : type || "text"; + const fieldType = type === "filename" ? "text" : type || "text"; let $input; - if (_type === "checkbox" || _type === "radio") { - $input = Checkbox(placeholder, value, name, id, type); + if (fieldType === "checkbox" || fieldType === "radio") { + $input = ( + + ); if (!group) { $input.style.marginTop = "1rem"; } } else { - $input = tag(inputType, { + const props = { id, placeholder, - value: value, + value, className: "input", isRequired: required, readOnly, autofocus, hidden, - }); + }; + $input = + inputType === "textarea" ? ( +