diff --git a/.github/workflows/native-release.yml b/.github/workflows/native-release.yml new file mode 100644 index 00000000..af035106 --- /dev/null +++ b/.github/workflows/native-release.yml @@ -0,0 +1,491 @@ +# Signed store builds of the apps: TestFlight for iOS, the Play internal track for Android. +# Design: local/split-native-app ARCHITECTURE 14.4; the steps that need accounts are in +# docs/NATIVE-HANDOFF.md. The unsigned builds and all tests are in native.yml. +# +# Trigger: push a tag `native-v..` on the commit to ship. A tag push runs +# the workflow file of the tagged commit, so this works before native-apps is merged to main. +# +# The workflow is dormant until the secrets exist. One export job builds the web bundle for +# both platforms. The iOS and Android jobs are separate jobs, not a matrix, and neither needs +# the other, so a failure in one never cancels the other. Each platform job first checks only +# its own secrets and lists the missing names, so one platform ships as soon as its secrets +# are in place. Promotion to production and submission for review stay manual in the consoles. +name: Native release + +on: + push: + tags: ['native-v*'] + +permissions: + contents: read + +concurrency: + group: native-release-${{ github.ref }} + cancel-in-progress: false + +jobs: + export: + runs-on: ubuntu-latest + timeout-minutes: 20 + outputs: + build_number: ${{ steps.build_number.outputs.value }} + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: 22 + + # Production state the store reviewers depend on (CORS for the app origins, the two + # association files, receipt scan). A warning here: the build does not need it, but it + # must be green before submission (HANDOFF K5). The script needs no dependencies. + - name: Check production readiness for review (warning only) + continue-on-error: true + run: node apps/web/scripts/native/check-review-readiness.mjs + + - run: corepack enable + + - run: pnpm bootstrap + + # One build number for both stores: whole minutes since 2026-01-01, so it only grows. + # Computed once here so the iOS and Android builds of one tag carry the same number. + - name: Compute the build number + id: build_number + run: echo "value=$(node apps/web/scripts/native/version-code.mjs)" >> "$GITHUB_OUTPUT" + + - name: Check the native project settings + run: node apps/web/scripts/native/assert-native-config.mjs + + # NODE_ENV is set on this step only: on the install step it would skip devDependencies. + # Push is always compiled in; until the server has push credentials it answers 503 and + # the app hides the notification row. The PostHog and Sentry values are the public client + # values the live web bundle already ships; a repo variable of the same name overrides + # each. The CORS self-test flag of native.yml is never set here, so the release bundle + # contains no self-test. The placeholder DATABASE_URL matches the Dockerfile. + - name: Build the static export + run: pnpm --dir apps/web native:build + env: + NODE_ENV: production + NEXT_PUBLIC_BASE_URL: https://peanutsplit.com + NEXT_PUBLIC_SPLIT_APNS_ENV: production + NEXT_PUBLIC_NATIVE_PUSH: '1' + NEXT_PUBLIC_POSTHOG_KEY: ${{ vars.NEXT_PUBLIC_POSTHOG_KEY || 'phc_sgS6DahQFBXTEuLjLZA7F5NBLQeN8e3uRJskMcQo6jyU' }} + NEXT_PUBLIC_POSTHOG_HOST: ${{ vars.NEXT_PUBLIC_POSTHOG_HOST || 'https://eu.i.posthog.com' }} + NEXT_PUBLIC_SENTRY_DSN: ${{ vars.NEXT_PUBLIC_SENTRY_DSN || 'https://46a188ac2e047dcfecb20ec0068fd75f@o4505827429187584.ingest.us.sentry.io/4511812348870656' }} + DATABASE_URL: postgresql://build:build@localhost:5432/build + + - name: Write the job summary + env: + BUILD_NUMBER: ${{ steps.build_number.outputs.value }} + run: | + { + echo "push compiled in: yes" + echo "build number: ${BUILD_NUMBER}" + } >> "$GITHUB_STEP_SUMMARY" + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: native-release-export + path: apps/web/.next-native + # `.next-native` itself starts with a dot; without this the upload finds no files. + include-hidden-files: true + if-no-files-found: error + retention-days: 7 + + ios: + needs: export + runs-on: macos-15 + timeout-minutes: 60 + steps: + # First, so a missing secret fails in seconds. Prints names only, never values. + - name: Check the iOS release secrets + env: + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + IOS_DIST_CERT_P12_BASE64: ${{ secrets.IOS_DIST_CERT_P12_BASE64 }} + IOS_DIST_CERT_PASSWORD: ${{ secrets.IOS_DIST_CERT_PASSWORD }} + IOS_PROVISIONING_PROFILE_BASE64: ${{ secrets.IOS_PROVISIONING_PROFILE_BASE64 }} + ASC_KEY_ID: ${{ secrets.ASC_KEY_ID }} + ASC_ISSUER_ID: ${{ secrets.ASC_ISSUER_ID }} + ASC_KEY_CONTENT: ${{ secrets.ASC_KEY_CONTENT }} + run: | + missing=() + for name in APPLE_TEAM_ID IOS_DIST_CERT_P12_BASE64 IOS_DIST_CERT_PASSWORD \ + IOS_PROVISIONING_PROFILE_BASE64 ASC_KEY_ID ASC_ISSUER_ID ASC_KEY_CONTENT; do + [ -n "${!name}" ] || missing+=("${name}") + done + if [ "${#missing[@]}" -gt 0 ]; then + echo "::error::Missing iOS release secrets: ${missing[*]}. See docs/NATIVE-HANDOFF.md step 5." + exit 1 + fi + echo "All iOS release secrets are set." + + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + + # MARKETING_VERSION comes from the tag; App Store Connect accepts only numbers and dots. + - name: Read the version from the tag + id: version + env: + TAG: ${{ github.ref_name }} + run: | + if ! [[ "${TAG}" =~ ^native-v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]]; then + echo "::error::Tag ${TAG} is not native-v..." + exit 1 + fi + echo "name=${TAG#native-v}" >> "$GITHUB_OUTPUT" + + - uses: maxim-lobanov/setup-xcode@ed7a3b1fda3918c0306d1b724322adc0b8cc0a90 # v1 + with: + xcode-version: latest-stable + + # App Store uploads need Xcode 26 and the iOS 26 SDK since 28 Apr 2026. + - name: Require Xcode 26 or later + run: | + xcodebuild -version + major="$(xcodebuild -version | awk 'NR == 1 { split($2, v, "."); print v[1] }')" + if [ "${major}" -lt 26 ]; then + echo "::error::Xcode ${major} is too old. App Store uploads need Xcode 26 or later." + exit 1 + fi + + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: 22 + + - run: corepack enable + + - run: pnpm bootstrap + + - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7 + with: + name: native-release-export + path: apps/web/.next-native + + - name: Copy the export into the iOS project + working-directory: apps/web + run: NODE_ENV=production pnpm exec cap sync ios + + # The archive signs with the team in the Release configuration of project.pbxproj. A + # different team in the secret would fail the export later with a less clear error. + - name: Check that the project uses the team of the secrets + env: + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + run: | + team="$(node -e ' + const text = require("fs").readFileSync("apps/web/ios/App/App.xcodeproj/project.pbxproj", "utf8") + const release = text.match(/\/\* Release \*\/ = \{\s*isa = XCBuildConfiguration;\s*buildSettings = \{[^}]*?INFOPLIST_FILE[^}]*?\};/) + console.log(release?.[0].match(/DEVELOPMENT_TEAM = (\w+);/)?.[1] ?? "") + ')" + if [ "${team}" != "${APPLE_TEAM_ID}" ]; then + echo "::error::DEVELOPMENT_TEAM in the App Release configuration does not match APPLE_TEAM_ID. Run scripts/native/set-identifiers.mjs (HANDOFF step 2)." + exit 1 + fi + + - name: Install the Apple Distribution certificate + uses: apple-actions/import-codesign-certs@5142e029c445c10ffc7149d172e540235a065466 # v7 + with: + p12-file-base64: ${{ secrets.IOS_DIST_CERT_P12_BASE64 }} + p12-password: ${{ secrets.IOS_DIST_CERT_PASSWORD }} + + # The profile's name and UUID are read from the profile itself, so they need no secret. + # A profile without aps-environment = production builds an app that can never register + # for push while every step stays green. + - name: Install the provisioning profile + id: profile + env: + IOS_PROVISIONING_PROFILE_BASE64: ${{ secrets.IOS_PROVISIONING_PROFILE_BASE64 }} + run: | + profile="${RUNNER_TEMP}/release.mobileprovision" + printf '%s' "${IOS_PROVISIONING_PROFILE_BASE64}" | base64 --decode > "${profile}" + security cms -D -i "${profile}" > "${RUNNER_TEMP}/release-profile.plist" + uuid="$(/usr/libexec/PlistBuddy -c 'Print :UUID' "${RUNNER_TEMP}/release-profile.plist")" + name="$(/usr/libexec/PlistBuddy -c 'Print :Name' "${RUNNER_TEMP}/release-profile.plist")" + aps="$(/usr/libexec/PlistBuddy -c 'Print :Entitlements:aps-environment' "${RUNNER_TEMP}/release-profile.plist" 2> /dev/null || true)" + if [ "${aps}" != "production" ]; then + echo "::error::The provisioning profile has aps-environment '${aps:-missing}', expected production. Enable Push Notifications on the App ID, regenerate the profile and update IOS_PROVISIONING_PROFILE_BASE64." + exit 1 + fi + # The Release configuration names the profile it signs with; both must agree. + if ! grep -qF "PROVISIONING_PROFILE_SPECIFIER = \"${name}\";" apps/web/ios/App/App.xcodeproj/project.pbxproj; then + echo "::error::The profile is named '${name}', but the App Release configuration names a different profile." + exit 1 + fi + mkdir -p "${HOME}/Library/MobileDevice/Provisioning Profiles" + cp "${profile}" "${HOME}/Library/MobileDevice/Provisioning Profiles/${uuid}.mobileprovision" + echo "name=${name}" >> "$GITHUB_OUTPUT" + echo "Installed provisioning profile ${name} (${uuid})." + + # Signing lives only in the App target's Release configuration in project.pbxproj. It is + # not passed on the command line: settings given there also apply to the Swift package + # targets, which reject a provisioning profile and fail the archive. The command line sets + # only the two version numbers, which Info.plist reads. + - name: Archive + working-directory: apps/web + env: + VERSION_NAME: ${{ steps.version.outputs.name }} + BUILD_NUMBER: ${{ needs.export.outputs.build_number }} + run: >- + xcodebuild -project ios/App/App.xcodeproj -scheme App -configuration Release + -destination 'generic/platform=iOS' -archivePath build/ios/App.xcarchive + MARKETING_VERSION="${VERSION_NAME}" CURRENT_PROJECT_VERSION="${BUILD_NUMBER}" archive + + - name: Export the IPA + working-directory: apps/web + env: + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + PROFILE_NAME: ${{ steps.profile.outputs.name }} + run: | + options_dir="$(mktemp -d "${RUNNER_TEMP}/export-options.XXXXXX")" + EXPORT_OPTIONS_PATH="${options_dir}/ExportOptions.plist" node scripts/native/render-export-options.mjs + xcodebuild -exportArchive -archivePath build/ios/App.xcarchive -exportPath build/ios \ + -exportOptionsPlist "${options_dir}/ExportOptions.plist" + + # Checks the signed app that goes to the store, not the project: production push, + # the associated domain for room links, the versions and the Info.plist keys. + - name: Check the signed app + working-directory: apps/web + env: + VERSION_NAME: ${{ steps.version.outputs.name }} + BUILD_NUMBER: ${{ needs.export.outputs.build_number }} + run: | + check_dir="$(mktemp -d "${RUNNER_TEMP}/ipa-check.XXXXXX")" + unzip -q build/ios/App.ipa -d "${check_dir}" + app="${check_dir}/Payload/App.app" + codesign -d --entitlements :- "${app}" > "${check_dir}/entitlements.plist" 2> /dev/null + python3 - "${check_dir}/entitlements.plist" "${app}/Info.plist" <<'PY' + import os, plistlib, sys + + with open(sys.argv[1], "rb") as f: + entitlements = plistlib.load(f) + with open(sys.argv[2], "rb") as f: + info = plistlib.load(f) + problems = [] + if entitlements.get("aps-environment") != "production": + problems.append(f"aps-environment is {entitlements.get('aps-environment')!r}, expected 'production'") + if "applinks:peanutsplit.com" not in entitlements.get("com.apple.developer.associated-domains", []): + problems.append("associated domains do not include applinks:peanutsplit.com") + if info.get("CFBundleShortVersionString") != os.environ["VERSION_NAME"]: + problems.append(f"CFBundleShortVersionString is {info.get('CFBundleShortVersionString')!r}") + if info.get("CFBundleVersion") != os.environ["BUILD_NUMBER"]: + problems.append(f"CFBundleVersion is {info.get('CFBundleVersion')!r}") + for problem in problems: + print(f"::error::Signed app: {problem}") + sys.exit(1 if problems else 0) + PY + node scripts/native/assert-native-config.mjs --app "${app}" + echo "Signed app: aps-environment production, applinks:peanutsplit.com, version ${VERSION_NAME} (${BUILD_NUMBER})." + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: ios-release-ipa + path: apps/web/build/ios/App.ipa + if-no-files-found: error + retention-days: 30 + + # App Store Connect rejects a second upload of the same build number, so the retry can + # never publish twice. The processing poll is skipped: its token expires mid-wait and + # fails a run whose upload worked. + - name: Upload to TestFlight + id: testflight + continue-on-error: true + uses: apple-actions/upload-testflight-build@1ad58030672057aa084b4e96beb6f7a8c627f9e6 # v5 + with: + app-path: apps/web/build/ios/App.ipa + issuer-id: ${{ secrets.ASC_ISSUER_ID }} + api-key-id: ${{ secrets.ASC_KEY_ID }} + api-private-key: ${{ secrets.ASC_KEY_CONTENT }} + wait-for-processing: 'false' + + - name: Wait before retrying the TestFlight upload + if: steps.testflight.outcome == 'failure' + run: sleep 30 + + - name: Retry the TestFlight upload + if: steps.testflight.outcome == 'failure' + uses: apple-actions/upload-testflight-build@1ad58030672057aa084b4e96beb6f7a8c627f9e6 # v5 + with: + app-path: apps/web/build/ios/App.ipa + issuer-id: ${{ secrets.ASC_ISSUER_ID }} + api-key-id: ${{ secrets.ASC_KEY_ID }} + api-private-key: ${{ secrets.ASC_KEY_CONTENT }} + wait-for-processing: 'false' + + android: + needs: export + runs-on: ubuntu-latest + timeout-minutes: 40 + steps: + # First, so a missing secret fails in seconds. Prints names only, never values. + # google-services.json is required: release builds always compile push in. + - name: Check the Android release secrets + env: + ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }} + ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} + ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }} + ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }} + PLAY_SERVICE_ACCOUNT_JSON: ${{ secrets.PLAY_SERVICE_ACCOUNT_JSON }} + GOOGLE_SERVICES_JSON_BASE64: ${{ secrets.GOOGLE_SERVICES_JSON_BASE64 }} + run: | + missing=() + for name in ANDROID_KEYSTORE_BASE64 ANDROID_KEYSTORE_PASSWORD ANDROID_KEY_ALIAS \ + ANDROID_KEY_PASSWORD PLAY_SERVICE_ACCOUNT_JSON GOOGLE_SERVICES_JSON_BASE64; do + [ -n "${!name}" ] || missing+=("${name}") + done + if [ "${#missing[@]}" -gt 0 ]; then + echo "::error::Missing Android release secrets: ${missing[*]}. See docs/NATIVE-HANDOFF.md step 5." + exit 1 + fi + echo "All Android release secrets are set." + + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + + # versionName comes from the tag. The Play package name is the appId in + # capacitor.config.ts, so set-identifiers.mjs needs no edit here. + - name: Read the version from the tag + id: version + env: + TAG: ${{ github.ref_name }} + run: | + if ! [[ "${TAG}" =~ ^native-v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]]; then + echo "::error::Tag ${TAG} is not native-v..." + exit 1 + fi + echo "name=${TAG#native-v}" >> "$GITHUB_OUTPUT" + echo "package=$(sed -n "s/.*appId: '\([^']*\)'.*/\1/p" apps/web/capacitor.config.ts)" >> "$GITHUB_OUTPUT" + + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: 22 + + - run: corepack enable + + - run: pnpm bootstrap + + # Capacitor 8 needs Java 21. + - uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5 + with: + distribution: temurin + java-version: '21' + + - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7 + with: + name: native-release-export + path: apps/web/.next-native + + # NODE_ENV=production turns WebView debugging off in capacitor.config.ts. + - name: Copy the export into the Android project + working-directory: apps/web + run: NODE_ENV=production pnpm exec cap sync android + + # build.gradle signs the release bundle only when keystore.properties exists, and applies + # the Firebase plugin only when google-services.json exists. Backslashes are doubled + # because Java properties files treat them as escapes. + - name: Write the upload keystore and google-services.json + working-directory: apps/web/android + env: + ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }} + ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} + ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }} + ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }} + GOOGLE_SERVICES_JSON_BASE64: ${{ secrets.GOOGLE_SERVICES_JSON_BASE64 }} + run: | + umask 077 + printf '%s' "${ANDROID_KEYSTORE_BASE64}" | base64 --decode > release.keystore + { + echo "storeFile=release.keystore" + echo "storePassword=${ANDROID_KEYSTORE_PASSWORD//\\/\\\\}" + echo "keyAlias=${ANDROID_KEY_ALIAS//\\/\\\\}" + echo "keyPassword=${ANDROID_KEY_PASSWORD//\\/\\\\}" + } > keystore.properties + printf '%s' "${GOOGLE_SERVICES_JSON_BASE64}" | base64 --decode > app/google-services.json + + # The export always compiles push in. Without a valid google-services.json for this + # package, Firebase is not set up and the app crashes when a room screen registers for + # push. Checked here, before the build, so such a bundle never reaches a store. + - name: Check google-services.json + working-directory: apps/web/android + env: + PACKAGE: ${{ steps.version.outputs.package }} + run: | + python3 - app/google-services.json <<'PY' + import json, os, sys + + try: + with open(sys.argv[1]) as f: + config = json.load(f) + except ValueError: + print("::error::google-services.json is not valid JSON. Check GOOGLE_SERVICES_JSON_BASE64.") + sys.exit(1) + packages = [c.get("client_info", {}).get("android_client_info", {}).get("package_name") for c in config.get("client", [])] + if os.environ["PACKAGE"] not in packages: + print(f"::error::google-services.json has no Android client for {os.environ['PACKAGE']} (found {packages}).") + sys.exit(1) + print(f"google-services.json has a client for {os.environ['PACKAGE']}.") + PY + + - name: Build the signed release bundle + working-directory: apps/web/android + env: + VERSION_NAME: ${{ steps.version.outputs.name }} + VERSION_CODE: ${{ needs.export.outputs.build_number }} + run: ./gradlew :app:bundleRelease + + # The upload certificate's SHA-256 is public. It goes into assetlinks.json next to the + # Play App Signing fingerprint (HANDOFF step 9). No certificate means an unsigned bundle. + - name: Check the bundle signature + working-directory: apps/web/android + run: | + fingerprint="$(keytool -printcert -jarfile app/build/outputs/bundle/release/app-release.aab | awk '/SHA256:/ && !found { print $2; found = 1 }')" + if [ -z "${fingerprint}" ]; then + echo "::error::app-release.aab is not signed." + exit 1 + fi + echo "upload key SHA-256: ${fingerprint}" >> "$GITHUB_STEP_SUMMARY" + + # Always kept: the first release goes into Play Console by hand (HANDOFF step 8). + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: android-release-aab + path: apps/web/android/app/build/outputs/bundle/release/app-release.aab + if-no-files-found: error + retention-days: 30 + + # The Play API cannot create an app or publish to a draft app, so the upload waits for + # the repo variable PLAY_API_UPLOAD=1, set after the first manual upload. Play rejects a + # second upload of the same versionCode, so the retry can never publish twice. + - name: Upload to the Play internal track + id: play + if: vars.PLAY_API_UPLOAD == '1' + continue-on-error: true + uses: r0adkll/upload-google-play@e738b9dd8f2476ea806d921b64aacd24f34515a5 # v1 + with: + serviceAccountJsonPlainText: ${{ secrets.PLAY_SERVICE_ACCOUNT_JSON }} + packageName: ${{ steps.version.outputs.package }} + releaseFiles: apps/web/android/app/build/outputs/bundle/release/app-release.aab + tracks: internal + status: completed + + - name: Wait before retrying the Play upload + if: steps.play.outcome == 'failure' + run: sleep 30 + + - name: Retry the Play upload + if: steps.play.outcome == 'failure' + uses: r0adkll/upload-google-play@e738b9dd8f2476ea806d921b64aacd24f34515a5 # v1 + with: + serviceAccountJsonPlainText: ${{ secrets.PLAY_SERVICE_ACCOUNT_JSON }} + packageName: ${{ steps.version.outputs.package }} + releaseFiles: apps/web/android/app/build/outputs/bundle/release/app-release.aab + tracks: internal + status: completed + + - name: Note a skipped Play upload + if: vars.PLAY_API_UPLOAD != '1' + run: | + echo "::notice::Play upload skipped: PLAY_API_UPLOAD is not 1. Upload the android-release-aab artifact in Play Console (HANDOFF step 8)." + echo "Play upload skipped (PLAY_API_UPLOAD is not 1); the AAB is in the android-release-aab artifact." >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/native.yml b/.github/workflows/native.yml new file mode 100644 index 00000000..f4f4b91c --- /dev/null +++ b/.github/workflows/native.yml @@ -0,0 +1,764 @@ +# Unsigned builds of the store apps (Capacitor) plus a web regression gate. No secrets: the +# signed lane is native-release.yml. Design: local/split-native-app ARCHITECTURE 14.1 and PLAN 10. +# +# One push filter serves both branches, because GitHub allows one `push` block per workflow. A +# push to native-apps that touches none of these paths changes nothing a native build reads. +# On main only the export runs: most changes reach main without a PR, and the static export is +# what they break. Android, iOS and the web e2e comparison carry `if: github.ref != main`. +name: Native apps + +on: + push: + branches: [native-apps, main] + paths: + - 'apps/web/**' + - '.github/workflows/native.yml' + pull_request: + paths: + - 'apps/web/**' + - '.github/workflows/native.yml' + +permissions: + contents: read + +concurrency: + group: native-${{ github.ref }} + cancel-in-progress: true + +jobs: + # Every job repeats the same guard: a PR whose head is native-apps already ran on its push, so + # the pull_request run for that SHA is skipped. + export: + if: github.event_name != 'pull_request' || github.head_ref != 'native-apps' + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: 22 + + # corepack, not a pinned pnpm action: apps/web and the root each declare their own pnpm. + - run: corepack enable + + - run: pnpm bootstrap + + # Source mode: pinned scheme and hostname, no server.url, status bar, AppDelegate push + # forwarding, plist keys, entitlements, privacy manifest, deployment target, allowBackup. + - name: Check the native project settings + run: node apps/web/scripts/native/assert-native-config.mjs + + # The store images in apps/web/store/assets must exist at the exact sizes, with no alpha. + - name: Check the store images + run: node apps/web/store/check-assets.mjs + + # The self-test flag makes the debug APK and the simulator build log `SPLIT_CORS ok|blocked` + # on boot. Only this job sets it; the release lane never does, so release bundles drop it. + # The placeholder DATABASE_URL matches the Dockerfile: the build needs a value, not a database. + - name: Build the static export + run: pnpm --dir apps/web native:build + env: + NEXT_PUBLIC_BASE_URL: https://peanutsplit.com + NEXT_PUBLIC_SPLIT_CORS_SELFTEST: '1' + DATABASE_URL: postgresql://build:build@localhost:5432/build + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: native-export + path: apps/web/.next-native + # `.next-native` itself starts with a dot; without this the upload finds no files. + include-hidden-files: true + if-no-files-found: error + retention-days: 7 + + android: + needs: export + if: github.ref != 'refs/heads/main' && (github.event_name != 'pull_request' || github.head_ref != 'native-apps') + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: 22 + + - run: corepack enable + + - run: pnpm bootstrap + + # Capacitor 8 needs Java 21. + - uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5 + with: + distribution: temurin + java-version: '21' + + - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7 + with: + name: native-export + path: apps/web/.next-native + + # No NODE_ENV=production prefix: this is the debug build, and Capacitor keeps WebView + # debugging on only outside production, which the emulator smoke needs. + - name: Copy the export into the Android project + working-directory: apps/web + run: pnpm exec cap sync android + + # The release bundle is unsigned: build.gradle attaches a signing config only when + # keystore.properties exists, and CI has none. + - name: Build the debug APK and the unsigned release bundle + working-directory: apps/web/android + run: ./gradlew :app:assembleDebug :app:bundleRelease + + # Google Play rejects native libraries that are not 16 KB page aligned. Split ships no + # native code of its own. The only expected library is androidx.datastore's + # libdatastore_shared_counter.so, which firebase-messaging (push) pulls in. Any other .so + # is a plugin change to look at first. The 16 KB rule applies to 64-bit libraries only. + - name: Check the bundle's native libraries + working-directory: apps/web/android + run: | + shopt -s nullglob + bundles=(app/build/outputs/bundle/release/*.aab) + if [ "${#bundles[@]}" -ne 1 ]; then + echo "::error::Expected exactly one release bundle, found ${#bundles[@]}." + exit 1 + fi + python3 - "${bundles[0]}" <<'PY' + import struct, sys, zipfile + + ALLOWED = {"libdatastore_shared_counter.so"} + bad = [] + with zipfile.ZipFile(sys.argv[1]) as bundle: + for name in bundle.namelist(): + if not name.endswith(".so"): + continue + base = name.rsplit("/", 1)[-1] + if base not in ALLOWED: + bad.append(f"{name}: not on the allowed list") + continue + elf = bundle.read(name) + is64 = elf[4] == 2 + if not is64: + print(f"ok (32-bit): {name}") + continue + endian = "<" if elf[5] == 1 else ">" + if is64: + phoff, = struct.unpack_from(endian + "Q", elf, 0x20) + phentsize, phnum = struct.unpack_from(endian + "HH", elf, 0x36) + else: + phoff, = struct.unpack_from(endian + "I", elf, 0x1C) + phentsize, phnum = struct.unpack_from(endian + "HH", elf, 0x2A) + for i in range(phnum): + off = phoff + i * phentsize + p_type, = struct.unpack_from(endian + "I", elf, off) + if p_type != 1: + continue + align, = struct.unpack_from(endian + "Q", elf, off + 0x30) if is64 else struct.unpack_from(endian + "I", elf, off + 0x1C) + if align < 16384: + bad.append(f"{name}: LOAD segment aligned to {align} bytes") + break + else: + print(f"ok: {name}") + for line in bad: + print(f"::error::{line}") + sys.exit(1 if bad else 0) + PY + + # The release manifest after every library merged into it: exactly what Split declares, plus + # the three that Firebase Cloud Messaging and AndroidX add for push. A new permission is a + # dependency change to review against the Play data-safety answers before it ships; the + # banned ones would contradict those answers outright. + - name: Check the merged manifest's permissions + working-directory: apps/web/android + run: | + python3 - <<'PY' + import glob, sys + import xml.etree.ElementTree as ET + + NAME = "{http://schemas.android.com/apk/res/android}name" + BANNED = ("com.google.android.gms.permission.AD_ID", "android.permission.READ_MEDIA_", + "android.permission.READ_EXTERNAL_STORAGE", "android.permission.FOREGROUND_SERVICE") + manifests = sorted(glob.glob("app/build/intermediates/merged_manifest*/release/**/AndroidManifest.xml", recursive=True)) + if not manifests: + print("::error::No merged release manifest under app/build/intermediates.") + sys.exit(1) + bad = False + for path in manifests: + root = ET.parse(path).getroot() + package = root.get("package") + if not package: + print(f"::error::{path} has no package attribute.") + sys.exit(1) + found = {e.get(NAME) for tag in ("uses-permission", "uses-permission-sdk-23") for e in root.iter(tag)} + expected = { + "android.permission.INTERNET", + "android.permission.ACCESS_NETWORK_STATE", + "android.permission.CAMERA", + "android.permission.POST_NOTIFICATIONS", + "android.permission.WAKE_LOCK", + "com.google.android.c2dm.permission.RECEIVE", + f"{package}.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION", + } + print(f"{path}:") + for name in sorted(found): + print(f" {name}") + for name in sorted(found): + if name.startswith(BANNED): + print(f"::error::Banned permission in the merged manifest: {name}") + bad = True + for name in sorted(found - expected): + print(f"::error::Unexpected permission in the merged manifest: {name}") + bad = True + for name in sorted(expected - found): + print(f"::error::Expected permission missing from the merged manifest: {name}") + bad = True + sys.exit(1 if bad else 0) + PY + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: android + path: | + apps/web/android/app/build/outputs/apk/debug/*.apk + apps/web/android/app/build/outputs/bundle/release/*.aab + if-no-files-found: error + retention-days: 14 + + # The debug APK on an Android 15 emulator: launch, open a room link, press back, screenshots. + # Never gating (emulators on hosted runners are slow and flaky). The debug export calls the + # production API read-only, so the SPLIT_CORS line says `blocked` until server-prep is live. + android-smoke: + needs: android + if: github.ref != 'refs/heads/main' && (github.event_name != 'pull_request' || github.head_ref != 'native-apps') + runs-on: ubuntu-latest + timeout-minutes: 30 + continue-on-error: true + steps: + - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7 + with: + name: android + path: android-build + + - name: Enable KVM + run: | + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --name-match=kvm + + # The emulator action runs each `script` line as its own shell, so the steps live in a file. + # The package and launcher activity are read from the APK and the device, so a changed + # application ID (set-identifiers.mjs) needs no edit here. + - name: Write the smoke script + run: | + cat > "${RUNNER_TEMP}/android-smoke.sh" <<'SH' + set -uo pipefail + out="$1" + mkdir -p "${out}" + apk="$(find android-build -name '*.apk' | head -n 1)" + aapt2="$(ls "${ANDROID_HOME}"/build-tools/*/aapt2 | sort -V | tail -n 1)" + pkg="$("${aapt2}" dump packagename "${apk}")" + adb install -r "${apk}" + adb logcat -c + component="$(adb shell cmd package resolve-activity --brief "${pkg}" | tail -n 1 | tr -d '\r')" + echo "Launching ${component}" + adb shell am start -W -n "${component}" + sleep 15 + adb exec-out screencap -p > "${out}/1-launch.png" + adb shell am start -W -a android.intent.action.VIEW \ + -d 'https://peanutsplit.com/r/ski-trip-kunc-syrup-drum' -n "${component}" + sleep 10 + adb exec-out screencap -p > "${out}/2-room-link.png" + adb shell input keyevent KEYCODE_BACK + sleep 3 + adb exec-out screencap -p > "${out}/3-after-back.png" + adb logcat -d > "${out}/logcat.txt" + grep -h 'SPLIT_CORS' "${out}/logcat.txt" || echo '::warning::No SPLIT_CORS line in logcat.' + # Only the WebView console counts: system_server logs 'Uncaught remote exception' on its own. + if grep 'Capacitor/Console' "${out}/logcat.txt" | grep -q 'Uncaught'; then + grep 'Capacitor/Console' "${out}/logcat.txt" | grep 'Uncaught' | head -n 20 + echo '::error::The WebView logged an uncaught error.' + exit 1 + fi + SH + + - name: Launch on the emulator + uses: reactivecircus/android-emulator-runner@a421e43855164a8197daf9d8d40fe71c6996bb0d # v2.38.0 + with: + api-level: 35 + target: google_apis + arch: x86_64 + force-avd-creation: false + emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none + disable-animations: true + script: bash "${{ runner.temp }}/android-smoke.sh" "${{ runner.temp }}/android-smoke" + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + if: ${{ !cancelled() }} + with: + name: android-smoke + path: ${{ runner.temp }}/android-smoke + if-no-files-found: warn + retention-days: 14 + + ios: + needs: export + if: github.ref != 'refs/heads/main' && (github.event_name != 'pull_request' || github.head_ref != 'native-apps') + runs-on: macos-15 + timeout-minutes: 45 + env: + NODE_OPTIONS: --max-old-space-size=4096 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + + - uses: maxim-lobanov/setup-xcode@ed7a3b1fda3918c0306d1b724322adc0b8cc0a90 # v1 + with: + xcode-version: latest-stable + + # App Store uploads need Xcode 26 and the iOS 26 SDK since 28 Apr 2026. Fail here, not at + # upload time, when the runner image falls behind. + - name: Require Xcode 26 or later + run: | + xcodebuild -version + major="$(xcodebuild -version | awk 'NR == 1 { split($2, v, "."); print v[1] }')" + if [ "${major}" -lt 26 ]; then + echo "::error::Xcode ${major} is too old. App Store uploads need Xcode 26 or later." + exit 1 + fi + + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: 22 + + - run: corepack enable + + - run: pnpm bootstrap + + - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7 + with: + name: native-export + path: apps/web/.next-native + + - name: Copy the export into the iOS project + working-directory: apps/web + run: pnpm exec cap sync ios + + - name: Build for the simulator (no signing) + working-directory: apps/web + run: >- + xcodebuild -project ios/App/App.xcodeproj -scheme App -configuration Debug + -sdk iphonesimulator -destination 'generic/platform=iOS Simulator' + -derivedDataPath build/sim CODE_SIGNING_ALLOWED=NO build + + # Proves the Release configuration compiles for a device without any certificate. + - name: Archive for a device (unsigned) + working-directory: apps/web + run: >- + xcodebuild -project ios/App/App.xcodeproj -scheme App -configuration Release + -destination 'generic/platform=iOS' -archivePath build/ios/App.xcarchive + CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY="" archive + + # The Info.plist as built, for the simulator app and for the Release archive that ships. + - name: Check the built apps' settings + run: | + node apps/web/scripts/native/assert-native-config.mjs --app apps/web/build/sim/Build/Products/Debug-iphonesimulator/App.app + node apps/web/scripts/native/assert-native-config.mjs --app apps/web/build/ios/App.xcarchive/Products/Applications/App.app + + # Not gating: the simulator build is unsigned and hosted simulators are slow. The console + # shows the CORS self-test line (`blocked` until server-prep is live on production). + - name: Launch in the simulator + continue-on-error: true + working-directory: apps/web + run: | + set -euo pipefail + out="${RUNNER_TEMP}/ios-smoke" + mkdir -p "${out}" + udid="$(xcrun simctl list devices available --json | python3 -c ' + import json, sys + devices = json.load(sys.stdin)["devices"] + print(next(d["udid"] for runtime in sorted(devices, reverse=True) if ".iOS-" in runtime + for d in devices[runtime] if d["name"].startswith("iPhone"))) + ')" + app=build/sim/Build/Products/Debug-iphonesimulator/App.app + bundle="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "${app}/Info.plist")" + xcrun simctl boot "${udid}" || true + xcrun simctl bootstatus "${udid}" -b + xcrun simctl install "${udid}" "${app}" + # --stdout/--stderr let simctl return at once with the pid; Capacitor prints the WebView + # console to stdout, so the SPLIT_CORS line lands in console.log. + touch "${out}/console.log" + if ! xcrun simctl launch --terminate-running-process \ + --stdout="${out}/console.log" --stderr="${out}/console.log" "${udid}" "${bundle}"; then + echo '::warning::simctl launch failed.' + fi + # grep without -q reads all input, so pipefail never sees a SIGPIPE from launchctl. + running() { xcrun simctl spawn "${udid}" launchctl list | grep "UIKitApplication:${bundle}" > /dev/null; } + alive=1 + for _ in $(seq 1 30); do + grep -q 'SPLIT_CORS' "${out}/console.log" && break + if ! running; then alive=0; break; fi + sleep 2 + done + running || alive=0 + xcrun simctl io "${udid}" screenshot "${out}/launch.png" + xcrun simctl spawn "${udid}" log show --last 3m --style compact --predicate 'process == "App"' > "${out}/oslog.txt" 2>&1 || true + if [ "${alive}" = 0 ]; then + cp ~/Library/Logs/DiagnosticReports/App*.ips "${out}/" 2> /dev/null || true + echo '::warning::iOS app is not running after launch (crash report attached if one was written).' + fi + grep -h 'SPLIT_CORS' "${out}/console.log" || echo '::warning::No SPLIT_CORS line in the simulator console.' + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + if: ${{ !cancelled() }} + with: + name: ios-smoke + path: ${{ runner.temp }}/ios-smoke + if-no-files-found: warn + retention-days: 14 + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: ios-sim-app + path: apps/web/build/sim/Build/Products/Debug-iphonesimulator/App.app + if-no-files-found: error + retention-days: 14 + + # Swift Package Manager resolves the plugin versions only on macOS. The resolved file is + # committed from this artifact so every later build uses the same versions. + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: ios-package-resolved + path: apps/web/ios/App/App.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved + if-no-files-found: warn + retention-days: 30 + + # The bundled app against the web server, cross-origin, on Chromium and WebKit + # (playwright.native.config.ts, e2e-native/). The test export is built first: native:build + # builds inside .next and clears it afterwards, so the web build that serves the API comes after. + native-e2e: + if: github.ref != 'refs/heads/main' && (github.event_name != 'pull_request' || github.head_ref != 'native-apps') + runs-on: ubuntu-latest + timeout-minutes: 40 + env: + CI: true + DATABASE_URL: postgresql://peanut:peanut@localhost:5432/peanut_split_dev + E2E_DATABASE_URL: postgresql://peanut:peanut@localhost:5432/peanut_split_dev + # Both builds call the API on the local web server, never production. + NEXT_PUBLIC_BASE_URL: http://localhost:3100 + services: + postgres: + image: postgres:16-alpine + env: + POSTGRES_USER: peanut + POSTGRES_PASSWORD: peanut + POSTGRES_DB: peanut_split_dev + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U peanut" + --health-interval 5s + --health-timeout 5s + --health-retries 10 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: 22 + + - run: corepack enable + + - run: pnpm bootstrap + + - run: pnpm --dir apps/web exec prisma migrate deploy + + - name: Build the test export + run: pnpm --dir apps/web native:build + + # Same product flags as production (the Dockerfile sets both). Its postbuild step, + # assert-pwa-build-boundary.mjs, fails on any Capacitor code in .next/static. + - name: Build the web app that serves the API + run: pnpm --dir apps/web build + env: + NEXT_PUBLIC_SPLIT_V2_ENABLED: '1' + NEXT_PUBLIC_FOSS_RELEASED: '1' + + # The server is stopped again, so Playwright's own webServer can take the port. + - name: Check the app-association files + working-directory: apps/web + run: | + node_modules/.bin/next start --port 3100 > "${RUNNER_TEMP}/association-server.log" 2>&1 & + server=$! + for attempt in {1..60}; do + curl --fail --silent http://127.0.0.1:3100/healthcheck > /dev/null && break + sleep 1 + done + status=0 + node scripts/native/check-association.mjs http://localhost:3100 || status=$? + kill "${server}" 2> /dev/null || true + fuser -k 3100/tcp 2> /dev/null || true + [ "${status}" -eq 0 ] || cat "${RUNNER_TEMP}/association-server.log" + exit "${status}" + + - run: pnpm --dir apps/web exec playwright install --with-deps chromium webkit + + - name: Run the cross-origin suite + working-directory: apps/web + run: pnpm exec playwright test --config playwright.native.config.ts + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + if: ${{ !cancelled() }} + with: + name: native-e2e-report + path: | + apps/web/playwright-report + apps/web/test-results + if-no-files-found: ignore + retention-days: 14 + + # Negative control: with the app origin removed from the server's CORS list, E4 must fail on + # both engines. If it passes, the suite is not testing CORS at all. + - name: Check that E4 fails without CORS for the app origin + working-directory: apps/web + env: + PLAYWRIGHT_JSON_OUTPUT_FILE: ${{ runner.temp }}/negative-control.json + run: | + export SPLIT_CORS_TEST_ORIGINS= + pnpm exec playwright test --config playwright.native.config.ts --grep 'E4:' --retries=0 \ + --reporter=json --output "${RUNNER_TEMP}/negative-control-results" > /dev/null || true + node - "${PLAYWRIGHT_JSON_OUTPUT_FILE}" <<'EOF' + const fs = require('fs') + const report = JSON.parse(fs.readFileSync(process.argv[2], 'utf8')) + const results = [] + const walk = (suite) => { + for (const spec of suite.specs ?? []) + if (spec.title.startsWith('E4:')) + for (const test of spec.tests) results.push({ project: test.projectName, status: test.status, error: test.results[0]?.error?.message ?? '' }) + for (const child of suite.suites ?? []) walk(child) + } + for (const suite of report.suites ?? []) walk(suite) + for (const r of results) console.log(`${r.project}: ${r.status} ${r.error.split('\n')[0]}`) + const failedBoth = results.length === 2 && results.every((r) => r.status === 'unexpected') + if (!failedBoth) console.log('::error::E4 did not fail on both engines without CORS for the app origin.') + process.exit(failedBoth ? 0 : 1) + EOF + + # The three existing Playwright suites, once on the merge base with main and once on the pushed + # commit. Each leg records results and never fails on a test: web-e2e-compare decides, so a + # failure that already exists on main never blocks this branch. + web-e2e: + name: web-e2e (${{ matrix.ref }}, ${{ matrix.suite.id }}) + if: github.ref != 'refs/heads/main' && (github.event_name != 'pull_request' || github.head_ref != 'native-apps') + runs-on: ubuntu-latest + timeout-minutes: 70 + strategy: + fail-fast: false + matrix: + ref: [base, head] + suite: + - { id: e2e, config: playwright.config.ts } + - { id: pwa-boundary, config: playwright.pwa-boundary.config.ts } + - { id: v2, config: playwright.v2.config.ts } + env: + # Playwright reads CI for forbidOnly and its two retries. + CI: true + # migrate deploy reads DATABASE_URL; the Playwright webServer reads only E2E_DATABASE_URL. + DATABASE_URL: postgresql://peanut:peanut@localhost:5432/peanut_split_dev + E2E_DATABASE_URL: postgresql://peanut:peanut@localhost:5432/peanut_split_dev + services: + postgres: + image: postgres:16-alpine + env: + POSTGRES_USER: peanut + POSTGRES_PASSWORD: peanut + POSTGRES_DB: peanut_split_dev + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U peanut" + --health-interval 5s + --health-timeout 5s + --health-retries 10 + steps: + # Full history so the merge base with main can be found. + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + fetch-depth: 0 + persist-credentials: false + + - name: Check out the merge base with main + if: matrix.ref == 'base' + run: | + git checkout --detach "$(git merge-base origin/main HEAD)" + git log -1 --format='Base commit: %H %s' + + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: 22 + + - run: corepack enable + + - run: pnpm bootstrap + + - run: pnpm --dir apps/web exec prisma migrate deploy + + - run: pnpm --dir apps/web exec playwright install --with-deps chromium + + # The PWA boundary config has no webServer: it needs a production build, served the way + # the Dockerfile serves it (static assets and public/ copied next to server.js). + - name: Build and start the standalone server + if: matrix.suite.id == 'pwa-boundary' + working-directory: apps/web + run: | + pnpm build + server="$(find .next/standalone -name server.js -not -path '*/node_modules/*' | head -n 1)" + app_dir="$(dirname "${server}")" + cp -R .next/static "${app_dir}/.next/static" + cp -R public "${app_dir}/public" + PORT=8777 HOSTNAME=0.0.0.0 nohup node "${server}" > "${RUNNER_TEMP}/standalone.log" 2>&1 & + for attempt in {1..60}; do + if curl --fail --silent http://127.0.0.1:8777/healthcheck > /dev/null; then + exit 0 + fi + sleep 1 + done + cat "${RUNNER_TEMP}/standalone.log" + exit 1 + + - name: Run the suite + working-directory: apps/web + env: + SUITE_CONFIG: ${{ matrix.suite.config }} + PLAYWRIGHT_JSON_OUTPUT_FILE: ${{ runner.temp }}/web-e2e/results.json + PWA_BOUNDARY_PORT: '8777' + run: | + pnpm exec playwright test --config "${SUITE_CONFIG}" --reporter=json \ + || echo "::warning::Some tests failed. web-e2e-compare decides whether any is new." + + # The e2e suite runs six workers against a dev server on a small runner, so some tests fail + # from load alone; base shows the same rate. Head failures get one more run with a single + # worker, and web-e2e-compare blocks only on a test that fails here too. + - name: Re-run the head failures with one worker + if: matrix.ref == 'head' + working-directory: apps/web + env: + SUITE_CONFIG: ${{ matrix.suite.config }} + PLAYWRIGHT_JSON_OUTPUT_FILE: ${{ runner.temp }}/web-e2e/confirm.json + PWA_BOUNDARY_PORT: '8777' + run: | + pnpm exec playwright test --config "${SUITE_CONFIG}" --last-failed --workers=1 --retries=1 --reporter=json \ + || echo "::warning::Some head failures repeat with one worker. web-e2e-compare lists them." + + # The iPhone store offer is off until the App Store ID exists, so the suites above run with it + # unset and skip e2e/store-offer.spec.ts. Here a second production build has it set, and the + # spec gates directly: it is new, so there is no base result to compare against. It runs on + # the pwa-boundary leg, after that suite is done with its own build, because that leg has no + # dev server and already builds the standalone server. + - name: Store offer against a build with the App Store ID + if: matrix.ref == 'head' && matrix.suite.id == 'pwa-boundary' + working-directory: apps/web + env: + NEXT_PUBLIC_IOS_APP_STORE_ID: '6740000000' + NEXT_PUBLIC_BASE_URL: http://localhost:8779 + E2E_BASE_URL: http://localhost:8779 + E2E_SKIP_GLOBAL_SETUP: '1' + SPLIT_FX_MODE: static + run: | + pnpm build + server="$(find .next/standalone -name server.js -not -path '*/node_modules/*' | head -n 1)" + app_dir="$(dirname "${server}")" + cp -R .next/static "${app_dir}/.next/static" + cp -R public "${app_dir}/public" + PORT=8779 HOSTNAME=0.0.0.0 nohup node "${server}" > "${RUNNER_TEMP}/store-offer.log" 2>&1 & + for attempt in {1..60}; do + if curl --fail --silent http://127.0.0.1:8779/healthcheck > /dev/null; then + break + fi + sleep 1 + done + pnpm exec playwright test --config playwright.config.ts --project=mobile e2e/store-offer.spec.ts \ + --reporter=list || { cat "${RUNNER_TEMP}/store-offer.log"; exit 1; } + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + if: ${{ !cancelled() }} + with: + name: web-e2e-results-${{ matrix.ref }}-${{ matrix.suite.id }} + path: ${{ runner.temp }}/web-e2e/ + if-no-files-found: warn + retention-days: 14 + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + if: ${{ !cancelled() }} + with: + name: web-e2e-traces-${{ matrix.ref }}-${{ matrix.suite.id }} + path: apps/web/test-results + if-no-files-found: ignore + retention-days: 7 + + # Fails when a test fails on head and either passed on base or does not exist there (so new + # specs gate), and when a suite has no passing test on base or head (a broken harness turns + # red instead of passing). A failure that also fails on base, or that passes on the head's + # one-worker re-run, is listed and does not block. + web-e2e-compare: + needs: web-e2e + if: ${{ !cancelled() && needs.web-e2e.result != 'skipped' }} + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7 + with: + pattern: web-e2e-results-* + path: results + + - name: Compare head with base + run: | + node - <<'EOF' + const fs = require('fs') + const passed = (status) => status === 'expected' || status === 'flaky' + function load(ref, suite, name = 'results.json') { + const file = `results/web-e2e-results-${ref}-${suite}/${name}` + if (!fs.existsSync(file)) return null + const tests = new Map() + const walk = (node, titles) => { + for (const spec of node.specs ?? []) + for (const test of spec.tests) + tests.set([...titles, spec.title, test.projectName].join(' > '), test.status) + for (const child of node.suites ?? []) walk(child, [...titles, child.title]) + } + for (const top of JSON.parse(fs.readFileSync(file, 'utf8')).suites ?? []) walk(top, [top.title]) + return tests + } + const problems = [] + for (const suite of ['e2e', 'pwa-boundary', 'v2']) { + const base = load('base', suite) + const head = load('head', suite) + const confirm = load('head', suite, 'confirm.json') + const count = (tests) => (tests ? [...tests.values()].filter(passed).length : 0) + console.log(`${suite}: base passed ${count(base)}/${base?.size ?? 0}, head passed ${count(head)}/${head?.size ?? 0}`) + if (count(base) === 0) problems.push(`${suite}: no passing test on base (missing or broken harness)`) + if (count(head) === 0) problems.push(`${suite}: no passing test on head (missing or broken harness)`) + for (const [id, status] of head ?? []) { + if (status !== 'unexpected') continue + if (passed(confirm?.get(id))) { + console.log(` passed on the one-worker re-run (load flake, not blocking): ${id}`) + continue + } + const before = base?.get(id) + if (before === undefined) problems.push(`${suite}: new test fails on head: ${id}`) + else if (passed(before)) problems.push(`${suite}: passed on base, fails on head: ${id}`) + else console.log(` also fails on base (not blocking): ${id}`) + } + } + for (const problem of problems) console.log(`::error::${problem}`) + console.log(problems.length ? `${problems.length} blocking problem(s).` : 'No new failures.') + process.exit(problems.length ? 1 : 0) + EOF diff --git a/CLAUDE.md b/CLAUDE.md index df0c7528..d3554564 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -51,6 +51,7 @@ two is the remaining merge. - **Do not scaffold deferred ideas.** Future-facing fields, states, routes, or abstractions require an approved ROADMAP item that explicitly authorizes implementation; listing an idea as deferred does not. - **No identity in analytics either** — no room slug, no member name, no amount. The slug is the room's access control; a name is what someone chose to show their friends. Rooms are grouped by `analyticsKey`, a one-way digest of the room UUID issued by the server — it cannot be turned back into a room, and the slug still never leaves the device. Attach it with `roomProps(slug, …)`, which looks the key up; never put a slug in a property bag. - Dependencies must be ≥14 days old (`.npmrc` enforces it). +- **API routes stay backward compatible with every shipped app build.** The store apps have no over-the-air updates, so an old binary keeps calling the live API for months. A change an older build cannot handle raises `minBuild` in `apps/web/public/app-config.json` in the same push. - Run `pnpm typecheck && pnpm test && pnpm format` before pushing. Run `pnpm format` from `apps/web`, never the repo root — the root config can't resolve `prettier-plugin-tailwindcss` and reformats CI yaml as a side effect. ## Local dev @@ -60,6 +61,8 @@ pnpm bootstrap # NOT plain `pnpm install` — see below pnpm dev # API :5051 + web :3000 (or dev:api / dev:web for one) ``` +The iOS and Android apps (Capacitor, `apps/web/ios` and `apps/web/android`) bundle a static export of the app: `pnpm --dir apps/web native:build` builds it into `apps/web/.next-native`, and `pnpm --dir apps/web native:sync` builds it and copies it into both native projects. Details: [`docs/current/NATIVE.md`](docs/current/NATIVE.md). + `apps/web` is not a workspace member, which has one sharp edge: running `pnpm install` inside `apps/web` walks _up_ and installs the workspace instead, leaving `apps/web/node_modules` missing. It needs `--ignore-workspace`, which is diff --git a/ROADMAP.md b/ROADMAP.md index 5fbb42fd..c2854f90 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -7,6 +7,20 @@ deliberately not built — with enough context to pick any item up cold. Owner of record for each open item is in brackets. Last full update: 2026-08-12. +## In progress — native iOS and Android apps [Konrad] + +- Konrad's instruction of 2026-11-14 reopened native apps: ship Peanut Split to the App Store and + Google Play, built with Capacitor ("don't overcomplicate; I don't expect many UX differences + between the two"). This item authorizes that work; it moved here from "Deliberately not building". +- Branch `native-apps` holds the apps: one codebase, a static export of the app surface bundled in + each binary, no over-the-air updates. The room link stays the only link, and the apps stay + accountless. No room or identity transfer between browser and app: `docs/NATIVE-MIGRATION.md`'s + transfer code is not built. +- How it works: [`docs/current/NATIVE.md`](docs/current/NATIVE.md). What Hugo and Konrad still do + before submission (accounts, secrets, production env, store consoles): + [`docs/NATIVE-HANDOFF.md`](docs/NATIVE-HANDOFF.md). Store texts and declarations: + `apps/web/store/`. + ## Open — SEO issues tracker from the 2026-08-14 audit [Konrad] - A 14-agent audit (every finding reproduced by an independent verifier) confirmed 49 @@ -805,11 +819,7 @@ the one-month kill condition can't justify. The bunq/Tricount post-mortem in flat rooms are the design (see SPEC). - **Budgets, analytics dashboards, AI chat agent** — a second product inside Split. -- **Native apps, monetization features** — out of scope for the bet. If native - is ever reopened, the migration cost is already mapped in - `docs/NATIVE-MIGRATION.md` (server schema unaffected; the room list in - `ps:recent` is the only unrecoverable state; a transfer code is a copy, not - a sync, and has no lost-device recovery). That document authorizes nothing. +- **Monetization features** — out of scope for the bet. ## Known debt diff --git a/THIRD_PARTY_LICENSES.md b/THIRD_PARTY_LICENSES.md index 93a08542..55e9b92a 100644 --- a/THIRD_PARTY_LICENSES.md +++ b/THIRD_PARTY_LICENSES.md @@ -6,7 +6,7 @@ Every installed dependency of Peanut Split and the license it ships under, acros lockfiles. Prose notices for the material that needs one — fonts, icon geometry, quoted competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). -826 packages, 15 license classes. +900 packages, 17 license classes. | License | Packages | | --- | ---: | @@ -14,17 +14,19 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). | `(MIT OR CC0-1.0)` | 4 | | `(MPL-2.0 OR Apache-2.0)` | 1 | | `0BSD` | 1 | -| `Apache-2.0` | 48 | +| `Apache-2.0` | 49 | | `Apache-2.0 AND MIT` | 1 | -| `BSD-2-Clause` | 10 | +| `BSD-2-Clause` | 11 | | `BSD-3-Clause` | 24 | -| `BlueOak-1.0.0` | 5 | +| `BlueOak-1.0.0` | 11 | | `CC-BY-4.0` | 1 | | `FSL-1.1-MIT` | 2 | -| `ISC` | 37 | +| `ISC` | 42 | | `LGPL-3.0-or-later` | 1 | -| `MIT` | 688 | +| `MIT` | 747 | | `MPL-2.0` | 2 | +| `OFL-1.1` | 1 | +| `Unlicense` | 1 | ## (Apache-2.0 AND MIT) @@ -82,6 +84,7 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `detect-libc@2.1.2` - `didyoumean@1.2.2` - `ecdsa-sig-formatter@1.0.11` +- `elementtree@0.1.7` - `expect-type@1.4.0` - `fb-watchman@2.0.2` - `human-signals@2.1.0` @@ -104,6 +107,7 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `dotenv@16.6.1` - `dotenv@17.4.2` +- `entities@7.0.1` - `eslint-scope@5.1.1` - `esprima@4.0.1` - `esrecurse@4.3.0` @@ -142,11 +146,17 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). ## BlueOak-1.0.0 +- `chownr@3.0.0` - `glob@13.0.6` - `lru-cache@11.5.3` - `minimatch@10.2.6` - `minipass@7.1.3` +- `package-json-from-dist@1.0.1` - `path-scurry@2.0.2` +- `rimraf@6.1.3` +- `sax@1.6.1` +- `tar@7.5.22` +- `yallist@5.0.0` ## CC-BY-4.0 @@ -159,9 +169,12 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). ## ISC +- `@capacitor/synapse@1.0.4` +- `@isaacs/fs-minipass@4.0.1` - `@istanbuljs/load-nyc-config@1.1.0` - `@ungap/structured-clone@1.4.0` - `anymatch@3.1.3` +- `at-least-node@1.0.0` - `cliui@8.0.1` - `electron-to-chromium@1.5.440` - `fastq@1.20.3` @@ -174,6 +187,7 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `idb@8.0.3` - `inflight@1.0.6` - `inherits@2.0.4` +- `ini@4.1.3` - `isexe@2.0.0` - `lru-cache@5.1.1` - `make-error@1.3.6` @@ -182,6 +196,7 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `once@1.4.0` - `picocolors@1.1.1` - `qrcode.react@4.2.0` +- `sax@1.1.4` - `semver@6.3.1` - `semver@7.8.5` - `siginfo@2.0.0` @@ -239,6 +254,18 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `@babel/traverse@7.29.8` - `@babel/types@7.29.8` - `@bcoe/v8-coverage@0.2.3` +- `@capacitor/android@8.2.0` +- `@capacitor/app@8.1.2` +- `@capacitor/browser@8.0.5` +- `@capacitor/cli@8.2.0` +- `@capacitor/core@8.2.0` +- `@capacitor/filesystem@8.1.5` +- `@capacitor/ios@8.2.0` +- `@capacitor/preferences@8.0.1` +- `@capacitor/push-notifications@8.1.3` +- `@capacitor/share@8.0.3` +- `@capacitor/splash-screen@8.0.2` +- `@capacitor/status-bar@8.0.4` - `@eloqnt/config@0.1.1` - `@eloqnt/format-json@0.1.0` - `@eloqnt/format-po@0.1.1` @@ -261,6 +288,14 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `@formatjs/intl-localematcher@0.8.14` - `@headlessui/tailwindcss@0.2.2` - `@img/colour@1.1.0` +- `@ionic/cli-framework-output@2.2.8` +- `@ionic/utils-array@2.1.6` +- `@ionic/utils-fs@3.1.7` +- `@ionic/utils-object@2.1.6` +- `@ionic/utils-process@2.1.12` +- `@ionic/utils-stream@3.1.7` +- `@ionic/utils-subprocess@3.0.1` +- `@ionic/utils-terminal@2.3.5` - `@istanbuljs/schema@0.1.6` - `@jest/console@29.7.0` - `@jest/core@29.7.0` @@ -354,6 +389,7 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `@types/deep-eql@4.0.2` - `@types/estree-jsx@1.0.5` - `@types/estree@1.0.9` +- `@types/fs-extra@8.1.5` - `@types/graceful-fs@4.1.9` - `@types/hast@3.0.5` - `@types/istanbul-lib-coverage@2.0.6` @@ -368,11 +404,14 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `@types/node@22.20.4` - `@types/react-dom@19.3.0` - `@types/react@19.3.0` +- `@types/slice-ansi@4.0.0` - `@types/stack-utils@2.0.3` - `@types/trusted-types@2.0.7` - `@types/unist@2.0.11` - `@types/unist@3.0.3` - `@types/web-push@3.6.4` +- `@types/whatwg-mimetype@3.0.2` +- `@types/ws@8.18.2` - `@types/yargs-parser@21.0.3` - `@types/yargs@17.0.35` - `@vitest/expect@4.1.11` @@ -396,6 +435,7 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `@webassemblyjs/wasm-opt@1.14.1` - `@webassemblyjs/wasm-parser@1.14.1` - `@webassemblyjs/wast-printer@1.14.1` +- `@xmldom/xmldom@0.9.12` - `abstract-logging@2.0.1` - `acorn-import-phases@1.0.4` - `acorn-jsx@5.3.2` @@ -416,6 +456,7 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `aria-hidden@1.2.6` - `asn1.js@5.4.1` - `assertion-error@2.0.1` +- `astral-regex@2.0.0` - `astring@1.9.0` - `atomic-sleep@1.0.0` - `autoprefixer@10.6.1` @@ -427,14 +468,18 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `bail@2.0.2` - `balanced-match@1.0.2` - `balanced-match@4.0.4` +- `base64-js@1.5.1` - `binary-extensions@2.3.0` - `bn.js@4.12.5` +- `bplist-parser@0.3.2` - `brace-expansion@1.1.21` - `brace-expansion@5.0.12` - `braces@3.0.3` - `browserslist@4.29.2` - `bs-logger@0.2.6` +- `buffer-crc32@0.2.13` - `buffer-from@1.1.2` +- `buffer-image-size@0.6.4` - `c12@3.1.0` - `callsites@3.1.0` - `camelcase-css@2.0.1` @@ -463,6 +508,7 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `color-convert@2.0.1` - `color-name@1.1.4` - `comma-separated-tokens@2.0.3` +- `commander@12.1.0` - `commander@2.20.3` - `commander@4.1.1` - `common-tags@1.8.2` @@ -483,6 +529,7 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `decode-named-character-reference@1.3.0` - `dedent@1.7.2` - `deepmerge@4.3.1` +- `define-lazy-prop@2.0.0` - `defu@6.1.7` - `dequal@2.0.3` - `destr@2.0.5` @@ -497,6 +544,7 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `emoji-regex@8.0.0` - `empathic@2.0.0` - `enhanced-resolve@5.25.1` +- `env-paths@2.2.1` - `error-ex@1.3.4` - `es-errors@1.3.0` - `es-module-lexer@2.3.2` @@ -533,6 +581,7 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `fastest-levenshtein@1.0.16` - `fastify-plugin@6.0.0` - `fastify@5.12.5` +- `fd-slicer@1.1.0` - `fdir@6.5.0` - `fflate@0.4.9` - `fill-range@7.1.1` @@ -541,6 +590,8 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `find-up@5.0.0` - `fraction.js@5.3.4` - `framer-motion@12.43.0` +- `fs-extra@11.4.1` +- `fs-extra@9.1.0` - `function-bind@1.1.2` - `gensync@1.0.0-beta.2` - `get-nonce@1.0.1` @@ -549,6 +600,7 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `giget@2.0.0` - `gray-matter@4.0.3` - `handlebars@4.7.9` +- `happy-dom@21.0.4` - `has-flag@4.0.0` - `hasown@2.0.4` - `hast-util-to-estree@3.1.3` @@ -570,6 +622,7 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `is-binary-path@2.1.0` - `is-core-module@2.17.0` - `is-decimal@2.0.1` +- `is-docker@2.2.1` - `is-extendable@0.1.1` - `is-extglob@2.1.1` - `is-fullwidth-code-point@3.0.0` @@ -580,6 +633,7 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `is-plain-obj@4.1.0` - `is-reference@1.2.1` - `is-stream@2.0.1` +- `is-wsl@2.2.0` - `jest-changed-files@29.7.0` - `jest-circus@29.7.0` - `jest-cli@29.7.0` @@ -616,10 +670,12 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `json-schema-ref-resolver@3.0.0` - `json-schema-traverse@1.0.0` - `json5@2.2.3` +- `jsonfile@6.2.1` - `jwa@2.0.1` - `jws@4.0.1` - `kind-of@6.0.3` - `kleur@3.0.3` +- `kleur@4.1.5` - `kolorist@1.8.0` - `leven@3.1.0` - `lilconfig@3.1.3` @@ -692,6 +748,7 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `mimic-fn@2.1.0` - `minimist@1.2.8` - `minimizer-webpack-plugin@5.12.0` +- `minizlib@3.1.0` - `module-details-from-path@1.0.4` - `motion-dom@12.43.0` - `motion-utils@12.39.0` @@ -699,6 +756,7 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `ms@2.1.3` - `mz@2.7.0` - `nanoid@3.3.19` +- `native-run@2.0.3` - `natural-compare@1.4.0` - `negotiator@1.1.0` - `neo-async@2.6.2` @@ -721,6 +779,7 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `ohash@2.0.12` - `on-exit-leak-free@2.1.2` - `onetime@5.1.2` +- `open@8.4.2` - `p-limit@2.3.0` - `p-limit@3.1.0` - `p-locate@4.1.0` @@ -733,6 +792,7 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `path-key@3.1.1` - `path-parse@1.0.7` - `pathe@2.0.3` +- `pend@1.2.0` - `perfect-debounce@1.0.0` - `picomatch@2.3.2` - `picomatch@4.0.7` @@ -742,6 +802,7 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `pirates@4.0.7` - `pkg-dir@4.2.0` - `pkg-types@2.3.3` +- `plist@3.1.1` - `po-parser@2.2.0` - `postcss-import@15.1.0` - `postcss-import@16.2.0` @@ -776,6 +837,7 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `react-style-singleton@2.2.3` - `react@19.3.0` - `read-cache@1.0.2` +- `readable-stream@3.6.2` - `readdirp@3.6.0` - `readdirp@4.1.2` - `real-require@0.2.0` @@ -814,6 +876,7 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `shebang-regex@3.0.0` - `sisteransi@1.0.5` - `slash@3.0.0` +- `slice-ansi@4.0.0` - `sonic-boom@4.2.1` - `sonner@2.0.8` - `source-map-support@0.5.13` @@ -823,6 +886,7 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `stackback@0.0.2` - `stacktrace-parser@0.1.11` - `std-env@4.2.0` +- `string_decoder@1.3.0` - `string-length@4.0.2` - `string-width@4.2.3` - `stringify-entities@4.0.4` @@ -846,6 +910,7 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `thenify-all@1.6.0` - `thenify@3.3.1` - `thread-stream@3.2.0` +- `through2@4.0.2` - `tinybench@2.9.0` - `tinyexec@1.3.1` - `tinyglobby@0.2.17` @@ -853,6 +918,7 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `to-regex-range@5.0.1` - `toad-cache@3.7.4` - `tr46@0.0.3` +- `tree-kill@1.2.2` - `trim-lines@3.0.1` - `trough@2.2.0` - `ts-jest@29.4.14` @@ -868,6 +934,8 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `unist-util-stringify-position@4.0.0` - `unist-util-visit-parents@6.0.2` - `unist-util-visit@5.1.0` +- `universalify@2.0.1` +- `untildify@4.0.0` - `update-browserslist-db@1.3.3` - `use-callback-ref@1.3.3` - `use-intl@4.14.8` @@ -882,11 +950,17 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `watchpack@2.5.2` - `webpack-sources@3.6.0` - `webpack@5.108.4` +- `whatwg-mimetype@3.0.0` - `whatwg-url@5.0.0` - `why-is-node-running@2.3.0` - `wordwrap@1.0.0` - `wrap-ansi@7.0.0` +- `ws@8.22.1` +- `xml2js@0.6.2` +- `xmlbuilder@11.0.1` +- `xmlbuilder@15.1.1` - `yargs@17.7.3` +- `yauzl@2.10.0` - `yocto-queue@0.1.0` - `zod@3.24.1` - `zod@4.4.3` @@ -896,3 +970,11 @@ competitor copy — are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - `next-mdx-remote@6.0.0` - `web-push@3.6.7` + +## OFL-1.1 + +- `@fontsource-variable/roboto-flex@5.3.0` + +## Unlicense + +- `big-integer@1.6.52` diff --git a/apps/web/.dockerignore b/apps/web/.dockerignore index 9d5dc0be..6f35959a 100644 --- a/apps/web/.dockerignore +++ b/apps/web/.dockerignore @@ -4,6 +4,11 @@ node_modules .github e2e e2e-v2 +e2e-native +ios +android +.next-native +resources docs local *.log diff --git a/apps/web/.gitignore b/apps/web/.gitignore index b90f7c37..db14e762 100644 --- a/apps/web/.gitignore +++ b/apps/web/.gitignore @@ -1,5 +1,6 @@ node_modules/ .next/ +.next-native/ out/ build/ .pnpm-store/ @@ -25,3 +26,6 @@ test-results/ .vscode/ local/ *.tsbuildinfo + +# Raw store captures and the review contact sheet (e2e-native/store-screenshots.spec.ts) +store/captures/ diff --git a/apps/web/.prettierignore b/apps/web/.prettierignore index 11aa7134..36e6b56d 100644 --- a/apps/web/.prettierignore +++ b/apps/web/.prettierignore @@ -5,3 +5,7 @@ pnpm-lock.yaml next-env.d.ts docs/ src/generated/seo/ +ios/ +android/ +.next-native/ +resources/ diff --git a/apps/web/Dockerfile b/apps/web/Dockerfile index a06a1521..598e4ea5 100644 --- a/apps/web/Dockerfile +++ b/apps/web/Dockerfile @@ -48,6 +48,11 @@ ARG NEXT_PUBLIC_POSTHOG_HOST ENV NEXT_PUBLIC_POSTHOG_HOST=$NEXT_PUBLIC_POSTHOG_HOST ARG NEXT_PUBLIC_VAPID_PUBLIC_KEY ENV NEXT_PUBLIC_VAPID_PUBLIC_KEY=$NEXT_PUBLIC_VAPID_PUBLIC_KEY +# The iOS app's numeric App Store ID. Empty keeps every store offer (Smart App Banner, "Get the app") +# off, so the web behaves as before until the app is live. Android has no store ID on purpose: +# Android browsers keep the PWA install, which keeps every room. +ARG NEXT_PUBLIC_IOS_APP_STORE_ID= +ENV NEXT_PUBLIC_IOS_APP_STORE_ID=$NEXT_PUBLIC_IOS_APP_STORE_ID RUN pnpm build # ---- runtime ---------------------------------------------------------------- diff --git a/apps/web/android/.gitignore b/apps/web/android/.gitignore new file mode 100644 index 00000000..b4f66d47 --- /dev/null +++ b/apps/web/android/.gitignore @@ -0,0 +1,107 @@ +# Using Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore + +# Built application files +*.apk +*.aar +*.ap_ +*.aab + +# Files for the ART/Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +bin/ +gen/ +out/ +# Uncomment the following line in case you need and you don't have the release build type files in your app +# release/ + +# Gradle files +.gradle/ +build/ + +# Local configuration file (sdk path, etc) +local.properties + +# Proguard folder generated by Eclipse +proguard/ + +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation/ + +# Android Studio captures folder +captures/ + +# IntelliJ +*.iml +.idea/workspace.xml +.idea/tasks.xml +.idea/gradle.xml +.idea/assetWizardSettings.xml +.idea/dictionaries +.idea/libraries +# Android Studio 3 in .gitignore file. +.idea/caches +.idea/modules.xml +# Comment next line if keeping position of elements in Navigation Editor is relevant for you +.idea/navEditor.xml + +# Keystore files +# Uncomment the following lines if you do not want to check your keystore files in. +#*.jks +#*.keystore + +# External native build folder generated in Android Studio 2.2 and later +.externalNativeBuild +.cxx/ + +# Google Services (e.g. APIs or Firebase) +# google-services.json + +# Freeline +freeline.py +freeline/ +freeline_project_description.json + +# fastlane +fastlane/report.xml +fastlane/Preview.html +fastlane/screenshots +fastlane/test_output +fastlane/readme.md + +# Version control +vcs.xml + +# lint +lint/intermediates/ +lint/generated/ +lint/outputs/ +lint/tmp/ +# lint/reports/ + +# Android Profiling +*.hprof + +# Cordova plugins for Capacitor +capacitor-cordova-android-plugins + +# Copied web assets +app/src/main/assets/public + +# Generated Config files +app/src/main/assets/capacitor.config.json +app/src/main/assets/capacitor.plugins.json +app/src/main/res/xml/config.xml + +# Release secrets, written only by native-release.yml +keystore.properties +*.jks +*.keystore +app/google-services.json diff --git a/apps/web/android/app/.gitignore b/apps/web/android/app/.gitignore new file mode 100644 index 00000000..043df802 --- /dev/null +++ b/apps/web/android/app/.gitignore @@ -0,0 +1,2 @@ +/build/* +!/build/.npmkeep diff --git a/apps/web/android/app/build.gradle b/apps/web/android/app/build.gradle new file mode 100644 index 00000000..5f0b5d57 --- /dev/null +++ b/apps/web/android/app/build.gradle @@ -0,0 +1,76 @@ +apply plugin: 'com.android.application' + +// Release signing comes from keystore.properties (storeFile, storePassword, keyAlias, keyPassword), +// which only the release lane writes. Without it CI builds an unsigned bundle and needs no secrets. +def keystorePropertiesFile = rootProject.file('keystore.properties') +def keystoreProperties = new Properties() +if (keystorePropertiesFile.exists()) { + keystorePropertiesFile.withInputStream { keystoreProperties.load(it) } +} + +android { + namespace = "com.peanutsplit.app" + compileSdk = rootProject.ext.compileSdkVersion + defaultConfig { + applicationId "com.peanutsplit.app" + minSdkVersion rootProject.ext.minSdkVersion + targetSdkVersion rootProject.ext.targetSdkVersion + // The release lane passes both (scripts/native/version-code.mjs and the tag); local and + // debug builds fall back to 1 and 1.0. + versionCode((System.getenv('VERSION_CODE') ?: '1') as Integer) + versionName(System.getenv('VERSION_NAME') ?: '1.0') + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + aaptOptions { + // Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps. + // Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61 + ignoreAssetsPattern = '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~' + } + } + if (keystorePropertiesFile.exists()) { + signingConfigs { + release { + storeFile rootProject.file(keystoreProperties['storeFile']) + storePassword keystoreProperties['storePassword'] + keyAlias keystoreProperties['keyAlias'] + keyPassword keystoreProperties['keyPassword'] + } + } + } + buildTypes { + release { + if (keystorePropertiesFile.exists()) { + signingConfig signingConfigs.release + } + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +repositories { + flatDir{ + dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs' + } +} + +dependencies { + implementation fileTree(include: ['*.jar'], dir: 'libs') + implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion" + implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion" + implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion" + implementation project(':capacitor-android') + testImplementation "junit:junit:$junitVersion" + androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion" + androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion" + implementation project(':capacitor-cordova-android-plugins') +} + +apply from: 'capacitor.build.gradle' + +// Firebase (Android push) only when google-services.json exists: the release lane writes it from a +// secret, and debug CI builds stay green without it (ARCHITECTURE 10.3). +if (file('google-services.json').exists()) { + apply plugin: 'com.google.gms.google-services' +} else { + logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work") +} diff --git a/apps/web/android/app/capacitor.build.gradle b/apps/web/android/app/capacitor.build.gradle new file mode 100644 index 00000000..0b22dbda --- /dev/null +++ b/apps/web/android/app/capacitor.build.gradle @@ -0,0 +1,26 @@ +// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN + +android { + compileOptions { + sourceCompatibility JavaVersion.VERSION_21 + targetCompatibility JavaVersion.VERSION_21 + } +} + +apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle" +dependencies { + implementation project(':capacitor-app') + implementation project(':capacitor-browser') + implementation project(':capacitor-filesystem') + implementation project(':capacitor-preferences') + implementation project(':capacitor-push-notifications') + implementation project(':capacitor-share') + implementation project(':capacitor-splash-screen') + implementation project(':capacitor-status-bar') + +} + + +if (hasProperty('postBuildExtras')) { + postBuildExtras() +} diff --git a/apps/web/android/app/proguard-rules.pro b/apps/web/android/app/proguard-rules.pro new file mode 100644 index 00000000..f1b42451 --- /dev/null +++ b/apps/web/android/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/apps/web/android/app/src/androidTest/java/com/getcapacitor/myapp/ExampleInstrumentedTest.java b/apps/web/android/app/src/androidTest/java/com/getcapacitor/myapp/ExampleInstrumentedTest.java new file mode 100644 index 00000000..f2c2217e --- /dev/null +++ b/apps/web/android/app/src/androidTest/java/com/getcapacitor/myapp/ExampleInstrumentedTest.java @@ -0,0 +1,26 @@ +package com.getcapacitor.myapp; + +import static org.junit.Assert.*; + +import android.content.Context; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import androidx.test.platform.app.InstrumentationRegistry; +import org.junit.Test; +import org.junit.runner.RunWith; + +/** + * Instrumented test, which will execute on an Android device. + * + * @see Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class ExampleInstrumentedTest { + + @Test + public void useAppContext() throws Exception { + // Context of the app under test. + Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); + + assertEquals("com.getcapacitor.app", appContext.getPackageName()); + } +} diff --git a/apps/web/android/app/src/main/AndroidManifest.xml b/apps/web/android/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000..2db486c9 --- /dev/null +++ b/apps/web/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/web/android/app/src/main/java/com/peanutsplit/app/MainActivity.java b/apps/web/android/app/src/main/java/com/peanutsplit/app/MainActivity.java new file mode 100644 index 00000000..0a891681 --- /dev/null +++ b/apps/web/android/app/src/main/java/com/peanutsplit/app/MainActivity.java @@ -0,0 +1,5 @@ +package com.peanutsplit.app; + +import com.getcapacitor.BridgeActivity; + +public class MainActivity extends BridgeActivity {} diff --git a/apps/web/android/app/src/main/res/drawable-hdpi/ic_stat_split.png b/apps/web/android/app/src/main/res/drawable-hdpi/ic_stat_split.png new file mode 100644 index 00000000..f31a4c7b Binary files /dev/null and b/apps/web/android/app/src/main/res/drawable-hdpi/ic_stat_split.png differ diff --git a/apps/web/android/app/src/main/res/drawable-land-hdpi/splash.png b/apps/web/android/app/src/main/res/drawable-land-hdpi/splash.png new file mode 100644 index 00000000..2f970e37 Binary files /dev/null and b/apps/web/android/app/src/main/res/drawable-land-hdpi/splash.png differ diff --git a/apps/web/android/app/src/main/res/drawable-land-ldpi/splash.png b/apps/web/android/app/src/main/res/drawable-land-ldpi/splash.png new file mode 100644 index 00000000..23850bd1 Binary files /dev/null and b/apps/web/android/app/src/main/res/drawable-land-ldpi/splash.png differ diff --git a/apps/web/android/app/src/main/res/drawable-land-mdpi/splash.png b/apps/web/android/app/src/main/res/drawable-land-mdpi/splash.png new file mode 100644 index 00000000..f38dbc8f Binary files /dev/null and b/apps/web/android/app/src/main/res/drawable-land-mdpi/splash.png differ diff --git a/apps/web/android/app/src/main/res/drawable-land-xhdpi/splash.png b/apps/web/android/app/src/main/res/drawable-land-xhdpi/splash.png new file mode 100644 index 00000000..f1c56b00 Binary files /dev/null and b/apps/web/android/app/src/main/res/drawable-land-xhdpi/splash.png differ diff --git a/apps/web/android/app/src/main/res/drawable-land-xxhdpi/splash.png b/apps/web/android/app/src/main/res/drawable-land-xxhdpi/splash.png new file mode 100644 index 00000000..5f899c84 Binary files /dev/null and b/apps/web/android/app/src/main/res/drawable-land-xxhdpi/splash.png differ diff --git a/apps/web/android/app/src/main/res/drawable-land-xxxhdpi/splash.png b/apps/web/android/app/src/main/res/drawable-land-xxxhdpi/splash.png new file mode 100644 index 00000000..7b2b06f2 Binary files /dev/null and b/apps/web/android/app/src/main/res/drawable-land-xxxhdpi/splash.png differ diff --git a/apps/web/android/app/src/main/res/drawable-mdpi/ic_stat_split.png b/apps/web/android/app/src/main/res/drawable-mdpi/ic_stat_split.png new file mode 100644 index 00000000..1ecc8b19 Binary files /dev/null and b/apps/web/android/app/src/main/res/drawable-mdpi/ic_stat_split.png differ diff --git a/apps/web/android/app/src/main/res/drawable-port-hdpi/splash.png b/apps/web/android/app/src/main/res/drawable-port-hdpi/splash.png new file mode 100644 index 00000000..938601ae Binary files /dev/null and b/apps/web/android/app/src/main/res/drawable-port-hdpi/splash.png differ diff --git a/apps/web/android/app/src/main/res/drawable-port-ldpi/splash.png b/apps/web/android/app/src/main/res/drawable-port-ldpi/splash.png new file mode 100644 index 00000000..5575bede Binary files /dev/null and b/apps/web/android/app/src/main/res/drawable-port-ldpi/splash.png differ diff --git a/apps/web/android/app/src/main/res/drawable-port-mdpi/splash.png b/apps/web/android/app/src/main/res/drawable-port-mdpi/splash.png new file mode 100644 index 00000000..c7c29aa4 Binary files /dev/null and b/apps/web/android/app/src/main/res/drawable-port-mdpi/splash.png differ diff --git a/apps/web/android/app/src/main/res/drawable-port-xhdpi/splash.png b/apps/web/android/app/src/main/res/drawable-port-xhdpi/splash.png new file mode 100644 index 00000000..dac4adfa Binary files /dev/null and b/apps/web/android/app/src/main/res/drawable-port-xhdpi/splash.png differ diff --git a/apps/web/android/app/src/main/res/drawable-port-xxhdpi/splash.png b/apps/web/android/app/src/main/res/drawable-port-xxhdpi/splash.png new file mode 100644 index 00000000..c588137b Binary files /dev/null and b/apps/web/android/app/src/main/res/drawable-port-xxhdpi/splash.png differ diff --git a/apps/web/android/app/src/main/res/drawable-port-xxxhdpi/splash.png b/apps/web/android/app/src/main/res/drawable-port-xxxhdpi/splash.png new file mode 100644 index 00000000..4f575a41 Binary files /dev/null and b/apps/web/android/app/src/main/res/drawable-port-xxxhdpi/splash.png differ diff --git a/apps/web/android/app/src/main/res/drawable-xhdpi/ic_stat_split.png b/apps/web/android/app/src/main/res/drawable-xhdpi/ic_stat_split.png new file mode 100644 index 00000000..8d213837 Binary files /dev/null and b/apps/web/android/app/src/main/res/drawable-xhdpi/ic_stat_split.png differ diff --git a/apps/web/android/app/src/main/res/drawable-xxhdpi/ic_stat_split.png b/apps/web/android/app/src/main/res/drawable-xxhdpi/ic_stat_split.png new file mode 100644 index 00000000..189d83e7 Binary files /dev/null and b/apps/web/android/app/src/main/res/drawable-xxhdpi/ic_stat_split.png differ diff --git a/apps/web/android/app/src/main/res/drawable-xxxhdpi/ic_stat_split.png b/apps/web/android/app/src/main/res/drawable-xxxhdpi/ic_stat_split.png new file mode 100644 index 00000000..0b980757 Binary files /dev/null and b/apps/web/android/app/src/main/res/drawable-xxxhdpi/ic_stat_split.png differ diff --git a/apps/web/android/app/src/main/res/drawable/splash.png b/apps/web/android/app/src/main/res/drawable/splash.png new file mode 100644 index 00000000..c7c29aa4 Binary files /dev/null and b/apps/web/android/app/src/main/res/drawable/splash.png differ diff --git a/apps/web/android/app/src/main/res/layout/activity_main.xml b/apps/web/android/app/src/main/res/layout/activity_main.xml new file mode 100644 index 00000000..b5ad1387 --- /dev/null +++ b/apps/web/android/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,12 @@ + + + + + diff --git a/apps/web/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/apps/web/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 00000000..0aa82aa1 --- /dev/null +++ b/apps/web/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/apps/web/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/apps/web/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 00000000..0aa82aa1 --- /dev/null +++ b/apps/web/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/apps/web/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/apps/web/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 00000000..4624f98d Binary files /dev/null and b/apps/web/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/apps/web/android/app/src/main/res/mipmap-hdpi/ic_launcher_background.png b/apps/web/android/app/src/main/res/mipmap-hdpi/ic_launcher_background.png new file mode 100644 index 00000000..985e5005 Binary files /dev/null and b/apps/web/android/app/src/main/res/mipmap-hdpi/ic_launcher_background.png differ diff --git a/apps/web/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png b/apps/web/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..9a3305bc Binary files /dev/null and b/apps/web/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png differ diff --git a/apps/web/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/apps/web/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png new file mode 100644 index 00000000..017edd17 Binary files /dev/null and b/apps/web/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png differ diff --git a/apps/web/android/app/src/main/res/mipmap-ldpi/ic_launcher.png b/apps/web/android/app/src/main/res/mipmap-ldpi/ic_launcher.png new file mode 100644 index 00000000..aaedc25a Binary files /dev/null and b/apps/web/android/app/src/main/res/mipmap-ldpi/ic_launcher.png differ diff --git a/apps/web/android/app/src/main/res/mipmap-ldpi/ic_launcher_background.png b/apps/web/android/app/src/main/res/mipmap-ldpi/ic_launcher_background.png new file mode 100644 index 00000000..c7476d95 Binary files /dev/null and b/apps/web/android/app/src/main/res/mipmap-ldpi/ic_launcher_background.png differ diff --git a/apps/web/android/app/src/main/res/mipmap-ldpi/ic_launcher_foreground.png b/apps/web/android/app/src/main/res/mipmap-ldpi/ic_launcher_foreground.png new file mode 100644 index 00000000..3a0aef64 Binary files /dev/null and b/apps/web/android/app/src/main/res/mipmap-ldpi/ic_launcher_foreground.png differ diff --git a/apps/web/android/app/src/main/res/mipmap-ldpi/ic_launcher_round.png b/apps/web/android/app/src/main/res/mipmap-ldpi/ic_launcher_round.png new file mode 100644 index 00000000..8bdea157 Binary files /dev/null and b/apps/web/android/app/src/main/res/mipmap-ldpi/ic_launcher_round.png differ diff --git a/apps/web/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/apps/web/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 00000000..051add13 Binary files /dev/null and b/apps/web/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/apps/web/android/app/src/main/res/mipmap-mdpi/ic_launcher_background.png b/apps/web/android/app/src/main/res/mipmap-mdpi/ic_launcher_background.png new file mode 100644 index 00000000..ca26da79 Binary files /dev/null and b/apps/web/android/app/src/main/res/mipmap-mdpi/ic_launcher_background.png differ diff --git a/apps/web/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png b/apps/web/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..716b51f1 Binary files /dev/null and b/apps/web/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png differ diff --git a/apps/web/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/apps/web/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png new file mode 100644 index 00000000..94ae71b2 Binary files /dev/null and b/apps/web/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png differ diff --git a/apps/web/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/apps/web/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 00000000..82ff04d1 Binary files /dev/null and b/apps/web/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/apps/web/android/app/src/main/res/mipmap-xhdpi/ic_launcher_background.png b/apps/web/android/app/src/main/res/mipmap-xhdpi/ic_launcher_background.png new file mode 100644 index 00000000..9d23c525 Binary files /dev/null and b/apps/web/android/app/src/main/res/mipmap-xhdpi/ic_launcher_background.png differ diff --git a/apps/web/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png b/apps/web/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..f55aa7ff Binary files /dev/null and b/apps/web/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png differ diff --git a/apps/web/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/apps/web/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png new file mode 100644 index 00000000..7f1dd813 Binary files /dev/null and b/apps/web/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/apps/web/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/apps/web/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 00000000..3a11ea4f Binary files /dev/null and b/apps/web/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/apps/web/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.png b/apps/web/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.png new file mode 100644 index 00000000..a42091bc Binary files /dev/null and b/apps/web/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.png differ diff --git a/apps/web/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png b/apps/web/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..83af0977 Binary files /dev/null and b/apps/web/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png differ diff --git a/apps/web/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/apps/web/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png new file mode 100644 index 00000000..312ea5c4 Binary files /dev/null and b/apps/web/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/apps/web/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/apps/web/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 00000000..cf612c4e Binary files /dev/null and b/apps/web/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/apps/web/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.png b/apps/web/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.png new file mode 100644 index 00000000..b6d4c265 Binary files /dev/null and b/apps/web/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.png differ diff --git a/apps/web/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png b/apps/web/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..61cbf7df Binary files /dev/null and b/apps/web/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png differ diff --git a/apps/web/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/apps/web/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100644 index 00000000..b07b8dc7 Binary files /dev/null and b/apps/web/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/apps/web/android/app/src/main/res/values/colors.xml b/apps/web/android/app/src/main/res/values/colors.xml new file mode 100644 index 00000000..a7a7783d --- /dev/null +++ b/apps/web/android/app/src/main/res/values/colors.xml @@ -0,0 +1,5 @@ + + + + #FAF4F0 + diff --git a/apps/web/android/app/src/main/res/values/strings.xml b/apps/web/android/app/src/main/res/values/strings.xml new file mode 100644 index 00000000..ede85d6b --- /dev/null +++ b/apps/web/android/app/src/main/res/values/strings.xml @@ -0,0 +1,7 @@ + + + Split + Split + com.peanutsplit.app + com.peanutsplit.app + diff --git a/apps/web/android/app/src/main/res/values/styles.xml b/apps/web/android/app/src/main/res/values/styles.xml new file mode 100644 index 00000000..56777c91 --- /dev/null +++ b/apps/web/android/app/src/main/res/values/styles.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/apps/web/android/app/src/main/res/xml/file_paths.xml b/apps/web/android/app/src/main/res/xml/file_paths.xml new file mode 100644 index 00000000..63d8bf27 --- /dev/null +++ b/apps/web/android/app/src/main/res/xml/file_paths.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/apps/web/android/app/src/test/java/com/getcapacitor/myapp/ExampleUnitTest.java b/apps/web/android/app/src/test/java/com/getcapacitor/myapp/ExampleUnitTest.java new file mode 100644 index 00000000..02973278 --- /dev/null +++ b/apps/web/android/app/src/test/java/com/getcapacitor/myapp/ExampleUnitTest.java @@ -0,0 +1,18 @@ +package com.getcapacitor.myapp; + +import static org.junit.Assert.*; + +import org.junit.Test; + +/** + * Example local unit test, which will execute on the development machine (host). + * + * @see Testing documentation + */ +public class ExampleUnitTest { + + @Test + public void addition_isCorrect() throws Exception { + assertEquals(4, 2 + 2); + } +} diff --git a/apps/web/android/build.gradle b/apps/web/android/build.gradle new file mode 100644 index 00000000..f8f0e43b --- /dev/null +++ b/apps/web/android/build.gradle @@ -0,0 +1,29 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + + repositories { + google() + mavenCentral() + } + dependencies { + classpath 'com.android.tools.build:gradle:8.13.0' + classpath 'com.google.gms:google-services:4.4.4' + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +apply from: "variables.gradle" + +allprojects { + repositories { + google() + mavenCentral() + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/apps/web/android/capacitor.settings.gradle b/apps/web/android/capacitor.settings.gradle new file mode 100644 index 00000000..9ef36948 --- /dev/null +++ b/apps/web/android/capacitor.settings.gradle @@ -0,0 +1,27 @@ +// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN +include ':capacitor-android' +project(':capacitor-android').projectDir = new File('../node_modules/.pnpm/@capacitor+android@8.2.0_@capacitor+core@8.2.0/node_modules/@capacitor/android/capacitor') + +include ':capacitor-app' +project(':capacitor-app').projectDir = new File('../node_modules/.pnpm/@capacitor+app@8.1.2_@capacitor+core@8.2.0/node_modules/@capacitor/app/android') + +include ':capacitor-browser' +project(':capacitor-browser').projectDir = new File('../node_modules/.pnpm/@capacitor+browser@8.0.5_@capacitor+core@8.2.0/node_modules/@capacitor/browser/android') + +include ':capacitor-filesystem' +project(':capacitor-filesystem').projectDir = new File('../node_modules/.pnpm/@capacitor+filesystem@8.1.5_@capacitor+core@8.2.0/node_modules/@capacitor/filesystem/android') + +include ':capacitor-preferences' +project(':capacitor-preferences').projectDir = new File('../node_modules/.pnpm/@capacitor+preferences@8.0.1_@capacitor+core@8.2.0/node_modules/@capacitor/preferences/android') + +include ':capacitor-push-notifications' +project(':capacitor-push-notifications').projectDir = new File('../node_modules/.pnpm/@capacitor+push-notifications@8.1.3_@capacitor+core@8.2.0/node_modules/@capacitor/push-notifications/android') + +include ':capacitor-share' +project(':capacitor-share').projectDir = new File('../node_modules/.pnpm/@capacitor+share@8.0.3_@capacitor+core@8.2.0/node_modules/@capacitor/share/android') + +include ':capacitor-splash-screen' +project(':capacitor-splash-screen').projectDir = new File('../node_modules/.pnpm/@capacitor+splash-screen@8.0.2_@capacitor+core@8.2.0/node_modules/@capacitor/splash-screen/android') + +include ':capacitor-status-bar' +project(':capacitor-status-bar').projectDir = new File('../node_modules/.pnpm/@capacitor+status-bar@8.0.4_@capacitor+core@8.2.0/node_modules/@capacitor/status-bar/android') diff --git a/apps/web/android/gradle.properties b/apps/web/android/gradle.properties new file mode 100644 index 00000000..2e87c52f --- /dev/null +++ b/apps/web/android/gradle.properties @@ -0,0 +1,22 @@ +# Project-wide Gradle settings. + +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. + +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html + +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx1536m + +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true + +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app's APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true diff --git a/apps/web/android/gradle/wrapper/gradle-wrapper.jar b/apps/web/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..1b33c55b Binary files /dev/null and b/apps/web/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/apps/web/android/gradle/wrapper/gradle-wrapper.properties b/apps/web/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..7705927e --- /dev/null +++ b/apps/web/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-all.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/apps/web/android/gradlew b/apps/web/android/gradlew new file mode 100755 index 00000000..23d15a93 --- /dev/null +++ b/apps/web/android/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/apps/web/android/gradlew.bat b/apps/web/android/gradlew.bat new file mode 100644 index 00000000..5eed7ee8 --- /dev/null +++ b/apps/web/android/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/apps/web/android/settings.gradle b/apps/web/android/settings.gradle new file mode 100644 index 00000000..3b4431d7 --- /dev/null +++ b/apps/web/android/settings.gradle @@ -0,0 +1,5 @@ +include ':app' +include ':capacitor-cordova-android-plugins' +project(':capacitor-cordova-android-plugins').projectDir = new File('./capacitor-cordova-android-plugins/') + +apply from: 'capacitor.settings.gradle' \ No newline at end of file diff --git a/apps/web/android/variables.gradle b/apps/web/android/variables.gradle new file mode 100644 index 00000000..ee4ba41c --- /dev/null +++ b/apps/web/android/variables.gradle @@ -0,0 +1,16 @@ +ext { + minSdkVersion = 24 + compileSdkVersion = 36 + targetSdkVersion = 36 + androidxActivityVersion = '1.11.0' + androidxAppCompatVersion = '1.7.1' + androidxCoordinatorLayoutVersion = '1.3.0' + androidxCoreVersion = '1.17.0' + androidxFragmentVersion = '1.8.9' + coreSplashScreenVersion = '1.2.0' + androidxWebkitVersion = '1.14.0' + junitVersion = '4.13.2' + androidxJunitVersion = '1.3.0' + androidxEspressoCoreVersion = '3.7.0' + cordovaAndroidVersion = '14.0.1' +} \ No newline at end of file diff --git a/apps/web/capacitor.config.ts b/apps/web/capacitor.config.ts new file mode 100644 index 00000000..5e960a2d --- /dev/null +++ b/apps/web/capacitor.config.ts @@ -0,0 +1,28 @@ +import type { CapacitorConfig } from '@capacitor/cli' + +/** + * The first-paint surface: `body` gets `bg-background` from globals.css (tailwind.config.js + * `background: '#FAF4F0'`). The WebView, the status bar and the splash use it so nothing flashes. + */ +const SURFACE = '#FAF4F0' + +const config: CapacitorConfig = { + appId: 'com.peanutsplit.app', // PLACEHOLDER: Hugo confirms before the first signed build; never changes after + appName: 'Split', + webDir: '.next-native', + backgroundColor: SURFACE, + // Origin of localStorage. NEVER change these three after release: every user's rooms live under them. + server: { iosScheme: 'capacitor', androidScheme: 'https', hostname: 'localhost' }, + // Release lanes export NODE_ENV=production before `cap sync`, which turns WebView debugging off. + android: { allowMixedContent: false, webContentsDebuggingEnabled: process.env.NODE_ENV !== 'production' }, + plugins: { + CapacitorHttp: { enabled: false }, + // NativeShell hides the splash once the first real screen commits (4 s cap). + SplashScreen: { launchAutoHide: false, launchFadeOutDuration: 0, backgroundColor: SURFACE }, + // Not overlaying: Android 7-14 WebViews report no top inset, so the header would sit under the clock. + StatusBar: { style: 'LIGHT', backgroundColor: SURFACE, overlaysWebView: false }, + PushNotifications: { presentationOptions: [] }, + }, +} + +export default config diff --git a/apps/web/e2e-native/e1-cold-open.spec.ts b/apps/web/e2e-native/e1-cold-open.spec.ts new file mode 100644 index 00000000..7a3cfce2 --- /dev/null +++ b/apps/web/e2e-native/e1-cold-open.spec.ts @@ -0,0 +1,19 @@ +import { claimMember, createRoomOnWeb, expect, openRoomLinkInApp, test } from './fixtures' + +/** + * E1 (ARCHITECTURE 14.2): someone made a room in a browser and shared its link; a friend with + * the app taps it. The app cold-starts on the link path, shows the room behind the JoinGate, and + * a tap on an existing name makes this device that member. + */ +test('E1: a web room link opens cold in the app and an existing name claims it', async ({ page, openWeb }) => { + const web = await openWeb() + const slug = await createRoomOnWeb(web, 'Cold open trip', 'Ana', ['Bea']) + + await openRoomLinkInApp(page, slug) + await expect(page.getByTestId('join-gate')).toBeVisible({ timeout: 15_000 }) + await claimMember(page, 'Bea') + + await expect(page.getByTestId('open-add-expense')).toBeVisible() + const member = await page.evaluate((key) => localStorage.getItem(key), `ps:member:${slug}`) + expect(member, 'the claim is stored on this device').not.toBeNull() +}) diff --git a/apps/web/e2e-native/e2-create-and-share.spec.ts b/apps/web/e2e-native/e2-create-and-share.spec.ts new file mode 100644 index 00000000..17c7ec19 --- /dev/null +++ b/apps/web/e2e-native/e2-create-and-share.spec.ts @@ -0,0 +1,44 @@ +import { API_ORIGIN, appRoomUrl, expect, test } from './fixtures' + +/** + * E2 (ARCHITECTURE 14.2): a room made in the app is shared with the same link the web shares, + * `/r/`. Never the app's own origin and never the in-app `/room/?slug=` path, which + * would open nothing for the friend who receives it. + */ +test('E2: a room created in the app shares the canonical web link', async ({ page }) => { + // The copy button writes through navigator.clipboard; record what it writes instead of + // reading the system clipboard, which only Chromium lets a test read. + await page.addInitScript(() => { + const copied: string[] = [] + Object.defineProperty(window, '__copied', { value: copied }) + Object.defineProperty(navigator, 'clipboard', { + configurable: true, + value: { writeText: async (text: string) => void copied.push(text) }, + }) + }) + + await page.goto('/app/') + await page.getByTestId('app-new-split').click() + await page.getByTestId('room-name').fill('App made trip') + await page.getByTestId('room-currency').selectOption('EUR') + await page.getByTestId('creator-name').fill('Ana') + await page.getByTestId('create-room').click() + + await expect(page).toHaveURL(/\/room\/\?slug=/, { timeout: 15_000 }) + const slug = new URL(page.url()).searchParams.get('slug')! + await expect(page).toHaveURL(appRoomUrl(slug)) + await expect(page.getByTestId('join-gate')).toHaveCount(0) + + const roomLink = `${API_ORIGIN}/r/${slug}` + const linkRow = page.getByTestId('room-link-row') + if (!(await linkRow.isVisible())) await page.getByTestId('share-room').click() + await expect(linkRow).toBeVisible({ timeout: 15_000 }) + await expect(linkRow.getByTestId('room-link')).toContainText(`/r/${slug}`) + + await linkRow.getByTestId('copy-link').click() + await expect.poll(() => page.evaluate(() => (window as unknown as { __copied: string[] }).__copied)).toHaveLength(1) + const [copied] = await page.evaluate(() => (window as unknown as { __copied: string[] }).__copied) + expect(copied).toContain(roomLink) + expect(copied).not.toContain(':8778') + expect(copied).not.toContain('/room/') +}) diff --git a/apps/web/e2e-native/e3-reload-drawers-locale.spec.ts b/apps/web/e2e-native/e3-reload-drawers-locale.spec.ts new file mode 100644 index 00000000..f4848137 --- /dev/null +++ b/apps/web/e2e-native/e3-reload-drawers-locale.spec.ts @@ -0,0 +1,68 @@ +import de from '../src/i18n/messages/de.json' +import { appRoomUrl, claimMember, expect, openRoomLinkInApp, seedRoom, test } from './fixtures' + +/** + * E3 (ARCHITECTURE 14.2): the in-app room URL is `/room/?slug=`, and every drawer is a query key + * next to it. Opening and closing drawers must keep the slug; a reload (Android recreating the + * WebView, a language switch) must land in the same room through the boot path. + */ +test('E3: drawers, a reload and a language switch all stay in the same room', async ({ page, request }) => { + const room = await seedRoom(request, 'Drawer trip') + await openRoomLinkInApp(page, room.slug) + await claimMember(page, 'Ana') + + // Add expense + await page.getByTestId('open-add-expense').click() + await expect(page.getByTestId('expense-amount')).toBeVisible() + await expect(page).toHaveURL(appRoomUrl(room.slug)) + await page.keyboard.press('Escape') + await expect(page.getByTestId('expense-amount')).toBeHidden() + await expect(page).toHaveURL(appRoomUrl(room.slug)) + + // Share + await page.getByTestId('share-room').click() + await expect(page.getByTestId('room-link-row')).toBeVisible({ timeout: 15_000 }) + await expect(page).toHaveURL(appRoomUrl(room.slug)) + await page.keyboard.press('Escape') + await expect(page.getByTestId('room-link-row')).toBeHidden() + await expect(page).toHaveURL(appRoomUrl(room.slug)) + + // Room switcher, then Settings from it + await page.getByTestId('open-room-switcher').click() + await expect(page.getByTestId('room-switcher-sheet')).toBeVisible() + await expect(page).toHaveURL(appRoomUrl(room.slug)) + await page + .getByTestId('room-switcher-sheet') + .locator('[data-testid="room-switcher-settings"][data-current="true"]') + .click() + await expect(page.getByTestId('settings-sheet')).toBeVisible() + await expect(page).toHaveURL(appRoomUrl(room.slug)) + await page.keyboard.press('Escape') + await expect(page.getByTestId('settings-sheet')).toBeHidden() + await expect(page).toHaveURL(appRoomUrl(room.slug)) + + // A hard reload restores the room, and this device is still Ana (no JoinGate). + await page.reload() + await expect(page).toHaveURL(appRoomUrl(room.slug), { timeout: 15_000 }) + await expect(page.getByTestId('open-add-expense')).toBeVisible({ timeout: 15_000 }) + await expect(page.getByTestId('join-gate')).toHaveCount(0) + + // The language switch stores the choice and reloads the WebView. + await page.getByTestId('open-room-switcher').click() + await page + .getByTestId('room-switcher-sheet') + .locator('[data-testid="room-switcher-settings"][data-current="true"]') + .click() + await page.getByTestId('device-row').click() + await expect(page.getByTestId('device-sheet')).toBeVisible() + // The store app is the installed app: no PWA install row ("Add Split to Home Screen"). + await expect(page.getByTestId('device-sheet').locator('[data-testid^="install-row"]')).toHaveCount(0) + await page.getByTestId('locale-de').click() + + await expect(page.locator('html')).toHaveAttribute('lang', 'de', { timeout: 15_000 }) + await expect(page).toHaveURL(appRoomUrl(room.slug)) + await expect(page.getByTestId('open-add-expense').first()).toHaveText(de.room.actions.addExpense, { + timeout: 15_000, + }) + await expect(page.getByTestId('join-gate')).toHaveCount(0) +}) diff --git a/apps/web/e2e-native/e4-web-and-app-one-room.spec.ts b/apps/web/e2e-native/e4-web-and-app-one-room.spec.ts new file mode 100644 index 00000000..1876cc62 --- /dev/null +++ b/apps/web/e2e-native/e4-web-and-app-one-room.spec.ts @@ -0,0 +1,40 @@ +import { addExpense, claimMember, createRoomOnWeb, expect, expenseRow, openRoomLinkInApp, test } from './fixtures' + +/** + * E4 (ARCHITECTURE 14.2): the PWA and the app in one room. Two containers, two origins, one truth + * on the server. Each side sees the other's expense, exactly once, without a reload. + * + * The app's stream is observed to open (a 200 on its cross-origin `/events`), so the 10 s budget + * is a latency bound on a live stream, not a bet on the polling backstop. native.yml reruns this + * test with the test origin removed from the server's CORS list and expects it to fail. + */ +const LIVE_BUDGET_MS = 10_000 + +test('E4: web and app in one room see each other’s expense exactly once', async ({ page, openWeb }) => { + const web = await openWeb() + const slug = await createRoomOnWeb(web, 'Shared flat', 'Ana', ['Bea']) + + const appStream = page.waitForResponse( + (response) => + response.url().startsWith(`http://localhost:3100/api/rooms/${slug}/events`) && response.status() === 200, + { timeout: 30_000 } + ) + await openRoomLinkInApp(page, slug) + await claimMember(page, 'Bea') + await appStream + + // Web first, then the app, so both directions are proven. + await addExpense(web, 'Groceries from the web', '30') + await expect(expenseRow(page, 'Groceries from the web')).toHaveCount(1, { timeout: LIVE_BUDGET_MS }) + + await addExpense(page, 'Taxi from the app', '18') + await expect(expenseRow(web, 'Taxi from the app')).toHaveCount(1, { timeout: LIVE_BUDGET_MS }) + + // Let any late echo (a stream event plus a poll, a replayed write) arrive, then count again. + await page.waitForTimeout(2_000) + for (const device of [page, web]) { + await expect(expenseRow(device, 'Groceries from the web')).toHaveCount(1) + await expect(expenseRow(device, 'Taxi from the app')).toHaveCount(1) + await expect(device.getByTestId('expense-row')).toHaveCount(2) + } +}) diff --git a/apps/web/e2e-native/e5-offline-write.spec.ts b/apps/web/e2e-native/e5-offline-write.spec.ts new file mode 100644 index 00000000..99e92a92 --- /dev/null +++ b/apps/web/e2e-native/e5-offline-write.spec.ts @@ -0,0 +1,52 @@ +import { + addExpense, + claimMember, + expect, + expenseRow, + goOffline, + goOnline, + openRoomLinkInApp, + seedRoom, + test, +} from './fixtures' + +/** + * E5 (ARCHITECTURE 14.2): an expense saved in the app while the API is unreachable reaches the + * room once the phone is back online, and the web sees it exactly once. Offline here cuts only the + * API; the app's own files keep loading, as on a device (fixtures.ts). + */ +test('E5: an expense saved offline in the app reaches the web exactly once', async ({ page, request, openWeb }) => { + const room = await seedRoom(request, 'Tunnel trip', 'Ana', ['Bea']) + const web = await openWeb() + await web.goto(`/r/${room.slug}`) + await claimMember(web, 'Ana') + + await openRoomLinkInApp(page, room.slug) + await claimMember(page, 'Bea') + + await goOffline(page) + await addExpense(page, 'Dinner in the tunnel', '42') + // Nothing reached the server yet. + const offlineState = (await (await request.get(`/api/rooms/${room.slug}`)).json()) as { + expenses: Array<{ description: string }> + } + expect(offlineState.expenses.filter((expense) => expense.description === 'Dinner in the tunnel')).toHaveLength(0) + + await goOnline(page) + await expect(expenseRow(web, 'Dinner in the tunnel')).toHaveCount(1, { timeout: 20_000 }) + await expect + .poll(async () => { + const state = (await (await request.get(`/api/rooms/${room.slug}`)).json()) as { + expenses: Array<{ description: string }> + } + return state.expenses.filter((expense) => expense.description === 'Dinner in the tunnel').length + }) + .toBe(1) + + await page.waitForTimeout(2_000) + await expect(expenseRow(web, 'Dinner in the tunnel')).toHaveCount(1) + await expect(expenseRow(page, 'Dinner in the tunnel')).toHaveCount(1) + await expect + .poll(() => page.evaluate(() => Object.keys(localStorage).filter((key) => key.startsWith('ps:pending:')))) + .toHaveLength(0) +}) diff --git a/apps/web/e2e-native/e6-rate-limit.spec.ts b/apps/web/e2e-native/e6-rate-limit.spec.ts new file mode 100644 index 00000000..a336ef59 --- /dev/null +++ b/apps/web/e2e-native/e6-rate-limit.spec.ts @@ -0,0 +1,36 @@ +import en from '../src/i18n/messages/en.json' +import { API_ORIGIN, expect, test } from './fixtures' + +/** + * E6 (ARCHITECTURE 14.2): a server refusal reaches the app as the server's own answer. The proxy + * adds Access-Control-Allow-Origin to error responses too; without it the browser hides the 429 + * and the app can only say "could not reach the server". + */ +test('E6: a rate-limited create shows the rate-limit message, not a network error', async ({ + page, + playwright, + appIp, +}) => { + // Spend this device's room-creation budget (20 an hour) from the same address the app uses. + const sameDevice = await playwright.request.newContext({ + baseURL: API_ORIGIN, + extraHTTPHeaders: { 'x-forwarded-for': appIp }, + }) + let status = 0 + for (let attempt = 0; attempt < 25 && status !== 429; attempt++) { + status = ( + await sameDevice.post('/api/rooms', { data: { name: 'Budget', currency: 'EUR', creatorName: 'Ana' } }) + ).status() + } + await sameDevice.dispose() + expect(status, 'the create bucket never ran out').toBe(429) + + await page.goto('/new/') + await page.getByTestId('room-name').fill('One room too many') + await page.getByTestId('room-currency').selectOption('EUR') + await page.getByTestId('creator-name').fill('Ana') + await page.getByTestId('create-room').click() + + await expect(page.getByRole('alert').filter({ hasText: en.errors.RATE_LIMITED })).toBeVisible({ timeout: 15_000 }) + await expect(page.getByText(en.errors.NETWORK_ERROR)).toHaveCount(0) +}) diff --git a/apps/web/e2e-native/e7-version-gate.spec.ts b/apps/web/e2e-native/e7-version-gate.spec.ts new file mode 100644 index 00000000..1337c709 --- /dev/null +++ b/apps/web/e2e-native/e7-version-gate.spec.ts @@ -0,0 +1,26 @@ +import { expect, test } from './fixtures' + +/** + * E7 (ARCHITECTURE 14.2): the version gate fails open. When `app-config.json` answers 500 or + * cannot be reached, the app runs. + * + * In a browser Capacitor reports the platform as 'web' and no build number, so the gate decides + * "no gate" before it fetches; on a phone the same failures reach `fetchGateStoreUrl`, whose + * fail-open answer is pinned in src/lib/native/version-gate.test.ts. What this proves end to end + * is that a broken config endpoint never walls off the bundled app. + */ +for (const failure of ['http-500', 'network-error'] as const) { + test(`E7: the app runs when app-config.json fails (${failure})`, async ({ page }) => { + await page.route('**/app-config.json', (route) => + failure === 'http-500' ? route.fulfill({ status: 500, body: 'down' }) : route.abort('internetdisconnected') + ) + + await page.goto('/app/') + await expect(page.getByTestId('app-home')).toBeVisible({ timeout: 15_000 }) + await expect(page.getByTestId('version-gate')).toHaveCount(0) + + await page.getByTestId('app-new-split').click() + await expect(page.getByTestId('room-name')).toBeVisible() + await expect(page.getByTestId('version-gate')).toHaveCount(0) + }) +} diff --git a/apps/web/e2e-native/e8-offline-room.spec.ts b/apps/web/e2e-native/e8-offline-room.spec.ts new file mode 100644 index 00000000..dfd6d3c6 --- /dev/null +++ b/apps/web/e2e-native/e8-offline-room.spec.ts @@ -0,0 +1,83 @@ +import en from '../src/i18n/messages/en.json' +import { + appRoomUrl, + expect, + goOffline, + goOfflineBeforeLoad, + goOnline, + seedRecentRooms, + seedRoom, + test, +} from './fixtures' + +/** + * E8 and E8b (ARCHITECTURE 14.2, INTERACTION 9): a room the API cannot reach shows the calm offline + * line and a way back to "Your rooms", never the generic load error or an endless skeleton, and + * loads by itself once the phone is back online. + */ + +const offlineLine = (page: import('@playwright/test').Page) => page.getByText(en.room.states.offlineBody) +const yourRoomsLink = (page: import('@playwright/test').Page) => + page.getByRole('link', { name: en.marketing.rooms.title, exact: true }) +/** The room's data arrived: this device is not a member yet, so the JoinGate shows. */ +const roomLoaded = (page: import('@playwright/test').Page) => page.getByTestId('join-gate') + +test('E8: an offline cold start opens the recent room offline, with a way back', async ({ page, request }) => { + const room = await seedRoom(request, 'Airplane trip') + + // A device that has visited the room before: seed its list, then cut the API and hard-load. + await page.goto('/app/') + await expect(page.getByTestId('app-home')).toBeVisible({ timeout: 15_000 }) + await seedRecentRooms(page, [room]) + await goOfflineBeforeLoad(page) + await page.goto('/') + + await expect(page).toHaveURL(appRoomUrl(room.slug), { timeout: 15_000 }) + await expect(offlineLine(page)).toBeVisible({ timeout: 15_000 }) + await expect(yourRoomsLink(page)).toBeVisible() + await expect(page.getByText(en.room.states.errorTitle)).toHaveCount(0) + + // "Your rooms" shows the list and stays there: no resume back into the failing room. + await yourRoomsLink(page).click() + await expect(page.getByTestId('app-home')).toBeVisible({ timeout: 15_000 }) + await expect(page.getByTestId('recent-room-list')).toBeVisible() + await page.waitForTimeout(2_000) + await expect(page.getByTestId('app-home')).toBeVisible() + expect(page.url()).not.toContain('/room/') + + // Back into the room, then the network returns: it loads without a tap. + await page.goBack() + await expect(page).toHaveURL(appRoomUrl(room.slug), { timeout: 15_000 }) + await expect(offlineLine(page)).toBeVisible({ timeout: 15_000 }) + await goOnline(page) + await expect(roomLoaded(page)).toBeVisible({ timeout: 15_000 }) + await expect(offlineLine(page)).toHaveCount(0) +}) + +test('E8b: a room opened after the phone went offline shows the offline line, not the skeleton', async ({ + page, + request, +}) => { + const room = await seedRoom(request, 'Tunnel list') + + // The list view (`manage=1`), so the app does not resume into the room on its own. + await page.goto('/app/?manage=1') + await expect(page.getByTestId('app-home')).toBeVisible({ timeout: 15_000 }) + await seedRecentRooms(page, [room]) + await page.reload() + await expect(page.getByTestId('recent-room-list')).toBeVisible({ timeout: 15_000 }) + + // Offline while running: React Query hears the event and pauses every new read. + await goOffline(page) + await page.getByTestId('recent-room-list').getByRole('link').first().click() + + await expect(page).toHaveURL(appRoomUrl(room.slug), { timeout: 15_000 }) + await expect(offlineLine(page)).toBeVisible({ timeout: 15_000 }) + await expect(yourRoomsLink(page)).toBeVisible() + await expect(yourRoomsLink(page)).toHaveAttribute('href', /\/app\/?\?manage=1$/) + await expect(page.getByTestId('room-skeleton')).toHaveCount(0) + + await goOnline(page) + await expect(roomLoaded(page)).toBeVisible({ timeout: 15_000 }) + await expect(offlineLine(page)).toHaveCount(0) +}) diff --git a/apps/web/e2e-native/fixtures.ts b/apps/web/e2e-native/fixtures.ts new file mode 100644 index 00000000..7de98be9 --- /dev/null +++ b/apps/web/e2e-native/fixtures.ts @@ -0,0 +1,206 @@ +import { test as base, expect, type APIRequestContext, type Locator, type Page } from '@playwright/test' +import { deviceContext, uniqueClientIp } from '../e2e/fixtures' +import { draftRoomPeople, enterCreatedRoom } from '../e2e/helpers' + +/** + * Shared harness for the store-app suite (playwright.native.config.ts). + * + * `page` is the app: the static export on :8778, calling the API on :3100 cross-origin. A web + * device (`openWeb`) is the web build on :3100 itself, the room link a friend opens in a browser. + */ + +export const API_ORIGIN = 'http://localhost:3100' +export const APP_ORIGIN = 'http://localhost:8778' +const API_ROUTES = `${API_ORIGIN}/**` + +/** + * Why the app's address goes on through a route and not through `extraHTTPHeaders`: Chromium + * treats an extra header as a page header, so every cross-origin call then preflights for + * `x-forwarded-for`, which the server rightly does not allow, and the whole app reads as offline. + * A route adds it below CORS. The cost: with a route active Playwright answers Chromium's + * preflight itself, so the real preflight is exercised by the WebKit project (and by + * cors.test.ts and proxy.test.ts). Chromium still enforces the response's + * Access-Control-Allow-Origin, which is what the negative control in native.yml relies on. + */ +interface NativeFixtures { + /** The address the app presents to the API, so its rate-limit buckets belong to this test. */ + appIp: string + /** Opens a phone-sized browser on the web build (:3100): a second person's device. */ + openWeb: () => Promise + /** Every script the app requested from an origin other than localhost. Must stay empty. */ + remoteScripts: string[] +} + +export const test = base.extend({ + appIp: async ({}, use) => { + await use(uniqueClientIp()) + }, + + context: async ({ context, appIp }, use) => { + await context.route(API_ROUTES, (route) => + route.continue({ headers: { ...route.request().headers(), 'x-forwarded-for': appIp } }) + ) + await use(context) + }, + + // Seeding calls go straight to the API from their own address, never the app's budget. + request: async ({ playwright }, use) => { + const api = await playwright.request.newContext({ + baseURL: API_ORIGIN, + extraHTTPHeaders: { 'x-forwarded-for': uniqueClientIp() }, + }) + await use(api) + await api.dispose() + }, + + openWeb: async ({ browser }, use) => { + const contexts: Awaited>[] = [] + await use(async () => { + const context = await browser.newContext(deviceContext({ baseURL: API_ORIGIN, serviceWorkers: 'block' })) + contexts.push(context) + return context.newPage() + }) + await Promise.all(contexts.map((context) => context.close())) + }, + + // The bundle must never run code fetched from the network (App Store 2.5.2). Checked for every + // test, since any screen could pull a script in. + remoteScripts: [ + async ({ context }, use) => { + const remote: string[] = [] + context.on('request', (request) => { + if (request.resourceType() !== 'script') return + const url = new URL(request.url()) + if (url.protocol === 'data:') return + // A blob: URL's origin is the page that made it, so it is judged by that. + const { hostname } = new URL(url.origin) + if (hostname !== 'localhost' && hostname !== '127.0.0.1') remote.push(request.url()) + }) + await use(remote) + expect(remote, 'the app requested a script from another origin').toEqual([]) + }, + { auto: true }, + ], +}) + +export { expect } + +// ── Offline ────────────────────────────────────────────────────────────────────────────────── + +/** + * "Offline" in this suite means the API is unreachable while the app's own files still load, as + * on a phone where the bundle is local. `context.setOffline` would also cut :8778, so a hard load + * or a lazy chunk would fail in a way no device ever sees. + */ +const OFFLINE_FLAG = 'e2e:offline' + +/** Offline for the next hard load: the init script forces `navigator.onLine` false before the app boots. */ +export async function goOfflineBeforeLoad(page: Page): Promise { + await page.route(API_ROUTES, (route) => route.abort('internetdisconnected')) + await page.addInitScript((flag) => { + if (sessionStorage.getItem(flag) !== '1') return + Object.defineProperty(navigator, 'onLine', { configurable: true, get: () => false }) + }, OFFLINE_FLAG) + await page.evaluate((flag) => sessionStorage.setItem(flag, '1'), OFFLINE_FLAG) +} + +/** Offline now, on a running page: the dispatched event is what pauses React Query's new reads. */ +export async function goOffline(page: Page): Promise { + await page.route(API_ROUTES, (route) => route.abort('internetdisconnected')) + await page.evaluate(() => { + Object.defineProperty(navigator, 'onLine', { configurable: true, get: () => false }) + window.dispatchEvent(new Event('offline')) + }) +} + +/** Back online: the API answers again, `navigator.onLine` is true, and the page hears `online`. */ +export async function goOnline(page: Page): Promise { + await page.unroute(API_ROUTES) + await page.evaluate((flag) => { + sessionStorage.removeItem(flag) + Object.defineProperty(navigator, 'onLine', { configurable: true, get: () => true }) + window.dispatchEvent(new Event('online')) + }, OFFLINE_FLAG) +} + +// ── Rooms ──────────────────────────────────────────────────────────────────────────────────── + +export interface SeededRoom { + slug: string + name: string +} + +/** A room made through the API, with `people` added as members, for specs whose subject is elsewhere. */ +export async function seedRoom( + request: APIRequestContext, + name: string, + creatorName = 'Ana', + people: string[] = [] +): Promise { + const created = await request.post('/api/rooms', { data: { name, currency: 'EUR', creatorName } }) + expect(created.status()).toBe(201) + const { room } = (await created.json()) as { room: { slug: string } } + for (const person of people) { + const joined = await request.post(`/api/rooms/${room.slug}/members`, { data: { name: person } }) + expect(joined.status()).toBe(201) + } + return { slug: room.slug, name } +} + +/** Creates a room in the web build's own form and returns its slug. The creator is already in. */ +export async function createRoomOnWeb(web: Page, name: string, creator: string, people: string[] = []) { + await web.goto('/new') + await web.getByTestId('room-name').fill(name) + await web.getByTestId('room-currency').selectOption('EUR') + await web.getByTestId('creator-name').fill(creator) + if (people.length > 0) await draftRoomPeople(web, people) + await web.getByTestId('create-room').click() + const url = await enterCreatedRoom(web) + return new URL(url).pathname.split('/').at(-1)! +} + +/** Escapes a slug for use inside a URL regular expression. */ +const escape = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + +/** The app's room screen URL for `slug`, with any drawer keys after it. */ +export const appRoomUrl = (slug: string) => new RegExp(`/room/\\?slug=${escape(slug)}(?:&|$)`) + +/** + * A cold open of a shared room link in the app: a hard load of `/r/`, which the export + * server answers with the root index.html, and the boot path takes to `/room/?slug=`. + */ +export async function openRoomLinkInApp(page: Page, slug: string): Promise { + await page.goto(`/r/${slug}`) + await expect(page).toHaveURL(appRoomUrl(slug), { timeout: 15_000 }) +} + +/** Taps an existing name on the JoinGate. */ +export async function claimMember(page: Page, name: string): Promise { + await page.locator(`[data-testid="claim-member"][data-member="${name}"]`).click() + await expect(page.getByTestId('join-gate')).toHaveCount(0, { timeout: 15_000 }) +} + +/** One expense row by its description. */ +export const expenseRow = (page: Page, description: string): Locator => + page.locator(`[data-testid="expense-row"][data-description="${description}"]`) + +/** Adds an expense paid by the person holding the device, split equally. */ +export async function addExpense(page: Page, description: string, amount = '24'): Promise { + await page.getByTestId('open-add-expense').click() + await page.getByTestId('expense-amount').fill(amount) + await page.getByTestId('expense-description').fill(description) + await page.getByTestId('save-expense').click() + await expect(expenseRow(page, description)).toHaveCount(1, { timeout: 15_000 }) +} + +/** Writes the device's recent-room list the way the app stores it. */ +export async function seedRecentRooms(page: Page, rooms: SeededRoom[]): Promise { + await page.evaluate( + (list) => + localStorage.setItem( + 'ps:recent', + JSON.stringify(list.map((room, index) => ({ ...room, lastSeenAt: Date.now() - index * 60_000 }))) + ), + rooms + ) +} diff --git a/apps/web/e2e-native/store-screenshots.spec.ts b/apps/web/e2e-native/store-screenshots.spec.ts new file mode 100644 index 00000000..910b65e5 --- /dev/null +++ b/apps/web/e2e-native/store-screenshots.spec.ts @@ -0,0 +1,758 @@ +import { mkdirSync } from 'node:fs' +import path from 'node:path' +import { pathToFileURL } from 'node:url' +import type { APIRequestContext, Browser, BrowserContext, Locator, Page } from '@playwright/test' +import sharp from 'sharp' +import { uniqueClientIp } from '../e2e/fixtures' +import { mockCamera, TINY_JPEG } from '../e2e-v2/helpers' +import { API_ORIGIN, APP_ORIGIN, expect, test } from './fixtures' + +/** + * The store screenshots, the Play feature graphic and the Play icon (PLAN 7.3, + * apps/web/store/screenshots.md). Not part of the cross-origin suite: it runs only with + * STORE_SCREENSHOTS=1 and writes images into apps/web/store/assets/, which a person reviews and + * commits. How to run it is in apps/web/store/assets/README.md. + * + * Two steps. The first captures the real app at two raw phone sizes into store/captures/ + * (gitignored). The second puts each capture in store/screenshot-frame.html with a headline and + * renders the three store sizes, then a contact sheet for review. + * + * The app is the real static export talking to the real API server, so every screen is what a + * phone shows. Two things are not real: the receipt-scan POST answers with the fixture below (no + * model call), and the camera is the e2e-v2 fake (no host camera). The API server must run with a + * placeholder SPLIT_OPENROUTER_API_KEY so its capability probe says scanning is on; the POST never + * reaches it. + */ + +test.skip(!process.env.STORE_SCREENSHOTS, 'store screenshots run only with STORE_SCREENSHOTS=1') +test.describe.configure({ mode: 'serial' }) + +/** The origin the export must be baked with for this spec: `pnpm native:build` with + * NEXT_PUBLIC_BASE_URL unset (the release default), unlike the cross-origin suite. */ +const PRODUCT_ORIGIN = 'https://peanutsplit.com' +const STORE = path.resolve(__dirname, '../store') +const ASSETS = path.join(STORE, 'assets') +const CAPTURES = path.join(STORE, 'captures') + +/** The raw phones the app is captured on, at DSF 3. One raw set feeds one or more store sets. */ +const RAW_SETS = [ + { id: 'iphone', width: 402, height: 874, userAgent: 'iphone' }, + { id: 'android', width: 412, height: 892, userAgent: 'android' }, +] as const +type RawSet = (typeof RAW_SETS)[number] + +/** + * The store sizes: CSS canvas x 3 = the store's pixel size (screenshots.md, "Sizes"), and where + * the headline and the frame sit on that canvas (CSS px). + */ +const STORE_SETS = [ + { + id: 'iphone-6.9', + raw: 'iphone', + layout: { + width: 440, + height: 956, + margin: 26, + headlineTop: 48, + headlineSize: 50, + gap: 13, + sublineSize: 22, + frameTop: 215, + frameWidth: 370, + frameBottom: 921, + radius: 34, + }, + }, + { + id: 'iphone-6.3', + raw: 'iphone', + layout: { + width: 402, + height: 874, + margin: 24, + headlineTop: 44, + headlineSize: 46, + gap: 12, + sublineSize: 20, + frameTop: 196, + frameWidth: 338, + frameBottom: 842, + radius: 34, + }, + }, + { + id: 'android-phone', + raw: 'android', + layout: { + width: 360, + height: 640, + margin: 20, + headlineTop: 28, + headlineSize: 40, + gap: 8, + sublineSize: 17, + frameTop: 150, + frameWidth: 290, + frameBottom: 620, + radius: 28, + }, + }, +] as const satisfies readonly { id: string; raw: RawSet['id']; layout: Record }[] +type StoreSet = (typeof STORE_SETS)[number] + +/** The number of raw CSS rows the frame of a store set shows (the frame's border is 3 px). */ +export function windowRows(storeSet: StoreSet): number { + const { layout, raw } = storeSet + const rawWidth = RAW_SETS.find((set) => set.id === raw)!.width + return (layout.frameBottom - layout.frameTop - 6) / ((layout.frameWidth - 6) / rawWidth) +} + +/** + * One raw set can feed two store sets with slightly different windows. Something that must show + * has to fit the smaller window; something that must stay hidden has to clear the larger one. + */ +function rowsFor(raw: RawSet): { visible: number; hidden: number } { + const rows = STORE_SETS.filter((set) => set.raw === raw.id).map(windowRows) + return { visible: Math.min(...rows), hidden: Math.max(...rows) } +} + +const YELLOW = '#FFC900' +const PINK = '#FF90E8' + +/** + * The five screenshots in upload order (the first three show in search results). The file names + * stay as check-assets.mjs expects. Headlines are landing page lines; `` is the highlight. + * Every headline has two lines, so the frame sits at the same height on every screen. + */ +const SHOTS = [ + { + file: '4-share', + background: PINK, + markColour: YELLOW, + headlineHtml: 'ONE LINK.
PICK YOUR NAME.', + subline: 'No signup. No password.', + anchor: 'bottom', + }, + { + file: '2-add-expense', + background: YELLOW, + markColour: PINK, + headlineHtml: 'EVERYONE ADDS
EXPENSES.', + subline: 'Who paid, how much, for whom.', + anchor: 'bottom', + }, + { + file: '1-room', + background: '#EAFBEE', + markColour: YELLOW, + headlineHtml: 'WHO OWES WHAT.
SORTED.', + subline: 'Every balance in one room.', + anchor: 'top', + }, + { + file: '3-receipt-scan', + background: '#FAF4F0', + markColour: YELLOW, + headlineHtml: 'SCAN THE
BILL.', + subline: 'Then tap who had what.', + anchor: 'bottom', + }, + { + file: '5-home', + background: PINK, + markColour: YELLOW, + headlineHtml: 'SPLIT
ANYTHING.', + subline: 'Trips, roommates, dinners.', + anchor: 'top', + }, +] as const + +/** + * Words no text on the canvas may hold: prices, promo words, store and OS names, and the + * BANNED_EVERYWHERE list of store/check-listing.mjs (copied: that script runs on import). + */ +const BANNED_ON_CANVAS = [ + /\bfree\b/i, + /\bbest\b/i, + /#1\b/, + /\bdownload/i, + /\bno ads\b/i, + /[$€£]\s?\d|\d\s?[$€£]|\d+[.,]\d{2}\b/, + /\bapp ?store\b|\bgoogle\b|\bplay store\b|\biphone\b|\bipad\b|\bios\b|\bapple\b|\bandroid\b/i, + /\bcrypto\w*/i, + /\bwallets?\b/i, + /\bstablecoins?\b/i, + /\bUSDC\b/i, + /\bdigital dollars?\b/i, + /\bpayments?\b/i, + /\bsend(?:s|ing)? money\b/i, + /\btransfers?\b/i, + /\bbank(?:s|ing)?\b/i, + /\bPWA\b/i, + /\bweb ?apps?\b/i, + /\bworks? offline\b/i, + /\bopens? offline\b/i, + /(? { + const created = await api.post('/api/rooms', { data: { name, currency: 'EUR', creatorName: people[0] } }) + expect(created.status()).toBe(201) + const { room, memberId, memberToken } = (await created.json()) as { + room: { slug: string } + memberId: string + memberToken: string + } + const ids: Record = { [people[0]]: memberId } + for (const person of people.slice(1)) { + const added = await api.post(`/api/rooms/${room.slug}/members`, { data: { name: person, intent: 'add' } }) + expect(added.status()).toBe(201) + ids[person] = ((await added.json()) as { memberId: string }).memberId + } + for (const expense of expenses) { + const saved = await api.post(`/api/rooms/${room.slug}/expenses`, { + headers: { 'x-member-token': memberToken }, + data: { + description: expense.description, + amountMinor: expense.amountMinor, + currency: 'EUR', + paidById: ids[expense.paidBy], + splitMode: 'EQUAL', + participantIds: people.map((person) => ids[person]), + }, + }) + expect(saved.status(), await saved.text()).toBe(201) + } + return { slug: room.slug, name, memberId, memberToken } +} + +// ── One phone per screen ───────────────────────────────────────────────────────────────────── + +/** + * A fresh phone for one screen: Ana's identity in every seeded room, the three rooms in her + * recent list, reduced motion so no capture lands mid-animation, and nothing but the two local + * servers reachable. + */ +async function openPhone(browser: Browser, set: RawSet, rooms: Seeded[]): Promise { + const context: BrowserContext = await browser.newContext({ + viewport: { width: set.width, height: set.height }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + userAgent: USER_AGENTS[set.userAgent], + locale: 'en-US', + timezoneId: 'Europe/Lisbon', + reducedMotion: 'reduce', + serviceWorkers: 'block', + }) + const appIp = uniqueClientIp() + // The export is baked with the production origin, so the share screen shows the real room + // link. Its API calls are answered by the local server instead; nothing reaches production. + // The live stream is cut (the room falls back to its normal refetch), because a fetched + // response must end before it can be handed to the page. + await context.route( + (url) => url.hostname !== 'localhost' && url.hostname !== '127.0.0.1', + async (route) => { + const url = new URL(route.request().url()) + if (url.origin !== PRODUCT_ORIGIN || !url.pathname.startsWith('/api/') || url.pathname.endsWith('/events')) + return route.abort() + const response = await route.fetch({ + url: `${API_ORIGIN}${url.pathname}${url.search}`, + headers: { ...route.request().headers(), 'x-forwarded-for': appIp }, + }) + await route.fulfill({ response }) + } + ) + await context.addInitScript( + ({ origin, list }) => { + if (location.origin !== origin || sessionStorage.getItem('store:seeded') === '1') return + sessionStorage.setItem('store:seeded', '1') + list.forEach((room, index) => { + localStorage.setItem( + `ps:member:${room.slug}`, + JSON.stringify({ memberId: room.memberId, name: 'Ana', token: room.memberToken }) + ) + }) + localStorage.setItem( + 'ps:recent', + JSON.stringify( + list.map((room, index) => ({ + slug: room.slug, + name: room.name, + lastSeenAt: Date.now() - index * 3_600_000, + })) + ) + ) + }, + { + origin: APP_ORIGIN, + list: rooms.map(({ slug, name, memberId, memberToken }) => ({ slug, name, memberId, memberToken })), + } + ) + return context.newPage() +} + +async function openTripRoom(page: Page, slug: string): Promise { + await page.goto(`/room/?slug=${slug}`) + await expect(page.getByTestId('join-gate')).toHaveCount(0) + for (const person of PEOPLE) { + await expect(page.locator(`[data-testid="balance-card"][data-member="${person}"]`)).toBeVisible({ + timeout: 20_000, + }) + } + await expect(page.locator('[data-testid="expense-row"]')).toHaveCount(TRIP.expenses.length) + // A fresh device celebrates the four-person roster once. It is a share prompt, not the room. + const celebration = page.getByTestId('achievement-dismiss') + if (await celebration.isVisible({ timeout: 3_000 }).catch(() => false)) await celebration.click() + await expect(page.getByTestId('achievement-moment')).toHaveCount(0) +} + +/** Every capture must hold no settle sheet, no web install offer and no placeholder text. */ +async function capture(page: Page, file: string): Promise { + // The settle sheet's own parts: its transfer list, amount field and method buttons. + await expect( + page.locator('[data-testid="transfer-row"], [data-testid="settle-amount"], [data-testid^="method-"]') + ).toHaveCount(0) + await expect(page.locator('[data-testid^="install-"]')).toHaveCount(0) + await expect(page.locator('body')).not.toContainText(/lorem|placeholder|TODO|undefined|NaN|localhost/i) + await page.evaluate(() => document.fonts.ready) + // Settle any layout shift from the last state change before the capture. + await page.waitForTimeout(400) + mkdirSync(path.dirname(file), { recursive: true }) + await page.screenshot({ path: file, type: 'png', animations: 'disabled', caret: 'hide' }) +} + +async function box(locator: Locator): Promise<{ top: number; bottom: number }> { + const found = await locator.boundingBox({ timeout: 10_000 }) + expect(found, `${locator} has no box`).not.toBeNull() + return { top: found!.y, bottom: found!.y + found!.height } +} + +/** The element lies fully inside raw rows `from` to `to`, so the frame shows all of it. */ +async function expectWithinRows(locator: Locator, from: number, to: number): Promise { + const { top, bottom } = await box(locator) + expect(top, `${locator} top`).toBeGreaterThanOrEqual(from) + expect(bottom, `${locator} bottom`).toBeLessThanOrEqual(to) +} + +test('store screenshots: raw captures at two phone sizes', async ({ browser, playwright }) => { + test.setTimeout(15 * 60_000) + const api = await playwright.request.newContext({ + baseURL: API_ORIGIN, + extraHTTPHeaders: { 'x-forwarded-for': uniqueClientIp() }, + }) + // Seeded oldest first, so the trip room is the most recent one on the home screen. + const others = [] + for (const room of [...OTHER_ROOMS].reverse()) { + others.unshift(await seedRoom(api, room.name, room.people, [{ ...room.expense, paidBy: room.people[1] }])) + } + const trip = await seedRoom(api, TRIP.name, PEOPLE, TRIP.expenses) + await api.dispose() + const rooms = [trip, ...others] + + for (const raw of RAW_SETS) { + const out = (name: string) => path.join(CAPTURES, raw.id, `${name}.png`) + const { visible, hidden } = rowsFor(raw) + const H = raw.height + + // 1. The trip room with its balances and expenses (frame anchored at the top). + { + const page = await openPhone(browser, raw, rooms) + await openTripRoom(page, trip.slug) + for (const card of await page.getByTestId('balance-card').all()) await expectWithinRows(card, 0, visible) + let shownRows = 0 + for (const row of await page.getByTestId('expense-row').all()) { + if ((await box(row)).bottom <= visible) shownRows += 1 + } + expect(shownRows).toBeGreaterThanOrEqual(4) + // "Settle up" is also a competitor's name: it stays below the frame's window. + for (const settle of await page.getByText('Settle up', { exact: true }).all()) { + if (await settle.isVisible()) expect((await box(settle)).top).toBeGreaterThanOrEqual(hidden) + } + await capture(page, out('1-room')) + await page.context().close() + } + + // 2. The add-expense drawer mid-entry, with the split editor open (anchored at the bottom). + { + const page = await openPhone(browser, raw, rooms) + await openTripRoom(page, trip.slug) + await page.getByTestId('open-add-expense').click() + await expect(page.getByTestId('expense-drawer')).toBeVisible() + await page.getByTestId('expense-amount').fill('64.80') + await page.getByTestId('expense-description').fill('Museum tickets') + await page.getByTestId('expense-split-summary').click() + await expect(page.getByTestId('split-editor')).toBeVisible() + await page.locator(':focus').evaluate((element) => (element as HTMLElement).blur()) + await page.waitForTimeout(300) + // Scroll the drawer so the last person row sits 12 px above the footer with the + // "Add €64.80 expense" button. The amount may scroll out; the button carries it. + const layout = await page.getByTestId('expense-drawer').evaluate((drawer) => { + const editor = drawer.querySelector('[data-testid="split-editor"]')! + const people = editor.querySelectorAll('ul[aria-label="Who shares this?"] > li') + const lastRow = people[people.length - 1] + const button = [...drawer.querySelectorAll('button')].find((candidate) => + /^Add .+ expense$/.test(candidate.textContent?.trim() ?? '') + )! + // The footer is the button's outermost ancestor that does not hold the form. + let footer: HTMLElement = button + while (footer.parentElement && !footer.parentElement.contains(editor)) footer = footer.parentElement + let scroller: HTMLElement | null = editor.parentElement + while (scroller && scroller !== drawer) { + const overflow = getComputedStyle(scroller).overflowY + if ((overflow === 'auto' || overflow === 'scroll') && scroller.scrollHeight > scroller.clientHeight) + break + scroller = scroller.parentElement + } + if (scroller) + scroller.scrollTop += + lastRow.getBoundingClientRect().bottom - (footer.getBoundingClientRect().top - 12) + const heading = editor.querySelector('h3')! + return { + people: people.length, + headingTop: heading.getBoundingClientRect().top, + lastRowBottom: lastRow.getBoundingClientRect().bottom, + footerTop: footer.getBoundingClientRect().top, + buttonTop: button.getBoundingClientRect().top, + buttonBottom: button.getBoundingClientRect().bottom, + } + }) + expect(layout.people).toBe(PEOPLE.length) + await expect(page.getByText('Who shares this?', { exact: true })).toBeVisible() + expect(layout.headingTop).toBeGreaterThanOrEqual(H - visible) + expect(layout.lastRowBottom).toBeLessThanOrEqual(layout.footerTop) + expect(layout.buttonTop).toBeGreaterThanOrEqual(0) + expect(layout.buttonBottom).toBeLessThanOrEqual(H) + await capture(page, out('2-add-expense')) + await page.context().close() + } + + // 3. Receipt scan review, every item assigned. Only the scan POST is mocked. + { + const page = await openPhone(browser, raw, rooms) + await mockCamera(page, 'ready') + await page.route('**/api/rooms/*/receipt-parse', (route) => + route.request().method() === 'POST' ? route.fulfill({ json: RECEIPT }) : route.fallback() + ) + await openTripRoom(page, trip.slug) + await page.getByTestId('open-add-expense').click() + await page.getByTestId('scan-bill').click({ timeout: 20_000 }) + // The app asks once before the first photo goes to the AI (OVERRIDES 1). + const allow = page.getByTestId('scan-consent-allow') + await expect(allow.or(page.getByTestId('scan-camera'))).toBeVisible({ timeout: 15_000 }) + if (await allow.isVisible()) await allow.click() + await expect(page.getByTestId('scan-camera')).toBeVisible({ timeout: 15_000 }) + await page + .getByTestId('scan-upload-input') + .setInputFiles({ name: 'receipt.jpg', mimeType: 'image/jpeg', buffer: TINY_JPEG }) + await expect(page.getByTestId('scan-item-label')).toHaveCount(RECEIPT.items.length, { timeout: 20_000 }) + await page.getByTestId('scan-continue').click() + const rows = page.getByTestId('scan-assign-row') + await expect(rows).toHaveCount(RECEIPT.items.length) + for (const [index, who] of ASSIGNMENTS.entries()) { + const row = rows.nth(index) + if (who === 'everyone') { + await row.getByTestId('scan-everyone').click() + continue + } + for (const person of who) { + const chip = row.locator(`[data-testid="scan-assignee-chip"][data-member="${person}"]`) + if ((await chip.getAttribute('aria-pressed')) !== 'true') await chip.click() + } + } + await expect(page.getByTestId('scan-unassigned')).toHaveCount(0) + // Scrolled to the end, so the per-person totals and "Use this split" show whole. When the + // top of the frame's window would cut an item card, scroll back until that card shows + // whole, as far as "Use this split" stays on screen ("Back to the items" may leave it). + const scanRows = rowsFor(raw) + const windowTop = H - scanRows.hidden + await page.getByTestId('scan-apply').evaluate( + (button, { top, height }) => { + let scroller: HTMLElement | null = button.parentElement + while (scroller) { + const overflow = getComputedStyle(scroller).overflowY + if ( + (overflow === 'auto' || overflow === 'scroll') && + scroller.scrollHeight > scroller.clientHeight + ) + break + scroller = scroller.parentElement + } + if (!scroller) return + scroller.scrollTop = scroller.scrollHeight + for (const card of document.querySelectorAll('[data-testid="scan-assign-row"]')) { + const { top: cardTop, bottom } = card.getBoundingClientRect() + if (cardTop >= top || bottom <= top) continue + const room = height - 2 - button.getBoundingClientRect().bottom + scroller.scrollTop -= Math.min(top + 8 - cardTop, room) + } + }, + { top: windowTop, height: H } + ) + await page.waitForTimeout(300) + for (const card of await page.getByTestId('scan-assign-row').all()) { + const { top, bottom } = await box(card) + for (const edge of [H - scanRows.visible, windowTop]) + expect(top < edge && bottom > edge, `an item card is cut at row ${edge}`).toBe(false) + } + // The per-person totals block sits just above the button's group. + await expectWithinRows( + page.getByTestId('scan-apply').locator('xpath=../preceding-sibling::div[1]'), + H - scanRows.visible, + H + ) + await expectWithinRows(page.getByTestId('scan-apply'), H - scanRows.visible, H) + await capture(page, out('3-receipt-scan')) + await page.context().close() + } + + // 4. The share moment: the room link and its QR code (anchored at the bottom). + { + const page = await openPhone(browser, raw, rooms) + await openTripRoom(page, trip.slug) + await page.getByTestId('share-room').click() + await expect(page.getByTestId('room-qr')).toBeVisible({ timeout: 15_000 }) + await expect(page.getByTestId('room-link')).toContainText(`peanutsplit.com/r/${trip.slug}`) + await page.waitForTimeout(300) + await expectWithinRows(page.getByTestId('room-qr'), H - visible, H) + await expectWithinRows(page.getByTestId('room-link'), H - visible, H) + await expectWithinRows(page.getByRole('button', { name: 'Share room link', exact: true }), H - visible, H) + await capture(page, out('4-share')) + await page.context().close() + } + + // 5. The app home with three recent rooms, trimmed below "New split". `manage=1` keeps + // the list on screen instead of opening the most recent room. + { + const page = await openPhone(browser, raw, rooms) + await page.goto('/app/?manage=1') + await expect(page.getByTestId('app-home')).toBeVisible({ timeout: 15_000 }) + for (const room of rooms) await expect(page.getByText(room.name, { exact: true })).toBeVisible() + const newSplit = await box(page.getByTestId('app-new-split')) + // 24 px under "New split", but never into "Import from Splitwise" (12 px below it), + // which names a competitor. + const importTop = (await box(page.getByTestId('app-import'))).top + const trimmedHeight = Math.min(Math.ceil(newSplit.bottom) + 24, Math.floor(importTop)) + await page.setViewportSize({ width: raw.width, height: trimmedHeight }) + await page.waitForTimeout(300) + for (const room of rooms) + await expectWithinRows(page.getByText(room.name, { exact: true }), 0, trimmedHeight) + await expectWithinRows(page.getByText('Saved on this device.', { exact: true }), 0, trimmedHeight) + await expectWithinRows(page.getByTestId('app-new-split'), 0, trimmedHeight) + expect((await box(page.getByTestId('app-import'))).top).toBeGreaterThanOrEqual(trimmedHeight) + await capture(page, out('5-home')) + await page.context().close() + } + } +}) + +test('store screenshots: framed at three store sizes, and the contact sheet', async ({ browser }) => { + test.setTimeout(5 * 60_000) + for (const storeSet of STORE_SETS) { + const raw = RAW_SETS.find((set) => set.id === storeSet.raw)! + const { layout } = storeSet + const context = await browser.newContext({ + viewport: { width: layout.width, height: layout.height }, + deviceScaleFactor: 3, + // The project's iPhone profile would lay the page out at 980 px and autosize its text. + isMobile: false, + }) + const page = await context.newPage() + // A local file with relative links to the captures and the font; nothing else may load. + await page.route(/^(?!file:)/, (route) => route.abort()) + await page.goto(pathToFileURL(path.join(STORE, 'screenshot-frame.html')).href) + for (const shot of SHOTS) { + const measured = await page.evaluate( + (cfg) => (window as unknown as { render: (cfg: unknown) => Promise }).render(cfg), + { ...shot, capture: `captures/${raw.id}/${shot.file}.png`, layout } + ) + const where = `${storeSet.id}/${shot.file}` + expect( + await page.evaluate(() => [...document.fonts].filter((font) => font.status !== 'loaded').length), + where + ).toBe(0) + expect(await page.evaluate(() => document.fonts.check("1000 48px 'Roboto Flex'")), where).toBe(true) + expect(measured.image.complete, where).toBe(true) + expect(measured.image.naturalWidth, where).toBe(raw.width * 3) + expect(measured.headline.height, `${where} headline lines`).toBeLessThanOrEqual( + 2 * measured.headline.lineHeight + 1 + ) + expect(measured.subline.height, `${where} sub-line lines`).toBeLessThanOrEqual( + measured.subline.lineHeight + 1 + ) + for (const text of [measured.headline, measured.subline]) { + expect(text.left, `${where} left margin`).toBeGreaterThanOrEqual(layout.margin - 0.5) + expect(text.right, `${where} right margin`).toBeLessThanOrEqual(layout.width - layout.margin + 0.5) + } + expect(measured.subline.bottom, `${where} text above the frame`).toBeLessThanOrEqual(measured.frame.top) + for (const pattern of BANNED_ON_CANVAS) expect(measured.text, `${where} ${pattern}`).not.toMatch(pattern) + const file = path.join(ASSETS, 'screenshots', storeSet.id, `${shot.file}.jpg`) + mkdirSync(path.dirname(file), { recursive: true }) + await page.screenshot({ path: file, type: 'jpeg', quality: 90 }) + } + await context.close() + } + + // One row per store set in upload order, longest side under 1600 px, for Konrad's review. + const rowHeight = 480 + const gap = 16 + const tiles = [] + let sheetWidth = 0 + for (const [row, storeSet] of STORE_SETS.entries()) { + let left = gap + for (const shot of SHOTS) { + const input = await sharp(path.join(ASSETS, 'screenshots', storeSet.id, `${shot.file}.jpg`)) + .resize({ height: rowHeight }) + .toBuffer({ resolveWithObject: true }) + tiles.push({ input: input.data, left, top: gap + row * (rowHeight + gap) }) + left += input.info.width + gap + } + sheetWidth = Math.max(sheetWidth, left) + } + const sheetHeight = gap + STORE_SETS.length * (rowHeight + gap) + expect(Math.max(sheetWidth, sheetHeight)).toBeLessThanOrEqual(1600) + await sharp({ create: { width: sheetWidth, height: sheetHeight, channels: 3, background: '#ffffff' } }) + .composite(tiles) + .jpeg({ quality: 85 }) + .toFile(path.join(CAPTURES, 'contact-sheet.jpg')) +}) + +interface TextBox { + left: number + right: number + top: number + bottom: number + height: number + lineHeight: number +} +interface RenderResult { + headline: TextBox + subline: TextBox + frame: { top: number; bottom: number; left: number; right: number } + image: { naturalWidth: number; complete: boolean } + text: string +} + +test('store graphics: Play feature graphic and Play icon', async ({ browser }) => { + // Rendered at 2x and scaled down: at 1x the condensed 72 px headline merges letters. + const context = await browser.newContext({ viewport: { width: 1024, height: 500 }, deviceScaleFactor: 2 }) + const page = await context.newPage() + // A local file with relative links to the repo's own fonts and art; nothing else may load. + await page.route(/^(?!file:)/, (route) => route.abort()) + await page.goto(pathToFileURL(path.join(STORE, 'feature-graphic.html')).href) + await page.evaluate(() => document.fonts.ready) + expect(await page.evaluate(() => [...document.fonts].filter((font) => font.status !== 'loaded').length)).toBe(0) + for (const image of await page.locator('img').all()) { + expect(await image.evaluate((element: HTMLImageElement) => element.complete && element.naturalWidth > 0)).toBe( + true + ) + } + // Play crops the edges on some surfaces: no text within 32 px of any edge. + const textBoxes = await page.locator('.copy').evaluate((copy) => + [...copy.querySelectorAll('.wordmark, h1, .lede, .chip')].map((element) => { + const range = document.createRange() + range.selectNodeContents(element) + const rect = element.classList.contains('chip') + ? element.getBoundingClientRect() + : range.getBoundingClientRect() + return { name: element.className || element.tagName, ...rect.toJSON() } + }) + ) + for (const text of textBoxes) { + expect(text.left, text.name).toBeGreaterThanOrEqual(32) + expect(text.top, text.name).toBeGreaterThanOrEqual(32) + expect(text.right, text.name).toBeLessThanOrEqual(1024 - 32) + expect(text.bottom, text.name).toBeLessThanOrEqual(500 - 32) + } + mkdirSync(ASSETS, { recursive: true }) + await sharp(await page.screenshot({ type: 'png' })) + .resize(1024, 500, { kernel: 'lanczos3' }) + .jpeg({ quality: 92 }) + .toFile(path.join(ASSETS, 'feature-graphic.jpg')) + await context.close() + + // The app icon artwork as Play wants it: 512 px, a 32-bit PNG that is fully opaque. + await sharp(path.resolve(__dirname, '../resources/icon.png')) + .resize(512, 512, { kernel: 'lanczos3' }) + .flatten({ background: '#FF90E8' }) + .ensureAlpha() + .png({ compressionLevel: 9 }) + .toFile(path.join(ASSETS, 'play-icon.png')) +}) diff --git a/apps/web/e2e-v2/scan-consent.spec.ts b/apps/web/e2e-v2/scan-consent.spec.ts new file mode 100644 index 00000000..71807893 --- /dev/null +++ b/apps/web/e2e-v2/scan-consent.spec.ts @@ -0,0 +1,58 @@ +import { expect, test, type Page } from '@playwright/test' +import { openCurrentRoomSettings } from '../e2e/helpers' +import { makeRoom, mockCamera, stubTheModel, TINY_JPEG, type Posted } from './helpers' + +/** + * The explicit AI consent before a receipt scan is an app-only step (Apple 5.1.2(i)); the web + * keeps today's flow with its passive provider note and no extra tap. This suite runs the web + * build, so it pins that boundary: the web never shows the consent step or its settings switch, + * whatever a device has stored, and the photo is sent exactly once, only after it is picked. + * The app side of the gate (`scanConsentNeeded`) is unit-tested in `src/lib/use-settings.test.ts`. + */ + +const pickPhoto = (page: Page) => + page.getByTestId('scan-upload-input').setInputFiles({ + name: 'bill.jpg', + mimeType: 'image/jpeg', + buffer: TINY_JPEG, + }) + +test('the web scan asks for no AI consent, even with a stored refusal, and sends the photo once', async ({ page }) => { + // A device that turned consent off in the app shape of the setting. The web must ignore it. + await page.addInitScript(() => { + window.localStorage.setItem( + 'ps:settings', + JSON.stringify({ soundEnabled: true, hapticsEnabled: true, animationsEnabled: true, scanConsent: false }) + ) + }) + await mockCamera(page, 'denied') + const posted: Posted = {} + await stubTheModel(page, posted) + await makeRoom(page, 'Consent trip') + + await page.getByTestId('open-add-expense').click() + await expect(page.getByTestId('scan-bill')).toBeVisible({ timeout: 15_000 }) + await page.getByTestId('scan-bill').click() + await expect(page.getByTestId('scan-camera')).toBeVisible({ timeout: 15_000 }) + await expect(page.getByTestId('scan-consent')).toHaveCount(0) + await expect(page.locator('#scan-provider-terms')).toBeVisible() + expect(posted.calls ?? 0).toBe(0) + + await pickPhoto(page) + await expect(page.getByTestId('scan-item-label').first()).toBeVisible({ timeout: 15_000 }) + await expect(page.getByTestId('scan-consent')).toHaveCount(0) + expect(posted.calls).toBe(1) + + // The web never writes the setting either; the device's stored answer is left as it was. + expect(await page.evaluate(() => JSON.parse(window.localStorage.getItem('ps:settings') ?? '{}').scanConsent)).toBe( + false + ) +}) + +test('web room settings offer no AI consent switch', async ({ page }) => { + await makeRoom(page, 'Settings trip') + await openCurrentRoomSettings(page) + const sheet = page.getByTestId('settings-sheet') + await expect(sheet.getByTestId('device-row')).toBeVisible() + await expect(sheet.getByTestId('setting-scan-consent')).toHaveCount(0) +}) diff --git a/apps/web/e2e/achievements.spec.ts b/apps/web/e2e/achievements.spec.ts index bf91b117..8da0cbf8 100644 --- a/apps/web/e2e/achievements.spec.ts +++ b/apps/web/e2e/achievements.spec.ts @@ -166,14 +166,20 @@ test('the crew moment is a keepsake, not roster completion or an invitation prom await page.evaluate( () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))) ) - await page.getByTestId('share-card-crew').click() - await expect - .poll(() => - page.evaluate( - () => (window as Window & { __achievementSharePayload?: ShareData }).__achievementSharePayload + // `cardReady` can be the shelf tile's request; the button fetches its own copy of the card and + // a tap before that copy lands shares nothing. Tap again until the button holds the card. + await expect(async () => { + await page.getByTestId('share-card-crew').click() + await expect + .poll( + () => + page.evaluate( + () => (window as Window & { __achievementSharePayload?: ShareData }).__achievementSharePayload + ), + { timeout: 2_000 } ) - ) - .toBeTruthy() + .toBeTruthy() + }).toPass({ timeout: 15_000 }) const payload = await page.evaluate( () => (window as Window & { __achievementSharePayload?: ShareData }).__achievementSharePayload ) diff --git a/apps/web/e2e/legal-links.spec.ts b/apps/web/e2e/legal-links.spec.ts new file mode 100644 index 00000000..e741075b --- /dev/null +++ b/apps/web/e2e/legal-links.spec.ts @@ -0,0 +1,47 @@ +import { expect, test, type Page } from '@playwright/test' +import { enterCreatedRoom, openCurrentRoomSettings } from './helpers' + +/** + * Both stores require a privacy link inside the app, and the web carries the same one so the two + * surfaces never drift. Neither store requires terms, and the only terms that exist today are + * peanut.me's wallet terms, which contradict the Split listing. So the app surfaces (rooms home + * and room settings) carry a Privacy link and no terms link. The marketing footer keeps its own. + */ + +const expectPrivacyLink = async (page: Page, testId: string) => { + const link = page.getByTestId(testId) + await expect(link).toBeVisible() + await expect(link).toHaveText('Privacy') + const href = await link.getAttribute('href') + expect(href).toBeTruthy() + // An absolute product URL, so the same link works from the store app's bundled origin. + expect(new URL(href!).pathname).toBe('/privacy') + const response = await page.request.get(href!) + expect(response.status()).toBe(200) +} + +const noTermsLink = (page: Page) => page.locator('a[href*="/terms"]') + +test('the rooms home links to the privacy page and carries no terms link', async ({ page }) => { + // manage=1 keeps the home on screen even when this device has a recent room. + await page.goto('/app?manage=1') + await expect(page.getByTestId('app-home')).toBeVisible({ timeout: 15_000 }) + await expectPrivacyLink(page, 'app-privacy-link') + await expect(noTermsLink(page)).toHaveCount(0) +}) + +test('room settings link to the privacy page and carry no terms link', async ({ page }) => { + await page.goto('/new?name=Privacy%20check¤cy=EUR') + await expect(page.getByTestId('room-name')).toHaveValue('Privacy check') + await page.getByTestId('creator-name').fill('Ana') + await page.getByTestId('create-room').click() + await enterCreatedRoom(page) + + await openCurrentRoomSettings(page) + const sheet = page.getByTestId('settings-sheet') + await sheet.getByTestId('privacy-link').scrollIntoViewIfNeeded() + await expectPrivacyLink(page, 'privacy-link') + await expect(sheet.locator('a[href*="/terms"]')).toHaveCount(0) + // The web does not ask for AI consent, so it offers no switch to change that answer. + await expect(sheet.getByTestId('setting-scan-consent')).toHaveCount(0) +}) diff --git a/apps/web/e2e/store-offer.spec.ts b/apps/web/e2e/store-offer.spec.ts new file mode 100644 index 00000000..a35bde4a --- /dev/null +++ b/apps/web/e2e/store-offer.spec.ts @@ -0,0 +1,122 @@ +import { devices, type APIRequestContext, type BrowserContextOptions, type Page } from '@playwright/test' +import { expect, test } from './fixtures' + +/** + * The iPhone store offer (INTERACTION.md 10.1, the recipient guard). It needs a server built with + * `NEXT_PUBLIC_IOS_APP_STORE_ID`, which only the head leg of `native.yml` provides; every other run + * skips it, so the plain suites stay exactly as they were. + */ +const STORE_ID = process.env.NEXT_PUBLIC_IOS_APP_STORE_ID ?? '' +test.skip(!STORE_ID, 'Needs a build with NEXT_PUBLIC_IOS_APP_STORE_ID set') +test.setTimeout(90_000) + +const STORE_URL = `https://apps.apple.com/app/id${STORE_ID}` +const STORE_TAPPED_AT_KEY = 'ps:pwa-store-tapped-at:v1' +/** Every store surface the web can render, automatic or manual. */ +const STORE_SURFACES = ['install-app-store', 'install-row-store', 'room-updates-store'] + +/** `newContext` rejects a device's browser choice; the rest of the descriptor is the device. */ +const contextFor = (name: 'iPhone 14' | 'Pixel 7'): BrowserContextOptions => { + const { defaultBrowserType: _browser, ...device } = devices[name] + return device +} + +async function createRoom(request: APIRequestContext, name: string): Promise { + const response = await request.post('/api/rooms', { data: { name, currency: 'EUR', creatorName: 'Ana' } }) + expect(response.ok()).toBe(true) + const { room } = (await response.json()) as { room: { slug: string } } + return room.slug +} + +/** The Smart App Banner tag as Safari reads it: from the raw response, before ``. */ +async function bannerContent(request: APIRequestContext, path: string): Promise { + const response = await request.get(path) + expect(response.status(), path).toBeLessThan(400) + const html = await response.text() + const headEnd = html.indexOf('') + expect(headEnd).toBeGreaterThan(0) + const match = / { + await page.waitForTimeout(2_500) + await expect(page.getByTestId('install-prompt')).toHaveCount(0) + for (const testId of STORE_SURFACES) await expect(page.getByTestId(testId)).toHaveCount(0) + await expect(page.locator('a[href^="https://apps.apple.com/"]')).toHaveCount(0) +} + +test('room and recap pages carry the banner tag in the head; no other page does', async ({ request }) => { + const slug = await createRoom(request, 'Banner room') + const expected = `app-id=${STORE_ID}, app-argument=https://peanutsplit.com/r/${slug}` + + expect(await bannerContent(request, `/r/${slug}`)).toBe(expected) + expect(await bannerContent(request, `/r/${slug}/recap`)).toBe(expected) + for (const path of ['/', '/blog', '/app', '/new', '/import', `/r/${slug}/import`]) { + expect(await bannerContent(request, path), path).toBeNull() + } +}) + +test('a first-time recipient on an iPhone gets the room and the banner, never a store card', async ({ + request, + newDevice, +}) => { + const slug = await createRoom(request, 'Recipient room') + const page = await newDevice(contextFor('iPhone 14')) + + await page.goto(`/r/${slug}`) + await expect(page.getByTestId('join-gate')).toBeVisible({ timeout: 15_000 }) + await expect(page.locator('head meta[name="apple-itunes-app"]')).toHaveAttribute( + 'content', + `app-id=${STORE_ID}, app-argument=https://peanutsplit.com/r/${slug}` + ) + await expectNoStoreOffer(page) +}) + +test('on an iPhone, /app offers the store; a tap quiets every automatic offer', async ({ request, newDevice }) => { + const [first, second] = await Promise.all([createRoom(request, 'Room one'), createRoom(request, 'Room two')]) + const page = await newDevice(contextFor('iPhone 14')) + // The store is another origin; answer it locally so the test never leaves the machine. + await page + .context() + .route('https://apps.apple.com/**', (route) => + route.fulfill({ status: 200, contentType: 'text/html', body: 'App Store' }) + ) + + await page.goto('/app?install=1&source=app') + const store = page.getByTestId('install-app-store') + await expect(store).toBeVisible({ timeout: 15_000 }) + await expect(store).toHaveAttribute('href', STORE_URL) + await expect(page.getByTestId('install-app-native')).toHaveCount(0) + + await store.click() + await page.waitForURL(STORE_URL) + + for (const slug of [first, first, second]) { + await page.goto(`/r/${slug}`) + await expect(page.getByTestId('join-gate')).toBeVisible({ timeout: 15_000 }) + const tappedAt = await page.evaluate((key) => window.localStorage.getItem(key), STORE_TAPPED_AT_KEY) + expect(Number(tappedAt)).toBeGreaterThan(0) + // A store tap is not a refusal. + expect(await page.evaluate(() => window.localStorage.getItem('ps:pwa-dismiss-count'))).toBeNull() + await expectNoStoreOffer(page) + } +}) + +test('on Android, the web keeps the PWA install and offers no store anywhere', async ({ request, newDevice }) => { + const slug = await createRoom(request, 'Android room') + const page = await newDevice(contextFor('Pixel 7')) + + await page.goto('/app?install=1&source=app') + await expect(page.getByTestId('install-app-surface')).toBeVisible({ timeout: 15_000 }) + // Today's PWA path: the browser install steps until Chrome offers its own prompt. + await expect(page.getByTestId('install-app-surface')).toContainText('Install Split') + await expectNoStoreOffer(page) + + await page.goto(`/r/${slug}`) + await expect(page.getByTestId('join-gate')).toBeVisible({ timeout: 15_000 }) + await expectNoStoreOffer(page) +}) diff --git a/apps/web/ios/.gitignore b/apps/web/ios/.gitignore new file mode 100644 index 00000000..f4702997 --- /dev/null +++ b/apps/web/ios/.gitignore @@ -0,0 +1,13 @@ +App/build +App/Pods +App/output +App/App/public +DerivedData +xcuserdata + +# Cordova plugins for Capacitor +capacitor-cordova-ios-plugins + +# Generated Config files +App/App/capacitor.config.json +App/App/config.xml diff --git a/apps/web/ios/App/App.xcodeproj/project.pbxproj b/apps/web/ios/App/App.xcodeproj/project.pbxproj new file mode 100644 index 00000000..a8812e7c --- /dev/null +++ b/apps/web/ios/App/App.xcodeproj/project.pbxproj @@ -0,0 +1,389 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 60; + objects = { + +/* Begin PBXBuildFile section */ + 2FAD9763203C412B000D30F8 /* config.xml in Resources */ = {isa = PBXBuildFile; fileRef = 2FAD9762203C412B000D30F8 /* config.xml */; }; + 4D22ABE92AF431CB00220026 /* CapApp-SPM in Frameworks */ = {isa = PBXBuildFile; productRef = 4D22ABE82AF431CB00220026 /* CapApp-SPM */; }; + 50379B232058CBB4000EE86E /* capacitor.config.json in Resources */ = {isa = PBXBuildFile; fileRef = 50379B222058CBB4000EE86E /* capacitor.config.json */; }; + 504EC3081FED79650016851F /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 504EC3071FED79650016851F /* AppDelegate.swift */; }; + 504EC30D1FED79650016851F /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 504EC30B1FED79650016851F /* Main.storyboard */; }; + 504EC30F1FED79650016851F /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 504EC30E1FED79650016851F /* Assets.xcassets */; }; + 504EC3121FED79650016851F /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 504EC3101FED79650016851F /* LaunchScreen.storyboard */; }; + 50B271D11FEDC1A000F3C39B /* public in Resources */ = {isa = PBXBuildFile; fileRef = 50B271D01FEDC1A000F3C39B /* public */; }; + A1F0C0DE0000000000000004 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = A1F0C0DE0000000000000003 /* PrivacyInfo.xcprivacy */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 2FAD9762203C412B000D30F8 /* config.xml */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = config.xml; sourceTree = ""; }; + 50379B222058CBB4000EE86E /* capacitor.config.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = capacitor.config.json; sourceTree = ""; }; + 504EC3041FED79650016851F /* App.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = App.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 504EC3071FED79650016851F /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 504EC30C1FED79650016851F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 504EC30E1FED79650016851F /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 504EC3111FED79650016851F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 504EC3131FED79650016851F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 50B271D01FEDC1A000F3C39B /* public */ = {isa = PBXFileReference; lastKnownFileType = folder; path = public; sourceTree = ""; }; + 958DCC722DB07C7200EA8C5F /* debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = debug.xcconfig; path = ../debug.xcconfig; sourceTree = SOURCE_ROOT; }; + A1F0C0DE0000000000000001 /* App.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = App.entitlements; sourceTree = ""; }; + A1F0C0DE0000000000000002 /* AppRelease.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = AppRelease.entitlements; sourceTree = ""; }; + A1F0C0DE0000000000000003 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = PrivacyInfo.xcprivacy; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 504EC3011FED79650016851F /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 4D22ABE92AF431CB00220026 /* CapApp-SPM in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 504EC2FB1FED79650016851F = { + isa = PBXGroup; + children = ( + 958DCC722DB07C7200EA8C5F /* debug.xcconfig */, + 504EC3061FED79650016851F /* App */, + 504EC3051FED79650016851F /* Products */, + ); + sourceTree = ""; + }; + 504EC3051FED79650016851F /* Products */ = { + isa = PBXGroup; + children = ( + 504EC3041FED79650016851F /* App.app */, + ); + name = Products; + sourceTree = ""; + }; + 504EC3061FED79650016851F /* App */ = { + isa = PBXGroup; + children = ( + 50379B222058CBB4000EE86E /* capacitor.config.json */, + 504EC3071FED79650016851F /* AppDelegate.swift */, + 504EC30B1FED79650016851F /* Main.storyboard */, + 504EC30E1FED79650016851F /* Assets.xcassets */, + 504EC3101FED79650016851F /* LaunchScreen.storyboard */, + 504EC3131FED79650016851F /* Info.plist */, + A1F0C0DE0000000000000001 /* App.entitlements */, + A1F0C0DE0000000000000002 /* AppRelease.entitlements */, + A1F0C0DE0000000000000003 /* PrivacyInfo.xcprivacy */, + 2FAD9762203C412B000D30F8 /* config.xml */, + 50B271D01FEDC1A000F3C39B /* public */, + ); + path = App; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 504EC3031FED79650016851F /* App */ = { + isa = PBXNativeTarget; + buildConfigurationList = 504EC3161FED79650016851F /* Build configuration list for PBXNativeTarget "App" */; + buildPhases = ( + 504EC3001FED79650016851F /* Sources */, + 504EC3011FED79650016851F /* Frameworks */, + 504EC3021FED79650016851F /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = App; + packageProductDependencies = ( + 4D22ABE82AF431CB00220026 /* CapApp-SPM */, + ); + productName = App; + productReference = 504EC3041FED79650016851F /* App.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 504EC2FC1FED79650016851F /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 0920; + TargetAttributes = { + 504EC3031FED79650016851F = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + }; + }; + }; + buildConfigurationList = 504EC2FF1FED79650016851F /* Build configuration list for PBXProject "App" */; + compatibilityVersion = "Xcode 8.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 504EC2FB1FED79650016851F; + packageReferences = ( + D4C12C0A2AAA248700AAC8A2 /* XCLocalSwiftPackageReference "CapApp-SPM" */, + ); + productRefGroup = 504EC3051FED79650016851F /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 504EC3031FED79650016851F /* App */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 504EC3021FED79650016851F /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 504EC3121FED79650016851F /* LaunchScreen.storyboard in Resources */, + 50B271D11FEDC1A000F3C39B /* public in Resources */, + 504EC30F1FED79650016851F /* Assets.xcassets in Resources */, + 50379B232058CBB4000EE86E /* capacitor.config.json in Resources */, + 504EC30D1FED79650016851F /* Main.storyboard in Resources */, + 2FAD9763203C412B000D30F8 /* config.xml in Resources */, + A1F0C0DE0000000000000004 /* PrivacyInfo.xcprivacy in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 504EC3001FED79650016851F /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 504EC3081FED79650016851F /* AppDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXVariantGroup section */ + 504EC30B1FED79650016851F /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 504EC30C1FED79650016851F /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 504EC3101FED79650016851F /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 504EC3111FED79650016851F /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 504EC3141FED79650016851F /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 958DCC722DB07C7200EA8C5F /* debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 16.4; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 504EC3151FED79650016851F /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 16.4; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 504EC3171FED79650016851F /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 958DCC722DB07C7200EA8C5F /* debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_ENTITLEMENTS = App/App.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + INFOPLIST_FILE = App/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 16.4; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + OTHER_SWIFT_FLAGS = "$(inherited) \"-D\" \"COCOAPODS\" \"-DDEBUG\""; + PRODUCT_BUNDLE_IDENTIFIER = com.peanutsplit.app; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = 1; + }; + name = Debug; + }; + 504EC3181FED79650016851F /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_ENTITLEMENTS = App/AppRelease.entitlements; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "Apple Distribution"; + CODE_SIGN_STYLE = Manual; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = PW388G893L; + INFOPLIST_FILE = App/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 16.4; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.peanutsplit.app; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = "Peanut Split App Store"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = ""; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = 1; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 504EC2FF1FED79650016851F /* Build configuration list for PBXProject "App" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 504EC3141FED79650016851F /* Debug */, + 504EC3151FED79650016851F /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 504EC3161FED79650016851F /* Build configuration list for PBXNativeTarget "App" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 504EC3171FED79650016851F /* Debug */, + 504EC3181FED79650016851F /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + D4C12C0A2AAA248700AAC8A2 /* XCLocalSwiftPackageReference "CapApp-SPM" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = "CapApp-SPM"; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 4D22ABE82AF431CB00220026 /* CapApp-SPM */ = { + isa = XCSwiftPackageProductDependency; + package = D4C12C0A2AAA248700AAC8A2 /* XCLocalSwiftPackageReference "CapApp-SPM" */; + productName = "CapApp-SPM"; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 504EC2FC1FED79650016851F /* Project object */; +} diff --git a/apps/web/ios/App/App.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/apps/web/ios/App/App.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000..18d98100 --- /dev/null +++ b/apps/web/ios/App/App.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/apps/web/ios/App/App.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/apps/web/ios/App/App.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 00000000..34ea5701 --- /dev/null +++ b/apps/web/ios/App/App.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,24 @@ +{ + "originHash" : "11a925ef52b2185a4f3db4ee30ddf6bd1c5f671f0422edda84272a84a6bf7909", + "pins" : [ + { + "identity" : "capacitor-swift-pm", + "kind" : "remoteSourceControl", + "location" : "https://github.com/ionic-team/capacitor-swift-pm.git", + "state" : { + "revision" : "0e862e6ff13852a710c8a484180ca4d6a2cc9761", + "version" : "8.2.0" + } + }, + { + "identity" : "ion-ios-filesystem", + "kind" : "remoteSourceControl", + "location" : "https://github.com/ionic-team/ion-ios-filesystem.git", + "state" : { + "revision" : "549c18ad9d9bb70d05df37cc3f6f7aa7f5d0ee52", + "version" : "2.0.1" + } + } + ], + "version" : 3 +} diff --git a/apps/web/ios/App/App/App.entitlements b/apps/web/ios/App/App/App.entitlements new file mode 100644 index 00000000..edb733ae --- /dev/null +++ b/apps/web/ios/App/App/App.entitlements @@ -0,0 +1,12 @@ + + + + + aps-environment + development + com.apple.developer.associated-domains + + applinks:peanutsplit.com + + + diff --git a/apps/web/ios/App/App/AppDelegate.swift b/apps/web/ios/App/App/AppDelegate.swift new file mode 100644 index 00000000..4a603e99 --- /dev/null +++ b/apps/web/ios/App/App/AppDelegate.swift @@ -0,0 +1,61 @@ +import UIKit +import Capacitor + +@UIApplicationMain +class AppDelegate: UIResponder, UIApplicationDelegate { + + var window: UIWindow? + + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { + // Override point for customization after application launch. + return true + } + + func applicationWillResignActive(_ application: UIApplication) { + // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. + // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. + } + + func applicationDidEnterBackground(_ application: UIApplication) { + // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. + // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. + } + + func applicationWillEnterForeground(_ application: UIApplication) { + // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. + } + + func applicationDidBecomeActive(_ application: UIApplication) { + // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. + } + + func applicationWillTerminate(_ application: UIApplication) { + // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. + } + + func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { + // Called when the app was launched with a url. Feel free to add additional processing here, + // but if you want the App API to support tracking app url opens, make sure to keep this call + return ApplicationDelegateProxy.shared.application(app, open: url, options: options) + } + + func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { + // Called when the app was launched with an activity, including Universal Links. + // Feel free to add additional processing here, but if you want the App API to support + // tracking app url opens, make sure to keep this call + return ApplicationDelegateProxy.shared.application(application, continue: userActivity, restorationHandler: restorationHandler) + } + + // Push token forwarding, word for word from the @capacitor/push-notifications README. The + // plugin listens only for these two NotificationCenter posts: without them register() + // resolves and no token ever arrives. `cap sync` never rewrites this file, and + // scripts/native/assert-native-config.mjs fails if either name goes missing. + func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { + NotificationCenter.default.post(name: .capacitorDidRegisterForRemoteNotifications, object: deviceToken) + } + + func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { + NotificationCenter.default.post(name: .capacitorDidFailToRegisterForRemoteNotifications, object: error) + } + +} diff --git a/apps/web/ios/App/App/AppRelease.entitlements b/apps/web/ios/App/App/AppRelease.entitlements new file mode 100644 index 00000000..754468dc --- /dev/null +++ b/apps/web/ios/App/App/AppRelease.entitlements @@ -0,0 +1,12 @@ + + + + + aps-environment + production + com.apple.developer.associated-domains + + applinks:peanutsplit.com + + + diff --git a/apps/web/ios/App/App/Assets.xcassets/AppIcon.appiconset/AppIcon-512@2x.png b/apps/web/ios/App/App/Assets.xcassets/AppIcon.appiconset/AppIcon-512@2x.png new file mode 100644 index 00000000..db103264 Binary files /dev/null and b/apps/web/ios/App/App/Assets.xcassets/AppIcon.appiconset/AppIcon-512@2x.png differ diff --git a/apps/web/ios/App/App/Assets.xcassets/AppIcon.appiconset/Contents.json b/apps/web/ios/App/App/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000..b1a84833 --- /dev/null +++ b/apps/web/ios/App/App/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images": [ + { + "idiom": "universal", + "size": "1024x1024", + "filename": "AppIcon-512@2x.png", + "platform": "ios" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} \ No newline at end of file diff --git a/apps/web/ios/App/App/Assets.xcassets/Contents.json b/apps/web/ios/App/App/Assets.xcassets/Contents.json new file mode 100644 index 00000000..da4a164c --- /dev/null +++ b/apps/web/ios/App/App/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/apps/web/ios/App/App/Assets.xcassets/Splash.imageset/Contents.json b/apps/web/ios/App/App/Assets.xcassets/Splash.imageset/Contents.json new file mode 100644 index 00000000..a6acd177 --- /dev/null +++ b/apps/web/ios/App/App/Assets.xcassets/Splash.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images": [ + { + "idiom": "universal", + "filename": "Default@1x~universal~anyany.png", + "scale": "1x" + }, + { + "idiom": "universal", + "filename": "Default@2x~universal~anyany.png", + "scale": "2x" + }, + { + "idiom": "universal", + "filename": "Default@3x~universal~anyany.png", + "scale": "3x" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +} \ No newline at end of file diff --git a/apps/web/ios/App/App/Assets.xcassets/Splash.imageset/Default@1x~universal~anyany.png b/apps/web/ios/App/App/Assets.xcassets/Splash.imageset/Default@1x~universal~anyany.png new file mode 100644 index 00000000..71c91c11 Binary files /dev/null and b/apps/web/ios/App/App/Assets.xcassets/Splash.imageset/Default@1x~universal~anyany.png differ diff --git a/apps/web/ios/App/App/Assets.xcassets/Splash.imageset/Default@2x~universal~anyany.png b/apps/web/ios/App/App/Assets.xcassets/Splash.imageset/Default@2x~universal~anyany.png new file mode 100644 index 00000000..71c91c11 Binary files /dev/null and b/apps/web/ios/App/App/Assets.xcassets/Splash.imageset/Default@2x~universal~anyany.png differ diff --git a/apps/web/ios/App/App/Assets.xcassets/Splash.imageset/Default@3x~universal~anyany.png b/apps/web/ios/App/App/Assets.xcassets/Splash.imageset/Default@3x~universal~anyany.png new file mode 100644 index 00000000..71c91c11 Binary files /dev/null and b/apps/web/ios/App/App/Assets.xcassets/Splash.imageset/Default@3x~universal~anyany.png differ diff --git a/apps/web/ios/App/App/Base.lproj/LaunchScreen.storyboard b/apps/web/ios/App/App/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 00000000..e7ae5d78 --- /dev/null +++ b/apps/web/ios/App/App/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/web/ios/App/App/Base.lproj/Main.storyboard b/apps/web/ios/App/App/Base.lproj/Main.storyboard new file mode 100644 index 00000000..b44df7be --- /dev/null +++ b/apps/web/ios/App/App/Base.lproj/Main.storyboard @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/apps/web/ios/App/App/Info.plist b/apps/web/ios/App/App/Info.plist new file mode 100644 index 00000000..5f6cdfef --- /dev/null +++ b/apps/web/ios/App/App/Info.plist @@ -0,0 +1,48 @@ + + + + + CAPACITOR_DEBUG + $(CAPACITOR_DEBUG) + CFBundleDevelopmentRegion + en + CFBundleDisplayName + Split + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(MARKETING_VERSION) + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + ITSAppUsesNonExemptEncryption + + LSRequiresIPhoneOS + + NSCameraUsageDescription + Split uses the camera to scan a receipt you choose to photograph. + NSPhotoLibraryAddUsageDescription + Split saves the image you choose to your photos. + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + + UIViewControllerBasedStatusBarAppearance + + + diff --git a/apps/web/ios/App/App/PrivacyInfo.xcprivacy b/apps/web/ios/App/App/PrivacyInfo.xcprivacy new file mode 100644 index 00000000..2834cdf3 --- /dev/null +++ b/apps/web/ios/App/App/PrivacyInfo.xcprivacy @@ -0,0 +1,141 @@ + + + + + NSPrivacyTracking + + NSPrivacyTrackingDomains + + NSPrivacyCollectedDataTypes + + + NSPrivacyCollectedDataType + NSPrivacyCollectedDataTypeName + NSPrivacyCollectedDataTypeLinked + + NSPrivacyCollectedDataTypeTracking + + NSPrivacyCollectedDataTypePurposes + + NSPrivacyCollectedDataTypePurposeAppFunctionality + + + + NSPrivacyCollectedDataType + NSPrivacyCollectedDataTypePhotosorVideos + NSPrivacyCollectedDataTypeLinked + + NSPrivacyCollectedDataTypeTracking + + NSPrivacyCollectedDataTypePurposes + + NSPrivacyCollectedDataTypePurposeAppFunctionality + + + + NSPrivacyCollectedDataType + NSPrivacyCollectedDataTypeCustomerSupport + NSPrivacyCollectedDataTypeLinked + + NSPrivacyCollectedDataTypeTracking + + NSPrivacyCollectedDataTypePurposes + + NSPrivacyCollectedDataTypePurposeAppFunctionality + + + + NSPrivacyCollectedDataType + NSPrivacyCollectedDataTypeOtherUserContent + NSPrivacyCollectedDataTypeLinked + + NSPrivacyCollectedDataTypeTracking + + NSPrivacyCollectedDataTypePurposes + + NSPrivacyCollectedDataTypePurposeAppFunctionality + + + + NSPrivacyCollectedDataType + NSPrivacyCollectedDataTypeUserID + NSPrivacyCollectedDataTypeLinked + + NSPrivacyCollectedDataTypeTracking + + NSPrivacyCollectedDataTypePurposes + + NSPrivacyCollectedDataTypePurposeAppFunctionality + + + + NSPrivacyCollectedDataType + NSPrivacyCollectedDataTypeDeviceID + NSPrivacyCollectedDataTypeLinked + + NSPrivacyCollectedDataTypeTracking + + NSPrivacyCollectedDataTypePurposes + + NSPrivacyCollectedDataTypePurposeAnalytics + NSPrivacyCollectedDataTypePurposeAppFunctionality + + + + NSPrivacyCollectedDataType + NSPrivacyCollectedDataTypeProductInteraction + NSPrivacyCollectedDataTypeLinked + + NSPrivacyCollectedDataTypeTracking + + NSPrivacyCollectedDataTypePurposes + + NSPrivacyCollectedDataTypePurposeAnalytics + + + + NSPrivacyCollectedDataType + NSPrivacyCollectedDataTypeCrashData + NSPrivacyCollectedDataTypeLinked + + NSPrivacyCollectedDataTypeTracking + + NSPrivacyCollectedDataTypePurposes + + NSPrivacyCollectedDataTypePurposeAppFunctionality + + + + NSPrivacyCollectedDataType + NSPrivacyCollectedDataTypeOtherDiagnosticData + NSPrivacyCollectedDataTypeLinked + + NSPrivacyCollectedDataTypeTracking + + NSPrivacyCollectedDataTypePurposes + + NSPrivacyCollectedDataTypePurposeAppFunctionality + + + + NSPrivacyAccessedAPITypes + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryUserDefaults + NSPrivacyAccessedAPITypeReasons + + CA92.1 + + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryFileTimestamp + NSPrivacyAccessedAPITypeReasons + + C617.1 + + + + + diff --git a/apps/web/ios/App/CapApp-SPM/.gitignore b/apps/web/ios/App/CapApp-SPM/.gitignore new file mode 100644 index 00000000..3b298120 --- /dev/null +++ b/apps/web/ios/App/CapApp-SPM/.gitignore @@ -0,0 +1,9 @@ +.DS_Store +/.build +/Packages +/*.xcodeproj +xcuserdata/ +DerivedData/ +.swiftpm/config/registries.json +.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata +.netrc diff --git a/apps/web/ios/App/CapApp-SPM/Package.swift b/apps/web/ios/App/CapApp-SPM/Package.swift new file mode 100644 index 00000000..5f36d476 --- /dev/null +++ b/apps/web/ios/App/CapApp-SPM/Package.swift @@ -0,0 +1,41 @@ +// swift-tools-version: 5.9 +import PackageDescription + +// DO NOT MODIFY THIS FILE - managed by Capacitor CLI commands +let package = Package( + name: "CapApp-SPM", + platforms: [.iOS(.v15)], + products: [ + .library( + name: "CapApp-SPM", + targets: ["CapApp-SPM"]) + ], + dependencies: [ + .package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", exact: "8.2.0"), + .package(name: "CapacitorApp", path: "../../../node_modules/.pnpm/@capacitor+app@8.1.2_@capacitor+core@8.2.0/node_modules/@capacitor/app"), + .package(name: "CapacitorBrowser", path: "../../../node_modules/.pnpm/@capacitor+browser@8.0.5_@capacitor+core@8.2.0/node_modules/@capacitor/browser"), + .package(name: "CapacitorFilesystem", path: "../../../node_modules/.pnpm/@capacitor+filesystem@8.1.5_@capacitor+core@8.2.0/node_modules/@capacitor/filesystem"), + .package(name: "CapacitorPreferences", path: "../../../node_modules/.pnpm/@capacitor+preferences@8.0.1_@capacitor+core@8.2.0/node_modules/@capacitor/preferences"), + .package(name: "CapacitorPushNotifications", path: "../../../node_modules/.pnpm/@capacitor+push-notifications@8.1.3_@capacitor+core@8.2.0/node_modules/@capacitor/push-notifications"), + .package(name: "CapacitorShare", path: "../../../node_modules/.pnpm/@capacitor+share@8.0.3_@capacitor+core@8.2.0/node_modules/@capacitor/share"), + .package(name: "CapacitorSplashScreen", path: "../../../node_modules/.pnpm/@capacitor+splash-screen@8.0.2_@capacitor+core@8.2.0/node_modules/@capacitor/splash-screen"), + .package(name: "CapacitorStatusBar", path: "../../../node_modules/.pnpm/@capacitor+status-bar@8.0.4_@capacitor+core@8.2.0/node_modules/@capacitor/status-bar") + ], + targets: [ + .target( + name: "CapApp-SPM", + dependencies: [ + .product(name: "Capacitor", package: "capacitor-swift-pm"), + .product(name: "Cordova", package: "capacitor-swift-pm"), + .product(name: "CapacitorApp", package: "CapacitorApp"), + .product(name: "CapacitorBrowser", package: "CapacitorBrowser"), + .product(name: "CapacitorFilesystem", package: "CapacitorFilesystem"), + .product(name: "CapacitorPreferences", package: "CapacitorPreferences"), + .product(name: "CapacitorPushNotifications", package: "CapacitorPushNotifications"), + .product(name: "CapacitorShare", package: "CapacitorShare"), + .product(name: "CapacitorSplashScreen", package: "CapacitorSplashScreen"), + .product(name: "CapacitorStatusBar", package: "CapacitorStatusBar") + ] + ) + ] +) diff --git a/apps/web/ios/App/CapApp-SPM/README.md b/apps/web/ios/App/CapApp-SPM/README.md new file mode 100644 index 00000000..03964db9 --- /dev/null +++ b/apps/web/ios/App/CapApp-SPM/README.md @@ -0,0 +1,5 @@ +# CapApp-SPM + +This package is used to host SPM dependencies for your Capacitor project + +Do not modify the contents of it or there may be unintended consequences. diff --git a/apps/web/ios/App/CapApp-SPM/Sources/CapApp-SPM/CapApp-SPM.swift b/apps/web/ios/App/CapApp-SPM/Sources/CapApp-SPM/CapApp-SPM.swift new file mode 100644 index 00000000..945afec8 --- /dev/null +++ b/apps/web/ios/App/CapApp-SPM/Sources/CapApp-SPM/CapApp-SPM.swift @@ -0,0 +1 @@ +public let isCapacitorApp = true diff --git a/apps/web/ios/debug.xcconfig b/apps/web/ios/debug.xcconfig new file mode 100644 index 00000000..53ce18de --- /dev/null +++ b/apps/web/ios/debug.xcconfig @@ -0,0 +1 @@ +CAPACITOR_DEBUG = true diff --git a/apps/web/next.config.js b/apps/web/next.config.js index 50eed144..f618c341 100644 --- a/apps/web/next.config.js +++ b/apps/web/next.config.js @@ -25,6 +25,10 @@ const nextConfig = { // and the proxy owns the general strip for everything else. skipTrailingSlashRedirect: true, + // Defined so Next inlines it: an undefined NEXT_PUBLIC_* survives as `process.env.X`, webpack + // cannot fold the guard in src/lib/native/host.ts, and the Capacitor chunk lands in this build. + env: { NEXT_PUBLIC_NATIVE_BUILD: '0' }, + /** * Two retirements, neither of them locale detection: nothing here reads `Accept-Language` or a * cookie, and no reader is ever moved off the language they asked for. @@ -55,6 +59,27 @@ const nextConfig = { ] }, + /** + * Two static files the store apps depend on. Both paths contain a dot, so src/proxy.ts's + * matcher skips them. iOS reads the association file only as JSON (it is served as + * application/octet-stream otherwise), and the apps fetch the version config cross-origin. + */ + async headers() { + return [ + { + source: '/.well-known/apple-app-site-association', + headers: [{ key: 'Content-Type', value: 'application/json' }], + }, + { + source: '/app-config.json', + headers: [ + { key: 'Access-Control-Allow-Origin', value: '*' }, + { key: 'Cache-Control', value: 'public, max-age=300' }, + ], + }, + ] + }, + /** * `public/` serves files at their exact path only — a directory never resolves to its own * index.html. The funnel quiz is one self-contained static file under `public/dev/funnel-quiz/`, @@ -65,9 +90,26 @@ const nextConfig = { }, } -// Serwist compiles src/app/sw.ts → public/sw.js. Skipped in dev so cold starts -// stay fast and the SW never caches a half-built dev bundle. -if (process.env.NODE_ENV !== 'development') { +if (process.env.SPLIT_NATIVE_BUILD === '1') { + // App-store build: static export of the app surface only. docs/current/NATIVE.md + module.exports = withNextIntl({ + output: 'export', + // The export lands here. Next still builds into .next (forced for output: 'export'), which + // replaces any web build there; scripts/native/postbuild.mjs then clears it except cache. + distDir: '.next-native', + trailingSlash: true, // room/index.html, which Capacitor's file server resolves + images: { unoptimized: true }, + pageExtensions: ['native.tsx', 'native.ts'], + reactStrictMode: true, + productionBrowserSourceMaps: false, + typescript: { tsconfigPath: 'tsconfig.native.json' }, + // NEXT_PUBLIC_BASE_URL stays out of this block on purpose: a config value would override + // the process env, and the test export must be able to point at a loopback API. + env: { NEXT_PUBLIC_NATIVE_BUILD: '1' }, + }) +} else if (process.env.NODE_ENV !== 'development') { + // Serwist compiles src/app/sw.ts → public/sw.js. Skipped in dev so cold starts + // stay fast and the SW never caches a half-built dev bundle. module.exports = async () => { const withSerwist = (await import('@serwist/next')).default({ swSrc: './src/app/sw.ts', diff --git a/apps/web/package.json b/apps/web/package.json index edf4df79..40a3a13b 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -22,7 +22,9 @@ "e2e": "playwright test", "e2e:pwa-boundary": "playwright test --config playwright.pwa-boundary.config.ts", "e2e:v2": "playwright test --config playwright.v2.config.ts", - "icons": "node scripts/generate-icons.mjs" + "icons": "node scripts/generate-icons.mjs", + "native:build": "export SPLIT_NATIVE_BUILD=1 NEXT_PUBLIC_BASE_URL=${NEXT_PUBLIC_BASE_URL:-https://peanutsplit.com} NEXT_PUBLIC_SPLIT_V2_ENABLED=${NEXT_PUBLIC_SPLIT_V2_ENABLED:-1} NEXT_PUBLIC_FOSS_RELEASED=${NEXT_PUBLIC_FOSS_RELEASED:-1} && next build --webpack && node scripts/native/postbuild.mjs", + "native:sync": "pnpm native:build && NODE_ENV=production cap sync" }, "pnpm": { "onlyBuiltDependencies": [ @@ -41,6 +43,17 @@ } }, "dependencies": { + "@capacitor/android": "8.2.0", + "@capacitor/app": "8.1.2", + "@capacitor/browser": "8.0.5", + "@capacitor/core": "8.2.0", + "@capacitor/filesystem": "8.1.5", + "@capacitor/ios": "8.2.0", + "@capacitor/preferences": "8.0.1", + "@capacitor/push-notifications": "8.1.3", + "@capacitor/share": "8.0.3", + "@capacitor/splash-screen": "8.0.2", + "@capacitor/status-bar": "8.0.4", "@fontsource/gluten": "4.5.12", "@fontsource/roboto": "4.5.8", "@headlessui/tailwindcss": "^0.2.2", @@ -72,12 +85,15 @@ "zod": "3.24.1" }, "devDependencies": { + "@capacitor/cli": "8.2.0", + "@fontsource-variable/roboto-flex": "5.3.0", "@playwright/test": "^1.63.0", "@types/node": "^22.20.4", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", "@types/web-push": "^3.6.4", "autoprefixer": "^10.6.1", + "happy-dom": "^21.0.4", "postcss": "^8.5.28", "postcss-import": "^16.2.0", "prettier": "^3.9.9", diff --git a/apps/web/playwright.native.config.ts b/apps/web/playwright.native.config.ts new file mode 100644 index 00000000..19580708 --- /dev/null +++ b/apps/web/playwright.native.config.ts @@ -0,0 +1,73 @@ +import { defineConfig, devices } from '@playwright/test' + +/** + * The store app's cross-origin suite (local/split-native-app ARCHITECTURE 14.2). + * + * Two servers on two ports, so every API call the bundled app makes is cross-origin, exactly as + * on a phone where the bundle loads from `capacitor://localhost` and the API is + * `https://peanutsplit.com`: + * + * - API (:3100): `next start` on the `pnpm build` output, so `src/proxy.ts` and its CORS answer run + * as in production. `SPLIT_CORS_TEST_ORIGINS` admits the app origin. The negative control in + * native.yml sets it to an empty string, which is why `??` and not `||` reads it below. + * - App (:8778): the static export served by `scripts/native/serve-export.mjs`, which copies + * Capacitor's rule that every dotless path gets the root index.html. The export must be built + * with `NEXT_PUBLIC_BASE_URL=http://localhost:3100` (native.yml does), or the app calls + * production. + * + * This file sits in the Docker context and the web typecheck, so it imports only + * `@playwright/test` (the 2026-08-03 incident class). Specs in `e2e-native/` may import `../e2e` + * helpers because `e2e-native` is excluded from both. + */ + +const API_PORT = 3100 +const APP_PORT = 8778 +const apiOrigin = `http://localhost:${API_PORT}` +const appOrigin = `http://localhost:${APP_PORT}` + +export default defineConfig({ + testDir: './e2e-native', + // `next start` is a production server, far lighter than the `next dev` the web suite uses. + workers: Number(process.env.E2E_WORKERS ?? 3), + fullyParallel: true, + // Two-device specs wait on cross-origin writes and the live stream; leave room on a CI runner. + timeout: 60_000, + forbidOnly: !!process.env.CI, + retries: process.env.CI ? 1 : 0, + // Default output folders (`test-results/`, `playwright-report/`): both are gitignored. + reporter: process.env.CI ? [['list'], ['html', { open: 'never' }]] : 'list', + use: { + baseURL: appOrigin, + trace: 'retain-on-failure', + // The app has no service worker; the web context in the specs blocks the web one so a + // cached response never hides a server answer. + serviceWorkers: 'block', + }, + webServer: [ + { + command: `pnpm exec next start --port ${API_PORT}`, + url: `${apiOrigin}/healthcheck`, + reuseExistingServer: !process.env.CI, + timeout: 120_000, + env: { + DATABASE_URL: + process.env.E2E_DATABASE_URL ?? 'postgresql://split:split@localhost:5433/peanut_split_dev', + SPLIT_FX_MODE: 'static', + NEXT_PUBLIC_BASE_URL: apiOrigin, + SPLIT_CORS_TEST_ORIGINS: process.env.SPLIT_CORS_TEST_ORIGINS ?? appOrigin, + }, + }, + { + command: `node scripts/native/serve-export.mjs .next-native ${APP_PORT}`, + url: `${appOrigin}/index.html`, + reuseExistingServer: !process.env.CI, + timeout: 30_000, + }, + ], + projects: [ + // iPhone geometry on both engines. WebKit is the closest Linux stand-in for WKWebView's + // CORS and EventSource; Chromium stands in for the Android System WebView. + { name: 'chromium', use: { ...devices['iPhone 14'], browserName: 'chromium' } }, + { name: 'webkit', use: { ...devices['iPhone 14'], browserName: 'webkit' } }, + ], +}) diff --git a/apps/web/pnpm-lock.yaml b/apps/web/pnpm-lock.yaml index c49c243a..1296d04a 100644 --- a/apps/web/pnpm-lock.yaml +++ b/apps/web/pnpm-lock.yaml @@ -13,6 +13,39 @@ importers: .: dependencies: + '@capacitor/android': + specifier: 8.2.0 + version: 8.2.0(@capacitor/core@8.2.0) + '@capacitor/app': + specifier: 8.1.2 + version: 8.1.2(@capacitor/core@8.2.0) + '@capacitor/browser': + specifier: 8.0.5 + version: 8.0.5(@capacitor/core@8.2.0) + '@capacitor/core': + specifier: 8.2.0 + version: 8.2.0 + '@capacitor/filesystem': + specifier: 8.1.5 + version: 8.1.5(@capacitor/core@8.2.0) + '@capacitor/ios': + specifier: 8.2.0 + version: 8.2.0(@capacitor/core@8.2.0) + '@capacitor/preferences': + specifier: 8.0.1 + version: 8.0.1(@capacitor/core@8.2.0) + '@capacitor/push-notifications': + specifier: 8.1.3 + version: 8.1.3(@capacitor/core@8.2.0) + '@capacitor/share': + specifier: 8.0.3 + version: 8.0.3(@capacitor/core@8.2.0) + '@capacitor/splash-screen': + specifier: 8.0.2 + version: 8.0.2(@capacitor/core@8.2.0) + '@capacitor/status-bar': + specifier: 8.0.4 + version: 8.0.4(@capacitor/core@8.2.0) '@fontsource/gluten': specifier: 4.5.12 version: 4.5.12 @@ -101,6 +134,12 @@ importers: specifier: 3.24.1 version: 3.24.1 devDependencies: + '@capacitor/cli': + specifier: 8.2.0 + version: 8.2.0 + '@fontsource-variable/roboto-flex': + specifier: 5.3.0 + version: 5.3.0 '@playwright/test': specifier: ^1.63.0 version: 1.63.0 @@ -119,6 +158,9 @@ importers: autoprefixer: specifier: ^10.6.1 version: 10.6.1(postcss@8.5.28) + happy-dom: + specifier: ^21.0.4 + version: 21.0.4 postcss: specifier: ^8.5.28 version: 8.5.28 @@ -145,7 +187,7 @@ importers: version: 5.9.3 vitest: specifier: ^4.1.11 - version: 4.1.11(@opentelemetry/api@1.9.1)(@types/node@22.20.4)(vite@7.3.6(@types/node@22.20.4)(jiti@1.21.7)(terser@5.51.2)(yaml@2.9.1)) + version: 4.1.11(@opentelemetry/api@1.9.1)(@types/node@22.20.4)(happy-dom@21.0.4)(vite@7.3.6(@types/node@22.20.4)(jiti@1.21.7)(terser@5.51.2)(yaml@2.9.1)) packages: @@ -220,6 +262,67 @@ packages: resolution: {integrity: sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==} engines: {node: '>=6.9.0'} + '@capacitor/android@8.2.0': + resolution: {integrity: sha512-XLm5OsWLPfXQxDxzFS7SOdMEgGvW+2c7TGLXkTR2cSKdkWK5Abns4imlT5qghKYhjM9r74IrDkBWg/9ALUGNKQ==} + peerDependencies: + '@capacitor/core': ^8.2.0 + + '@capacitor/app@8.1.2': + resolution: {integrity: sha512-uKBlsrXH0IdvUn69e/KKYbZ32A06pcrUdG8LWuZ/6y33YMXZXLEEdNSwl+jKS/SrsTWqnePs8EqSWaiQM3mUGA==} + peerDependencies: + '@capacitor/core': '>=8.0.0' + + '@capacitor/browser@8.0.5': + resolution: {integrity: sha512-qqcEjUqs9kG1naF+tsD8rERuZ3wuIfXzvoIJEERHI4RNWwNSUqAHHduaKhkyb+t01VyVPa0ydx0mZ/eOskk2Ug==} + peerDependencies: + '@capacitor/core': '>=8.0.0' + + '@capacitor/cli@8.2.0': + resolution: {integrity: sha512-1cMEk0d/I6tl1U+v/lnJR5Oylpx8ZBIHrvQxD5zK0MkjYOUyQAAGJgh97rkhGJqjAUvrGpa8H4BmyhNQN9a17A==} + engines: {node: '>=22.0.0'} + hasBin: true + + '@capacitor/core@8.2.0': + resolution: {integrity: sha512-oKaoNeNtH2iIZMDFVrb1atoyRECDGHcfLMunJ5KWN8DtvpVBeeA4c41e20NTuhMxw1cSYbpq2PV2hb+/9CJxlQ==} + + '@capacitor/filesystem@8.1.5': + resolution: {integrity: sha512-m1RkI8L83NJeppEKyRWioK3MDp2vjlA+QfUQcF8/xRlcXNC2HYxqoyYJ+K4M0EcVovy+g+4F24S05+bhK4Vgdg==} + peerDependencies: + '@capacitor/core': '>=8.0.0' + + '@capacitor/ios@8.2.0': + resolution: {integrity: sha512-X2/VtM4qP/R1SM0VQ5W/VotEc6PS/KTooD33EijsfAHWBdee+xmBapW8SeNLnu16wJ+tsfWlvtipaJEyfKbRKQ==} + peerDependencies: + '@capacitor/core': ^8.2.0 + + '@capacitor/preferences@8.0.1': + resolution: {integrity: sha512-T6no3ebi79XJCk91U3Jp/liJUwgBdvHR+s6vhvPkPxSuch7z3zx5Rv1bdWM6sWruNx+pViuEGqZvbfCdyBvcHQ==} + peerDependencies: + '@capacitor/core': '>=8.0.0' + + '@capacitor/push-notifications@8.1.3': + resolution: {integrity: sha512-UlOCTS3uiw8ZUJ1rkFKJgoqPADipHDNn0lq5mNRwtXALVxQXIeIoRd3iqpzC+962R2LpCRJRkCTjPX2OHK3tBA==} + peerDependencies: + '@capacitor/core': '>=8.0.0' + + '@capacitor/share@8.0.3': + resolution: {integrity: sha512-gnvZBV1NPu2B8vd1UKncR56G15ueHd0aZLqgDov++t3SmTBG9Q0VrAZ1VnHn5stxlmglVaTb4RwopMgbpLzroA==} + peerDependencies: + '@capacitor/core': '>=8.0.0' + + '@capacitor/splash-screen@8.0.2': + resolution: {integrity: sha512-0C6rYScr13WfAE9nPl4ScOQynmjFv9NT3Th+RZkD4ezYHmER6mcl1/lDYsv7jg3Rj3FOvLrlTlmNkUrr83kZzQ==} + peerDependencies: + '@capacitor/core': '>=8.0.0' + + '@capacitor/status-bar@8.0.4': + resolution: {integrity: sha512-ZMzBUyHBzwDUxcHadEhvOvmoPmMQGMZgaMRJu8ohELeI6IaxoVH9ZhdF/OHnY3/yykv3Glev8Tnbh4aZY/0B0w==} + peerDependencies: + '@capacitor/core': '>=8.0.0' + + '@capacitor/synapse@1.0.4': + resolution: {integrity: sha512-/C1FUo8/OkKuAT4nCIu/34ny9siNHr9qtFezu4kxm6GY1wNFxrCFWjfYx5C1tUhVGz3fxBABegupkpjXvjCHrw==} + '@eloqnt/config@0.1.1': resolution: {integrity: sha512-YRDigSaiJEzKDfzTth5kG+L/PKfB3mo8h7yNzpXExPfvQmcD05WoZT57PdhJE0jI+Vva6eb0OCU8hnHHgdME3g==} @@ -388,6 +491,9 @@ packages: cpu: [x64] os: [win32] + '@fontsource-variable/roboto-flex@5.3.0': + resolution: {integrity: sha512-bOxckUy0qXNRjhV6e4pcHGSvptix4ZRD1uaj5Za8h+p3qrb2GL4U4TQdpVmPSy0SmqwldfD+JJqEKdF68EyiAw==} + '@fontsource/gluten@4.5.12': resolution: {integrity: sha512-/zJdLtSulaOunqllmksPzka6kch4IKZUywXsorVZTYSYYyvhIZHysI7J4NDRolrhlZScJi2vxlOVnrjmiufxbg==} @@ -580,6 +686,42 @@ packages: cpu: [x64] os: [win32] + '@ionic/cli-framework-output@2.2.8': + resolution: {integrity: sha512-TshtaFQsovB4NWRBydbNFawql6yul7d5bMiW1WYYf17hd99V6xdDdk3vtF51bw6sLkxON3bDQpWsnUc9/hVo3g==} + engines: {node: '>=16.0.0'} + + '@ionic/utils-array@2.1.6': + resolution: {integrity: sha512-0JZ1Zkp3wURnv8oq6Qt7fMPo5MpjbLoUoa9Bu2Q4PJuSDWM8H8gwF3dQO7VTeUj3/0o1IB1wGkFWZZYgUXZMUg==} + engines: {node: '>=16.0.0'} + + '@ionic/utils-fs@3.1.7': + resolution: {integrity: sha512-2EknRvMVfhnyhL1VhFkSLa5gOcycK91VnjfrTB0kbqkTFCOXyXgVLI5whzq7SLrgD9t1aqos3lMMQyVzaQ5gVA==} + engines: {node: '>=16.0.0'} + + '@ionic/utils-object@2.1.6': + resolution: {integrity: sha512-vCl7sl6JjBHFw99CuAqHljYJpcE88YaH2ZW4ELiC/Zwxl5tiwn4kbdP/gxi2OT3MQb1vOtgAmSNRtusvgxI8ww==} + engines: {node: '>=16.0.0'} + + '@ionic/utils-process@2.1.12': + resolution: {integrity: sha512-Jqkgyq7zBs/v/J3YvKtQQiIcxfJyplPgECMWgdO0E1fKrrH8EF0QGHNJ9mJCn6PYe2UtHNS8JJf5G21e09DfYg==} + engines: {node: '>=16.0.0'} + + '@ionic/utils-stream@3.1.7': + resolution: {integrity: sha512-eSELBE7NWNFIHTbTC2jiMvh1ABKGIpGdUIvARsNPMNQhxJB3wpwdiVnoBoTYp+5a6UUIww4Kpg7v6S7iTctH1w==} + engines: {node: '>=16.0.0'} + + '@ionic/utils-subprocess@3.0.1': + resolution: {integrity: sha512-cT4te3AQQPeIM9WCwIg8ohroJ8TjsYaMb2G4ZEgv9YzeDqHZ4JpeIKqG2SoaA3GmVQ3sOfhPM6Ox9sxphV/d1A==} + engines: {node: '>=16.0.0'} + + '@ionic/utils-terminal@2.3.5': + resolution: {integrity: sha512-3cKScz9Jx2/Pr9ijj1OzGlBDfcmx7OMVBt4+P1uRR0SSW4cm1/y3Mo4OY3lfkuaYifMNBW8Wz6lQHbs1bihr7A==} + engines: {node: '>=16.0.0'} + + '@isaacs/fs-minipass@4.0.1': + resolution: {integrity: sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==} + engines: {node: '>=18.0.0'} + '@jridgewell/gen-mapping@0.3.13': resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} @@ -1509,6 +1651,9 @@ packages: '@types/estree@1.0.9': resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + '@types/fs-extra@8.1.5': + resolution: {integrity: sha512-0dzKcwO+S8s2kuF5Z9oUWatQJj5Uq/iqphEtE3GQJVRRYm/tD1LglU2UnXi2A8jLq5umkGouOXOR9y0n613ZwQ==} + '@types/hast@3.0.5': resolution: {integrity: sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g==} @@ -1535,6 +1680,9 @@ packages: '@types/react@19.3.0': resolution: {integrity: sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==} + '@types/slice-ansi@4.0.0': + resolution: {integrity: sha512-+OpjSaq85gvlZAYINyzKpLeiFkSC4EsC6IIiT6v6TLSU5k5U83fHGj9Lel8oKEXM0HqgrMVCjXPDPVICtxF7EQ==} + '@types/trusted-types@2.0.7': resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==} @@ -1547,6 +1695,12 @@ packages: '@types/web-push@3.6.4': resolution: {integrity: sha512-GnJmSr40H3RAnj0s34FNTcJi1hmWFV5KXugE0mYWnYhgTAHLJ/dJKAwDmvPJYMke0RplY2XE9LnM4hqSqKIjhQ==} + '@types/whatwg-mimetype@3.0.2': + resolution: {integrity: sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==} + + '@types/ws@8.18.2': + resolution: {integrity: sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==} + '@ungap/structured-clone@1.4.0': resolution: {integrity: sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ==} @@ -1624,6 +1778,10 @@ packages: '@webassemblyjs/wast-printer@1.14.1': resolution: {integrity: sha512-kPSSXE6De1XOR820C90RIo2ogvZG+c3KiHzqUoO/F34Y2shGzesfqv7o57xrxovZJH/MetF5UjroJ/R/3isoiw==} + '@xmldom/xmldom@0.9.12': + resolution: {integrity: sha512-5AXjrcMClTryPe9LgZrygpB1lj7s0S9E0+W+AHaVKAVyHanafK86iPSvG5xHVSp/jC+VH1UXu0TAEmY279xH7A==} + engines: {node: '>=14.6'} + '@xtuc/ieee754@1.2.0': resolution: {integrity: sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==} @@ -1674,6 +1832,14 @@ packages: ajv@8.20.0: resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==} + ansi-regex@5.0.1: + resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} + engines: {node: '>=8'} + + ansi-styles@4.3.0: + resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} + engines: {node: '>=8'} + any-promise@1.3.0: resolution: {integrity: sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==} @@ -1698,10 +1864,18 @@ packages: resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} engines: {node: '>=12'} + astral-regex@2.0.0: + resolution: {integrity: sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==} + engines: {node: '>=8'} + astring@1.9.0: resolution: {integrity: sha512-LElXdjswlqjWrPpJFg1Fx4wpkOCxj1TDHlSV4PlaRxHGWko024xICaa97ZkMfs6DRKlCguiAI+rbXv5GWwXIkg==} hasBin: true + at-least-node@1.0.0: + resolution: {integrity: sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==} + engines: {node: '>= 4.0.0'} + autoprefixer@10.6.1: resolution: {integrity: sha512-cL1Qz6ADZhcEbny/8HPfe99J6HhNoYtpX2LFLIbhgGE7Q1hlQVkYFdetDN7Id3KiQxhDrHwzlHr/YQCnZ8+xSA==} engines: {node: ^10 || ^12 || >=14} @@ -1716,11 +1890,18 @@ packages: resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} engines: {node: 18 || 20 || >=22} + base64-js@1.5.1: + resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} + baseline-browser-mapping@2.11.26: resolution: {integrity: sha512-GLQdD3y6UF8iVuMJl5fHgE4jdn/ua7n+toKfLgNlg3BqQtOZjpy68T8Tup8/wGWZCDlm7KMg7tPb4MPn7oN0TQ==} engines: {node: '>=6.0.0'} hasBin: true + big-integer@1.6.52: + resolution: {integrity: sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==} + engines: {node: '>=0.6'} + binary-extensions@2.3.0: resolution: {integrity: sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==} engines: {node: '>=8'} @@ -1728,6 +1909,10 @@ packages: bn.js@4.12.5: resolution: {integrity: sha512-3aRg6/JxfffFD+OlOjOFR3Vo79l39ooBTFucxx+MT3dhCtzn3EmiUPQo+6/OZuI2jbXi3YKgmiTFBgChQMwIRQ==} + bplist-parser@0.3.2: + resolution: {integrity: sha512-apC2+fspHGI3mMKj+dGevkGo/tCqVB8jMb6i+OX+E29p0Iposz07fABkRIfVUPNd5A5VbuOz1bZbnmkKLYF+wQ==} + engines: {node: '>= 5.10.0'} + brace-expansion@5.0.12: resolution: {integrity: sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==} engines: {node: 20 || >=22} @@ -1741,12 +1926,19 @@ packages: engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} hasBin: true + buffer-crc32@0.2.13: + resolution: {integrity: sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==} + buffer-equal-constant-time@1.0.1: resolution: {integrity: sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==} buffer-from@1.1.2: resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==} + buffer-image-size@0.6.4: + resolution: {integrity: sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==} + engines: {node: '>=4.0'} + c12@3.1.0: resolution: {integrity: sha512-uWoS8OU1MEIsOv8p/5a82c3H31LsWVR5qiyXVfBNOzfffjUWtPnhAb4BYI2uG2HfGmZmFjCtui5XNWaps+iFuw==} peerDependencies: @@ -1789,6 +1981,10 @@ packages: resolution: {integrity: sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==} engines: {node: '>= 14.16.0'} + chownr@3.0.0: + resolution: {integrity: sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==} + engines: {node: '>=18'} + chrome-trace-event@1.0.4: resolution: {integrity: sha512-rNjApaLzuwaOTjCiT8lSDdGN1APCiqkChLMJxJPWLunPAt5fy8xgU9/jNOchV84wfIxrA0lRQB7oCT8jrn/wrQ==} engines: {node: '>=6.0'} @@ -1808,9 +2004,20 @@ packages: collapse-white-space@2.1.0: resolution: {integrity: sha512-loKTxY1zCOuG4j9f6EPnuyyYkf58RnhhWTvRoZEokgB+WbdXehfjFviyOVYkqzEWz1Q5kRiZdBYS5SwxbQYwzw==} + color-convert@2.0.1: + resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} + engines: {node: '>=7.0.0'} + + color-name@1.1.4: + resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} + comma-separated-tokens@2.0.3: resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==} + commander@12.1.0: + resolution: {integrity: sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==} + engines: {node: '>=18'} + commander@2.20.3: resolution: {integrity: sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==} @@ -1845,6 +2052,10 @@ packages: core-js@3.50.0: resolution: {integrity: sha512-BRWgOLKkFeCgRudR6zrs8p9XJZcE14grzKMMssoYrk6krtuEZ7MTKPIY5RzOnqsEKIR9kst7wNzphttraT+Yqw==} + cross-spawn@7.0.6: + resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} + engines: {node: '>= 8'} + cssesc@3.0.0: resolution: {integrity: sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==} engines: {node: '>=4'} @@ -1869,6 +2080,10 @@ packages: resolution: {integrity: sha512-uqbvqLUMrc6p0MO+WBRtTxY55hmyh94WRwI5a++PZe54X+bfVh59FSN7uWCBCW1CCVjzjnrwzfI8zidE2obMMw==} engines: {node: '>=16.9.0'} + define-lazy-prop@2.0.0: + resolution: {integrity: sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og==} + engines: {node: '>=8'} + defu@6.1.7: resolution: {integrity: sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==} @@ -1915,6 +2130,13 @@ packages: electron-to-chromium@1.5.440: resolution: {integrity: sha512-SghDzqdJokdz8zP8YNlvS74+CwLRoUPDGvP/gFA+HrKVw+pOshUAgx8pXR37xl/u16zGae746rFNWvZ/22kU2Q==} + elementtree@0.1.7: + resolution: {integrity: sha512-wkgGT6kugeQk/P6VZ/f4T+4HB41BVgNBq5CDIZVbQ02nvTVqAiVTbskxxu3eA/X96lMlfYOwnLQpN2v5E1zDEg==} + engines: {node: '>= 0.4.0'} + + emoji-regex@8.0.0: + resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} + empathic@2.0.0: resolution: {integrity: sha512-i6UzDscO/XfAcNYD75CfICkmfLedpyPDdozrLMmQc5ORaQcdMoc21OnlEylMIqI7U8eniKrPMxxtj8k0vhmJhA==} engines: {node: '>=14'} @@ -1923,6 +2145,14 @@ packages: resolution: {integrity: sha512-nGXts5znJzmWPu+mIE9izCOzdg63oJca2mDzGWWTth7sr4aCToKcoyFVBQwN75Ij5Pf6p510EwkTqViTRzDV+w==} engines: {node: '>=10.13.0'} + entities@7.0.1: + resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==} + engines: {node: '>=0.12'} + + env-paths@2.2.1: + resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==} + engines: {node: '>=6'} + es-errors@1.3.0: resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==} engines: {node: '>= 0.4'} @@ -2039,6 +2269,9 @@ packages: fastq@1.20.3: resolution: {integrity: sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw==} + fd-slicer@1.1.0: + resolution: {integrity: sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==} + fdir@6.5.0: resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} engines: {node: '>=12.0.0'} @@ -2076,6 +2309,14 @@ packages: react-dom: optional: true + fs-extra@11.4.1: + resolution: {integrity: sha512-KYAb4c9BJQI6QqGKthV68OHe0badztdXJWKo0WtBA9IuCFPTKvE5ZdUBglP833aMjhaSPNO4A5j/EkzZtGlKjA==} + engines: {node: '>=14.14'} + + fs-extra@9.1.0: + resolution: {integrity: sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==} + engines: {node: '>=10'} + fsevents@2.3.3: resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} @@ -2115,6 +2356,10 @@ packages: resolution: {integrity: sha512-5v6yZd4JK3eMI3FqqCouswVqwugaA9r4dNZB1wwcmrD02QkV5H0y7XBQW8QwQqEaZY1pM9aqORSORhJRdNK44Q==} engines: {node: '>=6.0'} + happy-dom@21.0.4: + resolution: {integrity: sha512-tFm+GaLBgo6o0awHnvHaNoraVo27qJ+2tZEtZ+cIa08hXbeitrxAJajLI05hsUy/2/YTKcUjQYzHe5mCcraLBw==} + engines: {node: '>=20.0.0'} + has-flag@4.0.0: resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} engines: {node: '>=8'} @@ -2161,6 +2406,10 @@ packages: inherits@2.0.4: resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} + ini@4.1.3: + resolution: {integrity: sha512-X7rqawQBvfdjS10YU1y1YVreA3SsLrW9dX2CewP2EbBJM4ypVNLDkO5y04gejPwKIY9lR+7r9gn3rFPt/kmWFg==} + engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0} + inline-style-parser@0.2.7: resolution: {integrity: sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==} @@ -2184,6 +2433,11 @@ packages: is-decimal@2.0.1: resolution: {integrity: sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==} + is-docker@2.2.1: + resolution: {integrity: sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==} + engines: {node: '>=8'} + hasBin: true + is-extendable@0.1.1: resolution: {integrity: sha512-5BMULNob1vgFX6EjQw5izWDxrecWK9AM72rugNr0TFldMOi0fj6Jk+zeKIt0xGj4cEfQIJth4w3OKWOJ4f+AFw==} engines: {node: '>=0.10.0'} @@ -2192,6 +2446,10 @@ packages: resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} engines: {node: '>=0.10.0'} + is-fullwidth-code-point@3.0.0: + resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==} + engines: {node: '>=8'} + is-glob@4.0.3: resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==} engines: {node: '>=0.10.0'} @@ -2210,6 +2468,10 @@ packages: is-reference@1.2.1: resolution: {integrity: sha512-U82MsXXiFIrjCK4otLT+o2NA2Cd2g5MLoOVXUZjIOhLurrRxpEXzI8O0KZHr3IjLvlAH1kTPYSuqer5T9ZVBKQ==} + is-wsl@2.2.0: + resolution: {integrity: sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==} + engines: {node: '>=8'} + isexe@2.0.0: resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} @@ -2245,6 +2507,9 @@ packages: engines: {node: '>=6'} hasBin: true + jsonfile@6.2.1: + resolution: {integrity: sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==} + jwa@2.0.1: resolution: {integrity: sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==} @@ -2255,6 +2520,14 @@ packages: resolution: {integrity: sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==} engines: {node: '>=0.10.0'} + kleur@3.0.3: + resolution: {integrity: sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==} + engines: {node: '>=6'} + + kleur@4.1.5: + resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==} + engines: {node: '>=6'} + kolorist@1.8.0: resolution: {integrity: sha512-Y+60/zizpJ3HRH8DCss+q95yr6145JXZo46OTpFvDZWLfRCE4qChOyk1b26nMaNpfHHgxagk9dXT5OP0Tfe+dQ==} @@ -2533,6 +2806,10 @@ packages: resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==} engines: {node: '>=16 || 14 >=14.17'} + minizlib@3.1.0: + resolution: {integrity: sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==} + engines: {node: '>= 18'} + module-details-from-path@1.0.4: resolution: {integrity: sha512-EGWKgxALGMgzvxYF1UyGTy0HXX/2vHLkw6+NvDKW2jypWbHpjQuj4UMcqQWXHERJhVGKikolT06G3bcKe4fi7w==} @@ -2567,6 +2844,11 @@ packages: engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} hasBin: true + native-run@2.0.3: + resolution: {integrity: sha512-U1PllBuzW5d1gfan+88L+Hky2eZx+9gv3Pf6rNBxKbORxi7boHzqiA6QFGSnqMem4j0A9tZ08NMIs5+0m/VS1Q==} + engines: {node: '>=16.0.0'} + hasBin: true + negotiator@1.1.0: resolution: {integrity: sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==} engines: {node: '>=18'} @@ -2681,6 +2963,10 @@ packages: ohash@2.0.12: resolution: {integrity: sha512-65S/5gk9YSsaRjcyf7Nfa6h/d3E8/1gslpXfI4W7Dxn/oap8IKRuNT5VXkLQ1YFKIEg4apRY4Pj6aiwFzrDdmw==} + open@8.4.2: + resolution: {integrity: sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==} + engines: {node: '>=12'} + p-limit@3.1.0: resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==} engines: {node: '>=10'} @@ -2689,6 +2975,9 @@ packages: resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} engines: {node: '>=10'} + package-json-from-dist@1.0.1: + resolution: {integrity: sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==} + parse-entities@4.0.2: resolution: {integrity: sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw==} @@ -2696,6 +2985,10 @@ packages: resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} engines: {node: '>=8'} + path-key@3.1.1: + resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} + engines: {node: '>=8'} + path-parse@1.0.7: resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==} @@ -2706,6 +2999,9 @@ packages: pathe@2.0.3: resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} + pend@1.2.0: + resolution: {integrity: sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==} + perfect-debounce@1.0.0: resolution: {integrity: sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==} @@ -2737,6 +3033,10 @@ packages: engines: {node: '>=20'} hasBin: true + plist@3.1.1: + resolution: {integrity: sha512-ZIfcLJC+7E7FBFnDxm9MPmt7D+DidyQ26lewieO75AdhA2ayMtsJSES0iWzqJQbcVRSrTufQoy0DR94xHue0oA==} + engines: {node: '>=10.4.0'} + po-parser@2.2.0: resolution: {integrity: sha512-NdTrKgh0oO7+y+RFX8KKhOB438x/j94UGXEFzl/7pHH0JjWSn42iJ9tgmPksIO6n1JKDHmNDcejPJfKspljB9g==} @@ -2900,6 +3200,10 @@ packages: resolution: {integrity: sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==} engines: {node: '>=0.4.0'} + prompts@2.4.2: + resolution: {integrity: sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==} + engines: {node: '>= 6'} + property-information@7.2.0: resolution: {integrity: sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg==} @@ -2974,6 +3278,10 @@ packages: read-cache@1.0.2: resolution: {integrity: sha512-/peqiBB/n07gQGLsWaHho3WfvUyRscw0gYTsEFMhrIe/nWLkYaf5SbKYjGYqtRV3aPwykJgF2VEMo1ac4bnsGA==} + readable-stream@3.6.2: + resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==} + engines: {node: '>= 6'} + readdirp@3.6.0: resolution: {integrity: sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==} engines: {node: '>=8.10.0'} @@ -3031,6 +3339,11 @@ packages: resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==} engines: {iojs: '>=1.0.0', node: '>=0.10.0'} + rimraf@6.1.3: + resolution: {integrity: sha512-LKg+Cr2ZF61fkcaK1UdkH2yEBBKnYjTyWzTJT6KNPcSPaiT7HSdhtMXQuN5wkTX0Xu72KQ1l8S42rlmexS2hSA==} + engines: {node: 20 || >=22} + hasBin: true + rollup@4.63.5: resolution: {integrity: sha512-KRWwmNLlPw5M7HcdYfm15oBv9n9LPtjzpzCIxS/phwqvPyxHSoKX6Y2YU3pxSPfy0CLquVgsx/j/hBi6OvH1Nw==} engines: {node: '>=18.0.0', npm: '>=8.0.0'} @@ -3045,6 +3358,13 @@ packages: safer-buffer@2.1.2: resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} + sax@1.1.4: + resolution: {integrity: sha512-5f3k2PbGGp+YtKJjOItpg3P99IMD84E4HOvcfleTb5joCHNXYLsR9yWFPOYGgaeMPDubQILTCMdsFb2OMeOjtg==} + + sax@1.6.1: + resolution: {integrity: sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==} + engines: {node: '>=11.0.0'} + scheduler@0.28.0: resolution: {integrity: sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==} @@ -3082,9 +3402,27 @@ packages: '@types/node': optional: true + shebang-command@2.0.0: + resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} + engines: {node: '>=8'} + + shebang-regex@3.0.0: + resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} + engines: {node: '>=8'} + siginfo@2.0.0: resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + signal-exit@3.0.7: + resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==} + + sisteransi@1.0.5: + resolution: {integrity: sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==} + + slice-ansi@4.0.0: + resolution: {integrity: sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==} + engines: {node: '>=10'} + sonner@2.0.8: resolution: {integrity: sha512-UM/ByIoFra8yzV75n1o0Puu0bw5U/9UNnDacrJNspekBewIfsQ3D6ez1nvlWpt7aTsO6rujQtifBpycwIivqlg==} peerDependencies: @@ -3117,6 +3455,10 @@ packages: space-separated-tokens@2.0.2: resolution: {integrity: sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==} + split2@4.2.0: + resolution: {integrity: sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==} + engines: {node: '>= 10.x'} + sprintf-js@1.0.3: resolution: {integrity: sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==} @@ -3130,9 +3472,20 @@ packages: std-env@4.2.0: resolution: {integrity: sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==} + string-width@4.2.3: + resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==} + engines: {node: '>=8'} + + string_decoder@1.3.0: + resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==} + stringify-entities@4.0.4: resolution: {integrity: sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==} + strip-ansi@6.0.1: + resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} + engines: {node: '>=8'} + strip-bom-string@1.0.0: resolution: {integrity: sha512-uCC2VHvQRYu+lMh4My/sFNmF2klFymLX1wHJeXnbEJERpV/ZsVuonzerjfrGpIGF7LBVa1O7i9kjiWvJiFck8g==} engines: {node: '>=0.10.0'} @@ -3191,6 +3544,10 @@ packages: resolution: {integrity: sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==} engines: {node: '>=6'} + tar@7.5.22: + resolution: {integrity: sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==} + engines: {node: '>=18'} + terser@5.51.2: resolution: {integrity: sha512-bWnjSNscmuI+GJze6ZupnHP8G/cTcsJF+bXCeQknk2SHQsgbNJnLrqiH9jZ2W4STPVXH2mDKKRX3iwPhc9Cn/Q==} engines: {node: '>=10'} @@ -3203,6 +3560,9 @@ packages: thenify@3.3.1: resolution: {integrity: sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==} + through2@4.0.2: + resolution: {integrity: sha512-iOqSav00cVxEEICeD7TjLB1sueEL+81Wpzp2bY17uZjZN0pWZPuo4suZ/61VujxmqSGFfgOcNuTZ85QJwNZQpw==} + tinybench@2.9.0: resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} @@ -3225,6 +3585,10 @@ packages: tr46@0.0.3: resolution: {integrity: sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==} + tree-kill@1.2.2: + resolution: {integrity: sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==} + hasBin: true + trim-lines@3.0.1: resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==} @@ -3281,6 +3645,14 @@ packages: unist-util-visit@5.1.0: resolution: {integrity: sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==} + universalify@2.0.1: + resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==} + engines: {node: '>= 10.0.0'} + + untildify@4.0.0: + resolution: {integrity: sha512-KK8xQ1mkzZeg9inewmFVDNkg3l5LUhoq9kN6iWYB/CC9YMG8HA+c1Q8HwDe6dEX7kErrEVNVBO3fWsVq5iDgtw==} + engines: {node: '>=8'} + update-browserslist-db@1.3.3: resolution: {integrity: sha512-pJ2sYawQS0R/WI928Gj5GlPhTGzbMelq0+4INtSYNDV9ErKJcX6xjGWkoG/VnB3dpUm00zALaqkrUD77pO5TDQ==} hasBin: true @@ -3447,6 +3819,10 @@ packages: webpack-cli: optional: true + whatwg-mimetype@3.0.0: + resolution: {integrity: sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==} + engines: {node: '>=12'} + whatwg-url@5.0.0: resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==} @@ -3460,14 +3836,49 @@ packages: engines: {node: '>=8'} hasBin: true + wrap-ansi@7.0.0: + resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==} + engines: {node: '>=10'} + + ws@8.22.1: + resolution: {integrity: sha512-oyL6OPYme/CmiFvNuGzeoxCJ4nOrZE2O1FwM9MWM1AsGri6nLXB2pg+lNA8aLeXMSav0J6eIVS1j6vUPzUtK9g==} + engines: {node: '>=10.0.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: '>=5.0.2' + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + + xml2js@0.6.2: + resolution: {integrity: sha512-T4rieHaC1EXcES0Kxxj4JWgaUQHDk+qwHcYOCFHfiwKz7tOVPLq7Hjq9dM1WCMhylqMEfP7hMcOIChvotiZegA==} + engines: {node: '>=4.0.0'} + + xmlbuilder@11.0.1: + resolution: {integrity: sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==} + engines: {node: '>=4.0'} + + xmlbuilder@15.1.1: + resolution: {integrity: sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==} + engines: {node: '>=8.0'} + yallist@3.1.1: resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} + yallist@5.0.0: + resolution: {integrity: sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==} + engines: {node: '>=18'} + yaml@2.9.1: resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==} engines: {node: '>= 14.6'} hasBin: true + yauzl@2.10.0: + resolution: {integrity: sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==} + yocto-queue@0.1.0: resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} engines: {node: '>=10'} @@ -3585,6 +3996,75 @@ snapshots: '@babel/helper-string-parser': 7.29.7 '@babel/helper-validator-identifier': 7.29.7 + '@capacitor/android@8.2.0(@capacitor/core@8.2.0)': + dependencies: + '@capacitor/core': 8.2.0 + + '@capacitor/app@8.1.2(@capacitor/core@8.2.0)': + dependencies: + '@capacitor/core': 8.2.0 + + '@capacitor/browser@8.0.5(@capacitor/core@8.2.0)': + dependencies: + '@capacitor/core': 8.2.0 + + '@capacitor/cli@8.2.0': + dependencies: + '@ionic/cli-framework-output': 2.2.8 + '@ionic/utils-subprocess': 3.0.1 + '@ionic/utils-terminal': 2.3.5 + commander: 12.1.0 + debug: 4.4.3 + env-paths: 2.2.1 + fs-extra: 11.4.1 + kleur: 4.1.5 + native-run: 2.0.3 + open: 8.4.2 + plist: 3.1.1 + prompts: 2.4.2 + rimraf: 6.1.3 + semver: 7.8.5 + tar: 7.5.22 + tslib: 2.8.1 + xml2js: 0.6.2 + transitivePeerDependencies: + - supports-color + + '@capacitor/core@8.2.0': + dependencies: + tslib: 2.8.1 + + '@capacitor/filesystem@8.1.5(@capacitor/core@8.2.0)': + dependencies: + '@capacitor/core': 8.2.0 + '@capacitor/synapse': 1.0.4 + + '@capacitor/ios@8.2.0(@capacitor/core@8.2.0)': + dependencies: + '@capacitor/core': 8.2.0 + + '@capacitor/preferences@8.0.1(@capacitor/core@8.2.0)': + dependencies: + '@capacitor/core': 8.2.0 + + '@capacitor/push-notifications@8.1.3(@capacitor/core@8.2.0)': + dependencies: + '@capacitor/core': 8.2.0 + + '@capacitor/share@8.0.3(@capacitor/core@8.2.0)': + dependencies: + '@capacitor/core': 8.2.0 + + '@capacitor/splash-screen@8.0.2(@capacitor/core@8.2.0)': + dependencies: + '@capacitor/core': 8.2.0 + + '@capacitor/status-bar@8.0.4(@capacitor/core@8.2.0)': + dependencies: + '@capacitor/core': 8.2.0 + + '@capacitor/synapse@1.0.4': {} + '@eloqnt/config@0.1.1': {} '@eloqnt/format-json@0.1.0': @@ -3679,6 +4159,8 @@ snapshots: '@esbuild/win32-x64@0.28.2': optional: true + '@fontsource-variable/roboto-flex@5.3.0': {} + '@fontsource/gluten@4.5.12': {} '@fontsource/roboto@4.5.8': {} @@ -3811,6 +4293,86 @@ snapshots: '@img/sharp-win32-x64@0.35.5': optional: true + '@ionic/cli-framework-output@2.2.8': + dependencies: + '@ionic/utils-terminal': 2.3.5 + debug: 4.4.3 + tslib: 2.8.1 + transitivePeerDependencies: + - supports-color + + '@ionic/utils-array@2.1.6': + dependencies: + debug: 4.4.3 + tslib: 2.8.1 + transitivePeerDependencies: + - supports-color + + '@ionic/utils-fs@3.1.7': + dependencies: + '@types/fs-extra': 8.1.5 + debug: 4.4.3 + fs-extra: 9.1.0 + tslib: 2.8.1 + transitivePeerDependencies: + - supports-color + + '@ionic/utils-object@2.1.6': + dependencies: + debug: 4.4.3 + tslib: 2.8.1 + transitivePeerDependencies: + - supports-color + + '@ionic/utils-process@2.1.12': + dependencies: + '@ionic/utils-object': 2.1.6 + '@ionic/utils-terminal': 2.3.5 + debug: 4.4.3 + signal-exit: 3.0.7 + tree-kill: 1.2.2 + tslib: 2.8.1 + transitivePeerDependencies: + - supports-color + + '@ionic/utils-stream@3.1.7': + dependencies: + debug: 4.4.3 + tslib: 2.8.1 + transitivePeerDependencies: + - supports-color + + '@ionic/utils-subprocess@3.0.1': + dependencies: + '@ionic/utils-array': 2.1.6 + '@ionic/utils-fs': 3.1.7 + '@ionic/utils-process': 2.1.12 + '@ionic/utils-stream': 3.1.7 + '@ionic/utils-terminal': 2.3.5 + cross-spawn: 7.0.6 + debug: 4.4.3 + tslib: 2.8.1 + transitivePeerDependencies: + - supports-color + + '@ionic/utils-terminal@2.3.5': + dependencies: + '@types/slice-ansi': 4.0.0 + debug: 4.4.3 + signal-exit: 3.0.7 + slice-ansi: 4.0.0 + string-width: 4.2.3 + strip-ansi: 6.0.1 + tslib: 2.8.1 + untildify: 4.0.0 + wrap-ansi: 7.0.0 + transitivePeerDependencies: + - supports-color + + '@isaacs/fs-minipass@4.0.1': + dependencies: + minipass: 7.1.3 + '@jridgewell/gen-mapping@0.3.13': dependencies: '@jridgewell/sourcemap-codec': 1.6.0 @@ -4648,6 +5210,10 @@ snapshots: '@types/estree@1.0.9': {} + '@types/fs-extra@8.1.5': + dependencies: + '@types/node': 22.20.4 + '@types/hast@3.0.5': dependencies: '@types/unist': 3.0.3 @@ -4674,6 +5240,8 @@ snapshots: dependencies: csstype: 3.2.3 + '@types/slice-ansi@4.0.0': {} + '@types/trusted-types@2.0.7': {} '@types/unist@2.0.11': {} @@ -4684,6 +5252,12 @@ snapshots: dependencies: '@types/node': 22.20.4 + '@types/whatwg-mimetype@3.0.2': {} + + '@types/ws@8.18.2': + dependencies: + '@types/node': 22.20.4 + '@ungap/structured-clone@1.4.0': {} '@vitest/expect@4.1.11': @@ -4803,6 +5377,8 @@ snapshots: '@webassemblyjs/ast': 1.14.1 '@xtuc/long': 4.2.2 + '@xmldom/xmldom@0.9.12': {} + '@xtuc/ieee754@1.2.0': {} '@xtuc/long@4.2.2': {} @@ -4843,6 +5419,12 @@ snapshots: json-schema-traverse: 1.0.0 require-from-string: 2.0.2 + ansi-regex@5.0.1: {} + + ansi-styles@4.3.0: + dependencies: + color-convert: 2.0.1 + any-promise@1.3.0: {} anymatch@3.1.3: @@ -4869,8 +5451,12 @@ snapshots: assertion-error@2.0.1: {} + astral-regex@2.0.0: {} + astring@1.9.0: {} + at-least-node@1.0.0: {} + autoprefixer@10.6.1(postcss@8.5.28): dependencies: browserslist: 4.29.2 @@ -4884,12 +5470,20 @@ snapshots: balanced-match@4.0.4: {} + base64-js@1.5.1: {} + baseline-browser-mapping@2.11.26: {} + big-integer@1.6.52: {} + binary-extensions@2.3.0: {} bn.js@4.12.5: {} + bplist-parser@0.3.2: + dependencies: + big-integer: 1.6.52 + brace-expansion@5.0.12: dependencies: balanced-match: 4.0.4 @@ -4906,10 +5500,16 @@ snapshots: node-releases: 2.0.57 update-browserslist-db: 1.3.3(browserslist@4.29.2) + buffer-crc32@0.2.13: {} + buffer-equal-constant-time@1.0.1: {} buffer-from@1.1.2: {} + buffer-image-size@0.6.4: + dependencies: + '@types/node': 22.20.4 + c12@3.1.0: dependencies: chokidar: 4.0.3 @@ -4957,6 +5557,8 @@ snapshots: dependencies: readdirp: 4.1.2 + chownr@3.0.0: {} + chrome-trace-event@1.0.4: {} citty@0.1.6: @@ -4971,8 +5573,16 @@ snapshots: collapse-white-space@2.1.0: {} + color-convert@2.0.1: + dependencies: + color-name: 1.1.4 + + color-name@1.1.4: {} + comma-separated-tokens@2.0.3: {} + commander@12.1.0: {} + commander@2.20.3: {} commander@4.1.1: {} @@ -4993,6 +5603,12 @@ snapshots: core-js@3.50.0: {} + cross-spawn@7.0.6: + dependencies: + path-key: 3.1.1 + shebang-command: 2.0.0 + which: 2.0.2 + cssesc@3.0.0: {} csstype@3.2.3: {} @@ -5007,6 +5623,8 @@ snapshots: deepmerge-ts@8.0.2: {} + define-lazy-prop@2.0.0: {} + defu@6.1.7: {} dequal@2.0.3: {} @@ -5044,6 +5662,12 @@ snapshots: electron-to-chromium@1.5.440: {} + elementtree@0.1.7: + dependencies: + sax: 1.1.4 + + emoji-regex@8.0.0: {} + empathic@2.0.0: {} enhanced-resolve@5.25.1: @@ -5051,6 +5675,10 @@ snapshots: graceful-fs: 4.2.11 tapable: 2.3.3 + entities@7.0.1: {} + + env-paths@2.2.1: {} + es-errors@1.3.0: {} es-module-lexer@2.3.2: {} @@ -5190,6 +5818,10 @@ snapshots: dependencies: reusify: 1.1.0 + fd-slicer@1.1.0: + dependencies: + pend: 1.2.0 + fdir@6.5.0(picomatch@4.0.7): optionalDependencies: picomatch: 4.0.7 @@ -5216,6 +5848,19 @@ snapshots: react: 19.3.0 react-dom: 19.3.0(react@19.3.0) + fs-extra@11.4.1: + dependencies: + graceful-fs: 4.2.11 + jsonfile: 6.2.1 + universalify: 2.0.1 + + fs-extra@9.1.0: + dependencies: + at-least-node: 1.0.0 + graceful-fs: 4.2.11 + jsonfile: 6.2.1 + universalify: 2.0.1 + fsevents@2.3.3: optional: true @@ -5257,6 +5902,19 @@ snapshots: section-matter: 1.0.0 strip-bom-string: 1.0.0 + happy-dom@21.0.4: + dependencies: + '@types/node': 22.20.4 + '@types/whatwg-mimetype': 3.0.2 + '@types/ws': 8.18.2 + buffer-image-size: 0.6.4 + entities: 7.0.1 + whatwg-mimetype: 3.0.0 + ws: 8.22.1 + transitivePeerDependencies: + - bufferutil + - utf-8-validate + has-flag@4.0.0: {} hasown@2.0.4: @@ -5347,6 +6005,8 @@ snapshots: inherits@2.0.4: {} + ini@4.1.3: {} + inline-style-parser@0.2.7: {} intl-messageformat@11.2.15: @@ -5371,10 +6031,14 @@ snapshots: is-decimal@2.0.1: {} + is-docker@2.2.1: {} + is-extendable@0.1.1: {} is-extglob@2.1.1: {} + is-fullwidth-code-point@3.0.0: {} + is-glob@4.0.3: dependencies: is-extglob: 2.1.1 @@ -5389,6 +6053,10 @@ snapshots: dependencies: '@types/estree': 1.0.9 + is-wsl@2.2.0: + dependencies: + is-docker: 2.2.1 + isexe@2.0.0: {} jest-worker@27.5.1: @@ -5414,6 +6082,12 @@ snapshots: json5@2.2.3: {} + jsonfile@6.2.1: + dependencies: + universalify: 2.0.1 + optionalDependencies: + graceful-fs: 4.2.11 + jwa@2.0.1: dependencies: buffer-equal-constant-time: 1.0.1 @@ -5427,6 +6101,10 @@ snapshots: kind-of@6.0.3: {} + kleur@3.0.3: {} + + kleur@4.1.5: {} + kolorist@1.8.0: {} lilconfig@3.1.3: {} @@ -5922,6 +6600,10 @@ snapshots: minipass@7.1.3: {} + minizlib@3.1.0: + dependencies: + minipass: 7.1.3 + module-details-from-path@1.0.4: {} motion-dom@12.43.0: @@ -5948,6 +6630,22 @@ snapshots: nanoid@3.3.19: {} + native-run@2.0.3: + dependencies: + '@ionic/utils-fs': 3.1.7 + '@ionic/utils-terminal': 2.3.5 + bplist-parser: 0.3.2 + debug: 4.4.3 + elementtree: 0.1.7 + ini: 4.1.3 + plist: 3.1.1 + split2: 4.2.0 + through2: 4.0.2 + tslib: 2.8.1 + yauzl: 2.10.0 + transitivePeerDependencies: + - supports-color + negotiator@1.1.0: dependencies: content-type: 2.1.0 @@ -6053,6 +6751,12 @@ snapshots: ohash@2.0.12: {} + open@8.4.2: + dependencies: + define-lazy-prop: 2.0.0 + is-docker: 2.2.1 + is-wsl: 2.2.0 + p-limit@3.1.0: dependencies: yocto-queue: 0.1.0 @@ -6061,6 +6765,8 @@ snapshots: dependencies: p-limit: 3.1.0 + package-json-from-dist@1.0.1: {} + parse-entities@4.0.2: dependencies: '@types/unist': 2.0.11 @@ -6073,6 +6779,8 @@ snapshots: path-exists@4.0.0: {} + path-key@3.1.1: {} + path-parse@1.0.7: {} path-scurry@2.0.2: @@ -6082,6 +6790,8 @@ snapshots: pathe@2.0.3: {} + pend@1.2.0: {} + perfect-debounce@1.0.0: {} picocolors@1.1.1: {} @@ -6104,6 +6814,12 @@ snapshots: dependencies: playwright-core: 1.63.0 + plist@3.1.1: + dependencies: + '@xmldom/xmldom': 0.9.12 + base64-js: 1.5.1 + xmlbuilder: 15.1.1 + po-parser@2.2.0: {} postcss-import@15.1.0(postcss@8.5.28): @@ -6196,6 +6912,11 @@ snapshots: progress@2.0.3: {} + prompts@2.4.2: + dependencies: + kleur: 3.0.3 + sisteransi: 1.0.5 + property-information@7.2.0: {} proxy-agent-negotiate@1.1.0: {} @@ -6253,6 +6974,12 @@ snapshots: read-cache@1.0.2: {} + readable-stream@3.6.2: + dependencies: + inherits: 2.0.4 + string_decoder: 1.3.0 + util-deprecate: 1.0.2 + readdirp@3.6.0: dependencies: picomatch: 2.3.2 @@ -6355,6 +7082,11 @@ snapshots: reusify@1.1.0: {} + rimraf@6.1.3: + dependencies: + glob: 13.0.6 + package-json-from-dist: 1.0.1 + rollup@4.63.5: dependencies: '@types/estree': 1.0.9 @@ -6395,6 +7127,10 @@ snapshots: safer-buffer@2.1.2: {} + sax@1.1.4: {} + + sax@1.6.1: {} + scheduler@0.28.0: {} schema-utils@4.5.0: @@ -6455,8 +7191,24 @@ snapshots: '@img/sharp-win32-x64': 0.35.5 '@types/node': 22.20.4 + shebang-command@2.0.0: + dependencies: + shebang-regex: 3.0.0 + + shebang-regex@3.0.0: {} + siginfo@2.0.0: {} + signal-exit@3.0.7: {} + + sisteransi@1.0.5: {} + + slice-ansi@4.0.0: + dependencies: + ansi-styles: 4.3.0 + astral-regex: 2.0.0 + is-fullwidth-code-point: 3.0.0 + sonner@2.0.8(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0): dependencies: react: 19.3.0 @@ -6479,6 +7231,8 @@ snapshots: space-separated-tokens@2.0.2: {} + split2@4.2.0: {} + sprintf-js@1.0.3: {} stackback@0.0.2: {} @@ -6489,11 +7243,25 @@ snapshots: std-env@4.2.0: {} + string-width@4.2.3: + dependencies: + emoji-regex: 8.0.0 + is-fullwidth-code-point: 3.0.0 + strip-ansi: 6.0.1 + + string_decoder@1.3.0: + dependencies: + safe-buffer: 5.2.1 + stringify-entities@4.0.4: dependencies: character-entities-html4: 2.1.0 character-entities-legacy: 3.0.0 + strip-ansi@6.0.1: + dependencies: + ansi-regex: 5.0.1 + strip-bom-string@1.0.0: {} style-to-js@1.1.21: @@ -6565,6 +7333,14 @@ snapshots: tapable@2.3.3: {} + tar@7.5.22: + dependencies: + '@isaacs/fs-minipass': 4.0.1 + chownr: 3.0.0 + minipass: 7.1.3 + minizlib: 3.1.0 + yallist: 5.0.0 + terser@5.51.2: dependencies: '@jridgewell/source-map': 0.3.11 @@ -6580,6 +7356,10 @@ snapshots: dependencies: any-promise: 1.3.0 + through2@4.0.2: + dependencies: + readable-stream: 3.6.2 + tinybench@2.9.0: {} tinyexec@1.3.1: {} @@ -6597,6 +7377,8 @@ snapshots: tr46@0.0.3: {} + tree-kill@1.2.2: {} + trim-lines@3.0.1: {} trough@2.2.0: {} @@ -6660,6 +7442,10 @@ snapshots: unist-util-is: 6.0.1 unist-util-visit-parents: 6.0.2 + universalify@2.0.1: {} + + untildify@4.0.0: {} + update-browserslist-db@1.3.3(browserslist@4.29.2): dependencies: browserslist: 4.29.2 @@ -6732,7 +7518,7 @@ snapshots: terser: 5.51.2 yaml: 2.9.1 - vitest@4.1.11(@opentelemetry/api@1.9.1)(@types/node@22.20.4)(vite@7.3.6(@types/node@22.20.4)(jiti@1.21.7)(terser@5.51.2)(yaml@2.9.1)): + vitest@4.1.11(@opentelemetry/api@1.9.1)(@types/node@22.20.4)(happy-dom@21.0.4)(vite@7.3.6(@types/node@22.20.4)(jiti@1.21.7)(terser@5.51.2)(yaml@2.9.1)): dependencies: '@vitest/expect': 4.1.11 '@vitest/mocker': 4.1.11(vite@7.3.6(@types/node@22.20.4)(jiti@1.21.7)(terser@5.51.2)(yaml@2.9.1)) @@ -6757,6 +7543,7 @@ snapshots: optionalDependencies: '@opentelemetry/api': 1.9.1 '@types/node': 22.20.4 + happy-dom: 21.0.4 transitivePeerDependencies: - msw @@ -6824,6 +7611,8 @@ snapshots: - svgo - uglify-js + whatwg-mimetype@3.0.0: {} + whatwg-url@5.0.0: dependencies: tr46: 0.0.3 @@ -6838,10 +7627,34 @@ snapshots: siginfo: 2.0.0 stackback: 0.0.2 + wrap-ansi@7.0.0: + dependencies: + ansi-styles: 4.3.0 + string-width: 4.2.3 + strip-ansi: 6.0.1 + + ws@8.22.1: {} + + xml2js@0.6.2: + dependencies: + sax: 1.6.1 + xmlbuilder: 11.0.1 + + xmlbuilder@11.0.1: {} + + xmlbuilder@15.1.1: {} + yallist@3.1.1: {} + yallist@5.0.0: {} + yaml@2.9.1: {} + yauzl@2.10.0: + dependencies: + buffer-crc32: 0.2.13 + fd-slicer: 1.1.0 + yocto-queue@0.1.0: {} zod@3.24.1: {} diff --git a/apps/web/prisma/migrations/20261114011233_push_transport/migration.sql b/apps/web/prisma/migrations/20261114011233_push_transport/migration.sql new file mode 100644 index 00000000..d93c4eef --- /dev/null +++ b/apps/web/prisma/migrations/20261114011233_push_transport/migration.sql @@ -0,0 +1,5 @@ +-- AlterTable +ALTER TABLE "split"."PushSubscription" ADD COLUMN "transport" TEXT NOT NULL DEFAULT 'webpush', +ALTER COLUMN "p256dh" DROP NOT NULL, +ALTER COLUMN "auth" DROP NOT NULL; + diff --git a/apps/web/prisma/schema.prisma b/apps/web/prisma/schema.prisma index e326bff1..b342a22d 100644 --- a/apps/web/prisma/schema.prisma +++ b/apps/web/prisma/schema.prisma @@ -321,7 +321,14 @@ model FxRate { // somebody ELSE in the room writes. No accounts exist here, so the identity a // subscription carries is the per-room member it was registered as. -/// One delivery channel: this browser, acting as this member, in this room. +/// One delivery channel: this browser or app install, acting as this member, in +/// this room. +/// +/// `transport` says who delivers it. `webpush` rows hold a push-service URL in +/// `endpoint` plus the browser's `p256dh` and `auth` keys. Native app rows +/// (`apns`, `apns-sandbox`, `fcm`) hold `:` in +/// `endpoint` and no keys, so the uniqueness, the per-room cap and the status +/// check below carry over unchanged. /// /// The key is (endpoint, roomId), not endpoint alone. A browser has exactly one /// push endpoint, so a phone that joins two rooms would collide on a globally @@ -334,9 +341,10 @@ model PushSubscription { id String @id @default(uuid()) roomId String memberId String - endpoint String // push-service URL; the host is allowlisted at write time - p256dh String - auth String + transport String @default("webpush") + endpoint String // webpush: allowlisted push-service URL; native: ":" + p256dh String? // webpush only + auth String? // webpush only userAgent String? createdAt DateTime @default(now()) lastSeenAt DateTime @default(now()) diff --git a/apps/web/public/.well-known/apple-app-site-association b/apps/web/public/.well-known/apple-app-site-association new file mode 100644 index 00000000..c0ea9f65 --- /dev/null +++ b/apps/web/public/.well-known/apple-app-site-association @@ -0,0 +1,16 @@ +{ + "applinks": { + "details": [ + { + "appIDs": ["PW388G893L.com.peanutsplit.app"], + "components": [ + { "/": "/r/*/card/*", "exclude": true, "comment": "Share-card images open in the browser" }, + { "/": "/r/*/recap/card", "exclude": true, "comment": "Recap card image opens in the browser" }, + { "/": "/r/*/opengraph-image*", "exclude": true, "comment": "Link-preview image" }, + { "/": "/r/*/recap/opengraph-image*", "exclude": true, "comment": "Recap link-preview image" }, + { "/": "/r/*", "comment": "Every room link opens the app when it is installed" } + ] + } + ] + } +} diff --git a/apps/web/public/.well-known/assetlinks.json b/apps/web/public/.well-known/assetlinks.json new file mode 100644 index 00000000..7866256c --- /dev/null +++ b/apps/web/public/.well-known/assetlinks.json @@ -0,0 +1,12 @@ +[ + { + "relation": ["delegate_permission/common.handle_all_urls"], + "target": { + "namespace": "android_app", + "package_name": "com.peanutsplit.app", + "sha256_cert_fingerprints": [ + "PLACEHOLDER:REPLACE_WITH_PLAY_APP_SIGNING_AND_UPLOAD_KEY_SHA256_AFTER_FIRST_PLAY_UPLOAD" + ] + } + } +] diff --git a/apps/web/public/app-config.json b/apps/web/public/app-config.json new file mode 100644 index 00000000..2fae5897 --- /dev/null +++ b/apps/web/public/app-config.json @@ -0,0 +1,7 @@ +{ + "minBuild": { "ios": 0, "android": 0 }, + "store": { + "ios": "https://apps.apple.com/app/idPLACEHOLDER", + "android": "https://play.google.com/store/apps/details?id=com.peanutsplit.app" + } +} diff --git a/apps/web/resources/icon.png b/apps/web/resources/icon.png new file mode 100644 index 00000000..a4cd07c5 Binary files /dev/null and b/apps/web/resources/icon.png differ diff --git a/apps/web/resources/render-native-assets.mjs b/apps/web/resources/render-native-assets.mjs new file mode 100644 index 00000000..ded6077a --- /dev/null +++ b/apps/web/resources/render-native-assets.mjs @@ -0,0 +1,124 @@ +/** + * Store-app icons and splash, drawn from the same artwork and geometry as the PWA icons + * (scripts/generate-icons.mjs), so the app icon matches the installed PWA's. + * + * cd apps/web && node resources/render-native-assets.mjs + * + * Run it only when the artwork changes, then commit what it writes (ARCHITECTURE 9.6: generated + * once, never in CI). It writes: + * - resources/icon.png 1024 px, no alpha: the PWA apple-touch tile (thumb on flat pink). + * The App Store rejects an icon with an alpha channel. + * - resources/splash.png 2732 px, no alpha: the mark on the first-paint cream, sized like the + * PWA launch screens once iOS crops the square to a phone screen. + * - android/.../drawable-/ic_stat_split.png: the white mono mark (the PWA + * notification badge). Android draws only its alpha; without it a push + * shows a grey square. + * and then runs @capacitor/assets 3.0.5 to write the iOS app icon and splash and the Android + * launcher icons (adaptive: the PWA maskable thumb on pink) and splash screens. The tool reads + * `icon.png` as a logo and would draw it small on a plain background, so it gets its own input + * names in a temporary folder. + */ +import { execFileSync } from 'node:child_process' +import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync, copyFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import sharp from 'sharp' + +const root = path.resolve(fileURLToPath(new URL('..', import.meta.url))) +const RESOURCES = path.join(root, 'resources') +const ANDROID_RES = path.join(root, 'android/app/src/main/res') + +// The same values as scripts/generate-icons.mjs: artwork, colours and the thumb's ink box. +const SOURCE = readFileSync(path.join(root, 'src/assets/logos/split-mark.svg'), 'utf8') +const LOGO = SOURCE.replace(/^[\s\S]*?]*>/, '').replace(/<\/svg>[\s\S]*$/, '') +const MARK = SOURCE.match(/([\s\S]*?)<\/g>/)[1] +const PINK = '#FF90E8' +const CREAM = '#FAF4F0' +const BOARD = 1705 +const ART = { x: 191, y: 168, w: 1128, h: 1368 } + +function svg(size, body) { + return Buffer.from( + `${body}` + ) +} + +/** The thumb's ink box centred and scaled to `art` of the frame's height. */ +function thumb(art, mark = MARK) { + const scale = (BOARD * art) / ART.h + const tx = BOARD / 2 - scale * (ART.x + ART.w / 2) + const ty = BOARD / 2 - scale * (ART.y + ART.h / 2) + return `${mark}` +} + +const pinkTile = `` + +/** An opaque PNG (colour type 2): flattened onto `background`, alpha channel dropped. */ +function opaque(input, background) { + return sharp(input).flatten({ background }).removeAlpha().png({ compressionLevel: 9 }).toBuffer() +} + +// The PWA phone launch screens draw the disc at 38% of the screen width. iOS fills a phone screen +// with this square by its height (about 2.2 x the width), so 38% of the width is about 17.5% here. +const SPLASH = 2732 +const SPLASH_DISC = 0.175 + +function splashSvg() { + const diameter = Math.round(SPLASH * SPLASH_DISC) + const offset = (SPLASH - diameter) / 2 + return Buffer.from( + `` + + `` + + `${LOGO}` + ) +} + +/** Status-bar icon sizes: 24 dp at each density. */ +const STAT_DENSITIES = { mdpi: 24, hdpi: 36, xhdpi: 48, xxhdpi: 72, xxxhdpi: 96 } + +async function main() { + const icon = await opaque(svg(1024, pinkTile + thumb(0.72)), PINK) + const splash = await opaque(splashSvg(), CREAM) + writeFileSync(path.join(RESOURCES, 'icon.png'), icon) + writeFileSync(path.join(RESOURCES, 'splash.png'), splash) + + const white = MARK.replaceAll('stroke="black"', 'stroke="white"') + for (const [density, size] of Object.entries(STAT_DENSITIES)) { + const dir = path.join(ANDROID_RES, `drawable-${density}`) + mkdirSync(dir, { recursive: true }) + const png = await sharp(svg(size, thumb(0.82, white))).png({ compressionLevel: 9 }).toBuffer() + writeFileSync(path.join(dir, 'ic_stat_split.png'), png) + } + + const inputs = mkdtempSync(path.join(tmpdir(), 'split-assets-')) + try { + copyFileSync(path.join(RESOURCES, 'icon.png'), path.join(inputs, 'icon-only.png')) + copyFileSync(path.join(RESOURCES, 'splash.png'), path.join(inputs, 'splash.png')) + // Adaptive layers: the PWA maskable geometry (thumb at 61%) survives every launcher mask. + writeFileSync(path.join(inputs, 'icon-foreground.png'), await sharp(svg(1024, thumb(0.61))).png().toBuffer()) + writeFileSync(path.join(inputs, 'icon-background.png'), await opaque(svg(1024, pinkTile), PINK)) + execFileSync( + 'pnpm', + [ + 'dlx', + '--allow-build=sharp', + '@capacitor/assets@3.0.5', + 'generate', + '--ios', + '--android', + '--assetPath', + path.relative(root, inputs), + ], + { cwd: root, stdio: 'inherit' } + ) + } finally { + rmSync(inputs, { recursive: true, force: true }) + } +} + +main().catch((error) => { + console.error(error) + process.exit(1) +}) diff --git a/apps/web/resources/splash.png b/apps/web/resources/splash.png new file mode 100644 index 00000000..ba512493 Binary files /dev/null and b/apps/web/resources/splash.png differ diff --git a/apps/web/scripts/assert-pwa-build-boundary.mjs b/apps/web/scripts/assert-pwa-build-boundary.mjs index 1b21f4dd..e54749a9 100644 --- a/apps/web/scripts/assert-pwa-build-boundary.mjs +++ b/apps/web/scripts/assert-pwa-build-boundary.mjs @@ -55,4 +55,13 @@ assert.doesNotMatch( 'content layout owns a PWA side effect' ) -process.stdout.write('PWA build boundary: product-only registration verified.\n') +// Capacitor belongs only in the store-app export. Minified bundles keep no '@capacitor' import +// path, so also look for the core's own identifiers (isNativePlatform, androidBridge, Capacitor.). +// The native push hook's error text catches app code that a static import pulls into a web chunk. +const capacitorMarker = /isNativePlatform|androidBridge|@capacitor\/|Capacitor\.|the device did not get a push token/ +const capacitorChunks = chunks + .filter((file) => capacitorMarker.test(readFileSync(file, 'utf8'))) + .map((file) => file.slice(appRoot.length)) +assert.deepEqual(capacitorChunks, [], 'Capacitor code in the web bundle') + +process.stdout.write('PWA build boundary: product-only registration and no Capacitor verified.\n') diff --git a/apps/web/scripts/i18n-audit.mjs b/apps/web/scripts/i18n-audit.mjs index e50d6ee0..d3ee0933 100644 --- a/apps/web/scripts/i18n-audit.mjs +++ b/apps/web/scripts/i18n-audit.mjs @@ -332,24 +332,27 @@ for (const file of sourceFiles(srcRoot)) { // ---------------------------------------------------------------- document policy const layoutPath = 'src/app/(product-shell)/layout.tsx' +// The app export has its own root layout (it owns its ), so it carries the same +// single document-level policy as the product layout. +const documentRoots = new Set([layoutPath, 'src/app/(native)/layout.native.tsx']) const translationPolicyViolations = [] for (const file of sourceFiles(srcRoot)) { const path = relative(appRoot, file) const source = stripComments(readFileSync(file, 'utf8')) const notranslateOccurrences = source.match(/notranslate/g) ?? [] const googlePageOptOut = '' - if (path !== layoutPath && notranslateOccurrences.length > 0) { + if (!documentRoots.has(path) && notranslateOccurrences.length > 0) { translationPolicyViolations.push(`${path} uses notranslate outside the product document root`) } - if (path === layoutPath && (notranslateOccurrences.length !== 1 || !source.includes(googlePageOptOut))) { + if (documentRoots.has(path) && (notranslateOccurrences.length !== 1 || !source.includes(googlePageOptOut))) { translationPolicyViolations.push(`${path} must contain exactly one literal Google page-level opt-out`) } const attributes = [...source.matchAll(/translate\s*=\s*['"]no['"]/g)] - if (path !== layoutPath && attributes.length > 0) { + if (!documentRoots.has(path) && attributes.length > 0) { translationPolicyViolations.push(`${path} suppresses translation below the document root`) } - if (path === layoutPath && attributes.length !== 1) { + if (documentRoots.has(path) && attributes.length !== 1) { translationPolicyViolations.push(`${path} must contain exactly one translate="no" policy`) } } diff --git a/apps/web/scripts/native/assert-native-config.mjs b/apps/web/scripts/native/assert-native-config.mjs new file mode 100644 index 00000000..deef8bdd --- /dev/null +++ b/apps/web/scripts/native/assert-native-config.mjs @@ -0,0 +1,406 @@ +#!/usr/bin/env node +/** + * Fails when a native setting that a store review or a user's data depends on has drifted + * (ARCHITECTURE 13 and 15). No dependencies; prints one line per check. + * + * node scripts/native/assert-native-config.mjs # source mode: config and both projects + * node scripts/native/assert-native-config.mjs --app # the Info.plist Xcode built + * ... --root checks a copy of apps/web instead (used to prove a check fails) + * + * The Xcode project, the plists and the manifest are parsed as text: the checks must run on Linux, + * where neither Xcode nor the Android tools exist. + */ +import { execFileSync } from 'node:child_process' +import { existsSync, readFileSync } from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' + +const args = process.argv.slice(2) +const option = (name) => { + const index = args.indexOf(name) + return index === -1 ? null : args[index + 1] +} +const root = path.resolve(option('--root') ?? path.join(path.dirname(fileURLToPath(import.meta.url)), '../..')) +const appBundle = option('--app') + +const failures = [] +function check(label, ok, detail = '') { + console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${!ok && detail ? `: ${detail}` : ''}`) + if (!ok) failures.push(label) +} +const read = (file) => readFileSync(path.join(root, file), 'utf8') + +// --- A minimal XML plist reader (dict, array, string, integer, real, true, false) ---------------- + +function parsePlist(xml) { + // Comments, the XML declaration and the doctype are matched as tokens and dropped, so a comment + // that contains '<' or '>' never splits into stray tokens. + const tokens = xml + .match(/|<[^>]+>|[^<]+/g) + .filter((token) => token.trim() !== '' && !/^<(!--|\?xml|!DOCTYPE)/.test(token)) + let at = 0 + const decode = (text) => + text + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"') + .replace(/'/g, "'") + .replace(/&/g, '&') + function text(close) { + let value = '' + while (tokens[at] !== close) value += tokens[at++] + at++ + return decode(value) + } + function value() { + const tag = tokens[at++] + if (tag === '') return true + if (tag === '') return false + if (tag === '') return [] + if (tag === '') return {} + if (tag === '') return '' + if (tag === '') return text('') + if (tag === '' || tag === '') return Number(text(`') { + const list = [] + while (tokens[at] !== '') list.push(value()) + at++ + return list + } + if (tag === '') { + const dict = {} + while (tokens[at] !== '') { + if (tokens[at++] !== '') throw new Error(`plist: expected near token ${at}`) + const key = text('') + dict[key] = value() + } + at++ + return dict + } + throw new Error(`plist: unexpected ${tag}`) + } + if (tokens[at++] !== '') throw new Error('plist: no root') + return value() +} + +function readPlist(file) { + const raw = readFileSync(file) + // Xcode writes the built Info.plist as a binary plist; plutil exists wherever Xcode does. + const xml = + raw.subarray(0, 6).toString() === 'bplist' + ? execFileSync('plutil', ['-convert', 'xml1', '-o', '-', file], { encoding: 'utf8' }) + : raw.toString('utf8') + return parsePlist(xml) +} + +/** PNG colour types 4 and 6 carry alpha; a tRNS chunk adds it to the others. */ +function pngHasAlpha(file) { + const png = readFileSync(file) + if (png.subarray(1, 4).toString() !== 'PNG') throw new Error(`${file} is not a PNG`) + const colourType = png[25] + if (colourType === 4 || colourType === 6) return true + // Walk the chunks rather than search the bytes: compressed pixel data can contain "tRNS". + for (let at = 8; at + 8 <= png.length; at += 12 + png.readUInt32BE(at)) { + const type = png.subarray(at + 4, at + 8).toString('latin1') + if (type === 'tRNS') return true + if (type === 'IDAT' || type === 'IEND') break + } + return false +} + +// --- capacitor.config.ts ------------------------------------------------------------------------- + +/** + * The config file holds plain values plus one type annotation. Dropping the type import and the + * annotation leaves JavaScript, which runs as a module, so the checks see the real values rather + * than a regex's guess. A config that no longer evaluates this way fails here, loudly. + */ +async function loadCapacitorConfig() { + const source = read('capacitor.config.ts') + .replace(/^import type .*$/m, '') + .replace(/:\s*CapacitorConfig\b/, '') + return (await import(`data:text/javascript,${encodeURIComponent(source)}`)).default +} + +async function checkCapacitorConfig() { + let config + try { + config = await loadCapacitorConfig() + } catch (error) { + check('capacitor.config.ts evaluates', false, error.message) + return null + } + const server = config.server ?? {} + const plugins = config.plugins ?? {} + // Changing any of these three moves localStorage to a new origin: every room on the phone is lost. + check("server.iosScheme is 'capacitor'", server.iosScheme === 'capacitor', String(server.iosScheme)) + check("server.androidScheme is 'https'", server.androidScheme === 'https', String(server.androidScheme)) + check("server.hostname is 'localhost'", server.hostname === 'localhost', String(server.hostname)) + check('no server.url (the app ships its bundle, never a remote site)', server.url === undefined, String(server.url)) + check('CapacitorHttp is off', plugins.CapacitorHttp?.enabled === false) + check("webDir is '.next-native'", config.webDir === '.next-native', String(config.webDir)) + check( + 'StatusBar.overlaysWebView is false', + plugins.StatusBar?.overlaysWebView === false, + String(plugins.StatusBar?.overlaysWebView) + ) + check( + 'StatusBar has a backgroundColor', + /^#[0-9a-f]{6}$/i.test(plugins.StatusBar?.backgroundColor ?? ''), + String(plugins.StatusBar?.backgroundColor) + ) + check('SplashScreen hides itself only when the app says so', plugins.SplashScreen?.launchAutoHide === false) + return config +} + +// --- iOS ----------------------------------------------------------------------------------------- + +const IOS = 'ios/App' +const PORTRAIT = ['UIInterfaceOrientationPortrait'] +const CAMERA_TEXT = 'Split uses the camera to scan a receipt you choose to photograph.' +// The share sheet offers 'Save Image' for a card PNG; without this key iOS kills the app on that tap. +const PHOTO_ADD_TEXT = 'Split saves the image you choose to your photos.' + +function checkInfoPlist() { + const plist = readPlist(path.join(root, IOS, 'App/Info.plist')) + check('Info.plist: ITSAppUsesNonExemptEncryption is false', plist.ITSAppUsesNonExemptEncryption === false) + check( + 'Info.plist: NSCameraUsageDescription', + plist.NSCameraUsageDescription === CAMERA_TEXT, + plist.NSCameraUsageDescription + ) + check( + 'Info.plist: NSPhotoLibraryAddUsageDescription', + plist.NSPhotoLibraryAddUsageDescription === PHOTO_ADD_TEXT, + plist.NSPhotoLibraryAddUsageDescription + ) + check( + "Info.plist: CFBundleDisplayName is 'Split'", + plist.CFBundleDisplayName === 'Split', + plist.CFBundleDisplayName + ) + check('Info.plist: version from $(MARKETING_VERSION)', plist.CFBundleShortVersionString === '$(MARKETING_VERSION)') + check('Info.plist: build from $(CURRENT_PROJECT_VERSION)', plist.CFBundleVersion === '$(CURRENT_PROJECT_VERSION)') + check( + 'Info.plist: portrait only', + JSON.stringify(plist.UISupportedInterfaceOrientations) === JSON.stringify(PORTRAIT) + ) + check('Info.plist: no background modes', plist.UIBackgroundModes === undefined) +} + +function checkEntitlements(file, apsEnvironment) { + const label = path.basename(file) + if (!existsSync(path.join(root, IOS, file))) { + check(`${label} exists`, false) + return + } + const entitlements = readPlist(path.join(root, IOS, file)) + check( + `${label}: aps-environment is ${apsEnvironment}`, + entitlements['aps-environment'] === apsEnvironment, + entitlements['aps-environment'] + ) + check( + `${label}: associated domain applinks:peanutsplit.com`, + JSON.stringify(entitlements['com.apple.developer.associated-domains']) === '["applinks:peanutsplit.com"]' + ) +} + +function checkPrivacyManifest() { + const file = path.join(root, IOS, 'App/PrivacyInfo.xcprivacy') + if (!existsSync(file)) { + check('PrivacyInfo.xcprivacy exists', false) + return + } + const manifest = readPlist(file) + check('PrivacyInfo: NSPrivacyTracking is false', manifest.NSPrivacyTracking === false) + check('PrivacyInfo: no tracking domains', (manifest.NSPrivacyTrackingDomains ?? []).length === 0) + const collected = manifest.NSPrivacyCollectedDataTypes ?? [] + check('PrivacyInfo: collected data types declared', collected.length > 0) + check( + 'PrivacyInfo: no collected type is used for tracking', + collected.every((type) => type.NSPrivacyCollectedDataTypeTracking === false) + ) + const reasons = (manifest.NSPrivacyAccessedAPITypes ?? []).flatMap( + (api) => api.NSPrivacyAccessedAPITypeReasons ?? [] + ) + check('PrivacyInfo: UserDefaults reason CA92.1', reasons.includes('CA92.1')) + check('PrivacyInfo: file timestamp reason C617.1', reasons.includes('C617.1')) +} + +/** The build settings of every XCBuildConfiguration, with whether it belongs to the App target. */ +function buildConfigurations(pbxproj) { + return [ + ...pbxproj.matchAll( + /\/\* (\w+) \*\/ = \{\s*isa = XCBuildConfiguration;[\s\S]*?buildSettings = \{([\s\S]*?)\n\t\t\t\};/g + ), + ].map(([, name, body]) => ({ name, body, target: body.includes('INFOPLIST_FILE') })) +} +const setting = (body, key) => + body.match(new RegExp(`^\\s*"?${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}"? = ("?)(.*?)\\1;$`, 'm'))?.[2] + +function checkXcodeProject() { + const pbxproj = read(`${IOS}/App.xcodeproj/project.pbxproj`) + const configs = buildConfigurations(pbxproj) + check('project.pbxproj: four build configurations found', configs.length === 4, String(configs.length)) + const targets = [...pbxproj.matchAll(/IPHONEOS_DEPLOYMENT_TARGET = ([\d.]+);/g)].map((match) => match[1]) + check( + 'project.pbxproj: IPHONEOS_DEPLOYMENT_TARGET is 16.4 everywhere', + targets.length > 0 && targets.every((value) => value === '16.4'), + targets.join(', ') + ) + const families = [...pbxproj.matchAll(/TARGETED_DEVICE_FAMILY = ("?)([^";]*)\1;/g)].map((match) => match[2]) + check( + 'project.pbxproj: TARGETED_DEVICE_FAMILY is 1 (iPhone only)', + families.length > 0 && families.every((value) => value === '1'), + families.join(', ') + ) + + const debug = configs.find((config) => config.target && config.name === 'Debug') + const release = configs.find((config) => config.target && config.name === 'Release') + check( + 'App Debug uses App.entitlements', + setting(debug?.body ?? '', 'CODE_SIGN_ENTITLEMENTS') === 'App/App.entitlements' + ) + check( + 'App Release uses AppRelease.entitlements', + setting(release?.body ?? '', 'CODE_SIGN_ENTITLEMENTS') === 'App/AppRelease.entitlements' + ) + // Signing lives in the Release config only; on the xcodebuild command line it leaks onto the + // Swift packages and breaks the archive (peanut-ui pitfall 9). + check('App Release signs manually', setting(release?.body ?? '', 'CODE_SIGN_STYLE') === 'Manual') + check('App Release names a Team ID', /^[A-Z0-9]{10}$/.test(setting(release?.body ?? '', 'DEVELOPMENT_TEAM') ?? '')) + check( + 'App Release names the provisioning profile', + setting(release?.body ?? '', 'PROVISIONING_PROFILE_SPECIFIER') === 'Peanut Split App Store' + ) + + const resources = pbxproj.match(/isa = PBXResourcesBuildPhase;[\s\S]*?files = \(([\s\S]*?)\);/)?.[1] ?? '' + check( + 'PrivacyInfo.xcprivacy is in the App target resources', + resources.includes('PrivacyInfo.xcprivacy in Resources') + ) + check( + 'PrivacyInfo.xcprivacy has a file reference', + /isa = PBXFileReference;[^}]*path = PrivacyInfo\.xcprivacy;/.test(pbxproj) + ) +} + +function checkAppDelegate() { + // Comments do not count: the plugin needs the two posts in code. + const code = read(`${IOS}/App/AppDelegate.swift`).replace(/\/\/.*$/gm, '') + for (const name of [ + 'capacitorDidRegisterForRemoteNotifications', + 'capacitorDidFailToRegisterForRemoteNotifications', + ]) { + check( + `AppDelegate.swift posts .${name}`, + new RegExp(`NotificationCenter\\.default\\.post\\(name: \\.${name}\\b`).test(code) + ) + } +} + +function checkIcons() { + for (const file of ['resources/icon.png', `${IOS}/App/Assets.xcassets/AppIcon.appiconset/AppIcon-512@2x.png`]) { + const full = path.join(root, file) + check( + `${file} has no alpha channel`, + existsSync(full) && !pngHasAlpha(full), + existsSync(full) ? 'alpha found' : 'missing' + ) + } +} + +// --- Android ------------------------------------------------------------------------------------- + +function checkAndroid() { + const manifest = read('android/app/src/main/AndroidManifest.xml') + // The OS backup is the only way a person's room list reaches a new phone (INTERACTION 2.7). + check('AndroidManifest: android:allowBackup="true"', /]*android:allowBackup="true"/.test(manifest)) + check( + 'AndroidManifest: AD_ID removed', + /android:name="com\.google\.android\.gms\.permission\.AD_ID"\s+tools:node="remove"/.test(manifest) + ) + check('AndroidManifest: MainActivity is singleTask', /android:launchMode="singleTask"/.test(manifest)) + check( + 'AndroidManifest: verified App Link for https://peanutsplit.com/r/', + /[\s\S]*?/.test( + manifest + ) + ) + const variables = read('android/variables.gradle') + for (const [key, value] of [ + ['minSdkVersion', 24], + ['compileSdkVersion', 36], + ['targetSdkVersion', 36], + ]) { + check(`variables.gradle: ${key} = ${value}`, new RegExp(`${key} = ${value}\\b`).test(variables)) + } + for (const density of ['mdpi', 'hdpi', 'xhdpi', 'xxhdpi', 'xxxhdpi']) { + const file = `android/app/src/main/res/drawable-${density}/ic_stat_split.png` + check(`${file} exists`, existsSync(path.join(root, file))) + } +} + +// --- --app: the bundle Xcode built --------------------------------------------------------------- + +async function checkBuiltApp(bundle) { + const config = await loadCapacitorConfig() + const plist = readPlist(path.join(bundle, 'Info.plist')) + check( + 'built Info.plist: bundle ID matches capacitor.config.ts', + plist.CFBundleIdentifier === config.appId, + plist.CFBundleIdentifier + ) + check( + "built Info.plist: CFBundleDisplayName is 'Split'", + plist.CFBundleDisplayName === 'Split', + plist.CFBundleDisplayName + ) + check('built Info.plist: ITSAppUsesNonExemptEncryption is false', plist.ITSAppUsesNonExemptEncryption === false) + check('built Info.plist: NSCameraUsageDescription', plist.NSCameraUsageDescription === CAMERA_TEXT) + check( + 'built Info.plist: NSPhotoLibraryAddUsageDescription', + plist.NSPhotoLibraryAddUsageDescription === PHOTO_ADD_TEXT, + plist.NSPhotoLibraryAddUsageDescription + ) + check('built Info.plist: MinimumOSVersion is 16.4', plist.MinimumOSVersion === '16.4', plist.MinimumOSVersion) + check( + 'built Info.plist: iPhone only', + JSON.stringify(plist.UIDeviceFamily) === '[1]', + JSON.stringify(plist.UIDeviceFamily) + ) + check( + 'built Info.plist: portrait only', + JSON.stringify(plist.UISupportedInterfaceOrientations) === JSON.stringify(PORTRAIT) + ) + for (const key of ['CFBundleShortVersionString', 'CFBundleVersion']) { + check( + `built Info.plist: ${key} is resolved`, + typeof plist[key] === 'string' && plist[key] !== '' && !plist[key].includes('$('), + plist[key] + ) + } + check('built app contains PrivacyInfo.xcprivacy', existsSync(path.join(bundle, 'PrivacyInfo.xcprivacy'))) + check('built app contains the web bundle', existsSync(path.join(bundle, 'public/index.html'))) +} + +if (appBundle) { + await checkBuiltApp(path.resolve(appBundle)) +} else { + await checkCapacitorConfig() + checkInfoPlist() + checkEntitlements('App/App.entitlements', 'development') + checkEntitlements('App/AppRelease.entitlements', 'production') + checkPrivacyManifest() + checkXcodeProject() + checkAppDelegate() + checkIcons() + checkAndroid() +} + +if (failures.length > 0) { + console.error(`\n${failures.length} native config check(s) failed.`) + process.exit(1) +} +console.log('\nNative config OK.') diff --git a/apps/web/scripts/native/check-association.mjs b/apps/web/scripts/native/check-association.mjs new file mode 100644 index 00000000..5f8aa14c --- /dev/null +++ b/apps/web/scripts/native/check-association.mjs @@ -0,0 +1,39 @@ +#!/usr/bin/env node +/** + * Checks the two app-association files against a running server. + * Usage: node scripts/native/check-association.mjs [origin] (default http://localhost:3100) + * + * iOS fetches the apple-app-site-association file and Android the assetlinks.json file to decide + * whether `/r/` links open the app. Both refuse a redirect, and iOS refuses a body it cannot parse, + * so each file must answer 200, application/json, with no redirect and valid JSON. A failure here + * means room links open the browser instead of the app, with no error anywhere. + */ + +const origin = (process.argv[2] ?? 'http://localhost:3100').replace(/\/$/, '') +const FILES = ['/.well-known/apple-app-site-association', '/.well-known/assetlinks.json'] + +let failed = false +for (const path of FILES) { + const url = origin + path + const problems = [] + try { + const response = await fetch(url, { redirect: 'manual' }) + if (response.status !== 200) problems.push(`status ${response.status}, expected 200 with no redirect`) + const type = response.headers.get('content-type') ?? '' + if (!/^application\/json(?:;|$)/i.test(type)) problems.push(`content-type "${type}", expected application/json`) + try { + JSON.parse(await response.text()) + } catch { + problems.push('the body is not valid JSON') + } + } catch (error) { + problems.push(`request failed: ${error instanceof Error ? error.message : String(error)}`) + } + if (problems.length > 0) { + failed = true + for (const problem of problems) console.error(`FAIL ${url}: ${problem}`) + } else { + console.log(`ok ${url}`) + } +} +process.exit(failed ? 1 : 0) diff --git a/apps/web/scripts/native/check-review-readiness.mjs b/apps/web/scripts/native/check-review-readiness.mjs new file mode 100644 index 00000000..a089a976 --- /dev/null +++ b/apps/web/scripts/native/check-review-readiness.mjs @@ -0,0 +1,120 @@ +#!/usr/bin/env node +/** + * Checks that production is ready for store review of the apps (PLAN 8.2 K5, ARCHITECTURE 14.4). + * + * node scripts/native/check-review-readiness.mjs [room-slug] + * + * Each check prints one line and the script exits 1 when any check fails. It sends only read + * requests (OPTIONS and GET) to https://peanutsplit.com. The release workflow runs it as a + * warning; before submitting, a human runs it and every line must say ok. + * + * - CORS: the app's origins get a preflight answer, or every API call from the app fails. + * - apple-app-site-association: iOS opens room links in the app only when this file answers + * 200 application/json with no redirect and names the app as TEAMID.bundleID. + * - assetlinks.json: Android verifies App Links against the signing key fingerprints. The repo + * ships a placeholder until the Play App Signing key exists (HANDOFF step 9). + * - Receipt scan: the reviewer must see the scan button. The answer of the receipt-parse GET is + * the same for every room, so any valid slug works; the default is the test slug. + */ + +import { readFileSync } from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' + +const ORIGIN = 'https://peanutsplit.com' +const APP_ORIGINS = ['capacitor://localhost', 'https://localhost'] +const TIMEOUT_MS = 15_000 +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..') +const slug = process.argv[2] ?? 'ski-trip-kunc-syrup-drum' + +/** The bundle ID and the Release team, read from the same files set-identifiers.mjs edits. */ +function appIdentity() { + const appId = readFileSync(path.join(root, 'capacitor.config.ts'), 'utf8').match(/appId: '([^']+)'/)?.[1] + const releaseConfig = readFileSync(path.join(root, 'ios/App/App.xcodeproj/project.pbxproj'), 'utf8').match( + /\/\* Release \*\/ = \{\s*isa = XCBuildConfiguration;\s*buildSettings = \{[^}]*?INFOPLIST_FILE[^}]*?\};/ + )?.[0] + const team = releaseConfig?.match(/DEVELOPMENT_TEAM = (\w+);/)?.[1] + if (!appId) throw new Error('could not read appId from capacitor.config.ts') + if (!team) throw new Error('could not read DEVELOPMENT_TEAM from the App Release configuration') + return { appId, team } +} + +const request = (url, init = {}) => fetch(url, { redirect: 'manual', signal: AbortSignal.timeout(TIMEOUT_MS), ...init }) + +/** Reads a JSON body that must come back 200, application/json and without a redirect. */ +async function getJson(url) { + const response = await request(url) + if (response.status !== 200) throw new Error(`status ${response.status}, expected 200 with no redirect`) + const type = response.headers.get('content-type') ?? '' + if (!/^application\/json(?:;|$)/i.test(type)) throw new Error(`content-type "${type}", expected application/json`) + const text = await response.text() + try { + return { text, body: JSON.parse(text) } + } catch { + throw new Error('the body is not valid JSON') + } +} + +const checks = [ + ...APP_ORIGINS.map((appOrigin) => ({ + name: `CORS preflight from ${appOrigin}`, + async run() { + const response = await request(`${ORIGIN}/api/currencies`, { + method: 'OPTIONS', + headers: { Origin: appOrigin, 'Access-Control-Request-Method': 'GET' }, + }) + const allowed = response.headers.get('access-control-allow-origin') + if (response.status !== 204) throw new Error(`status ${response.status}, expected 204`) + if (allowed !== appOrigin) throw new Error(`Access-Control-Allow-Origin is "${allowed ?? ''}"`) + return '204 with a matching Access-Control-Allow-Origin' + }, + })), + { + name: 'apple-app-site-association', + async run() { + const { appId, team } = appIdentity() + const { text, body } = await getJson(`${ORIGIN}/.well-known/apple-app-site-association`) + if (text.includes('TEAMID')) throw new Error('the file still contains the TEAMID placeholder') + const appIds = (body?.applinks?.details ?? []).flatMap((detail) => detail?.appIDs ?? []) + const expected = `${team}.${appId}` + if (!appIds.includes(expected)) + throw new Error(`appIDs ${JSON.stringify(appIds)} do not include ${expected}`) + return `200 application/json, names ${expected}` + }, + }, + { + name: 'assetlinks.json', + async run() { + const { appId } = appIdentity() + const { body } = await getJson(`${ORIGIN}/.well-known/assetlinks.json`) + const entry = (Array.isArray(body) ? body : []).find((item) => item?.target?.package_name === appId) + if (!entry) throw new Error(`no entry for ${appId}`) + const fingerprints = entry.target.sha256_cert_fingerprints ?? [] + const real = fingerprints.filter((value) => /^([0-9A-F]{2}:){31}[0-9A-F]{2}$/.test(value)) + if (real.length !== fingerprints.length) + throw new Error('a fingerprint is still the placeholder or malformed') + if (real.length === 0) throw new Error('no SHA-256 fingerprint') + return `${real.length} SHA-256 fingerprint(s) for ${appId}` + }, + }, + { + name: 'receipt scan enabled', + async run() { + const { body } = await getJson(`${ORIGIN}/api/rooms/${encodeURIComponent(slug)}/receipt-parse`) + if (body?.enabled !== true) throw new Error(`answer is ${JSON.stringify(body)}, expected {"enabled":true}`) + return 'enabled: true' + }, + }, +] + +let failed = false +for (const check of checks) { + try { + console.log(`ok ${check.name}: ${await check.run()}`) + } catch (error) { + failed = true + const reason = error instanceof Error ? (error.cause?.message ?? error.message) : String(error) + console.log(`FAIL ${check.name}: ${reason}`) + } +} +process.exit(failed ? 1 : 0) diff --git a/apps/web/scripts/native/postbuild.mjs b/apps/web/scripts/native/postbuild.mjs new file mode 100644 index 00000000..3f948391 --- /dev/null +++ b/apps/web/scripts/native/postbuild.mjs @@ -0,0 +1,120 @@ +#!/usr/bin/env node +/** + * Prunes and checks the store-app export in .next-native/ (ARCHITECTURE 2.3). Runs after + * `next build` in `pnpm native:build`. Every failure exits non-zero with a one-line reason, so a + * broken export never reaches `cap sync`. + */ + +import { existsSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs' +import { dirname, join, relative } from 'node:path' +import { fileURLToPath } from 'node:url' + +const appRoot = join(dirname(fileURLToPath(import.meta.url)), '..', '..') +const outDir = join(appRoot, '.next-native') +const MAX_BYTES = 15 * 1024 * 1024 + +function fail(reason) { + console.error(`native postbuild: ${reason}`) + process.exit(1) +} + +function filesBelow(directory) { + return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { + const target = join(directory, entry.name) + return entry.isDirectory() ? filesBelow(target) : [target] + }) +} + +if (!existsSync(join(outDir, 'index.html'))) fail('.next-native/index.html is missing; did next build export?') + +// 1. Prune what public/ copied in (or Next always writes) that the app never loads. Capacitor +// never serves 404/ or _not-found/: an unknown path gets the root index.html. +const pruned = [ + 'press', + 'dev', + 'icons/splash', + 'install', + 'og-default.png', + 'sw.js', + 'sw.js.map', + '.well-known', + 'app-config.json', + '404', + '_not-found', +] +for (const path of pruned) rmSync(join(outDir, path), { recursive: true, force: true }) +for (const name of readdirSync(outDir)) { + const generated = /^opengraph-image/.test(name) || /^swe-worker.*\.js$/.test(name) + // Search-engine ownership files: Google's verification page and the IndexNow key. + const siteVerification = /^google[0-9a-f]+\.(html|txt)$/.test(name) || /^[0-9a-f]{32}\.txt$/.test(name) + if (generated || siteVerification) rmSync(join(outDir, name), { recursive: true, force: true }) +} + +const files = filesBelow(outDir) +const rel = (file) => relative(outDir, file).replaceAll('\\', '/') + +// 2. Exactly the native routes. An extra page means a web page leaked into the binary. +const expectedHtml = [ + '404.html', + 'app/index.html', + 'import/index.html', + 'index.html', + 'new/index.html', + 'room/import/index.html', + 'room/index.html', +] +const html = files + .map(rel) + .filter((path) => path.endsWith('.html')) + .sort() +if (JSON.stringify(html) !== JSON.stringify(expectedHtml)) { + fail(`HTML route set is [${html.join(', ')}], expected [${expectedHtml.join(', ')}]`) +} + +// 3. Web-only machinery that must not ship in the app. +for (const path of ['cache', 'server', 'sw.js', 'manifest.webmanifest']) { + if (existsSync(join(outDir, path))) fail(`${path} must not be in the export`) +} +const forbidden = [ + '/split-static/', + 'serviceWorker.register', + 'googletagmanager', + 'googleadservices', + 'static.ads-twitter.com', +] +const code = files.filter((file) => /\.(js|html)$/.test(file)) +const sources = new Map(code.map((file) => [file, readFileSync(file, 'utf8')])) +for (const [file, source] of sources) { + const hit = forbidden.find((needle) => source.includes(needle)) + if (hit) fail(`${rel(file)} contains forbidden string "${hit}"`) +} + +// 4. The API origin is baked in. Read the value this build inlined; never assume a fallback +// (peanut-ui shipped an unbaked env for months). +const chunks = [...sources].filter(([file]) => file.endsWith('.js')) +const containedInChunk = (value) => chunks.some(([, source]) => source.includes(value)) +const baseUrl = process.env.NEXT_PUBLIC_BASE_URL +if (!baseUrl) fail('NEXT_PUBLIC_BASE_URL is not set; run through `pnpm native:build`') +if (!containedInChunk(baseUrl)) fail(`API origin ${baseUrl} is not in any JS chunk`) + +// 5. Sentry reports from the app only when the DSN was baked in. +const dsn = process.env.NEXT_PUBLIC_SENTRY_DSN +if (dsn && !containedInChunk(dsn)) fail('NEXT_PUBLIC_SENTRY_DSN is set but not in any JS chunk') + +// 6. Size. +const total = files.reduce((sum, file) => sum + statSync(file).size, 0) +const megabytes = (total / 1024 / 1024).toFixed(2) +if (total > MAX_BYTES) fail(`export is ${megabytes} MB, above the 15 MB cap`) + +// 7. Next always builds an `output: 'export'` app inside .next and only copies the export to +// .next-native, so .next now holds this app build in place of any web build. Clear it (keeping +// .next/cache so the next web build stays fast): a later `next start`, standalone copy or +// `.next/static` check then fails loudly instead of using the app build. +const buildDir = join(appRoot, '.next') +if (existsSync(buildDir)) { + for (const name of readdirSync(buildDir)) { + if (name !== 'cache') rmSync(join(buildDir, name), { recursive: true, force: true }) + } +} + +console.log(`native postbuild: ok, ${html.length} pages, ${files.length} files, total ${megabytes} MB`) diff --git a/apps/web/scripts/native/render-export-options.mjs b/apps/web/scripts/native/render-export-options.mjs new file mode 100644 index 00000000..64269016 --- /dev/null +++ b/apps/web/scripts/native/render-export-options.mjs @@ -0,0 +1,79 @@ +#!/usr/bin/env node +/** + * Writes the ExportOptions.plist that `xcodebuild -exportArchive` uses in native-release.yml. + * + * EXPORT_OPTIONS_PATH= APPLE_TEAM_ID= PROFILE_NAME= node scripts/native/render-export-options.mjs + * + * App Store Connect distribution with manual signing: the archive is already signed by the + * Release configuration in project.pbxproj, and the export re-signs with the same profile. + * The bundle ID comes from capacitor.config.ts, so set-identifiers.mjs needs no edit here. + * Build numbers come from the archive (scripts/native/version-code.mjs), never from Xcode. + */ + +import { readFileSync, writeFileSync } from 'node:fs' +import path from 'node:path' +import { fileURLToPath, pathToFileURL } from 'node:url' + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..') + +const escapeXml = (value) => + value.replace( + /[&<>"']/g, + (character) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[character] + ) + +export function renderExportOptions({ appId, teamId, profileName }) { + if (!/^[A-Z0-9]{10}$/.test(teamId)) throw new Error('APPLE_TEAM_ID must be a 10-character Apple Team ID') + if (!appId) throw new Error('the bundle ID is empty') + if (!profileName) throw new Error('the provisioning profile name is empty') + return ` + + + + method + app-store-connect + destination + export + teamID + ${escapeXml(teamId)} + signingStyle + manual + provisioningProfiles + + ${escapeXml(appId)} + ${escapeXml(profileName)} + + manageAppVersionAndBuildNumber + + uploadSymbols + + + +` +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const required = (name) => { + const value = process.env[name] + if (!value) { + console.error(`render-export-options: ${name} is required`) + process.exit(1) + } + return value + } + const outputPath = required('EXPORT_OPTIONS_PATH') + const appId = readFileSync(path.join(root, 'capacitor.config.ts'), 'utf8').match(/appId: '([^']+)'/)?.[1] ?? '' + try { + const plist = renderExportOptions({ + appId, + teamId: required('APPLE_TEAM_ID'), + profileName: required('PROFILE_NAME'), + }) + // `wx` never follows or overwrites a file that is already there. + writeFileSync(outputPath, plist, { flag: 'wx', mode: 0o600 }) + } catch (error) { + console.error(`render-export-options: ${error instanceof Error ? error.message : String(error)}`) + process.exit(1) + } + console.log(`render-export-options: wrote ${outputPath} for ${appId}`) +} diff --git a/apps/web/scripts/native/seed-review-room.mjs b/apps/web/scripts/native/seed-review-room.mjs new file mode 100644 index 00000000..e9393384 --- /dev/null +++ b/apps/web/scripts/native/seed-review-room.mjs @@ -0,0 +1,142 @@ +#!/usr/bin/env node +/** + * Creates the room that App Store and Google Play reviewers open (docs/NATIVE-HANDOFF.md, step K2). + * + * node apps/web/scripts/native/seed-review-room.mjs # https://peanutsplit.com + * node apps/web/scripts/native/seed-review-room.mjs # another deployment + * node apps/web/scripts/native/seed-review-room.mjs --dry-run # print the plan, send nothing + * + * It uses only the public API, as the app does: one room create, then one expense create per row + * below, attributed to the creator through X-Member-Token. Generic first names, no real people. + * + * Against production this is a write, so only a person runs it, never CI. Keep the printed link out + * of the repository: the room link is the room's credential, and it belongs only in the App Review + * notes and the Play Console "App access" field. + */ + +import { randomUUID } from 'node:crypto' + +const DEFAULT_BASE_URL = 'https://peanutsplit.com' + +const ROOM = { + name: 'Lisbon weekend', + currency: 'EUR', + creatorName: 'Maya', + memberNames: ['Leo', 'Sam', 'Nora'], +} + +/** Amounts are minor units (cents). `among` omitted = everyone in the room, split equally. */ +const EXPENSES = [ + { description: 'Dinner at the harbour', amountMinor: '9640', paidBy: 'Maya' }, + { description: 'Groceries', amountMinor: '5430', paidBy: 'Leo' }, + { description: 'Tram day passes', amountMinor: '2560', paidBy: 'Sam' }, + { description: 'Museum tickets', amountMinor: '4500', paidBy: 'Nora', among: ['Maya', 'Leo', 'Nora'] }, + { description: 'Pastries and coffee', amountMinor: '1880', paidBy: 'Maya' }, +] + +function parseArgs(argv) { + const args = argv.slice(2) + const dryRun = args.includes('--dry-run') + const positional = args.filter((arg) => !arg.startsWith('--')) + const unknown = args.filter((arg) => arg.startsWith('--') && arg !== '--dry-run') + if (unknown.length > 0 || positional.length > 1) { + throw new Error( + `Usage: seed-review-room.mjs [base-url] [--dry-run] (unknown: ${[...unknown, ...positional.slice(1)].join(' ')})` + ) + } + const baseUrl = new URL(positional[0] ?? DEFAULT_BASE_URL) + if (baseUrl.protocol !== 'https:' && baseUrl.hostname !== 'localhost' && baseUrl.hostname !== '127.0.0.1') { + throw new Error(`Refusing ${baseUrl.origin}: use https, or localhost for a local server.`) + } + return { baseUrl: baseUrl.origin, dryRun } +} + +function formatEuro(amountMinor) { + return `EUR ${(Number(amountMinor) / 100).toFixed(2)}` +} + +function printPlan(baseUrl) { + console.log(`Target: ${baseUrl}`) + console.log(`Room: "${ROOM.name}" in ${ROOM.currency}, created by ${ROOM.creatorName}`) + console.log(`Members: ${[ROOM.creatorName, ...ROOM.memberNames].join(', ')}`) + for (const expense of EXPENSES) { + const among = expense.among ? expense.among.join(', ') : 'everyone' + console.log( + `Expense: ${expense.description}, ${formatEuro(expense.amountMinor)}, paid by ${expense.paidBy}, split among ${among}` + ) + } +} + +async function call(baseUrl, path, init) { + const response = await fetch(`${baseUrl}${path}`, { + ...init, + // The room remembers the language it was created in for its link preview. + headers: { 'Content-Type': 'application/json', 'Accept-Language': 'en', ...init?.headers }, + }) + const text = await response.text() + if (!response.ok) { + // The error body names the code and field; it never echoes a member token. + throw new Error( + `${init?.method ?? 'GET'} ${path.replace(/\/api\/rooms\/[^/]+/, '/api/rooms/')} -> ${response.status} ${text.slice(0, 300)}` + ) + } + return text ? JSON.parse(text) : null +} + +async function seed(baseUrl) { + const created = await call(baseUrl, '/api/rooms', { method: 'POST', body: JSON.stringify(ROOM) }) + const slug = created.room.slug + const memberIdByName = new Map(created.members.map((member) => [member.name, member.id])) + const memberId = (name) => { + const id = memberIdByName.get(name) + if (!id) throw new Error(`The created room has no member named ${name}.`) + return id + } + + for (const expense of EXPENSES) { + await call(baseUrl, `/api/rooms/${encodeURIComponent(slug)}/expenses`, { + method: 'POST', + headers: { 'X-Member-Token': created.memberToken }, + body: JSON.stringify({ + // One key per expense makes a retried request a no-op on the server. + clientKey: randomUUID(), + description: expense.description, + amountMinor: expense.amountMinor, + currency: ROOM.currency, + paidById: memberId(expense.paidBy), + splitMode: 'EQUAL', + ...(expense.among ? { participantIds: expense.among.map(memberId) } : {}), + }), + }) + } + + // Reviewers are told receipt scan works; this shows whether the deployment has it on. + const scan = await call(baseUrl, `/api/rooms/${encodeURIComponent(slug)}/receipt-parse`).catch(() => null) + + console.log('') + console.log(`Room link: ${baseUrl}/r/${slug}`) + console.log(`Slug: ${slug}`) + console.log(`Receipt scan enabled: ${scan?.enabled === true ? 'yes' : 'NO (check before submitting)'}`) + console.log('Paste the link only into the App Review notes and the Play Console App access field.') +} + +async function main() { + if (process.env.CI) { + console.error('seed-review-room.mjs writes a real room; it never runs in CI.') + process.exit(1) + } + const { baseUrl, dryRun } = parseArgs(process.argv) + printPlan(baseUrl) + if (dryRun) { + console.log('') + console.log('Dry run: no request sent.') + return + } + console.log('') + await seed(baseUrl) +} + +main().catch((error) => { + console.error(error instanceof Error ? error.message : error) + process.exit(1) +}) diff --git a/apps/web/scripts/native/serve-export.mjs b/apps/web/scripts/native/serve-export.mjs new file mode 100644 index 00000000..88fa3f8f --- /dev/null +++ b/apps/web/scripts/native/serve-export.mjs @@ -0,0 +1,46 @@ +#!/usr/bin/env node +/** + * Serves the store-app export the way Capacitor does, for local and CI cold-start checks. + * Usage: node scripts/native/serve-export.mjs + * + * Capacitor's rule (iOS Router.swift, Android WebViewLocalServer.java:399): a path whose last + * segment contains a dot is that file or a 404; every other path gets the ROOT index.html. A + * folder's own index.html is never served. The boot-path script in layout.native.tsx depends on + * this, so a plain static server would hide the bugs this one exists to show. + */ + +import { readFile } from 'node:fs/promises' +import { createServer } from 'node:http' +import { extname, join, normalize, resolve } from 'node:path' + +const [dirArg, portArg] = process.argv.slice(2) +if (!dirArg || !portArg) { + console.error('usage: serve-export.mjs ') + process.exit(1) +} +const root = resolve(dirArg) +const TYPES = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.css': 'text/css; charset=utf-8', + '.json': 'application/json', + '.png': 'image/png', + '.svg': 'image/svg+xml', + '.ico': 'image/x-icon', + '.woff2': 'font/woff2', + '.webp': 'image/webp', + '.txt': 'text/plain; charset=utf-8', +} + +createServer(async (request, response) => { + try { + const pathname = decodeURIComponent(new URL(request.url ?? '/', 'http://localhost').pathname) + const lastSegment = pathname.split('/').pop() ?? '' + const file = lastSegment.includes('.') ? normalize(join(root, pathname)) : join(root, 'index.html') + if (!file.startsWith(root)) throw new Error('outside the export') + const body = await readFile(file) + response.writeHead(200, { 'Content-Type': TYPES[extname(file)] ?? 'application/octet-stream' }).end(body) + } catch { + response.writeHead(404).end() + } +}).listen(Number(portArg), '127.0.0.1', () => console.log(`serving ${root} on http://localhost:${portArg}`)) diff --git a/apps/web/scripts/native/set-identifiers.mjs b/apps/web/scripts/native/set-identifiers.mjs new file mode 100644 index 00000000..2f75d8c1 --- /dev/null +++ b/apps/web/scripts/native/set-identifiers.mjs @@ -0,0 +1,103 @@ +#!/usr/bin/env node +/** + * Changes the app's bundle ID / package name and the Apple Team ID everywhere they are written, + * in one command (PLAN 4.5). Use it once, before the first signed build: the bundle ID can never + * change after release. + * + * node scripts/native/set-identifiers.mjs --app-id com.peanutsplit.app --team PW388G893L [--dry-run] + * + * The current values are read from capacitor.config.ts (appId) and the App target's Release + * configuration (DEVELOPMENT_TEAM). The Android `namespace` (the Java package of MainActivity) + * stays as it is: only the applicationId is the Play package name. + */ +import { readFileSync, writeFileSync } from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..') +const args = process.argv.slice(2) +const option = (name) => { + const index = args.indexOf(name) + return index === -1 ? null : args[index + 1] +} +const appId = option('--app-id') +const team = option('--team') +const dryRun = args.includes('--dry-run') + +function fail(message) { + console.error(message) + process.exit(1) +} + +// Android package names allow no hyphens; each segment starts with a letter. +if (!appId || !/^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)+$/.test(appId)) { + fail( + 'usage: set-identifiers.mjs --app-id --team [--dry-run]\n--app-id must look like com.example.app' + ) +} +if (!team || !/^[A-Z0-9]{10}$/.test(team)) fail('--team must be a 10-character Apple Team ID (A-Z, 0-9)') + +const FILES = { + config: 'capacitor.config.ts', + pbxproj: 'ios/App/App.xcodeproj/project.pbxproj', + gradle: 'android/app/build.gradle', + strings: 'android/app/src/main/res/values/strings.xml', + aasa: 'public/.well-known/apple-app-site-association', + assetlinks: 'public/.well-known/assetlinks.json', + appConfig: 'public/app-config.json', +} +const read = (file) => readFileSync(path.join(root, file), 'utf8') + +const currentAppId = read(FILES.config).match(/appId: '([^']+)'/)?.[1] +const releaseConfig = read(FILES.pbxproj).match( + /\/\* Release \*\/ = \{\s*isa = XCBuildConfiguration;\s*buildSettings = \{[^}]*?INFOPLIST_FILE[^}]*?\};/ +)?.[0] +const currentTeam = releaseConfig?.match(/DEVELOPMENT_TEAM = (\w+);/)?.[1] +if (!currentAppId) fail(`could not read appId from ${FILES.config}`) +if (!currentTeam) fail(`could not read DEVELOPMENT_TEAM from the App Release configuration in ${FILES.pbxproj}`) + +const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + +/** Each edit: a pattern that must match at least once, and what replaces each match. */ +const EDITS = { + [FILES.config]: [[new RegExp(`appId: '${escape(currentAppId)}'`, 'g'), `appId: '${appId}'`]], + [FILES.pbxproj]: [ + [ + new RegExp(`PRODUCT_BUNDLE_IDENTIFIER = ${escape(currentAppId)};`, 'g'), + `PRODUCT_BUNDLE_IDENTIFIER = ${appId};`, + ], + [new RegExp(`DEVELOPMENT_TEAM = ${escape(currentTeam)};`, 'g'), `DEVELOPMENT_TEAM = ${team};`], + ], + [FILES.gradle]: [[new RegExp(`applicationId "${escape(currentAppId)}"`, 'g'), `applicationId "${appId}"`]], + [FILES.strings]: [[new RegExp(`>${escape(currentAppId)}<`, 'g'), `>${appId}<`]], + [FILES.aasa]: [[new RegExp(`"${escape(currentTeam)}\\.${escape(currentAppId)}"`, 'g'), `"${team}.${appId}"`]], + [FILES.assetlinks]: [[new RegExp(`"package_name": "${escape(currentAppId)}"`, 'g'), `"package_name": "${appId}"`]], + [FILES.appConfig]: [[new RegExp(`details\\?id=${escape(currentAppId)}"`, 'g'), `details?id=${appId}"`]], +} + +const changes = [] +for (const [file, edits] of Object.entries(EDITS)) { + let text = read(file) + const before = text + for (const [pattern, replacement] of edits) { + const count = text.match(pattern)?.length ?? 0 + if (count === 0) fail(`${file}: expected ${pattern} and found none; nothing was written`) + text = text.replace(pattern, replacement) + changes.push(`${file}: ${count} x ${pattern.source.replace(/\\/g, '')} -> ${replacement}`) + } + if (text !== before) EDITS[file].result = text +} + +console.log(`${dryRun ? 'Would change' : 'Changing'} ${currentAppId} -> ${appId}, team ${currentTeam} -> ${team}:`) +for (const line of changes) console.log(` ${line}`) + +if (dryRun) { + console.log('Dry run: no file written.') +} else { + for (const [file, edits] of Object.entries(EDITS)) { + if (edits.result !== undefined) writeFileSync(path.join(root, file), edits.result) + } + console.log( + 'Done. Also update SPLIT_APNS_BUNDLE_ID and SPLIT_APNS_TEAM_ID on the server, and the App Store and Play records.' + ) +} diff --git a/apps/web/scripts/native/version-code.mjs b/apps/web/scripts/native/version-code.mjs new file mode 100644 index 00000000..46b4e778 --- /dev/null +++ b/apps/web/scripts/native/version-code.mjs @@ -0,0 +1,21 @@ +#!/usr/bin/env node +/** + * Prints the native build number: whole minutes since 2026-01-01T00:00Z (ARCHITECTURE 11). + * + * iOS CURRENT_PROJECT_VERSION and Android versionCode use the same number, so one build is one + * number on both stores. It grows with every run and stays under Android's 2,100,000,000 limit + * for about 4,000 years. The version gate compares it with minBuild in public/app-config.json. + */ + +import { pathToFileURL } from 'node:url' + +const EPOCH_MS = Date.UTC(2026, 0, 1) + +/** Whole minutes between 2026-01-01T00:00Z and `now` (milliseconds since the Unix epoch). */ +export function versionCode(now = Date.now()) { + return Math.floor((now - EPOCH_MS) / 60_000) +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + console.log(versionCode()) +} diff --git a/apps/web/src/app/(native)/app/page.native.tsx b/apps/web/src/app/(native)/app/page.native.tsx new file mode 100644 index 00000000..0d1575dd --- /dev/null +++ b/apps/web/src/app/(native)/app/page.native.tsx @@ -0,0 +1,95 @@ +'use client' + +import Link from 'next/link' +import { useTranslations } from 'next-intl' +import { useSearchParams } from 'next/navigation' +import { Suspense } from 'react' +import { YourRooms } from '@/components/marketing/YourRooms' +import { RecentRoomAppEntry } from '@/components/pwa/RecentRoomAppEntry' +import { Doodle } from '@/components/ui/Doodle' +import { buttonClassName } from '@/components/ui/button-style' +import { productUrl } from '@/lib/site' + +/** + * The app's rooms home: a client copy of (product-shell)/app/page.tsx without the install + * surfaces (no install=1 branch, no CanonicalAppLaunchMarker) and without the landing link, whose + * marketing page is not in the binary. Same test ids. `manage=1` shows the list without the + * redirect to the recent room: the offline error, RoomSwitcher and leaving a room link here. + */ +function AppHome() { + const tCreate = useTranslations('room.create') + const tFooter = useTranslations('marketing.footer') + const tRooms = useTranslations('marketing.rooms') + const tHeader = useTranslations('room.header') + const tLegal = useTranslations('legal') + const searchParams = useSearchParams() + const addExpense = searchParams.get('add') === '1' + + const home = ( +
+
+

{tRooms('title')}

+
+ + + + + {tCreate('title')} + + + + {tFooter('importLink')} + + + } + /> + {/* Both stores require a privacy link in the app (no Terms link in v1). The external-link + handler opens it in the system browser. */} +

+ + {tLegal('privacy')} + +

+
+ ) + + return searchParams.get('manage') === '1' ? ( + home + ) : ( + {home} + ) +} + +export default function NativeAppHomePage() { + return ( + + + + ) +} diff --git a/apps/web/src/app/(native)/error.native.tsx b/apps/web/src/app/(native)/error.native.tsx new file mode 100644 index 00000000..7b718705 --- /dev/null +++ b/apps/web/src/app/(native)/error.native.tsx @@ -0,0 +1,3 @@ +'use client' + +export { default } from '../(product-shell)/error' diff --git a/apps/web/src/app/(native)/import/page.native.tsx b/apps/web/src/app/(native)/import/page.native.tsx new file mode 100644 index 00000000..fb466bff --- /dev/null +++ b/apps/web/src/app/(native)/import/page.native.tsx @@ -0,0 +1,12 @@ +'use client' + +import { SplitwiseImport } from '@/components/import/SplitwiseImport' + +/** The Splitwise import tool alone; the web page's marketing frame stays on the web. */ +export default function NativeImportPage() { + return ( +
+ +
+ ) +} diff --git a/apps/web/src/app/(native)/layout.native.tsx b/apps/web/src/app/(native)/layout.native.tsx new file mode 100644 index 00000000..a50db1f9 --- /dev/null +++ b/apps/web/src/app/(native)/layout.native.tsx @@ -0,0 +1,59 @@ +import { type Metadata, type Viewport } from 'next' +import { bodyFontClassName } from '@/lib/fonts' +import { NativeShell } from '@/lib/native/NativeShell' +import '../../styles/globals.css' +import '../../styles/desktop-frame.css' + +export const metadata: Metadata = { + title: 'Split', +} + +/** Same viewport as the product layout; `viewport-fit=cover` keeps the home-indicator insets. */ +export const viewport: Viewport = { + width: 'device-width', + initialScale: 1, + colorScheme: 'light', + viewportFit: 'cover', + themeColor: '#FFC900', +} + +/** Copied from the product layout: the in-app animation switch has to apply before React mounts. */ +const motionPreferencePreflight = ` +try { + var splitSettings = JSON.parse(localStorage.getItem('ps:settings') || '{}'); + if (splitSettings.animationsEnabled === false) { + document.documentElement.classList.add('reduce-animations'); + } +} catch (_) {} +` + +/** + * Capacitor serves this root index.html for every path without a dot (a cold start, a reload + * after a language switch, Android recreating the WebView). Save the real path for NativeEntry and + * reset the URL to `/`, so Next hydrates the root payload at the URL it was built for. + * ARCHITECTURE 4.3. + */ +const bootPathCapture = ` +window.__splitBootPath = location.pathname + location.search + location.hash; +if (location.pathname !== '/') history.replaceState(null, '', '/'); +` + +/** + * The app's only root layout, built into a static export. No PWA head tags, no service worker, no + * JSON-LD: the binary is the app, and the locale is chosen on the device (NativeIntlProvider). + */ +export default function NativeRootLayout({ children }: { children: React.ReactNode }) { + return ( + + + + {/* Literal parser-blocking scripts: both must run before the Next bootstrap. */} + ', + 'file:///etc/passwd', + `capacitor://localhost/r/${SLUG}`, + '//evil.example', + `//evil.example/r/${SLUG}`, + `/\\evil.example/r/${SLUG}`, + `/r/ski-trip%2Fkunc-syrup-drum`, + `/r/${SLUG}%2F..%2F..%2Fapp`, + `/r/%2F%2Fevil.example`, + '/r/%E0%A4%A', + '', + ' ', + `https://peanutsplit.com/r/${SLUG}?add=1&x=${'a'.repeat(2048)}`, + ]) { + expect(nativePathForUrl(input)).toBeNull() + } + }) + + it('handles a 2 KB input quickly', () => { + const started = performance.now() + expect(nativePathForUrl('/r/' + 'a'.repeat(2049))).toBeNull() + expect(nativePathForUrl('https://peanutsplit.com/' + '/'.repeat(2100))).toBeNull() + expect(performance.now() - started).toBeLessThan(50) + }) + + it('treats an encoded slash in a non-room path as an ordinary product page', () => { + // `/r%2F` is not a room path, so it can only ever open the web page of the same name. + expect(nativePathForUrl(`https://peanutsplit.com/r%2F${SLUG}`)).toEqual({ + external: `${siteUrl}/r%2F${SLUG}`, + }) + }) +}) + +describe('roomSlugOfNativePath', () => { + it('reads the slug of a room or room-import path only', async () => { + const { roomSlugOfNativePath } = await load() + expect(roomSlugOfNativePath(`/room/?slug=${SLUG}&add=1#x`)).toBe(SLUG) + expect(roomSlugOfNativePath(`/room/import/?slug=${SLUG}`)).toBe(SLUG) + expect(roomSlugOfNativePath('/app/')).toBeNull() + expect(roomSlugOfNativePath('/room/')).toBeNull() + expect(roomSlugOfNativePath('/room/?slug=not_a_slug')).toBeNull() + }) + + it('validates the slug a native room screen receives', async () => { + const { nativeRoomSlug } = await load() + expect(nativeRoomSlug(SLUG)).toBe(SLUG) + expect(nativeRoomSlug(TOKEN_SLUG)).toBe(TOKEN_SLUG) + for (const bad of [null, '', 'nope', `${SLUG}/import`, `../${SLUG}`, `${SLUG}?add=1`, 'a'.repeat(3000)]) { + expect(nativeRoomSlug(bad)).toBeNull() + } + }) +}) + +describe('dispatchNativeLink', () => { + const LINK = `https://peanutsplit.com/r/${SLUG}?add=1#x` + const ROOM = `/room/?slug=${SLUG}&add=1#x` + + beforeEach(() => { + vi.stubGlobal('sessionStorage', fakeSessionStorage()) + }) + afterEach(() => { + vi.unstubAllGlobals() + }) + + it('cold start: launch URL then the replayed appUrlOpen within 3 s navigates once, with a replace', async () => { + const { dispatchNativeLink } = await load() + const { nav, history } = fakeNav('/') + expect(dispatchNativeLink(LINK, 'launch', nav, 1_000)).toBe('navigated') + expect(dispatchNativeLink(LINK, 'open', nav, 2_500)).toBe('duplicate') + expect(history).toEqual([ROOM]) + }) + + it('cold start, reverse order: appUrlOpen first replaces from the root, the launch URL is a duplicate', async () => { + const { dispatchNativeLink } = await load() + const { nav, history } = fakeNav('/') + expect(dispatchNativeLink(LINK, 'open', nav, 1_000)).toBe('navigated') + expect(dispatchNativeLink(LINK, 'launch', nav, 1_200)).toBe('duplicate') + expect(history).toEqual([ROOM]) + }) + + it('the same link again after more than 3 s on a non-root screen is pushed', async () => { + const { dispatchNativeLink } = await load() + const { nav, history } = fakeNav('/') + dispatchNativeLink(LINK, 'launch', nav, 1_000) + nav.push('/app/') + expect(dispatchNativeLink(LINK, 'open', nav, 4_001)).toBe('navigated') + expect(history).toEqual([ROOM, '/app/', ROOM]) + }) + + it('a warm link from a screen is pushed, so back returns to that screen', async () => { + const { dispatchNativeLink } = await load() + const { nav, history } = fakeNav('/app/') + expect(dispatchNativeLink(LINK, 'open', nav, 1_000)).toBe('navigated') + expect(history).toEqual(['/app/', ROOM]) + }) + + it('a launch URL replaces even when the app is already on a screen', async () => { + const { dispatchNativeLink } = await load() + const { nav, history } = fakeNav('/app/') + expect(dispatchNativeLink(LINK, 'launch', nav, 1_000)).toBe('navigated') + expect(history).toEqual([ROOM]) + }) + + it('a launch URL that an earlier page load handled is replayed, not navigated', async () => { + const first = await load() + first.dispatchNativeLink(LINK, 'launch', fakeNav('/').nav, 1_000) + expect(sessionStorage.getItem(first.LAUNCH_HANDLED_KEY)).toBe(LINK) + + // A WebView reload: new module state, same sessionStorage, getLaunchUrl returns the old link. + const reloaded = await load() + const { nav, history } = fakeNav('/') + expect(reloaded.dispatchNativeLink(LINK, 'launch', nav, 60_000)).toBe('replayed') + expect(history).toEqual(['/']) + // The same link tapped again while the app runs is a new tap. + expect(reloaded.dispatchNativeLink(LINK, 'open', nav, 61_000)).toBe('navigated') + expect(history).toEqual([ROOM]) + }) + + it('only a launch writes the replay key', async () => { + const { dispatchNativeLink, LAUNCH_HANDLED_KEY } = await load() + dispatchNativeLink(LINK, 'open', fakeNav('/app/').nav, 1_000) + expect(sessionStorage.getItem(LAUNCH_HANDLED_KEY)).toBeNull() + }) + + it('ignores a link the app cannot map and does not remember it', async () => { + const { dispatchNativeLink } = await load() + const { nav, history, external } = fakeNav('/') + expect(dispatchNativeLink('https://evil.example/r/x', 'launch', nav, 1_000)).toBe('ignored') + expect(dispatchNativeLink('javascript:alert(1)', 'open', nav, 1_100)).toBe('ignored') + expect(history).toEqual(['/']) + expect(external).toEqual([]) + expect(sessionStorage.length).toBe(0) + }) + + it('opens a product page the app lacks in the system browser, and leaves the blank root for home', async () => { + const { dispatchNativeLink } = await load() + const { nav, history, external } = fakeNav('/') + expect(dispatchNativeLink('https://peanutsplit.com/privacy', 'launch', nav, 1_000)).toBe('navigated') + expect(dispatchNativeLink('https://peanutsplit.com/privacy', 'open', nav, 1_500)).toBe('duplicate') + expect(external).toEqual([`${siteUrl}/privacy`]) + expect(history).toEqual(['/app/']) + }) + + it('opens an external page from a screen without moving the app', async () => { + const { dispatchNativeLink } = await load() + const { nav, history, external } = fakeNav(`/room/?slug=${SLUG}`) + expect(dispatchNativeLink('https://peanutsplit.com/blog/x', 'open', nav, 1_000)).toBe('navigated') + expect(external).toEqual([`${siteUrl}/blog/x`]) + expect(history).toEqual([`/room/?slug=${SLUG}`]) + }) + + it('still works when sessionStorage throws', async () => { + vi.stubGlobal('sessionStorage', { + getItem: () => { + throw new Error('denied') + }, + setItem: () => { + throw new Error('denied') + }, + }) + const { dispatchNativeLink } = await load() + const { nav, history } = fakeNav('/') + expect(dispatchNativeLink(LINK, 'launch', nav, 1_000)).toBe('navigated') + expect(history).toEqual([ROOM]) + }) +}) diff --git a/apps/web/src/lib/native/links.ts b/apps/web/src/lib/native/links.ts new file mode 100644 index 00000000..75611755 --- /dev/null +++ b/apps/web/src/lib/native/links.ts @@ -0,0 +1,181 @@ +import { CANONICAL_ORIGIN, isProductHost } from '../domains' +import { roomSlugFromLink } from '../recent-rooms' +import { siteUrl } from '../site' + +/** Every route in the bundled app, as `src/app/(native)` exports them (trailing slash on). */ +export const NATIVE_ROUTES: readonly string[] = ['/', '/app/', '/new/', '/room/', '/room/import/', '/import/'] + +/** The navigation calls `dispatchNativeLink` needs, injected so the function stays pure. */ +export type NativeNav = { + currentPath(): string + replace(p: string): void + push(p: string): void + openExternal(u: string): void +} + +/** Room query keys the room screen reads (its nuqs drawers); anything else on a shared link is chat decoration. */ +const ROOM_QUERY_KEYS = ['add', 'expense', 'shared', 'manage', 'settings'] as const + +/** Real links are short. A longer input is refused before any parsing work. */ +const MAX_LINK_LENGTH = 2048 + +/** The shared room link's path prefix. */ +const ROOM_LINK_PREFIX = '/r/' + +/** `/r/` plus an optional tail such as `/import`, `/recap` or `/card/...`. */ +const ROOM_LINK_PATH = /^(\/r\/[^/]+)(\/.*)?$/ + +/** App screens that keep their own path; the value is the exported route. */ +const APP_SCREENS: Record = { + '/app': '/app/', + '/new': '/new/', + '/import': '/import/', +} + +const ROOM_SCREENS: Record = { + '/room': '/room/', + '/room/import': '/room/import/', +} + +function parse(input: string): URL | null { + const trimmed = input.trim() + if (!trimmed || trimmed.length > MAX_LINK_LENGTH) return null + try { + // A path resolves against the product origin. Anything URL-shaped (`//host`, `/\host`, + // `javascript:`) keeps its own host or scheme and is checked below like any other URL. + if (trimmed.startsWith('/')) return new URL(trimmed, CANONICAL_ORIGIN) + return new URL(/^[a-z][a-z0-9+.-]*:/i.test(trimmed) ? trimmed : `https://${trimmed}`) + } catch { + return null + } +} + +/** A room slug from a `/r/` prefix, validated by the same contract as pasted links. */ +function slugFromRoomPrefix(prefix: string): string | null { + return roomSlugFromLink(CANONICAL_ORIGIN + prefix, CANONICAL_ORIGIN) +} + +function roomTarget(base: '/room/' | '/room/import/', slug: string, url: URL): string { + const query = new URLSearchParams({ slug }) + for (const key of ROOM_QUERY_KEYS) { + const value = url.searchParams.get(key) + if (value !== null) query.set(key, value) + } + return `${base}?${query.toString()}${url.hash}` +} + +/** + * Maps a URL (a universal link, an App Link, a pasted link or a boot path) to an in-app path, an + * external URL for the system browser, or null when the app has nothing to show for it. + * ARCHITECTURE 4.4 is the table this follows. + * + * Only product hosts count. Room slugs pass the permanent `roomSlugFromLink` contract, so an + * invalid slug never reaches navigation. An external result is rebuilt from the parsed path on + * `siteUrl`, never echoed from the input. + */ +export function nativePathForUrl(input: string): { path: string } | { external: string } | null { + const url = parse(input) + if (!url) return null + if (url.protocol !== 'https:' && url.protocol !== 'http:') return null + if (url.username || url.password || !isProductHost(url.hostname)) return null + + const pathname = url.pathname + + const roomLink = pathname.match(ROOM_LINK_PATH) + if (roomLink) { + const slug = slugFromRoomPrefix(roomLink[1]) + if (!slug) return null + const tail = roomLink[2] ?? '' + const base = tail === '/import' || tail === '/import/' ? '/room/import/' : '/room/' + return { path: roomTarget(base, slug, url) } + } + + const trimmedPath = pathname.length > 1 && pathname.endsWith('/') ? pathname.slice(0, -1) : pathname + + const appScreen = APP_SCREENS[trimmedPath] + if (appScreen) return { path: `${appScreen}${url.search}${url.hash}` } + + const roomScreen = ROOM_SCREENS[trimmedPath] + if (roomScreen) { + return nativeRoomSlug(url.searchParams.get('slug')) ? { path: `${roomScreen}${url.search}${url.hash}` } : null + } + + return { external: `${siteUrl}${pathname}${url.search}${url.hash}` } +} + +/** The `?slug=` of a native room screen if it is a valid room slug, else null (the screen then goes home). */ +export function nativeRoomSlug(slugParam: string | null): string | null { + return slugParam ? slugFromRoomPrefix(ROOM_LINK_PREFIX + encodeURIComponent(slugParam)) : null +} + +/** The room slug an in-app path opens, or null for any other screen. Used for the opened event. */ +export function roomSlugOfNativePath(path: string): string | null { + const url = parse(path) + if (!url || !/^\/room\/(?:import\/)?$/.test(url.pathname)) return null + return nativeRoomSlug(url.searchParams.get('slug')) +} + +/** A link delivered twice within this window is one link (cold start: launch URL plus the replayed `appUrlOpen`). */ +export const DUPLICATE_WINDOW_MS = 3_000 +/** The launch URL an earlier page load of this WebView already handled; `getLaunchUrl` returns it after every reload. */ +export const LAUNCH_HANDLED_KEY = 'ps:native:launch-handled' + +// Shared by NativeEntry (source 'launch') and NativeLinks (source 'open'): the module lives as +// long as the page, and both callers must see the same last link. +let lastUrl: string | null = null +let lastAt = 0 + +function readLaunchHandled(): string | null { + try { + return globalThis.sessionStorage?.getItem(LAUNCH_HANDLED_KEY) ?? null + } catch { + return null + } +} + +function writeLaunchHandled(url: string): void { + try { + globalThis.sessionStorage?.setItem(LAUNCH_HANDLED_KEY, url) + } catch { + // Without sessionStorage a reload may replay the launch link once; the room is still right. + } +} + +/** + * The one handler for a link, whether it arrives as the launch URL or through `appUrlOpen`, so a + * cold start navigates exactly once. Rules in PLAN.md 4.1: + * + * 1. The same URL again within 3 s is a duplicate: no navigation. + * 2. A launch URL this WebView session already handled is a replay (a reload returns it again). + * 3. A URL the app cannot map is ignored. + * 4. A product page the app does not have opens in the system browser. When that happens on the + * native root `/`, the app also moves to `/app/`, so the person never returns to a blank root. + * 5. An in-app path replaces the current entry for the launch URL or from the root `/` (so `/` + * never stays in history under the room), else it is pushed (Android back returns). + */ +export function dispatchNativeLink( + url: string, + source: 'launch' | 'open', + nav: NativeNav, + now: number = Date.now() +): 'navigated' | 'duplicate' | 'replayed' | 'ignored' { + if (url === lastUrl && now - lastAt <= DUPLICATE_WINDOW_MS) return 'duplicate' + if (source === 'launch' && readLaunchHandled() === url) return 'replayed' + + const target = nativePathForUrl(url) + if (!target) return 'ignored' + + lastUrl = url + lastAt = now + if (source === 'launch') writeLaunchHandled(url) + + const fromRoot = nav.currentPath() === '/' + if ('external' in target) { + nav.openExternal(target.external) + if (fromRoot) nav.replace('/app/') + return 'navigated' + } + if (source === 'launch' || fromRoot) nav.replace(target.path) + else nav.push(target.path) + return 'navigated' +} diff --git a/apps/web/src/lib/native/native-entry.test.ts b/apps/web/src/lib/native/native-entry.test.ts new file mode 100644 index 00000000..5e560b55 --- /dev/null +++ b/apps/web/src/lib/native/native-entry.test.ts @@ -0,0 +1,206 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { NativeNav } from './links' + +const SLUG = 'ski-trip-kunc-syrup-drum' +const LINK = `https://peanutsplit.com/r/${SLUG}` +const ROOM = `/room/?slug=${SLUG}` +const OTHER_SLUG = 'beach-house-mint-tide-oak' + +/** + * Loads the store-app build of both modules: `roomPath` reads the build flag at import, and + * `dispatchNativeLink` keeps its last link in module state, so every test gets fresh copies. + */ +async function load() { + vi.resetModules() + vi.stubEnv('NEXT_PUBLIC_NATIVE_BUILD', '1') + const entry = await import('./native-entry') + const links = await import('./links') + return { ...entry, ...links } +} + +function fakeSessionStorage(): Pick { + const values = new Map() + return { getItem: (key) => values.get(key) ?? null, setItem: (key, value) => void values.set(key, value) } +} + +function fakeNav() { + const history = ['/'] + const external: string[] = [] + const nav: NativeNav = { + currentPath: () => new URL(history[history.length - 1], 'https://localhost').pathname, + replace: (p) => { + history[history.length - 1] = p + }, + push: (p) => { + history.push(p) + }, + openExternal: (u) => { + external.push(u) + }, + } + return { nav, history, external } +} + +/** Records which inputs decideEntry consulted, to prove the order. */ +function inputs( + nav: NativeNav, + { + bootPath = '/', + launchUrl = null, + tap = null, + }: { bootPath?: string; launchUrl?: string | null; tap?: { slug: string | null; sendId: string } | null } +) { + const consulted: string[] = [] + return { + consulted, + value: { + bootPath, + nav, + getLaunchUrl: async () => { + consulted.push('launch') + return launchUrl + }, + awaitColdPushTap: async () => { + consulted.push('push') + return tap + }, + }, + } +} + +describe('decideEntry', () => { + beforeEach(() => { + vi.stubGlobal('sessionStorage', fakeSessionStorage()) + }) + afterEach(() => { + vi.unstubAllGlobals() + vi.unstubAllEnvs() + }) + + it('restores a non-root boot path before anything else', async () => { + const { decideEntry } = await load() + const { nav, history } = fakeNav() + const run = inputs(nav, { + bootPath: `/room/?slug=${SLUG}&add=1#x`, + launchUrl: `https://peanutsplit.com/r/${OTHER_SLUG}`, + tap: { slug: OTHER_SLUG, sendId: 's1' }, + }) + expect(await decideEntry(run.value)).toEqual({ step: 'boot', path: `/room/?slug=${SLUG}&add=1#x` }) + expect(history).toEqual([`/room/?slug=${SLUG}&add=1#x`]) + expect(run.consulted).toEqual([]) + }) + + it('restores the rooms list with its query after a reload', async () => { + const { decideEntry } = await load() + const { nav, history } = fakeNav() + await decideEntry(inputs(nav, { bootPath: '/app/?manage=1' }).value) + expect(history).toEqual(['/app/?manage=1']) + }) + + it('sends an unknown or web-only boot path home and never opens a browser', async () => { + for (const bootPath of ['/nope', '/privacy', '/blog/x', '/r/not-a-slug', '/room/?slug=bad']) { + const { decideEntry } = await load() + const { nav, history, external } = fakeNav() + expect(await decideEntry(inputs(nav, { bootPath, launchUrl: LINK }).value)).toEqual({ + step: 'boot', + path: '/app/', + }) + expect(history).toEqual(['/app/']) + expect(external).toEqual([]) + } + }) + + it('opens the launch link before the push tap and home', async () => { + const { decideEntry } = await load() + const { nav, history } = fakeNav() + const run = inputs(nav, { launchUrl: LINK, tap: { slug: OTHER_SLUG, sendId: 's1' } }) + expect(await decideEntry(run.value)).toEqual({ step: 'launch', url: LINK, result: 'navigated' }) + expect(history).toEqual([ROOM]) + expect(run.consulted).toEqual(['launch']) + }) + + it('stops when the replayed appUrlOpen already navigated (reverse order), with no fall-through home', async () => { + const { decideEntry, dispatchNativeLink } = await load() + const { nav, history } = fakeNav() + // The appUrlOpen listener mounts in NativeShell and may take the retained event first. + expect(dispatchNativeLink(LINK, 'open', nav)).toBe('navigated') + const run = inputs(nav, { launchUrl: LINK }) + expect(await decideEntry(run.value)).toEqual({ step: 'launch', url: LINK, result: 'duplicate' }) + expect(history).toEqual([ROOM]) + expect(run.consulted).toEqual(['launch']) + }) + + it('makes one navigation when the launch URL comes first and appUrlOpen replays it', async () => { + const { decideEntry, dispatchNativeLink } = await load() + const { nav, history } = fakeNav() + await decideEntry(inputs(nav, { launchUrl: LINK }).value) + expect(dispatchNativeLink(LINK, 'open', nav)).toBe('duplicate') + expect(history).toEqual([ROOM]) + }) + + it('moves on to the push tap when the launch URL is a replay from an earlier page load', async () => { + const first = await load() + await first.decideEntry(inputs(fakeNav().nav, { launchUrl: LINK }).value) + + const reloaded = await load() + const { nav, history } = fakeNav() + const run = inputs(nav, { launchUrl: LINK, tap: { slug: OTHER_SLUG, sendId: 's2' } }) + expect(await reloaded.decideEntry(run.value)).toEqual({ step: 'push', slug: OTHER_SLUG, sendId: 's2' }) + expect(history).toEqual([`/room/?slug=${OTHER_SLUG}`]) + expect(run.consulted).toEqual(['launch', 'push']) + }) + + it('moves on to the push tap when the launch URL cannot be mapped', async () => { + const { decideEntry } = await load() + const { nav, history, external } = fakeNav() + const run = inputs(nav, { launchUrl: 'https://evil.example/x', tap: { slug: OTHER_SLUG, sendId: 's3' } }) + expect((await decideEntry(run.value)).step).toBe('push') + expect(history).toEqual([`/room/?slug=${OTHER_SLUG}`]) + expect(external).toEqual([]) + }) + + it('opens the rooms list, not the most recent room, for a push tap with an unknown room key', async () => { + const { decideEntry } = await load() + const { nav, history } = fakeNav() + const run = inputs(nav, { tap: { slug: null, sendId: 's4' } }) + expect(await decideEntry(run.value)).toEqual({ step: 'push', slug: null, sendId: 's4' }) + expect(history).toEqual(['/app/?manage=1']) + }) + + it('goes home when there is no boot path, no launch link and no push tap', async () => { + const { decideEntry } = await load() + const { nav, history } = fakeNav() + const run = inputs(nav, {}) + expect(await decideEntry(run.value)).toEqual({ step: 'home' }) + expect(history).toEqual(['/app/']) + expect(run.consulted).toEqual(['launch', 'push']) + }) + + it('treats an empty boot path like the root', async () => { + const { decideEntry } = await load() + const { nav, history } = fakeNav() + await decideEntry({ ...inputs(nav, {}).value, bootPath: undefined }) + expect(history).toEqual(['/app/']) + }) +}) + +describe('backAction (Android back)', () => { + it('leaves the app on the rooms home and the rooms list', async () => { + const { backAction } = await load() + expect(backAction('/', false)).toBe('minimize') + expect(backAction('/app/', false)).toBe('minimize') + expect(backAction('/app', true)).toBe('minimize') + }) + + it('walks back through in-app history from a room', async () => { + const { backAction } = await load() + expect(backAction('/room/', true)).toBe('history-back') + }) + + it('goes to the rooms list without the latest-room redirect when the room has no history', async () => { + const { backAction, NATIVE_ROOMS_LIST } = await load() + expect(backAction('/room/', false)).toEqual({ replace: '/app/?manage=1' }) + // The next back from there leaves the app instead of looping into the same room. + expect(backAction(new URL(NATIVE_ROOMS_LIST, 'https://localhost').pathname, false)).toBe('minimize') + }) +}) diff --git a/apps/web/src/lib/native/native-entry.ts b/apps/web/src/lib/native/native-entry.ts new file mode 100644 index 00000000..08646c3f --- /dev/null +++ b/apps/web/src/lib/native/native-entry.ts @@ -0,0 +1,81 @@ +import { roomPath } from '../platform' +import { dispatchNativeLink, nativePathForUrl, type NativeNav } from './links' + +/** The app's rooms home; RecentRoomAppEntry there moves a returning person to their latest room. */ +export const NATIVE_HOME = '/app/' + +/** The rooms list itself: `/app/` without the redirect to the latest room. */ +export const NATIVE_ROOMS_LIST = '/app/?manage=1' + +/** On these screens Android back leaves the app instead of walking back into a room. */ +const isHomePath = (pathname: string): boolean => pathname === '/' || pathname === '/app' || pathname === '/app/' + +/** + * What Android back does. Without in-app history (every launcher open, cold link and cold push tap + * reaches the room through replace), back goes to the rooms list, not to `NATIVE_HOME`: that would + * redirect straight back into the same room, so back would never leave the app. + */ +export function backAction(pathname: string, canGoBack: boolean): 'minimize' | 'history-back' | { replace: string } { + if (isHomePath(pathname)) return 'minimize' + // Drawers are history entries (nuqs), so an open drawer closes first. + if (canGoBack) return 'history-back' + return { replace: NATIVE_ROOMS_LIST } +} + +export interface EntryInputs { + /** `window.__splitBootPath`: the location the WebView loaded before the boot script reset it to `/`. */ + bootPath: string | undefined + /** The URL that launched the app, or null. */ + getLaunchUrl(): Promise + /** The notification tap that launched the app (`slug` null for an unknown room key), or null. */ + awaitColdPushTap(): Promise<{ slug: string | null; sendId: string } | null> + nav: NativeNav +} + +export type EntryDecision = + | { step: 'boot'; path: string } + | { step: 'launch'; url: string; result: 'navigated' | 'duplicate' } + | { step: 'push'; slug: string | null; sendId: string } + | { step: 'home' } + +/** + * Decides the first screen after a cold start or a hard load (ARCHITECTURE 4.3, PLAN 4.1), and + * navigates there through `nav`. The order is fixed: + * + * 1. A non-root boot path (a reload, Android recreating the WebView) is restored. It comes from the + * WebView's own location, never from a tap, so an unmapped or external one goes home silently + * and never opens a browser. + * 2. The launch URL goes through `dispatchNativeLink`, the same function `appUrlOpen` uses. If either + * delivery already navigated, stop; a replayed or unmappable launch URL falls through. + * 3. A notification tap that launched the app opens its room, or the rooms list for an unknown room + * key (never the most recent room, which would read as the wrong notification). + * 4. Otherwise the rooms home. + * + * Steps 2 and 3 run before step 4, so a cold start from a link or a notification never shows the + * most recent room first. + */ +export async function decideEntry(inputs: EntryInputs): Promise { + const { bootPath, nav } = inputs + + if (bootPath && bootPath !== '/') { + const mapped = nativePathForUrl(bootPath) + const path = mapped && 'path' in mapped ? mapped.path : NATIVE_HOME + nav.replace(path) + return { step: 'boot', path } + } + + const launchUrl = await inputs.getLaunchUrl() + if (launchUrl) { + const result = dispatchNativeLink(launchUrl, 'launch', nav) + if (result === 'navigated' || result === 'duplicate') return { step: 'launch', url: launchUrl, result } + } + + const tap = await inputs.awaitColdPushTap() + if (tap) { + nav.replace(tap.slug ? roomPath(tap.slug) : NATIVE_ROOMS_LIST) + return { step: 'push', slug: tap.slug, sendId: tap.sendId } + } + + nav.replace(NATIVE_HOME) + return { step: 'home' } +} diff --git a/apps/web/src/lib/native/polyfills.test.ts b/apps/web/src/lib/native/polyfills.test.ts new file mode 100644 index 00000000..410683e7 --- /dev/null +++ b/apps/web/src/lib/native/polyfills.test.ts @@ -0,0 +1,136 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +// The native side as state: files in the app cache, and what the share sheet was given. +const native = vi.hoisted(() => ({ + cache: new Map(), + sheets: [] as Array<{ title?: string; text?: string; url?: string; files?: string[] }>, + sheetResult: true, + cacheWorks: true, +})) + +vi.mock('./capacitor/index', () => ({ + filesystem: { + writeCacheFile: async (name: string, data: string) => { + if (!native.cacheWorks) return null + native.cache.set(name, data) + return `file:///cache/${name}` + }, + }, + share: { + share: async (input: (typeof native.sheets)[number]) => { + if (!native.sheetResult) return false + native.sheets.push(input) + return true + }, + }, +})) + +type SharingNavigator = { share?: (data?: ShareData) => Promise; canShare?: (data?: ShareData) => boolean } +let nav: SharingNavigator + +beforeEach(() => { + vi.resetModules() + vi.stubEnv('NEXT_PUBLIC_NATIVE_BUILD', '1') + native.cache.clear() + native.sheets.length = 0 + native.sheetResult = true + native.cacheWorks = true + nav = {} + vi.stubGlobal('navigator', nav) +}) + +afterEach(() => { + vi.unstubAllEnvs() + vi.unstubAllGlobals() +}) + +async function install() { + const module = await import('./polyfills') + module.installSharePolyfill() + return module +} + +const decode = (base64: string) => Buffer.from(base64, 'base64').toString('utf8') + +describe('installSharePolyfill', () => { + it('defines share and canShare where the WebView has none (Android)', async () => { + await install() + expect(typeof nav.share).toBe('function') + expect(nav.canShare?.({ url: 'https://peanutsplit.com/r/ski-trip-kunc-syrup-drum' })).toBe(true) + expect(nav.canShare?.({})).toBe(false) + expect(nav.canShare?.({ files: [] })).toBe(false) + expect(nav.canShare?.({ files: [new File(['x'], 'a.png')] })).toBe(true) + }) + + it("replaces the WebView's own share (iOS), which refuses after an awaited fetch", async () => { + const own = vi.fn(async () => { + throw new DOMException('User activation is required', 'NotAllowedError') + }) + nav.share = own + nav.canShare = () => false + await install() + expect(nav.share).not.toBe(own) + expect(nav.canShare?.({ files: [new File(['a,b'], 'history.csv')] })).toBe(true) + + await nav.share?.({ files: [new File(['a,b'], 'history.csv', { type: 'text/csv' })] }) + expect(own).not.toHaveBeenCalled() + expect(native.sheets).toEqual([ + { title: undefined, text: undefined, url: undefined, files: ['file:///cache/history.csv'] }, + ]) + }) + + it('shares text and a link through the native sheet', async () => { + await install() + await nav.share?.({ text: 'Ski trip', url: 'https://peanutsplit.com/r/ski-trip-kunc-syrup-drum' }) + expect(native.sheets).toEqual([ + { + title: undefined, + text: 'Ski trip', + url: 'https://peanutsplit.com/r/ski-trip-kunc-syrup-drum', + files: undefined, + }, + ]) + expect(native.cache.size).toBe(0) + }) + + it('writes each file to the cache and shares it by URI', async () => { + await install() + const card = new File(['card-bytes'], 'room-card.png', { type: 'image/png' }) + const csv = new File(['a,b'], '../../escape.csv', { type: 'text/csv' }) + await nav.share?.({ files: [card, csv] }) + + expect(decode(native.cache.get('room-card.png') ?? '')).toBe('card-bytes') + // A path in the name never leaves the cache folder. + expect(decode(native.cache.get('escape.csv') ?? '')).toBe('a,b') + expect(native.sheets[0].files).toEqual(['file:///cache/room-card.png', 'file:///cache/escape.csv']) + }) + + it('rejects with AbortError when the sheet is dismissed, so callers stay quiet', async () => { + await install() + native.sheetResult = false + await expect(nav.share?.({ url: 'https://peanutsplit.com' })).rejects.toMatchObject({ name: 'AbortError' }) + expect(native.sheets).toEqual([]) + }) + + it('rejects with DataError and opens no sheet when a file cannot be cached', async () => { + await install() + native.cacheWorks = false + await expect(nav.share?.({ files: [new File(['x'], 'a.png')] })).rejects.toMatchObject({ name: 'DataError' }) + expect(native.sheets).toEqual([]) + }) + + it('rejects an empty payload with TypeError, as Web Share does', async () => { + await install() + await expect(nav.share?.({})).rejects.toBeInstanceOf(TypeError) + expect(native.sheets).toEqual([]) + }) +}) + +describe('cacheFileName', () => { + it('keeps the last path segment and never returns an empty or dot name', async () => { + const { cacheFileName } = await import('./polyfills') + expect(cacheFileName(new File([''], 'a/b/c.png'), 0)).toBe('c.png') + expect(cacheFileName(new File([''], '..'), 1)).toBe('share-2') + expect(cacheFileName(new File([''], ''), 0)).toBe('share-1') + }) +}) diff --git a/apps/web/src/lib/native/polyfills.ts b/apps/web/src/lib/native/polyfills.ts new file mode 100644 index 00000000..46d0578f --- /dev/null +++ b/apps/web/src/lib/native/polyfills.ts @@ -0,0 +1,64 @@ +import { loadHost } from './host' + +/** Base64 without a data-URL prefix, as the Filesystem plugin expects. Chunked to stay under the argument limit. */ +async function toBase64(blob: Blob): Promise { + const bytes = new Uint8Array(await blob.arrayBuffer()) + let binary = '' + for (let start = 0; start < bytes.length; start += 0x8000) { + binary += String.fromCharCode(...bytes.subarray(start, start + 0x8000)) + } + return btoa(binary) +} + +/** A cache file name the OS accepts: the last path segment of the File's name, never empty. */ +export function cacheFileName(file: File, index: number): string { + const base = (file.name || '').split(/[\\/]/).pop()?.trim() ?? '' + return base && base !== '.' && base !== '..' ? base : `share-${index + 1}` +} + +/** Web Share's rule: a payload must carry at least one of title, text, url or a non-empty file list. */ +export function isSharePayload(data: ShareData | undefined): boolean { + if (!data) return false + if (data.files !== undefined && (!Array.isArray(data.files) || data.files.some((file) => !(file instanceof Blob)))) + return false + return Boolean(data.title || data.text || data.url || data.files?.length) +} + +async function nativeShare(data?: ShareData): Promise { + if (!data || !isSharePayload(data)) throw new TypeError('Nothing to share') + const host = loadHost() + if (!host) throw new DOMException('Sharing is not available', 'NotAllowedError') + const { share, filesystem } = await host + + let files: string[] | undefined + if (data.files?.length) { + files = [] + for (const [index, file] of data.files.entries()) { + // The share sheet takes file URIs, not blobs: write each file to the app cache first. + const uri = await filesystem.writeCacheFile(cacheFileName(file, index), await toBase64(file)) + if (!uri) throw new DOMException('Could not prepare the file to share', 'DataError') + files.push(uri) + } + } + + const shared = await share.share({ title: data.title, text: data.text, url: data.url, files }) + // The wrapper cannot tell a dismissed sheet from a failed one. Callers treat AbortError as the + // person's own decision and stay quiet, which is the right reading for nearly every `false`. + if (!shared) throw new DOMException('Share canceled', 'AbortError') +} + +/** + * Serves `navigator.share` (including files) through the native share sheet (ARCHITECTURE 9.2). + * + * Installed on both platforms. Android's WebView has no `navigator.share`, so without this every + * Share button silently becomes Copy there. iOS's WKWebView has its own, but it needs transient user + * activation and refuses with NotAllowedError after an awaited fetch, which the history export does + * before it shares; the native plugin needs no activation. `canShare` is replaced together with + * `share` so the two always describe the same implementation. An own property on `navigator` shadows + * the WebView's and is not a prototype patch. + */ +export function installSharePolyfill(): void { + if (typeof navigator === 'undefined') return + Object.defineProperty(navigator, 'share', { configurable: true, writable: true, value: nativeShare }) + Object.defineProperty(navigator, 'canShare', { configurable: true, writable: true, value: isSharePayload }) +} diff --git a/apps/web/src/lib/native/push-room.test.ts b/apps/web/src/lib/native/push-room.test.ts new file mode 100644 index 00000000..2c1c7c9a --- /dev/null +++ b/apps/web/src/lib/native/push-room.test.ts @@ -0,0 +1,35 @@ +// @vitest-environment happy-dom +import { beforeEach, describe, expect, it } from 'vitest' +import { hasPushRoom, PUSH_ROOM_PREFIX, readPushRoom, removePushRoom, writePushRoom } from './push-room' + +const SLUG = 'ski-trip-kunc-syrup-drum' +const OTHER = 'flat-share-kunc-syrup-otter' + +beforeEach(() => window.localStorage.clear()) + +describe('push-room map', () => { + it('maps a notification key back to the room it opens', () => { + expect(writePushRoom('key-1', SLUG)).toBe(true) + expect(window.localStorage.getItem(`${PUSH_ROOM_PREFIX}key-1`)).toBe(SLUG) + expect(readPushRoom('key-1')).toBe(SLUG) + expect(hasPushRoom(SLUG)).toBe(true) + }) + + it('answers null for an unknown key and for a stored value that is not a room slug', () => { + expect(readPushRoom('nope')).toBeNull() + expect(readPushRoom('')).toBeNull() + window.localStorage.setItem(`${PUSH_ROOM_PREFIX}key-2`, 'javascript:alert(1)') + expect(readPushRoom('key-2')).toBeNull() + }) + + it('removes every entry of one room and keeps the other rooms', () => { + writePushRoom('key-1', SLUG) + writePushRoom('key-old', SLUG) + writePushRoom('key-2', OTHER) + removePushRoom(SLUG) + expect(readPushRoom('key-1')).toBeNull() + expect(readPushRoom('key-old')).toBeNull() + expect(hasPushRoom(SLUG)).toBe(false) + expect(readPushRoom('key-2')).toBe(OTHER) + }) +}) diff --git a/apps/web/src/lib/native/push-room.ts b/apps/web/src/lib/native/push-room.ts new file mode 100644 index 00000000..903c9f12 --- /dev/null +++ b/apps/web/src/lib/native/push-room.ts @@ -0,0 +1,75 @@ +import { nativeRoomSlug } from './links' + +/** + * The app's map from a notification's room key to the room it opens (ARCHITECTURE 10.1). + * + * APNs and FCM payloads are readable by Apple and Google, so they carry the room's `analyticsKey`, + * never the slug. The app writes `ps:push-room: = ` when it subscribes a room, and + * a tap looks the key up here. The in-memory key map in `analytics.ts` is empty after a cold start, + * so it cannot serve. The storage mirror copies this prefix to Preferences, so the map survives an OS + * eviction of localStorage. + */ +export const PUSH_ROOM_PREFIX = 'ps:push-room:' + +function deviceStorage(): Storage | null { + try { + return window.localStorage + } catch { + return null + } +} + +/** The slug a notification key opens, or null for an unknown key or a stored value that is not a slug. */ +export function readPushRoom(analyticsKey: string): string | null { + if (!analyticsKey) return null + try { + return nativeRoomSlug(deviceStorage()?.getItem(PUSH_ROOM_PREFIX + analyticsKey) ?? null) + } catch { + return null + } +} + +/** Records that notifications with `analyticsKey` open `slug`. False when storage refused the write. */ +export function writePushRoom(analyticsKey: string, slug: string): boolean { + if (!analyticsKey) return false + try { + const storage = deviceStorage() + if (!storage) return false + storage.setItem(PUSH_ROOM_PREFIX + analyticsKey, slug) + return true + } catch { + return false + } +} + +/** Every stored key that opens `slug`. A room has one key, but a stale copy must not outlive a forget. */ +function keysForSlug(storage: Storage, slug: string): string[] { + const keys: string[] = [] + for (let index = 0; index < storage.length; index++) { + const key = storage.key(index) + if (key?.startsWith(PUSH_ROOM_PREFIX) && storage.getItem(key) === slug) keys.push(key) + } + return keys +} + +/** True when this install subscribed `slug` and has not dropped it since. */ +export function hasPushRoom(slug: string): boolean { + try { + const storage = deviceStorage() + return storage !== null && keysForSlug(storage, slug).length > 0 + } catch { + return false + } +} + +/** Removes every entry that opens `slug` (unsubscribe, leave, forget). */ +export function removePushRoom(slug: string): void { + try { + const storage = deviceStorage() + if (!storage) return + // Collected first: removing while walking by index would skip the entry after each removal. + for (const key of keysForSlug(storage, slug)) storage.removeItem(key) + } catch { + // Blocked storage has nothing to remove. + } +} diff --git a/apps/web/src/lib/native/storage-mirror.test.ts b/apps/web/src/lib/native/storage-mirror.test.ts new file mode 100644 index 00000000..6060ce53 --- /dev/null +++ b/apps/web/src/lib/native/storage-mirror.test.ts @@ -0,0 +1,238 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +// Preferences as the native plugin would hold it: one key-value map that outlives localStorage. +// `stalled` holds every call's reply forever after the call itself reached the plugin, as when the +// page unloads before the native side answers. +const preferences = vi.hoisted(() => ({ store: new Map(), stalled: false })) + +vi.mock('./capacitor/index', () => ({ + preferences: { + keys: async () => [...preferences.store.keys()], + get: async (key: string) => preferences.store.get(key) ?? null, + set: async (key: string, value: string) => { + preferences.store.set(key, value) + if (preferences.stalled) await new Promise(() => {}) + return true + }, + remove: async (key: string) => { + preferences.store.delete(key) + if (preferences.stalled) await new Promise(() => {}) + return true + }, + }, +})) + +/** A fresh Storage class per test, because installStorageMirror patches its prototype. */ +function makeStorageClass() { + return class FakeStorage { + readonly items = new Map() + full = false + get length() { + return this.items.size + } + key(index: number) { + return [...this.items.keys()][index] ?? null + } + getItem(key: string) { + return this.items.get(key) ?? null + } + setItem(key: string, value: string) { + if (this.full) throw new Error('QuotaExceededError') + this.items.set(key, String(value)) + } + removeItem(key: string) { + this.items.delete(key) + } + clear() { + this.items.clear() + } + } +} + +type FakeStorage = InstanceType> + +let local: FakeStorage +let session: FakeStorage + +beforeEach(() => { + vi.resetModules() + vi.stubEnv('NEXT_PUBLIC_NATIVE_BUILD', '1') + preferences.store.clear() + preferences.stalled = false + const FakeStorageClass = makeStorageClass() + local = new FakeStorageClass() + session = new FakeStorageClass() + vi.stubGlobal('Storage', FakeStorageClass) + vi.stubGlobal('window', { localStorage: local, sessionStorage: session }) +}) + +afterEach(() => { + vi.unstubAllEnvs() + vi.unstubAllGlobals() +}) + +async function load() { + return import('./storage-mirror') +} + +describe('isMirroredKey', () => { + it('mirrors only the room list, member tokens, queued writes and push rooms', async () => { + const { isMirroredKey } = await load() + expect(isMirroredKey('ps:recent')).toBe(true) + expect(isMirroredKey('ps:member:ski-trip-kunc-syrup-drum')).toBe(true) + expect(isMirroredKey('ps:pending:abc')).toBe(true) + expect(isMirroredKey('ps:push-room:key123')).toBe(true) + // The drain lease and the legacy queue array would do harm if restored from an old copy. + expect(isMirroredKey('ps:pending-owner')).toBe(false) + expect(isMirroredKey('ps:pending')).toBe(false) + expect(isMirroredKey('ps:settings')).toBe(false) + expect(isMirroredKey('ps-locale')).toBe(false) + expect(isMirroredKey('ps:memberx')).toBe(false) + }) +}) + +describe('installStorageMirror', () => { + it('writes mirrored localStorage keys through to Preferences and skips the rest', async () => { + const { installStorageMirror } = await load() + installStorageMirror() + + local.setItem('ps:recent', '[{"slug":"ski-trip-kunc-syrup-drum"}]') + local.setItem('ps:member:ski-trip-kunc-syrup-drum', '{"id":"m1","token":"t1"}') + local.setItem('ps:settings', '{"sound":false}') + local.setItem('ps:pending-owner', 'tab-1') + + await vi.waitFor(() => expect(preferences.store.size).toBe(2)) + expect(Object.fromEntries(preferences.store)).toEqual({ + 'ps:recent': '[{"slug":"ski-trip-kunc-syrup-drum"}]', + 'ps:member:ski-trip-kunc-syrup-drum': '{"id":"m1","token":"t1"}', + }) + // localStorage itself is unchanged by the wrapper. + expect(local.getItem('ps:settings')).toBe('{"sound":false}') + expect(local.getItem('ps:recent')).toBe('[{"slug":"ski-trip-kunc-syrup-drum"}]') + }) + + it('mirrors removals, in order after the write they follow', async () => { + const { installStorageMirror } = await load() + installStorageMirror() + + local.setItem('ps:pending:q1', '{"clientKey":"q1"}') + local.setItem('ps:pending:q2', '{"clientKey":"q2"}') + local.removeItem('ps:pending:q1') + + await vi.waitFor(() => expect([...preferences.store.keys()]).toEqual(['ps:pending:q2'])) + expect(local.getItem('ps:pending:q1')).toBeNull() + }) + + it('sends a remove without waiting for the reply to the write before it', async () => { + const { installStorageMirror } = await load() + installStorageMirror() + local.setItem('ps:member:ski-trip-kunc-syrup-drum', '{"id":"m1","token":"t1"}') + await vi.waitFor(() => expect(preferences.store.has('ps:member:ski-trip-kunc-syrup-drum')).toBe(true)) + + // Remove from device: the room list is rewritten, then the member token removed, and the + // page navigates away before any native reply arrives. + preferences.stalled = true + local.setItem('ps:recent', '[]') + local.removeItem('ps:member:ski-trip-kunc-syrup-drum') + + await vi.waitFor(() => expect(preferences.store.has('ps:member:ski-trip-kunc-syrup-drum')).toBe(false)) + expect(preferences.store.get('ps:recent')).toBe('[]') + }) + + it('leaves sessionStorage alone', async () => { + const { installStorageMirror } = await load() + installStorageMirror() + + session.setItem('ps:recent', '[]') + session.setItem('ps:member:x', 'y') + preferences.store.set('ps:member:kept', 'z') + session.removeItem('ps:member:kept') + local.setItem('ps:push-room:k', 'slug') + + // The localStorage write lands; the sessionStorage ones never do. + await vi.waitFor(() => expect(preferences.store.get('ps:push-room:k')).toBe('slug')) + expect(Object.fromEntries(preferences.store)).toEqual({ 'ps:member:kept': 'z', 'ps:push-room:k': 'slug' }) + expect(session.getItem('ps:recent')).toBe('[]') + }) + + it('does not mirror a write that localStorage refused, and the caller still sees the error', async () => { + const { installStorageMirror } = await load() + installStorageMirror() + + local.full = true + expect(() => local.setItem('ps:recent', '[1]')).toThrow('QuotaExceededError') + local.full = false + local.setItem('ps:member:a', 'b') + + await vi.waitFor(() => expect(preferences.store.get('ps:member:a')).toBe('b')) + expect(preferences.store.has('ps:recent')).toBe(false) + }) + + it('wraps the prototype once, so a second install does not mirror twice', async () => { + const { installStorageMirror } = await load() + installStorageMirror() + const wrapped = Storage.prototype.setItem + installStorageMirror() + expect(Storage.prototype.setItem).toBe(wrapped) + }) + + it('does nothing in the web build', async () => { + vi.stubEnv('NEXT_PUBLIC_NATIVE_BUILD', '0') + const original = Storage.prototype.setItem + const { installStorageMirror } = await load() + installStorageMirror() + expect(Storage.prototype.setItem).toBe(original) + local.setItem('ps:recent', '[]') + await Promise.resolve() + expect(preferences.store.size).toBe(0) + }) +}) + +describe('hydrateStorageMirror', () => { + it('restores mirrored keys that localStorage lost and never overwrites a present key', async () => { + preferences.store.set('ps:recent', '[{"slug":"old"}]') + preferences.store.set('ps:member:lost-room', '{"id":"m2"}') + preferences.store.set('ps:pending:q9', '{"clientKey":"q9"}') + preferences.store.set('ps:settings', '{"sound":true}') + local.setItem('ps:recent', '[{"slug":"new"}]') + + const { hydrateStorageMirror } = await load() + await hydrateStorageMirror() + + expect(local.getItem('ps:recent')).toBe('[{"slug":"new"}]') + expect(local.getItem('ps:member:lost-room')).toBe('{"id":"m2"}') + expect(local.getItem('ps:pending:q9')).toBe('{"clientKey":"q9"}') + // Not a mirrored family, so Preferences is not its source. + expect(local.getItem('ps:settings')).toBeNull() + expect(session.length).toBe(0) + }) + + it('resolves without restoring when localStorage cannot be read', async () => { + preferences.store.set('ps:recent', '[]') + vi.stubGlobal('window', { + get localStorage(): Storage { + throw new Error('SecurityError') + }, + }) + const { hydrateStorageMirror } = await load() + await expect(hydrateStorageMirror()).resolves.toBeUndefined() + expect(local.length).toBe(0) + }) + + it('resolves and keeps the Preferences copy when localStorage refuses the restore', async () => { + preferences.store.set('ps:member:a', 'b') + local.full = true + const { hydrateStorageMirror } = await load() + await expect(hydrateStorageMirror()).resolves.toBeUndefined() + expect(local.getItem('ps:member:a')).toBeNull() + expect(preferences.store.get('ps:member:a')).toBe('b') + }) + + it('does nothing in the web build', async () => { + vi.stubEnv('NEXT_PUBLIC_NATIVE_BUILD', '0') + preferences.store.set('ps:recent', '[]') + const { hydrateStorageMirror } = await load() + await hydrateStorageMirror() + expect(local.getItem('ps:recent')).toBeNull() + }) +}) diff --git a/apps/web/src/lib/native/storage-mirror.ts b/apps/web/src/lib/native/storage-mirror.ts new file mode 100644 index 00000000..ca93dd89 --- /dev/null +++ b/apps/web/src/lib/native/storage-mirror.ts @@ -0,0 +1,102 @@ +import { loadHost, type NativeHost } from './host' + +/** + * The key families that are the device's only copy of something a person cannot get back: the + * room list, member tokens, queued offline expenses and the push-room map (ARCHITECTURE 8.3). + * `ps:recent` is the room-list key itself; the others are prefixes of one key per item. + * `ps:pending-owner` (a drain lease) and the legacy `ps:pending` array are not mirrored on purpose: + * a lease restored from an old copy would block the queue, and the app never wrote the old array. + */ +export const MIRRORED_PREFIXES = ['ps:recent', 'ps:member:', 'ps:pending:', 'ps:push-room:'] as const + +export const isMirroredKey = (key: string): boolean => MIRRORED_PREFIXES.some((prefix) => key.startsWith(prefix)) + +/** localStorage, or null where reading the property itself throws (blocked or evicted storage). */ +function deviceStorage(): Storage | null { + try { + return window.localStorage + } catch { + return null + } +} + +/** + * Copies room-list and member-token keys from Preferences back into a localStorage that the OS + * evicted (WKWebView storage can be cleared under disk pressure; peanut-ui incident PEANUT-UI-QTQ). + * NativeShell awaits it before any screen mounts. + * + * Only keys that localStorage is missing are restored. A present key is newer than or equal to its + * Preferences copy, because every localStorage write of these keys is mirrored, so it always wins. + */ +export async function hydrateStorageMirror(): Promise { + const host = loadHost() + const storage = deviceStorage() + if (!host || !storage) return + const { preferences } = await host + const keys = (await preferences.keys()).filter(isMirroredKey) + await Promise.all( + keys.map(async (key) => { + try { + if (storage.getItem(key) !== null) return + } catch { + return + } + const value = await preferences.get(key) + if (value === null) return + try { + storage.setItem(key, value) + } catch { + // A full or blocked localStorage keeps the Preferences copy for the next launch. + } + }) + ) +} + +/** Set once by installStorageMirror; every mirrored write reuses the one loaded host. */ +let mirrorHost: Promise | null = null + +/** + * Sends the Preferences call in the microtask after its localStorage write, without waiting for the + * previous call's native reply. Waiting would lose a remove that a hard navigation follows (Remove + * from device, Leave): the page unloads before the earlier reply returns, Preferences keeps the + * key, and the next hydrate restores it. Capacitor runs one plugin's calls in dispatch order on + * iOS and Android, so a set followed by a remove still lands in that order. + */ +function mirror(write: (preferences: NativeHost['preferences']) => Promise): void { + const host = mirrorHost + if (!host) return + void host.then((loaded) => write(loaded.preferences)).catch(() => {}) +} + +/** + * Mirrors every later write of those keys into Preferences. + * + * An interceptor rather than explicit calls: these keys are written from eviction and rollback + * paths in recent-rooms.ts, identity.ts, offline-queue.ts and ExpenseDrawer.tsx, and one missed + * call site would let the copies diverge silently. localStorage stays the synchronous source of + * truth: the original write runs first, and a write that throws (quota) is not mirrored. The + * Preferences write is fire-and-forget. sessionStorage and any other Storage are untouched. + */ +export function installStorageMirror(): void { + if (mirrorHost || typeof Storage === 'undefined') return + mirrorHost = loadHost() + if (!mirrorHost) return + const proto = Storage.prototype + const originalSet = proto.setItem + const originalRemove = proto.removeItem + + proto.setItem = function setItem(this: Storage, key: string, value: string): void { + originalSet.call(this, key, value) + const name = String(key) + if (this === deviceStorage() && isMirroredKey(name)) { + const text = String(value) + mirror((preferences) => preferences.set(name, text)) + } + } + + proto.removeItem = function removeItem(this: Storage, key: string): void { + originalRemove.call(this, key) + const name = String(key) + if (this === deviceStorage() && isMirroredKey(name)) mirror((preferences) => preferences.remove(name)) + } +} diff --git a/apps/web/src/lib/native/use-native-push.test.ts b/apps/web/src/lib/native/use-native-push.test.ts new file mode 100644 index 00000000..7eabf66b --- /dev/null +++ b/apps/web/src/lib/native/use-native-push.test.ts @@ -0,0 +1,298 @@ +// @vitest-environment happy-dom +import { act, createElement } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { PushControls } from '../push-status' + +/** + * The app's push client against a fake plugin and a fake server. The server holds the per-room rows + * (`:` per room, as the route stores them), so every assertion is about what the + * server and the device end up holding, and what the row shows. + */ + +const SLUG = 'ski-trip-kunc-syrup-drum' +const KEY = 'room-key-1' +const TOKEN = 'device-token-1' + +type Registration = 'token' | 'error' | 'silent' + +const plugin = vi.hoisted(() => ({ + permission: 'prompt' as 'granted' | 'denied' | 'prompt', + answer: 'granted' as 'granted' | 'denied' | 'prompt', + registration: 'token' as Registration, + registerCalls: 0, + tokenListeners: new Set<(token: string) => void>(), + errorListeners: new Set<(message: string) => void>(), +})) + +vi.mock('./capacitor/index', () => ({ + push: { + permission: async () => plugin.permission, + requestPermission: async () => { + plugin.permission = plugin.answer + return plugin.permission + }, + register: async () => { + plugin.registerCalls += 1 + // The native side answers on its own schedule, after register() resolves. + setTimeout(() => { + if (plugin.registration === 'token') plugin.tokenListeners.forEach((listener) => listener(TOKEN)) + if (plugin.registration === 'error') plugin.errorListeners.forEach((listener) => listener('no APNs')) + }, 0) + return true + }, + onRegistration: async (handler: (token: string) => void) => { + plugin.tokenListeners.add(handler) + return () => plugin.tokenListeners.delete(handler) + }, + onRegistrationError: async (handler: (message: string) => void) => { + plugin.errorListeners.add(handler) + return () => plugin.errorListeners.delete(handler) + }, + }, +})) + +const server = vi.hoisted(() => ({ rows: new Set(), unavailable: false, offline: false })) + +const unavailableError = () => Object.assign(new Error('503'), { code: 'NATIVE_PUSH_UNAVAILABLE' }) + +vi.mock('../api', () => { + type Body = { transport: string; token: string; memberToken: string } + const guard = (body: Body) => { + if (server.offline) throw new Error('offline') + if (server.unavailable) throw unavailableError() + if (body.memberToken !== 'member-token') throw Object.assign(new Error('403'), { code: 'FORBIDDEN' }) + } + const row = (slug: string, body: Body) => `${slug}|${body.transport}:${body.token}` + return { + isApiError: (error: unknown, code?: string) => + typeof error === 'object' && error !== null && 'code' in error && (!code || error.code === code), + api: { + push: { + subscribe: async (slug: string, body: Body) => { + guard(body) + server.rows.add(row(slug, body)) + return { subscribed: true } + }, + unsubscribe: async (slug: string, body: Body) => { + if (server.offline) throw new Error('offline') + server.rows.delete(row(slug, body)) + return { subscribed: false, endpointStillUsed: false } + }, + status: async (slug: string, body: Body) => { + guard(body) + return { subscribed: server.rows.has(row(slug, body)) } + }, + }, + }, + } +}) + +vi.mock('../analytics', () => ({ + roomProps: (_slug: string, extra: Record = {}) => ({ room: KEY, ...extra }), +})) + +beforeEach(() => { + vi.resetModules() + vi.stubEnv('NEXT_PUBLIC_NATIVE_BUILD', '1') + vi.stubEnv('NEXT_PUBLIC_NATIVE_PUSH', '1') + vi.stubGlobal('Capacitor', { getPlatform: () => 'android' }) + Object.assign(plugin, { permission: 'prompt', answer: 'granted', registration: 'token', registerCalls: 0 }) + plugin.tokenListeners.clear() + plugin.errorListeners.clear() + Object.assign(server, { unavailable: false, offline: false }) + server.rows.clear() + window.localStorage.clear() + window.localStorage.setItem( + `ps:member:${SLUG}`, + JSON.stringify({ memberId: 'm1', name: 'Ana', token: 'member-token' }) + ) +}) + +afterEach(() => { + vi.useRealTimers() + vi.unstubAllEnvs() + vi.unstubAllGlobals() +}) + +const load = () => import('./use-native-push') +const pushRoomEntry = () => window.localStorage.getItem(`ps:push-room:${KEY}`) + +describe('nativeTransport', () => { + it('is fcm on Android, apns-sandbox on iOS unless the build says production, and null in a browser', async () => { + expect((await load()).nativeTransport()).toBe('fcm') + vi.stubGlobal('Capacitor', { getPlatform: () => 'ios' }) + expect((await load()).nativeTransport()).toBe('apns-sandbox') + vi.stubEnv('NEXT_PUBLIC_SPLIT_APNS_ENV', 'production') + expect((await load()).nativeTransport()).toBe('apns') + vi.stubGlobal('Capacitor', undefined) + expect((await load()).nativeTransport()).toBeNull() + }) +}) + +describe('readNativeStatus', () => { + it('hides the row and registers nothing when push is compiled out', async () => { + vi.stubEnv('NEXT_PUBLIC_NATIVE_PUSH', '') + expect(await (await load()).readNativeStatus(SLUG)).toBe('unsupported') + expect(plugin.registerCalls).toBe(0) + }) + + it('maps the permission and the server row', async () => { + const { readNativeStatus } = await load() + expect(await readNativeStatus(SLUG)).toBe('default') + plugin.permission = 'denied' + expect(await readNativeStatus(SLUG)).toBe('denied') + plugin.permission = 'granted' + expect(await readNativeStatus(SLUG)).toBe('default') + server.rows.add(`${SLUG}|fcm:${TOKEN}`) + expect(await readNativeStatus(SLUG)).toBe('subscribed') + // One registration serves every check in this app run. + expect(plugin.registerCalls).toBe(1) + }) + + it('hides the row when the server has no push credentials (503)', async () => { + server.unavailable = true + expect(await (await load()).readNativeStatus(SLUG)).toBe('unsupported') + }) + + it('says unknown when the server does not answer', async () => { + server.offline = true + expect(await (await load()).readNativeStatus(SLUG)).toBe('unknown') + }) + + it('hides the row on a registration error', async () => { + plugin.registration = 'error' + expect(await (await load()).readNativeStatus(SLUG)).toBe('unsupported') + }) + + it('hides the row when no token arrives within 10 s, and does not hang', async () => { + vi.useFakeTimers() + plugin.registration = 'silent' + const { readNativeStatus, REGISTRATION_TIMEOUT_MS } = await load() + let status: string | null = null + void readNativeStatus(SLUG).then((value) => (status = value)) + await vi.advanceTimersByTimeAsync(REGISTRATION_TIMEOUT_MS - 1) + expect(status).toBeNull() + await vi.advanceTimersByTimeAsync(1) + expect(status).toBe('unsupported') + }) +}) + +describe('addNativeRoomSubscription and dropNativeRoomSubscription', () => { + it('subscribes the room and records which room the notification key opens', async () => { + const { addNativeRoomSubscription } = await load() + expect(await addNativeRoomSubscription(SLUG, 'm1', 'member-token')).toEqual({ status: 'subscribed' }) + expect([...server.rows]).toEqual([`${SLUG}|fcm:${TOKEN}`]) + expect(pushRoomEntry()).toBe(SLUG) + }) + + it('stops at a refusal: no row, no entry', async () => { + plugin.answer = 'denied' + const { addNativeRoomSubscription } = await load() + expect(await addNativeRoomSubscription(SLUG, 'm1', 'member-token')).toEqual({ + status: 'denied', + permission: 'denied', + }) + expect(server.rows.size).toBe(0) + expect(pushRoomEntry()).toBeNull() + }) + + it('leave and forget remove the server row and the entry', async () => { + const { addNativeRoomSubscription, dropNativeRoomSubscription } = await load() + await addNativeRoomSubscription(SLUG, 'm1', 'member-token') + await dropNativeRoomSubscription(SLUG, 'm1', 'member-token') + expect(server.rows.size).toBe(0) + expect(pushRoomEntry()).toBeNull() + }) + + it('forgetting offline still removes the entry, so a later tap cannot open the forgotten room', async () => { + const { addNativeRoomSubscription, dropNativeRoomSubscription } = await load() + await addNativeRoomSubscription(SLUG, 'm1', 'member-token') + server.offline = true + await expect(dropNativeRoomSubscription(SLUG, 'm1', 'member-token')).rejects.toThrow('offline') + expect(pushRoomEntry()).toBeNull() + }) + + it('a room this install never subscribed costs no registration on forget', async () => { + await (await load()).dropNativeRoomSubscription(SLUG, 'm1', 'member-token') + expect(plugin.registerCalls).toBe(0) + }) +}) + +describe('useNativePush', () => { + let container: HTMLDivElement + let root: Root + let controls: PushControls + + beforeEach(() => { + ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) + }) + + afterEach(async () => { + await act(async () => root.unmount()) + document.body.innerHTML = '' + }) + + async function mount() { + const { useNativePush } = await load() + function Probe() { + controls = useNativePush(SLUG) + return null + } + await act(async () => root.render(createElement(Probe))) + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 5)) + }) + } + + it('is hidden from the first render when push is compiled out', async () => { + vi.stubEnv('NEXT_PUBLIC_NATIVE_PUSH', '') + await mount() + expect(controls.status).toBe('unsupported') + }) + + it('turns the room on and off from the tap', async () => { + await mount() + expect(controls.status).toBe('default') + let outcome: string | undefined + await act(async () => { + outcome = await controls.subscribe('m1', 'member-token') + }) + expect(outcome).toBe('subscribed') + expect(controls.status).toBe('subscribed') + expect(pushRoomEntry()).toBe(SLUG) + await act(async () => { + await controls.unsubscribe('m1', 'member-token') + }) + expect(controls.status).toBe('default') + expect(server.rows.size).toBe(0) + expect(pushRoomEntry()).toBeNull() + }) + + it('hides the row after a registration error at the tap', async () => { + plugin.registration = 'error' + await mount() + // The status check already failed to get a token; the row is hidden before any tap. + expect(controls.status).toBe('unsupported') + let outcome: string | undefined + await act(async () => { + outcome = await controls.subscribe('m1', 'member-token') + }) + expect(outcome).toBe('failed') + expect(controls.status).toBe('unsupported') + expect(server.rows.size).toBe(0) + }) + + it('hides the row when the server answers 503 at the tap', async () => { + await mount() + server.unavailable = true + await act(async () => { + await controls.subscribe('m1', 'member-token') + }) + expect(controls.status).toBe('unsupported') + expect(pushRoomEntry()).toBeNull() + }) +}) diff --git a/apps/web/src/lib/native/use-native-push.ts b/apps/web/src/lib/native/use-native-push.ts new file mode 100644 index 00000000..374373c3 --- /dev/null +++ b/apps/web/src/lib/native/use-native-push.ts @@ -0,0 +1,322 @@ +'use client' + +import { useCallback, useEffect, useRef, useState } from 'react' +import { roomProps } from '../analytics' +import { api, isApiError } from '../api' +import type { NativePushTransport } from '../api-types' +import { identityGeneration, memberStorageKey, readIdentity } from '../identity' +import { NATIVE_PUSH_ENABLED, nativePlatform } from '../platform' +import { derivePushStatus, type PushControls, type SettledPushStatus, type SubscribeOutcome } from '../push-status' +import { completeRoomUpdates, muteRoomUpdates, roomUpdatesStorageKey } from '../room-updates' +import { loadHost } from './host' +import { hasPushRoom, removePushRoom, writePushRoom } from './push-room' + +/** + * Notification opt-in for one room in the store app (ARCHITECTURE 10.1). Same contract as the web + * hook in `use-push.ts`; the channel is the device's APNs or FCM token instead of a browser + * `PushSubscription`, and the server still holds the per-room fact. + */ + +/** The longest wait for the device token. A missing token hides the row instead of hanging the UI. */ +export const REGISTRATION_TIMEOUT_MS = 10_000 + +const PUSH_ROOMS_CHANGE_EVENT = 'ps:native-push-change' + +// One device token serves every room, so only one control may change subscriptions at a time, +// including while the OS permission dialog is open. +let activeMutation: symbol | null = null + +const announceChange = (): void => { + if (typeof window !== 'undefined') window.dispatchEvent?.(new Event(PUSH_ROOMS_CHANGE_EVENT)) +} + +/** `fcm` on Android; on iOS the APNs environment the binary was signed for. Null in a plain browser. */ +export function nativeTransport(): NativePushTransport | null { + const platform = nativePlatform() + if (platform === 'android') return 'fcm' + // A literal property access, so the build inlines it. The release lane sets `production`; + // every other build talks to the APNs sandbox. + if (platform === 'ios') return process.env.NEXT_PUBLIC_SPLIT_APNS_ENV === 'production' ? 'apns' : 'apns-sandbox' + return null +} + +/** + * Registers with APNs or FCM and resolves the device token: the first of the `registration` event, + * the `registrationError` event and the timeout. Registration shows no prompt on either platform. + */ +async function registerDevice(): Promise { + const host = loadHost() + if (!host) return null + const { push } = await host + return await new Promise((resolve) => { + let settled = false + const disposers: Array void>> = [] + const finish = (token: string | null) => { + if (settled) return + settled = true + clearTimeout(timer) + disposers.forEach((disposer) => void disposer.then((dispose) => dispose())) + resolve(token) + } + const timer = setTimeout(() => finish(null), REGISTRATION_TIMEOUT_MS) + disposers.push(push.onRegistration((token) => finish(token || null))) + disposers.push(push.onRegistrationError(() => finish(null))) + // Both listeners first: the token event can arrive before register() resolves. + void Promise.all(disposers).then(async () => { + if (!settled && !(await push.register())) finish(null) + }) + }) +} + +let tokenRequest: Promise | null = null + +/** The device token, registered once per app run. A failed registration is retried on the next call. */ +export function deviceToken(): Promise { + if (!NATIVE_PUSH_ENABLED) return Promise.resolve(null) + tokenRequest ??= registerDevice().then((token) => { + if (token === null) tokenRequest = null + return token + }) + return tokenRequest +} + +/** The server answers this when it has no APNs or FCM credentials yet; the row hides. */ +const isUnavailable = (error: unknown): boolean => isApiError(error, 'NATIVE_PUSH_UNAVAILABLE') + +/** Thrown when the device could not get a token; the row hides. */ +export class NativeRegistrationError extends Error { + constructor() { + super('the device did not get a push token') + } +} + +/** + * The row's state for `slug`. `unknown` when the server did not answer, as on the web. + * + * The token is fetched even before the person is asked, because only the server's status answer + * says whether it can deliver at all (503 NATIVE_PUSH_UNAVAILABLE), and a reviewer must never see a + * switch that fails. + */ +export async function readNativeStatus(slug: string): Promise { + const env = { native: true as const, pushEnabled: NATIVE_PUSH_ENABLED } + if (!NATIVE_PUSH_ENABLED) + return derivePushStatus({ ...env, available: false, permission: 'prompt', hasRoomSubscription: false }) + const host = loadHost() + const transport = nativeTransport() + const permission = host ? await (await host).push.permission() : null + const token = transport && permission ? await deviceToken() : null + if (!transport || !permission || !token) + return derivePushStatus({ ...env, available: false, permission: 'prompt', hasRoomSubscription: false }) + + const identity = readIdentity(slug) + // A tokenless identity cannot prove membership; the row offers to pick a name again. + if (!identity?.token) return derivePushStatus({ ...env, available: true, permission, hasRoomSubscription: false }) + try { + const { subscribed } = await api.push.status(slug, { + transport, + token, + memberId: identity.memberId, + memberToken: identity.token, + }) + return derivePushStatus({ ...env, available: true, permission, hasRoomSubscription: subscribed }) + } catch (error) { + if (isUnavailable(error)) + return derivePushStatus({ ...env, available: false, permission, hasRoomSubscription: false }) + return 'unknown' + } +} + +/** As on the web, a refusal is an answer, not a failure. A dismissed dialog leaves `prompt`. */ +export type NativeAddOutcome = { status: 'subscribed' } | { status: 'denied'; permission: 'denied' | 'prompt' | null } + +/** + * Turns one room on: ask the OS (THE only requestPermissions() call, reachable only from the + * per-room tap), get the token, register it for the room, and remember which room the + * notification key opens. + */ +export async function addNativeRoomSubscription( + slug: string, + memberId: string, + memberToken: string +): Promise { + const generation = identityGeneration(slug) + const assertCurrentIdentity = () => { + if (identityGeneration(slug) !== generation) throw new Error('room identity changed during notification setup') + } + const host = loadHost() + const transport = nativeTransport() + if (!host || !transport) throw new NativeRegistrationError() + const { push } = await host + + // Granted already: the plugin answers without a dialog, so later rooms take one tap. + const permission = await push.requestPermission() + if (permission !== 'granted') return { status: 'denied', permission } + assertCurrentIdentity() + + const token = await deviceToken() + if (!token) throw new NativeRegistrationError() + assertCurrentIdentity() + + await api.push.subscribe(slug, { transport, token, memberId, memberToken }) + try { + assertCurrentIdentity() + } catch (error) { + // Forget may have deleted the row before this POST committed. + await api.push.unsubscribe(slug, { transport, token, memberId, memberToken }).catch(() => {}) + throw error + } + + // The payload names the room by its analyticsKey only. The key is known here because the room + // screen has loaded its state; without it a tap opens the rooms home, never a wrong room. + const room = (roomProps(slug) as { room?: unknown }).room + if (typeof room === 'string') writePushRoom(room, slug) + return { status: 'subscribed' } +} + +/** The per-room switch turned off. Throws when the server refuses, so the row only reads off once the row is gone. */ +async function deleteNativeRoomSubscription(slug: string, memberId: string, memberToken: string): Promise { + const transport = nativeTransport() + const token = await deviceToken() + if (!transport || !token) throw new NativeRegistrationError() + await api.push.unsubscribe(slug, { transport, token, memberId, memberToken }) + removePushRoom(slug) + announceChange() +} + +/** + * Leave or forget a room in the app (`dropRoomSubscription` in `use-push.ts` routes here). The local + * entry goes first and synchronously: the leave flow hard-reloads right after, and the room is + * forgotten whether or not the network call finishes. A room this install never subscribed costs + * no registration and no request. + */ +export async function dropNativeRoomSubscription(slug: string, memberId: string, memberToken: string): Promise { + if (!hasPushRoom(slug)) return + removePushRoom(slug) + const transport = nativeTransport() + const token = await deviceToken() + if (transport && token) await api.push.unsubscribe(slug, { transport, token, memberId, memberToken }) + announceChange() +} + +export function useNativePush(slug: string): PushControls { + // With push compiled out the row is hidden from the first render: no loader, no request. + const [settled, setSettled] = useState(NATIVE_PUSH_ENABLED ? null : 'unsupported') + const [busy, setBusy] = useState(false) + const [error, setError] = useState(null) + const mounted = useRef(true) + const busyRef = useRef(false) + const revision = useRef(0) + const identity = readIdentity(slug) + const scope = `${slug}\0${identity?.memberId ?? ''}\0${identity?.token ?? ''}` + const scopeRef = useRef(scope) + const operationId = useRef(0) + if (scopeRef.current !== scope) { + scopeRef.current = scope + busyRef.current = false + revision.current += 1 + operationId.current += 1 + } + + useEffect(() => { + mounted.current = true + return () => { + mounted.current = false + } + }, []) + + useEffect(() => { + if (!NATIVE_PUSH_ENABLED) return + let cancelled = false + const refresh = async () => { + setBusy(activeMutation !== null) + if (activeMutation !== null || busyRef.current) return + const requestRevision = ++revision.current + const next = await readNativeStatus(slug) + if (!cancelled && !busyRef.current && requestRevision === revision.current) setSettled(next) + } + const onRefresh = () => void refresh() + // The person may have changed the permission in the phone's Settings while away. + const onVisible = () => { + if (document.visibilityState === 'visible') onRefresh() + } + const onStorage = (event: StorageEvent) => { + if (event.key === null || event.key === memberStorageKey(slug) || event.key === roomUpdatesStorageKey(slug)) + onRefresh() + } + setError(null) + setSettled(null) + onRefresh() + window.addEventListener(PUSH_ROOMS_CHANGE_EVENT, onRefresh) + window.addEventListener('storage', onStorage) + document.addEventListener('visibilitychange', onVisible) + return () => { + cancelled = true + window.removeEventListener(PUSH_ROOMS_CHANGE_EVENT, onRefresh) + window.removeEventListener('storage', onStorage) + document.removeEventListener('visibilitychange', onVisible) + } + }, [slug, identity?.memberId, identity?.token]) + + /** Runs one change under the module lock; `undefined` means it did not run or went stale. */ + const mutate = useCallback( + async (change: () => Promise): Promise => { + if (busyRef.current || activeMutation !== null) return undefined + const mutation = Symbol() + activeMutation = mutation + busyRef.current = true + revision.current += 1 + const id = ++operationId.current + const current = () => mounted.current && scopeRef.current === scope && operationId.current === id + setBusy(true) + setError(null) + try { + const result = await change() + return current() ? result : undefined + } catch (err) { + if (current()) { + setError(err) + // No token, or no server credentials: hide the row rather than offer it again. + if (err instanceof NativeRegistrationError || isUnavailable(err)) setSettled('unsupported') + } + return undefined + } finally { + if (activeMutation === mutation) activeMutation = null + if (current()) { + busyRef.current = false + setBusy(false) + } + announceChange() + } + }, + [scope] + ) + + const subscribe = useCallback( + async (memberId: string, memberToken: string): Promise => { + const outcome = await mutate(() => addNativeRoomSubscription(slug, memberId, memberToken)) + if (!outcome) return 'failed' + if (outcome.status === 'subscribed') { + completeRoomUpdates(slug) + setSettled('subscribed') + } else setSettled(outcome.permission === 'denied' ? 'denied' : 'default') + return outcome.status + }, + [mutate, slug] + ) + + const unsubscribe = useCallback( + async (memberId: string, memberToken: string): Promise => { + const done = await mutate(async () => { + await deleteNativeRoomSubscription(slug, memberId, memberToken) + return true + }) + if (!done) return false + muteRoomUpdates(slug) + setSettled('default') + return true + }, + [mutate, slug] + ) + + return { status: busy || settled === null ? 'pending' : settled, error, subscribe, unsubscribe } +} diff --git a/apps/web/src/lib/native/version-gate.test.ts b/apps/web/src/lib/native/version-gate.test.ts new file mode 100644 index 00000000..541c6991 --- /dev/null +++ b/apps/web/src/lib/native/version-gate.test.ts @@ -0,0 +1,124 @@ +import { describe, expect, it } from 'vitest' +import { siteUrl } from '../site' +import { fetchGateStoreUrl, gateFallbackUrl, shouldBlock } from './version-gate' + +const STORE = { + ios: 'https://apps.apple.com/app/id123', + android: 'https://play.google.com/store/apps/details?id=com.peanutsplit.app', +} +const config = { minBuild: { ios: 500, android: 400 }, store: STORE } + +const respondWith = + (body: string, status = 200) => + async () => + new Response(body, { status, headers: { 'content-type': 'application/json' } }) + +describe('shouldBlock', () => { + it('blocks a build below the minimum', () => { + expect(shouldBlock(config, 'ios', 499)).toBe(true) + expect(shouldBlock(config, 'android', 1)).toBe(true) + }) + + it('lets a build equal to the minimum run', () => { + expect(shouldBlock(config, 'ios', 500)).toBe(false) + expect(shouldBlock(config, 'android', 400)).toBe(false) + }) + + it('lets a build above the minimum run', () => { + expect(shouldBlock(config, 'ios', 501)).toBe(false) + }) + + it('never blocks an unknown platform', () => { + expect(shouldBlock(config, 'web', 0)).toBe(false) + expect(shouldBlock({ ...config, minBuild: { ios: 500 } }, 'android', 1)).toBe(false) + }) + + it('fails open on missing or malformed fields', () => { + expect(shouldBlock(null, 'ios', 1)).toBe(false) + expect(shouldBlock('nope', 'ios', 1)).toBe(false) + expect(shouldBlock({}, 'ios', 1)).toBe(false) + expect(shouldBlock({ minBuild: { ios: '500' }, store: STORE }, 'ios', 1)).toBe(false) + // No store URL means no way to update, so the screen would be a wall. + expect(shouldBlock({ minBuild: { ios: 500 } }, 'ios', 1)).toBe(false) + expect(shouldBlock({ minBuild: { ios: 500 }, store: { ios: 'javascript:alert(1)' } }, 'ios', 1)).toBe(false) + expect(shouldBlock(config, 'ios', Number.NaN)).toBe(false) + }) +}) + +describe('fetchGateStoreUrl', () => { + it('returns the platform store URL when the build is below the minimum', async () => { + expect(await fetchGateStoreUrl(respondWith(JSON.stringify(config)), 'ios', 10)).toBe(STORE.ios) + expect(await fetchGateStoreUrl(respondWith(JSON.stringify(config)), 'android', 10)).toBe(STORE.android) + }) + + it('returns null for an equal or newer build', async () => { + expect(await fetchGateStoreUrl(respondWith(JSON.stringify(config)), 'ios', 500)).toBeNull() + expect(await fetchGateStoreUrl(respondWith(JSON.stringify(config)), 'ios', 900)).toBeNull() + }) + + it('returns null for bad JSON', async () => { + expect(await fetchGateStoreUrl(respondWith('{"minBuild":'), 'ios', 1)).toBeNull() + }) + + it('returns null for missing fields', async () => { + expect(await fetchGateStoreUrl(respondWith('{}'), 'ios', 1)).toBeNull() + expect(await fetchGateStoreUrl(respondWith(JSON.stringify({ minBuild: { ios: 500 } })), 'ios', 1)).toBeNull() + }) + + it('returns null when the fetch rejects or the server errors', async () => { + const offline = async (): Promise => { + throw new TypeError('Failed to fetch') + } + expect(await fetchGateStoreUrl(offline, 'ios', 1)).toBeNull() + expect(await fetchGateStoreUrl(respondWith(JSON.stringify(config), 503), 'ios', 1)).toBeNull() + }) + + it('returns null for an unknown platform or build', async () => { + expect(await fetchGateStoreUrl(respondWith(JSON.stringify(config)), 'web', 1)).toBeNull() + expect(await fetchGateStoreUrl(respondWith(JSON.stringify(config)), 'ios', null)).toBeNull() + }) +}) + +describe('gateFallbackUrl', () => { + const origin = (url: string) => new URL(url).origin + + it('opens the canonical room link from a room', () => { + const url = gateFallbackUrl('/room/', '?slug=ski-trip-kunc-syrup-drum') + expect(url).toBe(`${siteUrl}/r/ski-trip-kunc-syrup-drum`) + expect(origin(url)).toBe(siteUrl) + }) + + it('opens the canonical room link from a room import', () => { + const url = gateFallbackUrl('/room/import/', '?slug=ski-trip-kunc-syrup-drum&step=2') + expect(url).toBe(`${siteUrl}/r/ski-trip-kunc-syrup-drum`) + expect(origin(url)).toBe(siteUrl) + }) + + it('keeps a strange slug inside one path segment', () => { + const url = gateFallbackUrl('/room/', '?slug=../../evil?x=1') + expect(origin(url)).toBe(siteUrl) + expect(new URL(url).pathname.startsWith('/r/')).toBe(true) + expect(new URL(url).pathname.split('/')).toHaveLength(3) + }) + + it('opens the web rooms home from any other screen', () => { + for (const [pathname, search] of [ + ['/app/', ''], + ['/new/', ''], + ['/', ''], + ['/import/', '?slug=ski-trip-kunc-syrup-drum'], + ['/room/', ''], + ]) { + const url = gateFallbackUrl(pathname, search) + expect(url).toBe(`${siteUrl}/app`) + expect(origin(url)).toBe(siteUrl) + } + }) + + it('never returns a store host', () => { + for (const url of [gateFallbackUrl('/room/', '?slug=a-b'), gateFallbackUrl('/app/', '')]) { + expect(['apps.apple.com', 'play.google.com']).not.toContain(new URL(url).hostname) + expect(origin(url)).toBe(siteUrl) + } + }) +}) diff --git a/apps/web/src/lib/native/version-gate.ts b/apps/web/src/lib/native/version-gate.ts new file mode 100644 index 00000000..bd437dba --- /dev/null +++ b/apps/web/src/lib/native/version-gate.ts @@ -0,0 +1,111 @@ +import { apiUrl, nativePlatform } from '../platform' +import { productUrl, siteUrl } from '../site' +import { loadHost } from './host' + +type Platform = 'ios' | 'android' | 'web' + +/** A slow network must never hold the app on an old screen; after this the check gives up. */ +const FETCH_TIMEOUT_MS = 4_000 +/** Resume checks are cheap but not free: one per 10 minutes is enough for an escape hatch. */ +const RESUME_INTERVAL_MS = 10 * 60 * 1_000 + +function storeUrlFor(config: unknown, platform: Platform): string | null { + if (platform === 'web' || typeof config !== 'object' || config === null) return null + const store = (config as { store?: unknown }).store + if (typeof store !== 'object' || store === null) return null + const url = (store as Record)[platform] + return typeof url === 'string' && url.startsWith('https://') ? url : null +} + +function minBuildFor(config: unknown, platform: Platform): number | null { + if (platform === 'web' || typeof config !== 'object' || config === null) return null + const minBuild = (config as { minBuild?: unknown }).minBuild + if (typeof minBuild !== 'object' || minBuild === null) return null + const value = (minBuild as Record)[platform] + return typeof value === 'number' && Number.isFinite(value) ? value : null +} + +/** + * True when `config` (public/app-config.json) says this build is too old for `platform`. Fails + * open: anything it cannot read lets the app run. A config without a store URL for the platform + * also lets the app run, because the update screen would have no way to update. + */ +export function shouldBlock(config: unknown, platform: Platform, build: number): boolean { + const minBuild = minBuildFor(config, platform) + if (minBuild === null || storeUrlFor(config, platform) === null) return false + return Number.isFinite(build) && build < minBuild +} + +/** + * The web URL that "Open in browser" opens from the update screen, for the screen the person + * was on: the canonical room link from a room, else the web rooms home. Never a store URL: the + * web room is always complete, so an old build must never wall someone off from a room. + */ +export function gateFallbackUrl(pathname: string, search: string): string { + const onRoom = pathname === '/room/' || pathname === '/room' || pathname.startsWith('/room/import') + const slug = onRoom ? new URLSearchParams(search).get('slug') : null + // Built from productUrl('/r/') with URL resolution, so the slug is encoded as one path segment. + if (slug) return new URL(encodeURIComponent(slug), productUrl('/r/')).href + return `${siteUrl}/app` +} + +/** + * Fetches the version config and returns the store URL to show when this build must update, or + * null to let the app run. Every failure (network, timeout, HTTP error, bad JSON, missing fields, + * unknown platform or build) returns null: offline use is never blocked. + */ +export async function fetchGateStoreUrl( + fetchConfig: (url: string, init: RequestInit) => Promise, + platform: Platform, + build: number | null +): Promise { + if (build === null || platform === 'web') return null + try { + const response = await fetchConfig(apiUrl('/app-config.json'), { + cache: 'no-store', + signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), + }) + if (!response.ok) return null + const config: unknown = await response.json() + return shouldBlock(config, platform, build) ? storeUrlFor(config, platform) : null + } catch { + return null + } +} + +// The gate state lives at module level so NativeLinks (resume) and VersionGate (render) share it +// without a context provider. +let storeUrl: string | null = null +let lastCheckAt = 0 +const listeners = new Set<(url: string | null) => void>() + +async function runCheck(): Promise { + lastCheckAt = Date.now() + const build = (await loadHost()?.then((host) => host.app.getBuildNumber())) ?? null + const next = await fetchGateStoreUrl(fetch, nativePlatform(), build) + if (next === storeUrl) return + storeUrl = next + listeners.forEach((listener) => listener(next)) +} + +/** + * Fetches the version config again, at most once per 10 minutes. NativeLinks calls it when the + * app resumes; VersionGate runs the first check on boot through subscribeVersionGate. + */ +export function checkVersionNow(): void { + if (Date.now() - lastCheckAt < RESUME_INTERVAL_MS) return + void runCheck() +} + +/** + * Calls `listener` with the store URL whenever the gate opens or closes, and runs the boot check + * once. Returns a disposer. + */ +export function subscribeVersionGate(listener: (url: string | null) => void): () => void { + listeners.add(listener) + if (lastCheckAt === 0) void runCheck() + else listener(storeUrl) + return () => { + listeners.delete(listener) + } +} diff --git a/apps/web/src/lib/platform.test.ts b/apps/web/src/lib/platform.test.ts new file mode 100644 index 00000000..66c71ef0 --- /dev/null +++ b/apps/web/src/lib/platform.test.ts @@ -0,0 +1,82 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { apiUrl, IS_NATIVE_APP, RECAP_AVAILABLE, roomPath } from './platform' + +const SLUG = 'ski-trip-kunc-syrup-drum' + +/** The native branch is chosen at module load, so each native case loads a fresh copy of the module. */ +async function loadNative(baseUrl = 'https://peanutsplit.com') { + vi.stubEnv('NEXT_PUBLIC_NATIVE_BUILD', '1') + vi.stubEnv('NEXT_PUBLIC_BASE_URL', baseUrl) + vi.resetModules() + return import('./platform') +} + +afterEach(() => { + vi.unstubAllEnvs() + vi.resetModules() +}) + +describe('platform on web', () => { + it('is not the app', () => { + expect(IS_NATIVE_APP).toBe(false) + expect(RECAP_AVAILABLE).toBe(true) + }) + + it('builds the room paths the web has always used', () => { + expect(roomPath(SLUG)).toBe(`/r/${SLUG}`) + expect(roomPath(SLUG, 'import')).toBe(`/r/${SLUG}/import`) + expect(roomPath(SLUG, 'room', 'add=1')).toBe(`/r/${SLUG}?add=1`) + expect(roomPath(SLUG, 'room', 'settings=1')).toBe(`/r/${SLUG}?settings=1`) + expect(roomPath(SLUG, 'import', 'step=2')).toBe(`/r/${SLUG}/import?step=2`) + }) + + it('leaves API paths same-origin', () => { + expect(apiUrl('/api/rooms')).toBe('/api/rooms') + expect(apiUrl(`/r/${SLUG}/recap/card`)).toBe(`/r/${SLUG}/recap/card`) + }) +}) + +describe('platform in the app', () => { + it('is the app and hides the recap page', async () => { + const native = await loadNative() + expect(native.IS_NATIVE_APP).toBe(true) + expect(native.RECAP_AVAILABLE).toBe(false) + }) + + it('puts the slug in the query of the two static room routes', async () => { + const native = await loadNative() + expect(native.roomPath(SLUG)).toBe(`/room/?slug=${SLUG}`) + expect(native.roomPath(SLUG, 'import')).toBe(`/room/import/?slug=${SLUG}`) + expect(native.roomPath(SLUG, 'room', 'add=1')).toBe(`/room/?slug=${SLUG}&add=1`) + expect(native.roomPath(SLUG, 'import', 'step=2')).toBe(`/room/import/?slug=${SLUG}&step=2`) + }) + + it('sends API paths to the configured site origin', async () => { + const production = await loadNative() + expect(production.apiUrl('/api/rooms')).toBe('https://peanutsplit.com/api/rooms') + + const loopback = await loadNative('http://localhost:3100') + expect(loopback.apiUrl('/api/rooms/x/state')).toBe('http://localhost:3100/api/rooms/x/state') + }) + + it('enables push UI only with its own flag', async () => { + expect((await loadNative()).NATIVE_PUSH_ENABLED).toBe(false) + vi.stubEnv('NEXT_PUBLIC_NATIVE_PUSH', '1') + expect((await loadNative()).NATIVE_PUSH_ENABLED).toBe(true) + }) +}) + +describe('nativePlatform', () => { + afterEach(() => { + delete (globalThis as { Capacitor?: unknown }).Capacitor + }) + + it('reads the bridge at call time', async () => { + const { nativePlatform } = await import('./platform') + expect(nativePlatform()).toBe('web') + ;(globalThis as { Capacitor?: unknown }).Capacitor = { getPlatform: () => 'ios' } + expect(nativePlatform()).toBe('ios') + ;(globalThis as { Capacitor?: unknown }).Capacitor = { getPlatform: () => 'android' } + expect(nativePlatform()).toBe('android') + }) +}) diff --git a/apps/web/src/lib/platform.ts b/apps/web/src/lib/platform.ts new file mode 100644 index 00000000..a7ff6a3f --- /dev/null +++ b/apps/web/src/lib/platform.ts @@ -0,0 +1,40 @@ +import { siteUrl } from './site' + +/** Compile-time: the store-app build inlines '1', the web build '0'. Never user-agent sniffing. */ +export const IS_NATIVE_APP = process.env.NEXT_PUBLIC_NATIVE_BUILD === '1' + +/** Push UI in the app exists only once Hugo's APNs and FCM credentials do. */ +export const NATIVE_PUSH_ENABLED = IS_NATIVE_APP && process.env.NEXT_PUBLIC_NATIVE_PUSH === '1' + +type CapacitorGlobal = { Capacitor?: { getPlatform(): string } } + +/** Runtime, no import: the native bridge injects window.Capacitor. 'web' in a plain browser. */ +export const nativePlatform = (): 'ios' | 'android' | 'web' => { + const platform = (globalThis as CapacitorGlobal).Capacitor?.getPlatform() + return platform === 'ios' ? 'ios' : platform === 'android' ? 'android' : 'web' +} + +/** API and card-image URLs. Same-origin on web; the production apex in the app. */ +export const apiUrl = (path: string): string => (IS_NATIVE_APP ? `${siteUrl}${path}` : path) + +export type RoomView = 'room' | 'import' + +/** + * In-app navigation to a room. Shared links use productUrl('/r/…') instead, never this. + * + * The app has no dynamic routes (a static export cannot know the slugs), so a room lives at + * `/room/?slug=`. The parameter is named `slug`, not `s`, so the Sentry redaction can match it + * narrowly. On web the result is exactly the path the call sites built before this helper. + */ +export function roomPath(slug: string, view: RoomView = 'room', query = ''): string { + const encoded = encodeURIComponent(slug) + if (IS_NATIVE_APP) { + const base = view === 'import' ? '/room/import/' : '/room/' + return `${base}?slug=${encoded}${query ? `&${query}` : ''}` + } + const base = view === 'import' ? `/r/${encoded}/import` : `/r/${encoded}` + return query ? `${base}?${query}` : base +} + +/** The recap page reads the database on the server; the app ships without it in v1. */ +export const RECAP_AVAILABLE = !IS_NATIVE_APP diff --git a/apps/web/src/lib/providers.tsx b/apps/web/src/lib/providers.tsx index 3502ac71..2c7ffd91 100644 --- a/apps/web/src/lib/providers.tsx +++ b/apps/web/src/lib/providers.tsx @@ -74,8 +74,9 @@ export function Providers({ children }: { children: React.ReactNode }) { // before anyone opens a settings sheet. See `lib/install.ts`. captureInstallPrompt() // A shared receipt nobody came back for. Every normal exit discards it; this covers the - // ones nobody takes, so a photo cannot outlive the share that parked it. - void sweepSharedReceipt(caches) + // ones nobody takes, so a photo cannot outlive the share that parked it. WKWebView in the + // store app has no Cache Storage, and there is no share target there to park a photo. + if (typeof caches !== 'undefined') void sweepSharedReceipt(caches) }, []) // On mount and on every return to the app. Both events: `visibilitychange` covers a phone diff --git a/apps/web/src/lib/push-status.test.ts b/apps/web/src/lib/push-status.test.ts index 3564c435..c2c88f3b 100644 --- a/apps/web/src/lib/push-status.test.ts +++ b/apps/web/src/lib/push-status.test.ts @@ -4,6 +4,7 @@ import { isIOSDevice, isStandaloneDisplay, urlBase64ToUint8Array, + type NativePushEnvironment, type PushEnvironment, } from './push-status' @@ -85,6 +86,43 @@ describe('derivePushStatus', () => { }) }) +describe('derivePushStatus in the store app', () => { + /** A release build with push compiled in, a token, and server credentials, never asked. */ + const app: NativePushEnvironment = { + native: true, + pushEnabled: true, + available: true, + permission: 'prompt', + hasRoomSubscription: false, + } + const native = (overrides: Partial) => derivePushStatus({ ...app, ...overrides }) + + it('hides the row (unsupported) whenever push is compiled out, whatever else is true', () => { + expect(native({ pushEnabled: false })).toBe('unsupported') + expect(native({ pushEnabled: false, permission: 'granted', hasRoomSubscription: true })).toBe('unsupported') + expect(native({ pushEnabled: false, permission: 'denied' })).toBe('unsupported') + }) + + it('hides the row without a token or server credentials', () => { + expect(native({ available: false })).toBe('unsupported') + expect(native({ available: false, permission: 'granted', hasRoomSubscription: true })).toBe('unsupported') + }) + + it('maps the permission and the room row with push on', () => { + expect(native({})).toBe('default') + expect(native({ permission: 'denied' })).toBe('denied') + expect(native({ permission: 'denied', hasRoomSubscription: true })).toBe('denied') + expect(native({ permission: 'granted' })).toBe('default') + expect(native({ permission: 'granted', hasRoomSubscription: true })).toBe('subscribed') + }) + + it('never answers ios-needs-pwa: the app is installed by definition', () => { + for (const permission of ['prompt', 'granted', 'denied'] as const) + for (const hasRoomSubscription of [false, true]) + expect(native({ permission, hasRoomSubscription })).not.toBe('ios-needs-pwa') + }) +}) + describe('isIOSDevice', () => { it('matches iPhone and iPod user agents', () => { expect( diff --git a/apps/web/src/lib/push-status.ts b/apps/web/src/lib/push-status.ts index 90e78d0b..a8f7aa65 100644 --- a/apps/web/src/lib/push-status.ts +++ b/apps/web/src/lib/push-status.ts @@ -26,6 +26,21 @@ export type SettledPushStatus = Exclude */ export type DerivedPushStatus = Exclude +/** What a subscribe attempt produced. Mapped straight onto analytics by the + * caller, which is why "the user said no" is a return value and not an error: + * it is an answer, and nothing went wrong. */ +export type SubscribeOutcome = 'subscribed' | 'denied' | 'failed' + +/** The per-room push hook's contract, shared by the web and the app implementations. */ +export interface PushControls { + status: PushStatus + /** Last failure, untranslated. The surface turns it into a sentence with + * `useErrorMessage`; a lib module has no business holding UI copy. */ + error: unknown + subscribe: (memberId: string, memberToken: string) => Promise + unsubscribe: (memberId: string, memberToken: string) => Promise +} + export interface PushEnvironment { hasNotification: boolean hasServiceWorker: boolean @@ -49,7 +64,37 @@ export interface PushEnvironment { hasRoomSubscription: boolean } -export function derivePushStatus(env: PushEnvironment): DerivedPushStatus { +/** + * The store app's inputs. The app has no service worker or VAPID key: it asks the push plugin for + * the permission and the server for this room's row (ARCHITECTURE 10.1). + */ +export interface NativePushEnvironment { + native: true + /** `NATIVE_PUSH_ENABLED`: the build compiled the push client in. CI debug builds do not. */ + pushEnabled: boolean + /** + * The device has a token and the server can deliver to it. False after a registration error, + * the registration timeout, or `503 NATIVE_PUSH_UNAVAILABLE` (no APNs or FCM credentials yet). + */ + available: boolean + /** The plugin's permission state; `prompt` means the person has not been asked. */ + permission: 'granted' | 'denied' | 'prompt' + /** The server has a row for (this device's token, this room). */ + hasRoomSubscription: boolean +} + +/** + * Decides the row's state. In the app it is only ever `unsupported` (no row), `denied`, `default` + * or `subscribed`: the app is installed by definition, so `ios-needs-pwa` cannot apply. + */ +export function derivePushStatus(env: PushEnvironment | NativePushEnvironment): DerivedPushStatus { + if ('native' in env) { + if (!env.pushEnabled || !env.available) return 'unsupported' + if (env.permission === 'denied') return 'denied' + // As on the web, a granted permission without this room's row is an ordinary 'default'. + if (env.permission === 'granted' && env.hasRoomSubscription) return 'subscribed' + return 'default' + } if (!env.hasServiceWorker || !env.hasVapidKey) return 'unsupported' // iOS exposes the push APIs in the installed app, not necessarily in the // browser that must explain how to install it. diff --git a/apps/web/src/lib/queries.ts b/apps/web/src/lib/queries.ts index 8f5dd7a7..f5e3fc13 100644 --- a/apps/web/src/lib/queries.ts +++ b/apps/web/src/lib/queries.ts @@ -12,6 +12,7 @@ export { FALLBACK_POLL_MS, LIVE_POLL_MS, ROOM_FETCH_TIMEOUT_MS, + roomReadBlocked, useCurrencies, useModelStatus, useRoomHistory, diff --git a/apps/web/src/lib/queries/reads.offline.test.ts b/apps/web/src/lib/queries/reads.offline.test.ts new file mode 100644 index 00000000..2c048b4e --- /dev/null +++ b/apps/web/src/lib/queries/reads.offline.test.ts @@ -0,0 +1,37 @@ +import { QueryClient, QueryObserver, onlineManager } from '@tanstack/react-query' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { roomReadBlocked } from './reads' + +afterEach(() => { + onlineManager.setOnline(true) +}) + +describe('roomReadBlocked', () => { + it('treats a room read that starts after an offline event as blocked, not loading', async () => { + // Pins the React Query behaviour the room screen relies on: once the browser has fired + // `offline`, a new query pauses instead of failing, so it never reaches an error. + onlineManager.setOnline(false) + const queryFn = vi.fn().mockRejectedValue(new TypeError('Failed to fetch')) + const client = new QueryClient() + const observer = new QueryObserver(client, { queryKey: ['room', 'summer-trip'], queryFn }) + const unsubscribe = observer.subscribe(() => {}) + await new Promise((resolve) => setTimeout(resolve, 20)) + + const result = observer.getCurrentResult() + expect(queryFn).not.toHaveBeenCalled() + expect(result.error).toBeNull() + expect(result.isPending).toBe(true) + expect(result.fetchStatus).toBe('paused') + expect(roomReadBlocked(result)).toBe(true) + + unsubscribe() + client.clear() + }) + + it('keeps an ordinary first load and cached data out of the error screen', () => { + expect(roomReadBlocked({ data: undefined, error: null, fetchStatus: 'fetching' })).toBe(false) + expect(roomReadBlocked({ data: { room: {} }, error: null, fetchStatus: 'paused' })).toBe(false) + expect(roomReadBlocked({ data: { room: {} }, error: new Error('x'), fetchStatus: 'idle' })).toBe(false) + expect(roomReadBlocked({ data: undefined, error: new Error('x'), fetchStatus: 'idle' })).toBe(true) + }) +}) diff --git a/apps/web/src/lib/queries/reads.ts b/apps/web/src/lib/queries/reads.ts index c42d6ab8..d9a8c23f 100644 --- a/apps/web/src/lib/queries/reads.ts +++ b/apps/web/src/lib/queries/reads.ts @@ -1,7 +1,7 @@ 'use client' import { useCallback } from 'react' -import { queryOptions, useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/react-query' +import { type FetchStatus, queryOptions, useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/react-query' import { api } from '../api' import type { CurrencyInfo, RoomHistoryPage, RoomState } from '../api-types' import { FALLBACK_CURRENCIES } from '../money' @@ -52,6 +52,17 @@ const retryRoomRead = (failureCount: number, error: unknown): boolean => { return failureCount < 2 } +/** + * True when a room read has no data and will not get any by itself while the screen waits: it + * failed, or React Query paused it. A query that starts after the browser fired `offline` does + * not fail, it pauses (`fetchStatus: 'paused'`, still `isPending`, no error) until `online`. + * Without this the room would show its skeleton, with no Retry and no way back, for as long as + * the person stays offline. The paused query resumes by itself once the network returns. + */ +export function roomReadBlocked(query: { data: unknown; error: unknown; fetchStatus: FetchStatus }): boolean { + return query.data === undefined && (query.error != null || query.fetchStatus === 'paused') +} + /** * One authoritative snapshot for secondary room surfaces. * diff --git a/apps/web/src/lib/realtime.ts b/apps/web/src/lib/realtime.ts index 8148dc71..6e937ee3 100644 --- a/apps/web/src/lib/realtime.ts +++ b/apps/web/src/lib/realtime.ts @@ -11,6 +11,7 @@ */ import { useEffect, useRef, useState } from 'react' +import { apiUrl } from './platform' /** First retry. Doubling from here, so a server that comes straight back is * noticed within a second. */ @@ -67,7 +68,7 @@ export function useRoomEvents(slug: string, onPoke: () => void): RoomEvents { const connect = () => { if (stopped || source) return - const stream = new EventSource(`/api/rooms/${encodeURIComponent(slug)}/events`) + const stream = new EventSource(apiUrl(`/api/rooms/${encodeURIComponent(slug)}/events`)) source = stream stream.onopen = () => { diff --git a/apps/web/src/lib/recap.test.ts b/apps/web/src/lib/recap.test.ts new file mode 100644 index 00000000..56367343 --- /dev/null +++ b/apps/web/src/lib/recap.test.ts @@ -0,0 +1,25 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { recapImagePath, recapPath } from './recap' + +const SLUG = 'ski-trip-kunc-syrup-drum' + +afterEach(() => { + vi.unstubAllEnvs() + vi.resetModules() +}) + +describe('recap paths', () => { + it('keeps the web card path relative and unchanged', () => { + expect(recapImagePath(SLUG)).toBe(`/r/${SLUG}/recap/card`) + expect(recapPath(SLUG)).toBe(`/r/${SLUG}/recap`) + }) + + it('puts the card on the site origin in the app, whose bundle has no card route', async () => { + vi.stubEnv('NEXT_PUBLIC_NATIVE_BUILD', '1') + vi.stubEnv('NEXT_PUBLIC_BASE_URL', 'https://peanutsplit.com') + vi.resetModules() + const native = await import('./recap') + + expect(native.recapImagePath(SLUG)).toBe(`https://peanutsplit.com/r/${SLUG}/recap/card`) + }) +}) diff --git a/apps/web/src/lib/recap.ts b/apps/web/src/lib/recap.ts index 2b75ae6d..7024c9a9 100644 --- a/apps/web/src/lib/recap.ts +++ b/apps/web/src/lib/recap.ts @@ -22,6 +22,8 @@ * revocable token — a real feature with a real surface, deliberately not V1. */ +import { apiUrl } from './platform' + /** The members-only recap screen. Not shareable — see the note above. */ export const recapPath = (slug: string): string => `/r/${slug}/recap` @@ -45,8 +47,11 @@ export const recapPath = (slug: string): string => `/r/${slug}/recap` * deck's ``. A Route Handler's path is served exactly as written, so this * one stays true across builds — and it renders the same art, through * `server/og/recapImage.tsx`. + * + * Through `apiUrl` because the store app is served from its own bundle: a relative path there + * resolves against `capacitor://localhost`, where no card exists. On web it stays relative. */ -export const recapImagePath = (slug: string): string => `/r/${slug}/recap/card` +export const recapImagePath = (slug: string): string => apiUrl(`/r/${slug}/recap/card`) /** Which rung of the share chain actually fired. Analytics only. */ export type RecapShareTier = 'files' | 'clipboard' | 'download' diff --git a/apps/web/src/lib/recent-rooms.test.ts b/apps/web/src/lib/recent-rooms.test.ts index 708303e6..945dca9d 100644 --- a/apps/web/src/lib/recent-rooms.test.ts +++ b/apps/web/src/lib/recent-rooms.test.ts @@ -234,3 +234,31 @@ describe('recent-room persistence results', () => { expect(forgetRoom(SLUG)).toBe(false) }) }) + +describe('recent rooms in the store app', () => { + afterEach(() => { + vi.unstubAllEnvs() + vi.unstubAllGlobals() + vi.resetModules() + }) + + it('opens the most recent room on the static native route', async () => { + vi.stubEnv('NEXT_PUBLIC_NATIVE_BUILD', '1') + vi.resetModules() + const recent = await import('./recent-rooms') + vi.stubGlobal('window', { + localStorage: { + getItem: (key: string) => + key === RECENT_ROOMS_KEY ? JSON.stringify([{ slug: SLUG, name: 'Lisbon', lastSeenAt: 1 }]) : null, + setItem: () => undefined, + }, + }) + + expect(recent.mostRecentRoomPath()).toBe(`/room/?slug=${SLUG}`) + }) + + it('accepts a pasted web room link while the app runs on its own origin', () => { + expect(roomSlugFromLink(`https://peanutsplit.com/r/${SLUG}`, 'capacitor://localhost')).toBe(SLUG) + expect(roomSlugFromLink(`https://peanutsplit.com/r/${SLUG}`, 'https://localhost')).toBe(SLUG) + }) +}) diff --git a/apps/web/src/lib/recent-rooms.ts b/apps/web/src/lib/recent-rooms.ts index 3179b900..1dc4c18d 100644 --- a/apps/web/src/lib/recent-rooms.ts +++ b/apps/web/src/lib/recent-rooms.ts @@ -11,6 +11,7 @@ import { memberStorageKey } from '@/lib/identity' import { roomInstallStorageKey } from '@/lib/install-funnel' import { roomUpdatesStorageKey } from '@/lib/room-updates' +import { roomPath } from '@/lib/platform' export const RECENT_ROOMS_KEY = 'ps:recent' export const RECENT_ROOMS_LIMIT = 12 @@ -148,13 +149,13 @@ export function readRecentRooms(): RecentRoom[] { * * localStorage belongs to the browser, not to us: a person, extension or stale * build can put any string in `slug`. Keep that untrusted value out of navigation - * by applying the same permanent room-slug contract used for pasted links, then - * encode the path segment even though today's contract contains only URL-safe - * characters. + * by applying the same permanent room-slug contract used for pasted links; + * `roomPath` then encodes the slug even though today's contract contains only + * URL-safe characters. */ export function mostRecentRoomPath(): string | null { const room = readRecentRooms().find((candidate) => ROOM_SLUG.test(candidate.slug)) - return room ? `/r/${encodeURIComponent(room.slug)}` : null + return room ? roomPath(room.slug) : null } /** diff --git a/apps/web/src/lib/redact.test.ts b/apps/web/src/lib/redact.test.ts index ecffc090..2df94198 100644 --- a/apps/web/src/lib/redact.test.ts +++ b/apps/web/src/lib/redact.test.ts @@ -30,6 +30,26 @@ describe('redactRoomSlugs', () => { ) }) + it('scrubs the slug query parameter the native app’s room pages use', () => { + expect(redactRoomSlugs('capacitor://localhost/room/?slug=ski-trip-kunc-syrup-drum&add=1')).toBe( + 'capacitor://localhost/room/?slug=[slug]&add=1' + ) + expect(redactRoomSlugs('https://localhost/room/import/?slug=ski-trip-kunc-syrup-drum')).toBe( + 'https://localhost/room/import/?slug=[slug]' + ) + expect(redactRoomSlugs('https://localhost/room/?add=1&slug=ski-trip-kunc-syrup-drum#expenses')).toBe( + 'https://localhost/room/?add=1&slug=[slug]#expenses' + ) + }) + + it('scrubs any slug parameter, on purpose, even outside a room path', () => { + // Over-redacting an unrelated `slug=` loses a little debugging detail; a narrower rule + // would leak a room credential the first time a new page passes one. + expect(redactRoomSlugs('https://peanutsplit.com/blog/?slug=splitwise-alternative')).toBe( + 'https://peanutsplit.com/blog/?slug=[slug]' + ) + }) + it('leaves slug-free strings alone', () => { expect(redactRoomSlugs('/new')).toBe('/new') expect(redactRoomSlugs('/api/currencies')).toBe('/api/currencies') @@ -79,4 +99,38 @@ describe('redactTelemetryEvent', () => { breadcrumbs: [{ message: 'Navigated from /r/[slug]' }], }) }) + + it('scrubs the native app’s slug query from breadcrumbs and exception text', () => { + const capability = 'ski-trip-kunc-syrup-drum' + const event = redactTelemetryEvent({ + exception: { + values: [{ value: `Failed to load capacitor://localhost/room/?slug=${capability}&add=1` }], + }, + breadcrumbs: [ + { + message: `Navigated to /room/?slug=${capability}`, + data: { + from: 'capacitor://localhost/app/', + to: `capacitor://localhost/room/?slug=${capability}&add=1`, + url: `https://localhost/room/import/?slug=${capability}`, + }, + }, + ], + }) + + expect(JSON.stringify(event)).not.toContain(capability) + expect(event).toEqual({ + exception: { values: [{ value: 'Failed to load capacitor://localhost/room/?slug=[slug]&add=1' }] }, + breadcrumbs: [ + { + message: 'Navigated to /room/?slug=[slug]', + data: { + from: 'capacitor://localhost/app/', + to: 'capacitor://localhost/room/?slug=[slug]&add=1', + url: 'https://localhost/room/import/?slug=[slug]', + }, + }, + ], + }) + }) }) diff --git a/apps/web/src/lib/redact.ts b/apps/web/src/lib/redact.ts index 5a528b0e..dff1a65b 100644 --- a/apps/web/src/lib/redact.ts +++ b/apps/web/src/lib/redact.ts @@ -8,9 +8,17 @@ */ /** `/r/ski-trip-x7k2m9` and `/api/rooms/ski-trip-x7k2m9/expenses` — the two - * shapes a slug ever appears in. */ + * path shapes a slug appears in. The native app adds a query shape, below. */ const SLUG_PATHS = [/(\/r)\/[^/?#]+/g, /(\/api\/rooms)\/[^/?#]+/g] +/** + * The native app's static export cannot have a dynamic `/r/` route, so its room pages carry the + * slug as a query parameter instead: `capacitor://localhost/room/?slug=&add=1`. Every `slug=` + * parameter is redacted, on any path, because a stray non-room `slug=` costing a little debugging + * detail is cheaper than a room credential reaching Sentry. + */ +const SLUG_QUERY = /([?&]slug=)[^&#\s"']+/g + /** * The card query string, dropped whole. * @@ -25,6 +33,7 @@ const CARD_QUERY = /(\/card\/[a-z]+)\?[^#\s"']*/g export function redactRoomSlugs(value: string): string { let out = value for (const pattern of SLUG_PATHS) out = out.replace(pattern, '$1/[slug]') + out = out.replace(SLUG_QUERY, '$1[slug]') return out.replace(CARD_QUERY, '$1') } diff --git a/apps/web/src/lib/room-preview.test.ts b/apps/web/src/lib/room-preview.test.ts index 9dc88d1c..70b5433c 100644 --- a/apps/web/src/lib/room-preview.test.ts +++ b/apps/web/src/lib/room-preview.test.ts @@ -1,5 +1,9 @@ -import { describe, expect, it, vi } from 'vitest' -import { prewarmRoomPreview } from './room-preview' +import { existsSync } from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import { fillMetadataSegment } from 'next/dist/lib/metadata/get-metadata-route' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { prewarmRoomPreview, roomPreviewImagePath } from './room-preview' /** * The bug these cover: the app used to build `/r//opengraph-image` itself, @@ -90,3 +94,51 @@ describe('room social-preview prewarm', () => { await expect(prewarmRoomPreview('offline-room', fetcher as typeof fetch, doc)).resolves.toBe(false) }) }) + +describe('room social-preview prewarm in the app', () => { + const SLUG = 'ski-trip-kunc-syrup-drum' + const appDir = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'app') + + afterEach(() => { + vi.unstubAllEnvs() + vi.resetModules() + }) + + async function loadNative() { + vi.stubEnv('NEXT_PUBLIC_NATIVE_BUILD', '1') + vi.stubEnv('NEXT_PUBLIC_BASE_URL', 'https://peanutsplit.com') + vi.resetModules() + return import('./room-preview') + } + + it('derives the image path exactly as Next routes the room opengraph-image', () => { + // If the route moves, the hash Next derives from its location moves with it. + expect(existsSync(path.join(appDir, '(product-shell)', 'r', '[slug]', 'opengraph-image.tsx'))).toBe(true) + expect(roomPreviewImagePath(SLUG)).toBe( + fillMetadataSegment('/(product-shell)/r/[slug]', { slug: SLUG }, 'opengraph-image', false) + ) + }) + + it('fetches the room image on the site origin, opaquely, without a document to ask', async () => { + const native = await loadNative() + const calls: Array<[string, RequestInit | undefined]> = [] + const fetcher = (async (url: string, init?: RequestInit) => { + calls.push([url, init]) + return new Response(null, { status: 200 }) + }) as unknown as typeof fetch + + await expect(native.prewarmRoomPreview(SLUG, fetcher, undefined)).resolves.toBe(true) + expect(calls).toEqual([ + [`https://peanutsplit.com${roomPreviewImagePath(SLUG)}`, { mode: 'no-cors', cache: 'no-store' }], + ]) + expect(calls[0][0]).toMatch(new RegExp(`^https://peanutsplit\\.com/r/${SLUG}/opengraph-image-[0-9a-z]{6}$`)) + }) + + it('never rejects into the app when the warm fails', async () => { + const native = await loadNative() + const fetcher = (async () => { + throw new TypeError('offline') + }) as unknown as typeof fetch + await expect(native.prewarmRoomPreview(SLUG, fetcher, undefined)).resolves.toBe(false) + }) +}) diff --git a/apps/web/src/lib/room-preview.ts b/apps/web/src/lib/room-preview.ts index 964c35c9..5393e42b 100644 --- a/apps/web/src/lib/room-preview.ts +++ b/apps/web/src/lib/room-preview.ts @@ -1,15 +1,43 @@ /** * The social image attached by chat apps after they inspect a room URL. * - * The URL is deliberately not built here, and must not be. `opengraph-image.tsx` - * is a Next file convention, and Next — not this app — decides what to serve it - * under: the route group in the path earns the route a build-scoped hash suffix - * (`/r//opengraph-image-`), and the tag Next writes can carry a - * cache-busting query on top of it. Neither part is derivable from the slug, so - * the only honest source for the URL is the tag Next already put in the document. + * On web the URL is deliberately not built here. `opengraph-image.tsx` is a Next + * file convention, and Next — not this app — decides what to serve it under: the + * route group in the path earns the route a hash suffix + * (`/r//opengraph-image-`), and the tag Next writes carries a + * cache-busting query on top of it. The tag Next already put in the document is + * the exact URL a crawler will ask for, query included, so web reads that. * Hand-building `/r//opengraph-image` is what used to 404 in production. + * + * The store app has no room `` to ask: its page is a bundled file. There + * `roomPreviewImagePath` derives the path the way Next derives it (see there), and + * the warm is an opaque request through `apiUrl`. */ +import { djb2Hash } from 'next/dist/shared/lib/hash' +import { apiUrl, IS_NATIVE_APP } from './platform' + +/** + * The room route's source segment, as the app directory spells it. Next names the room's + * `opengraph-image` after a hash of exactly this string because it contains the `(product-shell)` + * route group. `room-preview.test.ts` checks that the file exists here and that Next's own route + * builder produces the same URL, so moving the route fails a test instead of warming a 404. + */ +const ROOM_SEGMENT = '/(product-shell)/r/[slug]' + +/** + * `/r//opengraph-image-`: the path Next serves the room's unfurl image at. + * + * The suffix is Next's `getMetadataRouteSuffix`: the first six base-36 digits of `djb2Hash` over + * the parent segment. It depends on the route's location in the source tree, not on the build. + * Next adds a `?` of the image file to the `` tag. That part is not derivable + * here; the route is matched on the path alone, so the request without it renders the same card. + */ +export function roomPreviewImagePath(slug: string): string { + const suffix = djb2Hash(ROOM_SEGMENT).toString(36).slice(0, 6) + return `/r/${encodeURIComponent(slug)}/opengraph-image-${suffix}` +} + /** Just enough of `Document` to find the tag and to know where it was served from. */ interface PreviewDocument { readonly baseURI: string @@ -62,7 +90,21 @@ export async function prewarmRoomPreview( fetcher: typeof fetch = globalThis.fetch, doc: PreviewDocument | undefined = globalThis.document ): Promise { - if (!slug || typeof fetcher !== 'function' || !doc) return false + if (!slug || typeof fetcher !== 'function') return false + + if (IS_NATIVE_APP) { + // `no-cors`: the image route sends no CORS header and the app does not need to read the + // bytes. The server renders the card either way, which is the warming. `no-store` keeps + // the WebView from answering the request out of its own cache instead of asking. + try { + await fetcher(apiUrl(roomPreviewImagePath(slug)), { mode: 'no-cors', cache: 'no-store' }) + return true + } catch { + return false + } + } + + if (!doc) return false const image = advertisedPreviewUrl(slug, doc) if (!image) return false diff --git a/apps/web/src/lib/save-file.test.ts b/apps/web/src/lib/save-file.test.ts new file mode 100644 index 00000000..32fde573 --- /dev/null +++ b/apps/web/src/lib/save-file.test.ts @@ -0,0 +1,86 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { saveFile } from './save-file' + +/** A stand-in for the bits of `document` and `window` the web download touches, recording what happened. */ +function webPage() { + const events: string[] = [] + const anchor = { + href: '', + download: '', + click: () => events.push(`click ${anchor.href} as ${anchor.download}`), + remove: () => events.push('removed'), + } + vi.stubGlobal('document', { + createElement: (tag: string) => (tag === 'a' ? anchor : null), + body: { append: () => events.push('appended') }, + }) + const timers: Array<() => void> = [] + vi.stubGlobal('window', { setTimeout: (run: () => void) => timers.push(run) }) + vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:split/1') + vi.spyOn(URL, 'revokeObjectURL').mockImplementation((href) => events.push(`revoked ${href}`)) + return { events, runTimers: () => timers.splice(0).forEach((run) => run()) } +} + +async function loadNative() { + vi.stubEnv('NEXT_PUBLIC_NATIVE_BUILD', '1') + vi.resetModules() + return (await import('./save-file')).saveFile +} + +afterEach(() => { + vi.unstubAllGlobals() + vi.unstubAllEnvs() + vi.restoreAllMocks() + vi.resetModules() +}) + +describe('saveFile on web', () => { + it('clicks a download link and frees the object URL only after the click', async () => { + const page = webPage() + + await expect(saveFile(new Blob(['a,b'], { type: 'text/csv' }), 'ski-trip.csv')).resolves.toBe(true) + expect(page.events).toEqual(['appended', 'click blob:split/1 as ski-trip.csv', 'removed']) + + page.runTimers() + expect(page.events.at(-1)).toBe('revoked blob:split/1') + }) +}) + +describe('saveFile in the app', () => { + it('hands the share sheet one file with the given name, type and bytes', async () => { + const save = await loadNative() + const shared: ShareData[] = [] + vi.stubGlobal('navigator', { share: async (data: ShareData) => void shared.push(data) }) + + await expect(save(new Blob(['{"a":1}'], { type: 'application/json' }), 'room-history.json')).resolves.toBe(true) + + expect(shared).toHaveLength(1) + expect(Object.keys(shared[0])).toEqual(['files']) + const [file] = shared[0].files ?? [] + expect(file.name).toBe('room-history.json') + expect(file.type).toBe('application/json') + expect(await file.text()).toBe('{"a":1}') + }) + + it('treats a closed share sheet as a decision, not a failure', async () => { + const save = await loadNative() + vi.stubGlobal('navigator', { + share: async () => { + throw new DOMException('closed', 'AbortError') + }, + }) + + await expect(save(new Blob(['x']), 'room.csv')).resolves.toBe(false) + }) + + it('rejects when the share itself fails, so the caller can say so', async () => { + const save = await loadNative() + vi.stubGlobal('navigator', { + share: async () => { + throw new Error('cache write failed') + }, + }) + + await expect(save(new Blob(['x']), 'room.csv')).rejects.toThrow('cache write failed') + }) +}) diff --git a/apps/web/src/lib/save-file.ts b/apps/web/src/lib/save-file.ts new file mode 100644 index 00000000..7e15bf52 --- /dev/null +++ b/apps/web/src/lib/save-file.ts @@ -0,0 +1,41 @@ +'use client' + +/** + * Hand a generated file to the person: the room export, the history export, an image card. + * + * On web this is the `` click the call sites used to repeat, unchanged. The store app + * cannot do that: WKWebView ignores `download`, so the click would save nothing. There the file goes + * to `navigator.share({ files })`, which the native polyfill (`src/lib/native/polyfills.ts`) serves + * by writing the file to the app cache and opening the system share sheet, where "Save to Files" + * and every other target live. This module deliberately imports nothing from `src/lib/native`, so + * the web bundle never reaches the native code through it. + * + * Resolves `true` when the file was handed over and `false` when the person closed the share sheet. + * Closing the sheet is a decision, not a failure, so it never rejects for that. Any other share + * error rejects, so the caller can say the save failed. + */ + +import { IS_NATIVE_APP } from './platform' + +export async function saveFile(blob: Blob, filename: string): Promise { + if (IS_NATIVE_APP) { + try { + await navigator.share({ files: [new File([blob], filename, { type: blob.type })] }) + return true + } catch (error) { + if (error instanceof DOMException && error.name === 'AbortError') return false + throw error + } + } + + const href = URL.createObjectURL(blob) + const anchor = document.createElement('a') + anchor.href = href + anchor.download = filename + document.body.append(anchor) + anchor.click() + anchor.remove() + // Firefox may still be consuming the object URL when click() returns. + window.setTimeout(() => URL.revokeObjectURL(href), 0) + return true +} diff --git a/apps/web/src/lib/share-card.test.ts b/apps/web/src/lib/share-card.test.ts index cafcacd4..c0667ba1 100644 --- a/apps/web/src/lib/share-card.test.ts +++ b/apps/web/src/lib/share-card.test.ts @@ -3,8 +3,13 @@ import { shareImageFile } from './share-card' afterEach(() => { vi.unstubAllGlobals() + vi.unstubAllEnvs() + vi.restoreAllMocks() + vi.resetModules() }) +const card = () => new File([new Uint8Array([0x89, 0x50, 0x4e, 0x47])], 'crew.png', { type: 'image/png' }) + describe('public card sharing', () => { it('hands the native sheet one image and no room-link-capable fields', async () => { const file = new File([new Uint8Array([0x89, 0x50, 0x4e, 0x47])], 'crew.png', { @@ -28,3 +33,46 @@ describe('public card sharing', () => { expect(payload).not.toHaveProperty('title') }) }) + +describe('the download floor', () => { + it('on web, saves the card through a download link when share and clipboard are missing', async () => { + vi.stubGlobal('navigator', {}) + const clicked: string[] = [] + const anchor = { href: '', download: '', click: () => clicked.push(anchor.download), remove: () => {} } + vi.stubGlobal('document', { createElement: () => anchor, body: { append: () => {} } }) + vi.stubGlobal('window', { setTimeout: () => 0 }) + vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:split/card') + + await expect(shareImageFile(card())).resolves.toBe('download') + expect(clicked).toEqual(['crew.png']) + }) + + it('in the app, a closed share sheet on the floor is no share at all', async () => { + vi.stubEnv('NEXT_PUBLIC_NATIVE_BUILD', '1') + vi.resetModules() + const native = await import('./share-card') + // canShare says no (the files rung is skipped); the floor's share sheet is then closed. + vi.stubGlobal('navigator', { + canShare: () => false, + share: async () => { + throw new DOMException('closed', 'AbortError') + }, + }) + + await expect(native.shareImageFile(card())).resolves.toBeNull() + }) + + it('in the app, the floor hands the card to the share sheet as a file', async () => { + vi.stubEnv('NEXT_PUBLIC_NATIVE_BUILD', '1') + vi.resetModules() + const native = await import('./share-card') + const shared: File[] = [] + vi.stubGlobal('navigator', { + canShare: () => false, + share: async (data: ShareData) => void shared.push(...(data.files ?? [])), + }) + + await expect(native.shareImageFile(card())).resolves.toBe('download') + expect(shared.map((file) => [file.name, file.type])).toEqual([['crew.png', 'image/png']]) + }) +}) diff --git a/apps/web/src/lib/share-card.ts b/apps/web/src/lib/share-card.ts index f76f0644..3d37f63a 100644 --- a/apps/web/src/lib/share-card.ts +++ b/apps/web/src/lib/share-card.ts @@ -11,6 +11,7 @@ import { useEffect, useState } from 'react' import { copyImage } from '@/lib/clipboard' import type { RecapShareTier } from '@/lib/recap' +import { saveFile } from '@/lib/save-file' /** * Fetch the PNG on mount and keep the `File`. @@ -95,11 +96,10 @@ export async function shareImageFile(file: File): Promise if (await copyImage(file)) return 'clipboard' - const objectUrl = URL.createObjectURL(file) - const anchor = document.createElement('a') - anchor.href = objectUrl - anchor.download = file.name - anchor.click() - URL.revokeObjectURL(objectUrl) - return 'download' + try { + return (await saveFile(file, file.name)) ? 'download' : null + } catch { + // Only the app's share sheet can fail here. Every rung is spent; the card stays on screen. + return null + } } diff --git a/apps/web/src/lib/splash.test.ts b/apps/web/src/lib/splash.test.ts index 6d2d4cc0..81d30c0b 100644 --- a/apps/web/src/lib/splash.test.ts +++ b/apps/web/src/lib/splash.test.ts @@ -36,16 +36,16 @@ describe('iOS launch screens', () => { * include list stops covering a folder that did not exist when it was written, and the symptom * — an asset silently missing offline — is invisible until someone is on a train. So the shape * of `public/` is pinned here: add a folder, and this fails until it is either added to the - * patterns or deliberately recorded as online-only. `dev/` and `press/` are the latter: an - * internal static quiz and downloadable distribution assets are not part of the installable - * app shell. + * patterns or deliberately recorded as online-only. `.well-known/`, `dev/` and `press/` are + * the latter: the app-link association files, an internal static quiz and downloadable + * distribution assets are not part of the installable app shell. */ it('keeps every public folder either precached or explicitly online-only', () => { const folders = readdirSync(path.join(WEB, 'public'), { withFileTypes: true }) .filter((entry) => entry.isDirectory()) .map((entry) => entry.name) .sort() - expect(folders).toEqual(['dev', 'doodles', 'fonts', 'icons', 'install', 'press']) + expect(folders).toEqual(['.well-known', 'dev', 'doodles', 'fonts', 'icons', 'install', 'press']) expect(readFileSync(path.join(WEB, 'next.config.js'), 'utf8')).toContain("'install/*.svg'") }) }) diff --git a/apps/web/src/lib/store-app.test.ts b/apps/web/src/lib/store-app.test.ts new file mode 100644 index 00000000..7f05a59e --- /dev/null +++ b/apps/web/src/lib/store-app.test.ts @@ -0,0 +1,88 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { appStoreUrlFor, smartAppBannerContent, storeAppUrl } from './store-app' + +const IPHONE = { + userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) Version/17.5 Safari/604.1', + platform: 'iPhone', + maxTouchPoints: 5, +} +const IPAD_AS_MAC = { + userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Version/17.5 Safari/605.1.15', + platform: 'MacIntel', + maxTouchPoints: 5, +} +const MAC = { ...IPAD_AS_MAC, maxTouchPoints: 0 } +const ANDROID = { + userAgent: 'Mozilla/5.0 (Linux; Android 14; Pixel 8 Pro) AppleWebKit/537.36 Chrome/127.0 Mobile Safari/537.36', + platform: 'Linux armv8l', + maxTouchPoints: 5, +} +const DESKTOP = { + userAgent: 'Mozilla/5.0 (X11; Linux x86_64) Chrome/127.0', + platform: 'Linux x86_64', + maxTouchPoints: 0, +} + +const onDevice = (navigator: typeof IPHONE) => vi.stubGlobal('window', { navigator }) + +afterEach(() => { + vi.unstubAllGlobals() + vi.unstubAllEnvs() +}) + +describe('appStoreUrlFor', () => { + it('links an Apple touch device to the listing', () => { + expect(appStoreUrlFor(true, '6740000000')).toBe('https://apps.apple.com/app/id6740000000') + }) + + it('offers nothing off Apple or without an ID', () => { + expect(appStoreUrlFor(false, '6740000000')).toBeNull() + expect(appStoreUrlFor(true, null)).toBeNull() + }) +}) + +describe('storeAppUrl', () => { + it('answers the listing on an iPhone and an iPad when the ID is set', () => { + vi.stubEnv('NEXT_PUBLIC_IOS_APP_STORE_ID', '6740000000') + onDevice(IPHONE) + expect(storeAppUrl()).toBe('https://apps.apple.com/app/id6740000000') + onDevice(IPAD_AS_MAC) + expect(storeAppUrl()).toBe('https://apps.apple.com/app/id6740000000') + }) + + it('answers null on Android, a Mac and desktop even with the ID set', () => { + vi.stubEnv('NEXT_PUBLIC_IOS_APP_STORE_ID', '6740000000') + for (const device of [ANDROID, MAC, DESKTOP]) { + onDevice(device) + expect(storeAppUrl()).toBeNull() + } + }) + + it('answers null on an iPhone while the ID is unset or malformed', () => { + onDevice(IPHONE) + for (const id of ['', ' 6740000000', 'id6740000000', '674, app-argument=https://evil.example']) { + vi.stubEnv('NEXT_PUBLIC_IOS_APP_STORE_ID', id) + expect(storeAppUrl()).toBeNull() + } + }) + + it('answers null on the server', () => { + vi.stubEnv('NEXT_PUBLIC_IOS_APP_STORE_ID', '6740000000') + expect(typeof window).toBe('undefined') + expect(storeAppUrl()).toBeNull() + }) +}) + +describe('smartAppBannerContent', () => { + it('names the app and hands it the canonical room link', () => { + vi.stubEnv('NEXT_PUBLIC_IOS_APP_STORE_ID', '6740000000') + expect(smartAppBannerContent('ski-trip-kunc-syrup-drum')).toBe( + 'app-id=6740000000, app-argument=https://peanutsplit.com/r/ski-trip-kunc-syrup-drum' + ) + }) + + it('renders nothing while the ID is unset', () => { + vi.stubEnv('NEXT_PUBLIC_IOS_APP_STORE_ID', '') + expect(smartAppBannerContent('ski-trip-kunc-syrup-drum')).toBeNull() + }) +}) diff --git a/apps/web/src/lib/store-app.ts b/apps/web/src/lib/store-app.ts new file mode 100644 index 00000000..6d9b8674 --- /dev/null +++ b/apps/web/src/lib/store-app.ts @@ -0,0 +1,45 @@ +import { CANONICAL_ORIGIN } from './domains' +import { isIOSDevice } from './push-status' + +/** + * Where the web offers the store app, and where it does not. + * + * Only iPhone and iPad browsers get the App Store. An installed Android PWA shares Chrome's storage + * for this origin, so every room and member token is already there on first launch, while the Play + * app starts empty: pointing Android at the store would cost people their rooms. Desktop has no + * store app. Everything here is off until Hugo sets `NEXT_PUBLIC_IOS_APP_STORE_ID` as a build arg. + */ + +/** + * Read as a literal property access so Next inlines it into the client bundle. An App Store ID is + * digits only; anything else is treated as unset, which also keeps the banner `` content + * free of separators a typo could inject. + */ +const configuredStoreId = (): string | null => { + const id = process.env.NEXT_PUBLIC_IOS_APP_STORE_ID + return id && /^\d+$/.test(id) ? id : null +} + +/** Pure: the App Store listing for an Apple touch device, `null` everywhere else. */ +export function appStoreUrlFor(isIOS: boolean, storeId: string | null = configuredStoreId()): string | null { + return isIOS && storeId ? `https://apps.apple.com/app/id${storeId}` : null +} + +/** + * The store link for this browser. Asks the same device question as `isIOSHere()` in + * `install.ts`; it reads the navigator itself because `install.ts` imports this file. + */ +export function storeAppUrl(): string | null { + if (typeof window === 'undefined') return null + const { userAgent, platform, maxTouchPoints } = window.navigator + return appStoreUrlFor(isIOSDevice({ userAgent, platform, maxTouchPoints })) +} + +/** + * Content of Apple's Smart App Banner tag for a room page. The `app-argument` is the canonical room + * link, because the app's link mapper accepts only that host. `null` when the store ID is unset. + */ +export function smartAppBannerContent(slug: string, storeId: string | null = configuredStoreId()): string | null { + if (!storeId) return null + return `app-id=${storeId}, app-argument=${CANONICAL_ORIGIN}/r/${encodeURIComponent(slug)}` +} diff --git a/apps/web/src/lib/use-push.ts b/apps/web/src/lib/use-push.ts index 1329503e..0b00dffe 100644 --- a/apps/web/src/lib/use-push.ts +++ b/apps/web/src/lib/use-push.ts @@ -4,17 +4,21 @@ import { useCallback, useEffect, useRef, useState } from 'react' import { api } from './api' import { vapidPublicKey } from './flags' import { identityGeneration, memberStorageKey, readIdentity } from './identity' +import { dropNativeRoomSubscription, useNativePush } from './native/use-native-push' import { completeRoomUpdates, muteRoomUpdates, roomUpdatesStorageKey } from './room-updates' import { derivePushStatus, isIOSDevice, isStandaloneDisplay, urlBase64ToUint8Array, + type PushControls, type PushEnvironment, - type PushStatus, type SettledPushStatus, + type SubscribeOutcome, } from './push-status' +export type { PushControls, SubscribeOutcome } + /** * Notification opt-in for one device in ONE room. * @@ -29,11 +33,6 @@ import { * and the calls that must stay in lock-step with the server. */ -/** What a subscribe attempt produced. Mapped straight onto analytics by the - * caller, which is why "the user said no" is a return value and not an error: - * it is an answer, and nothing went wrong. */ -export type SubscribeOutcome = 'subscribed' | 'denied' | 'failed' - const PUSH_SUBSCRIPTION_CHANGE_EVENT = 'ps:push-subscription-change' // Every room and surface shares one browser endpoint. Only one control may // change it at a time, including while a permission dialog is open. @@ -43,15 +42,6 @@ const announceSubscriptionChange = (): void => { if (typeof window !== 'undefined') window.dispatchEvent?.(new Event(PUSH_SUBSCRIPTION_CHANGE_EVENT)) } -export interface PushControls { - status: PushStatus - /** Last failure, untranslated. The surface turns it into a sentence with - * `useErrorMessage`; a lib module has no business holding UI copy. */ - error: unknown - subscribe: (memberId: string, memberToken: string) => Promise - unsubscribe: (memberId: string, memberToken: string) => Promise -} - /** The synchronous half of the environment. `hasRoomSubscription` is the * server's answer, so it is passed in by whoever already asked. */ function deviceEnvironment(hasRoomSubscription: boolean): PushEnvironment { @@ -96,7 +86,12 @@ function deviceEnvironment(hasRoomSubscription: boolean): PushEnvironment { * deliver to. */ async function activeRegistration(): Promise { - if (!(await navigator.serviceWorker.getRegistration())) await navigator.serviceWorker.register('/sw.js') + // The app export has no service worker, and its postbuild check rejects any + // `serviceWorker.register` call. The inline flag comparison lets the bundler + // drop the call from that export; the web build keeps it unchanged. + if (process.env.NEXT_PUBLIC_NATIVE_BUILD !== '1' && !(await navigator.serviceWorker.getRegistration())) { + await navigator.serviceWorker.register('/sw.js') + } return await navigator.serviceWorker.ready } @@ -221,13 +216,14 @@ export async function addRoomSubscription(slug: string, memberId: string, member } /** - * Remove this device's subscription for one room. + * Remove this device's subscription for one room. In the store app it removes the device token's + * row and the room's notification-key entry instead (`native/use-native-push.ts`). * * Exported for `forget()` in `use-identity.ts`, which has to do this before it * deletes the token that authorises it. Throws when the server refuses, so the * UI only reports the room as off after its row is gone. */ -export async function dropRoomSubscription(slug: string, memberId: string, memberToken: string): Promise { +async function dropWebRoomSubscription(slug: string, memberId: string, memberToken: string): Promise { const subscription = await currentSubscription() if (!subscription) return @@ -242,7 +238,7 @@ export async function dropRoomSubscription(slug: string, memberId: string, membe announceSubscriptionChange() } -export function usePush(slug: string): PushControls { +function useWebPush(slug: string): PushControls { const [settled, setSettled] = useState(null) const [busy, setBusy] = useState(false) const [error, setError] = useState(null) @@ -407,3 +403,15 @@ export function usePush(slug: string): PushControls { return { status: busy || settled === null ? 'pending' : settled, error, subscribe, unsubscribe } } + +/** + * The store app uses native push (APNs or FCM) instead of Web Push. The constant is fixed per build, + * so a component always calls the same hook and the hook order never changes at runtime. The inline + * env literal (not IS_NATIVE_APP) lets webpack fold the choice and drop the native hook from the web + * build; see host.ts. + */ +export const usePush: (slug: string) => PushControls = + process.env.NEXT_PUBLIC_NATIVE_BUILD === '1' ? useNativePush : useWebPush + +export const dropRoomSubscription: (slug: string, memberId: string, memberToken: string) => Promise = + process.env.NEXT_PUBLIC_NATIVE_BUILD === '1' ? dropNativeRoomSubscription : dropWebRoomSubscription diff --git a/apps/web/src/lib/use-settings.test.ts b/apps/web/src/lib/use-settings.test.ts index 7f64ccd0..b0a89744 100644 --- a/apps/web/src/lib/use-settings.test.ts +++ b/apps/web/src/lib/use-settings.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { HAPTIC_MS, HAPTIC_PATTERNS, IOS_PATTERN_OFFSETS_MS } from './use-settings' +import { HAPTIC_MS, HAPTIC_PATTERNS, IOS_PATTERN_OFFSETS_MS, parseSettings, scanConsentNeeded } from './use-settings' /** * The haptic tables, asserted as data. @@ -67,3 +67,45 @@ describe('iOS pattern emulation', () => { } }) }) + +describe('stored settings', () => { + const defaults = { soundEnabled: true, hapticsEnabled: true, animationsEnabled: true, scanConsent: false } + + it('falls back to the defaults for missing, corrupt or non-object storage', () => { + expect(parseSettings(null)).toEqual(defaults) + expect(parseSettings('{not json')).toEqual(defaults) + expect(parseSettings('null')).toEqual(defaults) + }) + + it('keeps the feedback choices of someone who stored settings before AI consent existed', () => { + // The shape every device wrote before this field: no scanConsent at all. + expect(parseSettings('{"soundEnabled":false,"hapticsEnabled":true,"animationsEnabled":false}')).toEqual({ + ...defaults, + soundEnabled: false, + animationsEnabled: false, + }) + }) + + it('reads a stored consent back, and never treats a non-boolean as consent', () => { + expect(parseSettings('{"scanConsent":true}').scanConsent).toBe(true) + expect(parseSettings('{"scanConsent":false}').scanConsent).toBe(false) + expect(parseSettings('{"scanConsent":"yes"}').scanConsent).toBe(false) + expect(parseSettings('{"scanConsent":1}').scanConsent).toBe(false) + }) +}) + +describe('AI consent before a receipt scan', () => { + it('asks in the store app until the person allows it', () => { + expect(scanConsentNeeded({ scanConsent: false }, true)).toBe(true) + expect(scanConsentNeeded({ scanConsent: true }, true)).toBe(false) + }) + + it('never asks on the web, whatever is stored', () => { + expect(scanConsentNeeded({ scanConsent: false }, false)).toBe(false) + expect(scanConsentNeeded({ scanConsent: true }, false)).toBe(false) + }) + + it('follows the build: this test runs as the web build', () => { + expect(scanConsentNeeded({ scanConsent: false })).toBe(false) + }) +}) diff --git a/apps/web/src/lib/use-settings.ts b/apps/web/src/lib/use-settings.ts index bd00300c..3f9fbc8f 100644 --- a/apps/web/src/lib/use-settings.ts +++ b/apps/web/src/lib/use-settings.ts @@ -1,6 +1,7 @@ 'use client' import { useCallback, useEffect, useSyncExternalStore } from 'react' +import { IS_NATIVE_APP } from './platform' import { playSound, warmAudio, type SoundName } from './sounds' const STORAGE_KEY = 'ps:settings' @@ -9,10 +10,46 @@ export interface Settings { soundEnabled: boolean hapticsEnabled: boolean animationsEnabled: boolean + /** The person allowed receipt photos to go to the AI model. Read only in the store app. */ + scanConsent: boolean } -/** All ON — the palette is the product, and it is quiet by design. */ -const DEFAULTS: Settings = { soundEnabled: true, hapticsEnabled: true, animationsEnabled: true } +/** All feedback ON — the palette is the product, and it is quiet by design. AI consent starts OFF: + * it is only ever given by a tap. */ +const DEFAULTS: Settings = { soundEnabled: true, hapticsEnabled: true, animationsEnabled: true, scanConsent: false } + +/** + * Whether the scan must ask before the photo leaves the device. + * + * App only (Apple 5.1.2(i) asks for explicit consent before personal data goes to a third-party + * AI). The web flow keeps its passive provider note and no extra tap until Konrad decides + * otherwise (decision 8.3 #12 in the native-app plan). + */ +export function scanConsentNeeded( + settings: Pick, + nativeApp: boolean = IS_NATIVE_APP +): boolean { + return nativeApp && !settings.scanConsent +} + +/** Stored JSON to settings. Missing or non-boolean fields take the default, so a value written + * before a setting existed never turns into `false` by accident. */ +export function parseSettings(raw: string | null): Settings { + if (!raw) return DEFAULTS + try { + const parsed = JSON.parse(raw) as Partial> | null + const read = (key: keyof Settings): boolean => + typeof parsed?.[key] === 'boolean' ? (parsed[key] as boolean) : DEFAULTS[key] + return { + soundEnabled: read('soundEnabled'), + hapticsEnabled: read('hapticsEnabled'), + animationsEnabled: read('animationsEnabled'), + scanConsent: read('scanConsent'), + } + } catch { + return DEFAULTS + } +} /** * A tiny external store rather than context: the settings are read from the @@ -29,18 +66,9 @@ function hydrate(): void { if (hydrated || typeof window === 'undefined') return hydrated = true try { - const raw = window.localStorage.getItem(STORAGE_KEY) - if (!raw) return - const parsed = JSON.parse(raw) as Partial - current = { - soundEnabled: parsed.soundEnabled ?? DEFAULTS.soundEnabled, - hapticsEnabled: parsed.hapticsEnabled ?? DEFAULTS.hapticsEnabled, - // Absent for everyone who used the app before this setting existed — - // they get the default, not `false`. - animationsEnabled: parsed.animationsEnabled ?? DEFAULTS.animationsEnabled, - } + current = parseSettings(window.localStorage.getItem(STORAGE_KEY)) } catch { - // Corrupt or blocked storage just means defaults. Never throw here. + // Blocked storage just means defaults. Never throw here. } } @@ -89,7 +117,11 @@ export function useSettings() { write({ ...current, animationsEnabled: value }) }, []) - return { settings, setSoundEnabled, setHapticsEnabled, setAnimationsEnabled } + const setScanConsent = useCallback((value: boolean) => { + write({ ...current, scanConsent: value }) + }, []) + + return { settings, setSoundEnabled, setHapticsEnabled, setAnimationsEnabled, setScanConsent } } /** Semantic haptics, mapped one-to-one to the cues. Durations are deliberately diff --git a/apps/web/src/native-boundary.test.ts b/apps/web/src/native-boundary.test.ts new file mode 100644 index 00000000..148fa921 --- /dev/null +++ b/apps/web/src/native-boundary.test.ts @@ -0,0 +1,136 @@ +/** + * Source-level gates for the store app (ARCHITECTURE.md 3.2 in the native-app plan). + * + * - Capacitor code must stay behind `src/lib/native/capacitor/**`, reached through the one guarded + * dynamic import in `src/lib/native/host.ts`. An import anywhere else can pull the plugin code + * into the web bundle. + * - The app has no `/r/` route (a static export cannot know the slugs), so in-app navigation + * to a room must go through `roomPath()`. A hand-built `/r/` path still works on web and silently + * breaks navigation in the app, so the only files allowed to build one are listed below with the + * reason they are safe. + * - `NATIVE_ROUTES` (used by the link mapper) must list exactly the pages the export contains. + */ +import { readdirSync, readFileSync } from 'node:fs' +import path from 'node:path' +import { describe, expect, it } from 'vitest' +import { NATIVE_ROUTES } from '@/lib/native/links' + +const WEB_ROOT = path.resolve(__dirname, '..') +const SRC = path.join(WEB_ROOT, 'src') +const SOURCE_FILE = /\.(?:ts|tsx|js|jsx|mjs|cjs)$/ +/** Tests build `/r/` URLs as inputs and expectations; they never navigate the app. */ +const TEST_FILE = /\.test\.(?:ts|tsx)$/ + +/** Repo-relative (to apps/web), forward slashes, so messages and the allowlist read the same on every OS. */ +const relative = (file: string): string => path.relative(WEB_ROOT, file).split(path.sep).join('/') + +const walk = (dir: string): string[] => + readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { + const full = path.join(dir, entry.name) + if (entry.isDirectory()) return entry.name === 'node_modules' ? [] : walk(full) + return SOURCE_FILE.test(entry.name) ? [full] : [] + }) + +/** `file:line source` for every line that matches, so a failure points at the exact call site. */ +const offendingLines = (files: string[], pattern: RegExp): string[] => + files.flatMap((file) => + readFileSync(file, 'utf8') + .split('\n') + .flatMap((line, index) => (pattern.test(line) ? [`${relative(file)}:${index + 1} ${line.trim()}`] : [])) + ) + +// Built from parts so this file never matches its own patterns. +const CAPACITOR = '@' + 'capacitor/' +/** Static `import … from`, side-effect `import '…'`, `export … from`, dynamic `import()` and `require()`. */ +const CAPACITOR_IMPORT = new RegExp( + String.raw`(?:\bfrom\s*|\bimport\s*\(?\s*|\brequire\s*\(\s*)['"\x60]` + CAPACITOR.replace('/', '\\/') +) +const CAPACITOR_HOME = 'src/lib/native/capacitor/' + +/** `` `/r/${ `` and `'/r/' +` (either quote style). */ +const HAND_BUILT_ROOM_PATH = new RegExp(String.raw`\/r\/\$\{|['"]\/r\/['"]\s*\+`) + +/** + * The exact files that may build a `/r/` path, each for a reason that holds in the app. + * Add a file here only with that reason; anything else uses `roomPath()` or `productUrl('/r/…')` in + * one of these files. + */ +const ROOM_PATH_ALLOWLIST = new Set([ + // roomPath itself: the web branch builds the path. + 'src/lib/platform.ts', + // productUrl('/r/…'): shared links stay canonical web URLs, from the app too. + 'src/components/room/LinkMoment.tsx', + // productUrl copy and a display string, never navigation. + 'src/components/room/SettingsSheet.tsx', + // recapPath is web-only (RECAP_AVAILABLE is false in the app); recapImagePath goes through apiUrl. + 'src/lib/recap.ts', + // The server PNG path, fetched through apiUrl. + 'src/lib/achievements-contract.ts', + // The PWA share target is not in the app. + 'src/components/pwa/ShareTarget.tsx', + // Marketing pages are not in the app. + 'src/components/marketing/HeroCreateForm.tsx', + // The web install handoff; the app never calls it (ARCHITECTURE.md 5.3). + 'src/lib/install-handoff.ts', + // The server's link-preview image path, fetched through apiUrl for the prewarm, never navigated. + 'src/lib/room-preview.ts', + // The Smart App Banner's app-argument is the canonical shared web link (web only, iOS Safari). + 'src/lib/store-app.ts', +]) + +/** Every page in `src/app/(native)`, as the route the export serves it under (trailing slash on). */ +const nativePageRoutes = (): string[] => { + const nativeDir = path.join(SRC, 'app', '(native)') + return walk(nativeDir) + .filter((file) => path.basename(file) === 'page.native.tsx') + .map((file) => { + const segments = path + .relative(nativeDir, path.dirname(file)) + .split(path.sep) + // Route groups such as `(x)` do not appear in the URL. + .filter((segment) => segment !== '' && !/^\(.*\)$/.test(segment)) + return segments.length === 0 ? '/' : `/${segments.join('/')}/` + }) +} + +describe('native boundary', () => { + it('imports Capacitor only inside src/lib/native/capacitor/**', () => { + const files = walk(SRC).filter((file) => !relative(file).startsWith(CAPACITOR_HOME)) + expect(files.length).toBeGreaterThan(100) + const offenders = offendingLines(files, CAPACITOR_IMPORT) + expect(offenders, `Capacitor imported outside ${CAPACITOR_HOME}:\n${offenders.join('\n')}`).toEqual([]) + }) + + it('builds /r/ room paths in components and lib only in the allowlisted files', () => { + const files = [path.join(SRC, 'components'), path.join(SRC, 'lib')] + .flatMap(walk) + .filter((file) => !TEST_FILE.test(file) && !ROOM_PATH_ALLOWLIST.has(relative(file))) + expect(files.length).toBeGreaterThan(100) + const offenders = offendingLines(files, HAND_BUILT_ROOM_PATH) + expect( + offenders, + `Hand-built /r/ paths; use roomPath() from src/lib/platform.ts:\n${offenders.join('\n')}` + ).toEqual([]) + }) + + it('keeps every allowlisted file in the tree, so the allowlist cannot go stale', () => { + const present = new Set(walk(SRC).map(relative)) + expect([...ROOM_PATH_ALLOWLIST].filter((file) => !present.has(file))).toEqual([]) + }) + + it('lists exactly the src/app/(native) pages in NATIVE_ROUTES', () => { + expect([...NATIVE_ROUTES].sort()).toEqual(nativePageRoutes().sort()) + }) + + it('recognises the patterns it guards against', () => { + // Negative controls, so a regex typo cannot turn the gates above into no-ops. + expect(CAPACITOR_IMPORT.test(`import { App } from '${CAPACITOR}app'`)).toBe(true) + expect(CAPACITOR_IMPORT.test(`const m = await import("${CAPACITOR}share")`)).toBe(true) + expect(CAPACITOR_IMPORT.test(`import '${CAPACITOR}core'`)).toBe(true) + expect(CAPACITOR_IMPORT.test(`export * from '${CAPACITOR}app'`)).toBe(true) + expect(CAPACITOR_IMPORT.test(`// see the ${CAPACITOR}app docs`)).toBe(false) + expect(HAND_BUILT_ROOM_PATH.test('router.push(`/r/${slug}`)')).toBe(true) + expect(HAND_BUILT_ROOM_PATH.test("router.push('/r/' + slug)")).toBe(true) + expect(HAND_BUILT_ROOM_PATH.test('router.push(roomPath(slug))')).toBe(false) + }) +}) diff --git a/apps/web/src/proxy.test.ts b/apps/web/src/proxy.test.ts index db1fd72c..1f358efb 100644 --- a/apps/web/src/proxy.test.ts +++ b/apps/web/src/proxy.test.ts @@ -7,7 +7,7 @@ import { MARKETING_CACHE_CONTROL } from '@/lib/marketing-cache' import { siteUrl } from '@/lib/site' import { splitGuidePaths } from '@/lib/split-content/artifact' import { SPLIT_CONTENT_INDEX_RELEASED_PATHS } from '@/lib/split-content/index-release' -import { config, proxy } from './proxy' +import { config, proxy, ROOM_SLUG_HEADER } from './proxy' describe('proxy /new locale handoff', () => { it('matches identity-bearing files and APIs for alias canonicalisation', () => { @@ -253,3 +253,172 @@ describe('proxy released and parked guide headers on the indexed deployment', () } }) }) + +describe('proxy CORS for the store apps', () => { + const APP_ORIGINS = ['capacitor://localhost', 'https://localhost'] + const slug = 'ski-trip-kunc-syrup-drum' + const canonicalHost = new URL(siteUrl).host + const request = (path: string, init: { method?: string; origin?: string; host?: string } = {}) => + new NextRequest(`https://renderer.internal${path}`, { + method: init.method ?? 'GET', + headers: { + 'x-forwarded-host': init.host ?? canonicalHost, + ...(init.origin ? { origin: init.origin } : {}), + }, + }) + const corsHeaderNames = (response: Response) => + [...response.headers.keys()].filter((name) => name.startsWith('access-control-')) + + afterEach(() => { + vi.unstubAllEnvs() + }) + + it('answers a preflight from each app origin with 204 and exactly the agreed headers', () => { + for (const origin of APP_ORIGINS) { + const response = proxy(request('/api/currencies', { method: 'OPTIONS', origin })) + + expect(response.status, origin).toBe(204) + expect(response.headers.get('access-control-allow-origin'), origin).toBe(origin) + expect(response.headers.get('access-control-allow-methods'), origin).toBe('GET, POST, PATCH, DELETE') + expect(response.headers.get('access-control-allow-headers'), origin).toBe('Content-Type, X-Member-Token') + expect(response.headers.get('access-control-max-age'), origin).toBe('600') + expect(response.headers.get('vary'), origin).toBe('Origin') + expect(corsHeaderNames(response).sort(), origin).toEqual([ + 'access-control-allow-headers', + 'access-control-allow-methods', + 'access-control-allow-origin', + 'access-control-max-age', + ]) + // A preflight is answered here; it must never reach a handler or a rate-limit bucket. + expect(response.headers.get('x-middleware-next'), origin).toBeNull() + } + }) + + it('lets a GET from an app origin through to the handler with the origin reflected', () => { + for (const origin of APP_ORIGINS) { + const response = proxy(request('/api/currencies', { origin })) + + expect(response.status, origin).toBe(200) + expect(response.headers.get('x-middleware-next'), origin).toBe('1') + expect(response.headers.get('access-control-allow-origin'), origin).toBe(origin) + expect(response.headers.get('access-control-expose-headers'), origin).toBe('Content-Disposition') + expect(response.headers.get('vary'), origin).toBe('Origin') + } + }) + + it('includes the room card routes, which live outside /api', () => { + for (const path of [`/r/${slug}/card/settled`, `/r/${slug}/recap/card`]) { + const preflight = proxy(request(path, { method: 'OPTIONS', origin: 'capacitor://localhost' })) + expect(preflight.status, path).toBe(204) + expect(preflight.headers.get('access-control-allow-origin'), path).toBe('capacitor://localhost') + + const get = proxy(request(path, { origin: 'https://localhost' })) + expect(get.status, path).toBe(200) + expect(get.headers.get('access-control-allow-origin'), path).toBe('https://localhost') + } + }) + + it("gives an unknown origin no CORS headers and today's behaviour", () => { + for (const method of ['OPTIONS', 'GET']) { + const response = proxy(request('/api/currencies', { method, origin: 'https://evil.example' })) + + expect(response.status, method).toBe(200) + expect(response.headers.get('x-middleware-next'), method).toBe('1') + expect(corsHeaderNames(response), method).toEqual([]) + expect(response.headers.get('vary'), method).toBeNull() + } + }) + + it('adds the e2e harness origin only while SPLIT_CORS_TEST_ORIGINS names it', () => { + expect(corsHeaderNames(proxy(request('/api/currencies', { origin: 'http://localhost:8779' })))).toEqual([]) + + vi.stubEnv('SPLIT_CORS_TEST_ORIGINS', 'http://localhost:8779') + const response = proxy(request('/api/currencies', { method: 'OPTIONS', origin: 'http://localhost:8779' })) + expect(response.status).toBe(204) + expect(response.headers.get('access-control-allow-origin')).toBe('http://localhost:8779') + }) + + it('keeps both install-handoff routes same-origin only', () => { + for (const path of ['/api/install-handoff', `/api/rooms/${slug}/install-handoff`]) { + for (const method of ['OPTIONS', 'POST']) { + const response = proxy(request(path, { method, origin: 'capacitor://localhost' })) + expect(response.status, `${method} ${path}`).toBe(200) + expect(corsHeaderNames(response), `${method} ${path}`).toEqual([]) + } + } + }) + + it('still answers an alias host with only the 308, even from an app origin', () => { + for (const method of ['OPTIONS', 'GET']) { + const response = proxy( + request('/api/currencies', { method, origin: 'capacitor://localhost', host: 'split.peanut.me' }) + ) + expect(response.status, method).toBe(308) + expect(response.headers.get('location'), method).toBe(`${siteUrl}/api/currencies`) + expect(corsHeaderNames(response), method).toEqual([]) + } + }) + + it('never allows credentials and never answers with a wildcard', () => { + for (const origin of APP_ORIGINS) { + for (const method of ['OPTIONS', 'GET', 'POST', 'PATCH', 'DELETE']) { + for (const path of ['/api/currencies', `/api/rooms/${slug}/expenses`, `/r/${slug}/recap/card`]) { + const response = proxy(request(path, { method, origin })) + expect(response.headers.get('access-control-allow-credentials'), `${method} ${path}`).toBeNull() + expect(response.headers.get('access-control-allow-origin'), `${method} ${path}`).not.toBe('*') + } + } + } + }) +}) + +describe('proxy room-slug header for the Smart App Banner', () => { + const slug = 'ski-trip-kunc-syrup-drum' + const forwardedSlug = (response: Response) => response.headers.get(`x-middleware-request-${ROOM_SLUG_HEADER}`) + + it('names the room on the room page and its recap', () => { + for (const path of [`/r/${slug}`, `/r/${slug}/recap`]) { + const response = proxy(new NextRequest(`https://renderer.internal${path}`)) + expect(response.status, path).toBe(200) + expect(forwardedSlug(response), path).toBe(slug) + } + }) + + it('is absent everywhere else, including other room paths and invalid slugs', () => { + for (const path of [ + '/app', + '/new', + '/', + '/blog', + `/r/${slug}/import`, + `/r/${slug}/card/settled`, + `/r/${slug}/recap/card`, + '/r/not_a_valid_slug', + '/r/Ski-Trip-kunc-syrup-drum', + ]) { + const response = proxy(new NextRequest(`https://renderer.internal${path}`)) + expect(forwardedSlug(response), path).toBeNull() + } + }) + + it('replaces a spoofed header on room pages and strips it everywhere else, APIs included', () => { + const spoofed = 'evil-room-kunc-syrup-drum' + const cases = [ + [`/r/${slug}`, slug], + [`/r/${slug}/recap`, slug], + ['/app', null], + ['/guides/synthetic-guide', null], + [`/api/rooms/${slug}`, null], + ] as const + + for (const [path, expected] of cases) { + const response = proxy( + new NextRequest(`https://renderer.internal${path}`, { headers: { [ROOM_SLUG_HEADER]: spoofed } }) + ) + expect(response.status, path).toBe(200) + // An overridden request header list that lacks the name is how Next drops it. + expect(response.headers.get('x-middleware-override-headers'), path).not.toBeNull() + expect(forwardedSlug(response), path).toBe(expected) + } + }) +}) diff --git a/apps/web/src/proxy.ts b/apps/web/src/proxy.ts index 8c58449a..09966f07 100644 --- a/apps/web/src/proxy.ts +++ b/apps/web/src/proxy.ts @@ -2,12 +2,29 @@ import { NextResponse, type NextRequest } from 'next/server' import { LOCALE_COOKIE, LOCALE_COOKIE_MAX_AGE_SECONDS } from '@/i18n/locales' import { LOCALE_HEADER, localeFromPathname } from '@/i18n/paths' import { canonicalRedirect } from '@/lib/canonical-redirect' +import { corsFor, PREFLIGHT_STATUS } from '@/lib/cors' import { localeFromNewRoomHandoff } from '@/lib/locale-handoff' import { MARKETING_CACHE_CONTROL, marketingCacheable } from '@/lib/marketing-cache' +import { roomSlugFromLink } from '@/lib/recent-rooms' import { siteUrl } from '@/lib/site' import { splitContentIndexable } from '@/lib/split-content/indexability' import { splitGuideLocale } from '@/lib/split-content/urls' +/** + * Internal request header naming the room on `/r/` and `/r//recap`. The product-shell + * layout reads it to put the Smart App Banner `` in the ``, which the Metadata API + * cannot do on a streamed dynamic route. Only this proxy may set it. + */ +export const ROOM_SLUG_HEADER = 'x-split-room-slug' + +const ROOM_PAGE_PATH = /^\/r\/([^/]+)(?:\/recap)?$/ + +/** The room slug of a room or recap page, validated against the room-slug contract. */ +function roomPageSlug(pathname: string): string | null { + const segment = pathname.match(ROOM_PAGE_PATH)?.[1] + return segment ? roomSlugFromLink(`/r/${segment}`, siteUrl) : null +} + /** * Tells the server what language a URL is in. It does not route or rewrite anything. * (The configured-origin redirect runs first, and `/new?locale=…` persists a guide CTA's locale.) @@ -27,6 +44,19 @@ import { splitGuideLocale } from '@/lib/split-content/urls' * cookie-localized public marketing. */ export function proxy(request: NextRequest) { + const response = routeRequest(request) + // Redirects stay as they were: the apps only call canonical paths on the configured host. + if (response.status >= 300 && response.status < 400) return response + + // CORS for the store apps comes after the canonical redirect, so an alias host still answers + // 308 and nothing else. See `src/lib/cors.ts` for why the proxy owns it. + const cors = corsFor(request.headers.get('origin'), request.nextUrl.pathname, request.method) + if (cors?.kind === 'preflight') return new NextResponse(null, { status: PREFLIGHT_STATUS, headers: cors.headers }) + if (cors) for (const [name, value] of Object.entries(cors.headers)) response.headers.set(name, value) + return response +} + +function routeRequest(request: NextRequest): NextResponse { // The trailing-slash strip Next no longer applies (`skipTrailingSlashRedirect` in // next.config.js). First, where Next's built-in ran, so `/guides/` and friends have // already been retired in one hop by the config redirects before reaching here. A @@ -47,15 +77,24 @@ export function proxy(request: NextRequest) { // from the ordinary `localeFromPathname` path below — a guide URL states its language. const isGuide = splitGuideLocale(request.nextUrl.pathname) !== null - // API requests are matched only so requests to an alias can be canonicalised above. - // On the configured host they must remain untouched: creation locale and request-origin - // checks belong to the API handlers themselves. - if (request.nextUrl.pathname.startsWith('/api/')) return NextResponse.next() + // API requests are matched so requests to an alias can be canonicalised above and the store + // apps get CORS headers in `proxy`. On the configured host the request itself stays untouched: + // creation locale and request-origin checks belong to the API handlers themselves. + if (request.nextUrl.pathname.startsWith('/api/')) { + // The room-slug header is internal; a caller must not be able to hand one to any route. + if (!request.headers.has(ROOM_SLUG_HEADER)) return NextResponse.next() + const stripped = new Headers(request.headers) + stripped.delete(ROOM_SLUG_HEADER) + return NextResponse.next({ request: { headers: stripped } }) + } // The locale header is internal state derived here. A caller-supplied value must never // survive into the request React sees. const forwarded = new Headers(request.headers) forwarded.delete(LOCALE_HEADER) + forwarded.delete(ROOM_SLUG_HEADER) + const roomSlug = roomPageSlug(request.nextUrl.pathname) + if (roomSlug) forwarded.set(ROOM_SLUG_HEADER, roomSlug) const handoffLocale = localeFromNewRoomHandoff(request.nextUrl.pathname, request.nextUrl.searchParams) const locale = handoffLocale ?? localeFromPathname(request.nextUrl.pathname) if (!locale) return NextResponse.next({ request: { headers: forwarded } }) diff --git a/apps/web/src/server/model.ts b/apps/web/src/server/model.ts index 08962acc..36fe0a1d 100644 --- a/apps/web/src/server/model.ts +++ b/apps/web/src/server/model.ts @@ -30,6 +30,10 @@ * fallback only when `SPLIT_GEMINI_PAID_TIER_CONFIRMED=1`. Unpaid Gemini may * use inputs to improve products, so a bare key must never reveal the feature. * + * The privacy page, the in-app scan consent and the store listing all name "Google Gemini, through + * OpenRouter". Running production on the Gemini-direct fallback, or pointing the model env vars at + * another provider, makes those texts untrue: change them first. + * * Neither key is a first-class state: the capability probe says * `enabled: false`, the UI hides the scanner, and a POST that arrives anyway * answers 503. Nothing half-works. diff --git a/apps/web/src/server/notifyCopy.ts b/apps/web/src/server/notifyCopy.ts index a4abdb3c..340a3415 100644 --- a/apps/web/src/server/notifyCopy.ts +++ b/apps/web/src/server/notifyCopy.ts @@ -5,11 +5,16 @@ * and nowhere else — that is the whole reason the copy is not inlined at the * three call sites that produce it. * - * Amounts and member names ARE allowed in a payload: it is encrypted end-to-end - * to a device that already holds the room link and can read all of it in the - * app anyway. The room SLUG is the thing to be careful with — it is the room's - * access control, so it appears only in the click-through `url`, never in a log - * line or an analytics property. + * Amounts and member names ARE allowed in a Web Push payload: it is encrypted + * end-to-end to a device that already holds the room link and can read all of + * it in the app anyway. The room SLUG is the thing to be careful with — it is + * the room's access control, so it appears only in the click-through `url`, + * never in a log line or an analytics property. + * + * App notifications (APNs and FCM) are readable by Apple and Google, so they + * never carry the slug at all: `server/push-native/payload.ts` builds them from + * the title and body here plus the room's `analyticsKey`, using the three + * constants at the end of this file. */ import { formatMoney } from '@/lib/money' @@ -109,3 +114,16 @@ export function allSettledPayload(input: { room: RoomRef; roomId: string; sendId sendId: input.sendId, } } + +/** + * The body of every app notification. `null` sends the same text as Web Push, + * names and amounts included (the decided default; Apple and Google can read + * it). Set it to `NATIVE_GENERIC_BODY` to keep names and amounts off their + * servers — a one-line change, nothing else reads the body. + */ +export const NATIVE_PUSH_BODY: string | null = null + +/** Replaces an app notification's title or body that would contain the slug, + * for instance a room named exactly like its own link. */ +export const NATIVE_GENERIC_TITLE = 'Split' +export const NATIVE_GENERIC_BODY = 'New activity in your room.' diff --git a/apps/web/src/server/push-native/apns.test.ts b/apps/web/src/server/push-native/apns.test.ts new file mode 100644 index 00000000..04f22347 --- /dev/null +++ b/apps/web/src/server/push-native/apns.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from 'vitest' +import { generateKeyPairSync, verify } from 'node:crypto' +import { isDeadApnsToken, signApnsToken } from '@/server/push-native/apns' + +const decode = (part: string) => JSON.parse(Buffer.from(part, 'base64url').toString('utf8')) + +describe('APNs provider token', () => { + it('is an ES256 JWT that verifies against the key pair it was signed with', () => { + // Apple's .p8 is a PKCS#8 P-256 key; a fresh one stands in for it. + const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'prime256v1' }) + const keyP8 = privateKey.export({ type: 'pkcs8', format: 'pem' }).toString() + const now = Date.UTC(2026, 10, 14, 2, 0, 0) + + const token = signApnsToken({ keyP8, keyId: 'ABC123DEFG', teamId: 'TEAM123456' }, now) + const [header, claims, signature] = token.split('.') + + expect(decode(header)).toEqual({ alg: 'ES256', kid: 'ABC123DEFG' }) + expect(decode(claims)).toEqual({ iss: 'TEAM123456', iat: now / 1000 }) + const signatureBytes = Buffer.from(signature, 'base64url') + // JOSE ES256 is the raw 64-byte r||s form, not DER. + expect(signatureBytes).toHaveLength(64) + expect( + verify( + 'sha256', + Buffer.from(`${header}.${claims}`), + { key: publicKey, dsaEncoding: 'ieee-p1363' }, + signatureBytes + ) + ).toBe(true) + + const other = generateKeyPairSync('ec', { namedCurve: 'prime256v1' }).publicKey + expect( + verify( + 'sha256', + Buffer.from(`${header}.${claims}`), + { key: other, dsaEncoding: 'ieee-p1363' }, + signatureBytes + ) + ).toBe(false) + }) +}) + +describe('APNs dead-token classification', () => { + it.each([ + [410, 'Unregistered', true], + [400, 'BadDeviceToken', true], + [400, 'BadCollapseId', false], + [403, 'InvalidProviderToken', false], + [429, 'TooManyRequests', false], + [500, 'InternalServerError', false], + [200, undefined, false], + ])('status %i with reason %s → dead %s', (status, reason, dead) => { + expect(isDeadApnsToken(status, reason)).toBe(dead) + }) +}) diff --git a/apps/web/src/server/push-native/apns.ts b/apps/web/src/server/push-native/apns.ts new file mode 100644 index 00000000..21b85e42 --- /dev/null +++ b/apps/web/src/server/push-native/apns.ts @@ -0,0 +1,166 @@ +/** + * Apple Push Notification service sender: token-based auth over HTTP/2. + * + * No SDK: the provider token is an ES256 JWT signed with `node:crypto`, and the + * request is one `http2` POST per device. A row's transport picks the host: + * `apns` goes to production, `apns-sandbox` to Apple's development service + * (debug and TestFlight-less device builds). + */ +import { sign } from 'node:crypto' +import http2 from 'node:http2' +import tls from 'node:tls' +import type { ApnsCredentials } from '@/server/push-native/config' +import { + apnsPayload, + NATIVE_TTL_SECONDS, + type NativeDelivery, + type NativeNotification, +} from '@/server/push-native/payload' +import { openTunnel } from '@/server/push-native/tunnel' + +const HOSTS = { production: 'api.push.apple.com', sandbox: 'api.sandbox.push.apple.com' } as const +const REQUEST_TIMEOUT_MS = 10_000 +/** Apple rejects a provider token older than an hour and throttles one renewed + * more often than every 20 minutes. */ +const TOKEN_LIFETIME_MS = 50 * 60_000 + +const base64url = (value: string | Buffer) => Buffer.from(value).toString('base64url') + +/** The provider JWT: `{ alg: ES256, kid }` over `{ iss: teamId, iat }`. */ +export function signApnsToken(credentials: Pick, nowMs: number): string { + const header = base64url(JSON.stringify({ alg: 'ES256', kid: credentials.keyId })) + const claims = base64url(JSON.stringify({ iss: credentials.teamId, iat: Math.floor(nowMs / 1000) })) + const input = `${header}.${claims}` + // JOSE wants the raw r||s signature, not Node's default DER encoding. + const signature = sign('sha256', Buffer.from(input), { key: credentials.keyP8, dsaEncoding: 'ieee-p1363' }) + return `${input}.${base64url(signature)}` +} + +let cachedToken: { value: string; keyId: string; issuedAt: number } | null = null + +function providerToken(credentials: ApnsCredentials): string { + const now = Date.now() + if (!cachedToken || cachedToken.keyId !== credentials.keyId || now - cachedToken.issuedAt > TOKEN_LIFETIME_MS) { + cachedToken = { value: signApnsToken(credentials, now), keyId: credentials.keyId, issuedAt: now } + } + return cachedToken.value +} + +/** Test seam: drops the cached provider token. */ +export function resetApnsToken(): void { + cachedToken = null +} + +/** + * Apple says the token is gone: 410 (Unregistered, the app was removed) or 400 + * BadDeviceToken (a token from the other environment, or garbage). Retrying it + * on every future event would only add noise, so the row is deleted. + */ +export function isDeadApnsToken(status: number, reason: string | undefined): boolean { + return status === 410 || (status === 400 && reason === 'BadDeviceToken') +} + +async function openSession(host: string): Promise { + const authority = `https://${host}:443` + const proxyUrl = process.env.SPLIT_PUSH_PROXY_URL + if (!proxyUrl) return http2.connect(authority) + const socket = await openTunnel(proxyUrl, host, 443) + const secure = tls.connect({ socket, servername: host, ALPNProtocols: ['h2'] }) + return http2.connect(authority, { createConnection: () => secure }) +} + +function post( + session: http2.ClientHttp2Session, + headers: http2.OutgoingHttpHeaders, + body: string +): Promise<{ status: number; reason?: string }> { + return new Promise((resolve, reject) => { + const request = session.request(headers) + let status = 0 + let text = '' + request.setEncoding('utf8') + request.setTimeout(REQUEST_TIMEOUT_MS, () => request.close(http2.constants.NGHTTP2_CANCEL)) + request.on('response', (response) => { + status = Number(response[':status']) + }) + request.on('data', (chunk: string) => { + text += chunk + }) + request.on('end', () => { + let reason: string | undefined + try { + reason = text ? (JSON.parse(text) as { reason?: string }).reason : undefined + } catch { + reason = undefined + } + resolve({ status, reason }) + }) + request.on('error', reject) + // A cancelled (timed-out) stream closes without 'end'; status 0 then + // reads as a failed send that keeps its row. + request.on('close', () => resolve({ status, reason: undefined })) + request.end(body) + }) +} + +/** + * Sends one notification to every token, one HTTP/2 session per Apple host for + * the whole batch. Results come back in the order of `targets`. A connection + * failure fails the batch's sends but never marks a token dead. + */ +export async function sendApns( + credentials: ApnsCredentials, + targets: readonly { token: string; sandbox: boolean }[], + notification: NativeNotification +): Promise { + const body = JSON.stringify(apnsPayload(notification)) + const results: NativeDelivery[] = targets.map(() => ({ ok: false, dead: false })) + for (const sandbox of [false, true]) { + const indexes = targets.flatMap((target, index) => (target.sandbox === sandbox ? [index] : [])) + if (indexes.length === 0) continue + let session: http2.ClientHttp2Session | null = null + try { + session = await openSession(sandbox ? HOSTS.sandbox : HOSTS.production) + // An idle session error must not crash the process; requests on it + // fail through their own error events. + session.on('error', () => {}) + const open = session + await Promise.all( + indexes.map(async (index) => { + try { + const { status, reason } = await post( + open, + { + ':method': 'POST', + ':path': `/3/device/${targets[index].token}`, + authorization: `bearer ${providerToken(credentials)}`, + 'apns-topic': credentials.bundleId, + 'apns-push-type': 'alert', + 'apns-priority': '10', + 'apns-expiration': String(Math.floor(Date.now() / 1000) + NATIVE_TTL_SECONDS), + // Same coalescing as the Web Push tag: a newer + // notification for the room replaces the older one. + 'apns-collapse-id': notification.room, + 'content-type': 'application/json', + }, + body + ) + results[index] = { + ok: status === 200, + dead: isDeadApnsToken(status, reason), + statusCode: status, + } + if (status !== 200) console.warn('[split] apns delivery failed', { status, reason }) + } catch { + console.warn('[split] apns delivery failed', { status: 'request-error' }) + } + }) + ) + } catch { + console.warn('[split] apns connection failed') + } finally { + session?.close() + } + } + return results +} diff --git a/apps/web/src/server/push-native/channel.test.ts b/apps/web/src/server/push-native/channel.test.ts new file mode 100644 index 00000000..ca25d928 --- /dev/null +++ b/apps/web/src/server/push-native/channel.test.ts @@ -0,0 +1,130 @@ +/** + * The request shapes and the credentials gate, without a database. The route + * handler tests in `server/test/push.test.ts` cover the same paths end to end. + */ +import { afterEach, describe, expect, it } from 'vitest' +import { ApiError } from '@/server/http' +import { assertNativePushAvailable, fcmCredentials } from '@/server/push-native/config' +import { pushStatusSchema, pushSubscribeSchema, pushUnsubscribeSchema } from '@/server/validation' + +const member = { memberId: 'member-1', memberToken: 'token-1' } +const APNS_TOKEN = 'a1b2c3d4'.repeat(8) +const FCM_TOKEN = 'dGVzdA:APA91bH-xyz_123' +const WEB = 'https://fcm.googleapis.com/fcm/send/abc' +const KEYS = { p256dh: 'BPk3p256dhKeyMaterial', auth: 'authKeyMaterial' } + +describe('push subscribe body', () => { + it('keeps a web body a web channel with its keys', () => { + expect(pushSubscribeSchema.parse({ endpoint: WEB, keys: KEYS, ...member })).toMatchObject({ + transport: 'webpush', + endpoint: WEB, + keys: KEYS, + }) + }) + + it('still rejects a web body without keys', () => { + expect(pushSubscribeSchema.safeParse({ endpoint: WEB, ...member }).success).toBe(false) + }) + + it.each([ + ['apns', APNS_TOKEN], + ['apns-sandbox', APNS_TOKEN], + ['fcm', FCM_TOKEN], + ])('stores a %s token as a prefixed endpoint without keys', (transport, token) => { + expect(pushSubscribeSchema.parse({ transport, token, ...member })).toEqual({ + transport, + endpoint: `${transport}:${token}`, + keys: null, + ...member, + }) + }) + + it.each([ + ['an unknown transport', { transport: 'webpush', token: APNS_TOKEN }], + ['a path in an APNs token', { transport: 'apns', token: 'abcd/../x' }], + ['a non-hex APNs token', { transport: 'apns', token: FCM_TOKEN }], + ['a query in an FCM token', { transport: 'fcm', token: 'abc?x=1' }], + ['an empty token', { transport: 'fcm', token: '' }], + ])('rejects %s', (_label, body) => { + expect(pushSubscribeSchema.safeParse({ ...member, ...body }).success).toBe(false) + }) + + it('rejects a native body without the member token', () => { + expect( + pushSubscribeSchema.safeParse({ transport: 'fcm', token: FCM_TOKEN, memberId: 'member-1' }).success + ).toBe(false) + }) +}) + +describe('push unsubscribe and status bodies', () => { + it.each([ + ['unsubscribe', pushUnsubscribeSchema], + ['status', pushStatusSchema], + ])('%s accepts a web endpoint or a native token', (_label, schema) => { + expect(schema.parse({ endpoint: WEB, ...member })).toEqual({ transport: 'webpush', endpoint: WEB, ...member }) + expect(schema.parse({ transport: 'fcm', token: FCM_TOKEN, ...member })).toEqual({ + transport: 'fcm', + endpoint: `fcm:${FCM_TOKEN}`, + ...member, + }) + expect(schema.safeParse({ ...member }).success).toBe(false) + }) +}) + +describe('native push credentials gate', () => { + const names = [ + 'SPLIT_APNS_KEY_P8', + 'SPLIT_APNS_KEY_ID', + 'SPLIT_APNS_TEAM_ID', + 'SPLIT_APNS_BUNDLE_ID', + 'SPLIT_FCM_SERVICE_ACCOUNT_JSON', + ] as const + const saved = Object.fromEntries(names.map((name) => [name, process.env[name]])) + + afterEach(() => { + for (const name of names) { + if (saved[name] === undefined) delete process.env[name] + else process.env[name] = saved[name] + } + }) + + const codeOf = (transport: Parameters[0]) => { + try { + assertNativePushAvailable(transport) + return 'ok' + } catch (err) { + return err instanceof ApiError ? `${err.status} ${err.code}` : 'other' + } + } + + it('answers 503 NATIVE_PUSH_UNAVAILABLE for a native transport without credentials, never for web', () => { + for (const name of names) delete process.env[name] + expect(codeOf('apns')).toBe('503 NATIVE_PUSH_UNAVAILABLE') + expect(codeOf('apns-sandbox')).toBe('503 NATIVE_PUSH_UNAVAILABLE') + expect(codeOf('fcm')).toBe('503 NATIVE_PUSH_UNAVAILABLE') + expect(codeOf('webpush')).toBe('ok') + }) + + it('opens each transport only with its own complete credentials', () => { + for (const name of names) delete process.env[name] + process.env.SPLIT_APNS_KEY_P8 = 'key' + process.env.SPLIT_APNS_KEY_ID = 'id' + process.env.SPLIT_APNS_TEAM_ID = 'team' + expect(codeOf('apns')).toBe('503 NATIVE_PUSH_UNAVAILABLE') + process.env.SPLIT_APNS_BUNDLE_ID = 'com.peanutsplit.app' + expect(codeOf('apns')).toBe('ok') + expect(codeOf('apns-sandbox')).toBe('ok') + expect(codeOf('fcm')).toBe('503 NATIVE_PUSH_UNAVAILABLE') + + process.env.SPLIT_FCM_SERVICE_ACCOUNT_JSON = '{not json' + expect(codeOf('fcm')).toBe('503 NATIVE_PUSH_UNAVAILABLE') + process.env.SPLIT_FCM_SERVICE_ACCOUNT_JSON = JSON.stringify({ + project_id: 'split-test', + client_email: 'push@split-test.iam.gserviceaccount.com', + // Any escaped multi-line string proves the unescape; a PEM-shaped literal trips the secret hook. + private_key: 'line-one\\nline-two\\n', + }) + expect(codeOf('fcm')).toBe('ok') + expect(fcmCredentials()?.privateKey).toBe('line-one\nline-two\n') + }) +}) diff --git a/apps/web/src/server/push-native/config.ts b/apps/web/src/server/push-native/config.ts new file mode 100644 index 00000000..38e77125 --- /dev/null +++ b/apps/web/src/server/push-native/config.ts @@ -0,0 +1,71 @@ +/** + * Which app push services this server can deliver to, read from the runtime + * environment. + * + * Every value is optional. Without them the subscribe and status routes answer + * 503 NATIVE_PUSH_UNAVAILABLE, the app hides its notification row, and the + * fan-out skips native rows. Setting them on the server turns app push on with + * no store release. Like the VAPID pair, the APNs key and the FCM service + * account are never rotated in place without a plan for the stored tokens. + */ +import type { NativePushTransport } from '@/lib/api-types' +import { ApiError } from '@/server/http' + +export const NATIVE_PUSH_TRANSPORTS = ['apns', 'apns-sandbox', 'fcm'] as const satisfies readonly NativePushTransport[] + +export interface ApnsCredentials { + /** PEM text of the `.p8` key. */ + keyP8: string + keyId: string + teamId: string + /** The app's bundle ID, sent as `apns-topic`. */ + bundleId: string +} + +export interface FcmCredentials { + projectId: string + clientEmail: string + privateKey: string +} + +export function apnsCredentials(): ApnsCredentials | null { + const keyP8 = process.env.SPLIT_APNS_KEY_P8 + const keyId = process.env.SPLIT_APNS_KEY_ID + const teamId = process.env.SPLIT_APNS_TEAM_ID + const bundleId = process.env.SPLIT_APNS_BUNDLE_ID + if (!keyP8 || !keyId || !teamId || !bundleId) return null + // Secret stores often keep a multi-line PEM as one line with literal \n. + return { keyP8: keyP8.replace(/\\n/g, '\n'), keyId, teamId, bundleId } +} + +export function fcmCredentials(): FcmCredentials | null { + const raw = process.env.SPLIT_FCM_SERVICE_ACCOUNT_JSON + if (!raw) return null + try { + const json = JSON.parse(raw) as { project_id?: unknown; client_email?: unknown; private_key?: unknown } + const { project_id: projectId, client_email: clientEmail, private_key: privateKey } = json + if (typeof projectId !== 'string' || typeof clientEmail !== 'string' || typeof privateKey !== 'string') { + return null + } + return { projectId, clientEmail, privateKey: privateKey.replace(/\\n/g, '\n') } + } catch { + // A malformed value is treated as unset: the routes answer 503 instead + // of storing tokens that every send would then fail on. + return null + } +} + +export function isNativePushAvailable(transport: NativePushTransport): boolean { + return transport === 'fcm' ? fcmCredentials() !== null : apnsCredentials() !== null +} + +/** + * The routes' gate for app tokens. It runs before the room lookup, so it says + * nothing about whether a room exists. The app hides its notification row on + * this code, so a store build never shows a button the server cannot serve. + */ +export function assertNativePushAvailable(transport: NativePushTransport | 'webpush'): void { + if (transport !== 'webpush' && !isNativePushAvailable(transport)) { + throw new ApiError(503, 'NATIVE_PUSH_UNAVAILABLE', 'app notifications are not configured on this server') + } +} diff --git a/apps/web/src/server/push-native/fcm.test.ts b/apps/web/src/server/push-native/fcm.test.ts new file mode 100644 index 00000000..6756c3da --- /dev/null +++ b/apps/web/src/server/push-native/fcm.test.ts @@ -0,0 +1,120 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { generateKeyPairSync, verify } from 'node:crypto' +import { isDeadFcmToken, resetFcmToken, sendFcm, signFcmAssertion } from '@/server/push-native/fcm' +import type { NativeNotification } from '@/server/push-native/payload' + +const decode = (part: string) => JSON.parse(Buffer.from(part, 'base64url').toString('utf8')) + +const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 }) +const credentials = { + projectId: 'split-test', + clientEmail: 'push@split-test.iam.gserviceaccount.com', + privateKey: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(), +} + +describe('FCM OAuth assertion', () => { + it('is an RS256 JWT for the messaging scope that verifies against the service account key', () => { + const now = Date.UTC(2026, 10, 14, 2, 0, 0) + const [header, claims, signature] = signFcmAssertion(credentials, now).split('.') + + expect(decode(header)).toEqual({ alg: 'RS256', typ: 'JWT' }) + expect(decode(claims)).toEqual({ + iss: credentials.clientEmail, + scope: 'https://www.googleapis.com/auth/firebase.messaging', + aud: 'https://oauth2.googleapis.com/token', + iat: now / 1000, + exp: now / 1000 + 3600, + }) + expect( + verify('sha256', Buffer.from(`${header}.${claims}`), publicKey, Buffer.from(signature, 'base64url')) + ).toBe(true) + }) +}) + +describe('FCM dead-token classification', () => { + const unregistered = { + error: { + status: 'NOT_FOUND', + details: [{ '@type': 'type.googleapis.com/google.firebase.fcm.v1.FcmError', errorCode: 'UNREGISTERED' }], + }, + } + const invalidArgument = { + error: { status: 'INVALID_ARGUMENT', details: [{ errorCode: 'INVALID_ARGUMENT' }] }, + } + + it.each([ + [404, unregistered, true], + [404, null, true], + [400, { error: { details: [{ errorCode: 'UNREGISTERED' }] } }, true], + [400, invalidArgument, false], + [401, null, false], + [429, { error: { details: [{ errorCode: 'QUOTA_EXCEEDED' }] } }, false], + [503, 'not json', false], + ])('status %i → dead %s', (status, body, dead) => { + expect(isDeadFcmToken(status, body)).toBe(dead) + }) +}) + +describe('sendFcm', () => { + const notification: NativeNotification = { + title: 'Ski Trip', + body: 'Ana added Lift passes — €120.00', + room: '0123456789abcdef0123456789abcdef', + sendId: '00000000-0000-4000-8000-000000000001', + } + const fetchMock = vi.fn() + + beforeEach(() => { + resetFcmToken() + fetchMock.mockReset() + vi.stubGlobal('fetch', fetchMock) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + // No proxy: egressFetch uses the global fetch, which is the stub. + delete process.env.SPLIT_PUSH_PROXY_URL + }) + + afterEach(() => { + vi.unstubAllGlobals() + vi.restoreAllMocks() + }) + + it('gets one access token, sends to each device and marks only the unregistered one dead', async () => { + fetchMock.mockImplementation(async (input, init) => { + const url = String(input) + if (url === 'https://oauth2.googleapis.com/token') { + return Response.json({ access_token: 'access-1', expires_in: 3600 }) + } + const sent = JSON.parse(String(init?.body)) as { message: { token: string } } + if (sent.message.token === 'gone-token') + return Response.json({ error: { status: 'NOT_FOUND' } }, { status: 404 }) + if (sent.message.token === 'busy-token') return Response.json({ error: {} }, { status: 503 }) + return Response.json({ name: 'projects/split-test/messages/1' }) + }) + + const results = await sendFcm(credentials, ['live-token', 'gone-token', 'busy-token'], notification) + + expect(results).toEqual([ + { ok: true, dead: false, statusCode: 200 }, + { ok: false, dead: true, statusCode: 404 }, + { ok: false, dead: false, statusCode: 503 }, + ]) + const urls = fetchMock.mock.calls.map(([input]) => String(input)) + expect(urls.filter((url) => url.endsWith('/token'))).toHaveLength(1) + expect( + urls.filter((url) => url === 'https://fcm.googleapis.com/v1/projects/split-test/messages:send') + ).toHaveLength(3) + + // The cached token is reused for the next event. + await sendFcm(credentials, ['live-token'], notification) + expect(fetchMock.mock.calls.filter(([input]) => String(input).endsWith('/token'))).toHaveLength(1) + }) + + it('fails every send without marking a token dead when the token call fails', async () => { + fetchMock.mockResolvedValue(Response.json({ error: 'invalid_grant' }, { status: 400 })) + + expect(await sendFcm(credentials, ['a', 'b'], notification)).toEqual([ + { ok: false, dead: false }, + { ok: false, dead: false }, + ]) + }) +}) diff --git a/apps/web/src/server/push-native/fcm.ts b/apps/web/src/server/push-native/fcm.ts new file mode 100644 index 00000000..fc79be6f --- /dev/null +++ b/apps/web/src/server/push-native/fcm.ts @@ -0,0 +1,116 @@ +/** + * Firebase Cloud Messaging sender (HTTP v1) for the Android app. + * + * No SDK: the service account signs an RS256 JWT with `node:crypto`, Google's + * token endpoint swaps it for an hour-long access token, and each device gets + * one `messages:send` POST. Both calls go through `egressFetch` with + * `SPLIT_PUSH_PROXY_URL`, the same way out of the container as every other + * runtime request. + */ +import { sign } from 'node:crypto' +import type { FcmCredentials } from '@/server/push-native/config' +import { fcmMessage, type NativeDelivery, type NativeNotification } from '@/server/push-native/payload' +import { egressFetch } from '@/server/egress' + +const TOKEN_URL = 'https://oauth2.googleapis.com/token' +const SCOPE = 'https://www.googleapis.com/auth/firebase.messaging' +const TOKEN_LIFETIME_S = 3600 +/** Renew a minute early so a token never expires between check and send. */ +const RENEW_MARGIN_MS = 60_000 +const REQUEST_TIMEOUT_MS = 10_000 + +const base64url = (value: string | Buffer) => Buffer.from(value).toString('base64url') + +/** The OAuth assertion Google's token endpoint takes for a service account. */ +export function signFcmAssertion( + credentials: Pick, + nowMs: number +): string { + const iat = Math.floor(nowMs / 1000) + const header = base64url(JSON.stringify({ alg: 'RS256', typ: 'JWT' })) + const claims = base64url( + JSON.stringify({ iss: credentials.clientEmail, scope: SCOPE, aud: TOKEN_URL, iat, exp: iat + TOKEN_LIFETIME_S }) + ) + const input = `${header}.${claims}` + return `${input}.${base64url(sign('sha256', Buffer.from(input), credentials.privateKey))}` +} + +/** + * FCM says the token is gone: the app was uninstalled or the token rotated + * (`UNREGISTERED`, usually with 404). Anything else, including 400 + * INVALID_ARGUMENT, keeps the row: that code also covers a bad payload. + */ +export function isDeadFcmToken(status: number, body: unknown): boolean { + if (status === 404) return true + const details = (body as { error?: { details?: { errorCode?: unknown }[] } } | null)?.error?.details + return Array.isArray(details) && details.some((detail) => detail?.errorCode === 'UNREGISTERED') +} + +let cachedToken: { value: string; clientEmail: string; expiresAt: number } | null = null + +/** Test seam: drops the cached access token. */ +export function resetFcmToken(): void { + cachedToken = null +} + +async function accessToken(credentials: FcmCredentials, proxyUrl: string | undefined): Promise { + const now = Date.now() + if (cachedToken && cachedToken.clientEmail === credentials.clientEmail && now < cachedToken.expiresAt) { + return cachedToken.value + } + const response = await egressFetch(proxyUrl, TOKEN_URL, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', + assertion: signFcmAssertion(credentials, now), + }).toString(), + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }) + if (!response.ok) throw new Error(`fcm token request failed: ${response.status}`) + const json = (await response.json()) as { access_token?: unknown; expires_in?: unknown } + if (typeof json.access_token !== 'string') throw new Error('fcm token response had no access_token') + const lifetimeS = typeof json.expires_in === 'number' ? json.expires_in : TOKEN_LIFETIME_S + cachedToken = { + value: json.access_token, + clientEmail: credentials.clientEmail, + expiresAt: now + lifetimeS * 1000 - RENEW_MARGIN_MS, + } + return cachedToken.value +} + +/** Sends one notification to every token. Results come back in token order. */ +export async function sendFcm( + credentials: FcmCredentials, + tokens: readonly string[], + notification: NativeNotification +): Promise { + const proxyUrl = process.env.SPLIT_PUSH_PROXY_URL + let bearer: string + try { + bearer = await accessToken(credentials, proxyUrl) + } catch { + console.warn('[split] fcm auth failed') + return tokens.map(() => ({ ok: false, dead: false })) + } + const url = `https://fcm.googleapis.com/v1/projects/${encodeURIComponent(credentials.projectId)}/messages:send` + return Promise.all( + tokens.map(async (token): Promise => { + try { + const response = await egressFetch(proxyUrl, url, { + method: 'POST', + headers: { Authorization: `Bearer ${bearer}`, 'Content-Type': 'application/json' }, + body: JSON.stringify(fcmMessage(token, notification)), + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }) + if (response.ok) return { ok: true, dead: false, statusCode: response.status } + const body = await response.json().catch(() => null) + console.warn('[split] fcm delivery failed', { status: response.status }) + return { ok: false, dead: isDeadFcmToken(response.status, body), statusCode: response.status } + } catch { + console.warn('[split] fcm delivery failed', { status: 'request-error' }) + return { ok: false, dead: false } + } + }) + ) +} diff --git a/apps/web/src/server/push-native/payload.test.ts b/apps/web/src/server/push-native/payload.test.ts new file mode 100644 index 00000000..bdbd5c7a --- /dev/null +++ b/apps/web/src/server/push-native/payload.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, it } from 'vitest' +import { allSettledPayload, expenseAddedPayload, NATIVE_GENERIC_BODY, NATIVE_GENERIC_TITLE } from '@/server/notifyCopy' +import { apnsPayload, fcmMessage, toNativeNotification } from '@/server/push-native/payload' + +const SLUG = 'ski-trip-kunc-syrup-drum' +const ANALYTICS_KEY = '0123456789abcdef0123456789abcdef' +const SEND_ID = '00000000-0000-4000-8000-000000000001' + +const room = (name: string) => ({ slug: SLUG, name, emoji: null, currency: 'EUR' }) + +const serialized = (name: string, description = 'Lift passes') => { + const web = expenseAddedPayload({ + room: room(name), + roomId: 'room-uuid', + sendId: SEND_ID, + actorName: 'Ana', + description, + amountMinor: '12000', + currency: 'EUR', + }) + const notification = toNativeNotification(web, { slug: SLUG, analyticsKey: ANALYTICS_KEY }) + return { + notification, + apns: JSON.stringify(apnsPayload(notification)), + fcm: JSON.stringify(fcmMessage('device-token', notification)), + } +} + +describe('app notification payloads', () => { + it('carry the web title and body, the analytics key and the send id', () => { + const { notification, apns, fcm } = serialized('Ski Trip') + expect(notification).toEqual({ + title: 'Ski Trip', + body: 'Ana added Lift passes — €120.00', + room: ANALYTICS_KEY, + sendId: SEND_ID, + }) + expect(JSON.parse(apns)).toEqual({ + aps: { alert: { title: 'Ski Trip', body: 'Ana added Lift passes — €120.00' }, 'thread-id': ANALYTICS_KEY }, + room: ANALYTICS_KEY, + sendId: SEND_ID, + }) + expect(JSON.parse(fcm)).toEqual({ + message: { + token: 'device-token', + notification: { title: 'Ski Trip', body: 'Ana added Lift passes — €120.00' }, + android: { ttl: '86400s', notification: { tag: ANALYTICS_KEY, icon: 'ic_stat_split' } }, + data: { room: ANALYTICS_KEY, sendId: SEND_ID }, + }, + }) + }) + + it('never contain the slug, while the web payload does', () => { + const web = allSettledPayload({ room: room('Ski Trip'), roomId: 'room-uuid', sendId: SEND_ID }) + expect(JSON.stringify(web)).toContain(SLUG) + + const { apns, fcm } = serialized('Ski Trip') + expect(apns).not.toContain(SLUG) + expect(fcm).not.toContain(SLUG) + expect(apns).not.toContain('/r/') + expect(fcm).not.toContain('/r/') + }) + + it('replace a title that is the slug, as when a room is named after its own link', () => { + const { notification, apns, fcm } = serialized(SLUG) + expect(notification.title).toBe(NATIVE_GENERIC_TITLE) + expect(apns).not.toContain(SLUG) + expect(fcm).not.toContain(SLUG) + }) + + it('replace a body that mentions the slug, in any letter case', () => { + const { notification, apns, fcm } = serialized('Ski Trip', `Paid via ${SLUG.toUpperCase()}`) + expect(notification.body).toBe(NATIVE_GENERIC_BODY) + expect(apns.toLowerCase()).not.toContain(SLUG) + expect(fcm.toLowerCase()).not.toContain(SLUG) + }) +}) diff --git a/apps/web/src/server/push-native/payload.ts b/apps/web/src/server/push-native/payload.ts new file mode 100644 index 00000000..28c0f0ff --- /dev/null +++ b/apps/web/src/server/push-native/payload.ts @@ -0,0 +1,73 @@ +/** + * App notification bodies for APNs and FCM. Pure, so the "no slug" rule is a + * unit test rather than a promise. + * + * Apple and Google can read these payloads (Web Push is end-to-end encrypted; + * these are not), and the slug is the room's credential. So the only room id + * here is the `analyticsKey`, a one-way digest the app maps back to a room it + * already knows, and any title or body that would contain the slug is replaced + * with generic copy. + */ +import { NATIVE_GENERIC_BODY, NATIVE_GENERIC_TITLE, NATIVE_PUSH_BODY, type PushPayload } from '@/server/notifyCopy' + +/** Web Push drops a message it could not deliver within a day; so do these. */ +export const NATIVE_TTL_SECONDS = 86_400 + +/** What an app notification may carry. No slug, no URL. */ +export interface NativeNotification { + title: string + body: string + /** The room's `analyticsKey`. */ + room: string + /** Ledger row id, echoed back by the app's opened beacon. */ + sendId: string +} + +/** One device's outcome. `dead` means the service says the token is gone for + * good and the row should be deleted. */ +export interface NativeDelivery { + ok: boolean + dead: boolean + statusCode?: number +} + +const mentions = (text: string, slug: string) => text.toLowerCase().includes(slug.toLowerCase()) + +export function toNativeNotification( + payload: PushPayload, + room: { slug: string; analyticsKey: string } +): NativeNotification { + const body = NATIVE_PUSH_BODY ?? payload.body + return { + title: mentions(payload.title, room.slug) ? NATIVE_GENERIC_TITLE : payload.title, + body: mentions(body, room.slug) ? NATIVE_GENERIC_BODY : body, + room: room.analyticsKey, + sendId: payload.sendId, + } +} + +/** The JSON body of one APNs request. `thread-id` groups a room's notifications. */ +export function apnsPayload(n: NativeNotification) { + return { + aps: { alert: { title: n.title, body: n.body }, 'thread-id': n.room }, + room: n.room, + sendId: n.sendId, + } +} + +/** The JSON body of one FCM HTTP v1 `messages:send` request. */ +export function fcmMessage(token: string, n: NativeNotification) { + return { + message: { + token, + notification: { title: n.title, body: n.body }, + android: { + ttl: `${NATIVE_TTL_SECONDS}s`, + // One tag per room: a newer notification replaces the older one + // on the device, as the Web Push tag does. + notification: { tag: n.room, icon: 'ic_stat_split' }, + }, + data: { room: n.room, sendId: n.sendId }, + }, + } +} diff --git a/apps/web/src/server/push-native/tunnel.test.ts b/apps/web/src/server/push-native/tunnel.test.ts new file mode 100644 index 00000000..78405088 --- /dev/null +++ b/apps/web/src/server/push-native/tunnel.test.ts @@ -0,0 +1,84 @@ +import { afterEach, describe, expect, it } from 'vitest' +import http from 'node:http' +import net, { type AddressInfo } from 'node:net' +import { openTunnel } from '@/server/push-native/tunnel' + +/** Local stand-ins: a TCP echo server as the "push service" and a CONNECT proxy + * in front of it. No request leaves the machine. */ +const servers: { close(): unknown }[] = [] + +afterEach(async () => { + for (const server of servers.splice(0)) server.close() +}) + +const listen = async (server: T): Promise => { + servers.push(server) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + return (server.address() as AddressInfo).port +} + +const echoServer = () => listen(net.createServer((socket) => socket.pipe(socket))) + +function connectProxy(options: { refuse?: boolean } = {}) { + const seen: { url?: string; auth?: string } = {} + const server = http.createServer((_req, res) => res.writeHead(405).end()) + server.on('connect', (req, client: net.Socket) => { + seen.url = req.url + seen.auth = req.headers['proxy-authorization'] + if (options.refuse) { + client.end('HTTP/1.1 403 Forbidden\r\n\r\n') + return + } + const [host, port] = (req.url ?? '').split(':') + const upstream = net.connect(Number(port), host, () => { + client.write('HTTP/1.1 200 Connection Established\r\n\r\n') + upstream.pipe(client) + client.pipe(upstream) + }) + upstream.on('error', () => client.destroy()) + }) + return { seen, port: listen(server) } +} + +const roundTrip = (socket: net.Socket, text: string) => + new Promise((resolve) => { + socket.once('data', (chunk) => resolve(chunk.toString('utf8'))) + socket.write(text) + }) + +describe('openTunnel', () => { + it('asks the proxy for the target host and port, then carries bytes both ways', async () => { + const target = await echoServer() + const proxy = connectProxy() + const socket = await openTunnel(`http://127.0.0.1:${await proxy.port}`, '127.0.0.1', target) + + expect(proxy.seen.url).toBe(`127.0.0.1:${target}`) + expect(proxy.seen.auth).toBeUndefined() + expect(await roundTrip(socket, 'hello through the tunnel')).toBe('hello through the tunnel') + socket.destroy() + }) + + it('sends basic proxy credentials from the proxy URL', async () => { + const target = await echoServer() + const proxy = connectProxy() + const socket = await openTunnel(`http://split%40box:p%3Ass@127.0.0.1:${await proxy.port}`, '127.0.0.1', target) + + expect(proxy.seen.auth).toBe(`Basic ${Buffer.from('split@box:p:ss').toString('base64')}`) + socket.destroy() + }) + + it('rejects when the proxy refuses the CONNECT', async () => { + const proxy = connectProxy({ refuse: true }) + await expect(openTunnel(`http://127.0.0.1:${await proxy.port}`, 'api.push.apple.com', 443)).rejects.toThrow( + 'proxy refused CONNECT: 403' + ) + expect(proxy.seen.url).toBe('api.push.apple.com:443') + }) + + it('rejects when the proxy is not there', async () => { + const closed = net.createServer() + const port = await listen(closed) + closed.close() + await expect(openTunnel(`http://127.0.0.1:${port}`, 'api.push.apple.com', 443)).rejects.toThrow() + }) +}) diff --git a/apps/web/src/server/push-native/tunnel.ts b/apps/web/src/server/push-native/tunnel.ts new file mode 100644 index 00000000..ae40b101 --- /dev/null +++ b/apps/web/src/server/push-native/tunnel.ts @@ -0,0 +1,45 @@ +/** + * A TCP tunnel through the egress proxy, for APNs. + * + * Production has no egress except the pinned proxy in `SPLIT_PUSH_PROXY_URL`. + * Web Push and FCM are HTTP/1.1 and go through `egressFetch`; APNs needs + * HTTP/2, and Node's `http2.connect` has no proxy option. So this opens an + * HTTP CONNECT tunnel and returns the raw socket; the caller wraps it in TLS + * and hands it to `http2.connect({ createConnection })`. + */ +import http from 'node:http' +import type { Socket } from 'node:net' + +const CONNECT_TIMEOUT_MS = 10_000 + +export function openTunnel(proxyUrl: string, host: string, port: number): Promise { + const proxy = new URL(proxyUrl) + const headers: Record = { Host: `${host}:${port}` } + if (proxy.username) { + const credentials = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}` + headers['Proxy-Authorization'] = `Basic ${Buffer.from(credentials).toString('base64')}` + } + return new Promise((resolve, reject) => { + const request = http.request({ + host: proxy.hostname, + port: proxy.port || 80, + method: 'CONNECT', + path: `${host}:${port}`, + headers, + timeout: CONNECT_TIMEOUT_MS, + }) + request.once('connect', (response, socket) => { + if (response.statusCode === 200) { + // The connect timeout must not outlive the handshake: an idle + // HTTP/2 session on this socket is normal. + socket.setTimeout(0) + return resolve(socket) + } + socket.destroy() + reject(new Error(`proxy refused CONNECT: ${response.statusCode}`)) + }) + request.once('timeout', () => request.destroy(new Error('proxy CONNECT timed out'))) + request.once('error', reject) + request.end() + }) +} diff --git a/apps/web/src/server/push.ts b/apps/web/src/server/push.ts index bc621f13..68b8b7ee 100644 --- a/apps/web/src/server/push.ts +++ b/apps/web/src/server/push.ts @@ -1,5 +1,6 @@ /** - * Web-push fan-out for room events. + * Push fan-out for room events: Web Push for browsers, APNs and FCM for the + * store apps (`server/push-native/`). * * The product rule is one line: you get a notification when SOMEBODY ELSE in a * room you opted into writes something. Everything below exists to make that @@ -13,8 +14,11 @@ * entering a trip's worth of receipts in one sitting is one session, not * twenty events. * - * With no VAPID keys configured the whole module is inert — it warns once and - * every send returns `disabled`. That is the local-dev and self-hoster default. + * Each transport turns on with its own credentials: VAPID keys for Web Push, + * the APNs key for iOS, the FCM service account for Android. Rows of a + * transport without credentials are skipped. With none configured the whole + * module is inert — it warns once and every send returns `disabled`. That is + * the local-dev and self-hoster default. */ import { Prisma, type PushSubscription as PushSubscriptionRow } from '@prisma/client' import webpush, { type RequestOptions, WebPushError } from 'web-push' @@ -29,6 +33,10 @@ import { } from '@/server/notifyCopy' import type { RoomWithRelations } from '@/server/roomState' import type { RoomState } from '@/lib/api-types' +import { sendApns } from '@/server/push-native/apns' +import { apnsCredentials, fcmCredentials, type ApnsCredentials, type FcmCredentials } from '@/server/push-native/config' +import { sendFcm } from '@/server/push-native/fcm' +import { toNativeNotification, type NativeNotification } from '@/server/push-native/payload' /** A 20-expense entry session must not fire 20 pushes. Post-delivery coalescing * (one tag per room) would collapse them on the device, but they would still @@ -130,6 +138,8 @@ export async function claimSend( interface SendRoomEventInput { room: RoomWithRelations + /** The room id app notifications carry instead of the slug. */ + analyticsKey: string template: NotificationTemplate /** Whoever caused the event — excluded from delivery. Null when the writer * sent no member token, in which case everyone subscribed gets it. */ @@ -139,13 +149,36 @@ interface SendRoomEventInput { buildPayload: (sendId: string) => PushPayload } +interface Senders { + webPush: boolean + apns: ApnsCredentials | null + fcm: FcmCredentials | null +} + +function configuredSenders(): Senders { + return { webPush: vapidReady(), apns: apnsCredentials(), fcm: fcmCredentials() } +} + +function deliverableTransports(senders: Senders): string[] { + return [ + ...(senders.webPush ? ['webpush'] : []), + ...(senders.apns ? ['apns', 'apns-sandbox'] : []), + ...(senders.fcm ? ['fcm'] : []), + ] +} + export async function sendRoomEvent(input: SendRoomEventInput): Promise { - if (!vapidReady()) return { status: 'disabled' } + const senders = configuredSenders() + const transports = deliverableTransports(senders) + if (transports.length === 0) return { status: 'disabled' } const { room, template, actorMemberId } = input const targets = await prisma.pushSubscription.findMany({ where: { roomId: room.id, + // A row nobody here can deliver to is not a target: counting it + // would burn the dedupe slot on a send that cannot happen. + transport: { in: transports }, // Removal deletes subscriptions transactionally; this relation // filter is defense in depth for legacy/orphaned rows. member: { removedAt: null }, @@ -185,12 +218,17 @@ export async function sendRoomEvent(input: SendRoomEventInput): Promise deliver(target, payload, options))) + const payload = input.buildPayload(claim.id) + const results = await deliverAll( + targets, + payload, + toNativeNotification(payload, { slug: room.slug, analyticsKey: input.analyticsKey }), + senders + ) const dead = results.filter((r) => r.dead).map((r) => r.id) - // A 404/410 is the push service saying the browser threw this endpoint away. + // A 404/410 (or APNs BadDeviceToken, FCM UNREGISTERED) is the push service + // saying the browser or app threw this endpoint away. // Keeping it means retrying a corpse on every future event, forever. if (dead.length > 0) await prisma.pushSubscription.deleteMany({ where: { id: { in: dead } } }) @@ -216,7 +254,44 @@ interface DeliveryResult { statusCode?: number } -async function deliver(target: PushSubscriptionRow, payload: string, options: RequestOptions): Promise { +type WebPushRow = PushSubscriptionRow & { transport: 'webpush'; p256dh: string; auth: string } + +const isWebPushRow = (row: PushSubscriptionRow): row is WebPushRow => + row.transport === 'webpush' && row.p256dh !== null && row.auth !== null + +/** A native row's endpoint is `:`. */ +const nativeToken = (row: PushSubscriptionRow) => row.endpoint.slice(row.transport.length + 1) + +async function deliverAll( + targets: PushSubscriptionRow[], + payload: PushPayload, + notification: NativeNotification, + senders: Senders +): Promise { + const web = targets.filter(isWebPushRow) + const apple = targets.filter((row) => row.transport === 'apns' || row.transport === 'apns-sandbox') + const google = targets.filter((row) => row.transport === 'fcm') + const webPayload = JSON.stringify(payload) + const options = requestOptions() + const [webResults, appleResults, googleResults] = await Promise.all([ + Promise.all(web.map((target) => deliverWebPush(target, webPayload, options))), + senders.apns && apple.length > 0 + ? sendApns( + senders.apns, + apple.map((row) => ({ token: nativeToken(row), sandbox: row.transport === 'apns-sandbox' })), + notification + ) + : [], + senders.fcm && google.length > 0 ? sendFcm(senders.fcm, google.map(nativeToken), notification) : [], + ]) + return [ + ...webResults, + ...appleResults.map((result, index) => ({ id: apple[index].id, ...result })), + ...googleResults.map((result, index) => ({ id: google[index].id, ...result })), + ] +} + +async function deliverWebPush(target: WebPushRow, payload: string, options: RequestOptions): Promise { try { await webpush.sendNotification( { endpoint: target.endpoint, keys: { p256dh: target.p256dh, auth: target.auth } }, @@ -255,6 +330,10 @@ export function notifyRoomWrite(input: { const { room, state, actorMemberId, event } = input const nameOf = (id: string | null | undefined) => room.members.find((m) => m.id === id)?.name ?? null const roomRef = { slug: room.slug, name: room.name, emoji: room.emoji, currency: room.currency } + // `toRoomState` always sets the key; the wire type is optional only so old + // cached client state parses. An empty key would open the app's home, never + // a wrong room. + const analyticsKey = state.room.analyticsKey ?? '' if (event.kind === 'expense_added') { const expense = room.expenses.find((e) => e.id === event.expenseId) @@ -262,6 +341,7 @@ export function notifyRoomWrite(input: { fireAndForget( sendRoomEvent({ room, + analyticsKey, template: 'expense_added', actorMemberId, eventId: expense.id, @@ -284,6 +364,7 @@ export function notifyRoomWrite(input: { fireAndForget( sendRoomEvent({ room, + analyticsKey, template: 'settlement_recorded', actorMemberId, eventId: settlement.id, @@ -308,6 +389,7 @@ export function notifyRoomWrite(input: { fireAndForget( sendRoomEvent({ room, + analyticsKey, template: 'all_settled', actorMemberId, buildPayload: (sendId) => allSettledPayload({ room: roomRef, roomId: room.id, sendId }), diff --git a/apps/web/src/server/test/push.test.ts b/apps/web/src/server/test/push.test.ts index 0e6d3db3..0ad965d0 100644 --- a/apps/web/src/server/test/push.test.ts +++ b/apps/web/src/server/test/push.test.ts @@ -4,7 +4,8 @@ * regression uses real web-push and stubs only the HTTPS request. Prisma stays * real so dedupe claims, daily caps, and endpoint pruning exercise database rules. */ -import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { generateKeyPairSync } from 'node:crypto' import { EventEmitter } from 'node:events' import type { ClientRequest, IncomingMessage } from 'node:http' import https from 'node:https' @@ -20,6 +21,7 @@ import { DELETE as deleteSubscription, POST as postSubscription } from '@/app/ap import { POST as postSubscriptionStatus } from '@/app/api/rooms/[slug]/push-subscriptions/status/route' import { POST as postOpened } from '@/app/api/push/opened/route' import { POST as postDismissed } from '@/app/api/push/dismissed/route' +import { resetFcmToken } from '@/server/push-native/fcm' import type { RoomStateWithMember } from '@/lib/api-types' const { sendNotification } = vi.hoisted(() => ({ sendNotification: vi.fn() })) @@ -240,6 +242,143 @@ describe('subscribe endpoint', () => { }) }) +const APNS_TOKEN = 'a1b2c3d4'.repeat(8) +const FCM_TOKEN = 'dGVzdA:APA91bH-native_device' +const NATIVE_ENV = [ + 'SPLIT_APNS_KEY_P8', + 'SPLIT_APNS_KEY_ID', + 'SPLIT_APNS_TEAM_ID', + 'SPLIT_APNS_BUNDLE_ID', + 'SPLIT_FCM_SERVICE_ACCOUNT_JSON', +] as const + +/** Fake but well-formed credentials: nothing here reaches Apple or Google. */ +function setNativeCredentials(): void { + const ec = generateKeyPairSync('ec', { namedCurve: 'prime256v1' }).privateKey + const rsa = generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey + process.env.SPLIT_APNS_KEY_P8 = ec.export({ type: 'pkcs8', format: 'pem' }).toString() + process.env.SPLIT_APNS_KEY_ID = 'ABC123DEFG' + process.env.SPLIT_APNS_TEAM_ID = 'TEAM123456' + process.env.SPLIT_APNS_BUNDLE_ID = 'com.peanutsplit.app' + process.env.SPLIT_FCM_SERVICE_ACCOUNT_JSON = JSON.stringify({ + project_id: 'split-test', + client_email: 'push@split-test.iam.gserviceaccount.com', + private_key: rsa.export({ type: 'pkcs8', format: 'pem' }).toString(), + }) +} + +function clearNativeCredentials(): void { + for (const name of NATIVE_ENV) delete process.env[name] +} + +const nativeBody = (member: { id: string; token: string }, transport: string, token: string) => ({ + transport, + token, + memberId: member.id, + memberToken: member.token, +}) + +const subscribeNative = (fixture: Fixture, member: { id: string; token: string }, transport: string, token: string) => + call<{ subscribed: boolean } | { error: { code: string } }>(postSubscription as Handler, { + path: `/api/rooms/${fixture.slug}/push-subscriptions`, + method: 'POST', + params: { slug: fixture.slug }, + body: nativeBody(member, transport, token), + }) + +const askNativeStatus = (fixture: Fixture, member: { id: string; token: string }, transport: string, token: string) => + call<{ subscribed: boolean } | { error: { code: string } }>(postSubscriptionStatus as Handler, { + path: `/api/rooms/${fixture.slug}/push-subscriptions/status`, + method: 'POST', + params: { slug: fixture.slug }, + body: nativeBody(member, transport, token), + }) + +describe('native app subscriptions', () => { + afterEach(clearNativeCredentials) + + it('still rejects a web body without keys', async () => { + const fixture = await makeRoom() + const { status, body } = await call<{ error: { code: string } }>(postSubscription as Handler, { + path: `/api/rooms/${fixture.slug}/push-subscriptions`, + method: 'POST', + params: { slug: fixture.slug }, + body: { endpoint: FCM('no-keys'), memberId: fixture.owner.id, memberToken: fixture.owner.token }, + }) + expect(status).toBe(400) + expect(body).toMatchObject({ error: { code: 'VALIDATION_ERROR' } }) + expect(await prisma.pushSubscription.count()).toBe(0) + }) + + it('stores an app token under its prefixed endpoint, without keys', async () => { + setNativeCredentials() + const fixture = await makeRoom() + expect((await subscribeNative(fixture, fixture.owner, 'apns', APNS_TOKEN)).status).toBe(201) + expect((await subscribeNative(fixture, fixture.friend, 'fcm', FCM_TOKEN)).status).toBe(201) + + const rows = await prisma.pushSubscription.findMany({ orderBy: { transport: 'asc' } }) + expect(rows).toMatchObject([ + { transport: 'apns', endpoint: `apns:${APNS_TOKEN}`, p256dh: null, auth: null, memberId: fixture.owner.id }, + { transport: 'fcm', endpoint: `fcm:${FCM_TOKEN}`, p256dh: null, auth: null, memberId: fixture.friend.id }, + ]) + }) + + it('keeps web rows on the webpush transport', async () => { + const fixture = await makeRoom() + await subscribe(fixture, fixture.owner, FCM('a')) + expect(await prisma.pushSubscription.findFirst()).toMatchObject({ transport: 'webpush', endpoint: FCM('a') }) + }) + + it('answers 503 NATIVE_PUSH_UNAVAILABLE on subscribe and status when the server has no credentials', async () => { + clearNativeCredentials() + const fixture = await makeRoom() + + const subscribed = await subscribeNative(fixture, fixture.owner, 'fcm', FCM_TOKEN) + expect(subscribed.status).toBe(503) + expect(subscribed.body).toMatchObject({ error: { code: 'NATIVE_PUSH_UNAVAILABLE' } }) + const status = await askNativeStatus(fixture, fixture.owner, 'apns-sandbox', APNS_TOKEN) + expect(status.status).toBe(503) + expect(status.body).toMatchObject({ error: { code: 'NATIVE_PUSH_UNAVAILABLE' } }) + expect(await prisma.pushSubscription.count()).toBe(0) + + // Web push is not gated on app credentials. + expect((await subscribe(fixture, fixture.owner, FCM('a'))).status).toBe(201) + }) + + it('answers status for a native token per room, and drops it on DELETE', async () => { + setNativeCredentials() + const first = await makeRoom() + const second = await makeRoom() + await subscribeNative(first, first.owner, 'apns-sandbox', APNS_TOKEN) + + expect((await askNativeStatus(first, first.owner, 'apns-sandbox', APNS_TOKEN)).body).toEqual({ + subscribed: true, + }) + expect((await askNativeStatus(second, second.owner, 'apns-sandbox', APNS_TOKEN)).body).toEqual({ + subscribed: false, + }) + // The same token on the other APNs environment is a different channel. + expect((await askNativeStatus(first, first.owner, 'apns', APNS_TOKEN)).body).toEqual({ subscribed: false }) + + const removed = await call<{ subscribed: false; endpointStillUsed: boolean }>(deleteSubscription as Handler, { + path: `/api/rooms/${first.slug}/push-subscriptions`, + method: 'DELETE', + params: { slug: first.slug }, + body: nativeBody(first.owner, 'apns-sandbox', APNS_TOKEN), + }) + expect(removed.body).toEqual({ subscribed: false, endpointStillUsed: false }) + expect(await prisma.pushSubscription.count()).toBe(0) + }) + + it('rejects a web body whose endpoint looks like a native channel', async () => { + const fixture = await makeRoom() + const { status, body } = await subscribe(fixture, fixture.owner, `fcm:${FCM_TOKEN}`) + expect(status).toBe(400) + expect(body).toMatchObject({ error: { code: 'UNSUPPORTED_PUSH_HOST' } }) + expect(await prisma.pushSubscription.count()).toBe(0) + }) +}) + describe('unsubscribe endpoint', () => { it('preserves a channel rebound to another member when the previous member finishes cleanup', async () => { const fixture = await makeRoom() @@ -391,6 +530,7 @@ describe('send pipeline', () => { const room = await loadRoom(fixture.slug) return sendRoomEvent({ room, + analyticsKey: toRoomState(room).room.analyticsKey as string, template: 'expense_added', actorMemberId: fixture.owner.id, eventId, @@ -582,6 +722,7 @@ describe('send pipeline', () => { const settled = () => sendRoomEvent({ room, + analyticsKey: toRoomState(room).room.analyticsKey as string, template: 'all_settled', actorMemberId: fixture.owner.id, buildPayload: (sendId) => allSettledPayload({ room, roomId: room.id, sendId }), @@ -592,6 +733,102 @@ describe('send pipeline', () => { }) }) +describe('native fan-out', () => { + const fetchMock = vi.fn() + + beforeEach(() => { + setNativeCredentials() + resetFcmToken() + fetchMock.mockReset() + vi.stubGlobal('fetch', fetchMock) + delete process.env.SPLIT_PUSH_PROXY_URL + }) + + afterEach(() => { + clearNativeCredentials() + vi.unstubAllGlobals() + vi.restoreAllMocks() + }) + + const seedNative = (roomId: string, memberId: string, transport: string, token: string) => + prisma.pushSubscription.create({ data: { roomId, memberId, transport, endpoint: `${transport}:${token}` } }) + + it('sends FCM without the slug, keeps web push, and prunes an unregistered app token', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const fixture = await makeRoom() + await seedSubscription(fixture.roomId, fixture.friend.id, FCM('friend-browser')) + await seedNative(fixture.roomId, fixture.friend.id, 'fcm', 'live-android') + await seedNative(fixture.roomId, fixture.friend.id, 'fcm', 'gone-android') + + const sent: unknown[] = [] + fetchMock.mockImplementation(async (input, init) => { + if (String(input) === 'https://oauth2.googleapis.com/token') { + return Response.json({ access_token: 'access-1', expires_in: 3600 }) + } + const message = JSON.parse(String(init?.body)) as { message: { token: string } } + sent.push(message) + return message.message.token === 'gone-android' + ? Response.json({ error: { details: [{ errorCode: 'UNREGISTERED' }] } }, { status: 404 }) + : Response.json({ name: 'projects/split-test/messages/1' }) + }) + + const room = await loadRoom(fixture.slug) + const analyticsKey = toRoomState(room).room.analyticsKey as string + const outcome = await sendRoomEvent({ + room, + analyticsKey, + template: 'expense_added', + actorMemberId: fixture.owner.id, + eventId: 'native-1', + buildPayload: (sendId) => + expenseAddedPayload({ + room, + roomId: room.id, + sendId, + actorName: 'Ana', + description: 'Lift passes', + amountMinor: '12000', + currency: 'EUR', + }), + }) + + expect(outcome).toEqual({ status: 'sent', delivered: 2, pruned: 1 }) + expect(sendNotification).toHaveBeenCalledTimes(1) + expect(sent).toHaveLength(2) + for (const message of sent) { + expect(JSON.stringify(message)).not.toContain(fixture.slug) + expect(message).toMatchObject({ + message: { + notification: { title: 'Ski Trip', body: 'Ana added Lift passes — €120.00' }, + data: { room: analyticsKey }, + }, + }) + } + const left = await prisma.pushSubscription.findMany({ orderBy: { endpoint: 'asc' } }) + expect(left.map((row) => row.endpoint)).toEqual(['fcm:live-android', FCM('friend-browser')]) + }) + + it('skips app rows whose transport has no credentials, without burning the dedupe slot', async () => { + clearNativeCredentials() + const fixture = await makeRoom() + await seedNative(fixture.roomId, fixture.friend.id, 'fcm', 'android-without-server-key') + const room = await loadRoom(fixture.slug) + + const outcome = await sendRoomEvent({ + room, + analyticsKey: toRoomState(room).room.analyticsKey as string, + template: 'all_settled', + actorMemberId: fixture.owner.id, + buildPayload: (sendId) => allSettledPayload({ room, roomId: room.id, sendId }), + }) + + expect(outcome).toEqual({ status: 'skipped', reason: 'no-targets' }) + expect(fetchMock).not.toHaveBeenCalled() + expect(await prisma.notificationSend.count()).toBe(0) + expect(await prisma.pushSubscription.count()).toBe(1) + }) +}) + describe('all-settled detection', () => { it('is false for an empty room and true once every balance is zero', async () => { const fixture = await makeRoom() diff --git a/apps/web/src/server/validation.ts b/apps/web/src/server/validation.ts index 2226bfba..8fca1071 100644 --- a/apps/web/src/server/validation.ts +++ b/apps/web/src/server/validation.ts @@ -15,6 +15,8 @@ import { MAX_MEMBERS, MAX_NAME_CHARS, } from '@/lib/splitwise-csv' +import type { NativePushTransport } from '@/lib/api-types' +import { NATIVE_PUSH_TRANSPORTS } from '@/server/push-native/config' /** * A currency code — one of the 162 real ones, or a ticker somebody invented. @@ -274,28 +276,72 @@ const pushKey = z .regex(/^[A-Za-z0-9_\-=]+$/, 'must be base64') const memberSecret = z.string().min(1).max(200) -export const pushSubscribeSchema = z.object({ - endpoint: pushEndpoint, - keys: z.object({ p256dh: pushKey, auth: pushKey }), - memberId: id, - memberToken: memberSecret, - userAgent: z.string().trim().max(512).nullish(), -}) - -export const pushUnsubscribeSchema = z.object({ - endpoint: pushEndpoint, - memberId: id, - memberToken: memberSecret, -}) +const nativeTransport = z.enum(NATIVE_PUSH_TRANSPORTS) +/** + * An APNs device token is hex; an FCM registration token is URL-safe base64 + * with colons. The charset matters beyond tidiness: the APNs token becomes part + * of the HTTP/2 `:path`, so a slash or a question mark must never get through. + */ +const nativeToken = z + .string() + .trim() + .min(1) + .max(1024) + .regex(/^[A-Za-z0-9_:-]+$/, 'must be a device token') +const isTokenShapeFor = (body: { transport: NativePushTransport; token: string }) => + body.transport === 'fcm' || /^[0-9A-Fa-f]+$/.test(body.token) +const nativeEndpoint = (body: { transport: NativePushTransport; token: string }) => `${body.transport}:${body.token}` -/** Asking whether THIS room is on for this endpoint. Same three fields as the - * unsubscribe, and deliberately its own schema: the question is a read, and it - * must stay free to gain a field without widening what a delete accepts. */ -export const pushStatusSchema = z.object({ - endpoint: pushEndpoint, - memberId: id, - memberToken: memberSecret, -}) +/** + * Both bodies normalise to one channel shape: `transport` plus the `endpoint` + * that is stored and looked up. A native token is stored as + * `:`, so `(endpoint, roomId)` uniqueness, the per-room cap + * and the status lookup work the same for every transport. A web body can never + * produce that shape: its URL must pass the https allowlist in the route. + */ +const webChannel = { endpoint: pushEndpoint } +const nativeChannel = { transport: nativeTransport, token: nativeToken } +const membership = { memberId: id, memberToken: memberSecret } +const tokenShapeError = { message: 'must be an APNs device token', path: ['token'] } + +export const pushSubscribeSchema = z.union([ + z + .object({ + ...webChannel, + keys: z.object({ p256dh: pushKey, auth: pushKey }), + ...membership, + userAgent: z.string().trim().max(512).nullish(), + }) + // A web body without keys fails here and then fails the native branch + // too (no transport), so it is still a 400. + .transform((body) => ({ ...body, transport: 'webpush' as const })), + z + .object({ ...nativeChannel, ...membership, userAgent: z.string().trim().max(512).nullish() }) + .refine(isTokenShapeFor, tokenShapeError) + .transform(({ token, ...body }) => ({ + ...body, + endpoint: nativeEndpoint({ transport: body.transport, token }), + keys: null, + })), +]) + +const pushChannelSchema = z.union([ + z.object({ ...webChannel, ...membership }).transform((body) => ({ ...body, transport: 'webpush' as const })), + z + .object({ ...nativeChannel, ...membership }) + .refine(isTokenShapeFor, tokenShapeError) + .transform(({ token, ...body }) => ({ + ...body, + endpoint: nativeEndpoint({ transport: body.transport, token }), + })), +]) + +export const pushUnsubscribeSchema = pushChannelSchema + +/** Asking whether THIS room is on for this channel. Same fields as the + * unsubscribe today, under its own name: the question is a read, and it must + * stay free to gain a field without widening what a delete accepts. */ +export const pushStatusSchema = pushChannelSchema /** What the service worker beacons back on a tap or a swipe-away. Every field is * optional-ish because the worker is fire-and-forget and must never be the diff --git a/apps/web/store/assets/README.md b/apps/web/store/assets/README.md new file mode 100644 index 00000000..724958af --- /dev/null +++ b/apps/web/store/assets/README.md @@ -0,0 +1,17 @@ +# Store images + +Made by `e2e-native/store-screenshots.spec.ts` (`STORE_SCREENSHOTS=1`, Chromium only) in three steps. It captures +the real static export against a local API server at two raw phone sizes into `store/captures/` (gitignored). It +puts each capture in `store/screenshot-frame.html` with its headline and writes the three store sizes to +`screenshots/`, plus `store/captures/contact-sheet.jpg`, one row per store size in upload order, for review. Then it +renders `store/feature-graphic.html` and resizes `resources/icon.png` to the Play icon (a 32-bit PNG, fully +opaque). Both HTML files use Roboto Flex from `@fontsource-variable/roboto-flex` in `node_modules`. + +Build the export with the release default (`pnpm native:build`, so the share screen shows +`https://peanutsplit.com/r/...`), build the web app with `NEXT_PUBLIC_BASE_URL=http://localhost:3100 +NEXT_PUBLIC_SPLIT_V2_ENABLED=1 NEXT_PUBLIC_FOSS_RELEASED=1 pnpm build`, migrate an empty Postgres, then run +`SPLIT_OPENROUTER_API_KEY=placeholder STORE_SCREENSHOTS=1 E2E_DATABASE_URL= pnpm exec playwright test --config +playwright.native.config.ts e2e-native/store-screenshots.spec.ts --project chromium --workers=1` (the key is a +placeholder that only turns on the scan button; the spec answers the scan request itself). Check the result with +`node store/check-assets.mjs`. Konrad approves every image before upload from the contact sheet +(`store/screenshots.md`). diff --git a/apps/web/store/assets/feature-graphic.jpg b/apps/web/store/assets/feature-graphic.jpg new file mode 100644 index 00000000..ea3114bd Binary files /dev/null and b/apps/web/store/assets/feature-graphic.jpg differ diff --git a/apps/web/store/assets/play-icon.png b/apps/web/store/assets/play-icon.png new file mode 100644 index 00000000..64e05f2a Binary files /dev/null and b/apps/web/store/assets/play-icon.png differ diff --git a/apps/web/store/assets/screenshots/android-phone/1-room.jpg b/apps/web/store/assets/screenshots/android-phone/1-room.jpg new file mode 100644 index 00000000..6db17305 Binary files /dev/null and b/apps/web/store/assets/screenshots/android-phone/1-room.jpg differ diff --git a/apps/web/store/assets/screenshots/android-phone/2-add-expense.jpg b/apps/web/store/assets/screenshots/android-phone/2-add-expense.jpg new file mode 100644 index 00000000..66073714 Binary files /dev/null and b/apps/web/store/assets/screenshots/android-phone/2-add-expense.jpg differ diff --git a/apps/web/store/assets/screenshots/android-phone/3-receipt-scan.jpg b/apps/web/store/assets/screenshots/android-phone/3-receipt-scan.jpg new file mode 100644 index 00000000..32949bf1 Binary files /dev/null and b/apps/web/store/assets/screenshots/android-phone/3-receipt-scan.jpg differ diff --git a/apps/web/store/assets/screenshots/android-phone/4-share.jpg b/apps/web/store/assets/screenshots/android-phone/4-share.jpg new file mode 100644 index 00000000..4021993f Binary files /dev/null and b/apps/web/store/assets/screenshots/android-phone/4-share.jpg differ diff --git a/apps/web/store/assets/screenshots/android-phone/5-home.jpg b/apps/web/store/assets/screenshots/android-phone/5-home.jpg new file mode 100644 index 00000000..3aee6271 Binary files /dev/null and b/apps/web/store/assets/screenshots/android-phone/5-home.jpg differ diff --git a/apps/web/store/assets/screenshots/iphone-6.3/1-room.jpg b/apps/web/store/assets/screenshots/iphone-6.3/1-room.jpg new file mode 100644 index 00000000..782a0616 Binary files /dev/null and b/apps/web/store/assets/screenshots/iphone-6.3/1-room.jpg differ diff --git a/apps/web/store/assets/screenshots/iphone-6.3/2-add-expense.jpg b/apps/web/store/assets/screenshots/iphone-6.3/2-add-expense.jpg new file mode 100644 index 00000000..a0495e3e Binary files /dev/null and b/apps/web/store/assets/screenshots/iphone-6.3/2-add-expense.jpg differ diff --git a/apps/web/store/assets/screenshots/iphone-6.3/3-receipt-scan.jpg b/apps/web/store/assets/screenshots/iphone-6.3/3-receipt-scan.jpg new file mode 100644 index 00000000..646ce692 Binary files /dev/null and b/apps/web/store/assets/screenshots/iphone-6.3/3-receipt-scan.jpg differ diff --git a/apps/web/store/assets/screenshots/iphone-6.3/4-share.jpg b/apps/web/store/assets/screenshots/iphone-6.3/4-share.jpg new file mode 100644 index 00000000..0809ab62 Binary files /dev/null and b/apps/web/store/assets/screenshots/iphone-6.3/4-share.jpg differ diff --git a/apps/web/store/assets/screenshots/iphone-6.3/5-home.jpg b/apps/web/store/assets/screenshots/iphone-6.3/5-home.jpg new file mode 100644 index 00000000..bff3b11b Binary files /dev/null and b/apps/web/store/assets/screenshots/iphone-6.3/5-home.jpg differ diff --git a/apps/web/store/assets/screenshots/iphone-6.9/1-room.jpg b/apps/web/store/assets/screenshots/iphone-6.9/1-room.jpg new file mode 100644 index 00000000..17ee6b9f Binary files /dev/null and b/apps/web/store/assets/screenshots/iphone-6.9/1-room.jpg differ diff --git a/apps/web/store/assets/screenshots/iphone-6.9/2-add-expense.jpg b/apps/web/store/assets/screenshots/iphone-6.9/2-add-expense.jpg new file mode 100644 index 00000000..8572e1bb Binary files /dev/null and b/apps/web/store/assets/screenshots/iphone-6.9/2-add-expense.jpg differ diff --git a/apps/web/store/assets/screenshots/iphone-6.9/3-receipt-scan.jpg b/apps/web/store/assets/screenshots/iphone-6.9/3-receipt-scan.jpg new file mode 100644 index 00000000..a3900cd9 Binary files /dev/null and b/apps/web/store/assets/screenshots/iphone-6.9/3-receipt-scan.jpg differ diff --git a/apps/web/store/assets/screenshots/iphone-6.9/4-share.jpg b/apps/web/store/assets/screenshots/iphone-6.9/4-share.jpg new file mode 100644 index 00000000..e09f2870 Binary files /dev/null and b/apps/web/store/assets/screenshots/iphone-6.9/4-share.jpg differ diff --git a/apps/web/store/assets/screenshots/iphone-6.9/5-home.jpg b/apps/web/store/assets/screenshots/iphone-6.9/5-home.jpg new file mode 100644 index 00000000..11e79d74 Binary files /dev/null and b/apps/web/store/assets/screenshots/iphone-6.9/5-home.jpg differ diff --git a/apps/web/store/check-assets.mjs b/apps/web/store/check-assets.mjs new file mode 100644 index 00000000..aa2f195d --- /dev/null +++ b/apps/web/store/check-assets.mjs @@ -0,0 +1,63 @@ +/** + * Checks the store images in store/assets/ before anyone uploads them (PLAN 7.3, + * store/screenshots.md): every expected file exists and has the exact pixel size the store asks + * for. The screenshots and the feature graphic have no alpha channel (both stores reject + * transparency in screenshots). The Play icon is the 32-bit PNG Play asks for: it has an alpha + * channel, and every pixel of it is fully opaque. + * + * node apps/web/store/check-assets.mjs (from the repo root, or `node store/check-assets.mjs`) + * + * Exits 1 and lists every problem when anything is missing or wrong. + */ +import { existsSync, statSync } from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import sharp from 'sharp' + +const ASSETS = path.join(path.dirname(fileURLToPath(import.meta.url)), 'assets') + +const SCREENS = ['1-room', '2-add-expense', '3-receipt-scan', '4-share', '5-home'] +const SETS = { + 'iphone-6.9': [1320, 2868], + 'iphone-6.3': [1206, 2622], + 'android-phone': [1080, 1920], +} + +const expected = [ + ...Object.entries(SETS).flatMap(([set, [width, height]]) => + SCREENS.map((screen) => ({ + file: `screenshots/${set}/${screen}.jpg`, + width, + height, + format: 'jpeg', + channels: 3, + })) + ), + { file: 'feature-graphic.jpg', width: 1024, height: 500, format: 'jpeg', channels: 3 }, + // Play: 512 x 512 32-bit PNG, at most 1024 KB. + { file: 'play-icon.png', width: 512, height: 512, format: 'png', channels: 4, maxBytes: 1024 * 1024 }, +] + +const problems = [] +for (const { file, width, height, format, channels, maxBytes } of expected) { + const full = path.join(ASSETS, file) + if (!existsSync(full)) { + problems.push(`${file}: missing`) + continue + } + const meta = await sharp(full).metadata() + if (meta.format !== format) problems.push(`${file}: format ${meta.format}, expected ${format}`) + if (meta.width !== width || meta.height !== height) + problems.push(`${file}: ${meta.width}x${meta.height}, expected ${width}x${height}`) + if (meta.channels !== channels) problems.push(`${file}: ${meta.channels} channels, expected ${channels}`) + else if (channels === 4 && (await sharp(full).stats()).channels[3].min !== 255) + problems.push(`${file}: has transparent pixels`) + const bytes = statSync(full).size + if (maxBytes && bytes > maxBytes) problems.push(`${file}: ${bytes} bytes, over ${maxBytes}`) +} + +if (problems.length > 0) { + console.error(`check-assets: ${problems.length} problem(s)\n${problems.map((line) => ` - ${line}`).join('\n')}`) + process.exit(1) +} +console.log(`check-assets: ${expected.length} images ok (exact sizes; opaque, 32-bit Play icon)`) diff --git a/apps/web/store/check-listing.mjs b/apps/web/store/check-listing.mjs new file mode 100644 index 00000000..ce9fc228 --- /dev/null +++ b/apps/web/store/check-listing.mjs @@ -0,0 +1,158 @@ +#!/usr/bin/env node +// Checks the store texts before anyone pastes them into App Store Connect or Play Console. +// +// listing.md: every required field exists, its stated length matches its text, the text fits the +// store limit, and no field uses a word the stores or the product rules forbid (PLAN 7.1). +// review-notes.md: every double-quoted string is a UI label that exists in en.json, so a +// reviewer who looks for it finds it on screen. +// +// Usage: node apps/web/store/check-listing.mjs [--listing ] [--review-notes ] +// Exits 1 and names the field or the label on the first kind of failure it finds. + +import { readFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' + +const here = dirname(fileURLToPath(import.meta.url)) + +function argValue(name, fallback) { + const at = process.argv.indexOf(name) + return at === -1 ? fallback : process.argv[at + 1] +} + +const listingPath = argValue('--listing', join(here, 'listing.md')) +const reviewNotesPath = argValue('--review-notes', join(here, 'review-notes.md')) +const enPath = join(here, '..', 'src', 'i18n', 'messages', 'en.json') + +// Store limits from PLAN 7.1. The limit written in listing.md must agree, so the file never +// advertises a looser limit than the store applies. +const LIMITS = { + 'ios.name': 30, + 'ios.subtitle': 30, + 'ios.keywords': 100, + 'ios.promotionalText': 170, + 'ios.description': 4000, + 'play.title': 30, + 'play.shortDescription': 80, + 'play.fullDescription': 4000, +} + +const REQUIRED = [ + ...Object.keys(LIMITS), + 'ios.category', + 'ios.privacyUrl', + 'ios.supportUrl', + 'ios.copyright', + 'play.category', + 'play.contactEmail', + 'play.privacyUrl', +] + +// Words that would invite finance or crypto review, describe Split as a website, or overpromise +// offline use (mono split-content/product/truths.md, offline-creates-only). +const BANNED_EVERYWHERE = [ + /\bcrypto\w*/i, + /\bwallets?\b/i, + /\bstablecoins?\b/i, + /\bUSDC\b/i, + /\bdigital dollars?\b/i, + /\bpayments?\b/i, + /\bsend(?:s|ing)? money\b/i, + /\btransfers?\b/i, + /\bbank(?:s|ing)?\b/i, + /\bPWA\b/i, + /\bweb ?apps?\b/i, + /\bworks? offline\b/i, + /\bopens? offline\b/i, + // Peanut appears only as part of the product name, never as a way to pay. The support + // address (support@peanut.me) is the one other allowed use. + /(? field.limit) failures.push(`${id}: ${actual} characters, over the limit of ${field.limit}`) + } + const platformBans = id.startsWith('ios.') ? BANNED_IOS : BANNED_PLAY + for (const pattern of [...BANNED_EVERYWHERE, ...platformBans]) { + const hit = field.text.match(pattern) + if (hit) failures.push(`${id}: banned word "${hit[0]}"`) + } + if (id === 'ios.keywords' && /\s/.test(field.text)) failures.push(`${id}: keywords contain whitespace`) + } +} + +function flattenValues(node, out) { + if (typeof node === 'string') out.add(node) + else if (node && typeof node === 'object') for (const value of Object.values(node)) flattenValues(value, out) + return out +} + +function checkReviewNotes() { + const labels = flattenValues(JSON.parse(readFileSync(enPath, 'utf8')), new Set()) + const notes = readFileSync(reviewNotesPath, 'utf8') + // Straight and curly double quotes both mark a UI label in the notes. + for (const match of notes.matchAll(/"([^"\n]+)"|“([^”\n]+)”/g)) { + const label = match[1] ?? match[2] + if (!labels.has(label)) failures.push(`review-notes: "${label}" is not a value in en.json`) + } +} + +checkListing() +checkReviewNotes() + +if (failures.length > 0) { + for (const failure of failures) console.error(failure) + process.exit(1) +} +console.log('store texts ok') diff --git a/apps/web/store/feature-graphic.html b/apps/web/store/feature-graphic.html new file mode 100644 index 00000000..e9fcd0b0 --- /dev/null +++ b/apps/web/store/feature-graphic.html @@ -0,0 +1,124 @@ + + + + + + Peanut Split feature graphic + + + +
+
PEANUT SPLIT
+

GOOD ACCOUNTING
MAKES GOOD
FRIENDS.

+

Share one link. Everyone adds what they paid.

+
+ No signup + Scan receipts + 156 currencies +
+
+ + + + diff --git a/apps/web/store/listing.md b/apps/web/store/listing.md new file mode 100644 index 00000000..41c1c2bc --- /dev/null +++ b/apps/web/store/listing.md @@ -0,0 +1,241 @@ +# Store listing: Peanut Split v1 + +Every text field for App Store Connect and Play Console, English (US) only. Paste each fenced block +as it stands. Every claim matches mono `split-content/product/truths.md`; change a claim there +first. + +`node apps/web/store/check-listing.mjs` checks this file. Run it after every edit. + +## Field format + +The checker reads only the fields written in this shape: + +````md +### `ios.name`: App Store name + +Limit: 30. Length: 25. + +```text +Peanut Split: Split Bills +``` +```` + +- The heading starts with the field id in backticks. `ios.*` fields go to App Store Connect and + `play.*` fields go to Play Console. +- `Limit` is the store limit in characters, or `none`. `Length` is the character count of the + fenced text. The checker counts the text again and fails when the two numbers differ or the text + is over the limit. +- The fenced block is the exact field text. Line breaks count as one character each. + +Rules the checker enforces on every field: no crypto, wallet, stablecoin, USDC, digital dollars, +payments, send money, transfer, bank, PWA, web app or "works offline"; "Peanut" only as part of +"Peanut Split"; no competitor names. No Android or Google Play words in `ios.*` fields. No iPhone, +iPad, iOS or App Store words in `play.*` fields. + +## App Store Connect + +### `ios.name`: App Store name + +Limit: 30. Length: 25. + +```text +Peanut Split: Split Bills +``` + +### `ios.subtitle`: Subtitle + +Limit: 30. Length: 25. + +```text +Group expenses, no signup +``` + +### `ios.keywords`: Keywords + +Commas, no spaces. Words already in the name and subtitle are left out, because Apple indexes those +fields too. + +Limit: 100. Length: 96. + +```text +trip,travel,roommates,friends,owe,iou,receipt,scan,costs,share,dinner,vacation,rent,currency,tab +``` + +### `ios.promotionalText`: Promotional text + +Limit: 170. Length: 160. + +```text +Good accounting makes good friends. Share one link with your group, everyone picks their name and adds what they paid, and Split shows who owes whom. No signup. +``` + +### `ios.description`: Description + +Limit: 4000. Length: 2123. + +```text +Good accounting makes good friends. Split keeps track of shared costs for trips, shared homes, dinners and anything else a group pays for together. + +HOW IT WORKS +1. Start a room and share its link in your group chat. +2. Everyone opens the link and picks their name. There is no signup, no email and no password. +3. Everyone adds what they paid. +4. Split shows every balance and a short plan of who owes whom. + +The link is the key to the room, so keep it in the chat. + +WHAT YOU CAN DO +• Add an expense in a few taps: who paid, how much, and who it was for. Split it equally, by percentage, by shares or by exact amounts. +• Scan a receipt with your camera. Split reads the items, you check them, then tap who had what. With your permission, Split sends the photo to Google Gemini, through OpenRouter, to be read. Split's server does not save the image. +• Mark a debt as settled when someone pays it back, however they paid. +• Add expenses in other currencies. Split converts them automatically for 156 currencies at the day's indicative rate. The rate is fixed when the expense is added, so history does not move. +• Turn on notifications for a room to hear when someone adds an expense. +• Tap a room link and the room opens in the app. +• Share a room link with your phone's share sheet. + +MADE FOR GROUPS +A room holds up to twenty people. Everyone sees the same numbers and the same history of changes. + +WHEN THE SIGNAL DROPS +Rooms need a connection to load. If you lose signal in an open room, Split can hold a new expense paid by someone already in the room and try again when you reconnect. + +NO ACCOUNT +Your phone keeps your list of rooms and which member you are in each one. There is no account to sign in to. Rooms, with the names and expenses in them, are stored on our servers so the whole group sees the same numbers. + +LANGUAGES +English, German, Spanish, French, Polish, Portuguese and Ukrainian. + +FREE +Split is free to use and has no paid tier. Squirrel Labs maintains Split and pays every project cost. + +Privacy policy: https://peanutsplit.com/privacy +Source code (AGPL-3.0-or-later): https://peanutsplit.com/source +``` + +### `ios.category`: Category + +Limit: none. + +```text +Primary: Utilities. Secondary: Productivity. +``` + +### `ios.privacyUrl`: Privacy policy URL + +Limit: none. + +```text +https://peanutsplit.com/privacy +``` + +### `ios.supportUrl`: Support URL + +The page's contact section shows `support@peanut.me`. + +Limit: none. + +```text +https://peanutsplit.com/privacy#contact +``` + +### `ios.copyright`: Copyright + +Limit: none. + +```text +© 2026 Squirrel Labs Ltd +``` + +## Play Console + +### `play.title`: App name + +Limit: 30. Length: 25. + +```text +Peanut Split: Split Bills +``` + +### `play.shortDescription`: Short description + +Limit: 80. Length: 78. + +```text +One link for your group. Everyone adds expenses. See who owes whom. No signup. +``` + +### `play.fullDescription`: Full description + +The same text as `ios.description`. It already uses no platform words, so one text serves both +stores. + +Limit: 4000. Length: 2123. + +```text +Good accounting makes good friends. Split keeps track of shared costs for trips, shared homes, dinners and anything else a group pays for together. + +HOW IT WORKS +1. Start a room and share its link in your group chat. +2. Everyone opens the link and picks their name. There is no signup, no email and no password. +3. Everyone adds what they paid. +4. Split shows every balance and a short plan of who owes whom. + +The link is the key to the room, so keep it in the chat. + +WHAT YOU CAN DO +• Add an expense in a few taps: who paid, how much, and who it was for. Split it equally, by percentage, by shares or by exact amounts. +• Scan a receipt with your camera. Split reads the items, you check them, then tap who had what. With your permission, Split sends the photo to Google Gemini, through OpenRouter, to be read. Split's server does not save the image. +• Mark a debt as settled when someone pays it back, however they paid. +• Add expenses in other currencies. Split converts them automatically for 156 currencies at the day's indicative rate. The rate is fixed when the expense is added, so history does not move. +• Turn on notifications for a room to hear when someone adds an expense. +• Tap a room link and the room opens in the app. +• Share a room link with your phone's share sheet. + +MADE FOR GROUPS +A room holds up to twenty people. Everyone sees the same numbers and the same history of changes. + +WHEN THE SIGNAL DROPS +Rooms need a connection to load. If you lose signal in an open room, Split can hold a new expense paid by someone already in the room and try again when you reconnect. + +NO ACCOUNT +Your phone keeps your list of rooms and which member you are in each one. There is no account to sign in to. Rooms, with the names and expenses in them, are stored on our servers so the whole group sees the same numbers. + +LANGUAGES +English, German, Spanish, French, Polish, Portuguese and Ukrainian. + +FREE +Split is free to use and has no paid tier. Squirrel Labs maintains Split and pays every project cost. + +Privacy policy: https://peanutsplit.com/privacy +Source code (AGPL-3.0-or-later): https://peanutsplit.com/source +``` + +### `play.category`: App category + +Limit: none. + +```text +Productivity +``` + +### `play.contactEmail`: Contact email + +Limit: none. + +```text +support@peanut.me +``` + +### `play.privacyUrl`: Privacy policy URL + +Limit: none. + +```text +https://peanutsplit.com/privacy +``` + +## Names outside the text fields + +- Store name: "Peanut Split". Home-screen name: "Split" (decision 8.3 #7 in the plan). +- App type: app. Price: free. Default language: English (United States). +- Marketing URL (App Store, optional): leave empty in v1. diff --git a/apps/web/store/privacy-answers.md b/apps/web/store/privacy-answers.md new file mode 100644 index 00000000..a9ead56c --- /dev/null +++ b/apps/web/store/privacy-answers.md @@ -0,0 +1,136 @@ +# Privacy and declaration answers: Peanut Split v1 + +The answers for App Store Connect (App Privacy, age rating, export compliance) and Play Console (App +content). Each answer has a one-line source. "research" means +`local/split-native-app/research/store-requirements.md` in the planning folder; file paths are under +`apps/web/`. + +These answers describe the app build. The website at peanutsplit.com also loads Google Ads and X Ads +conversion tags; no app page renders them, and the native postbuild check fails if their hosts +appear in the export. That is why every tracking answer below is No. + +Over-declaring never causes a rejection, but under-declaring can (research 1.6). Where a call was +close, the answer declares the data. + +## Recipients + +Every recipient below is named on `https://peanutsplit.com/privacy` +(`src/app/(product-shell)/privacy/page.tsx`). The bold name is the wording the page uses. Add a +recipient to the page in the same push as you add it here. + +- **Apple Push Notification service**: delivers notifications on iPhone. It can read the + notification title and text, which include names and amounts. Source: ARCHITECTURE 10.2, + `src/server/push-native/apns.ts`. +- **Firebase Cloud Messaging**: delivers notifications on Android, operated by Google. It can read + the notification title and text, which include names and amounts. Source: ARCHITECTURE 10.2, + `src/server/push-native/fcm.ts`. +- **Google Gemini, through OpenRouter**: reads a receipt photo, only after the person allows it in + the app (`src/server/model.ts`). The in-app consent names the same provider. Source: research 1.4 (Apple 5.1.2(i)), PLAN 4.2 `room.scan.consent.body`. +- **PostHog**: product analytics, with no room link, name or amount on any event. Source: + `src/lib/analytics.ts`, ARCHITECTURE 12.1. +- **Sentry**: error reports, with room links removed before sending. Source: + `src/instrumentation-client.ts`, `src/lib/redact.ts`. +- **hosting provider**: ordinary request logs, including IP addresses. Source: privacy page, + "Who else is involved". + +Not in the app: Google Ads and X Ads (website only, ARCHITECTURE 12.4). + +## Apple: App Privacy labels (App Store Connect → App Privacy) + +Data collection: **Yes**. Tracking: **No**. Data used to track you: **none**. + +| Data type | Collected | Purposes | Linked to the person | Used for tracking | Source | +| ------------------------------------------------------------------------------------------------------------------- | --------- | ---------------------------- | -------------------- | ----------------- | ------------------------------------------------------------------------------------------------------ | +| Contact Info → Name (display name picked in a room) | Yes | App Functionality | Yes | No | research 2.3 (Play maps it as Name); declared on Apple too for one consistent answer | +| User Content → Photos or Videos (receipt photo, sent once, not stored) | Yes | App Functionality | No | No | research 1.6; privacy page "Photographs of receipts" | +| User Content → Customer Support ("Report a problem": message, optional screenshot, device details) | Yes | App Functionality | No | No | `src/lib/feedback-contract.ts`; deleted after 90 days | +| User Content → Other User Content (room name, expense descriptions, reactions) | Yes | App Functionality | Yes | No | research 1.6, conservative Yes: it sits under a room and member token | +| Identifiers → User ID (member id and member token in a room) | Yes | App Functionality | Yes | No | conservative: the token says which member of a room you are (privacy page "What stays on your device") | +| Identifiers → Device ID (PostHog anonymous id, push token) | Yes | Analytics, App Functionality | Yes | No | research 1.6; `src/lib/analytics.ts`; ARCHITECTURE 10 | +| Usage Data → Product Interaction (PostHog events, no slug, name or amount) | Yes | Analytics | Yes | No | research 1.6, linked through the device id | +| Diagnostics → Crash Data (Sentry, errors only) | Yes | App Functionality | No | No | research 1.6 | +| Diagnostics → Other Diagnostic Data (error context; device details in a problem report) | Yes | App Functionality | No | No | `src/lib/feedback-contract.ts` `FeedbackDiagnostics` | +| Financial Info, Location, Contacts, Health and Fitness, Browsing History, Search History, Sensitive Info, Purchases | No | | | | research 1.6: amounts typed into a room are user content, not the person's own financial records | + +## Apple: privacy manifest mapping (`ios/App/App/PrivacyInfo.xcprivacy`) + +The manifest must say what the labels say. Source: research 1.5 and 5 (iOS checklist). + +| Key | Value | +| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `NSPrivacyTracking` | `false` | +| `NSPrivacyTrackingDomains` | empty array | +| `NSPrivacyCollectedDataTypes` | one entry per "Yes" row above: `NSPrivacyCollectedDataTypeName`, `…PhotosorVideos`, `…CustomerSupport`, `…OtherUserContent`, `…UserID`, `…DeviceID`, `…ProductInteraction`, `…CrashData`, `…OtherDiagnosticData`; each with `NSPrivacyCollectedDataTypeTracking = false`, `NSPrivacyCollectedDataTypeLinked` as in the table, and purposes `NSPrivacyCollectedDataTypePurposeAppFunctionality` or `…PurposeAnalytics` as in the table | +| `NSPrivacyAccessedAPITypes` | `NSPrivacyAccessedAPICategoryUserDefaults` with reason `CA92.1` (`@capacitor/preferences`, push plugin); `NSPrivacyAccessedAPICategoryFileTimestamp` with reason `C617.1` (as peanut-ui) | + +After the first upload, App Store Connect emails any ITMS-91053 missing-reason warning to the +account holder. That email is the final check (research 1.5). + +## Apple: age rating (App Store Connect → App Information → Age Rating) + +Source: research 1.7 and 1.8. The resulting rating is UNVERIFIED (likely 4+ or 9+). + +| Question | Answer | Why | +| ---------------------------------------------------------------------------------------------------------------- | --------- | ---------------------------------------------------------------------------- | +| Violence, sexual content, nudity, profanity, horror, mature themes, alcohol, tobacco, drugs, medical information | None | Split shows only what a group types about shared costs | +| Simulated gambling, contests, loot boxes | None / No | no games or prizes | +| Unrestricted web access | No | external links open in the system browser, outside the app (INTERACTION 2.8) | +| User-generated content | Yes | room and expense text is visible to everyone holding the room link | +| Messaging and chat | No | no in-room messaging (ROADMAP "Deliberately not building") | +| Advertising | No | no ads in the app (ARCHITECTURE 12.4) | +| Social-media questions (added 9 Jul 2026) | No | no feed, no public profiles, no followers | +| Shared Location (from 16 Nov 2026) | No | Split never reads location | +| Dating and Relationships (from 16 Nov 2026) | No | not a dating app | +| Parental controls, age assurance | No | none in the app | + +## Apple: export compliance + +- `ITSAppUsesNonExemptEncryption = false` in `ios/App/App/Info.plist`. Split uses only the HTTPS + that the OS provides, so it is exempt and App Store Connect asks nothing per build. Source: + research 1.9. + +## Apple and Google: remotely loaded code + +- **No remotely loaded code.** All JavaScript and CSS ship in the binary. There is no OTA update, no + ad tag and no CDN script. In the app PostHog runs with `disable_external_dependency_loading`, so a + dashboard setting cannot load new code. Source: research 1.3 (Apple 2.5.2), ARCHITECTURE 12.1 and + 12.4, PLAN 4.3. + +## Google: Data safety (Play Console → App content → Data safety) + +Source: research 2.3. + +| Category | Data type | Collected | Shared | Optional | Purposes | Processed ephemerally | +| ------------------------ | --------------------------------------------------------------------- | --------- | ------ | ------------------------- | ---------------------------- | --------------------- | +| Personal info | Name (display name in a room) | Yes | No | No, needed to join a room | App functionality | No | +| Photos and videos | Photos (receipt scan) | Yes | No | Yes | App functionality | Yes | +| App activity | App interactions | Yes | No | No | Analytics | No | +| App activity | Other user-generated content (room and expense text, problem reports) | Yes | No | No | App functionality | No | +| App info and performance | Crash logs | Yes | No | No | App functionality | No | +| App info and performance | Diagnostics | Yes | No | No | App functionality | No | +| Device or other IDs | Device or other IDs (PostHog id, FCM token) | Yes | No | No | Analytics, App functionality | No | + +- "Shared" is No for every row: PostHog, Sentry, Google Gemini through OpenRouter, and Firebase Cloud + Messaging act as service providers. Google's service-provider wording is UNVERIFIED (research 2.3). +- Data encrypted in transit: **Yes** (HTTPS only). +- Account creation: **No accounts**, so the account-deletion URL does not apply. Source: research 2.3 + and 8. +- Users can request that their data is deleted: **Yes**, by email to `support@peanut.me` with the + room link; rooms have no delete button. Source: privacy page "Your rights". +- Location, financial info, health, messages, contacts, calendar, audio, files, web browsing: **No**. + +## Google: other App content answers + +| Form | Answer | Source | +| --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------- | +| Privacy policy | `https://peanutsplit.com/privacy` | PLAN 7.1 | +| Ads | No, the app contains no ads | research 2.5 | +| Advertising ID | No; the merged manifest has no `com.google.android.gms.permission.AD_ID` | research 2.3 | +| App access | All functionality is available without special access. If the form offers an instructions field, paste the review room link there and nowhere in the repo | research 2.5; review-notes.md | +| Content rating (IARC) | Category Utility, Productivity, Communication or Other. Every question No, except "Users can interact or exchange content": Yes. Shares location: No. Digital purchases: No. Cash Convertible Rewards: No. Unrestricted internet: No. Expected Everyone / PEGI 3 with "Users Interact", UNVERIFIED | research 2.5 | +| Target audience and content | 18 and over only | research 2.5; privacy page "Children" | +| Financial features | "My app doesn't provide any financial features." | research 2.4 and 4 point 7 | +| Government apps | No | research 6 | +| Health apps | No | research 6 | +| News apps | No | research 6 | +| Data safety | as above | research 2.3 | diff --git a/apps/web/store/review-notes.md b/apps/web/store/review-notes.md new file mode 100644 index 00000000..019a9b72 --- /dev/null +++ b/apps/web/store/review-notes.md @@ -0,0 +1,67 @@ +# Review notes: Peanut Split v1 + +Paste the Apple block into App Store Connect → App Review Information → Notes, and the Google block +into the Play Console fields named below. Replace `` only in the consoles. This +repository is public and a room link is the room's credential, so the real link never goes into a +file here. It comes from HANDOFF step K2 (`scripts/native/seed-review-room.mjs`). + +`node apps/web/store/check-listing.mjs` checks that every double-quoted label in this file exists in +`src/i18n/messages/en.json`. Quote only exact UI labels. + +## What each native feature depends on + +Before you submit, check that the HANDOFF step behind each feature is done (`docs/NATIVE-HANDOFF.md`). +The reviewer tests these. + +| Native feature | HANDOFF step it depends on | +| ------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- | +| Push notifications per room (APNs on iOS, Firebase Cloud Messaging on Android) | Step 6 (production push credentials and egress), using the keys from steps 3 and 4. Without step 6 the notification row is hidden | +| Universal links into rooms (iOS) | Step 1 (the apple-app-site-association file live on peanutsplit.com) | +| App Links into rooms (Android) | Step 9 (the Play App Signing SHA-256 in `assetlinks.json`, live on peanutsplit.com) | +| Native share sheet | None | +| Camera receipt scan | Step K2 (the receipt-parse check reports scanning enabled in production). Apple 2.5.19: the feature must be on during review | + +## Apple: App Review notes + +```text +No login is needed. Split has no accounts. + +To start: tap "New split" on the home screen, add two names, then tap "Add expense". Or open this test room, which already has people, expenses and balances: + +Peanut Split is a bundled app. The UI ships in the binary. Rooms need a connection to load, and the app can hold a new expense paid by someone already in that room when the signal drops, and try it again when you reconnect. Edits, settlements and a new payer need a connection. + +Native features: +1. Push notifications per room, through APNs: Room → "Settings" → Notifications. Turn on the row named after the room. iOS asks for permission at that tap, never at launch. +2. Universal links. Tap a room link (https://peanutsplit.com/r/...) in Messages or Mail and the room opens in the app. +3. Native share sheet for the room link and share cards. +4. Camera receipt scan. In a room, tap "Add expense", then "Scan receipt". Before the first photo leaves the phone, the app asks "Read this receipt with AI?" and sends nothing until you tap "Allow". The photo then goes once to Google Gemini through OpenRouter. Split's server does not save the image. Room "Settings" has a "Read receipts with AI" switch to change the choice. + +Accounts: Split has no accounts, so account deletion does not apply. A room is shared by its link; joining means picking a display name in that room. To leave a room, open "Settings" and tap "Leave room". + +User-generated content: rooms are private to the people who hold the link. To report a problem, open "Settings" and tap "Report a problem", or write to support@peanut.me. The "Privacy" link in room "Settings" and on the home screen opens https://peanutsplit.com/privacy. + +Money: Split records who paid whom. It does not move money. Peanut is one of three labels for how a debt was settled (cash, bank transfer, Peanut), and it opens the separate Peanut website in the browser. +``` + +## Google: Play Console + +App content → App access: answer _All functionality is available without special access_. If the +form offers an instructions field, paste this block there with the real room link. + +```text +No login is needed. Split has no accounts. + +To start: tap "New split" on the home screen, add two names, then tap "Add expense". Or open this test room, which already has people, expenses and balances: + +The UI ships in the app. Rooms need a connection to load, and the app can hold a new expense paid by someone already in that room when the signal drops, and try it again when you reconnect. Edits, settlements and a new payer need a connection. + +Notifications: Room → "Settings" → Notifications. Turn on the row named after the room. Android asks for permission at that tap, never at launch. + +Room links (https://peanutsplit.com/r/...) open in the app through App Links. + +Receipt scan: in a room, tap "Add expense", then "Scan receipt". The app asks "Read this receipt with AI?" and sends nothing until you tap "Allow". + +To leave a room: "Settings", then "Leave room". To report a problem: "Settings", then "Report a problem", or support@peanut.me. + +Split records who paid whom. It does not move money. Peanut is one of three labels for how a debt was settled, and it opens the separate Peanut website in the browser. +``` diff --git a/apps/web/store/screenshot-frame.html b/apps/web/store/screenshot-frame.html new file mode 100644 index 00000000..38ab8ab3 --- /dev/null +++ b/apps/web/store/screenshot-frame.html @@ -0,0 +1,159 @@ + + + + + + + Peanut Split screenshot frame + + + +

+

+
+ + + diff --git a/apps/web/store/screenshots.md b/apps/web/store/screenshots.md new file mode 100644 index 00000000..1805e333 --- /dev/null +++ b/apps/web/store/screenshots.md @@ -0,0 +1,70 @@ +# Screenshot plan: Peanut Split v1 + +What task 4C captures and what Konrad approves before any upload (mono brand-asset rule). The +images go in `apps/web/store/assets/`. + +## Rules for every image + +- Framed captures of the real app: a flat brand background, one headline and one sub-line from + the LP voice, and the capture in a neutral ink frame with no device hardware. The text in an + image never names a price, a store or an OS. +- JPEG, quality 90, no alpha channel (both stores reject transparency). +- English (US) UI only. +- Generic first names only, such as Ana, Ben, Carla and Dev. No real people, no real rooms. +- Never show the settle sheet or the Peanut option. Never show the word crypto, wallet or payment. +- No Android UI in the iPhone sets and no iPhone UI in the Android set. + +## The five screens + +| # | Screen | What it shows | Setup | +| --- | ------------------- | ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | +| 1 | A trip room | Four people, several expenses and their balances | Seed a room through the local API server | +| 2 | Add expense | The expense drawer mid-entry, with "Who shares this?" open | Same room | +| 3 | Receipt scan review | Scanned items with people assigned to each item | Mock the scan response with a fixture; build the export and the API server with `NEXT_PUBLIC_SPLIT_V2_ENABLED=1` | +| 4 | The share moment | The room link and its QR code | Same room | +| 5 | The app home | Three recent rooms: a trip, roommates and a dinner | Three seeded rooms in local storage | + +"Import from Splitwise" and "Settle up" name competitors, so they stay outside every frame; the +spec asserts it. + +## Upload order + +The file numbers are the screen numbers above. Upload in this order (the first three show in +search results): + +| Upload | File | Headline | Sub-line | +| ------ | ---------------- | ------------------------- | ----------------------------- | +| 1 | `4-share` | ONE LINK. PICK YOUR NAME. | No signup. No password. | +| 2 | `2-add-expense` | EVERYONE ADDS EXPENSES. | Who paid, how much, for whom. | +| 3 | `1-room` | WHO OWES WHAT. SORTED. | Every balance in one room. | +| 4 | `3-receipt-scan` | SCAN THE BILL. | Then tap who had what. | +| 5 | `5-home` | SPLIT ANYTHING. | Trips, roommates, dinners. | + +## Sizes + +| Set | Pixels | Canvas | Raw capture | +| ------------- | ----------- | --------------- | ----------- | +| iPhone 6.9" | 1320 × 2868 | 440 × 956 at 3x | `iphone` | +| iPhone 6.3" | 1206 × 2622 | 402 × 874 at 3x | `iphone` | +| Android phone | 1080 × 1920 | 360 × 640 at 3x | `android` | + +The app is captured at two raw sizes, both at 3x: `iphone` 402 × 874 (iPhone user agent) and +`android` 412 × 892 (Android user agent). Each frame shows a window of the capture, anchored at +its top or its bottom. Every headline sets on two lines, so the frame starts at the same height on +all five screens. On the receipt-scan screen the spec scrolls back so the top of the window never +cuts an item card. + +Apple requires the 6.3" set (iPhone with Dynamic Island, medium display). The 6.9" set goes up +too, so Apple never scales one from the other (Apple screenshot specifications). Play needs at +least two phone screenshots; all five go up (Play graphic assets help page). + +## Play graphics + +- Feature graphic: 1024 × 500, JPEG or 24-bit PNG, required by Play. Headline: the LP H1, "Good + accounting makes good friends." +- Play icon: 512 × 512, 32-bit PNG, at most 1024 KB. + +## Approval + +Konrad approves every image, the feature graphic and the icon before upload (decision 8.3 #8 in +the plan). Nothing is uploaded from this folder automatically. diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 46778b87..7bf79262 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -28,5 +28,16 @@ "types": ["@serwist/next/typings"] }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", ".next/dev/types/**/*.ts"], - "exclude": ["node_modules", "src/app/sw.ts", ".next", "e2e", "e2e-v2"] + "exclude": [ + "node_modules", + "src/app/sw.ts", + ".next", + "e2e", + "e2e-v2", + "e2e-native", + "ios", + "android", + ".next-native", + "resources" + ] } diff --git a/apps/web/tsconfig.native.json b/apps/web/tsconfig.native.json new file mode 100644 index 00000000..5fa595b2 --- /dev/null +++ b/apps/web/tsconfig.native.json @@ -0,0 +1,15 @@ +{ + "extends": "./tsconfig.json", + "exclude": [ + "node_modules", + "src/app/sw.ts", + ".next", + ".next*", + "e2e*", + "**/*.test.ts", + "**/*.test.tsx", + "ios", + "android", + "resources" + ] +} diff --git a/docs/NATIVE-HANDOFF.md b/docs/NATIVE-HANDOFF.md new file mode 100644 index 00000000..48bc9d31 --- /dev/null +++ b/docs/NATIVE-HANDOFF.md @@ -0,0 +1,393 @@ +# Native apps: handoff to the first store submission + +This file lists every step between the `native-apps` branch and a submitted app that needs a person: an +account, a secret, a production change, a device or a decision. The code is complete up to each step. +CI is green without any of them. How the apps work: [`current/NATIVE.md`](current/NATIVE.md). + +- Repository: `peanutprotocol/peanutsplit`. Branch: `native-apps`. Draft PR: #37 (`native-apps` → + `main`, do not merge before step 9). +- Server-prep draft PR: #38 (`native-server-prep` → `main`, title "Native apps: server prep (CORS, push + transport)"). It holds only the server parts that must be live before a store build is useful. + `local/split-native-app/tools/server-prep.sh` in mono rebuilds it from `native-apps`. +- `main` gets exactly two merges before submission: the server-prep PR (step 1), then `native-apps` + (step 9). +- **UNVERIFIED** marks a fact that nobody could check from the repository, such as what exists in a + store console or a secret manager. Check it before you rely on it. +- Run repository commands from the repository root unless a step names another folder. + +Hands-on total: about 5.5 hours. Hugo does about 4 hours; Konrad or Hugo does the rest. + +## 1. Hugo only (account holder, admin, production) + +### Step 1. Merge the server-prep PR (30 min) + +1. Review the `native-server-prep` draft PR with Konrad. Konrad reviews the privacy page change + (`apps/web/src/app/(product-shell)/privacy/page.tsx`): it is a legal text. The page names Google + Gemini and OpenRouter for receipt scans, as the app's consent sheet does (decision 13). Set + the page's effective date at merge. +2. Confirm the AASA app ID `PW388G893L.com.peanutsplit.app` in + `apps/web/public/.well-known/apple-app-site-association` against decision 1. If the team differs, + edit that one line in the PR first. Apple's CDN caches this file, so it must be right on the first + deploy. +3. Mark the PR ready, merge it to `main`, and wait for the deploy. +4. Check the CORS answer. Expect `204` and `Access-Control-Allow-Origin: capacitor://localhost`: + ```bash + curl -si -X OPTIONS -H 'Origin: capacitor://localhost' \ + -H 'Access-Control-Request-Method: GET' https://peanutsplit.com/api/currencies + ``` +5. Check the association file. Expect `200`, `content-type: application/json`, and no redirect: + ```bash + curl -si https://peanutsplit.com/.well-known/apple-app-site-association | head -n 5 + ``` +6. Rerun the latest `native.yml` run on `native-apps`. Its Android smoke must now print `SPLIT_CORS ok`: + ```bash + gh run list --repo peanutprotocol/peanutsplit --workflow native.yml --branch native-apps --limit 1 + gh run rerun --repo peanutprotocol/peanutsplit + ``` + +### Step 2. Change the identifiers, only if decision 1 changed them (10 min) + +Do this step only if the Apple team or the bundle ID is not the default. + +1. On `native-apps`, run: + ```bash + node apps/web/scripts/native/set-identifiers.mjs --app-id --team --dry-run + node apps/web/scripts/native/set-identifiers.mjs --app-id --team + ``` +2. Commit the changed files and push `native-apps`. The bundle ID can never change after the first + release. + +### Step 3. Apple (30 min) + +**Reuse** these from the team secret manager. Check that each one exists first (UNVERIFIED): + +1. The Apple Distribution certificate (`.p12`) and its password. +2. The App Store Connect API key: key ID, issuer ID and the `.p8` content. +3. The team APNs auth key (`.p8`) and its key ID. Create a new key only if the team has fewer than 2 + APNs keys. Never revoke the key that OneSignal uses for peanut.me. + +**Create** these: + +1. An App ID `com.peanutsplit.app` with the Push Notifications and Associated Domains capabilities. +2. The App Store Connect app record (name "Peanut Split", primary language English (U.S.)). +3. An App Store provisioning profile named exactly `Peanut Split App Store`, for that App ID, with both + capabilities. The Xcode project expects this name. + +Then: + +1. In App Store Connect, turn off availability on Apple Silicon Macs. +2. Confirm the Digital Services Act trader status for the account. + +### Step 4. Google (40 min) + +**Reuse** (UNVERIFIED that each exists): + +1. Give the existing Play upload service account release access to the new app. +2. If a Firebase project for Peanut exists, add the Android app `com.peanutsplit.app` to it. + +**Create**: + +1. The Play app record on the Squirrel Labs organisation account. +2. An upload keystore. Record the keystore password, the key alias and the key password. +3. `google-services.json` for `com.peanutsplit.app` (Firebase console). +4. An FCM v1 service account key, if none can be reused. + +### Step 5. GitHub repository secrets (15 min, repository admin) + +Add these in GitHub → Settings → Secrets and variables → Actions. `.github/workflows/native-release.yml` +reads them. Each platform job checks only its own secrets, so each platform can ship as soon as its own +list is complete. + +| Platform | Secret | Value | +| -------- | --------------------------------- | -------------------------------------------------------- | +| iOS | `APPLE_TEAM_ID` | The Team ID from decision 1 | +| iOS | `IOS_DIST_CERT_P12_BASE64` | `base64` of the distribution `.p12` | +| iOS | `IOS_DIST_CERT_PASSWORD` | Its password | +| iOS | `IOS_PROVISIONING_PROFILE_BASE64` | `base64` of the `Peanut Split App Store` profile | +| iOS | `ASC_KEY_ID` | App Store Connect API key ID | +| iOS | `ASC_ISSUER_ID` | App Store Connect issuer ID | +| iOS | `ASC_KEY_CONTENT` | The API key `.p8` content | +| Android | `ANDROID_KEYSTORE_BASE64` | `base64` of the upload keystore | +| Android | `ANDROID_KEYSTORE_PASSWORD` | Keystore password | +| Android | `ANDROID_KEY_ALIAS` | Key alias | +| Android | `ANDROID_KEY_PASSWORD` | Key password | +| Android | `PLAY_SERVICE_ACCOUNT_JSON` | The Play upload service account JSON | +| Android | `GOOGLE_SERVICES_JSON_BASE64` | `base64` of `google-services.json` (push is compiled in) | + +The PostHog and Sentry client values are public (they ship in the web bundle) and are committed as +defaults. Repository variables with the same names override them; you do not need to set them. + +### Step 6. Production push credentials and egress (30 min) + +1. Set these runtime variables on the production app `split-org-web` (Dokploy): + `SPLIT_APNS_KEY_P8`, `SPLIT_APNS_KEY_ID`, `SPLIT_APNS_TEAM_ID`, `SPLIT_APNS_BUNDLE_ID`, + `SPLIT_FCM_SERVICE_ACCOUNT_JSON`. Treat them like the VAPID keys: never rotate them in place. +2. Check that `SPLIT_PUSH_PROXY_URL` is set there. Web push already uses it (UNVERIFIED for production). +3. On the Squid proxy `split-egress`, allow `CONNECT` on port 443 to `api.push.apple.com`, + `api.sandbox.push.apple.com`, `oauth2.googleapis.com` and `fcm.googleapis.com`. +4. Redeploy. Until this step is done, the server answers `503 NATIVE_PUSH_UNAVAILABLE` and the apps hide + the notification row. No store release is needed to turn it on. + +### Step 7. Testers (10 min) + +1. Add Konrad and Hugo to a TestFlight internal testing group. +2. Add Konrad and Hugo to the Play internal testing list. + +### Step 8. First release builds (20 min, plus about 40 min of CI) + +The release lane has never run: the overnight build skipped the dry-run tag. Expect this first run to +show any remaining problem in `.github/workflows/native-release.yml`. + +1. Tag the head of `native-apps` and push the tag: + ```bash + git fetch origin native-apps + git tag native-v1.0.0 origin/native-apps + git push origin native-v1.0.0 + ``` +2. Watch the "Native release" run: + `gh run list --repo peanutprotocol/peanutsplit --workflow native-release.yml --limit 1`. The `ios` job + uploads the build to TestFlight. A platform job that stops at its first step lists the secrets it is + missing (names only). +3. **First release only, Android:** the Play API cannot publish to a new app. Download the AAB: + `gh run download --repo peanutprotocol/peanutsplit -n android-release-aab`. Upload + `app-release.aab` in Play Console → Test and release → Testing → Internal testing. Roll it out to + internal testers. +4. Set the repository variable `PLAY_API_UPLOAD` to `1`. Later tags upload to the internal track by + themselves. + +### Step 9. App Links fingerprints and the `native-apps` merge (45 min) + +1. In Play Console → App integrity → App signing, copy the SHA-256 fingerprint of the app signing key + and of the upload key. +2. On `native-apps`, put both into `apps/web/public/.well-known/assetlinks.json`, in place of the + placeholder. Commit and push. +3. Merge `origin/main` into `native-apps` (server-prep is already on `main`). If + `docs/current/generated/*.md` conflicts, run `pnpm docs:generate` and commit the result. +4. Wait until `ci.yml` and `native.yml` pass on `native-apps`. +5. Review draft PR #37, mark it ready, and merge it to `main`. The merge changes the website in exactly + three intended ways (the parity items): a Privacy link in room settings and on `/app`, the empty-list + line on `/app`, and the calm offline room error with a way back to "Your rooms". The AI consent before + a receipt scan is app-only (decision 12). The App Store offer stays off while + `NEXT_PUBLIC_IOS_APP_STORE_ID` is unset. +6. Check `https://peanutsplit.com/.well-known/assetlinks.json`: `200`, `application/json`, your + fingerprints. +7. Read the Play pre-launch report. Known risk: Android 7-9 phones with a never-updated System WebView + may show a white screen (the bundle needs Chrome 111 or later). If the report shows it, raise + `minSdk`. + +### Step 10. Turn on the web store offer (15 min, after the App Store listing is live) + +1. Confirm that `join_gate_shown` and `join_gate_completed` events arrive in PostHog. Decision 2's + guardrail needs two weeks of them before the banner goes live. +2. In `apps/web/public/app-config.json`, replace `PLACEHOLDER` in `store.ios` with the numeric App Store + ID and push it to `main`. Until then, a raised `minBuild.ios` would show an **Update** button that + opens a dead store page. +3. Set the Dokploy build argument `NEXT_PUBLIC_IOS_APP_STORE_ID` to the numeric App Store ID and + redeploy. iPhone and iPad browsers then get the Smart App Banner on room pages and "Get the app" on + `/app`. Android browsers keep the PWA install. There is no Android store ID. + +### Step 11. Remove the install handoff (later) + +Fourteen days after the App Store ID is live, delete the install-handoff code (follow-up task). + +## 2. Konrad or Hugo (App Manager or Release Manager roles are enough) + +### K1. Try the debug APK (10 min, right after step 1) + +1. Download the `android` artifact of the latest `native.yml` run on `native-apps`: + `gh run download --repo peanutprotocol/peanutsplit -n android`. +2. Install the debug APK on any Android phone (`adb install .apk`, or open the file on the phone). +3. Open a room. Add an expense. The debug build calls production, so it works only after step 1. + +### K2. Seed the review room (10 min) + +This is a production write, so a person runs it. + +1. Check the plan first. It sends nothing: + ```bash + node apps/web/scripts/native/seed-review-room.mjs --dry-run + ``` +2. Create the room. It prints the room link, the slug and whether receipt scan is on: + ```bash + node apps/web/scripts/native/seed-review-room.mjs + ``` +3. Keep the link out of the repository. It goes only into the App Review notes and the Play Console + "App access" field (K4). +4. Check that receipt scan is on for the reviewers. Expect `{"enabled":true}`: + ```bash + curl -s https://peanutsplit.com/api/rooms//receipt-parse + ``` + +### K3. Device pass (40 min) + +Use the release builds from step 8: TestFlight on an iPhone, the Play internal track on an Android 15 +phone and on one Android 13 or 14 phone. Do the device checks in section 3. Record each result. + +Android link checks (1, 5, 6) need step 9.6 done first: before that, peanutsplit.com serves a +placeholder `assetlinks.json`. Android checks App Links once, at install, and does not retry. A phone +that installed the internal-track build before 9.6 must reinstall it, or run +`adb shell pm verify-app-links --re-verify com.peanutsplit.app`. Then confirm that +`adb shell pm get-app-links com.peanutsplit.app` shows peanutsplit.com as `verified`. The iOS checks +and the other Android checks can run right after step 8. + +### K4. Fill both store consoles (90 min) + +1. Copy the texts from `apps/web/store/listing.md`, the privacy and data-safety answers from + `apps/web/store/privacy-answers.md`, and the review notes from `apps/web/store/review-notes.md`. +2. Replace `` with the K2 link only in App Review notes and Play "App access". +3. Enter the App Review contact: name, phone and email. +4. Upload the approved images from `apps/web/store/assets/` (decision 8). +5. Run `node apps/web/store/check-listing.mjs` after any text change. + +### K5. Before you submit (15 min) + +1. Run the readiness check with the review room slug. Every line must pass: + ```bash + node apps/web/scripts/native/check-review-readiness.mjs + ``` + It checks the CORS preflight, the AASA, `assetlinks.json` (no placeholder) and receipt scan. +2. On each release build, turn on notifications for a room and send one test push (add an expense from + another device). The notification must arrive, and the room's notification row must show. +3. Submit in App Store Connect and in Play Console. Promotion to production and publishing stay manual. + +## 3. Device checks + +Do these on the release builds (K3). "Fresh app" means a new install. Write down which phone and OS +version you used. + +**Links and launch** + +1. Tap a room link in Messages and in WhatsApp with the app installed (Android: after step 9.6). The app + opens on that room. No other room shows first, also on a cold start. +2. Do the same without the app. The web room opens, with no wall. iOS Safari shows the Smart App Banner + with "Get" (only after step 10). +3. In iOS Safari, open a room on peanutsplit.com with the app installed. The banner shows "Open". Tap it. + The app opens on that room (only after step 10). +4. In a fresh app, open a room that you joined in the browser. The name list shows. Tap your name. Your + past reactions show as yours. +5. Android with the old PWA also installed (after step 9.6): tap a room link. Write down which one opens. +6. Open a room link in the Instagram and Telegram in-app browsers with the app installed (Android: + after step 9.6). The web room works. Write down whether the app opened. +7. iPhone Safari, `/app` (after step 10): **Get the app** opens the store. After the tap, open a room + again: no store card shows. Android Chrome and desktop Chrome still offer the PWA install. + +**Notifications** + +8. Turn on notifications for a room in the app. Add an expense from another device. The notification + arrives. +9. Kill the app. Tap a notification. The app opens on that room, never on the most recent other room, and + no other room shows first. + +**Navigation and offline** + +10. Android: open a drawer and press back. The drawer closes. Press back on the home screen. The app + leaves. With the app closed, open it from a room link, then press back: **Your rooms** shows, never + the same room again. Press back again: the app leaves. Open the app from the launcher (it shows the + latest room), press back: **Your rooms** shows. Press back again: the app leaves. +11. Airplane mode, then a cold start. The recent room shows the offline line and **Your rooms**. Turn the + network on. The room loads without a tap. +12. Airplane mode in an open room: add an expense. Turn the network on. The expense syncs once; check it + from another device. + +**Sharing, camera and layout** + +13. Create a room in the app and share it to WhatsApp. The link preview card shows. +14. Share a room card image, then choose "Save Image" (iOS). The app asks for photo access once and does + not crash. +15. iOS: start the first receipt scan in a room. The AI consent sheet shows first. Allow it. There is one + OS camera prompt, and the camera preview shows inside the app. +16. Status bar and safe areas: on the Android 13 or 14 phone and on the Android 15 phone, the room header + is not under the clock. On iOS, check the top of a room page and an open bottom sheet near the home + indicator. + +**Things CI could not prove** + +17. Live updates: open the same room on a phone (app) and in a desktop browser. An expense added on one + side shows on the other within seconds without a reload (cross-origin `EventSource` on + `capacitor://` is UNVERIFIED on a device). +18. Rooms survive: add two rooms, force-quit the app, reopen. Both rooms are in "Your rooms". + +## 4. Konrad's decisions + +The defaults hold and the build does not wait for them. Each change is small. + +1. **Apple team:** `PW388G893L` (default; the team the Peanut app ships on) or `4K73GMPZP8` (Squirrel + Labs). The bundle ID stays `com.peanutsplit.app` unless someone objects. A change means step 2. +2. **Smart App Banner on a recipient's first Safari visit:** shown (default). Guardrail: compare the + `join_gate_completed / join_gate_shown` ratio in iOS Safari with all other browsers, two weeks before + and two weeks after the App Store ID goes live. If iOS Safari drops relative to the others, remove the + banner first. +3. **Native notification text:** the same names and amounts as web push (default), or one generic body. + Apple and Google can read native payloads. +4. **Category:** Utilities and Productivity (default), or Finance. +5. **Storefronts:** all, including the UK (default, to confirm). The UK rule covers marketing copy, not + availability. +6. **The Peanut settle option stays in the app** (default), with the listing posture in the store texts. +7. **Names:** "Peanut Split" in the stores, "Split" on the home screen (default). +8. **Approve the screenshots, the feature graphic and the icon** in `apps/web/store/assets/` (brand-asset + rule). +9. **v1 without the recap screen and without offline last-known balances** (default). +10. **Licence: decided 2026-11-15, yes.** Konrad approved distributing the AGPL codebase through the + App Store and Google Play, and the app may link to `/source`. The store description links to + `https://peanutsplit.com/source`. The evidence is in section 5. +11. **Listing languages:** English only in v1 (default). es-419 and pt-br listings later. +12. **The one-time AI consent before the first receipt scan:** in the app only (default since + 2026-11-14), or on the web too. Apple requires it for the app. Nothing requires it on the web, where + it would add one tap, once per browser, to the first scan. +13. **AI provider on the privacy page: decided 2026-11-15.** The privacy page names the provider that + reads receipt photos: Google Gemini, through OpenRouter, as the app's consent sheet does. The store + description names it too. + +## 5. Licence evidence for decision 10 + +This is the evidence from the repository on 2026-11-15 (`native-apps` at `3971dea`), not legal advice. +The question: the codebase is `AGPL-3.0-or-later`, and the App Store's terms add restrictions that the +AGPL does not allow a licensee to add. That conflict matters only for code whose copyright belongs to +someone other than the distributor. + +**Authors.** `git shortlog -sn HEAD` (aliases collapsed by `.mailmap`): + +| Commits | Author | Kind | +| ------: | ------------------------------ | ---------------------------- | +| 691 | Konrad Urban | person, Squirrel Labs Ltd | +| 187 | Hugo Montenegro | person, Squirrel Labs Ltd | +| 8 | `chip-peanut-bot[bot]` | company bot | +| 4 | `peanutsplit-steward` | company bot (box supervisor) | +| 1 | `split-content-publisher[bot]` | company bot | + +The 11 `Co-authored-by` trailers in the history name only AI tools and the same company bots. No +outside person authored a commit. + +**Rights register.** `docs/current/RIGHTS-REGISTER.md` records the code as Squirrel Labs-owned: + +- "Granting entity: Squirrel Labs Ltd. Ruled by the project owner on 2026-08-24 and confirmed on + 2026-09-01 ... the work in this repository was authored for Squirrel Labs Ltd, which holds the rights + and grants the licenses below." +- Register row "Application code, migrations, tests, config": `AGPL-3.0-or-later`, Resolved. +- Register row "Code extracted from `peanut-ui` / `peanut-api-ts`": "Same owner under the Squirrel Labs + Ltd ruling; AGPL", Resolved. +- Register row "Dependencies and container packages": "Own licenses; per-build SBOM before shipping an + artifact", **Open**. The store binary is such an artifact. + +**Weak-copyleft entries in `THIRD_PARTY_LICENSES.md`**, and whether each ships in the binary. The +binary holds the static export (about 6 MB), Capacitor and its plugins. A search of the export built on +2026-11-15 found none of these packages: + +| Package | Licence | In the binary? | Why | +| ------------------------------------ | ----------------------- | -------------- | ------------------------------------------------------------------------------------------------------------ | +| `@img/sharp-libvips-linux-x64@1.3.4` | `LGPL-3.0-or-later` | No | Server-side image library behind `sharp` (share cards, OG images) | +| `next-mdx-remote@6.0.0` | `MPL-2.0` | No | Renders guides and blog pages on the server; no native page uses it | +| `web-push@3.6.7` | `MPL-2.0` | No | Server-side web push sender | +| `dompurify@3.4.16` | `MPL-2.0 OR Apache-2.0` | No | Used only by posthog-js's product-tours extension, which the app never loads; Apache-2.0 is available anyway | + +**Not covered by `THIRD_PARTY_LICENSES.md`:** the native layers. Capacitor and its plugins are MIT; the +Android build adds AndroidX and Firebase Cloud Messaging libraries (Apache-2.0); the iOS build adds no +third-party SDK. The fonts in the export (Sniglet, Roboto Flex) are OFL, which allows bundling with +software. These licences are from the packages' own metadata, not from a generated inventory +(UNVERIFIED as a full list). + +**What the evidence supports.** Every authored line is Squirrel Labs-owned, and no third-party copyleft +code ships in the binary. So the store terms conflict only with terms Squirrel Labs grants to others, +not with terms it is bound by. That supports **yes**. For `/source`: the app has no link to it in v1. +Adding one is optional goodwill, not a requirement that this evidence shows. Konrad decided both on +2026-11-15: yes to store distribution, and the app may link to `/source` (decision 10). diff --git a/docs/NATIVE-MIGRATION.md b/docs/NATIVE-MIGRATION.md index d6a5a67b..c256ac4f 100644 --- a/docs/NATIVE-MIGRATION.md +++ b/docs/NATIVE-MIGRATION.md @@ -1,6 +1,18 @@ # Native migration — contingency plan -**Status: not approved. Nothing here authorizes implementation.** `ROADMAP.md` +> **Executed (2026-11-14).** Konrad reopened native apps on 2026-11-14 (`ROADMAP.md`). The apps are a +> Capacitor shell around a bundled static export of `apps/web`. How they work now: +> [`current/NATIVE.md`](current/NATIVE.md). What a person still does before submission: +> [`NATIVE-HANDOFF.md`](NATIVE-HANDOFF.md). This file is historical decision context, not the current +> design. Where the two differ, `current/NATIVE.md` wins. +> +> What the build kept from this plan: the WebView shell (step 1) and the native notification transport +> (step 4, as APNs and FCM next to web push). What it did not build: any room or identity transfer +> (steps 2 and 3). A fresh app is a new device; opening a room link and tapping a name restores identity, +> as described below. The room-list risk stays as written: a room whose link exists nowhere else does not +> reach the app. + +**Original status (2026-08-24): not approved. Nothing here authorized implementation.** `ROADMAP.md` lists native apps under "Deliberately not building"; this document exists so that if that decision is ever reopened, the shape of the work is already known and nobody re-derives it from the source under time pressure. Per `CLAUDE.md`, diff --git a/docs/README.md b/docs/README.md index f96abb2d..a3b8dd26 100644 --- a/docs/README.md +++ b/docs/README.md @@ -13,6 +13,7 @@ product. When source and prose disagree, source wins and the documentation is a - [Security and data lifecycle](current/SECURITY-MODEL.md) - [Self-hosting](current/SELF-HOSTING.md) - [Testing](current/TESTING.md) +- [iOS and Android apps](current/NATIVE.md) - [Licensing decision](current/LICENSING.md) - [Rights register](current/RIGHTS-REGISTER.md) - [FOSS-posture audit](audits/2026-08-24-foss-posture.md) @@ -28,6 +29,7 @@ The following material can explain how a feature arrived, but it is not an opera - [`docs-split-rooms-spike.md`](../docs-split-rooms-spike.md) — original spike - [`changelog-july-25.md`](../changelog-july-25.md) — early design decisions - [`ROADMAP.md`](../ROADMAP.md) — planning and historical decisions, not a current API/schema reference +- [`NATIVE-HANDOFF.md`](NATIVE-HANDOFF.md) — the human steps to release the store apps Historical documents must retain a visible historical label. They must not be linked as the current architecture, schema, API, security, or self-host contract. diff --git a/docs/current/API.md b/docs/current/API.md index be0621d9..9825f2ab 100644 --- a/docs/current/API.md +++ b/docs/current/API.md @@ -59,6 +59,56 @@ single-replica baseline. Rate limits are also per process. Scaling replicas multiplies allowances unless a shared store is added. +## Cross-origin callers + +The iOS and Android apps load the product from inside the binary and call this API cross-origin (see +[NATIVE.md](NATIVE.md)). `apps/web/src/lib/cors.ts`, applied in `apps/web/src/proxy.ts`, answers CORS +for exactly two origins: + +| Origin | Caller | +| ----------------------- | ------------------------- | +| `capacitor://localhost` | the iOS app (WKWebView) | +| `https://localhost` | the Android app (WebView) | + +- **Paths:** every `/api/**` route, plus the share-card images `/r/:slug/card/:kind` and + `/r/:slug/recap/card`. +- **Excluded:** `/api/install-handoff` and `/api/rooms/:slug/install-handoff`. They are bound to a + `__Host-` cookie and check the exact request `Origin` themselves, so they stay same-origin only. +- **Preflight in the proxy:** an `OPTIONS` request from an allowed origin gets `204` with + `Access-Control-Allow-Origin: `, `Access-Control-Allow-Methods: GET, POST, PATCH, DELETE`, + `Access-Control-Allow-Headers: Content-Type, X-Member-Token`, `Access-Control-Max-Age: 600` and + `Vary: Origin`. It never reaches a handler or a rate-limit bucket. +- **Other methods** get `Access-Control-Allow-Origin: `, + `Access-Control-Expose-Headers: Content-Disposition` and `Vary: Origin`, also on error responses + (`403`, `429`, `500`), so the app reads a rate limit as `RATE_LIMITED`, not as a network error. +- **No credentials:** never `Access-Control-Allow-Credentials`, never `*`. The apps send no cookie; the + member token travels in `X-Member-Token` or the body, as on web. +- Any other origin gets no CORS headers, and the behaviour is the same as before. +- `SPLIT_CORS_TEST_ORIGINS` (comma-separated) adds origins for the cross-origin e2e suite only. Never + set it in production. `*` and `null` in it are ignored. + +Two static files are public on purpose: `/app-config.json` (the app version gate) carries +`Access-Control-Allow-Origin: *`, and `/.well-known/apple-app-site-association` is served as +`application/json` with no redirect, as iOS requires. + +Native push uses the existing push-subscription routes. The body carries +`{ transport: 'apns' | 'apns-sandbox' | 'fcm', token, memberId, memberToken }` in place of the web +`endpoint` and `keys`. Without server credentials for that transport the route answers +`503 NATIVE_PUSH_UNAVAILABLE`. + +## Backward compatibility with shipped app builds + +**API routes stay backward compatible with every shipped app build.** The store apps have no +over-the-air updates. An old binary keeps calling the live API for months, and production changes with +every push to `main`. + +- Add fields; do not remove or rename a field an app build reads or sends. +- Keep accepting every request body a shipped build sends. A new required field needs a default. +- Keep error codes stable; the app maps them to copy. +- If a break cannot be avoided, raise `minBuild` for the affected platform in + `apps/web/public/app-config.json` in the same push. Builds below it show **Update Split** and a way to + open the room in the browser. + ## Change rule When adding, removing, or changing a route: @@ -66,4 +116,5 @@ When adding, removing, or changing a route: 1. update validation and handler tests; 2. run `pnpm docs:generate` and review the route diff; 3. update credential, retention, idempotency, and feature-gate prose where behavior changed; -4. treat any future stable external contract as a separately versioned design decision. +4. check the change against [the compatibility rule](#backward-compatibility-with-shipped-app-builds); +5. treat any future stable external contract as a separately versioned design decision. diff --git a/docs/current/NATIVE.md b/docs/current/NATIVE.md new file mode 100644 index 00000000..6b2a383a --- /dev/null +++ b/docs/current/NATIVE.md @@ -0,0 +1,392 @@ +# Native apps (iOS and Android) + +The App Store and Google Play apps are the web app's product surface, bundled into a native shell. This +document describes how they are built, the rules that keep the web build unchanged, and how to run each +check. What a person must still do before the first submission is in +[`docs/NATIVE-HANDOFF.md`](../NATIVE-HANDOFF.md). + +## The shape in one screen + +| Topic | Decision | +| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Shell | Capacitor 8.2.0. A static export of the app surface ships inside the binary. No `server.url`, no over-the-air updates. | +| Build target | One extra branch in `apps/web/next.config.js` on `SPLIT_NATIVE_BUILD=1`. No second config file. The web build stays the same standalone build. | +| Seam | `IS_NATIVE_APP` in `apps/web/src/lib/platform.ts`, a compile-time constant. Every `@capacitor/*` import lives in `apps/web/src/lib/native/capacitor/`. | +| Routes | `/`, `/app/`, `/new/`, `/room/?slug=`, `/room/import/?slug=`, `/import/`, from `apps/web/src/app/(native)/`. | +| API | `https://peanutsplit.com`, called cross-origin. The server answers CORS for exactly `capacitor://localhost` and `https://localhost`, without credentials. | +| Links | `https://peanutsplit.com/r/` is the only link anyone shares. Universal links (iOS) and App Links (Android) open it in the app when the app is installed. | +| Storage | localStorage stays the source of truth. Room keys are mirrored into `@capacitor/preferences`. The WebView origin is pinned forever. | +| Push | APNs on iOS, FCM on Android, through the existing per-room subscription table. Payloads never carry the slug. | +| Updates | A version gate reads `apps/web/public/app-config.json` and fails open. API routes stay backward compatible with every shipped build. | +| Not in v1 | The recap page, offline last-known balances, share-in (share extension), foreground banners, a Terms link, iPad layouts, Mac availability, a custom URL scheme, any room or identity transfer between the browser and the app. | + +Store texts, privacy answers and review notes live in `apps/web/store/`. The decisions here were taken in +the planning notes for the native-apps branch (2026-11-14). Those notes are not in the repository, so +this file restates every decision it relies on. + +## How the build works + +### One branch in `next.config.js` + +`apps/web/next.config.js` checks `SPLIT_NATIVE_BUILD === '1'` first. That branch sets: + +- `output: 'export'` and `distDir: '.next-native'`; +- `trailingSlash: true`, so each route is a folder with an `index.html`; +- `pageExtensions: ['native.tsx', 'native.ts']`; +- `typescript.tsconfigPath: 'tsconfig.native.json'`, which excludes tests, `e2e*` and the native projects; +- `env: { NEXT_PUBLIC_NATIVE_BUILD: '1' }`. + +`pageExtensions` is what keeps the two builds apart. The native build sees only `*.native.tsx` pages, so +no web `page.tsx`, `layout.tsx`, `route.ts`, metadata file or `src/proxy.ts` reaches the binary. The web +build ignores `*.native.tsx`. The web branch defines `NEXT_PUBLIC_NATIVE_BUILD: '0'`. Next inlines a +`NEXT_PUBLIC_*` value only when it is defined at build time, and the seam below needs a literal in both +builds. + +The native branch does not set `NEXT_PUBLIC_BASE_URL`. A value in the config `env` block would override +the process environment and send the cross-origin test harness to production. + +### `native:build` and `native:sync` + +Run both from `apps/web`: + +```bash +pnpm native:build # static export into apps/web/.next-native, then postbuild checks +pnpm native:sync # native:build, then `cap sync` into apps/web/ios and apps/web/android +``` + +`native:build` defaults three values when the environment does not set them: + +| Variable | Default | Why | +| ------------------------------ | ------------------------- | --------------------------------------------------------------------------- | +| `NEXT_PUBLIC_BASE_URL` | `https://peanutsplit.com` | The API origin must be a literal in the chunks. Tests set the local server. | +| `NEXT_PUBLIC_SPLIT_V2_ENABLED` | `1` | Same product flags as the production Dockerfile, so receipt scan ships. | +| `NEXT_PUBLIC_FOSS_RELEASED` | `1` | Same as the Dockerfile. | + +Next always builds an export inside `.next` and only copies it to `.next-native`. +`apps/web/scripts/native/postbuild.mjs` then clears `.next` except `cache`, so a later `next start` +fails loudly instead of serving the app build as the website. **Run `native:build` first and +`pnpm build` last** when one job needs both. + +`postbuild.mjs` prunes what the app never loads (press kit, PWA splash images, `sw.js`, `.well-known/`, +`app-config.json`, the 404 pages Next always writes), then fails the build when: + +- the HTML files differ from the exact route set (a web page leaked into the binary); +- `cache/`, `server/`, `sw.js` or `manifest.webmanifest` exist; +- a file contains `/split-static/`, `serviceWorker.register` or an ad-tag host; +- the inlined `NEXT_PUBLIC_BASE_URL` is missing from the chunks; +- `NEXT_PUBLIC_SENTRY_DSN` is set and the DSN is missing from the chunks; +- the export is larger than 15 MB (it is about 6 MB). + +`cap sync` copies the export into the native projects (`webDir` is `.next-native`; there is no `www/` +copy step). `native:sync` puts `NODE_ENV=production` in front of `cap sync`. That value reaches only +`apps/web/capacitor.config.ts`, which runs in Node, and turns Android WebView debugging off. The debug +job in CI leaves it out, so the emulator smoke can read the WebView console. + +### `NODE_ENV` is always `'production'` in the bundle + +`next build` inlines `process.env.NODE_ENV` as `'production'` in every export, debug or not. Never gate +behaviour inside the bundle on it. Use a named `NEXT_PUBLIC_*` flag, read as a literal property access so +Next inlines it. Example: the boot CORS self-test runs only when +`process.env.NEXT_PUBLIC_SPLIT_CORS_SELFTEST === '1'`, which only the CI export job sets. + +### Build-time variables + +| Variable | Set by | Effect | +| --------------------------------- | ------------------------------------------ | --------------------------------------------------------------------------------- | +| `SPLIT_NATIVE_BUILD` | `native:build` | Selects the native branch of `next.config.js`. | +| `NEXT_PUBLIC_NATIVE_BUILD` | `next.config.js` (`'1'` app, `'0'` web) | Drives `IS_NATIVE_APP` and the Capacitor import guard. | +| `NEXT_PUBLIC_NATIVE_PUSH` | release lane `1`; CI debug builds unset | Compiles the native push client in. | +| `NEXT_PUBLIC_SPLIT_APNS_ENV` | release lane `production` | iOS subscribes as `apns`; anything else subscribes as `apns-sandbox`. | +| `NEXT_PUBLIC_SPLIT_CORS_SELFTEST` | `native.yml` export job only | Logs `SPLIT_CORS ok` or `SPLIT_CORS blocked` on boot. | +| `NEXT_PUBLIC_IOS_APP_STORE_ID` | Dokploy build arg, after the listing lives | Web only: the Smart App Banner and the iPhone and iPad store offer. Off if unset. | + +## The platform seam + +`apps/web/src/lib/platform.ts` holds everything shared code may ask about the platform: + +- `IS_NATIVE_APP`: `process.env.NEXT_PUBLIC_NATIVE_BUILD === '1'`. Compile-time, never user-agent + sniffing. +- `NATIVE_PUSH_ENABLED`: `IS_NATIVE_APP` and `NEXT_PUBLIC_NATIVE_PUSH === '1'`. +- `nativePlatform()`: `'ios'`, `'android'` or `'web'`, read at runtime from the `window.Capacitor` global + that the native bridge injects. No import. +- `apiUrl(path)`: the path unchanged on web; `siteUrl + path` in the app. +- `roomPath(slug, view?, query?)`: in-app navigation to a room (next section). +- `RECAP_AVAILABLE`: `false` in the app, because the recap page reads the database on the server. + +`apps/web/src/lib/native/host.ts` is the one door to Capacitor: + +```ts +export function loadHost(): Promise | null { + return process.env.NEXT_PUBLIC_NATIVE_BUILD === '1' ? import('./capacitor/index') : null +} +``` + +**The two rules of the seam:** + +1. **No `@capacitor/*` import outside `apps/web/src/lib/native/capacitor/`.** Those wrappers are reached + only through `loadHost()`. Each wrapper catches a missing bridge or an unimplemented web fallback and + reports the feature as absent, which is also the safe behaviour on a device. +2. **Shared code imports `apps/web/src/lib/native/` only inside an `IS_NATIVE_APP` branch, or from native + pages.** A guard that must drop code from the web build uses the inline + `process.env.NEXT_PUBLIC_NATIVE_BUILD === '1'` comparison, as `loadHost()` does. Webpack folds the + inlined literal and drops the branch. It does not see through the imported `IS_NATIVE_APP` binding, so + a guard on the constant still ships the code to every web visitor. + +Two gates hold the rules: + +- `apps/web/src/native-boundary.test.ts` (Vitest, runs in `ci.yml`) fails on a `@capacitor/` import + outside the wrappers, on a hand-built `/r/` path outside an exact file allowlist, and when the native + route list in `apps/web/src/lib/native/links.ts` does not match the `(native)` route tree. It prints each + offending `file:line`. +- `apps/web/scripts/assert-pwa-build-boundary.mjs` runs after every `pnpm build` (local, `ci.yml`, the + Docker image, `native.yml`). It fails when the web `.next/static` contains `isNativePlatform`, + `androidBridge`, `@capacitor/`, `Capacitor.` or the native push client's error text. A bare + `@capacitor` grep finds nothing in a minified bundle. + +### Native routes and hard loads + +The routes are client components in `apps/web/src/app/(native)/`: + +| Path | Renders | +| --------------- | ------------------------------------------------------------------------------------------- | +| `/` | `NativeEntry`, which decides the first screen. The splash is still up. | +| `/app/` | "Your rooms": recent rooms, paste a link, import, the Privacy link. `?manage=1` stays here. | +| `/new/` | `CreateRoomForm`, no ad tags. | +| `/room/` | `RoomScreen` for `?slug=`. A missing or invalid slug goes to `/app/`. | +| `/room/import/` | `ExistingRoomImportScreen` for `?slug=`. | +| `/import/` | `SplitwiseImport`. | + +Capacitor serves the **root** `index.html` for every path whose last segment has no dot, even when a +folder such as `room/index.html` exists. That covers cold starts, a reload after a language switch, and +Android recreating a killed WebView. So `layout.native.tsx` runs a script before hydration that saves the +URL in `window.__splitBootPath` and resets the address to `/`. `NativeEntry` then decides, in this order +(the pure function is `decideEntry` in `apps/web/src/lib/native/native-entry.ts`): + +1. A boot path other than `/` restores that screen. A boot path that maps to nothing or to an external URL + goes to `/app/` and never opens a browser. +2. The launch URL goes through `dispatchNativeLink(url, 'launch')`. +3. A notification tap that started the app (`awaitColdPushTap()`, capped at 500 ms) opens its room. +4. Otherwise `/app/`, where `RecentRoomAppEntry` opens the most recent room, as the installed PWA does. + +The launch URL and the push tap are read before `/app/`, so a cold start never flashes another room. + +`apps/web/scripts/native/serve-export.mjs` copies Capacitor's rule exactly (a dotted last segment is that +file or a 404; every other path is the root `index.html`). Every local and CI cold-start check uses it, +because a plain static server would hide the bugs this rule causes. + +### `roomPath` against `productUrl` + +- **`roomPath(slug)`** is for navigation inside the running app. On web it returns exactly the old string + (`/r/`, `/r//import`, plus a query). In the app it returns `/room/?slug=` or + `/room/import/?slug=`, because a static export has no dynamic routes. The parameter is `slug`, + not `s`, so the Sentry redaction can match it narrowly. +- **`productUrl('/r/')`** is for every link a person shares or sees: share sheets, copy buttons, QR + codes, the room link in settings. It is always the canonical `https://peanutsplit.com/r/`, from + the web and from the app. Never share a `roomPath` value. + +`apps/web/src/lib/native/links.ts` maps any incoming URL back into the app: `nativePathForUrl()` turns a +room link (also `www.` and `split.peanut.me` for pasted links) into a native path, keeps the query keys +the room understands and the fragment, sends other product pages to the system browser, and rejects +other hosts and invalid slugs. `dispatchNativeLink()` handles a link from the launch URL and from +`appUrlOpen` with one 3-second de-duplication window and a sessionStorage replay key, so a cold start +from a link navigates once. + +## The pinned origin + +`apps/web/capacitor.config.ts` sets `server.iosScheme: 'capacitor'`, `server.androidScheme: 'https'` and +`server.hostname: 'localhost'`. localStorage is keyed by origin, and localStorage holds every person's +room list and member tokens. **Never change these three values after the first release.** A change makes +every room disappear from every installed app. `apps/web/scripts/native/assert-native-config.mjs` fails +when one of them changes, and when `server.url` appears. + +The device is the only store of the room list. WKWebView can evict website data, so +`apps/web/src/lib/native/storage-mirror.ts` mirrors the keys `ps:recent`, `ps:member:*`, `ps:pending:*` +and `ps:push-room:*` into `@capacitor/preferences`: + +- On launch, before any screen mounts, it copies back each mirrored key that localStorage is missing. It + never overwrites a key that is present. +- In the app only, it wraps `localStorage.setItem` and `removeItem` once, so every write to those prefixes + also goes to Preferences. localStorage stays the synchronous source of truth. + +The interceptor exists because these keys are written from many places, including rollback paths in +identity and offline-queue code. Explicit mirror calls would have to follow each one. Android keeps +`android:allowBackup="true"`: the OS backup is the only way to recover a room list on a new phone. + +## Plugins + +Exact pins in `apps/web/package.json`, all at least 14 days old when added: + +| Package | Version | Used for | +| ------------------------------------------------------------------------------- | ------------ | -------------------------------------------------------------- | +| `@capacitor/core`, `@capacitor/ios`, `@capacitor/android`, dev `@capacitor/cli` | 8.2.0 | The shell (the line peanut-ui runs in production) | +| `@capacitor/app` | 8.1.2 | Launch URL, `appUrlOpen`, resume, Android back, build number | +| `@capacitor/browser` | 8.0.5 | External links and `window.open` in SFSafariViewController/Tab | +| `@capacitor/preferences` | 8.0.1 | The storage mirror | +| `@capacitor/share`, `@capacitor/filesystem` | 8.0.3, 8.1.5 | `navigator.share` polyfill and file saves via the share sheet | +| `@capacitor/splash-screen`, `@capacitor/status-bar` | 8.0.2, 8.0.4 | Splash hidden after the first real screen; solid status bar | +| `@capacitor/push-notifications` | 8.1.3 | APNs and FCM tokens and taps | + +Deliberately absent: keyboard, haptics, camera and app-launcher plugins, `CapacitorHttp` (off: it does not +patch `EventSource`), and Firebase on iOS. + +Behaviour the plugins carry: + +- **Share and files.** `apps/web/src/lib/native/polyfills.ts` installs `navigator.share` and + `navigator.canShare` on both platforms. Files are written to the cache directory and shared by URI. + `saveFile()` in `apps/web/src/lib/save-file.ts` is `
` on web and the share sheet in the app. +- **External links.** `apps/web/src/lib/native/external-links.ts` intercepts link clicks: a room link + navigates in the app; any other `http(s)` link opens in the system browser sheet. `window.open` does the + same, which keeps the peanut.me settle link outside the app's WebView. +- **Camera.** The receipt scanner keeps `getUserMedia`. Capacitor already grants the WebView media prompt, + so only the OS camera prompt appears. +- **Status bar.** `overlaysWebView: false` with the first-paint surface colour. Older Android WebViews + report no top inset, so an overlaid status bar would cover the header. + +## Push transports + +Web push stays exactly as it is. The app uses the same per-room subscription table with another +transport. + +**Client** (`apps/web/src/lib/use-push.ts`, `apps/web/src/lib/native/use-native-push.ts`): + +- `usePush` picks the web or the native hook at build time. The native hook exists only when + `NEXT_PUBLIC_NATIVE_PUSH=1`; the release lane always sets it. +- Subscribing is a per-room tap, as on web: request permission, register, wait for the token (10 s + timeout), then `POST /api/rooms//push-subscriptions` with + `{ transport, token, memberId, memberToken }`. `transport` is `fcm` on Android, `apns` or + `apns-sandbox` on iOS. The app stores `ps:push-room:` so a tap can find the room. +- `ios/App/App/AppDelegate.swift` forwards the two token callbacks to the plugin. Without them + `register()` resolves and no token ever arrives. `cap sync` never overwrites that file; + `assert-native-config.mjs` checks both notification names. +- A tap on a notification reads `data.room` (an `analyticsKey`) and opens the room stored for it. An + unknown key opens the rooms list (`/app/?manage=1`), never the most recent room. Taps are + de-duplicated by `sendId`. + +**Server** (`apps/web/src/server/push.ts`, `apps/web/src/server/push-native/`): + +- `PushSubscription.transport` is `webpush`, `apns`, `apns-sandbox` or `fcm`. Native tokens are stored in + `endpoint` as `:`, so the unique key, the 30-per-room cap, the membership proof and the + status endpoint carry over. Web bodies still require `p256dh` and `auth`. +- Both senders leave the container through `SPLIT_PUSH_PROXY_URL`, as web push does. APNs uses a + provider JWT over HTTP/2 through an HTTP CONNECT tunnel (`tunnel.ts`, because Node's `http2` has no + proxy option). FCM uses HTTP v1 with a service-account token through `egressFetch`. +- Without credentials for a transport, the route answers `503 NATIVE_PUSH_UNAVAILABLE` and the app hides + the notification row. Setting the credentials turns it on without a store release. +- Dead tokens (APNs `410` or `BadDeviceToken`, FCM `UNREGISTERED` or `404`) delete the row. +- Runtime variables: `SPLIT_APNS_KEY_P8`, `SPLIT_APNS_KEY_ID`, `SPLIT_APNS_TEAM_ID`, + `SPLIT_APNS_BUNDLE_ID`, `SPLIT_FCM_SERVICE_ACCOUNT_JSON`. Never rotate them in place, as with VAPID. + +**Payloads carry `{ room: analyticsKey, sendId }` and never the slug.** Web push payloads are encrypted to +the browser. APNs and FCM payloads are readable by Apple and Google, and the slug is the room's +credential. APNs gets `thread-id` and FCM gets `tag` set to the `analyticsKey`. + +iOS uses APNs directly, not FCM. FCM on iOS needs the Firebase iOS SDK, which crashes at launch without +its config file and adds Google SDKs to the privacy manifest. Android applies the Google Services plugin +only when `apps/web/android/app/google-services.json` exists, so CI builds without Firebase. + +## Version gate + +There are no over-the-air updates, and production's API changes with every push to `main`. **API routes +stay backward compatible with every shipped app build** (see [API.md](API.md#backward-compatibility-with-shipped-app-builds)). +The gate is the escape hatch for a break that cannot be avoided. + +- `apps/web/public/app-config.json` holds `minBuild` per platform and the store URLs. It is served with + `Access-Control-Allow-Origin: *` and a 5-minute cache. +- `apps/web/src/lib/native/version-gate.ts` fetches it on launch and on resume (at most every 10 minutes, + 4 s timeout) and compares it with the app's build number. Below the minimum, `VersionGate` shows + **Update Split** with a store button and an **Open in browser** link to the room's canonical URL (or + `/app`). A network error, bad JSON or an unknown platform shows no gate. Offline use is never blocked. +- Build numbers are whole minutes since 2026-01-01T00:00Z, from + `apps/web/scripts/native/version-code.mjs`, the same number on both platforms. +- Raising `minBuild` is a one-line commit to `main`, made by a person. Fill `store.ios` in the same commit + the first time; it is a placeholder until then. + +## Analytics and privacy in the app + +- PostHog registers `surface: 'ios' | 'android' | 'web'`. `app_room_opened { via }` fires in the app, + always through `roomProps(slug)`, never a slug. +- In the app, PostHog never loads remote code: `disable_external_dependency_loading`, `disable_surveys`, + `disable_conversations`, `disable_product_tours` and `advanced_disable_flags` are all on. A dashboard + toggle must not run new code in a reviewed binary. +- Sentry runs in the export through `apps/web/src/instrumentation-client.ts`. `apps/web/src/lib/redact.ts` + redacts `?slug=` from URLs, breadcrumbs and exception text. +- Ad conversion tags are not in any native page. The app declares "Tracking: No" and shows no tracking + prompt. +- The one-time AI consent before the first receipt scan is shown **in the app only** (default, open for + Konrad as HANDOFF decision 12). The web flow is unchanged. + +## CI + +| Workflow | Trigger | Jobs | +| -------------------------------------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `.github/workflows/native.yml` | push to `native-apps` or `main`, PRs, for `apps/web/**` and the file itself | `export` (native settings check, `native:build` with the CORS self-test, artifact `native-export`); `native-e2e` (test export, web build, association-file check, cross-origin suite on Chromium and WebKit, negative control); `android` (debug APK, unsigned AAB, no `.so`, merged-manifest permissions, artifact `android`); `ios` (simulator build, unsigned archive, built-plist check); `android-smoke` and the iOS launch steps (non-gating); `web-e2e` and `web-e2e-compare`. On `main` only `export` runs. | +| `.github/workflows/native-release.yml` | tag push `native-v` | Signed lanes, dormant until secrets exist. One export job, then an iOS job (TestFlight upload) and an Android job (AAB artifact, Play internal track when `PLAY_API_UPLOAD` is `1`). Each platform job checks only its own secrets and lists missing names, never values. Push is always compiled in. | +| `.github/workflows/ci.yml` | unchanged | Typecheck, docs, format, audits, Vitest (incl. `native-boundary.test.ts`, `link-contract.test.ts`, CORS and proxy tests), web build with the boundary check, Docker build. It runs on the draft PR from `native-apps` to `main`. | + +`web-e2e-compare` runs the three existing Playwright suites on the merge base and on the head. It fails +when a test fails on the head and passed on the base or is new, so a failure that already exists on +`main` never blocks the branch. To rerun a `native.yml` run: `gh run rerun `. Find the id with +`gh run list --workflow native.yml --branch native-apps --limit 3`. + +The emulator and simulator smokes print `SPLIT_CORS blocked` until the server change with the CORS answer +is live on production, then `SPLIT_CORS ok`. The iOS smoke reads only native log output, so on iOS the +line is not always captured; the WebKit run of the cross-origin suite covers the CORS preflight. + +## Running the checks + +Run each command from the folder in the "Where" column. A build and a full Vitest run are heavy; on a +laptop, prefer CI. + +| Check | Where | Command | In CI | +| ----------------------------- | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- | +| Native settings (source) | repository root | `node apps/web/scripts/native/assert-native-config.mjs` | `native.yml` export | +| Native settings (built app) | repository root | `node apps/web/scripts/native/assert-native-config.mjs --app ` | `native.yml` ios | +| Static export and postbuild | `apps/web` | `pnpm native:build` | `native.yml` export | +| Web build and boundary | `apps/web`, after `native:build` | `pnpm build` | `ci.yml`, `native.yml` native-e2e | +| Seam, link contract, units | `apps/web`, test database up | `pnpm exec vitest run src/native-boundary.test.ts src/lib/native` (Vitest's global setup migrates the test database, see [TESTING.md](TESTING.md)) | `ci.yml` | +| Capacitor's file rule locally | `apps/web`, after `native:build` | `node scripts/native/serve-export.mjs .next-native 8778` | used by `native.yml` native-e2e | +| Cross-origin suite (E1-E8) | `apps/web` | build the export with `NEXT_PUBLIC_BASE_URL=http://localhost:3100`, then `pnpm build`, then `pnpm exec playwright test --config playwright.native.config.ts` (needs a migrated Postgres, see [TESTING.md](TESTING.md)) | `native.yml` native-e2e | +| Association files | `apps/web`, server running | `node scripts/native/check-association.mjs http://localhost:3100` | `native.yml` native-e2e | +| Store texts | repository root | `node apps/web/store/check-listing.mjs` | none | +| Review readiness (production) | repository root | `node apps/web/scripts/native/check-review-readiness.mjs ` | `native-release.yml` (warning only) | +| Android build | `apps/web`, JDK 21, Android SDK | `pnpm native:sync`, then `cd android && ./gradlew :app:assembleDebug :app:bundleRelease` | `native.yml` android | +| iOS build | `apps/web`, macOS, Xcode 26+ | `pnpm native:sync`, then `pnpm exec cap open ios` | `native.yml` ios | + +## Changing the native projects + +`apps/web/ios/` and `apps/web/android/` are committed. `cap sync` rewrites the copied web files and the +generated config files; the templates' own `.gitignore` files keep those out of git. Put every setting +where `cap sync` keeps it: `apps/web/capacitor.config.ts`, `Info.plist`, the entitlements, `AppDelegate.swift`, +`AndroidManifest.xml` and `build.gradle`. + +**To bump a Capacitor plugin:** + +1. Check that the new version is at least 14 days old. `.npmrc` refuses a newer one. +2. Change the exact pin in `apps/web/package.json`. Keep `@capacitor/core`, `ios`, `android` and `cli` on + the same version. +3. Run `pnpm bootstrap` from the repository root, then `pnpm licenses:generate`. +4. From `apps/web`, run `pnpm native:sync`. +5. Commit `apps/web/package.json`, `apps/web/pnpm-lock.yaml`, `THIRD_PARTY_LICENSES.md`, + `apps/web/ios` and `apps/web/android` together. +6. Replace `Package.resolved` from a macOS run: download the `ios-package-resolved` artifact of the next + `native.yml` run on the branch and commit it at + `apps/web/ios/App/App.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved`. An archive + can fail on a stale file. +7. Push and wait for `native.yml` to pass. + +**To change the bundle ID, the package name or the Apple Team ID:** run +`node apps/web/scripts/native/set-identifiers.mjs --app-id --team ` (add `--dry-run` to see the +files first). It rewrites `capacitor.config.ts`, the Xcode project, `build.gradle`, both association files +and `app-config.json`. Do this only before the first signed build: the bundle ID never changes after +release. + +**To change the icon or the splash:** edit the artwork, run `node resources/render-native-assets.mjs` from +`apps/web`, and commit what it writes. It is never run in CI. A new brand asset needs Konrad's approval. + +## Related + +- [`docs/NATIVE-HANDOFF.md`](../NATIVE-HANDOFF.md): the steps that need an account, a secret or a device. +- [API.md](API.md#cross-origin-callers): the cross-origin callers and the compatibility rule. +- [SECURITY-MODEL.md](SECURITY-MODEL.md#store-apps): why the CORS allowlist grants nothing new, and why + push payloads carry no slug. +- [`docs/NATIVE-MIGRATION.md`](../NATIVE-MIGRATION.md): the earlier contingency plan, now executed. diff --git a/docs/current/SECURITY-MODEL.md b/docs/current/SECURITY-MODEL.md index a108a9c1..4f2bcce4 100644 --- a/docs/current/SECURITY-MODEL.md +++ b/docs/current/SECURITY-MODEL.md @@ -60,7 +60,9 @@ export field or ID-addressed route changes. - FX: the supplied Compose baseline is static and makes no request. Outside that baseline, an unset mode enables outbound refreshes and the code currently falls back to `https://api.peanut.me/fx/rates` unless `SPLIT_FX_ENDPOINT` is explicit. -- Push: endpoints and encrypted notification payloads go to allowlisted browser push services. +- Push: endpoints and encrypted notification payloads go to allowlisted browser push services. For the + store apps, device tokens and readable payloads go to Apple Push Notification service and Firebase + Cloud Messaging (see [Store apps](#store-apps)). - Receipt parsing: an image goes to OpenRouter or Gemini when explicitly configured and enabled. - Analytics/error reporting: client events go to configured PostHog/Sentry endpoints; room secrets and money must not. @@ -68,6 +70,28 @@ Self-hosters become responsible for their own legal notices, data-processing cho backups, access logs, subprocessors, and user requests. The repository does not provide a complete privacy/compliance program. +## Store apps + +The iOS and Android apps call the API from the origins `capacitor://localhost` and `https://localhost`, +and the server answers CORS for exactly those two, without credentials (`apps/web/src/lib/cors.ts`; the +full contract is in [API.md](API.md#cross-origin-callers)). This grants nothing that `curl` with the room +slug cannot already do. No API route accepts an ambient credential: there is no session cookie, the +slug in the path is the capability, and a member token travels in a header or the body. A page on +another origin still gets no CORS answer, and the CORS answer never includes +`Access-Control-Allow-Credentials` or `*`. The cookie-bound install handoff is excluded and stays +same-origin only. + +Native push payloads carry the room's `analyticsKey` and a send ID, never the slug. Web push payloads +are encrypted end to end to the browser, but APNs and FCM payloads are readable by Apple and Google. +The slug is the room's bearer credential, so it must not pass through them. The app maps the +`analyticsKey` back to a slug from device storage. The notification title and body still contain the +room name, member names and amounts, as web push does; that is a product decision recorded in +[`docs/NATIVE-HANDOFF.md`](../NATIVE-HANDOFF.md) (decision 3). + +In the app, member tokens and the room list live in WebView localStorage under a pinned origin and are +mirrored into the platform's app preferences store, so WebView data eviction does not lose them. They +stay on the device and in the user's own OS backup. + ## Deployment assumptions - Put TLS and a trusted reverse proxy in front of the application. diff --git a/docs/current/generated/API-ROUTES.md b/docs/current/generated/API-ROUTES.md index e7a22d2b..da006f45 100644 --- a/docs/current/generated/API-ROUTES.md +++ b/docs/current/generated/API-ROUTES.md @@ -3,7 +3,7 @@ Source: `apps/web/src/app/**/route.ts` -Input SHA-256: `406d4b2f3ea942224210b20d80c726b798a4453632dca910c3080d2d2df6f66f` +Input SHA-256: `b8b1c068f080a5d25dd3fe5abcec4e449719b7ce68d65f6e4b57607aada9854d` Exported operations: 43 diff --git a/docs/current/generated/DATA-MODEL-INVENTORY.md b/docs/current/generated/DATA-MODEL-INVENTORY.md index de9da57c..4339de07 100644 --- a/docs/current/generated/DATA-MODEL-INVENTORY.md +++ b/docs/current/generated/DATA-MODEL-INVENTORY.md @@ -3,7 +3,7 @@ Source: `apps/web/prisma/schema.prisma` -Input SHA-256: `a486551b2365dab7eb7a451ee4c0ccb8944a51f9e163bac5fddc0eb8bd7dd4b1` +Input SHA-256: `bc2551cdab23f0df1ed0eb246f33278628f3bc137acf01bf5de44d82091d3d6b` PostgreSQL namespace: `split` Models: 15 @@ -206,19 +206,20 @@ Split modes: `EQUAL`, `EXACT`, `PERCENTAGE`, `SHARES` ## PushSubscription -| Field | Prisma type | Attributes | -| ------------ | ----------- | ------------------------------------------------------------------ | -| `id` | `String` | @id @default(uuid()) | -| `roomId` | `String` | — | -| `memberId` | `String` | — | -| `endpoint` | `String` | // push-service URL; the host is allowlisted at write time | -| `p256dh` | `String` | — | -| `auth` | `String` | — | -| `userAgent` | `String?` | — | -| `createdAt` | `DateTime` | @default(now()) | -| `lastSeenAt` | `DateTime` | @default(now()) | -| `room` | `Room` | @relation(fields: [roomId], references: [id], onDelete: Cascade) | -| `member` | `Member` | @relation(fields: [memberId], references: [id], onDelete: Cascade) | +| Field | Prisma type | Attributes | +| ------------ | ----------- | ----------------------------------------------------------------------- | +| `id` | `String` | @id @default(uuid()) | +| `roomId` | `String` | — | +| `memberId` | `String` | — | +| `transport` | `String` | @default("webpush") | +| `endpoint` | `String` | // webpush: allowlisted push-service URL; native: ":" | +| `p256dh` | `String?` | // webpush only | +| `auth` | `String?` | // webpush only | +| `userAgent` | `String?` | — | +| `createdAt` | `DateTime` | @default(now()) | +| `lastSeenAt` | `DateTime` | @default(now()) | +| `room` | `Room` | @relation(fields: [roomId], references: [id], onDelete: Cascade) | +| `member` | `Member` | @relation(fields: [memberId], references: [id], onDelete: Cascade) | ## NotificationSend