diff --git a/.github/workflows/native-release.yml b/.github/workflows/native-release.yml new file mode 100644 index 000000000..fcea794d0 --- /dev/null +++ b/.github/workflows/native-release.yml @@ -0,0 +1,191 @@ +name: Native apps release + +# Builds the signed store builds of the iOS and Android apps and uploads them: +# the Android App Bundle to a Google Play testing track, the iOS archive to +# App Store Connect (TestFlight). Promotion to production stays a manual step +# in both consoles. +# +# Runs only in liketrek/TREK, only by hand or on a version tag, and only after a +# required reviewer approves the `store` environment, which holds every secret +# (see wiki/Native-Apps.md for the list). Pull requests never reach it. +# +# Both stores get the same numbers: the version from client/package.json +# without a prerelease suffix, and a build number that only grows. A prerelease +# reuses its X.Y.Z with a higher build number and belongs on the internal track +# and in TestFlight only. + +on: + workflow_dispatch: + inputs: + track: + description: Google Play track + type: choice + options: [internal, alpha, beta] + default: internal + push: + tags: ['v*'] + +permissions: + contents: read + +concurrency: + group: native-release + cancel-in-progress: false + +jobs: + android: + if: github.repository == 'liketrek/TREK' + runs-on: ubuntu-24.04 + timeout-minutes: 40 + environment: store + steps: + - uses: actions/checkout@v6 + + - uses: actions/setup-node@v6 + with: + node-version-file: .nvmrc + cache: npm + + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: 21 + cache: gradle + + - name: Version and build number + id: version + run: | + echo "version=$(node -p "require('./client/package.json').version.split('-')[0]")" >> "$GITHUB_OUTPUT" + echo "build=$((GITHUB_RUN_NUMBER + 1000))" >> "$GITHUB_OUTPUT" + + - name: Install + run: npm ci --workspace=shared --workspace=client + + - name: Build shared + run: npm run build --workspace=shared + + - name: Build the address screen and sync it into the shell + working-directory: client + run: npm run cap:sync -- android + + - name: Upload key + env: + KEYSTORE_B64: ${{ secrets.ANDROID_UPLOAD_KEYSTORE_B64 }} + run: printf '%s' "$KEYSTORE_B64" | base64 -d > "$RUNNER_TEMP/upload.jks" + + - name: Build the signed App Bundle + working-directory: client/android + env: + ORG_GRADLE_PROJECT_trekKeystorePassword: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} + ORG_GRADLE_PROJECT_trekKeyAlias: ${{ secrets.ANDROID_KEY_ALIAS }} + ORG_GRADLE_PROJECT_trekKeyPassword: ${{ secrets.ANDROID_KEY_PASSWORD }} + run: >- + ./gradlew bundleRelease --no-daemon + -PtrekVersionName=${{ steps.version.outputs.version }} + -PtrekVersionCode=${{ steps.version.outputs.build }} + -PtrekKeystore="$RUNNER_TEMP/upload.jks" + + - uses: actions/upload-artifact@v6 + with: + name: trek-android-${{ steps.version.outputs.version }}-${{ steps.version.outputs.build }} + path: client/android/app/build/outputs/bundle/release/app-release.aab + retention-days: 30 + + # Play only accepts API uploads once one bundle was uploaded by hand + # (wiki/Native-Apps.md). `draft` until the app has left draft in the console. + - name: Upload to Google Play + uses: r0adkll/upload-google-play@e738b9dd8f2476ea806d921b64aacd24f34515a5 # v1.1.5 + with: + serviceAccountJsonPlainText: ${{ secrets.PLAY_SERVICE_ACCOUNT_JSON }} + packageName: com.liketrek.trek + releaseFiles: client/android/app/build/outputs/bundle/release/app-release.aab + track: ${{ inputs.track || 'internal' }} + status: draft + + - name: Remove the upload key + if: always() + run: rm -f "$RUNNER_TEMP/upload.jks" + + ios: + if: github.repository == 'liketrek/TREK' + runs-on: macos-15 + timeout-minutes: 60 + environment: store + steps: + - uses: actions/checkout@v6 + + # App Store uploads must be built with Xcode 26; the image's default is older. + - name: Select Xcode 26 + run: | + XCODE=$(ls -d /Applications/Xcode_26*.app | sort -V | tail -1) + test -n "$XCODE" + sudo xcode-select -s "$XCODE" + xcodebuild -version + + - uses: actions/setup-node@v6 + with: + node-version-file: .nvmrc + cache: npm + + - name: Version and build number + id: version + run: | + echo "version=$(node -p "require('./client/package.json').version.split('-')[0]")" >> "$GITHUB_OUTPUT" + echo "build=$((GITHUB_RUN_NUMBER + 1000))" >> "$GITHUB_OUTPUT" + + - name: Install + run: npm ci --workspace=shared --workspace=client + + - name: Build shared + run: npm run build --workspace=shared + + - name: Build the address screen and sync it into the shell + working-directory: client + run: npm run cap:sync -- ios + + - name: App Store Connect API key + env: + ASC_KEY_P8_B64: ${{ secrets.ASC_KEY_P8_B64 }} + run: printf '%s' "$ASC_KEY_P8_B64" | base64 -d > "$RUNNER_TEMP/AuthKey.p8" + + - name: Archive + working-directory: client/ios/App + env: + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + ASC_KEY_ID: ${{ secrets.ASC_KEY_ID }} + ASC_ISSUER_ID: ${{ secrets.ASC_ISSUER_ID }} + run: >- + xcodebuild archive + -project App.xcodeproj + -scheme App + -configuration Release + -destination 'generic/platform=iOS' + -archivePath "$RUNNER_TEMP/TREK.xcarchive" + MARKETING_VERSION=${{ steps.version.outputs.version }} + CURRENT_PROJECT_VERSION=${{ steps.version.outputs.build }} + DEVELOPMENT_TEAM="$APPLE_TEAM_ID" + -allowProvisioningUpdates + -authenticationKeyPath "$RUNNER_TEMP/AuthKey.p8" + -authenticationKeyID "$ASC_KEY_ID" + -authenticationKeyIssuerID "$ASC_ISSUER_ID" + + # ExportOptions.plist says destination=upload, so this step sends the build + # to App Store Connect, where it shows up in TestFlight after processing. + - name: Export and upload to App Store Connect + working-directory: client/ios/App + env: + ASC_KEY_ID: ${{ secrets.ASC_KEY_ID }} + ASC_ISSUER_ID: ${{ secrets.ASC_ISSUER_ID }} + run: >- + xcodebuild -exportArchive + -archivePath "$RUNNER_TEMP/TREK.xcarchive" + -exportOptionsPlist ../ExportOptions.plist + -exportPath "$RUNNER_TEMP/export" + -allowProvisioningUpdates + -authenticationKeyPath "$RUNNER_TEMP/AuthKey.p8" + -authenticationKeyID "$ASC_KEY_ID" + -authenticationKeyIssuerID "$ASC_ISSUER_ID" + + - name: Remove the API key + if: always() + run: rm -f "$RUNNER_TEMP/AuthKey.p8" diff --git a/.github/workflows/native.yml b/.github/workflows/native.yml new file mode 100644 index 000000000..a76946f3e --- /dev/null +++ b/.github/workflows/native.yml @@ -0,0 +1,132 @@ +name: Native apps + +permissions: + contents: read + +# Builds the iOS and Android shells whenever they, their address screen or the +# Capacitor plugins change. Nobody on the team has to own a Mac for the Swift +# side to be compiled on every change, and every run leaves a debug APK to +# install on a phone. +# +# Unsigned on purpose: signing and store uploads need secrets that fork PRs do +# not get, and belong in a release workflow of their own. +on: + pull_request: + paths: + - 'client/android/**' + - 'client/ios/**' + - 'client/native-shell/**' + - 'client/src/native/trekShell.ts' + - 'client/src/native/serverAddress.ts' + - 'client/capacitor.config.ts' + - 'client/vite.native.config.js' + - 'client/scripts/check-store-metadata.mjs' + - 'client/fastlane/**' + - 'client/package.json' + - 'package-lock.json' + - 'shared/src/i18n/*/native.ts' + - '.github/workflows/native.yml' + workflow_dispatch: + +concurrency: + group: native-${{ github.ref }} + cancel-in-progress: true + +jobs: + # The store texts fit their limits and every listing image has its size and + # no alpha channel (client/fastlane/README.md). Plain Node, no install. + metadata: + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - uses: actions/checkout@v6 + + - uses: actions/setup-node@v6 + with: + node-version-file: .nvmrc + + - name: Check the store listings + run: node client/scripts/check-store-metadata.mjs + + android: + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + - uses: actions/checkout@v6 + + - uses: actions/setup-node@v6 + with: + node-version-file: .nvmrc + cache: npm + + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: 21 + cache: gradle + + - name: Install + run: npm ci --workspace=shared --workspace=client + + - name: Build shared + run: npm run build --workspace=shared + + - name: Build the address screen and sync it into the shells + working-directory: client + run: npm run cap:sync -- android + + # The release build runs R8 with the keep rules in proguard-rules.pro, so a + # rule that goes missing fails here rather than in the store build. It is + # unsigned: the upload key only exists in native-release.yml. + - name: Assemble debug and release APKs + working-directory: client/android + run: ./gradlew assembleDebug assembleRelease lintDebug --no-daemon + + - uses: actions/upload-artifact@v6 + with: + name: trek-android-debug + path: client/android/app/build/outputs/apk/debug/app-debug.apk + retention-days: 14 + + ios: + runs-on: macos-15 + timeout-minutes: 40 + steps: + - uses: actions/checkout@v6 + + # App Store uploads must be built with Xcode 26; the image's default is older. + - name: Select Xcode 26 + run: | + XCODE=$(ls -d /Applications/Xcode_26*.app | sort -V | tail -1) + test -n "$XCODE" + sudo xcode-select -s "$XCODE" + xcodebuild -version + + - name: Check the property lists + run: plutil -lint client/ios/App/App/Info.plist client/ios/ExportOptions.plist + + - uses: actions/setup-node@v6 + with: + node-version-file: .nvmrc + cache: npm + + - name: Install + run: npm ci --workspace=shared --workspace=client + + - name: Build shared + run: npm run build --workspace=shared + + - name: Build the address screen and sync it into the shells + working-directory: client + run: npm run cap:sync -- ios + + - name: Build for the simulator + working-directory: client/ios/App + run: | + xcodebuild build \ + -project App.xcodeproj \ + -scheme App \ + -configuration Debug \ + -sdk iphonesimulator \ + -destination 'generic/platform=iOS Simulator' \ + CODE_SIGNING_ALLOWED=NO diff --git a/README.md b/README.md index 84e184bee..e28239437 100644 --- a/README.md +++ b/README.md @@ -182,7 +182,7 @@ Most of what follows is an addon an admin switches on or off. Lists, Costs, Docu #### 📱 Mobile and offline -- **Installable**: iOS and Android straight from the browser, no App Store, standalone with a themed status bar +- **Apps**: TREK Travel Planner for iPhone, iPad and Android connects to any TREK server, and the browser installs TREK as a standalone app with a themed status bar too - **Phone layouts**: their own screens for every part of the app, with a bottom bar and dashboard widgets the user orders - **Offline reads**: the app shell is precached and trips, places, tours, files and nearby places live in a per-user IndexedDB store, so a trip opens with no network - **Offline writes**: changes queue and replay with an `X-Idempotency-Key`, and a stale edit waits for a keep-mine or keep-theirs choice @@ -335,7 +335,7 @@ See [`charts/README.md`](https://github.com/liketrek/TREK/blob/main/charts/READM

Install as App (PWA)

-TREK works as a Progressive Web App — no App Store needed. +TREK works as a Progressive Web App, and the TREK Travel Planner app for iPhone, iPad and Android connects to the same server ([Native Apps](https://github.com/liketrek/TREK/wiki/Native-Apps)). To install the web app instead: 1. Open TREK in the browser (HTTPS required) 2. **iOS**: Share ▸ *Add to Home Screen* diff --git a/client/.gitignore b/client/.gitignore index 63f406cb5..03c1acfae 100644 --- a/client/.gitignore +++ b/client/.gitignore @@ -7,3 +7,7 @@ playwright/.cache/ # vite-plugin-pwa dev output (devOptions.enabled) dev-dist/ e2e/help/media.env + +# The native apps' address screen (npm run build:native), copied into +# android/ and ios/ by `cap sync` +native-dist/ diff --git a/client/android/.gitignore b/client/android/.gitignore new file mode 100644 index 000000000..e3aa6c5ba --- /dev/null +++ b/client/android/.gitignore @@ -0,0 +1,108 @@ +# 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 and store credentials. The upload key and the Play service +# account live only in the release workflow's secrets and in the owner's +# offline backup, never in the repository. +*.jks +*.keystore +keystore.properties +*service-account*.json + +# External native build folder generated in Android Studio 2.2 and later +.externalNativeBuild +.cxx/ + +# Google Services (e.g. APIs or Firebase) +# Push is not wired up and the build does not apply the google-services plugin, +# so no CI secret is needed. Kept ignored so a stray Firebase config never lands +# in the repository. +google-services.json +app/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 diff --git a/client/android/app/.gitignore b/client/android/app/.gitignore new file mode 100644 index 000000000..043df802a --- /dev/null +++ b/client/android/app/.gitignore @@ -0,0 +1,2 @@ +/build/* +!/build/.npmkeep diff --git a/client/android/app/build.gradle b/client/android/app/build.gradle new file mode 100644 index 000000000..38c23a189 --- /dev/null +++ b/client/android/app/build.gradle @@ -0,0 +1,66 @@ +apply plugin: 'com.android.application' + +android { + namespace = "com.liketrek.trek" + compileSdk = rootProject.ext.compileSdkVersion + defaultConfig { + applicationId "com.liketrek.trek" + minSdkVersion rootProject.ext.minSdkVersion + targetSdkVersion rootProject.ext.targetSdkVersion + // The release workflow (.github/workflows/native-release.yml) passes both: + // the version from client/package.json and a build number that only grows. + // Local and PR builds fall back to these placeholders. + versionCode((project.findProperty('trekVersionCode') ?: '1') as Integer) + versionName(project.findProperty('trekVersionName') ?: '0.0.0-dev') + 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:!*~' + } + } + // The upload key only exists in the release workflow, which decodes it from a + // secret and passes its path and passwords as Gradle properties. Every other + // build (local, fork, PR) stays unsigned and needs no secret. + signingConfigs { + release { + if (project.hasProperty('trekKeystore')) { + storeFile file(project.property('trekKeystore')) + storePassword project.property('trekKeystorePassword') + keyAlias project.property('trekKeyAlias') + keyPassword project.property('trekKeyPassword') + } + } + } + buildTypes { + release { + if (project.hasProperty('trekKeystore')) { + signingConfig signingConfigs.release + } + minifyEnabled true + shrinkResources true + proguardFiles getDefaultProguardFile('proguard-android-optimize.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 "androidx.browser:browser:$androidxBrowserVersion" + 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' diff --git a/client/android/app/capacitor.build.gradle b/client/android/app/capacitor.build.gradle new file mode 100644 index 000000000..0fae6fad5 --- /dev/null +++ b/client/android/app/capacitor.build.gradle @@ -0,0 +1,25 @@ +// 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-filesystem') + implementation project(':capacitor-haptics') + implementation project(':capacitor-keyboard') + implementation project(':capacitor-share') + implementation project(':capacitor-splash-screen') + implementation project(':capacitor-status-bar') + +} + + +if (hasProperty('postBuildExtras')) { + postBuildExtras() +} diff --git a/client/android/app/proguard-rules.pro b/client/android/app/proguard-rules.pro new file mode 100644 index 000000000..79e4063a5 --- /dev/null +++ b/client/android/app/proguard-rules.pro @@ -0,0 +1,38 @@ +# 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 + +# TREK's own classes: TrekShellPlugin is reached from JavaScript by name and its +# methods through reflection, so R8 must neither rename nor drop them. +-keep class com.liketrek.trek.** { *; } + +# Every Capacitor plugin: the bridge finds plugins by their annotation and calls +# the annotated methods reflectively. +-keep @com.getcapacitor.annotation.CapacitorPlugin public class * { + @com.getcapacitor.PluginMethod public ; +} + +# The WebView bridge: Capacitor's message handler is called from JavaScript +# through @JavascriptInterface, and every plugin class is instantiated by name. +-keepclassmembers class * { + @android.webkit.JavascriptInterface ; +} +-keep public class * extends com.getcapacitor.Plugin diff --git a/client/android/app/src/main/AndroidManifest.xml b/client/android/app/src/main/AndroidManifest.xml new file mode 100644 index 000000000..ec0ca5e2b --- /dev/null +++ b/client/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,80 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/client/android/app/src/main/java/com/liketrek/trek/MainActivity.java b/client/android/app/src/main/java/com/liketrek/trek/MainActivity.java new file mode 100644 index 000000000..60f37f516 --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/MainActivity.java @@ -0,0 +1,50 @@ +package com.liketrek.trek; + +import android.content.Intent; +import android.os.Bundle; +import android.view.View; +import com.getcapacitor.BridgeActivity; + +public class MainActivity extends BridgeActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + registerPlugin(TrekShellPlugin.class); + // With a server picked, the WebView loads that server instead of the + // bundled address screen, so the UI arrives in the version the server + // runs and on its own origin. BridgeActivity reads `config` while it + // builds the bridge inside super.onCreate(). + boolean restarting = TrekServerStore.consumeRestart(this); + String server = TrekServerStore.getUrl(this); + boolean onServer = server != null && !TrekServerStore.consumeShellOnce(this); + config = TrekServerStore.configFor(this, onServer ? server : null, restarting); + super.onCreate(savedInstanceState); + if (bridge == null) return; + // The UI asks for no overscroll effect (overscroll-behavior: none on html) + // and Chrome honours that, but the WebView draws the stretch on its root + // scroller natively. It scales the whole view, top bar and bottom dock included. + bridge.getWebView().setOverScrollMode(View.OVER_SCROLL_NEVER); + // Set before any WebView callback can run: they are posted to this thread. + if (onServer) bridge.setWebViewClient(new TrekWebViewClient(bridge, this::showAddressScreen)); + } + + private boolean leavingServer; + + /** + * The server did not load: back to the address screen, which offers retry + * and change. A fresh task rather than recreate(), because this usually + * happens during launch, while the system splash is still up, and a + * recreated activity leaves that splash lying over the new page. + */ + private void showAddressScreen() { + // A failed page can report more than one error; restart only once. + if (leavingServer) return; + leavingServer = true; + TrekServerStore.showShellOnce(this); + TrekServerStore.markRestart(this); + runOnUiThread(() -> { + startActivity(new Intent(this, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK)); + overridePendingTransition(0, 0); + }); + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/TrekServerStore.java b/client/android/app/src/main/java/com/liketrek/trek/TrekServerStore.java new file mode 100644 index 000000000..49c4a5623 --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/TrekServerStore.java @@ -0,0 +1,123 @@ +package com.liketrek.trek; + +import android.content.Context; +import android.content.SharedPreferences; +import com.getcapacitor.CapConfig; +import com.getcapacitor.Logger; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import org.json.JSONException; +import org.json.JSONObject; + +/** The server the user picked, and the Capacitor configuration that loads it. */ +final class TrekServerStore { + + private static final String PREFS = "trek_shell"; + private static final String KEY_URL = "server_url"; + private static final String KEY_SHELL_ONCE = "shell_once"; + private static final String KEY_RESTART = "restart"; + private static final String CONFIG_DIR = "trek-server-config"; + + private TrekServerStore() {} + + static String getUrl(Context context) { + return prefs(context).getString(KEY_URL, null); + } + + static void setUrl(Context context, String url) { + SharedPreferences.Editor editor = prefs(context).edit(); + if (url == null) { + editor.remove(KEY_URL); + } else { + editor.putString(KEY_URL, url); + } + editor.commit(); + } + + /** Start the next launch on the bundled address screen, even with a server remembered. */ + static void showShellOnce(Context context) { + prefs(context).edit().putBoolean(KEY_SHELL_ONCE, true).commit(); + } + + static boolean consumeShellOnce(Context context) { + return consume(context, KEY_SHELL_ONCE); + } + + /** The next onCreate is the app restarting itself, not a launch. */ + static void markRestart(Context context) { + prefs(context).edit().putBoolean(KEY_RESTART, true).commit(); + } + + static boolean consumeRestart(Context context) { + return consume(context, KEY_RESTART); + } + + private static boolean consume(Context context, String key) { + boolean set = prefs(context).getBoolean(key, false); + if (set) prefs(context).edit().remove(key).commit(); + return set; + } + + /** + * The bundled capacitor.config.json, adjusted for this start. Capacitor only + * takes these settings from a config file, so this writes a copy into the + * app's private storage and loads that; null means the bundled one as it is. + * + * With a server: server.url set, and server.errorPath dropped, because that + * page would have no bridge on the server's origin (TrekWebViewClient + * handles a failed load instead). + * + * On a restart: no launch splash. The splash plugin shows it again after + * recreate() but cannot take it down when the page hides it early, which + * left it covering a fully rendered page. A restart has no launch to cover. + */ + static CapConfig configFor(Context context, String url, boolean restarting) { + if (url == null && !restarting) return null; + try { + JSONObject json = new JSONObject(readAsset(context, "capacitor.config.json")); + if (url != null) { + JSONObject server = child(json, "server"); + server.put("url", url); + server.remove("errorPath"); + } + if (restarting) { + child(child(json, "plugins"), "SplashScreen").put("launchShowDuration", 0); + } + + File dir = new File(context.getFilesDir(), CONFIG_DIR); + if (!dir.isDirectory() && !dir.mkdirs()) throw new IOException("Cannot create " + dir); + try (FileOutputStream out = new FileOutputStream(new File(dir, "capacitor.config.json"))) { + out.write(json.toString().getBytes(StandardCharsets.UTF_8)); + } + return CapConfig.loadFromFile(context, dir.getAbsolutePath()); + } catch (IOException | JSONException ex) { + Logger.error("TrekShell", "Could not adjust the app config for " + url, ex); + return null; + } + } + + private static JSONObject child(JSONObject parent, String key) throws JSONException { + JSONObject existing = parent.optJSONObject(key); + if (existing != null) return existing; + JSONObject created = new JSONObject(); + parent.put(key, created); + return created; + } + + private static String readAsset(Context context, String name) throws IOException { + try (InputStream in = context.getAssets().open(name); ByteArrayOutputStream out = new ByteArrayOutputStream()) { + byte[] buffer = new byte[8192]; + int read; + while ((read = in.read(buffer)) != -1) out.write(buffer, 0, read); + return out.toString("UTF-8"); + } + } + + private static SharedPreferences prefs(Context context) { + return context.getSharedPreferences(PREFS, Context.MODE_PRIVATE); + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java b/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java new file mode 100644 index 000000000..d59271a03 --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java @@ -0,0 +1,149 @@ +package com.liketrek.trek; + +import android.content.Intent; +import android.net.Uri; +import android.os.Handler; +import android.os.Looper; +import androidx.browser.customtabs.CustomTabsIntent; +import com.getcapacitor.JSObject; +import com.getcapacitor.Plugin; +import com.getcapacitor.PluginCall; +import com.getcapacitor.PluginMethod; +import com.getcapacitor.annotation.CapacitorPlugin; +import org.json.JSONObject; + +/** The native half of client/src/native/trekShell.ts. */ +@CapacitorPlugin(name = "TrekShell") +public class TrekShellPlugin extends Plugin { + + /** How long to wait after returning from the browser for the redirect to land. */ + private static final long CANCEL_GRACE_MS = 600; + + private String authCallId; + private String authScheme; + private boolean authBrowserOpen; + private final Handler handler = new Handler(Looper.getMainLooper()); + + @PluginMethod + public void getServer(PluginCall call) { + String url = TrekServerStore.getUrl(getContext()); + JSObject result = new JSObject(); + result.put("url", url == null ? JSONObject.NULL : url); + call.resolve(result); + } + + @PluginMethod + public void setServer(PluginCall call) { + String url = call.getString("url"); + Uri parsed = url == null ? null : Uri.parse(url); + if (parsed == null || parsed.getHost() == null || !("https".equals(parsed.getScheme()) || "http".equals(parsed.getScheme()))) { + call.reject("A http(s) URL is required"); + return; + } + TrekServerStore.setUrl(getContext(), url); + call.resolve(); + restart(); + } + + @PluginMethod + public void resetServer(PluginCall call) { + TrekServerStore.setUrl(getContext(), null); + call.resolve(); + restart(); + } + + @PluginMethod + public void reload(PluginCall call) { + call.resolve(); + restart(); + } + + /** The server URL is part of the bridge's configuration, so it takes a new activity. */ + private void restart() { + TrekServerStore.markRestart(getContext()); + getActivity().runOnUiThread(() -> getActivity().recreate()); + } + + @PluginMethod + public void authenticate(PluginCall call) { + String url = call.getString("url"); + String scheme = call.getString("callbackScheme"); + if (url == null || scheme == null) { + call.reject("url and callbackScheme are required"); + return; + } + rejectPendingAuth("Superseded by a new sign-in"); + call.setKeepAlive(true); + getBridge().saveCall(call); + authCallId = call.getCallbackId(); + authScheme = scheme; + authBrowserOpen = true; + // A Custom Tab shares the browser's cookies, so a running SSO session at + // the identity provider carries over. The redirect back to the app's + // scheme arrives through the intent-filter in AndroidManifest.xml. + new CustomTabsIntent.Builder().build().launchUrl(getActivity(), Uri.parse(url)); + } + + @Override + protected void handleOnNewIntent(Intent intent) { + super.handleOnNewIntent(intent); + Uri data = intent.getData(); + PluginCall call = pendingAuthCall(); + if (call == null || data == null || !authScheme.equals(data.getScheme())) return; + JSObject result = new JSObject(); + result.put("url", data.toString()); + call.resolve(result); + finishAuth(call); + } + + /** + * Back in the app without a redirect means the user closed the browser. + * onNewIntent runs before onResume when the redirect did arrive, so the + * grace period only covers devices that deliver the two out of order. + */ + @Override + protected void handleOnResume() { + super.handleOnResume(); + if (!authBrowserOpen) return; + authBrowserOpen = false; + handler.postDelayed(() -> { + PluginCall call = pendingAuthCall(); + if (call == null) return; + call.reject("Sign-in cancelled", "CANCELLED"); + finishAuth(call); + }, CANCEL_GRACE_MS); + } + + private PluginCall pendingAuthCall() { + return authCallId == null ? null : getBridge().getSavedCall(authCallId); + } + + private void rejectPendingAuth(String message) { + PluginCall call = pendingAuthCall(); + if (call == null) return; + call.reject(message, "CANCELLED"); + finishAuth(call); + } + + private void finishAuth(PluginCall call) { + getBridge().releaseCall(call); + authCallId = null; + authScheme = null; + authBrowserOpen = false; + } + + /** iOS only: Android keeps the service worker, which already starts TREK offline. */ + @PluginMethod + public void refreshOfflineCopy(PluginCall call) { + JSObject result = new JSObject(); + result.put("saved", false); + call.resolve(result); + } + + @PluginMethod + public void openOfflineCopy(PluginCall call) { + JSObject result = new JSObject(); + result.put("opened", false); + call.resolve(result); + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/TrekWebViewClient.java b/client/android/app/src/main/java/com/liketrek/trek/TrekWebViewClient.java new file mode 100644 index 000000000..389b971a9 --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/TrekWebViewClient.java @@ -0,0 +1,49 @@ +package com.liketrek.trek; + +import android.webkit.WebResourceError; +import android.webkit.WebResourceRequest; +import android.webkit.WebResourceResponse; +import android.webkit.WebView; +import com.getcapacitor.Bridge; +import com.getcapacitor.BridgeWebViewClient; + +/** + * Used while the WebView shows the user's server. When that server cannot be + * loaded, Capacitor would show server.errorPath, but on Android it injects + * its bridge only into the server's origin, so that local page could neither + * retry nor change the server and stayed blank. Instead the app restarts on + * the bundled address screen, where the bridge is present and the screen + * offers exactly those two things. + */ +class TrekWebViewClient extends BridgeWebViewClient { + + private final Runnable onUnreachable; + + TrekWebViewClient(Bridge bridge, Runnable onUnreachable) { + super(bridge); + this.onUnreachable = onUnreachable; + } + + @Override + public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { + if (request.isForMainFrame()) { + onUnreachable.run(); + return; + } + super.onReceivedError(view, request, error); + } + + /** + * Only a 5xx on the page itself means the server is down (a proxy's 502 or + * 503 while TREK restarts). A 4xx page is left alone: the server answered, + * and TREK serves its UI for every other path. + */ + @Override + public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) { + if (!request.isForMainFrame()) { + super.onReceivedHttpError(view, request, errorResponse); + } else if (errorResponse.getStatusCode() >= 500) { + onUnreachable.run(); + } + } +} diff --git a/client/android/app/src/main/res/drawable-land-hdpi/splash.png b/client/android/app/src/main/res/drawable-land-hdpi/splash.png new file mode 100644 index 000000000..74dc3b3b9 Binary files /dev/null and b/client/android/app/src/main/res/drawable-land-hdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-land-ldpi/splash.png b/client/android/app/src/main/res/drawable-land-ldpi/splash.png new file mode 100644 index 000000000..0fc76905b Binary files /dev/null and b/client/android/app/src/main/res/drawable-land-ldpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-land-mdpi/splash.png b/client/android/app/src/main/res/drawable-land-mdpi/splash.png new file mode 100644 index 000000000..44e47fe08 Binary files /dev/null and b/client/android/app/src/main/res/drawable-land-mdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-land-night-hdpi/splash.png b/client/android/app/src/main/res/drawable-land-night-hdpi/splash.png new file mode 100644 index 000000000..74dc3b3b9 Binary files /dev/null and b/client/android/app/src/main/res/drawable-land-night-hdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-land-night-ldpi/splash.png b/client/android/app/src/main/res/drawable-land-night-ldpi/splash.png new file mode 100644 index 000000000..0fc76905b Binary files /dev/null and b/client/android/app/src/main/res/drawable-land-night-ldpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-land-night-mdpi/splash.png b/client/android/app/src/main/res/drawable-land-night-mdpi/splash.png new file mode 100644 index 000000000..44e47fe08 Binary files /dev/null and b/client/android/app/src/main/res/drawable-land-night-mdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-land-night-xhdpi/splash.png b/client/android/app/src/main/res/drawable-land-night-xhdpi/splash.png new file mode 100644 index 000000000..86befb958 Binary files /dev/null and b/client/android/app/src/main/res/drawable-land-night-xhdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-land-night-xxhdpi/splash.png b/client/android/app/src/main/res/drawable-land-night-xxhdpi/splash.png new file mode 100644 index 000000000..05ed96e11 Binary files /dev/null and b/client/android/app/src/main/res/drawable-land-night-xxhdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-land-night-xxxhdpi/splash.png b/client/android/app/src/main/res/drawable-land-night-xxxhdpi/splash.png new file mode 100644 index 000000000..a10b336e5 Binary files /dev/null and b/client/android/app/src/main/res/drawable-land-night-xxxhdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-land-xhdpi/splash.png b/client/android/app/src/main/res/drawable-land-xhdpi/splash.png new file mode 100644 index 000000000..86befb958 Binary files /dev/null and b/client/android/app/src/main/res/drawable-land-xhdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-land-xxhdpi/splash.png b/client/android/app/src/main/res/drawable-land-xxhdpi/splash.png new file mode 100644 index 000000000..05ed96e11 Binary files /dev/null and b/client/android/app/src/main/res/drawable-land-xxhdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-land-xxxhdpi/splash.png b/client/android/app/src/main/res/drawable-land-xxxhdpi/splash.png new file mode 100644 index 000000000..a10b336e5 Binary files /dev/null and b/client/android/app/src/main/res/drawable-land-xxxhdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-night/splash.png b/client/android/app/src/main/res/drawable-night/splash.png new file mode 100644 index 000000000..0fc76905b Binary files /dev/null and b/client/android/app/src/main/res/drawable-night/splash.png differ diff --git a/client/android/app/src/main/res/drawable-port-hdpi/splash.png b/client/android/app/src/main/res/drawable-port-hdpi/splash.png new file mode 100644 index 000000000..26fb4b482 Binary files /dev/null and b/client/android/app/src/main/res/drawable-port-hdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-port-ldpi/splash.png b/client/android/app/src/main/res/drawable-port-ldpi/splash.png new file mode 100644 index 000000000..aebbc4c8d Binary files /dev/null and b/client/android/app/src/main/res/drawable-port-ldpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-port-mdpi/splash.png b/client/android/app/src/main/res/drawable-port-mdpi/splash.png new file mode 100644 index 000000000..55a7a810d Binary files /dev/null and b/client/android/app/src/main/res/drawable-port-mdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-port-night-hdpi/splash.png b/client/android/app/src/main/res/drawable-port-night-hdpi/splash.png new file mode 100644 index 000000000..26fb4b482 Binary files /dev/null and b/client/android/app/src/main/res/drawable-port-night-hdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-port-night-ldpi/splash.png b/client/android/app/src/main/res/drawable-port-night-ldpi/splash.png new file mode 100644 index 000000000..aebbc4c8d Binary files /dev/null and b/client/android/app/src/main/res/drawable-port-night-ldpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-port-night-mdpi/splash.png b/client/android/app/src/main/res/drawable-port-night-mdpi/splash.png new file mode 100644 index 000000000..55a7a810d Binary files /dev/null and b/client/android/app/src/main/res/drawable-port-night-mdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-port-night-xhdpi/splash.png b/client/android/app/src/main/res/drawable-port-night-xhdpi/splash.png new file mode 100644 index 000000000..4bc78881a Binary files /dev/null and b/client/android/app/src/main/res/drawable-port-night-xhdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-port-night-xxhdpi/splash.png b/client/android/app/src/main/res/drawable-port-night-xxhdpi/splash.png new file mode 100644 index 000000000..1db91f892 Binary files /dev/null and b/client/android/app/src/main/res/drawable-port-night-xxhdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-port-night-xxxhdpi/splash.png b/client/android/app/src/main/res/drawable-port-night-xxxhdpi/splash.png new file mode 100644 index 000000000..b4480e6c5 Binary files /dev/null and b/client/android/app/src/main/res/drawable-port-night-xxxhdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-port-xhdpi/splash.png b/client/android/app/src/main/res/drawable-port-xhdpi/splash.png new file mode 100644 index 000000000..4bc78881a Binary files /dev/null and b/client/android/app/src/main/res/drawable-port-xhdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-port-xxhdpi/splash.png b/client/android/app/src/main/res/drawable-port-xxhdpi/splash.png new file mode 100644 index 000000000..1db91f892 Binary files /dev/null and b/client/android/app/src/main/res/drawable-port-xxhdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-port-xxxhdpi/splash.png b/client/android/app/src/main/res/drawable-port-xxxhdpi/splash.png new file mode 100644 index 000000000..b4480e6c5 Binary files /dev/null and b/client/android/app/src/main/res/drawable-port-xxxhdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable/splash.png b/client/android/app/src/main/res/drawable/splash.png new file mode 100644 index 000000000..55a7a810d Binary files /dev/null and b/client/android/app/src/main/res/drawable/splash.png differ diff --git a/client/android/app/src/main/res/layout/activity_main.xml b/client/android/app/src/main/res/layout/activity_main.xml new file mode 100644 index 000000000..b5ad13870 --- /dev/null +++ b/client/android/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,12 @@ + + + + + diff --git a/client/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/client/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 000000000..9fa1d84f9 --- /dev/null +++ b/client/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/client/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/client/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 000000000..9fa1d84f9 --- /dev/null +++ b/client/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/client/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/client/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 000000000..1ecdbd50a Binary files /dev/null and b/client/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/client/android/app/src/main/res/mipmap-hdpi/ic_launcher_background.png b/client/android/app/src/main/res/mipmap-hdpi/ic_launcher_background.png new file mode 100644 index 000000000..9eda142ec Binary files /dev/null and b/client/android/app/src/main/res/mipmap-hdpi/ic_launcher_background.png differ diff --git a/client/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png b/client/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png new file mode 100644 index 000000000..4c4f0d080 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png differ diff --git a/client/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/client/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png new file mode 100644 index 000000000..48574eef7 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png differ diff --git a/client/android/app/src/main/res/mipmap-ldpi/ic_launcher.png b/client/android/app/src/main/res/mipmap-ldpi/ic_launcher.png new file mode 100644 index 000000000..18c52ea62 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-ldpi/ic_launcher.png differ diff --git a/client/android/app/src/main/res/mipmap-ldpi/ic_launcher_background.png b/client/android/app/src/main/res/mipmap-ldpi/ic_launcher_background.png new file mode 100644 index 000000000..156955491 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-ldpi/ic_launcher_background.png differ diff --git a/client/android/app/src/main/res/mipmap-ldpi/ic_launcher_foreground.png b/client/android/app/src/main/res/mipmap-ldpi/ic_launcher_foreground.png new file mode 100644 index 000000000..d703351f9 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-ldpi/ic_launcher_foreground.png differ diff --git a/client/android/app/src/main/res/mipmap-ldpi/ic_launcher_round.png b/client/android/app/src/main/res/mipmap-ldpi/ic_launcher_round.png new file mode 100644 index 000000000..df8fd53aa Binary files /dev/null and b/client/android/app/src/main/res/mipmap-ldpi/ic_launcher_round.png differ diff --git a/client/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/client/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 000000000..8ffbeb0f7 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/client/android/app/src/main/res/mipmap-mdpi/ic_launcher_background.png b/client/android/app/src/main/res/mipmap-mdpi/ic_launcher_background.png new file mode 100644 index 000000000..590b65af8 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-mdpi/ic_launcher_background.png differ diff --git a/client/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png b/client/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png new file mode 100644 index 000000000..380f393ba Binary files /dev/null and b/client/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png differ diff --git a/client/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/client/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png new file mode 100644 index 000000000..237de9a01 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png differ diff --git a/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 000000000..8233d2e85 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher_background.png b/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher_background.png new file mode 100644 index 000000000..c10f64659 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher_background.png differ diff --git a/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png b/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png new file mode 100644 index 000000000..1d654c1a3 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png differ diff --git a/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png new file mode 100644 index 000000000..911f1e4fa Binary files /dev/null and b/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 000000000..012c55d9a Binary files /dev/null and b/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.png b/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.png new file mode 100644 index 000000000..059ab588a Binary files /dev/null and b/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.png differ diff --git a/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png b/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png new file mode 100644 index 000000000..bc3061c86 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png differ diff --git a/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png new file mode 100644 index 000000000..e572cd218 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 000000000..bebe0ad39 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.png b/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.png new file mode 100644 index 000000000..92f23a500 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.png differ diff --git a/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png b/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png new file mode 100644 index 000000000..83d5921ac Binary files /dev/null and b/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png differ diff --git a/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100644 index 000000000..94317032b Binary files /dev/null and b/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/client/android/app/src/main/res/values/ic_launcher_background.xml b/client/android/app/src/main/res/values/ic_launcher_background.xml new file mode 100644 index 000000000..c96e7f892 --- /dev/null +++ b/client/android/app/src/main/res/values/ic_launcher_background.xml @@ -0,0 +1,5 @@ + + + #09090B + #09090B + diff --git a/client/android/app/src/main/res/values/strings.xml b/client/android/app/src/main/res/values/strings.xml new file mode 100644 index 000000000..768fe05ff --- /dev/null +++ b/client/android/app/src/main/res/values/strings.xml @@ -0,0 +1,7 @@ + + + TREK + TREK + com.liketrek.trek + com.liketrek.trek + diff --git a/client/android/app/src/main/res/values/styles.xml b/client/android/app/src/main/res/values/styles.xml new file mode 100644 index 000000000..3ee713faa --- /dev/null +++ b/client/android/app/src/main/res/values/styles.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/client/android/app/src/main/res/xml/file_paths.xml b/client/android/app/src/main/res/xml/file_paths.xml new file mode 100644 index 000000000..63d8bf279 --- /dev/null +++ b/client/android/app/src/main/res/xml/file_paths.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/client/android/app/src/main/res/xml/network_security_config.xml b/client/android/app/src/main/res/xml/network_security_config.xml new file mode 100644 index 000000000..479404e90 --- /dev/null +++ b/client/android/app/src/main/res/xml/network_security_config.xml @@ -0,0 +1,30 @@ + + + + + + + + + + diff --git a/client/android/build.gradle b/client/android/build.gradle new file mode 100644 index 000000000..4f622dca6 --- /dev/null +++ b/client/android/build.gradle @@ -0,0 +1,28 @@ +// 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' + + // 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/client/android/capacitor.settings.gradle b/client/android/capacitor.settings.gradle new file mode 100644 index 000000000..108993d73 --- /dev/null +++ b/client/android/capacitor.settings.gradle @@ -0,0 +1,24 @@ +// 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/@capacitor/android/capacitor') + +include ':capacitor-app' +project(':capacitor-app').projectDir = new File('../../node_modules/@capacitor/app/android') + +include ':capacitor-filesystem' +project(':capacitor-filesystem').projectDir = new File('../../node_modules/@capacitor/filesystem/android') + +include ':capacitor-haptics' +project(':capacitor-haptics').projectDir = new File('../../node_modules/@capacitor/haptics/android') + +include ':capacitor-keyboard' +project(':capacitor-keyboard').projectDir = new File('../../node_modules/@capacitor/keyboard/android') + +include ':capacitor-share' +project(':capacitor-share').projectDir = new File('../../node_modules/@capacitor/share/android') + +include ':capacitor-splash-screen' +project(':capacitor-splash-screen').projectDir = new File('../../node_modules/@capacitor/splash-screen/android') + +include ':capacitor-status-bar' +project(':capacitor-status-bar').projectDir = new File('../../node_modules/@capacitor/status-bar/android') diff --git a/client/android/gradle.properties b/client/android/gradle.properties new file mode 100644 index 000000000..2e87c52f8 --- /dev/null +++ b/client/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/client/android/gradle/wrapper/gradle-wrapper.jar b/client/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..1b33c55ba Binary files /dev/null and b/client/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/client/android/gradle/wrapper/gradle-wrapper.properties b/client/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..7705927e9 --- /dev/null +++ b/client/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/client/android/gradlew b/client/android/gradlew new file mode 100755 index 000000000..23d15a936 --- /dev/null +++ b/client/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/client/android/gradlew.bat b/client/android/gradlew.bat new file mode 100644 index 000000000..db3a6ac20 --- /dev/null +++ b/client/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/client/android/settings.gradle b/client/android/settings.gradle new file mode 100644 index 000000000..3b4431d77 --- /dev/null +++ b/client/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/client/android/variables.gradle b/client/android/variables.gradle new file mode 100644 index 000000000..980b88bd5 --- /dev/null +++ b/client/android/variables.gradle @@ -0,0 +1,18 @@ +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' + // Custom Tabs for SSO and passkey sign-in (TrekShellPlugin.authenticate). + androidxBrowserVersion = '1.8.0' +} \ No newline at end of file diff --git a/client/assets/icon-background.png b/client/assets/icon-background.png new file mode 100644 index 000000000..147028acc Binary files /dev/null and b/client/assets/icon-background.png differ diff --git a/client/assets/icon-foreground.png b/client/assets/icon-foreground.png new file mode 100644 index 000000000..494f4e95f Binary files /dev/null and b/client/assets/icon-foreground.png differ diff --git a/client/assets/icon-only.png b/client/assets/icon-only.png new file mode 100644 index 000000000..5ab37c184 Binary files /dev/null and b/client/assets/icon-only.png differ diff --git a/client/assets/splash-dark.png b/client/assets/splash-dark.png new file mode 100644 index 000000000..90e75a40f Binary files /dev/null and b/client/assets/splash-dark.png differ diff --git a/client/assets/splash.png b/client/assets/splash.png new file mode 100644 index 000000000..90e75a40f Binary files /dev/null and b/client/assets/splash.png differ diff --git a/client/capacitor.config.ts b/client/capacitor.config.ts new file mode 100644 index 000000000..9069f5b16 --- /dev/null +++ b/client/capacitor.config.ts @@ -0,0 +1,60 @@ +/// +/// +import type { CapacitorConfig } from '@capacitor/cli'; +import { KeyboardResize } from '@capacitor/keyboard'; + +const config: CapacitorConfig = { + appId: 'com.liketrek.trek', + // What the home screen shows under the icon; the longer title belongs to + // the store listings. + appName: 'TREK', + // The app ships only the address screen. Once a server is picked, the native + // side points the WebView at it (TrekBridgeViewController.swift, + // MainActivity.java) and the UI comes from that server, always in the version + // the server runs. Session cookie, uploads, /ws and plugins work as they do in + // a browser, because the WebView is on the server's own origin. + webDir: 'native-dist', + server: { + // Android serves the address screen from https://localhost so it is a + // secure context. iOS keeps its default capacitor:// scheme: WKWebView + // handles https itself and Capacitor silently drops an iosScheme of https. + androidScheme: 'https', + // iOS shows this page from the app bundle whenever the server fails to + // load. It knows a server is remembered, first tries the stored offline + // copy of the server's start page, then offers to retry or pick another + // one. Android restarts on the same page instead (TrekWebViewClient.java), + // because it injects no bridge into a local page while a server is set. + errorPath: 'index.html', + }, + ios: { + // Long-pressing a link shows a Safari preview otherwise, which no app does. + allowsLinkPreview: false, + }, + plugins: { + SplashScreen: { + // Matches in index.html, so the launch image, + // the splash and the first painted frame are the same colour and there is + // no white flash between them. + backgroundColor: '#09090b', + // The server's UI hides it once React has mounted (native/nativeApp.ts), + // the address screen once it has rendered. Auto-hide stays on as the + // ceiling, so a page that never gets there cannot leave it up for good. + launchAutoHide: true, + launchShowDuration: 4000, + launchFadeOutDuration: 200, + showSpinner: false, + androidScaleType: 'CENTER_CROP', + }, + Keyboard: { + // The mobile shell is built from bottom sheets (mobile/screens/**/M*Sheet). + // `body` resizes the webview itself, so a sheet's own scroll container + // keeps working; `native` resizes the whole view and fights the sheet. + resize: KeyboardResize.Body, + // Android-only workaround: with an edge-to-edge status bar the webview + // otherwise does not resize at all when the keyboard opens. + resizeOnFullScreen: true, + }, + }, +}; + +export default config; diff --git a/client/e2e/store/capture.store.ts b/client/e2e/store/capture.store.ts new file mode 100644 index 000000000..7e092ca23 --- /dev/null +++ b/client/e2e/store/capture.store.ts @@ -0,0 +1,72 @@ +import { test, type Page } from '@playwright/test'; +import { mkdirSync } from 'node:fs'; +import path from 'node:path'; + +import { E2E_STATE_FILE } from '../../playwright.config'; +import { clearNotices, seed } from '../screenshots/shot'; + +/** + * The store screenshots (`npm run store:shots`, then `npm run store:promote`). + * + * The same seeded demo trip the wiki pictures show, captured at the sizes App + * Store Connect and Google Play ask for: the iPhone 6.9" and iPad 13" displays, + * and a Play phone, 7" and 10" tablet. Below 768 px the phone shell answers, so + * the phone pictures show the phone UI; the tablets get the desktop layout they + * get on a real device. + * + * Raw captures go to e2e/.tmp/store//; scripts/store-screenshots.mjs + * flattens them (the stores refuse an alpha channel) and copies them into + * fastlane/. Nothing here asserts behaviour, and the run is not part of CI. + */ + +const STORE_OUT_DIR = path.join(process.cwd(), 'e2e', '.tmp', 'store'); + +const DEVICES = [ + { name: 'iphone69', viewport: { width: 440, height: 956 }, deviceScaleFactor: 3, isMobile: true }, + { name: 'ipad13', viewport: { width: 1032, height: 1376 }, deviceScaleFactor: 2, isMobile: true }, + { name: 'play-phone', viewport: { width: 360, height: 640 }, deviceScaleFactor: 3, isMobile: true }, + { name: 'play-7in', viewport: { width: 810, height: 1440 }, deviceScaleFactor: 2, isMobile: true }, + { name: 'play-10in', viewport: { width: 1280, height: 720 }, deviceScaleFactor: 1.5, isMobile: true }, +] as const; + +/** The screens, in the order the listings show them. */ +const SCREENS: { name: string; path: () => string }[] = [ + { name: 'dashboard', path: () => '/dashboard' }, + { name: 'plan', path: () => `/trips/${seed.tripId}?tab=plan` }, + { name: 'bookings', path: () => `/trips/${seed.tripId}?tab=buchungen` }, + { name: 'costs', path: () => `/trips/${seed.tripId}?tab=finanzplan` }, + { name: 'lists', path: () => `/trips/${seed.tripId}?tab=listen` }, + { name: 'journal', path: () => (seed.journeyId ? `/journey/${seed.journeyId}` : '/journey') }, +]; + +/** Waits until the page has drawn what it is going to draw: fonts, images, no pending fade. */ +async function settle(page: Page): Promise { + await page.waitForLoadState('networkidle', { timeout: 5_000 }).catch(() => undefined); + await page.evaluate(async () => { + await document.fonts.ready; + }); + await page.waitForTimeout(800); +} + +for (const device of DEVICES) { + test.describe(device.name, () => { + test.use({ + storageState: E2E_STATE_FILE, + viewport: device.viewport, + deviceScaleFactor: device.deviceScaleFactor, + isMobile: device.isMobile, + hasTouch: true, + }); + + SCREENS.forEach((screen, index) => { + test(`${index + 1} ${screen.name}`, async ({ page }) => { + const dir = path.join(STORE_OUT_DIR, device.name); + mkdirSync(dir, { recursive: true }); + await page.goto(screen.path()); + await clearNotices(page); + await settle(page); + await page.screenshot({ path: path.join(dir, `${index + 1}_${screen.name}.png`) }); + }); + }); + }); +} diff --git a/client/eslint.config.mjs b/client/eslint.config.mjs index 2fe715cee..1f24f898e 100644 --- a/client/eslint.config.mjs +++ b/client/eslint.config.mjs @@ -31,6 +31,14 @@ export default tseslint.config( 'public', 'test-results', 'playwright-report', + // Capacitor native shells. `npx cap sync` copies the built address screen + // from native-dist/ into both platforms, so without these ESLint lints the + // minified output. gitignore() does not cover them: the iOS and Android + // .gitignore files live one level down, and this config's gitignore + // integration only reads client/.gitignore. + 'native-dist', + 'android/**', + 'ios/**', 'e2e/**', 'scripts/**', '**/*.config.js', diff --git a/client/fastlane/README.md b/client/fastlane/README.md new file mode 100644 index 000000000..08edb1a5e --- /dev/null +++ b/client/fastlane/README.md @@ -0,0 +1,55 @@ +# Store listings + +The texts, review notes, policy drafts and images for the App Store and Google +Play listings of **TREK Travel Planner** (`com.liketrek.trek`). The folder +layout is the one fastlane's `deliver` (App Store) and `supply` (Google Play) +read, so the listings can be uploaded from here; the builds themselves come from +`.github/workflows/native-release.yml`. + +| Path | What | +| --- | --- | +| `metadata/en-US/` | App Store texts: name, subtitle, keywords, description, URLs, release notes | +| `metadata/review_information/` | App Review notes and contact. Placeholders only: the review server, accounts and passwords are entered in App Store Connect, never committed | +| `metadata/android/en-US/` | Google Play texts, the changelog, and `images/` (feature graphic, icon, screenshots) | +| `metadata/privacy-policy.md`, `metadata/delete-account.md` | Drafts of the pages published at https://liketrek.com/privacy and https://liketrek.com/delete-account | +| `screenshots/en-US/` | App Store screenshots, iPhone 6.9" and iPad 13" | + +`npm run store:check` (in `client/`) checks every text against its store limit +and every image for its size and for an alpha channel, which both stores refuse. +CI runs it in the `metadata` job of `native.yml`. + +## Screenshots + +The screenshots are not committed yet: they are captured from a running TREK +with the seeded demo trip, which is a Playwright run and does not run in CI. +To make them, from `client/`: + +1. `npx playwright install chromium` (once). +2. `npm run store:shots` starts its own backend on a throwaway database and the + Vite dev server, seeds the demo trip (the same one the wiki pictures show) + and captures six screens at five device sizes into `e2e/.tmp/store/`. +3. `npm run store:promote` checks each capture's size, flattens it onto the app + background (no alpha) and copies it into `screenshots/en-US/` (iPhone 6.9" + 1320x2868, iPad 13" 2064x2752) and + `metadata/android/en-US/images/{phone,sevenInch,tenInch}Screenshots/` + (1080x1920, 1620x2880, 1920x1080). +4. `npm run store:graphic` rebuilds the feature graphic, now with a crop of the + first phone screenshot, and the 512 px icon. +5. `npm run store:check`, look through the pictures, commit. + +The capture lives in `e2e/store/capture.store.ts`; the device sizes and screens +are listed at its top. + +## Uploading the listing + +With fastlane installed and the App Store Connect API key and Play service +account at hand (the same ones the release workflow uses, see +`wiki/Native-Apps.md`), from `client/`: + +```bash +fastlane deliver --skip_binary_upload --metadata_path fastlane/metadata --screenshots_path fastlane/screenshots +fastlane supply --skip_upload_apk --skip_upload_aab --metadata_path fastlane/metadata/android --package_name com.liketrek.trek +``` + +Both also work from the consoles by hand; the files here are the source of +truth for what the listings say. diff --git a/client/fastlane/metadata/android/en-US/changelogs/default.txt b/client/fastlane/metadata/android/en-US/changelogs/default.txt new file mode 100644 index 000000000..fd85f3c68 --- /dev/null +++ b/client/fastlane/metadata/android/en-US/changelogs/default.txt @@ -0,0 +1 @@ +The first release of TREK for Android: connect to your TREK server, plan together, and take your trips offline. diff --git a/client/fastlane/metadata/android/en-US/full_description.txt b/client/fastlane/metadata/android/en-US/full_description.txt new file mode 100644 index 000000000..bd7c62d99 --- /dev/null +++ b/client/fastlane/metadata/android/en-US/full_description.txt @@ -0,0 +1,24 @@ +TREK is a travel planner for the trips you take with other people. Plan the days together, see every place on the map, keep bookings, costs and packing lists in one place, and still have all of it with you when the connection drops. + +TREK is open source and works with a TREK server: one you run yourself, at home or on a rented server, one your organisation provides, or the public demo to try it out. Your trips stay on that server. The makers of TREK receive none of your data. + +PLAN TOGETHER +• Days with places, notes, transports and stays, in order and on the map +• Changes from everyone on the trip appear live +• Roles that decide who may change what + +BOOKINGS AND COSTS +• Flights, trains, hotels, rentals and tickets, with their documents +• Shared expenses with fair splits and who owes whom, in any currency + +ON THE ROAD +• Trips you choose are kept on the device, maps included, for when you are offline +• Packing lists and to-dos for the whole group +• A travel journal with photos, and an atlas of the countries you have visited + +YOUR DATA +• No account with us, no tracking, no ads +• Sign in with a password, a passkey or your organisation's single sign-on +• Available in 27 languages + +To use the app you need the address of a TREK server. Without one yet, tap "Try the demo" on the first screen, or read how to run your own at github.com/liketrek/TREK. diff --git a/client/fastlane/metadata/android/en-US/images/featureGraphic.png b/client/fastlane/metadata/android/en-US/images/featureGraphic.png new file mode 100644 index 000000000..ae4f53f4d Binary files /dev/null and b/client/fastlane/metadata/android/en-US/images/featureGraphic.png differ diff --git a/client/fastlane/metadata/android/en-US/images/icon.png b/client/fastlane/metadata/android/en-US/images/icon.png new file mode 100644 index 000000000..8ed9a14ef Binary files /dev/null and b/client/fastlane/metadata/android/en-US/images/icon.png differ diff --git a/client/fastlane/metadata/android/en-US/short_description.txt b/client/fastlane/metadata/android/en-US/short_description.txt new file mode 100644 index 000000000..3426da766 --- /dev/null +++ b/client/fastlane/metadata/android/en-US/short_description.txt @@ -0,0 +1 @@ +Plan trips together on your own TREK server, with maps, bookings and costs. diff --git a/client/fastlane/metadata/android/en-US/title.txt b/client/fastlane/metadata/android/en-US/title.txt new file mode 100644 index 000000000..208f34555 --- /dev/null +++ b/client/fastlane/metadata/android/en-US/title.txt @@ -0,0 +1 @@ +TREK Travel Planner diff --git a/client/fastlane/metadata/copyright.txt b/client/fastlane/metadata/copyright.txt new file mode 100644 index 000000000..7125b0aa7 --- /dev/null +++ b/client/fastlane/metadata/copyright.txt @@ -0,0 +1 @@ +2026 [PUBLISHER LEGAL NAME] diff --git a/client/fastlane/metadata/delete-account.md b/client/fastlane/metadata/delete-account.md new file mode 100644 index 000000000..ec93cd957 --- /dev/null +++ b/client/fastlane/metadata/delete-account.md @@ -0,0 +1,29 @@ +# TREK Travel Planner: Delete your account + +_Draft. The publisher fills in the bracketed fields before this is published at https://liketrek.com/delete-account._ + +Your TREK account and everything in it live on the TREK server you signed in to, not with [PUBLISHER LEGAL NAME], the publisher of the app. You can delete it in either of these ways: + +## In the app + +1. Open the app and sign in. +2. Go to **Settings > Account**. +3. Choose **Delete account** and confirm. + +The account is deleted on the server at once, together with its trips you own, your files, photos, journal entries and settings. Trips you share with others stay with their other members; your contributions to them are removed or anonymised. + +## Without the app + +Open your TREK server in a web browser, sign in and go to **Settings > Account > Delete account**. If you cannot sign in any more, ask the administrator of your server to delete the account. + +## The public demo + +Accounts on demo.liketrek.com cannot be deleted one by one: the demo is shared and is reset to its sample data every hour, which removes everything entered there. + +## Data on your device + +Removing the app from your phone or tablet removes the server address, your session and the trips kept offline. + +## Questions + +[CONTACT EMAIL] diff --git a/client/fastlane/metadata/en-US/description.txt b/client/fastlane/metadata/en-US/description.txt new file mode 100644 index 000000000..bd7c62d99 --- /dev/null +++ b/client/fastlane/metadata/en-US/description.txt @@ -0,0 +1,24 @@ +TREK is a travel planner for the trips you take with other people. Plan the days together, see every place on the map, keep bookings, costs and packing lists in one place, and still have all of it with you when the connection drops. + +TREK is open source and works with a TREK server: one you run yourself, at home or on a rented server, one your organisation provides, or the public demo to try it out. Your trips stay on that server. The makers of TREK receive none of your data. + +PLAN TOGETHER +• Days with places, notes, transports and stays, in order and on the map +• Changes from everyone on the trip appear live +• Roles that decide who may change what + +BOOKINGS AND COSTS +• Flights, trains, hotels, rentals and tickets, with their documents +• Shared expenses with fair splits and who owes whom, in any currency + +ON THE ROAD +• Trips you choose are kept on the device, maps included, for when you are offline +• Packing lists and to-dos for the whole group +• A travel journal with photos, and an atlas of the countries you have visited + +YOUR DATA +• No account with us, no tracking, no ads +• Sign in with a password, a passkey or your organisation's single sign-on +• Available in 27 languages + +To use the app you need the address of a TREK server. Without one yet, tap "Try the demo" on the first screen, or read how to run your own at github.com/liketrek/TREK. diff --git a/client/fastlane/metadata/en-US/keywords.txt b/client/fastlane/metadata/en-US/keywords.txt new file mode 100644 index 000000000..97a72ad9e --- /dev/null +++ b/client/fastlane/metadata/en-US/keywords.txt @@ -0,0 +1 @@ +travel,trip planner,itinerary,road trip,packing list,travel journal,offline map,budget,vacation diff --git a/client/fastlane/metadata/en-US/marketing_url.txt b/client/fastlane/metadata/en-US/marketing_url.txt new file mode 100644 index 000000000..b9041b3d3 --- /dev/null +++ b/client/fastlane/metadata/en-US/marketing_url.txt @@ -0,0 +1 @@ +https://liketrek.com diff --git a/client/fastlane/metadata/en-US/name.txt b/client/fastlane/metadata/en-US/name.txt new file mode 100644 index 000000000..208f34555 --- /dev/null +++ b/client/fastlane/metadata/en-US/name.txt @@ -0,0 +1 @@ +TREK Travel Planner diff --git a/client/fastlane/metadata/en-US/privacy_url.txt b/client/fastlane/metadata/en-US/privacy_url.txt new file mode 100644 index 000000000..248586c57 --- /dev/null +++ b/client/fastlane/metadata/en-US/privacy_url.txt @@ -0,0 +1 @@ +https://liketrek.com/privacy diff --git a/client/fastlane/metadata/en-US/promotional_text.txt b/client/fastlane/metadata/en-US/promotional_text.txt new file mode 100644 index 000000000..6209d274a --- /dev/null +++ b/client/fastlane/metadata/en-US/promotional_text.txt @@ -0,0 +1 @@ +Plan every day of a trip with the people you travel with, keep bookings and costs in one place, and take it all offline. Your trips stay on the TREK server you choose. diff --git a/client/fastlane/metadata/en-US/release_notes.txt b/client/fastlane/metadata/en-US/release_notes.txt new file mode 100644 index 000000000..d3f4542c7 --- /dev/null +++ b/client/fastlane/metadata/en-US/release_notes.txt @@ -0,0 +1 @@ +The first release of TREK for iPhone and iPad: connect to your TREK server, plan together, and take your trips offline. diff --git a/client/fastlane/metadata/en-US/subtitle.txt b/client/fastlane/metadata/en-US/subtitle.txt new file mode 100644 index 000000000..5cacad5c2 --- /dev/null +++ b/client/fastlane/metadata/en-US/subtitle.txt @@ -0,0 +1 @@ +Plan trips on your own server diff --git a/client/fastlane/metadata/en-US/support_url.txt b/client/fastlane/metadata/en-US/support_url.txt new file mode 100644 index 000000000..f5b94c1c2 --- /dev/null +++ b/client/fastlane/metadata/en-US/support_url.txt @@ -0,0 +1 @@ +https://liketrek.com/support diff --git a/client/fastlane/metadata/primary_category.txt b/client/fastlane/metadata/primary_category.txt new file mode 100644 index 000000000..bed7befd5 --- /dev/null +++ b/client/fastlane/metadata/primary_category.txt @@ -0,0 +1 @@ +TRAVEL diff --git a/client/fastlane/metadata/privacy-policy.md b/client/fastlane/metadata/privacy-policy.md new file mode 100644 index 000000000..2ff1bace5 --- /dev/null +++ b/client/fastlane/metadata/privacy-policy.md @@ -0,0 +1,44 @@ +# TREK Travel Planner: Privacy Policy + +_Draft. The publisher fills in the bracketed fields before this is published at https://liketrek.com/privacy._ + +Last updated: [DATE] + +## Who publishes the app + +TREK Travel Planner ("the app") is published by [PUBLISHER LEGAL NAME], [POSTAL ADDRESS], [CONTACT EMAIL] ("we"). + +## The short version + +The app is a client for a TREK server that you choose. Everything you enter in the app goes to that server and is stored there. We, the publisher of the app, receive none of it: no account, no analytics, no crash reports, no advertising identifiers, no tracking. + +## Where your data goes + +- **Your TREK server.** When you connect the app to a server, the app sends what you enter (your account details, trips, places, bookings, documents, photos, expenses, messages, journal entries and, if you allow it, your location for the map) to that server. Whoever runs that server is responsible for it: you, if you host it yourself, or the organisation that provides it. Their own privacy policy applies to it. +- **The public demo.** If you choose "Try the demo", the app connects to demo.liketrek.com, which we run. The demo is shared by everyone who tries it and is reset every hour; do not enter real personal data there. +- **Map tiles and exchange rates.** To draw maps, the app loads map tiles from the tile provider your server is configured with (by default OpenStreetMap-based providers such as OpenFreeMap). These requests carry the map area you look at and your IP address, as every web request does. Currency conversion rates come from a public exchange-rate service. These providers receive no account or trip data. +- **The system browser.** Signing in with single sign-on or a passkey opens the system browser on your server's sign-in page. + +## Data on your device + +The app keeps the server address, your session cookie and, for trips you choose to keep offline, a copy of those trips, their files and map tiles on your device. Removing the app removes all of it. On Android the app is excluded from device backups, so your session does not travel to other devices. + +## Permissions + +The camera, microphone and photo library are used only when you add a photo, a video or a document. Location is used only to centre the map on you. Each is asked for by the system when first needed and can be withdrawn in the system settings. + +## Deleting your data + +Delete your account in the app under Settings > Account > Delete account, or ask the administrator of your server. This removes the account and its data from that server. See https://liketrek.com/delete-account. Because we do not hold your data, we cannot delete it for you, but we will help you find the right contact. + +## Children + +The app is not directed at children under 13, and we do not knowingly receive data from them. + +## Changes + +We will publish changes to this policy on this page and update the date above. + +## Contact + +[CONTACT EMAIL] diff --git a/client/fastlane/metadata/review_information/demo_password.txt b/client/fastlane/metadata/review_information/demo_password.txt new file mode 100644 index 000000000..d8496d9b5 --- /dev/null +++ b/client/fastlane/metadata/review_information/demo_password.txt @@ -0,0 +1 @@ +[PASSWORD, never committed] diff --git a/client/fastlane/metadata/review_information/demo_user.txt b/client/fastlane/metadata/review_information/demo_user.txt new file mode 100644 index 000000000..0fc528787 --- /dev/null +++ b/client/fastlane/metadata/review_information/demo_user.txt @@ -0,0 +1 @@ +[REVIEW ACCOUNT 1 EMAIL] diff --git a/client/fastlane/metadata/review_information/email_address.txt b/client/fastlane/metadata/review_information/email_address.txt new file mode 100644 index 000000000..40b688978 --- /dev/null +++ b/client/fastlane/metadata/review_information/email_address.txt @@ -0,0 +1 @@ +[CONTACT EMAIL] diff --git a/client/fastlane/metadata/review_information/first_name.txt b/client/fastlane/metadata/review_information/first_name.txt new file mode 100644 index 000000000..0f98f5681 --- /dev/null +++ b/client/fastlane/metadata/review_information/first_name.txt @@ -0,0 +1 @@ +[CONTACT FIRST NAME] diff --git a/client/fastlane/metadata/review_information/last_name.txt b/client/fastlane/metadata/review_information/last_name.txt new file mode 100644 index 000000000..7d1cc9cff --- /dev/null +++ b/client/fastlane/metadata/review_information/last_name.txt @@ -0,0 +1 @@ +[CONTACT LAST NAME] diff --git a/client/fastlane/metadata/review_information/notes.txt b/client/fastlane/metadata/review_information/notes.txt new file mode 100644 index 000000000..e8bd67d45 --- /dev/null +++ b/client/fastlane/metadata/review_information/notes.txt @@ -0,0 +1,33 @@ +TREK Travel Planner is the iOS client of TREK, an open-source, self-hostable travel planner (https://github.com/liketrek/TREK). Each user or organisation runs their own TREK server; the app asks for the server's address on first start and then shows the TREK web interface that server delivers. + +HOW TO REVIEW +1. Open the app. On the address screen enter: [REVIEW SERVER URL, e.g. https://review.example.com] +2. Sign in with one of the review accounts below (each starts with the same sample trips). +3. Open a sample trip from the dashboard: the day plan with its map, then the Bookings, Costs and Lists tabs. +4. Settings > Account shows the connected server and the privacy policy link at the top, and "Delete account" with the profile. + +Review accounts on the review server (not the public demo, which blocks deletion): +- [REVIEW ACCOUNT 1 EMAIL] / [PASSWORD] +- [REVIEW ACCOUNT 2 EMAIL] / [PASSWORD] +- [REVIEW ACCOUNT 3 EMAIL] / [PASSWORD] + +NATIVE FEATURES +The app is more than a website in a frame: its own address screen with server validation and an offline fallback screen, sign-in through the system browser (ASWebAuthenticationSession) for single sign-on and passkeys, offline maps and trips stored on the device, the share sheet for exports and documents, haptic feedback, the native status bar, splash screen and back gestures. + +DOWNLOADED INTERFACE (2.5.2 / 4.2) +The interface comes from the user's own server, in the version that server runs, just as a mail client shows the messages its server holds. It contains no executable code that changes the app's features or purpose beyond what this build reviews; every server runs the same open-source TREK. + +APP TRANSPORT SECURITY +NSAllowsArbitraryLoads is set because the user types in their own server address, which the app cannot know at build time: often a home server reached as http://192.168.x.x or over a VPN such as Tailscale (100.64.0.0/10, not covered by NSAllowsLocalNetworking). HTTPS remains the documented recommendation for servers outside a local network. + +SIGN-IN (4.8) +Accounts belong to the user's server, not to us. The app offers whatever that server offers: a password, a passkey, or the single sign-on of the organisation running the server. There is no third-party social login, so Sign in with Apple does not apply. + +USER-GENERATED CONTENT +Content is shared only between people invited to the same trip on the same private server; there is no public feed. The server's administrator manages accounts and can remove content and users. + +ACCOUNT DELETION +Settings > Account > Delete account deletes the account and its data on the server. See also https://liketrek.com/delete-account. + +CONTACT +[CONTACT NAME], [CONTACT EMAIL] diff --git a/client/fastlane/metadata/review_information/phone_number.txt b/client/fastlane/metadata/review_information/phone_number.txt new file mode 100644 index 000000000..44625e806 --- /dev/null +++ b/client/fastlane/metadata/review_information/phone_number.txt @@ -0,0 +1 @@ +[CONTACT PHONE] diff --git a/client/fastlane/metadata/secondary_category.txt b/client/fastlane/metadata/secondary_category.txt new file mode 100644 index 000000000..cd65e7934 --- /dev/null +++ b/client/fastlane/metadata/secondary_category.txt @@ -0,0 +1 @@ +PRODUCTIVITY diff --git a/client/ios/.gitignore b/client/ios/.gitignore new file mode 100644 index 000000000..f47029973 --- /dev/null +++ b/client/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/client/ios/App/App.xcodeproj/project.pbxproj b/client/ios/App/App.xcodeproj/project.pbxproj new file mode 100644 index 000000000..d2dc88309 --- /dev/null +++ b/client/ios/App/App.xcodeproj/project.pbxproj @@ -0,0 +1,401 @@ +// !$*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 */; }; + 9582B6832FE993A70072D4E8 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9582B6822FE993A50072D4E8 /* SceneDelegate.swift */; }; + 7A1E00032C0000000000A003 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 7A1E00022C0000000000A002 /* PrivacyInfo.xcprivacy */; }; + 7A1E00052C0000000000A005 /* TrekBridgeViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A1E00042C0000000000A004 /* TrekBridgeViewController.swift */; }; + 7A1E00072C0000000000A007 /* TrekShellPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A1E00062C0000000000A006 /* TrekShellPlugin.swift */; }; +/* 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 = ""; }; + 9582B6822FE993A50072D4E8 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 958DCC722DB07C7200EA8C5F /* debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = debug.xcconfig; path = ../debug.xcconfig; sourceTree = SOURCE_ROOT; }; + 7A1E00012C0000000000A001 /* App.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = App.entitlements; sourceTree = ""; }; + 7A1E00022C0000000000A002 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = PrivacyInfo.xcprivacy; sourceTree = ""; }; + 7A1E00042C0000000000A004 /* TrekBridgeViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TrekBridgeViewController.swift; sourceTree = ""; }; + 7A1E00062C0000000000A006 /* TrekShellPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TrekShellPlugin.swift; 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 = ( + 9582B6822FE993A50072D4E8 /* SceneDelegate.swift */, + 50379B222058CBB4000EE86E /* capacitor.config.json */, + 504EC3071FED79650016851F /* AppDelegate.swift */, + 7A1E00042C0000000000A004 /* TrekBridgeViewController.swift */, + 7A1E00062C0000000000A006 /* TrekShellPlugin.swift */, + 504EC30B1FED79650016851F /* Main.storyboard */, + 504EC30E1FED79650016851F /* Assets.xcassets */, + 504EC3101FED79650016851F /* LaunchScreen.storyboard */, + 504EC3131FED79650016851F /* Info.plist */, + 7A1E00012C0000000000A001 /* App.entitlements */, + 7A1E00022C0000000000A002 /* 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; + SystemCapabilities = { + com.apple.Push = { + enabled = 1; + }; + }; + }; + }; + }; + 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 */, + 7A1E00032C0000000000A003 /* PrivacyInfo.xcprivacy in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 504EC3001FED79650016851F /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 504EC3081FED79650016851F /* AppDelegate.swift in Sources */, + 9582B6832FE993A70072D4E8 /* SceneDelegate.swift in Sources */, + 7A1E00052C0000000000A005 /* TrekBridgeViewController.swift in Sources */, + 7A1E00072C0000000000A007 /* TrekShellPlugin.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 = 15.0; + 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 = 15.0; + 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 = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + OTHER_SWIFT_FLAGS = "$(inherited) \"-D\" \"COCOAPODS\" \"-DDEBUG\""; + PRODUCT_BUNDLE_IDENTIFIER = com.liketrek.trek; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 504EC3181FED79650016851F /* Release */ = { + isa = XCBuildConfiguration; + 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 = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.liketrek.trek; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = ""; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + 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/client/ios/App/App.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/client/ios/App/App.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/client/ios/App/App.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/client/ios/App/App/App.entitlements b/client/ios/App/App/App.entitlements new file mode 100644 index 000000000..6631ffa6f --- /dev/null +++ b/client/ios/App/App/App.entitlements @@ -0,0 +1,6 @@ + + + + + + diff --git a/client/ios/App/App/AppDelegate.swift b/client/ios/App/App/AppDelegate.swift new file mode 100644 index 000000000..fec95acae --- /dev/null +++ b/client/ios/App/App/AppDelegate.swift @@ -0,0 +1,44 @@ +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(_ application: UIApplication, + configurationForConnecting connectingSceneSession: UISceneSession, + options: UIScene.ConnectionOptions) -> UISceneConfiguration { + let config = UISceneConfiguration(name: "Default Configuration", + sessionRole: connectingSceneSession.role) + config.delegateClass = SceneDelegate.self + return config + } +} diff --git a/client/ios/App/App/Assets.xcassets/AppIcon.appiconset/AppIcon-512@2x.png b/client/ios/App/App/Assets.xcassets/AppIcon.appiconset/AppIcon-512@2x.png new file mode 100644 index 000000000..adc348d3e Binary files /dev/null and b/client/ios/App/App/Assets.xcassets/AppIcon.appiconset/AppIcon-512@2x.png differ diff --git a/client/ios/App/App/Assets.xcassets/AppIcon.appiconset/Contents.json b/client/ios/App/App/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 000000000..b1a84833e --- /dev/null +++ b/client/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/client/ios/App/App/Assets.xcassets/Contents.json b/client/ios/App/App/Assets.xcassets/Contents.json new file mode 100644 index 000000000..da4a164c9 --- /dev/null +++ b/client/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/client/ios/App/App/Assets.xcassets/Splash.imageset/Contents.json b/client/ios/App/App/Assets.xcassets/Splash.imageset/Contents.json new file mode 100644 index 000000000..84a416d6b --- /dev/null +++ b/client/ios/App/App/Assets.xcassets/Splash.imageset/Contents.json @@ -0,0 +1,56 @@ +{ + "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" + }, + { + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ], + "idiom": "universal", + "scale": "1x", + "filename": "Default@1x~universal~anyany-dark.png" + }, + { + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ], + "idiom": "universal", + "scale": "2x", + "filename": "Default@2x~universal~anyany-dark.png" + }, + { + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ], + "idiom": "universal", + "scale": "3x", + "filename": "Default@3x~universal~anyany-dark.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +} \ No newline at end of file diff --git a/client/ios/App/App/Assets.xcassets/Splash.imageset/Default@1x~universal~anyany-dark.png b/client/ios/App/App/Assets.xcassets/Splash.imageset/Default@1x~universal~anyany-dark.png new file mode 100644 index 000000000..90e75a40f Binary files /dev/null and b/client/ios/App/App/Assets.xcassets/Splash.imageset/Default@1x~universal~anyany-dark.png differ diff --git a/client/ios/App/App/Assets.xcassets/Splash.imageset/Default@1x~universal~anyany.png b/client/ios/App/App/Assets.xcassets/Splash.imageset/Default@1x~universal~anyany.png new file mode 100644 index 000000000..90e75a40f Binary files /dev/null and b/client/ios/App/App/Assets.xcassets/Splash.imageset/Default@1x~universal~anyany.png differ diff --git a/client/ios/App/App/Assets.xcassets/Splash.imageset/Default@2x~universal~anyany-dark.png b/client/ios/App/App/Assets.xcassets/Splash.imageset/Default@2x~universal~anyany-dark.png new file mode 100644 index 000000000..90e75a40f Binary files /dev/null and b/client/ios/App/App/Assets.xcassets/Splash.imageset/Default@2x~universal~anyany-dark.png differ diff --git a/client/ios/App/App/Assets.xcassets/Splash.imageset/Default@2x~universal~anyany.png b/client/ios/App/App/Assets.xcassets/Splash.imageset/Default@2x~universal~anyany.png new file mode 100644 index 000000000..90e75a40f Binary files /dev/null and b/client/ios/App/App/Assets.xcassets/Splash.imageset/Default@2x~universal~anyany.png differ diff --git a/client/ios/App/App/Assets.xcassets/Splash.imageset/Default@3x~universal~anyany-dark.png b/client/ios/App/App/Assets.xcassets/Splash.imageset/Default@3x~universal~anyany-dark.png new file mode 100644 index 000000000..90e75a40f Binary files /dev/null and b/client/ios/App/App/Assets.xcassets/Splash.imageset/Default@3x~universal~anyany-dark.png differ diff --git a/client/ios/App/App/Assets.xcassets/Splash.imageset/Default@3x~universal~anyany.png b/client/ios/App/App/Assets.xcassets/Splash.imageset/Default@3x~universal~anyany.png new file mode 100644 index 000000000..90e75a40f Binary files /dev/null and b/client/ios/App/App/Assets.xcassets/Splash.imageset/Default@3x~universal~anyany.png differ diff --git a/client/ios/App/App/Base.lproj/LaunchScreen.storyboard b/client/ios/App/App/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 000000000..e7ae5d780 --- /dev/null +++ b/client/ios/App/App/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/client/ios/App/App/Base.lproj/Main.storyboard b/client/ios/App/App/Base.lproj/Main.storyboard new file mode 100644 index 000000000..2edb91811 --- /dev/null +++ b/client/ios/App/App/Base.lproj/Main.storyboard @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/client/ios/App/App/Info.plist b/client/ios/App/App/Info.plist new file mode 100644 index 000000000..b4d095119 --- /dev/null +++ b/client/ios/App/App/Info.plist @@ -0,0 +1,141 @@ + + + + + CAPACITOR_DEBUG + $(CAPACITOR_DEBUG) + CFBundleDevelopmentRegion + en + CFBundleDisplayName + TREK + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(MARKETING_VERSION) + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + + ITSAppUsesNonExemptEncryption + + LSRequiresIPhoneOS + + + NSAppTransportSecurity + + NSAllowsArbitraryLoads + + + + NSLocalNetworkUsageDescription + TREK connects to the TREK server you choose, which is often running on your home or office network. + + NSCameraUsageDescription + TREK uses the camera so you can photograph a place, a journey entry or a booking document and add it to your trip. + + NSMicrophoneUsageDescription + TREK records sound when you film a video for a journey entry. + NSPhotoLibraryUsageDescription + TREK needs access to your photos so you can add them to trips, places and journey entries. + + NSPhotoLibraryAddUsageDescription + TREK saves photos and exports you download from your trips back to your photo library. + + NSLocationWhenInUseUsageDescription + TREK uses your location to centre the map on you and to find places near you. + + CFBundleURLTypes + + + CFBundleURLName + com.liketrek.trek + CFBundleTypeRole + Editor + CFBundleURLSchemes + + com.liketrek.trek + + + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneConfigurationName + Default Configuration + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + UISceneStoryboardFile + Main + + + + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UIRequiredDeviceCapabilities + + arm64 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UIViewControllerBasedStatusBarAppearance + + + diff --git a/client/ios/App/App/PrivacyInfo.xcprivacy b/client/ios/App/App/PrivacyInfo.xcprivacy new file mode 100644 index 000000000..f1b6f6735 --- /dev/null +++ b/client/ios/App/App/PrivacyInfo.xcprivacy @@ -0,0 +1,44 @@ + + + + + + NSPrivacyAccessedAPITypes + + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryFileTimestamp + NSPrivacyAccessedAPITypeReasons + + C617.1 + + + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryUserDefaults + NSPrivacyAccessedAPITypeReasons + + CA92.1 + + + + + NSPrivacyTracking + + NSPrivacyTrackingDomains + + NSPrivacyCollectedDataTypes + + + diff --git a/client/ios/App/App/SceneDelegate.swift b/client/ios/App/App/SceneDelegate.swift new file mode 100644 index 000000000..5c55e16a0 --- /dev/null +++ b/client/ios/App/App/SceneDelegate.swift @@ -0,0 +1,24 @@ +import UIKit +import Capacitor + +class SceneDelegate: UIResponder, UIWindowSceneDelegate { + var window: UIWindow? + + func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { + guard let windowScene = scene as? UIWindowScene else { return } + + window = UIWindow(windowScene: windowScene) + window?.rootViewController = TrekBridgeViewController() + window?.makeKeyAndVisible() + + SceneDelegateProxy.shared.scene(scene, willConnectTo: session, options: connectionOptions) + } + + func scene(_ scene: UIScene, openURLContexts URLContexts: Set) { + SceneDelegateProxy.shared.scene(scene, openURLContexts: URLContexts) + } + + func scene(_ scene: UIScene, continue userActivity: NSUserActivity) { + SceneDelegateProxy.shared.scene(scene, continue: userActivity) + } +} diff --git a/client/ios/App/App/TrekBridgeViewController.swift b/client/ios/App/App/TrekBridgeViewController.swift new file mode 100644 index 000000000..9236553cb --- /dev/null +++ b/client/ios/App/App/TrekBridgeViewController.swift @@ -0,0 +1,44 @@ +import UIKit +import Capacitor + +/// Points the WebView at the TREK server the user picked instead of the bundled +/// address screen. The UI then comes from that server, in the version it runs, +/// on its own origin, so its session cookie and service calls work as they do +/// in Safari. +class TrekBridgeViewController: CAPBridgeViewController { + override func instanceDescriptor() -> InstanceDescriptor { + let descriptor = super.instanceDescriptor() + if let server = TrekServerStore.url { + // The trailing slash matters: Capacitor treats every URL that starts + // with this string as the app's own, and without it that would take + // in https://trek.example.com.attacker.test as well. + descriptor.serverURL = server.hasSuffix("/") ? server : server + "/" + } + return descriptor + } + + override func capacitorDidLoad() { + bridge?.registerPluginInstance(TrekShellPlugin()) + // The swipe from the left edge that goes back in every iOS app. It walks + // the SPA's history, the same entries Android's back button uses. + webView?.allowsBackForwardNavigationGestures = true + } +} + +/// The remembered server and the offline copy of its start page. +enum TrekServerStore { + private static let key = "TrekServerURL" + + static var url: String? { + get { UserDefaults.standard.string(forKey: key) } + set { + if let newValue { UserDefaults.standard.set(newValue, forKey: key) } else { UserDefaults.standard.removeObject(forKey: key) } + try? FileManager.default.removeItem(at: offlineCopyURL) + } + } + + static var offlineCopyURL: URL { + let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] + return support.appendingPathComponent("offline-start-page.html") + } +} diff --git a/client/ios/App/App/TrekShellPlugin.swift b/client/ios/App/App/TrekShellPlugin.swift new file mode 100644 index 000000000..0414b3598 --- /dev/null +++ b/client/ios/App/App/TrekShellPlugin.swift @@ -0,0 +1,142 @@ +import AuthenticationServices +import Capacitor +import UIKit +import WebKit + +/// The native half of client/src/native/trekShell.ts. +@objc(TrekShellPlugin) +public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPresentationContextProviding { + public let identifier = "TrekShellPlugin" + public let jsName = "TrekShell" + public let pluginMethods: [CAPPluginMethod] = [ + CAPPluginMethod(name: "getServer", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "setServer", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "resetServer", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "reload", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "authenticate", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "refreshOfflineCopy", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "openOfflineCopy", returnType: CAPPluginReturnPromise), + ] + + private var authSession: ASWebAuthenticationSession? + + @objc func getServer(_ call: CAPPluginCall) { + call.resolve(["url": TrekServerStore.url ?? NSNull()]) + } + + @objc func setServer(_ call: CAPPluginCall) { + guard let raw = call.getString("url"), let url = URL(string: raw), ["https", "http"].contains(url.scheme), url.host != nil else { + call.reject("A http(s) URL is required") + return + } + TrekServerStore.url = raw + call.resolve() + restartBridge() + } + + @objc func resetServer(_ call: CAPPluginCall) { + TrekServerStore.url = nil + call.resolve() + restartBridge() + } + + @objc func reload(_ call: CAPPluginCall) { + call.resolve() + restartBridge() + } + + /// A new bridge rather than a navigation: the server URL is part of the + /// bridge's configuration and decides which origin counts as the app. + private func restartBridge() { + DispatchQueue.main.async { [weak self] in + guard let window = self?.bridge?.viewController?.view.window else { return } + window.rootViewController = TrekBridgeViewController() + } + } + + // MARK: - Sign-in through the system browser + + @objc func authenticate(_ call: CAPPluginCall) { + guard let raw = call.getString("url"), let url = URL(string: raw), let scheme = call.getString("callbackScheme") else { + call.reject("url and callbackScheme are required") + return + } + DispatchQueue.main.async { [weak self] in + guard let self else { return } + let session = ASWebAuthenticationSession(url: url, callbackURLScheme: scheme) { [weak self] callbackURL, error in + self?.authSession = nil + if let callbackURL { + call.resolve(["url": callbackURL.absoluteString]) + } else if let authError = error as? ASWebAuthenticationSessionError, authError.code == .canceledLogin { + call.reject("Sign-in cancelled", "CANCELLED") + } else { + call.reject(error?.localizedDescription ?? "Sign-in failed") + } + } + // Shares Safari's cookies, so a running SSO session at the identity + // provider carries over and nobody types their password twice. + session.prefersEphemeralWebBrowserSession = false + session.presentationContextProvider = self + self.authSession = session + if !session.start() { + self.authSession = nil + call.reject("Could not open the browser") + } + } + } + + public func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { + bridge?.viewController?.view.window ?? ASPresentationAnchor() + } + + // MARK: - Offline start + + /// WKWebView runs no service worker for a domain that is not listed in the + /// app at build time, and a user's own server never is. So the app keeps + /// the server's start page itself, and the scripts it references stay in + /// WebKit's HTTP cache (the server marks them immutable). + @objc func refreshOfflineCopy(_ call: CAPPluginCall) { + guard let raw = TrekServerStore.url, let url = URL(string: raw) else { + call.resolve(["saved": false]) + return + } + var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 15) + request.setValue("text/html", forHTTPHeaderField: "Accept") + URLSession.shared.dataTask(with: request) { data, response, _ in + guard let data, let http = response as? HTTPURLResponse, http.statusCode == 200, + http.value(forHTTPHeaderField: "Content-Type")?.hasPrefix("text/html") == true, + TrekServerStore.url == raw else { + call.resolve(["saved": false]) + return + } + do { + let target = TrekServerStore.offlineCopyURL + try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true) + try data.write(to: target, options: .atomic) + call.resolve(["saved": true]) + } catch { + call.resolve(["saved": false]) + } + }.resume() + } + + @objc func openOfflineCopy(_ call: CAPPluginCall) { + // With the trailing slash, like the bridge's serverURL: Capacitor only + // keeps a navigation in the app when it starts with that exact string, + // and hands anything else to Safari. + guard let raw = TrekServerStore.url, let url = URL(string: raw.hasSuffix("/") ? raw : raw + "/"), + let html = try? Data(contentsOf: TrekServerStore.offlineCopyURL) else { + call.resolve(["opened": false]) + return + } + DispatchQueue.main.async { [weak self] in + guard let webView = self?.bridge?.webView else { + call.resolve(["opened": false]) + return + } + let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: ["Content-Type": "text/html; charset=utf-8"])! + call.resolve(["opened": true]) + webView.loadSimulatedRequest(URLRequest(url: url), response: response, responseData: html) + } + } +} diff --git a/client/ios/App/CapApp-SPM/.gitignore b/client/ios/App/CapApp-SPM/.gitignore new file mode 100644 index 000000000..3b2981208 --- /dev/null +++ b/client/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/client/ios/App/CapApp-SPM/Package.swift b/client/ios/App/CapApp-SPM/Package.swift new file mode 100644 index 000000000..ac9dff196 --- /dev/null +++ b/client/ios/App/CapApp-SPM/Package.swift @@ -0,0 +1,39 @@ +// 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.5.2"), + .package(name: "CapacitorApp", path: "../../../../node_modules/@capacitor/app"), + .package(name: "CapacitorFilesystem", path: "../../../../node_modules/@capacitor/filesystem"), + .package(name: "CapacitorHaptics", path: "../../../../node_modules/@capacitor/haptics"), + .package(name: "CapacitorKeyboard", path: "../../../../node_modules/@capacitor/keyboard"), + .package(name: "CapacitorShare", path: "../../../../node_modules/@capacitor/share"), + .package(name: "CapacitorSplashScreen", path: "../../../../node_modules/@capacitor/splash-screen"), + .package(name: "CapacitorStatusBar", path: "../../../../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: "CapacitorFilesystem", package: "CapacitorFilesystem"), + .product(name: "CapacitorHaptics", package: "CapacitorHaptics"), + .product(name: "CapacitorKeyboard", package: "CapacitorKeyboard"), + .product(name: "CapacitorShare", package: "CapacitorShare"), + .product(name: "CapacitorSplashScreen", package: "CapacitorSplashScreen"), + .product(name: "CapacitorStatusBar", package: "CapacitorStatusBar") + ] + ) + ] +) diff --git a/client/ios/App/CapApp-SPM/README.md b/client/ios/App/CapApp-SPM/README.md new file mode 100644 index 000000000..03964db90 --- /dev/null +++ b/client/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/client/ios/App/CapApp-SPM/Sources/CapApp-SPM/CapApp-SPM.swift b/client/ios/App/CapApp-SPM/Sources/CapApp-SPM/CapApp-SPM.swift new file mode 100644 index 000000000..945afec8c --- /dev/null +++ b/client/ios/App/CapApp-SPM/Sources/CapApp-SPM/CapApp-SPM.swift @@ -0,0 +1 @@ +public let isCapacitorApp = true diff --git a/client/ios/ExportOptions.plist b/client/ios/ExportOptions.plist new file mode 100644 index 000000000..5dc50541e --- /dev/null +++ b/client/ios/ExportOptions.plist @@ -0,0 +1,20 @@ + + + + + + method + app-store-connect + destination + upload + signingStyle + automatic + manageAppVersionAndBuildNumber + + uploadSymbols + + + diff --git a/client/ios/debug.xcconfig b/client/ios/debug.xcconfig new file mode 100644 index 000000000..53ce18dea --- /dev/null +++ b/client/ios/debug.xcconfig @@ -0,0 +1 @@ +CAPACITOR_DEBUG = true diff --git a/client/native-shell/i18n.ts b/client/native-shell/i18n.ts new file mode 100644 index 000000000..43e9df949 --- /dev/null +++ b/client/native-shell/i18n.ts @@ -0,0 +1,34 @@ +import { SUPPORTED_LANGUAGE_CODES } from '@trek/shared/i18n' +import type { TranslationStrings } from '@trek/shared/i18n' + +// Only the native strings of every locale, not the whole UI: this page ships +// inside the app binary and shows three screens. +const bundles = import.meta.glob('../../shared/src/i18n/*/native.ts', { eager: true, import: 'default' }) + +function bundleFor(code: string): TranslationStrings | undefined { + return bundles[`../../shared/src/i18n/${code}/native.ts`] +} + +export function pickLocale(preferred: readonly string[]): string { + for (const lang of preferred) { + const lower = lang.toLowerCase() + if (lower === 'pt-br') return 'br' + if (lower.startsWith('zh-tw') || lower.startsWith('zh-hk') || lower.startsWith('zh-hant')) return 'zh-TW' + if (lower.startsWith('el')) return 'gr' + const prefix = lower.split('-')[0] + const match = SUPPORTED_LANGUAGE_CODES.find((code) => code.toLowerCase() === lower || code === prefix) + if (match) return match + } + return 'en' +} + +export function translator(code: string) { + const strings = bundleFor(code) ?? {} + const fallback = bundleFor('en') ?? {} + return (key: string, params: Record = {}): string => { + const template = strings[key] ?? fallback[key] ?? key + return typeof template === 'string' + ? template.replace(/\{(\w+)\}/g, (whole, name: string) => params[name] ?? whole) + : key + } +} diff --git a/client/native-shell/index.html b/client/native-shell/index.html new file mode 100644 index 000000000..ba3f6913d --- /dev/null +++ b/client/native-shell/index.html @@ -0,0 +1,14 @@ + + + + + + + + TREK + + +
+ + + diff --git a/client/native-shell/main.ts b/client/native-shell/main.ts new file mode 100644 index 000000000..fd8cf0413 --- /dev/null +++ b/client/native-shell/main.ts @@ -0,0 +1,798 @@ +import { CapacitorHttp } from '@capacitor/core'; +import { Haptics, ImpactStyle, NotificationType } from '@capacitor/haptics'; +import { SplashScreen } from '@capacitor/splash-screen'; +import { StatusBar, Style } from '@capacitor/status-bar'; +import logoUrl from '../public/icons/icon-white.svg'; +import { getIapClient, productIdFor, type Purchase } from '../src/native/iap'; +import { CLOUD_URL, PRIVACY_URL, SERVER_DOCS_URL } from '../src/native/links'; +import { probeDemo, probeServer, type ProbeFailure, type ProbeGet } from '../src/native/serverAddress'; +import { TrekShell } from '../src/native/trekShell'; +import { pickLocale, translator } from './i18n'; +import './shell.css'; + +/** + * The only page the app ships itself. It welcomes someone on first start, asks + * for the TREK server they open in their browser, offers TREK Cloud to someone + * without one, and stands in when a remembered server cannot be reached. + * Everything past it is the UI that server delivers. + */ + +const locale = pickLocale(navigator.languages?.length ? navigator.languages : [navigator.language]); +const t = translator(locale); +document.documentElement.lang = locale; +document.documentElement.dir = locale === 'ar' ? 'rtl' : 'ltr'; + +const root = document.getElementById('shell')!; +const PROBE_TIMEOUT_MS = 8000; + +const iap = getIapClient(); +/** Whether this build can take a payment in-app; decided once at start. Until then, and in a store build without the purchase plugin, the plan picker finishes on the web. */ +let iapAvailable = false; + +/** The subdomain suffix a cloud instance sits on, from the cloud address: `liketrek.com` → `.liketrek.com`. */ +function cloudSuffix(): string { + try { + return `.${new URL(CLOUD_URL).host}`; + } catch { + return '.liketrek.com'; + } +} + +// Native HTTP rather than fetch: the probe goes to a server of the user's +// choosing, which has no reason to answer this page's origin with CORS. +const get: ProbeGet = async (url) => { + const response = await CapacitorHttp.get({ url, connectTimeout: PROBE_TIMEOUT_MS, readTimeout: PROBE_TIMEOUT_MS }); + return { status: response.status, data: response.data, url: response.url }; +}; + +function failureMessage(reason: ProbeFailure): string { + switch (reason) { + case 'invalid': + return t('native.connect.errorInvalid'); + case 'unreachable': + return t('native.connect.errorUnreachable'); + case 'notTrek': + return t('native.connect.errorNotTrek'); + case 'tooOld': + return t('native.connect.errorTooOld'); + } +} + +// ── Tiny DOM + haptics helpers ────────────────────────────────────────────── +function el( + tag: K, + props: Partial & { dataset?: Record } = {}, + ...children: (Node | string)[] +): HTMLElementTagNameMap[K] { + const { dataset, ...rest } = props; + const node = document.createElement(tag); + Object.assign(node, rest); + if (dataset) for (const [k, v] of Object.entries(dataset)) node.dataset[k] = v; + node.append(...children.filter((c) => c !== null && c !== undefined)); + return node; +} + +function icon(path: string, size = 22, className?: string): SVGSVGElement { + const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + svg.setAttribute('viewBox', '0 0 24 24'); + svg.setAttribute('width', String(size)); + svg.setAttribute('height', String(size)); + svg.setAttribute('fill', 'none'); + svg.setAttribute('stroke', 'currentColor'); + svg.setAttribute('stroke-width', '2'); + svg.setAttribute('stroke-linecap', 'round'); + svg.setAttribute('stroke-linejoin', 'round'); + if (className) svg.setAttribute('class', className); + const p = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + p.setAttribute('d', path); + svg.appendChild(p); + return svg; +} +const I = { + chevron: 'M9 18l6-6-6-6', + cloud: 'M17.5 19a4.5 4.5 0 0 0 .5-9 6 6 0 0 0-11.6-1.6A4 4 0 0 0 6 19z', + globe: 'M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20M2 12h20M12 2a15 15 0 0 1 0 20 15 15 0 0 1 0-20', + bolt: 'M13 2 4 14h7l-1 8 9-12h-7z', + shield: 'M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10', + check: 'M20 6 9 17l-5-5', +}; + +async function tap(style: ImpactStyle = ImpactStyle.Light): Promise { + try { + await Haptics.impact({ style }); + } catch { + /* web / unavailable */ + } +} +async function notify(type: NotificationType): Promise { + try { + await Haptics.notification({ type }); + } catch { + /* web / unavailable */ + } +} + +// ── Screen transitions ────────────────────────────────────────────────────── +let current: HTMLElement | null = null; + +function show(screen: HTMLElement, opts: { back?: boolean } = {}): void { + screen.classList.add('screen', 'screen-enter'); + if (opts.back) screen.classList.add('screen-back'); + const previous = current; + if (previous) { + previous.classList.remove('screen-enter'); + previous.classList.add('screen-leave'); + if (opts.back) previous.classList.add('screen-back'); + previous.addEventListener('animationend', () => previous.remove(), { once: true }); + setTimeout(() => previous.remove(), 400); + } + root.append(screen); + current = screen; +} + +function externalLink(text: string, href: string): HTMLAnchorElement { + return el('a', { href, target: '_blank', rel: 'noopener noreferrer' }, text); +} +function footLinks(...extra: Node[]): HTMLElement { + return el('div', { className: 'foot-links' }, ...extra, externalLink(t('native.privacy'), PRIVACY_URL)); +} +function topbar(onBack: () => void): HTMLElement { + const back = el('button', { type: 'button', className: 'back' }, icon('M15 18l-6-6 6-6', 18), t('native.back')); + back.addEventListener('click', () => { + void tap(); + onBack(); + }); + return el('div', { className: 'topbar' }, back); +} + +// ── Welcome ───────────────────────────────────────────────────────────────── +function showWelcome(opts: { back?: boolean } = {}): void { + const hero = el('img', { src: logoUrl, alt: '', className: 'hero-mark' }); + + const connect = el( + 'button', + { type: 'button', className: 'btn' }, + el( + 'span', + { className: 'btn-row' }, + el('b', {}, t('native.welcome.connect')), + el('small', {}, t('native.welcome.connectSub')) + ), + icon(I.chevron, 20, 'chev') + ); + connect.addEventListener('click', () => { + void tap(); + showConnect(); + }); + + const cloud = el( + 'button', + { type: 'button', className: 'btn btn-ghost' }, + el( + 'span', + { className: 'btn-row' }, + el('b', {}, t('native.welcome.getCloud')), + el('small', {}, t('native.welcome.getCloudSub')) + ), + icon(I.chevron, 20, 'chev') + ); + cloud.addEventListener('click', () => { + void tap(); + showCloud(); + }); + + const demo = el('button', { type: 'button', className: 'linkbtn' }, t('native.connect.tryDemo')); + demo.addEventListener('click', () => runDemo(demo)); + + show( + el( + 'div', + {}, + hero, + el('h1', { className: 'title' }, t('native.welcome.headline')), + el('p', { className: 'sub' }, t('native.welcome.sub')), + connect, + cloud, + demo, + footLinks(externalLink(t('native.connect.whatIsServer'), SERVER_DOCS_URL)) + ), + opts + ); +} + +// ── Connect (address) ─────────────────────────────────────────────────────── +function showConnect(prefill = '', opts: { back?: boolean } = {}): void { + const input = el('input', { + type: 'url', + placeholder: t('native.connect.placeholder'), + value: prefill, + autocapitalize: 'off', + spellcheck: false, + }); + input.setAttribute('inputmode', 'url'); + input.setAttribute('autocomplete', 'url'); + // The on-screen keyboard's return key submits the address; it reads "Go", not a newline. + input.setAttribute('enterkeyhint', 'go'); + input.setAttribute('aria-label', t('native.connect.title')); + const field = el('div', { className: 'field' }, input); + + const label = el('span', {}, t('native.connect.submit')); + const submit = el('button', { type: 'submit', className: 'btn' }, label); + const error = el('p', { className: 'error', role: 'alert' }); + const form = el('form', { className: 'form', noValidate: true }, field, submit, error); + + const fail = (reason: ProbeFailure): void => { + void notify(NotificationType.Error); + field.classList.add('bad'); + setTimeout(() => field.classList.remove('bad'), 350); + error.textContent = failureMessage(reason); + input.disabled = false; + submit.disabled = false; + label.textContent = t('native.connect.submit'); + submit.replaceChildren(label); + input.focus(); + }; + + form.addEventListener('submit', async (event) => { + event.preventDefault(); + void tap(ImpactStyle.Medium); + error.textContent = ''; + input.disabled = true; + submit.disabled = true; + submit.replaceChildren(el('span', { className: 'spinner' }), t('native.connect.checking')); + const result = await probeServer(input.value, get); + if (result.ok) { + await connected(result.url); + return; + } + fail(result.reason); + }); + + const demo = el('button', { type: 'button', className: 'linkbtn' }, t('native.connect.tryDemo')); + demo.addEventListener('click', () => runDemo(demo, error)); + + show( + el( + 'div', + {}, + topbar(() => showWelcome({ back: true })), + el('h1', { className: 'title-sm' }, t('native.connect.title')), + el('p', { className: 'sub' }, t('native.connect.hint')), + form, + demo, + footLinks(externalLink(t('native.connect.whatIsServer'), SERVER_DOCS_URL)) + ), + opts + ); + requestAnimationFrame(() => input.focus()); +} + +// ── Get TREK Cloud ────────────────────────────────────────────────────────── +function feature(path: string, text: string): HTMLElement { + return el( + 'div', + { className: 'feature' }, + el('span', { className: 'ic' }, icon(path, 18)), + el('span', { className: 'tx' }, text) + ); +} + +function showCloud(opts: { back?: boolean } = {}): void { + const cta = el('button', { type: 'button', className: 'btn' }, t('native.cloud.cta'), icon(I.chevron, 20, 'chev')); + cta.addEventListener('click', () => { + void tap(); + showPlans(); + }); + + const have = el('button', { type: 'button', className: 'linkbtn' }, t('native.cloud.haveServer')); + have.addEventListener('click', () => { + void tap(); + showConnect(); + }); + + show( + el( + 'div', + {}, + topbar(() => showWelcome({ back: true })), + el('h1', { className: 'title-sm' }, t('native.cloud.title')), + el('p', { className: 'sub' }, t('native.cloud.sub')), + el( + 'div', + { className: 'features' }, + feature(I.globe, t('native.cloud.f1')), + feature(I.bolt, t('native.cloud.f2')), + feature(I.shield, t('native.cloud.f3')) + ), + cta, + have, + footLinks() + ), + opts + ); +} + +// ── Choose a plan (TREK Cloud) ────────────────────────────────────────────── +interface CloudPlan { + id: string; + name: string; + monthlyCents: number; + yearlyCents: number; + aiDocuments: number; + storageGb: number; +} + +function money(cents: number): string { + return new Intl.NumberFormat(locale, { style: 'currency', currency: 'EUR' }).format(cents / 100); +} + +async function fetchPlans(): Promise { + try { + const res = await get(`${CLOUD_URL}/api/plans`); + const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data; + const plans = (data as { plans?: CloudPlan[] })?.plans; + return Array.isArray(plans) && plans.length ? plans : null; + } catch { + return null; + } +} + +function subscribe(plan: CloudPlan, interval: 'month' | 'year'): void { + void tap(ImpactStyle.Medium); + // In-app purchase when this build can take one; otherwise finish on the web, so + // nothing half-wired faces a customer until the store products exist. + if (iapAvailable) { + showClaim(plan, interval); + } else { + window.open(`${CLOUD_URL}/order?plan=${encodeURIComponent(plan.id)}`, '_blank', 'noopener'); + } +} + +function planCard(plan: CloudPlan, interval: 'month' | 'year', featured: boolean): HTMLElement { + const price = interval === 'year' ? plan.yearlyCents : plan.monthlyCents; + const per = interval === 'year' ? t('native.plans.perYear') : t('native.plans.perMonth'); + const feat = (text: string) => el('span', {}, icon(I.check, 16), text); + const sub = el('button', { type: 'button', className: 'btn' }, t('native.plans.subscribe')); + sub.addEventListener('click', () => subscribe(plan, interval)); + return el( + 'div', + { className: featured ? 'plan featured' : 'plan' }, + el( + 'div', + { className: 'plan-top' }, + el('span', { className: 'plan-name' }, plan.name), + el('span', { className: 'plan-price' }, money(price), el('small', {}, per)) + ), + el( + 'div', + { className: 'plan-feats' }, + feat(t('native.plans.unlimited')), + feat(t('native.plans.storage', { n: String(plan.storageGb) })), + feat(plan.aiDocuments > 0 ? t('native.plans.aiDocs', { n: String(plan.aiDocuments) }) : t('native.plans.noAi')) + ), + sub + ); +} + +function showPlans(opts: { back?: boolean } = {}): void { + let interval: 'month' | 'year' = 'month'; + let plans: CloudPlan[] | null = null; + + const content = el('div', { className: 'loading' }, el('span', { className: 'spinner' })); + + const monthBtn = el('button', { type: 'button' }, t('native.plans.monthly')); + const yearBtn = el( + 'button', + { type: 'button' }, + t('native.plans.yearly'), + el('span', { className: 'save' }, t('native.plans.save')) + ); + const seg = el('div', { className: 'segmented' }, monthBtn, yearBtn); + + const paintSeg = () => { + monthBtn.setAttribute('aria-pressed', String(interval === 'month')); + yearBtn.setAttribute('aria-pressed', String(interval === 'year')); + }; + const renderList = () => { + const list = plans; + if (!list) return; + content.className = 'plans'; + content.replaceChildren(...list.map((p, i) => planCard(p, interval, i === list.length - 1))); + }; + const choose = (next: 'month' | 'year') => { + if (interval === next) return; + void tap(); + interval = next; + paintSeg(); + renderList(); + }; + monthBtn.addEventListener('click', () => choose('month')); + yearBtn.addEventListener('click', () => choose('year')); + paintSeg(); + + const load = async () => { + plans = await fetchPlans(); + if (plans) { + renderList(); + return; + } + content.className = ''; + const retry = el('button', { type: 'button', className: 'btn btn-ghost' }, t('native.plans.retry')); + retry.addEventListener('click', () => { + void tap(); + content.className = 'loading'; + content.replaceChildren(el('span', { className: 'spinner' })); + void load(); + }); + content.replaceChildren(el('p', { className: 'error' }, t('native.plans.loadError')), retry); + }; + + show( + el( + 'div', + {}, + topbar(() => showCloud({ back: true })), + el('h1', { className: 'title-sm' }, t('native.plans.title')), + el('p', { className: 'sub' }, t('native.plans.sub')), + seg, + content, + el('p', { className: 'note' }, t('native.plans.soon')) + ), + opts + ); + void load(); +} + +// ── Claim a TREK Cloud instance (choose address, buy, provision) ──────────── +type SlugStatus = 'available' | 'taken' | 'invalid' | 'reserved' | 'error'; + +async function slugStatus(slug: string): Promise { + try { + const res = await get(`${CLOUD_URL}/api/slug/check?slug=${encodeURIComponent(slug)}`); + const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data; + const status = (data as { status?: string })?.status; + if (status === 'available' || status === 'taken' || status === 'invalid' || status === 'reserved') return status; + return 'error'; + } catch { + return 'error'; + } +} + +interface RedeemResult { + ok: boolean; + /** Set when ok: the address the app loads. */ + instanceUrl?: string; + /** Set when not ok: a stable refusal code. */ + code?: string; +} +async function redeemPurchase(slug: string, email: string, purchase: Purchase): Promise { + try { + const res = await CapacitorHttp.post({ + url: `${CLOUD_URL}/api/iap/redeem`, + headers: { 'content-type': 'application/json' }, + connectTimeout: PROBE_TIMEOUT_MS, + readTimeout: PROBE_TIMEOUT_MS, + data: { platform: purchase.platform, productId: purchase.productId, receipt: purchase.receipt, slug, email }, + }); + const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data; + const body = (data ?? {}) as { instanceUrl?: string; code?: string }; + if ((res.status === 200 || res.status === 201) && typeof body.instanceUrl === 'string') { + return { ok: true, instanceUrl: body.instanceUrl }; + } + return { ok: false, code: body.code ?? 'redeem-failed' }; + } catch { + return { ok: false, code: 'redeem-failed' }; + } +} + +function showClaim(plan: CloudPlan, interval: 'month' | 'year', opts: { back?: boolean } = {}): void { + const price = interval === 'year' ? plan.yearlyCents : plan.monthlyCents; + + const slugInput = el('input', { + type: 'text', + className: 'slug-input', + autocapitalize: 'off', + spellcheck: false, + value: '', + }); + slugInput.setAttribute('inputmode', 'url'); + slugInput.setAttribute('autocomplete', 'off'); + slugInput.setAttribute('maxlength', '40'); + slugInput.setAttribute('aria-label', t('native.claim.addressLabel')); + const slugField = el( + 'div', + { className: 'field slug-field' }, + slugInput, + el('span', { className: 'slug-suffix' }, cloudSuffix()) + ); + const slugNote = el('p', { className: 'hint' }); + + const emailInput = el('input', { type: 'email', value: '', autocapitalize: 'off', spellcheck: false }); + emailInput.setAttribute('inputmode', 'email'); + emailInput.setAttribute('autocomplete', 'email'); + emailInput.setAttribute('enterkeyhint', 'go'); + emailInput.setAttribute('aria-label', t('native.claim.emailLabel')); + const emailField = el('div', { className: 'field' }, emailInput); + + const submit = el( + 'button', + { type: 'submit', className: 'btn' }, + t('native.claim.subscribe', { price: money(price) }) + ); + const error = el('p', { className: 'error', role: 'alert' }); + const form = el( + 'form', + { className: 'form', noValidate: true }, + slugField, + slugNote, + emailField, + el('p', { className: 'hint' }, t('native.claim.emailHint')), + submit, + error + ); + + let status: SlugStatus | null = null; + let timer: ReturnType | undefined; + const noteFor: Partial> = { + available: t('native.claim.free'), + taken: t('native.claim.taken'), + invalid: t('native.claim.invalid'), + reserved: t('native.claim.reserved'), + }; + slugInput.addEventListener('input', () => { + clearTimeout(timer); + status = null; + slugNote.textContent = ''; + slugNote.className = 'hint'; + slugField.classList.remove('bad'); + const value = slugInput.value.trim().toLowerCase(); + if (value.length < 3) return; + timer = setTimeout(async () => { + const result = await slugStatus(value); + if (slugInput.value.trim().toLowerCase() !== value) return; + status = result; + slugNote.textContent = noteFor[result] ?? ''; + slugNote.className = `hint ${result === 'available' ? 'ok' : result === 'error' ? '' : 'bad'}`; + }, 350); + }); + + const shake = (field: HTMLElement): void => { + void notify(NotificationType.Error); + field.classList.add('bad'); + setTimeout(() => field.classList.remove('bad'), 350); + }; + + form.addEventListener('submit', async (event) => { + event.preventDefault(); + error.textContent = ''; + const slug = slugInput.value.trim().toLowerCase(); + const email = emailInput.value.trim(); + if (slug.length < 3 || status === 'taken' || status === 'invalid' || status === 'reserved') { + shake(slugField); + slugInput.focus(); + return; + } + if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { + shake(emailField); + emailInput.focus(); + return; + } + + void tap(ImpactStyle.Medium); + const lock = (on: boolean) => { + slugInput.disabled = on; + emailInput.disabled = on; + submit.disabled = on; + }; + lock(true); + submit.replaceChildren(el('span', { className: 'spinner' }), t('native.connect.checking')); + const restore = () => { + lock(false); + submit.replaceChildren(t('native.claim.subscribe', { price: money(price) })); + }; + + const outcome = await iap.purchase(productIdFor(plan.id, interval)); + if (outcome.kind === 'cancelled') { + restore(); + error.textContent = t('native.claim.cancelled'); + return; + } + if (outcome.kind === 'failed') { + void notify(NotificationType.Error); + restore(); + error.textContent = t('native.claim.failed'); + return; + } + + const redeemed = await redeemPurchase(slug, email, outcome.purchase); + if (redeemed.ok && redeemed.instanceUrl) { + showProvisioning(redeemed.instanceUrl); + return; + } + void notify(NotificationType.Error); + restore(); + if (redeemed.code === 'slug-taken') { + shake(slugField); + slugNote.textContent = t('native.claim.taken'); + slugNote.className = 'hint bad'; + } else { + error.textContent = t('native.claim.redeemFailed'); + } + }); + + show( + el( + 'div', + {}, + topbar(() => showPlans({ back: true })), + el('h1', { className: 'title-sm' }, t('native.claim.title')), + el('p', { className: 'sub' }, t('native.claim.sub')), + form + ), + opts + ); + requestAnimationFrame(() => slugInput.focus()); +} + +/** The build runs on the server; the app waits on the new address and loads it the moment it answers. */ +function showProvisioning(instanceUrl: string): void { + const host = (() => { + try { + return new URL(instanceUrl).host; + } catch { + return instanceUrl; + } + })(); + + const spinner = el('div', { className: 'provision-mark' }, el('span', { className: 'spinner' })); + show( + el( + 'div', + { className: 'screen-center' }, + spinner, + el('h1', { className: 'title-sm' }, t('native.provisioning.title')), + el('p', { className: 'sub' }, t('native.provisioning.sub', { host })) + ) + ); + + const deadline = Date.now() + 180_000; + const poll = async (): Promise => { + const result = await probeServer(instanceUrl, get); + if (result.ok) { + await connected(result.url); + return; + } + if (Date.now() > deadline) { + showProvisioningSlow(instanceUrl); + return; + } + setTimeout(() => void poll(), 4000); + }; + setTimeout(() => void poll(), 3000); +} + +function showProvisioningSlow(instanceUrl: string): void { + void notify(NotificationType.Warning); + const retry = el('button', { type: 'button', className: 'btn' }, t('native.provisioning.retry')); + retry.addEventListener('click', () => { + void tap(); + showProvisioning(instanceUrl); + }); + show( + el( + 'div', + { className: 'screen-center' }, + el('h1', { className: 'title-sm' }, t('native.provisioning.failedTitle')), + el('p', { className: 'sub' }, t('native.provisioning.failedSub')), + retry + ) + ); +} + +// ── Shared actions ────────────────────────────────────────────────────────── +async function runDemo(button: HTMLButtonElement, error?: HTMLElement): Promise { + void tap(); + if (error) error.textContent = ''; + button.disabled = true; + const result = await probeDemo(get); + if (result.ok) { + await connected(result.url); + return; + } + button.disabled = false; + if (error) { + error.textContent = failureMessage(result.reason); + } else { + void notify(NotificationType.Error); + } +} + +/** The tick, then the server takes over. A beat so the success registers. */ +async function connected(url: string): Promise { + void notify(NotificationType.Success); + const host = (() => { + try { + return new URL(url).host; + } catch { + return url; + } + })(); + const tick = el('div', { className: 'tick' }); + const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + svg.setAttribute('viewBox', '0 0 24 24'); + svg.setAttribute('fill', 'none'); + svg.setAttribute('stroke', 'currentColor'); + svg.setAttribute('stroke-width', '2.5'); + svg.setAttribute('stroke-linecap', 'round'); + svg.setAttribute('stroke-linejoin', 'round'); + const p = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + p.setAttribute('d', I.check); + svg.appendChild(p); + tick.appendChild(svg); + show( + el('div', { className: 'success' }, tick, el('h1', { className: 'title-sm' }, t('native.connecting', { host }))) + ); + await new Promise((r) => setTimeout(r, 700)); + await TrekShell.setServer({ url }); +} + +function showUnreachable(server: string): void { + const retry = el('button', { type: 'button', className: 'btn' }, t('native.offline.retry')); + retry.addEventListener('click', () => { + void tap(); + retry.disabled = true; + void TrekShell.reload(); + }); + const change = el('button', { type: 'button', className: 'linkbtn' }, t('native.changeServer')); + change.addEventListener('click', () => { + void tap(); + void TrekShell.resetServer(); + }); + show( + el( + 'div', + {}, + el('img', { src: logoUrl, alt: '', className: 'shell-logo' }), + el('h1', { className: 'title-sm' }, t('native.offline.title')), + el('p', { className: 'sub' }, t('native.offline.hint', { server: new URL(server).host })), + retry, + change, + footLinks() + ) + ); +} + +// ── Start ─────────────────────────────────────────────────────────────────── +/** + * The address screen is always on the near-black surface, so the status bar must + * draw its clock and icons in light. The server's UI sets its own style once it + * loads (native/nativeApp.ts); this is only for the screen the app ships. Fails + * quietly where there is no status bar (web, the simulator without the plugin). + */ +async function paintStatusBar(): Promise { + try { + await StatusBar.setStyle({ style: Style.Dark }); + } catch { + /* web / unavailable: no native status bar to style */ + } +} + +async function start(): Promise { + void paintStatusBar(); + iap.isAvailable().then((ok) => { + iapAvailable = ok; + }); + const { url } = await TrekShell.getServer(); + if (!url) { + showWelcome(); + } else { + // Only reached when loading the server failed. On iOS the stored copy of + // its start page brings the offline-capable UI up anyway. + const { opened } = await TrekShell.openOfflineCopy(); + if (opened) return; + showUnreachable(url); + } + await SplashScreen.hide(); +} + +void start(); diff --git a/client/native-shell/shell.css b/client/native-shell/shell.css new file mode 100644 index 000000000..2946ffd45 --- /dev/null +++ b/client/native-shell/shell.css @@ -0,0 +1,712 @@ +/* + * The address screen the app ships. Dark first, mirroring the app's neutral + * default scheme (client/src/index.css), so it shares the launch screen's + * background and never flashes. Everything past this screen is the UI the + * chosen server delivers. + */ +:root { + --bg: #09090b; + --bg-2: #101013; + --surface: #18181b; + --surface-2: #1f1f23; + --edge: #27272a; + --edge-strong: #3f3f46; + --ink: #fafafa; + --muted: #a1a1aa; + --faint: #71717a; + --accent: #fafafa; + --accent-ink: #09090b; + --danger: #f87171; + --ok: #4ade80; + --radius: 16px; + --ease: cubic-bezier(0.22, 1, 0.36, 1); + --ease-in: cubic-bezier(0.4, 0, 1, 1); + color-scheme: dark; +} + +@media (prefers-color-scheme: light) { + :root { + --bg: #ffffff; + --bg-2: #fafafa; + --surface: #f4f4f5; + --surface-2: #ececef; + --edge: #e4e4e7; + --edge-strong: #d4d4d8; + --ink: #111827; + --muted: #52525b; + --faint: #9ca3af; + --accent: #111827; + --accent-ink: #ffffff; + --danger: #dc2626; + --ok: #16a34a; + color-scheme: light; + } + .shell-logo, + .mark { + filter: none; + } +} + +* { + box-sizing: border-box; + -webkit-tap-highlight-color: transparent; +} + +html, +body { + margin: 0; + min-height: 100%; + background: var(--bg); + color: var(--ink); + font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Text', 'Segoe UI', Roboto, system-ui, sans-serif; + -webkit-text-size-adjust: 100%; + -webkit-font-smoothing: antialiased; + text-rendering: optimizeLegibility; + user-select: none; + -webkit-user-select: none; +} + +/* An ambient glow behind the content, so the flat dark gains a little depth. */ +body::before { + content: ''; + position: fixed; + inset: 0; + background: + radial-gradient(60% 50% at 50% -5%, color-mix(in srgb, var(--ink) 7%, transparent), transparent 70%), + radial-gradient(50% 40% at 50% 110%, color-mix(in srgb, var(--ink) 4%, transparent), transparent 70%); + pointer-events: none; + z-index: 0; +} + +.shell { + position: relative; + z-index: 1; + min-height: 100vh; + min-height: 100dvh; + display: flex; + flex-direction: column; + justify-content: center; + max-width: 440px; + margin: 0 auto; + padding: calc(env(safe-area-inset-top) + 28px) 24px calc(env(safe-area-inset-bottom) + 24px); + overflow: hidden; +} + +/* ── Screen transitions ──────────────────────────────────────────────────── */ +.screen { + display: flex; + flex-direction: column; + gap: 14px; +} +.screen-enter { + animation: screenIn 0.5s var(--ease) both; +} +.screen-leave { + animation: screenOut 0.28s var(--ease-in) both; + position: absolute; + inset: calc(env(safe-area-inset-top) + 28px) 24px calc(env(safe-area-inset-bottom) + 24px); +} +.screen-back.screen-enter { + animation-name: screenInBack; +} +.screen-back.screen-leave { + animation-name: screenOutBack; +} +@keyframes screenIn { + from { + opacity: 0; + transform: translateX(26px); + } + to { + opacity: 1; + transform: none; + } +} +@keyframes screenOut { + to { + opacity: 0; + transform: translateX(-22px); + } +} +@keyframes screenInBack { + from { + opacity: 0; + transform: translateX(-26px); + } + to { + opacity: 1; + transform: none; + } +} +@keyframes screenOutBack { + to { + opacity: 0; + transform: translateX(22px); + } +} + +/* Children stagger in, so a screen assembles rather than snaps. */ +.screen-enter > * { + animation: riseIn 0.55s var(--ease) both; +} +.screen-enter > *:nth-child(1) { + animation-delay: 0.02s; +} +.screen-enter > *:nth-child(2) { + animation-delay: 0.07s; +} +.screen-enter > *:nth-child(3) { + animation-delay: 0.12s; +} +.screen-enter > *:nth-child(4) { + animation-delay: 0.17s; +} +.screen-enter > *:nth-child(5) { + animation-delay: 0.22s; +} +.screen-enter > *:nth-child(6) { + animation-delay: 0.27s; +} +@keyframes riseIn { + from { + opacity: 0; + transform: translateY(12px); + } + to { + opacity: 1; + transform: none; + } +} + +/* ── Brand ───────────────────────────────────────────────────────────────── */ +.brand { + display: inline-flex; + align-items: center; + gap: 11px; + margin-bottom: 6px; +} +.brand .mark { + width: 40px; + height: 40px; +} +.brand .wordmark { + font-weight: 700; + font-size: 1.5rem; + letter-spacing: -0.01em; +} +.brand .tag { + font-style: italic; + font-weight: 600; + font-size: 0.9rem; + color: var(--accent-ink); + background: var(--accent); + border-radius: 999px; + padding: 2px 10px; + line-height: 1.3; +} + +.shell-logo { + width: 52px; + height: 52px; + margin-bottom: 4px; +} + +/* The big hero mark on the welcome screen, with a gentle breathing float. */ +.hero-mark { + width: 76px; + height: 76px; + margin-bottom: 18px; + animation: floaty 6s ease-in-out infinite; + filter: drop-shadow(0 10px 30px color-mix(in srgb, var(--ink) 18%, transparent)); +} +@keyframes floaty { + 0%, + 100% { + transform: translateY(0); + } + 50% { + transform: translateY(-6px); + } +} + +/* ── Type ────────────────────────────────────────────────────────────────── */ +.title { + font-size: 1.9rem; + line-height: 1.12; + font-weight: 700; + letter-spacing: -0.02em; + margin: 0; +} +.title-sm { + font-size: 1.45rem; + line-height: 1.2; + font-weight: 700; + letter-spacing: -0.015em; + margin: 0; +} +.sub { + color: var(--muted); + margin: 0; + line-height: 1.55; + font-size: 1.02rem; + overflow-wrap: anywhere; +} + +/* ── Buttons ─────────────────────────────────────────────────────────────── */ +.btn { + font: inherit; + font-weight: 600; + font-size: 1.02rem; + padding: 16px 18px; + border: 1px solid transparent; + border-radius: var(--radius); + background: var(--accent); + color: var(--accent-ink); + cursor: pointer; + transition: + transform 0.14s var(--ease), + opacity 0.2s, + background 0.2s, + border-color 0.2s; + display: inline-flex; + align-items: center; + justify-content: center; + gap: 10px; + min-height: 54px; +} +.btn:active { + transform: scale(0.975); +} +.btn:disabled { + opacity: 0.55; +} +.btn-ghost { + background: var(--surface); + color: var(--ink); + border-color: var(--edge); +} +.btn-ghost:active { + background: var(--surface-2); +} +.btn-row { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 2px; +} +.btn-row b { + font-weight: 650; +} +.btn-row small { + font-weight: 500; + font-size: 0.86rem; + opacity: 0.7; +} +.btn .chev { + margin-left: auto; + opacity: 0.5; +} + +.linkbtn { + font: inherit; + font-size: 0.95rem; + padding: 12px; + border: 0; + background: none; + color: var(--muted); + cursor: pointer; + align-self: center; + transition: color 0.2s; +} +.linkbtn:active { + color: var(--ink); +} +a.linkbtn { + text-decoration: none; +} + +.foot-links { + display: flex; + flex-wrap: wrap; + justify-content: center; + gap: 2px 18px; + margin-top: 6px; + font-size: 0.86rem; +} +.foot-links a { + color: var(--faint); + text-decoration: none; + padding: 8px 2px; +} + +/* ── Address form ────────────────────────────────────────────────────────── */ +.form { + display: flex; + flex-direction: column; + gap: 12px; +} +.field { + position: relative; +} +.field input { + width: 100%; + font: inherit; + font-size: 1.05rem; + padding: 16px 18px; + border-radius: var(--radius); + border: 1px solid var(--edge); + background: var(--surface); + color: var(--ink); + outline: none; + transition: + border-color 0.2s, + box-shadow 0.25s; + user-select: text; + -webkit-user-select: text; +} +.field input::placeholder { + color: var(--faint); +} +.field input:focus { + border-color: var(--edge-strong); + box-shadow: 0 0 0 4px color-mix(in srgb, var(--ink) 9%, transparent); +} +.field.bad input { + border-color: var(--danger); + box-shadow: 0 0 0 4px color-mix(in srgb, var(--danger) 16%, transparent); + animation: shake 0.3s; +} +@keyframes shake { + 25% { + transform: translateX(-5px); + } + 50% { + transform: translateX(5px); + } + 75% { + transform: translateX(-3px); + } +} + +.error { + color: var(--danger); + margin: 0; + min-height: 1.4em; + line-height: 1.45; + font-size: 0.95rem; + transition: opacity 0.2s; +} + +/* Spinner inside the connect button while probing. */ +.spinner { + width: 18px; + height: 18px; + border: 2px solid color-mix(in srgb, var(--accent-ink) 35%, transparent); + border-top-color: var(--accent-ink); + border-radius: 50%; + animation: spin 0.7s linear infinite; +} +@keyframes spin { + to { + transform: rotate(360deg); + } +} + +/* ── Feature list (cloud screen) ─────────────────────────────────────────── */ +.features { + display: flex; + flex-direction: column; + gap: 2px; + margin: 4px 0 2px; +} +.feature { + display: flex; + align-items: flex-start; + gap: 13px; + padding: 11px 0; + border-top: 1px solid var(--edge); +} +.feature:first-child { + border-top: 0; +} +.feature .ic { + flex: none; + width: 34px; + height: 34px; + border-radius: 10px; + background: var(--surface); + border: 1px solid var(--edge); + display: grid; + place-items: center; + color: var(--ink); +} +.feature .tx { + line-height: 1.4; + padding-top: 5px; + font-size: 0.98rem; +} + +/* ── Success tick before the server loads ────────────────────────────────── */ +.success { + align-items: center; + text-align: center; + justify-content: center; +} +.tick { + width: 72px; + height: 72px; + border-radius: 50%; + background: color-mix(in srgb, var(--ok) 16%, transparent); + display: grid; + place-items: center; + margin-bottom: 8px; + animation: pop 0.45s var(--ease) both; +} +.tick svg { + width: 38px; + height: 38px; + color: var(--ok); +} +.tick path { + stroke-dasharray: 48; + stroke-dashoffset: 48; + animation: draw 0.45s 0.15s var(--ease) forwards; +} +@keyframes pop { + from { + transform: scale(0.4); + opacity: 0; + } + to { + transform: scale(1); + opacity: 1; + } +} +@keyframes draw { + to { + stroke-dashoffset: 0; + } +} + +.topbar { + display: flex; + align-items: center; + margin: 0 0 2px -8px; +} +.back { + font: inherit; + border: 0; + background: none; + color: var(--muted); + font-size: 0.98rem; + padding: 8px; + display: inline-flex; + align-items: center; + gap: 4px; + cursor: pointer; +} +.back:active { + color: var(--ink); +} + +@media (prefers-reduced-motion: reduce) { + *, + *::before { + animation-duration: 0.001ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.001ms !important; + } +} + +/* ── Plan picker (cloud subscription) ────────────────────────────────────── */ +.segmented { + display: flex; + gap: 4px; + padding: 4px; + background: var(--surface); + border: 1px solid var(--edge); + border-radius: 13px; + align-self: stretch; +} +.segmented button { + flex: 1; + font: inherit; + font-weight: 600; + font-size: 0.95rem; + padding: 9px; + border: 0; + border-radius: 9px; + background: none; + color: var(--muted); + cursor: pointer; + transition: + background 0.2s, + color 0.2s; + display: inline-flex; + align-items: center; + justify-content: center; + gap: 7px; +} +.segmented button[aria-pressed='true'] { + background: var(--accent); + color: var(--accent-ink); +} +.segmented .save { + font-size: 0.72rem; + font-weight: 600; + padding: 1px 6px; + border-radius: 999px; + background: color-mix(in srgb, var(--ok) 22%, transparent); + color: var(--ok); +} +.segmented button[aria-pressed='true'] .save { + background: color-mix(in srgb, var(--accent-ink) 16%, transparent); + color: var(--accent-ink); +} + +.plans { + display: flex; + flex-direction: column; + gap: 12px; +} +.plan { + border: 1px solid var(--edge); + border-radius: var(--radius); + padding: 16px; + background: var(--surface); + transition: + border-color 0.2s, + transform 0.14s var(--ease); +} +.plan:active { + transform: scale(0.99); +} +.plan.featured { + border-color: var(--edge-strong); + background: var(--surface-2); +} +.plan-top { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 10px; +} +.plan-name { + font-weight: 700; + font-size: 1.12rem; +} +.plan-price { + font-weight: 700; + font-size: 1.3rem; + letter-spacing: -0.01em; +} +.plan-price small { + font-weight: 500; + font-size: 0.8rem; + color: var(--muted); + margin-left: 3px; +} +.plan-feats { + margin: 10px 0 14px; + display: flex; + flex-direction: column; + gap: 6px; + color: var(--muted); + font-size: 0.92rem; +} +.plan-feats span { + display: flex; + align-items: center; + gap: 8px; +} +.plan-feats svg { + flex: none; + color: var(--ok); +} +.plan .btn { + width: 100%; + min-height: 48px; + padding: 13px; +} +.plan:not(.featured) .btn { + background: var(--surface-2); + color: var(--ink); + border-color: var(--edge); +} + +.loading { + display: flex; + justify-content: center; + padding: 40px 0; +} +.loading .spinner { + width: 26px; + height: 26px; + border-color: var(--edge-strong); + border-top-color: var(--ink); +} +.note { + text-align: center; + color: var(--faint); + font-size: 0.84rem; + margin: 2px 0 0; + line-height: 1.45; +} + +/* ── Claim: address + email, and the provisioning wait ───────────────────── */ +.slug-field { + display: flex; + align-items: center; + padding-right: 14px; +} +.slug-field .slug-input { + flex: 1; + min-width: 0; + text-align: right; +} +.slug-suffix { + flex: none; + color: var(--muted); + font-size: 0.98rem; + padding-left: 2px; + user-select: none; +} +.hint { + margin: -6px 2px 2px; + font-size: 0.84rem; + color: var(--faint); + min-height: 1.1em; + transition: color 0.2s; +} +.hint.ok { + color: var(--ok); +} +.hint.bad { + color: var(--danger); +} + +.screen-center { + justify-content: center; + text-align: center; + align-items: center; + gap: 18px; +} +.screen-center .title-sm, +.screen-center .sub { + text-align: center; +} +.provision-mark { + width: 56px; + height: 56px; + display: flex; + align-items: center; + justify-content: center; + margin-bottom: 4px; +} +.provision-mark .spinner { + width: 40px; + height: 40px; + border-width: 3px; + border-color: var(--edge-strong); + border-top-color: var(--accent); +} diff --git a/client/package.json b/client/package.json index a5c654d0d..89ec48880 100644 --- a/client/package.json +++ b/client/package.json @@ -9,6 +9,14 @@ "scripts": { "dev": "vite", "prebuild": "node scripts/generate-icons.mjs", + "icons:native": "node scripts/generate-native-icons.mjs", + "icons:app": "node scripts/generate-app-icons.mjs && npx @capacitor/assets generate --android --ios --iconBackgroundColor #09090b --iconBackgroundColorDark #09090b --splashBackgroundColor #09090b --splashBackgroundColorDark #09090b && node scripts/generate-adaptive-icons.mjs", + "build:native": "vite build --config vite.native.config.js", + "cap:sync": "npm run build:native && cap sync", + "store:shots": "playwright test --project=store", + "store:promote": "node scripts/store-screenshots.mjs", + "store:graphic": "node scripts/generate-feature-graphic.mjs", + "store:check": "node scripts/check-store-metadata.mjs", "build": "vite build", "build:analyze": "vite build --mode analyze", "preview": "vite preview", @@ -45,6 +53,16 @@ }, "dependencies": { "@assistant-ui/react": "0.15.25", + "@capacitor/android": "^8.5.0", + "@capacitor/app": "^8.1.1", + "@capacitor/core": "^8.5.0", + "@capacitor/filesystem": "^8.1.3", + "@capacitor/haptics": "^8.0.2", + "@capacitor/ios": "^8.5.0", + "@capacitor/keyboard": "^8.0.5", + "@capacitor/share": "^8.0.1", + "@capacitor/splash-screen": "^8.0.2", + "@capacitor/status-bar": "^8.0.3", "@fontsource/abril-fatface": "^5.3.0", "@fontsource/alfa-slab-one": "^5.3.0", "@fontsource/allura": "^5.3.0", @@ -82,6 +100,7 @@ "@fontsource/yellowtail": "^5.3.0", "@mapbox/mapbox-gl-rtl-text": "^0.4.0", "@maplibre/maplibre-gl-leaflet": "0.1.4", + "@noble/hashes": "^1.8.0", "@simplewebauthn/browser": "^13.3.0", "@trek/shared": "*", "axios": "^1.20.0", @@ -110,6 +129,7 @@ "zustand": "^5.0.15" }, "devDependencies": { + "@capacitor/cli": "^8.5.0", "@eslint/js": "^10.0.1", "@jscpd/core": "^4.2.5", "@jscpd/tokenizer": "^4.2.6", diff --git a/client/playwright.config.ts b/client/playwright.config.ts index 0f5303c82..7edc98986 100644 --- a/client/playwright.config.ts +++ b/client/playwright.config.ts @@ -94,6 +94,15 @@ export default defineConfig({ }, dependencies: ['shot-fixtures'], }, + // App Store and Google Play screenshots (`npm run store:shots`): the + // seeded demo trip at every device size the listings need. Each device sets + // its own viewport and scale in e2e/store/capture.store.ts. Not part of CI. + { + name: 'store', + testMatch: /\.store\.ts/, + use: { ...devices['Desktop Chrome'], storageState: E2E_STATE_FILE }, + dependencies: ['shot-fixtures'], + }, // Help-center media (`npm run help:media`): pictures and walkthroughs for // the in-app guides, generated from the guide definitions in src/help/. // Same seed as the wiki screenshots; its own match so neither run pays diff --git a/client/scripts/check-store-metadata.mjs b/client/scripts/check-store-metadata.mjs new file mode 100644 index 000000000..26818f490 --- /dev/null +++ b/client/scripts/check-store-metadata.mjs @@ -0,0 +1,102 @@ +/** + * Checks the store listings in fastlane/ before anything is uploaded + * (`npm run store:check`, and the metadata job in .github/workflows/native.yml): + * + * - every text both stores require exists and fits its limit (App Store: name and + * subtitle 30, keywords 100, promotional text 170, description 4000; Google + * Play: title 30, short description 80, full description 4000, changelog 500); + * - the URL files hold one https URL each; + * - every screenshot and listing graphic that is present has the exact size its + * slot takes and no alpha channel, which both stores refuse. + * + * Plain Node, no dependencies: a PNG's size and colour type are in its header. + */ +import { existsSync, readdirSync, readFileSync } from 'fs'; +import { dirname, join } from 'path'; +import { fileURLToPath } from 'url'; + +const fastlane = join(dirname(fileURLToPath(import.meta.url)), '..', 'fastlane'); +const meta = join(fastlane, 'metadata'); +const problems = []; + +/** [file, max length] the listing needs. */ +const TEXTS = [ + ['en-US/name.txt', 30], + ['en-US/subtitle.txt', 30], + ['en-US/keywords.txt', 100], + ['en-US/promotional_text.txt', 170], + ['en-US/description.txt', 4000], + ['en-US/release_notes.txt', 4000], + ['android/en-US/title.txt', 30], + ['android/en-US/short_description.txt', 80], + ['android/en-US/full_description.txt', 4000], + ['android/en-US/changelogs/default.txt', 500], + ['review_information/notes.txt', 4000], +]; +const URLS = ['en-US/support_url.txt', 'en-US/marketing_url.txt', 'en-US/privacy_url.txt']; + +function read(rel) { + const path = join(meta, rel); + if (!existsSync(path)) { + problems.push(`${rel}: missing`); + return null; + } + return readFileSync(path, 'utf8').trim(); +} + +for (const [rel, max] of TEXTS) { + const text = read(rel); + if (text === null) continue; + if (!text) problems.push(`${rel}: empty`); + // Code points, as the stores count them, not UTF-16 units. + const length = [...text].length; + if (length > max) problems.push(`${rel}: ${length} characters, the limit is ${max}`); +} +for (const rel of URLS) { + const url = read(rel); + if (url !== null && !/^https:\/\/\S+$/.test(url)) problems.push(`${rel}: not a single https URL`); +} + +/** Width, height and whether the PNG carries alpha (colour types 4 and 6), from its header. */ +function pngInfo(path) { + const head = readFileSync(path).subarray(0, 26); + if (head.toString('latin1', 1, 4) !== 'PNG') return null; + return { width: head.readUInt32BE(16), height: head.readUInt32BE(20), alpha: head[25] === 4 || head[25] === 6 }; +} + +/** [folder or file, accepted sizes] for every image slot. */ +const IMAGES = [ + [join(fastlane, 'screenshots', 'en-US'), ['1320x2868', '2064x2752']], + [join(meta, 'android', 'en-US', 'images', 'phoneScreenshots'), ['1080x1920']], + [join(meta, 'android', 'en-US', 'images', 'sevenInchScreenshots'), ['1620x2880']], + [join(meta, 'android', 'en-US', 'images', 'tenInchScreenshots'), ['1920x1080']], + [join(meta, 'android', 'en-US', 'images', 'featureGraphic.png'), ['1024x500']], + [join(meta, 'android', 'en-US', 'images', 'icon.png'), ['512x512']], +]; + +for (const [target, sizes] of IMAGES) { + if (!existsSync(target)) continue; + const files = target.endsWith('.png') + ? [target] + : readdirSync(target) + .filter((f) => f.endsWith('.png')) + .map((f) => join(target, f)); + for (const file of files) { + const info = pngInfo(file); + const rel = file.slice(fastlane.length + 1); + if (!info) { + problems.push(`${rel}: not a PNG`); + continue; + } + if (!sizes.includes(`${info.width}x${info.height}`)) { + problems.push(`${rel}: ${info.width}x${info.height}, expected ${sizes.join(' or ')}`); + } + if (info.alpha) problems.push(`${rel}: has an alpha channel`); + } +} + +if (problems.length) { + for (const problem of problems) console.error(`FAIL ${problem}`); + process.exit(1); +} +console.log('store metadata: every text fits, every image has its size and no alpha'); diff --git a/client/scripts/feature-pairs.json b/client/scripts/feature-pairs.json index b7ddd0447..3d6be0426 100644 --- a/client/scripts/feature-pairs.json +++ b/client/scripts/feature-pairs.json @@ -691,6 +691,12 @@ "desktop": ["src/components/Settings/AccountTab.tsx"], "mobile": ["src/mobile/screens/settings/MSettingsAccount.tsx"] }, + { + "feature": "Settings / Account / Native app server", + "hooks": ["src/components/Settings/useNativeServer.ts"], + "desktop": ["src/components/Settings/NativeServerSection.tsx"], + "mobile": ["src/mobile/screens/settings/MSettingsServer.tsx"] + }, { "feature": "Settings / Account / Passkeys", "hooks": ["src/components/Settings/usePasskeys.ts"], diff --git a/client/scripts/generate-adaptive-icons.mjs b/client/scripts/generate-adaptive-icons.mjs new file mode 100644 index 000000000..c48a2f8c6 --- /dev/null +++ b/client/scripts/generate-adaptive-icons.mjs @@ -0,0 +1,33 @@ +/** + * Writes the Android adaptive icon layers at their full size, after + * `npx @capacitor/assets generate` (see the icons:app script). + * + * The assets tool renders the foreground and background layers at the legacy + * launcher size (192 px at xxxhdpi), while an adaptive icon layer is 108 dp + * (432 px at xxxhdpi), so launchers that draw the icon large showed it soft. + * The layers come from the same sources in assets/, and + * mipmap-anydpi-v26/ic_launcher*.xml keeps placing them as before; it also uses + * the foreground as the monochrome layer for themed icons, since the mark is + * white on transparent. + */ +import { dirname, join } from 'path'; +import sharp from 'sharp'; +import { fileURLToPath } from 'url'; + +const clientDir = join(dirname(fileURLToPath(import.meta.url)), '..'); +const resDir = join(clientDir, 'android', 'app', 'src', 'main', 'res'); + +/** 108 dp in pixels for each density bucket. */ +const DENSITIES = { ldpi: 81, mdpi: 108, hdpi: 162, xhdpi: 216, xxhdpi: 324, xxxhdpi: 432 }; +const LAYERS = { ic_launcher_foreground: 'icon-foreground.png', ic_launcher_background: 'icon-background.png' }; + +for (const [density, size] of Object.entries(DENSITIES)) { + for (const [name, source] of Object.entries(LAYERS)) { + const out = join(resDir, `mipmap-${density}`, `${name}.png`); + await sharp(join(clientDir, 'assets', source)) + .resize(size, size) + .png({ compressionLevel: 9 }) + .toFile(out); + console.log(`wrote ${out}`); + } +} diff --git a/client/scripts/generate-app-icons.mjs b/client/scripts/generate-app-icons.mjs new file mode 100644 index 000000000..dda9bddd3 --- /dev/null +++ b/client/scripts/generate-app-icons.mjs @@ -0,0 +1,108 @@ +/** + * Renders the native apps' icon and splash sources into assets/, from the + * white TREK mark in public/icons/icon-white.svg. `npx @capacitor/assets + * generate --android --ios` then turns them into every size both platforms + * ask for (see the icons:app script). + * + * The look: a dark, slightly glassy tile (a soft light from the top left and a + * sheen over the upper half) under the white mark. Dark because that is the + * app's launch background (#09090b) and its default scheme. + * + * Android's adaptive icon masks the foreground to a circle inside the + * canvas, so the mark there sits smaller than on the iOS tile. + */ +import { mkdirSync, readFileSync } from 'fs'; +import { dirname, join } from 'path'; +import sharp from 'sharp'; +import { fileURLToPath } from 'url'; + +const clientDir = join(dirname(fileURLToPath(import.meta.url)), '..'); +const outDir = join(clientDir, 'assets'); +mkdirSync(outDir, { recursive: true }); + +const source = readFileSync(join(clientDir, 'public', 'icons', 'icon-white.svg'), 'utf8'); +const markPath = [...source.matchAll(/ m[1]).find((d) => d.length > 500); +if (!markPath) throw new Error('No mark path found in icon-white.svg'); +// The mark's extent inside its 1500 x 1500 viewBox. +const MARK = { x: 40, y: 5, w: 1420, h: 1490 }; + +const LAUNCH_BG = '#09090b'; + +function tile(size) { + return ` + + + + + + + + + + + + + + + + + + + + + + + + + +`; +} + +/** The white mark, `share` of the canvas tall, centred, with a soft shadow for depth. */ +function mark(size, share, shadow = true) { + const scale = (1024 * share) / MARK.h; + const w = MARK.w * scale; + const h = MARK.h * scale; + const tx = (1024 - w) / 2 - MARK.x * scale; + const ty = (1024 - h) / 2 - MARK.y * scale; + return ` + + + + + + + + + + + + +`; +} + +async function render(svg, file) { + await sharp(Buffer.from(svg)).png().toFile(join(outDir, file)); +} + +async function composite(background, overlay, file, size) { + const base = await sharp(Buffer.from(background)).resize(size, size).png().toBuffer(); + const top = await sharp(Buffer.from(overlay)).resize(size, size).png().toBuffer(); + await sharp(base) + .composite([{ input: top }]) + .flatten({ background: LAUNCH_BG }) + .png() + .toFile(join(outDir, file)); +} + +// iOS and store listings: one opaque tile, the mark at about half its height. +await composite(tile(1024), mark(1024, 0.5), 'icon-only.png', 1024); +// Android adaptive icon: the two layers apart, the mark inside the safe circle. +await render(tile(1024), 'icon-background.png'); +await render(mark(1024, 0.58), 'icon-foreground.png'); +// Splash: the launch background with the mark, light and dark alike. +const splashBg = ``; +await composite(splashBg, mark(2732, 0.2, false), 'splash.png', 2732); +await composite(splashBg, mark(2732, 0.2, false), 'splash-dark.png', 2732); + +console.log(`[app-icons] wrote icon and splash sources to ${outDir}`); diff --git a/client/scripts/generate-feature-graphic.mjs b/client/scripts/generate-feature-graphic.mjs new file mode 100644 index 000000000..802bf0886 --- /dev/null +++ b/client/scripts/generate-feature-graphic.mjs @@ -0,0 +1,75 @@ +/** + * The Google Play listing graphics (`npm run store:graphic`): + * + * featureGraphic.png 1024 x 500, the dark app background, the white TREK mark, + * the name and the subtitle, and on the right a crop of the + * first phone screenshot when one has been promoted + * (`npm run store:promote`); without it, mark and text only. + * icon.png 512 x 512, from the same 1024 px tile as the app icon. + * + * Both are flattened: Play refuses an alpha channel in either. + */ +import { existsSync, mkdirSync, readFileSync } from 'fs'; +import { dirname, join } from 'path'; +import sharp from 'sharp'; +import { fileURLToPath } from 'url'; + +const clientDir = join(dirname(fileURLToPath(import.meta.url)), '..'); +const imagesDir = join(clientDir, 'fastlane', 'metadata', 'android', 'en-US', 'images'); +mkdirSync(imagesDir, { recursive: true }); + +const WIDTH = 1024; +const HEIGHT = 500; +const BACKGROUND = '#09090b'; +const TITLE = 'TREK Travel Planner'; +const SUBTITLE = readFileSync(join(clientDir, 'fastlane', 'metadata', 'en-US', 'subtitle.txt'), 'utf8').trim(); + +const escapeXml = (text) => text.replace(/&/g, '&').replace(//g, '>'); + +const mark = await sharp(join(clientDir, 'public', 'icons', 'icon-white.svg')) + .resize(120, 120) + .png() + .toBuffer(); + +const text = Buffer.from(` + ${escapeXml(TITLE)} + ${escapeXml(SUBTITLE)} +`); + +const layers = [ + { input: mark, left: 72, top: 110 }, + { input: text, left: 0, top: 0 }, +]; + +// The first phone screenshot, cut to the top of the screen and set at the right edge. +const phone = join(imagesDir, 'phoneScreenshots', '1_dashboard.png'); +if (existsSync(phone)) { + const crop = await sharp(phone) + .resize({ width: 300 }) + .extract({ left: 0, top: 0, width: 300, height: 440 }) + .png() + .toBuffer(); + const frame = Buffer.from(` + `); + const rounded = await sharp(crop) + .composite([{ input: frame, blend: 'dest-in' }]) + .png() + .toBuffer(); + layers.push({ input: rounded, left: WIDTH - 300 - 64, top: 30 }); +} + +await sharp({ create: { width: WIDTH, height: HEIGHT, channels: 3, background: BACKGROUND } }) + .composite(layers) + .flatten({ background: BACKGROUND }) + .removeAlpha() + .png() + .toFile(join(imagesDir, 'featureGraphic.png')); + +await sharp(join(clientDir, 'assets', 'icon-only.png')) + .resize(512, 512) + .flatten({ background: BACKGROUND }) + .removeAlpha() + .png() + .toFile(join(imagesDir, 'icon.png')); + +console.log(`wrote ${join(imagesDir, 'featureGraphic.png')} and icon.png`); diff --git a/client/scripts/generate-native-icons.mjs b/client/scripts/generate-native-icons.mjs new file mode 100644 index 000000000..0e00dffb1 --- /dev/null +++ b/client/scripts/generate-native-icons.mjs @@ -0,0 +1,67 @@ +/** + * Generates the Android status-bar notification icon from the master + * white-silhouette SVG. + * + * Android renders the small notification icon as a mask: every non-transparent + * pixel becomes the tint colour and everything else is dropped. Feeding it the + * launcher icon (a full-bleed coloured square) therefore produces a solid white + * blob, which is the single most common Capacitor push-notification complaint. + * public/icons/icon-white.svg is already white-on-transparent, so we only have + * to rasterise it at the five densities and flatten the colour to pure white so + * any future edit to that SVG's fill cannot silently change the mask. + * + * Referenced from AndroidManifest.xml as @drawable/notification_icon. + * Run: node scripts/generate-native-icons.mjs + */ +import { mkdirSync } from 'fs'; +import { dirname, join } from 'path'; +import sharp from 'sharp'; +import { fileURLToPath } from 'url'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const clientDir = join(__dirname, '..'); +const source = join(clientDir, 'public', 'icons', 'icon-white.svg'); +const resDir = join(clientDir, 'android', 'app', 'src', 'main', 'res'); + +// Android notification icon sizes, in px, per density bucket (24dp baseline). +const densities = [ + { dir: 'drawable-mdpi', size: 24 }, + { dir: 'drawable-hdpi', size: 36 }, + { dir: 'drawable-xhdpi', size: 48 }, + { dir: 'drawable-xxhdpi', size: 72 }, + { dir: 'drawable-xxxhdpi', size: 96 }, +]; + +for (const { dir, size } of densities) { + const outDir = join(resDir, dir); + mkdirSync(outDir, { recursive: true }); + + // Inset the glyph slightly: Android's status bar clips tight to the 24dp box + // and a mark that touches the edge reads as cropped. + const glyph = Math.round(size * 0.86); + + const mask = await sharp(source, { density: 512 }) + .resize(glyph, glyph, { fit: 'contain', background: { r: 0, g: 0, b: 0, alpha: 0 } }) + .extend({ + top: Math.floor((size - glyph) / 2), + bottom: Math.ceil((size - glyph) / 2), + left: Math.floor((size - glyph) / 2), + right: Math.ceil((size - glyph) / 2), + background: { r: 0, g: 0, b: 0, alpha: 0 }, + }) + .ensureAlpha() + .toBuffer(); + + // Keep the alpha, force every visible pixel to pure white. `dest-in` composites + // the white plate through the glyph's alpha channel. + await sharp({ + create: { width: size, height: size, channels: 4, background: { r: 255, g: 255, b: 255, alpha: 1 } }, + }) + .composite([{ input: mask, blend: 'dest-in' }]) + .png({ compressionLevel: 9 }) + .toFile(join(outDir, 'notification_icon.png')); + + console.log(` ✓ ${dir}/notification_icon.png (${size}x${size})`); +} + +console.log('Android notification icons generated.'); diff --git a/client/scripts/i18n-keys.mjs b/client/scripts/i18n-keys.mjs index 0f85ddd0f..0e23662c9 100644 --- a/client/scripts/i18n-keys.mjs +++ b/client/scripts/i18n-keys.mjs @@ -44,8 +44,9 @@ * * The en keys nothing reaches are a ratchet. Besides src/, the search for * references reads server/src (system notice and notification channel keys - * the server sends, *Key properties in its registries), plugin-sdk/src and - * shared/src/book (the Studio's layout template names), so + * the server sends, *Key properties in its registries), plugin-sdk/src, + * shared/src/book (the Studio's layout template names) and the native apps' + * address screen in native-shell/, so * a key the server uses does not read as dead; those references only count as * reached, they are not held to the rules above. The unused keys per en * domain file may not rise above scripts/i18n-unused-baseline.json, and an @@ -75,6 +76,9 @@ const UNUSED_BASELINE = join(HERE, 'i18n-unused-baseline.json'); * its layout templates. Read only to find which en keys are reached. */ export const REFERENCE_ROOTS = [ + // The address screen the native apps ship (vite.native.config.js): its own + // small build outside src/, reading only the native.* strings. + join(HERE, '..', 'native-shell'), join(HERE, '..', '..', 'server', 'src'), join(HERE, '..', '..', 'plugin-sdk', 'src'), join(HERE, '..', '..', 'shared', 'src', 'book'), diff --git a/client/scripts/size-baseline.json b/client/scripts/size-baseline.json index f2b36069a..166113985 100644 --- a/client/scripts/size-baseline.json +++ b/client/scripts/size-baseline.json @@ -18,7 +18,7 @@ "src/index.css": 1636, "src/mobile/screens/admin/MAdminPluginsPanel.tsx": 1507, "src/pages/JourneyDetailPage.test.tsx": 4028, - "src/pages/LoginPage.tsx": 1348, + "src/pages/LoginPage.tsx": 1347, "src/pages/TripPlannerPage.tsx": 1128, "src/pages/atlas/useAtlas.ts": 1210, "src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx": 3518, diff --git a/client/scripts/store-screenshots.mjs b/client/scripts/store-screenshots.mjs new file mode 100644 index 000000000..d5f6d62e7 --- /dev/null +++ b/client/scripts/store-screenshots.mjs @@ -0,0 +1,64 @@ +/** + * Moves the store screenshots from e2e/.tmp/store/ (written by the Playwright + * `store` project, `npm run store:shots`) into the folders fastlane uploads + * from, flattened onto the app background: both stores refuse an image with an + * alpha channel. + * + * iphone69, ipad13 fastlane/screenshots/en-US/ (deliver, App Store) + * play-phone fastlane/metadata/android/en-US/images/phoneScreenshots/ + * play-7in .../sevenInchScreenshots/ + * play-10in .../tenInchScreenshots/ (supply, Google Play) + * + * Every image is checked against the size its device must have, so a capture at + * the wrong viewport never reaches a listing. `npm run store:check` checks the + * committed files the same way. + */ +import { existsSync, mkdirSync, readdirSync } from 'fs'; +import { dirname, join } from 'path'; +import sharp from 'sharp'; +import { fileURLToPath } from 'url'; + +const clientDir = join(dirname(fileURLToPath(import.meta.url)), '..'); +const rawDir = join(clientDir, 'e2e', '.tmp', 'store'); +const fastlane = join(clientDir, 'fastlane'); +const playImages = join(fastlane, 'metadata', 'android', 'en-US', 'images'); + +const TARGETS = { + iphone69: { dir: join(fastlane, 'screenshots', 'en-US'), size: [1320, 2868] }, + ipad13: { dir: join(fastlane, 'screenshots', 'en-US'), size: [2064, 2752] }, + 'play-phone': { dir: join(playImages, 'phoneScreenshots'), size: [1080, 1920] }, + 'play-7in': { dir: join(playImages, 'sevenInchScreenshots'), size: [1620, 2880] }, + 'play-10in': { dir: join(playImages, 'tenInchScreenshots'), size: [1920, 1080] }, +}; + +const BACKGROUND = '#09090b'; + +if (!existsSync(rawDir)) { + console.error(`No captures in ${rawDir}. Run npm run store:shots first.`); + process.exit(1); +} + +let failed = false; +for (const [device, { dir, size }] of Object.entries(TARGETS)) { + const from = join(rawDir, device); + if (!existsSync(from)) { + console.error(`missing captures for ${device}`); + failed = true; + continue; + } + mkdirSync(dir, { recursive: true }); + for (const file of readdirSync(from).filter((f) => f.endsWith('.png'))) { + const image = sharp(join(from, file)); + const { width, height } = await image.metadata(); + if (width !== size[0] || height !== size[1]) { + console.error(`${device}/${file}: ${width}x${height}, expected ${size[0]}x${size[1]}`); + failed = true; + continue; + } + // The App Store folder holds both devices; the prefix keeps them apart. + const name = dir.endsWith(join('screenshots', 'en-US')) ? `${device}_${file}` : file; + await image.flatten({ background: BACKGROUND }).removeAlpha().png().toFile(join(dir, name)); + console.log(`wrote ${join(dir, name)}`); + } +} +process.exit(failed ? 1 : 0); diff --git a/client/src/App.tsx b/client/src/App.tsx index 6419e2018..39500bbd7 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -45,6 +45,7 @@ import { managedRoutes } from './managed' // for a reload. const PluginPage = lazyWithRetry(() => import('./pages/PluginPage')) const ForgotPasswordPage = lazyWithRetry(() => import('./pages/ForgotPasswordPage')) +const NativeHandoffPage = lazyWithRetry(() => import('./pages/NativeHandoffPage')) const ResetPasswordPage = lazyWithRetry(() => import('./pages/ResetPasswordPage')) const DashboardPage = lazyWithRetry(() => import('./pages/DashboardPage')) const TripPlannerPage = lazyWithRetry(() => import('./pages/TripPlannerPage')) @@ -453,6 +454,7 @@ export default function App() { } /> } /> } /> + } /> } /> {/* OAuth 2.1 consent page — intentionally outside ProtectedRoute */} } /> diff --git a/client/src/api/nativeAuth.test.ts b/client/src/api/nativeAuth.test.ts new file mode 100644 index 000000000..56c1adff5 --- /dev/null +++ b/client/src/api/nativeAuth.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it, vi } from 'vitest'; +import { apiClient } from './client'; +import { nativeAuthApi } from './nativeAuth'; + +vi.mock('./client', () => ({ apiClient: { post: vi.fn() } })); + +describe('nativeAuthApi', () => { + it('mints a hand-off code for a challenge', async () => { + vi.mocked(apiClient.post).mockResolvedValue({ data: { code: 'c1' } }); + await expect(nativeAuthApi.handoff('ab'.repeat(32))).resolves.toEqual({ code: 'c1' }); + expect(apiClient.post).toHaveBeenCalledWith('/auth/native/handoff', { challenge: 'ab'.repeat(32) }); + }); + + it('redeems the code with its verifier', async () => { + vi.mocked(apiClient.post).mockResolvedValue({ data: { ok: true } }); + await expect(nativeAuthApi.exchange({ code: 'c1', verifier: 'v'.repeat(64) })).resolves.toBeUndefined(); + expect(apiClient.post).toHaveBeenCalledWith('/auth/native/exchange', { code: 'c1', verifier: 'v'.repeat(64) }); + }); +}); diff --git a/client/src/api/nativeAuth.ts b/client/src/api/nativeAuth.ts new file mode 100644 index 000000000..db02fbc8e --- /dev/null +++ b/client/src/api/nativeAuth.ts @@ -0,0 +1,12 @@ +import type { NativeExchangeRequest, NativeHandoffResponse } from '@trek/shared'; +import { apiClient } from './client'; + +/** The two halves of the sign-in hand-off between system browser and app. */ +export const nativeAuthApi = { + /** Browser side: trade a signed-in session for a one-time code bound to `challenge`. */ + handoff: (challenge: string): Promise => + apiClient.post('/auth/native/handoff', { challenge }).then((r) => r.data), + /** App side: redeem the code with the verifier; the response sets the session cookie. */ + exchange: (body: NativeExchangeRequest): Promise => + apiClient.post('/auth/native/exchange', body).then(() => undefined), +}; diff --git a/client/src/components/Admin/GitHubPanel.tsx b/client/src/components/Admin/GitHubPanel.tsx index dda191525..ecdb620e1 100644 --- a/client/src/components/Admin/GitHubPanel.tsx +++ b/client/src/components/Admin/GitHubPanel.tsx @@ -15,6 +15,7 @@ import { } from 'lucide-react'; import { type ComponentType, type CSSProperties, type ReactNode } from 'react'; import { useTranslation } from '../../i18n'; +import { withoutDonationsInApp } from '../../utils/donations'; import { escapeReleaseHtml as escapeHtml, parseReleaseNotes } from '../../utils/releaseNotes'; import { fs } from '../shared/DialogShell'; import { SETTINGS_BUTTON, SettingsCard, StatusPill } from '../Settings/settingsKit'; @@ -134,7 +135,7 @@ export default function GitHubPanel({ isPrerelease = false }: { isPrerelease?: b }); }; - const supportLinks: SupportLink[] = [ + const supportLinks: SupportLink[] = withoutDonationsInApp([ { href: 'https://ko-fi.com/mauriceboe', brand: '#ff5e5b', // theme-lint-disable: Ko-fi brand colour @@ -177,7 +178,7 @@ export default function GitHubPanel({ isPrerelease = false }: { isPrerelease?: b title: 'Wiki', hint: t('settings.about.wikiHint'), }, - ]; + ]); const subtitle = t('admin.github.subtitle').replace('{repo}', REPO); diff --git a/client/src/components/Collections/collectionFile.test.ts b/client/src/components/Collections/collectionFile.test.ts index 20a4f9a81..657f7232b 100644 --- a/client/src/components/Collections/collectionFile.test.ts +++ b/client/src/components/Collections/collectionFile.test.ts @@ -75,10 +75,10 @@ describe('downloads', () => { expect(click).toHaveBeenCalledTimes(1) expect(names).toEqual(['lisbon' + COLLECTION_FILE_EXTENSION]) expect(created[0].type).toBe('application/json') - expect(document.querySelector('a')).toBeNull() expect(revoke).not.toHaveBeenCalled() vi.runAllTimers() expect(revoke).toHaveBeenCalledWith('blob:x') + expect(document.querySelector('a')).toBeNull() }) it('FE-COLL-FILE-014: hands the browser a GPX under the list name', async () => { diff --git a/client/src/components/Collections/collectionFile.ts b/client/src/components/Collections/collectionFile.ts index 94dc6714a..b0b6487c9 100644 --- a/client/src/components/Collections/collectionFile.ts +++ b/client/src/components/Collections/collectionFile.ts @@ -6,6 +6,7 @@ import { type CollectionGpxProblem, type CollectionGpxReadResult, } from '@trek/shared' +import { downloadBlob } from '../../utils/fileDownload' /** * The browser half of list export and import (#2198, #2301). @@ -37,16 +38,7 @@ export function collectionFileName(name: string, extension = COLLECTION_FILE_EXT } function download(content: string, type: string, fileName: string): void { - const url = URL.createObjectURL(new Blob([content], { type })) - const a = document.createElement('a') - a.href = url - a.download = fileName - document.body.appendChild(a) - a.click() - a.remove() - // Revoked on the next tick: revoking synchronously can cancel the download - // in some browsers before it has started reading the blob. - setTimeout(() => URL.revokeObjectURL(url), 0) + downloadBlob(new Blob([content], { type }), fileName) } /** Hand the file to the browser as a download. */ diff --git a/client/src/components/Journey/JourneyMapGL.tsx b/client/src/components/Journey/JourneyMapGL.tsx index 8464cd872..ccb39fe98 100644 --- a/client/src/components/Journey/JourneyMapGL.tsx +++ b/client/src/components/Journey/JourneyMapGL.tsx @@ -3,7 +3,7 @@ import type mapboxgl from 'mapbox-gl' import { useSettingsStore } from '../../store/settingsStore' import { isStandardFamily, supportsCustom3d, wantsTerrain, addCustom3dBuildings, addTerrainAndSky } from '../Map/mapboxSetup' import { MAPBOX_DEFAULT_STYLE, styleForActiveProvider, basemapLanguage, type GlMapProvider } from '../Map/glProviders' -import { buildGlMap } from '../Map/glSupport' +import { buildGlMap, initialMapStyle } from '../Map/glSupport' import type { JourneyTrack } from '@trek/shared' import { SHOT_INDEX_ATTR, ensureJourneyPopupStyle, formatMarkerDate, journeyPopupHtml } from './journeyMapPopup' import { clusterPhotos, photoMarkerHtml, type MapPhoto } from './journeyPhotoLayer' @@ -384,7 +384,7 @@ function JourneyMapGL( const mapOptions: Record = { container: containerRef.current, - style: glStyle, + style: initialMapStyle(glProvider, glStyle), center: hasPoints ? bounds.getCenter() : [0, 30], zoom: hasPoints ? 2 : 1, pitch: enableMapbox3d && fullScreen ? 45 : 0, diff --git a/client/src/components/Map/MapViewGL.tsx b/client/src/components/Map/MapViewGL.tsx index d5464a0dd..dfcf889f5 100644 --- a/client/src/components/Map/MapViewGL.tsx +++ b/client/src/components/Map/MapViewGL.tsx @@ -24,7 +24,7 @@ import { useTransportRoutes } from '../../hooks/useTransportRoutes' import { visibleRouteReservations } from '../../utils/reservationRoutes' import { safeHexColor } from '../../utils/safeColor' import { MAPBOX_DEFAULT_STYLE, styleForActiveProvider, basemapLanguage, type GlMapProvider } from './glProviders' -import { buildGlMap } from './glSupport' +import { buildGlMap, initialMapStyle } from './glSupport' import LocationButton from './LocationButton' import { useIsPhone } from '../../mobile/useIsPhone' import { useGeolocation } from '../../hooks/useGeolocation' @@ -1008,7 +1008,7 @@ export function MapViewGL({ const mapOptions: Record = { container: containerRef.current, - style: glStyle, + style: initialMapStyle(glProvider, glStyle), center: [initial.center[1], initial.center[0]], zoom: initial.zoom, pitch: enableMapbox3d ? 45 : 0, diff --git a/client/src/components/Map/VectorBasemap.tsx b/client/src/components/Map/VectorBasemap.tsx index e6607c1f8..b2c385aa0 100644 --- a/client/src/components/Map/VectorBasemap.tsx +++ b/client/src/components/Map/VectorBasemap.tsx @@ -10,6 +10,7 @@ import { import { hasWebGL, reportWebGLFailure } from '../../utils/webgl' import { isGpuInitFailure } from './glSupport' import { isChunkLoadError, reloadOnceForChunk } from '../../utils/chunkReload' +import { offlineStyle } from '../../native/offlineTiles' /** The Leaflet layer maplibre-gl-leaflet hands back. */ export type GlLeafletLayer = InstanceType @@ -145,7 +146,7 @@ export function detachBasemapLayer(layer: BasemapLayer | null | undefined): void */ export function restyleBasemap(layer: BasemapLayer | null | undefined, style: string): void { if (!layer || !isGlLayer(layer)) return - layer.getMaplibreMap()?.setStyle(style) + layer.getMaplibreMap()?.setStyle(offlineStyle(style)) } /** @@ -191,7 +192,7 @@ export function VectorBasemap({ style }: { style: string }) { // change must retile in place rather than tear the layer down, the same // reason the raster maps keep their template out of the build effect (#2097). const layer = maplibreGL({ - style: styleRef.current, + style: offlineStyle(styleRef.current), interactive: false, attributionControl: false, }) @@ -267,7 +268,7 @@ export async function attachVectorBasemap( return } - const layer = maplibreGL({ style, interactive: false, attributionControl: false }) + const layer = maplibreGL({ style: offlineStyle(style), interactive: false, attributionControl: false }) // The raster layer this replaces carried the credit, and OpenFreeMap asks for // one of its own; attachGlLayer adds it once the layer is actually on the map. if (!attachGlLayer(map, layer, style)) { diff --git a/client/src/components/Map/engines/maplibre.ts b/client/src/components/Map/engines/maplibre.ts index 0c4a72f3a..47e83e10f 100644 --- a/client/src/components/Map/engines/maplibre.ts +++ b/client/src/components/Map/engines/maplibre.ts @@ -1,6 +1,7 @@ import * as maplibregl from 'maplibre-gl' import 'maplibre-gl/dist/maplibre-gl.css' import workerUrl from 'maplibre-gl/dist/maplibre-gl-worker.mjs?worker&url' +import { installOfflineProtocol } from '../../../native/offlineTiles' /** * The only module in the client that pulls maplibre-gl in at runtime. Same rule as @@ -28,4 +29,7 @@ maplibregl.setWorkerUrl(workerUrl) // bidirectional text itself; the old plugin would replace that implementation, and // a v6 worker can only load the plugin's UMD build through eval. +// The iOS app has no service worker to serve pre-downloaded tiles; see native/offlineTiles.ts. +installOfflineProtocol(maplibregl) + export default maplibregl diff --git a/client/src/components/Map/glSupport.test.ts b/client/src/components/Map/glSupport.test.ts index 3061768b9..2dd916162 100644 --- a/client/src/components/Map/glSupport.test.ts +++ b/client/src/components/Map/glSupport.test.ts @@ -9,7 +9,7 @@ import { act, renderHook } from '@testing-library/react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { hasWebGL, resetWebGLProbe } from '../../utils/webgl'; -import { buildGlMap, isGpuInitFailure, pickGlRenderer, useGlRenderer, useWebGL2 } from './glSupport'; +import { buildGlMap, initialMapStyle, isGpuInitFailure, pickGlRenderer, useGlRenderer, useWebGL2 } from './glSupport'; const realGetContext = HTMLCanvasElement.prototype.getContext; @@ -132,3 +132,12 @@ describe('useGlRenderer', () => { expect(terrain.result.current).toBe(false); }); }); + +describe('initialMapStyle', () => { + it('FE-MAP-GLSUP-INIT-001: leaves the style as it is outside the iOS app, and always for Mapbox', () => { + expect(initialMapStyle('maplibre-gl', 'https://tiles.openfreemap.org/styles/liberty')).toBe( + 'https://tiles.openfreemap.org/styles/liberty' + ); + expect(initialMapStyle('mapbox-gl', 'mapbox://styles/mapbox/standard')).toBe('mapbox://styles/mapbox/standard'); + }); +}); diff --git a/client/src/components/Map/glSupport.ts b/client/src/components/Map/glSupport.ts index 9e3630bda..8b1469fb1 100644 --- a/client/src/components/Map/glSupport.ts +++ b/client/src/components/Map/glSupport.ts @@ -1,4 +1,5 @@ import { useSyncExternalStore } from 'react'; +import { offlineStyle } from '../../native/offlineTiles'; import { hasWebGL, reportWebGLFailure, subscribeWebGL, webGLFailures } from '../../utils/webgl'; import type { GlMapProvider } from './glProviders'; @@ -63,6 +64,15 @@ export function isGpuInitFailure(err: unknown): boolean { * and the caller gets null instead of a throw. Anything else is a bug and is * thrown on. */ +/** + * The style a new GL map is built with. A MapLibre map inside the iOS app reads + * its tiles through the offline protocol (native/offlineTiles.ts); Mapbox has no + * protocol hook, so its style goes in untouched. + */ +export function initialMapStyle(provider: GlMapProvider, style: string): string { + return provider === 'maplibre-gl' ? offlineStyle(style) : style; +} + export function buildGlMap(construct: () => T): T | null { try { return construct(); diff --git a/client/src/components/Planner/useTripExport.ts b/client/src/components/Planner/useTripExport.ts index 9dcd4bbe0..caa587296 100644 --- a/client/src/components/Planner/useTripExport.ts +++ b/client/src/components/Planner/useTripExport.ts @@ -6,6 +6,7 @@ import { useSettingsStore } from '../../store/settingsStore'; import type { AssignmentsMap, Category, Day, DayNote, Place, Reservation, Trip } from '../../types'; import { importChunk } from '../../utils/chunkReload'; import type { ViasByDay } from '../../utils/dayRouteVias'; +import { downloadBlob } from '../../utils/fileDownload'; import type { TourStageStops } from '../Map/dayTourProjection'; import { hasPersonalPlan } from '../PDF/pdfScope'; @@ -62,20 +63,11 @@ export interface TripExportOptions { } /** - * Hands the browser a downloaded file. Firefox and Safari cancel the download when - * the object URL is revoked before they picked the blob up, hence the delay. + * Hands the downloaded file on: a browser download, or the share sheet inside + * the native app (utils/fileDownload.ts). */ export function saveBlob(blob: Blob, filename: string) { - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = filename; - document.body.appendChild(a); - a.click(); - setTimeout(() => { - URL.revokeObjectURL(url); - a.remove(); - }, 100); + downloadBlob(blob, filename); } /** The day notes as one list, each carrying the day it belongs to. */ diff --git a/client/src/components/Settings/AboutTab.tsx b/client/src/components/Settings/AboutTab.tsx index 555ac63c7..e513120af 100644 --- a/client/src/components/Settings/AboutTab.tsx +++ b/client/src/components/Settings/AboutTab.tsx @@ -15,6 +15,7 @@ import { import React, { type CSSProperties, type ReactNode } from 'react'; import { useTranslation } from '../../i18n'; import { useAuthStore } from '../../store/authStore'; +import { donationsShown } from '../../utils/donations'; import { fs } from '../shared/DialogShell'; import Section from './Section'; import { StatusPill } from './settingsKit'; @@ -242,20 +243,25 @@ export default function AboutTab({ appVersion }: Props): React.ReactElement { not the part being trimmed here. */} {!managed && (
- } - title="Ko-fi" - hint={t('admin.github.support')} - /> - } - title="Buy Me a Coffee" - hint={t('admin.github.support')} - /> + {/* Not in the native apps, whose store rules allow no outside payment links. */} + {donationsShown() && ( + <> + } + title="Ko-fi" + hint={t('admin.github.support')} + /> + } + title="Buy Me a Coffee" + hint={t('admin.github.support')} + /> + + )} { expect(createObjectURL).toHaveBeenCalledWith(expect.any(Blob)); expect(downloadName).toBe('trek-mfa-backup-codes.txt'); - expect(revokeObjectURL).toHaveBeenCalledWith('blob:codes'); + await waitFor(() => expect(revokeObjectURL).toHaveBeenCalledWith('blob:codes')); expect(document.querySelector('a[download]')).toBeNull(); createObjectURL.mockRestore(); diff --git a/client/src/components/Settings/AccountTab.tsx b/client/src/components/Settings/AccountTab.tsx index d00dd6b5c..39d383389 100644 --- a/client/src/components/Settings/AccountTab.tsx +++ b/client/src/components/Settings/AccountTab.tsx @@ -3,6 +3,7 @@ import { User, Save, Lock, KeyRound, AlertTriangle, Shield, Camera, Trash2, Copy import { useTranslation } from '../../i18n' import Section from './Section' import PasskeysSection from './PasskeysSection' +import NativeServerSection from './NativeServerSection' import PasswordChecklist from '../shared/PasswordChecklist' import ConfirmDialog from '../shared/ConfirmDialog' import { Tooltip } from '../shared/Tooltip' @@ -72,6 +73,7 @@ export default function AccountTab(): React.ReactElement { return ( <> + {/* The shared demo account: everything here is shown, nothing can be changed. */}
diff --git a/client/src/components/Settings/NativeServerSection.test.tsx b/client/src/components/Settings/NativeServerSection.test.tsx new file mode 100644 index 000000000..03467e9eb --- /dev/null +++ b/client/src/components/Settings/NativeServerSection.test.tsx @@ -0,0 +1,57 @@ +// FE-SETTINGS-NATIVE-SERVER-001 to FE-SETTINGS-NATIVE-SERVER-008 +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen } from '../../../tests/helpers/render'; +import MSettingsServer from '../../mobile/screens/settings/MSettingsServer'; +import { nativeServerHost } from '../../native/platform'; +import { TrekShell } from '../../native/trekShell'; +import NativeServerLink from '../../pages/login/NativeServerLink'; +import NativeServerSection from './NativeServerSection'; + +vi.mock('../../native/platform', () => ({ nativeServerHost: vi.fn() })); +vi.mock('../../native/trekShell', () => ({ TrekShell: { resetServer: vi.fn() } })); + +beforeEach(() => { + vi.mocked(TrekShell.resetServer).mockReset().mockResolvedValue(); +}); + +describe.each([ + ['desktop', NativeServerSection], + ['mobile', MSettingsServer], +])('the %s server section', (_shell, Section) => { + it('renders nothing in a browser', () => { + vi.mocked(nativeServerHost).mockReturnValue(null); + const { container } = render(
); + expect(container).toBeEmptyDOMElement(); + }); + + it('names the server and leads back to the address screen', () => { + vi.mocked(nativeServerHost).mockReturnValue('trek.example.com'); + render(
); + expect(screen.getByText('This app is connected to trek.example.com.')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Change server' })); + expect(TrekShell.resetServer).toHaveBeenCalled(); + }); + + it('links to the privacy policy, opened outside the app', () => { + vi.mocked(nativeServerHost).mockReturnValue('trek.example.com'); + render(
); + const link = screen.getByRole('link', { name: 'Privacy policy' }); + expect(link).toHaveAttribute('href', 'https://liketrek.com/privacy'); + expect(link).toHaveAttribute('target', '_blank'); + }); +}); + +describe('the sign-in screen link', () => { + it('renders nothing in a browser', () => { + vi.mocked(nativeServerHost).mockReturnValue(null); + const { container } = render(); + expect(container).toBeEmptyDOMElement(); + }); + + it('leads back to the address screen in the app', () => { + vi.mocked(nativeServerHost).mockReturnValue('trek.example.com'); + render(); + fireEvent.click(screen.getByRole('button', { name: 'Change server' })); + expect(TrekShell.resetServer).toHaveBeenCalled(); + }); +}); diff --git a/client/src/components/Settings/NativeServerSection.tsx b/client/src/components/Settings/NativeServerSection.tsx new file mode 100644 index 000000000..9788c6bd3 --- /dev/null +++ b/client/src/components/Settings/NativeServerSection.tsx @@ -0,0 +1,33 @@ +import { Server } from 'lucide-react'; +import React from 'react'; + +import { useTranslation } from '../../i18n'; +import Section from './Section'; +import { useNativeServer } from './useNativeServer'; + +/** Only inside the iOS/Android app: which server it talks to, and the way to another one. */ +export default function NativeServerSection(): React.ReactElement | null { + const { t } = useTranslation(); + const { host, changeServer, privacyUrl } = useNativeServer(); + if (!host) return null; + return ( +
+

{t('native.settings.serverHint', { server: host })}

+ + + {t('native.privacy')} + +
+ ); +} diff --git a/client/src/components/Settings/useAccountSettings.test.tsx b/client/src/components/Settings/useAccountSettings.test.tsx index b41dbb76c..a03bb3832 100644 --- a/client/src/components/Settings/useAccountSettings.test.tsx +++ b/client/src/components/Settings/useAccountSettings.test.tsx @@ -246,7 +246,7 @@ describe('useAccountSettings', () => { act(() => result.current.downloadBackupCodes()); expect(createUrl).toHaveBeenCalledWith(expect.any(Blob)); expect(click).toHaveBeenCalledTimes(1); - expect(revokeUrl).toHaveBeenCalledWith('blob:codes'); + await waitFor(() => expect(revokeUrl).toHaveBeenCalledWith('blob:codes')); act(() => result.current.printBackupCodes()); expect(open).toHaveBeenCalledWith('', '_blank', 'width=900,height=700'); diff --git a/client/src/components/Settings/useAccountSettings.ts b/client/src/components/Settings/useAccountSettings.ts index c31d0de65..e409e6bb4 100644 --- a/client/src/components/Settings/useAccountSettings.ts +++ b/client/src/components/Settings/useAccountSettings.ts @@ -7,6 +7,7 @@ import { useTranslation } from '../../i18n'; import { useAuthStore } from '../../store/authStore'; import { getApiErrorMessage, type UserWithOidc } from '../../types'; import { formatDisplayDateTime } from '../../utils/dateFormat'; +import { downloadBlob } from '../../utils/fileDownload'; import { passwordErrorKey } from '../../utils/passwordError'; import { useToast } from '../shared/Toast'; @@ -115,14 +116,7 @@ export function useAccountSettings({ avatarRemoveErrorKey, ignoreEmptyBackupCode const downloadBackupCodes = () => { if (skipBackupCodes) return; const blob = new Blob([backupCodesText + '\n'], { type: 'text/plain;charset=utf-8' }); - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = 'trek-mfa-backup-codes.txt'; - document.body.appendChild(a); - a.click(); - a.remove(); - URL.revokeObjectURL(url); + downloadBlob(blob, 'trek-mfa-backup-codes.txt'); }; const printBackupCodes = () => { diff --git a/client/src/components/Settings/useNativeServer.ts b/client/src/components/Settings/useNativeServer.ts new file mode 100644 index 000000000..83814ed2c --- /dev/null +++ b/client/src/components/Settings/useNativeServer.ts @@ -0,0 +1,19 @@ +import { PRIVACY_URL } from '../../native/links'; +import { nativeServerHost } from '../../native/platform'; +import { TrekShell } from '../../native/trekShell'; + +/** + * The server section both settings views show inside the iOS and Android app: + * the host the app is connected to (null in a browser, where the section stays + * hidden), the way back to the address screen, and the privacy policy the store + * listings name, which an app has to reach from inside itself. + */ +export function useNativeServer(): { host: string | null; changeServer: () => void; privacyUrl: string } { + return { + host: nativeServerHost(), + privacyUrl: PRIVACY_URL, + changeServer: () => { + void TrekShell.resetServer(); + }, + }; +} diff --git a/client/src/components/Settings/usePasskeys.ts b/client/src/components/Settings/usePasskeys.ts index 4dc2a2ba9..3a5c5d19a 100644 --- a/client/src/components/Settings/usePasskeys.ts +++ b/client/src/components/Settings/usePasskeys.ts @@ -3,6 +3,7 @@ import { useEffect, useState } from 'react'; import { authApi, type PasskeyCredential } from '../../api/client'; import { readDateFormat } from '../../hooks/useDateFormat'; import { useTranslation } from '../../i18n'; +import { isNativeApp } from '../../native/platform'; import { getApiErrorMessage } from '../../types'; import { formatDisplayDate } from '../../utils/dateFormat'; import { useToast } from '../shared/Toast'; @@ -26,7 +27,9 @@ export function isWebauthnAbort(err: unknown): boolean { * list, add (a password step-up, then the WebAuthn ceremony), rename, and delete * (password step-up). Adding needs the instance toggle on AND a usable RP ID; the * list stays reachable when the feature is later switched off so users can clean up. - * `hidden` tells a view to render nothing: in demo mode, or when there is nothing to show. + * `hidden` tells a view to render nothing: in demo mode, when there is nothing to show, or + * inside the native app, whose WebView cannot run WebAuthn for every server's domain (the + * passkeys are managed in the browser there, and signing in with one goes through it too). */ export function usePasskeys({ demoMode = false }: { demoMode?: boolean } = {}) { const { t } = useTranslation(); @@ -70,7 +73,7 @@ export function usePasskeys({ demoMode = false }: { demoMode?: boolean } = {}) { const canAdd = enabled && configured; // Nothing to show: feature off and the user has no credentials to manage. const nothingToShow = !loading && !enabled && creds.length === 0; - const hidden = demoMode || nothingToShow; + const hidden = demoMode || nothingToShow || isNativeApp(); // The toggle is on but no usable RP ID resolves, so adding stays off. const notConfigured = enabled && !configured; diff --git a/client/src/components/Studio/spreadFile.ts b/client/src/components/Studio/spreadFile.ts index 67c9210b9..e5c4d3df8 100644 --- a/client/src/components/Studio/spreadFile.ts +++ b/client/src/components/Studio/spreadFile.ts @@ -1,5 +1,6 @@ import type { BookPageSetup, BookSpread } from '@trek/shared' import { bookElementSchema } from '@trek/shared' +import { downloadBlob } from '../../utils/fileDownload' /** * A spread as a file, so a design can leave the book it was made in. @@ -204,16 +205,7 @@ export function importSpread(raw: unknown, page: BookPageSetup): BookSpread | nu /** Hand the file to the browser as a download. */ export function downloadSpread(spread: BookSpread, page: BookPageSetup, name: string) { const json = JSON.stringify(exportSpread(spread, page, name), null, 2) - const url = URL.createObjectURL(new Blob([json], { type: 'application/json' })) - const a = document.createElement('a') - a.href = url - a.download = `${slug(name) || 'spread'}.trekspread.json` - document.body.appendChild(a) - a.click() - a.remove() - // Revoked on the next tick: revoking synchronously can cancel the download - // in some browsers before it has started reading the blob. - setTimeout(() => URL.revokeObjectURL(url), 0) + downloadBlob(new Blob([json], { type: 'application/json' }), `${slug(name) || 'spread'}.trekspread.json`) } function slug(name: string): string { diff --git a/client/src/components/SystemNotices/SystemNoticeHost.tsx b/client/src/components/SystemNotices/SystemNoticeHost.tsx index 6399da29c..d6625a998 100644 --- a/client/src/components/SystemNotices/SystemNoticeHost.tsx +++ b/client/src/components/SystemNotices/SystemNoticeHost.tsx @@ -3,6 +3,7 @@ import { useSystemNoticeStore, type SystemNoticeDTO } from '../../store/systemNo import { useTranslation } from '../../i18n/index.js'; import { ModalRenderer } from './SystemNoticeModal.js'; import { BannerRenderer, ToastRenderer } from './SystemNoticeBanner.js'; +import { donationsShown, noticeAsksForDonation } from '../../utils/donations'; // Mobile breakpoint matches the modal sheet's (max-width: 639px). function useIsMobile() { @@ -76,7 +77,9 @@ export function SystemNoticeHost() { // desktopOnly notices (e.g. the thank-you/support modal) are hidden on mobile, and a // notice whose copy this build does not have yet waits for the reload (see hasCopy). - const readable = notices.filter(n => hasCopy(n, t)); + // Inside the native apps a notice that asks for a donation never shows: the + // store rules on payments allow no outside payment link there. + const readable = notices.filter(n => hasCopy(n, t) && (donationsShown() || !noticeAsksForDonation(n))); const visible = isMobile ? readable.filter(n => !n.desktopOnly) : readable; const modals = visible.filter(n => n.display === 'modal'); diff --git a/client/src/components/shared/useToastQueue.ts b/client/src/components/shared/useToastQueue.ts index 269d8d7d0..410f6fc81 100644 --- a/client/src/components/shared/useToastQueue.ts +++ b/client/src/components/shared/useToastQueue.ts @@ -1,4 +1,5 @@ import { useCallback, useEffect, useRef, useState } from 'react'; +import { toastHaptic } from '../../native/haptics'; export type ToastType = 'success' | 'error' | 'warning' | 'info'; @@ -49,6 +50,7 @@ export function useToastQueue({ exitMs, restorePrevious }: ToastQueueOptions) { (message: string, type: ToastType = 'info', duration: number = 3000) => { const id = ++toastIdCounter; setToasts((prev) => [...prev, { id, message, type, duration, removing: false }]); + toastHaptic(type); if (duration > 0) { const t = setTimeout(() => dismissToast(id), duration); diff --git a/client/src/main.tsx b/client/src/main.tsx index a55c1fb0a..7b879d5c8 100644 --- a/client/src/main.tsx +++ b/client/src/main.tsx @@ -39,6 +39,7 @@ import './styles/hike.css' // double-tap zooms (#1440). See utils/touchDragPolyfill.ts. import { maybeInstallTouchDragPolyfill } from './utils/touchDragPolyfill' import { startConnectivityProbe } from './sync/connectivity' +import { startNativeApp } from './native/nativeApp' import { requestPersistentStorage } from './sync/persistentStorage' import ErrorBoundary, { RootErrorFallback } from './components/shared/ErrorBoundary' import { installGlobalErrorHandlers } from './utils/globalErrorHandlers' @@ -46,6 +47,8 @@ import { schedulePrecacheRepair } from './utils/serviceWorkerShell' void maybeInstallTouchDragPolyfill() startConnectivityProbe() +// Inside the iOS/Android app: splash, back button, status bar, offline start (iOS). +startNativeApp() // Keep offline data (map tiles, file blobs, IndexedDB) exempt from eviction. void requestPersistentStorage() // Event handlers and async code never reach a boundary; this is where they land. diff --git a/client/src/mobile/screens/admin/MAdminGitHubPanel.tsx b/client/src/mobile/screens/admin/MAdminGitHubPanel.tsx index a545bac42..3c508b78b 100644 --- a/client/src/mobile/screens/admin/MAdminGitHubPanel.tsx +++ b/client/src/mobile/screens/admin/MAdminGitHubPanel.tsx @@ -4,6 +4,7 @@ import { useTranslation } from '../../../i18n' import { useGithubReleases } from '../../../components/Admin/useGithubReleases' import { escapeReleaseHtml as escapeHtml, parseReleaseNotes } from '../../../utils/releaseNotes' import { MAdminButton, MAdminCard } from './MAdminUi' +import { withoutDonationsInApp } from '../../../utils/donations' const REPO = 'liketrek/TREK' @@ -116,14 +117,14 @@ export default function MAdminGitHubPanel({ isPrerelease = false }: { isPrerelea ) - const cards: LinkCard[] = [ + const cards: LinkCard[] = withoutDonationsInApp([ { href: 'https://ko-fi.com/mauriceboe', color: '#ff5e5b', icon: , title: 'Ko-fi', sub: t('admin.github.support') }, { href: 'https://buymeacoffee.com/mauriceboe', color: '#ffdd00', icon: , title: 'Buy Me a Coffee', sub: t('admin.github.support') }, { href: 'https://discord.gg/NhZBDSd4qW', color: '#5865F2', icon: discordIcon, title: 'Discord', sub: 'Join the community' }, { href: 'https://github.com/liketrek/TREK/issues/new?template=bug_report.yml', color: '#ef4444', icon: , title: t('settings.about.reportBug'), sub: t('settings.about.reportBugHint') }, { href: 'https://github.com/liketrek/TREK/discussions/new?category=feature-requests', color: '#f59e0b', icon: , title: t('settings.about.featureRequest'), sub: t('settings.about.featureRequestHint') }, { href: 'https://github.com/liketrek/TREK/wiki', color: '#6366f1', icon: , title: 'Wiki', sub: t('settings.about.wikiHint') }, - ] + ]) return (
diff --git a/client/src/mobile/screens/settings/MSettings.tsx b/client/src/mobile/screens/settings/MSettings.tsx index 9c92075d1..02689aff0 100644 --- a/client/src/mobile/screens/settings/MSettings.tsx +++ b/client/src/mobile/screens/settings/MSettings.tsx @@ -26,6 +26,7 @@ import MSettingsNotifications from './MSettingsNotifications' import MSettingsIntegrations from './MSettingsIntegrations' import MSettingsAccount from './MSettingsAccount' import MSettingsAbout from './MSettingsAbout' +import MSettingsServer from './MSettingsServer' interface SectionTab { id: string @@ -118,6 +119,7 @@ export default function MSettings() { {/* Per-plugin settings still reuse the existing responsive tab. */} {active.id === 'plugins' && hasPlugins && !managed && } {active.id === 'offline' && } + {active.id === 'account' && } {active.id === 'account' && } {active.id === 'about' && appVersion && } diff --git a/client/src/mobile/screens/settings/MSettingsAbout.tsx b/client/src/mobile/screens/settings/MSettingsAbout.tsx index a6f2a983e..8960bb3c0 100644 --- a/client/src/mobile/screens/settings/MSettingsAbout.tsx +++ b/client/src/mobile/screens/settings/MSettingsAbout.tsx @@ -2,6 +2,7 @@ import { Bug, BookOpen, Coffee, ExternalLink, Heart, Info, Lightbulb } from 'luc import type { LucideIcon } from 'lucide-react' import { useTranslation } from '../../../i18n' import { MSetCard } from './MSettingsUi' +import { withoutDonationsInApp } from '../../../utils/donations' interface AboutLink { href: string @@ -14,14 +15,14 @@ interface AboutLink { export default function MSettingsAbout({ appVersion }: { appVersion: string }) { const { t } = useTranslation() - const links: AboutLink[] = [ + const links: AboutLink[] = withoutDonationsInApp([ { href: 'https://ko-fi.com/mauriceboe', icon: Coffee, title: 'Ko-fi', sub: t('admin.github.support') }, { href: 'https://buymeacoffee.com/mauriceboe', icon: Heart, title: 'Buy Me a Coffee', sub: t('admin.github.support') }, { href: 'https://discord.gg/NhZBDSd4qW', icon: Heart, title: 'Discord', sub: 'Join the community' }, { href: 'https://github.com/liketrek/TREK/issues/new?template=bug_report.yml', icon: Bug, title: t('settings.about.reportBug'), sub: t('settings.about.reportBugHint') }, { href: 'https://github.com/liketrek/TREK/discussions/new?category=feature-requests', icon: Lightbulb, title: t('settings.about.featureRequest'), sub: t('settings.about.featureRequestHint') }, { href: 'https://github.com/liketrek/TREK/wiki', icon: BookOpen, title: 'Wiki', sub: t('settings.about.wikiHint') }, - ] + ]) return ( diff --git a/client/src/mobile/screens/settings/MSettingsServer.tsx b/client/src/mobile/screens/settings/MSettingsServer.tsx new file mode 100644 index 000000000..d7fd34851 --- /dev/null +++ b/client/src/mobile/screens/settings/MSettingsServer.tsx @@ -0,0 +1,28 @@ +import { Server } from 'lucide-react'; + +import { useNativeServer } from '../../../components/Settings/useNativeServer'; +import { useTranslation } from '../../../i18n'; +import { MSetButton, MSetCard, MSetHint } from './MSettingsUi'; + +/** Only inside the iOS/Android app: which server it talks to, and the way to another one. */ +export default function MSettingsServer() { + const { t } = useTranslation(); + const { host, changeServer, privacyUrl } = useNativeServer(); + if (!host) return null; + return ( + + {t('native.settings.serverHint', { server: host })} + + {t('native.changeServer')} + + + {t('native.privacy')} + + + ); +} diff --git a/client/src/native/browserSignIn.test.ts b/client/src/native/browserSignIn.test.ts new file mode 100644 index 000000000..7c95f3548 --- /dev/null +++ b/client/src/native/browserSignIn.test.ts @@ -0,0 +1,79 @@ +import { sha256 } from '@noble/hashes/sha2'; +import { bytesToHex } from '@noble/hashes/utils'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { nativeAuthApi } from '../api/nativeAuth'; +import { + BrowserSignInCancelled, + createHandoffSecret, + handoffUrl, + requestHandoffCode, + signInThroughBrowser, +} from './browserSignIn'; +import { TrekShell } from './trekShell'; + +vi.mock('./trekShell', () => ({ APP_URL_SCHEME: 'com.liketrek.trek', TrekShell: { authenticate: vi.fn() } })); +vi.mock('../api/nativeAuth', () => ({ nativeAuthApi: { exchange: vi.fn(), handoff: vi.fn() } })); + +beforeEach(() => { + vi.mocked(TrekShell.authenticate).mockReset(); + vi.mocked(nativeAuthApi.exchange).mockReset().mockResolvedValue(); +}); + +describe('createHandoffSecret', () => { + it('pairs a fresh 64-character verifier with the hex sha256 the server checks against', () => { + const { verifier, challenge } = createHandoffSecret(); + expect(verifier).toMatch(/^[0-9a-f]{64}$/); + expect(challenge).toBe(bytesToHex(sha256(new TextEncoder().encode(verifier)))); + expect(createHandoffSecret().verifier).not.toBe(verifier); + }); +}); + +describe('requestHandoffCode', () => { + it('asks the server for the one-time code bound to the challenge', async () => { + vi.mocked(nativeAuthApi.handoff).mockResolvedValue({ code: 'c-1' }); + await expect(requestHandoffCode('ab'.repeat(32))).resolves.toBe('c-1'); + expect(nativeAuthApi.handoff).toHaveBeenCalledWith('ab'.repeat(32)); + }); +}); + +describe('handoffUrl', () => { + it('points at the hand-off page with the challenge and an optional start', () => { + expect(handoffUrl('https://trek.example.com', 'c')).toBe('https://trek.example.com/native-handoff?challenge=c'); + expect(handoffUrl('https://trek.example.com', 'c', 'oidc')).toBe( + 'https://trek.example.com/native-handoff?challenge=c&start=oidc' + ); + }); +}); + +describe('signInThroughBrowser', () => { + it('opens the hand-off page and redeems the returned code with the verifier', async () => { + vi.mocked(TrekShell.authenticate).mockResolvedValue({ url: 'com.liketrek.trek://auth?code=abc' }); + + await signInThroughBrowser('oidc'); + + const opened = new URL(vi.mocked(TrekShell.authenticate).mock.calls[0][0].url); + expect(opened.pathname).toBe('/native-handoff'); + expect(opened.searchParams.get('start')).toBe('oidc'); + expect(vi.mocked(TrekShell.authenticate).mock.calls[0][0].callbackScheme).toBe('com.liketrek.trek'); + const { code, verifier } = vi.mocked(nativeAuthApi.exchange).mock.calls[0][0]; + expect(code).toBe('abc'); + expect(bytesToHex(sha256(new TextEncoder().encode(verifier)))).toBe(opened.searchParams.get('challenge')); + }); + + it('turns a closed browser into BrowserSignInCancelled', async () => { + vi.mocked(TrekShell.authenticate).mockRejectedValue(Object.assign(new Error('closed'), { code: 'CANCELLED' })); + await expect(signInThroughBrowser()).rejects.toBeInstanceOf(BrowserSignInCancelled); + expect(nativeAuthApi.exchange).not.toHaveBeenCalled(); + }); + + it('passes other failures on', async () => { + vi.mocked(TrekShell.authenticate).mockRejectedValue(new Error('no browser')); + await expect(signInThroughBrowser()).rejects.toThrow('no browser'); + }); + + it('refuses a return without a code', async () => { + vi.mocked(TrekShell.authenticate).mockResolvedValue({ url: 'com.liketrek.trek://auth' }); + await expect(signInThroughBrowser()).rejects.toThrow('without a sign-in code'); + expect(nativeAuthApi.exchange).not.toHaveBeenCalled(); + }); +}); diff --git a/client/src/native/browserSignIn.ts b/client/src/native/browserSignIn.ts new file mode 100644 index 000000000..c088855c7 --- /dev/null +++ b/client/src/native/browserSignIn.ts @@ -0,0 +1,67 @@ +import { sha256 } from '@noble/hashes/sha2'; +import { bytesToHex } from '@noble/hashes/utils'; +import { nativeAuthApi } from '../api/nativeAuth'; +import { APP_URL_SCHEME, TrekShell } from './trekShell'; + +/** + * SSO and passkeys cannot run inside the app's WebView: identity providers + * refuse embedded browsers, and WebAuthn wants the app to be associated with + * the server's domain, which no build can be for every server. So the app + * opens the server's /native-handoff page in the system browser, lets the user + * sign in there, and carries the session back with a one-time code. + * + * The verifier never leaves this function. Only its sha256 travels into the + * browser, and the code that comes back through the URL scheme is useless to + * anyone who does not also hold the verifier. The hash is computed in JS + * because crypto.subtle is missing on a plain-http server, which is how many + * home networks reach theirs. + */ + +export const HANDOFF_PATH = '/native-handoff'; + +export type BrowserSignInStart = 'oidc'; + +export function createHandoffSecret(): { verifier: string; challenge: string } { + const bytes = crypto.getRandomValues(new Uint8Array(32)); + const verifier = bytesToHex(bytes); + return { verifier, challenge: bytesToHex(sha256(new TextEncoder().encode(verifier))) }; +} + +export function handoffUrl(origin: string, challenge: string, start?: BrowserSignInStart, invite?: string): string { + const url = new URL(HANDOFF_PATH, origin); + url.searchParams.set('challenge', challenge); + if (start) url.searchParams.set('start', start); + if (invite) url.searchParams.set('invite', invite); + return url.href; +} + +/** The browser side: trade the signed-in session for a one-time code bound to `challenge`. */ +export async function requestHandoffCode(challenge: string): Promise { + const { code } = await nativeAuthApi.handoff(challenge); + return code; +} + +export class BrowserSignInCancelled extends Error { + constructor() { + super('Sign-in cancelled'); + this.name = 'BrowserSignInCancelled'; + } +} + +/** Resolves once the WebView holds a session cookie of its own. */ +export async function signInThroughBrowser(start?: BrowserSignInStart, invite?: string): Promise { + const { verifier, challenge } = createHandoffSecret(); + let returned: string; + try { + ({ url: returned } = await TrekShell.authenticate({ + url: handoffUrl(window.location.origin, challenge, start, invite), + callbackScheme: APP_URL_SCHEME, + })); + } catch (err) { + if ((err as { code?: string })?.code === 'CANCELLED') throw new BrowserSignInCancelled(); + throw err; + } + const code = new URL(returned).searchParams.get('code'); + if (!code) throw new Error('The browser returned without a sign-in code'); + await nativeAuthApi.exchange({ code, verifier }); +} diff --git a/client/src/native/haptics.test.ts b/client/src/native/haptics.test.ts new file mode 100644 index 000000000..4dc860c01 --- /dev/null +++ b/client/src/native/haptics.test.ts @@ -0,0 +1,44 @@ +import { Haptics, NotificationType } from '@capacitor/haptics'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { toastHaptic } from './haptics'; +import { isNativeApp } from './platform'; + +vi.mock('@capacitor/haptics', () => ({ + Haptics: { notification: vi.fn() }, + NotificationType: { Success: 'SUCCESS', Warning: 'WARNING', Error: 'ERROR' }, +})); +vi.mock('./platform', () => ({ isNativeApp: vi.fn() })); + +beforeEach(() => { + vi.mocked(Haptics.notification).mockReset().mockResolvedValue(); + vi.mocked(isNativeApp).mockReturnValue(true); +}); + +describe('toastHaptic', () => { + it('taps for success, warning and error toasts in the app', () => { + toastHaptic('success'); + toastHaptic('warning'); + toastHaptic('error'); + expect(vi.mocked(Haptics.notification).mock.calls.map(([o]) => o?.type)).toEqual([ + NotificationType.Success, + NotificationType.Warning, + NotificationType.Error, + ]); + }); + + it('stays still for info toasts and in a browser', () => { + toastHaptic('info'); + vi.mocked(isNativeApp).mockReturnValue(false); + toastHaptic('success'); + expect(Haptics.notification).not.toHaveBeenCalled(); + }); + + it('does not let a missing vibrator surface as an error', async () => { + const report = vi.fn(); + vi.stubGlobal('reportError', report); + vi.mocked(Haptics.notification).mockRejectedValue(new Error('not available')); + toastHaptic('error'); + await vi.waitFor(() => expect(report).toHaveBeenCalledWith(expect.any(Error))); + vi.unstubAllGlobals(); + }); +}); diff --git a/client/src/native/haptics.ts b/client/src/native/haptics.ts new file mode 100644 index 000000000..b88f9605e --- /dev/null +++ b/client/src/native/haptics.ts @@ -0,0 +1,20 @@ +import { Haptics, NotificationType } from '@capacitor/haptics'; +import { isNativeApp } from './platform'; +import { reportNativeFailure } from './reportFailure'; + +const FEEDBACK: Record = { + success: NotificationType.Success, + warning: NotificationType.Warning, + error: NotificationType.Error, +}; + +/** + * The short tap a native app gives when something saved, warned or failed. + * Hung off the toasts because every save and delete already reports through + * one; plain info toasts stay silent. Does nothing in a browser. + */ +export function toastHaptic(type: string): void { + const feedback = FEEDBACK[type]; + if (!feedback || !isNativeApp()) return; + Haptics.notification({ type: feedback }).catch(reportNativeFailure); +} diff --git a/client/src/native/iap.test.ts b/client/src/native/iap.test.ts new file mode 100644 index 000000000..fd7a01643 --- /dev/null +++ b/client/src/native/iap.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from 'vitest'; +import { fakeIapClient, nativeIapClient, productIdFor } from './iap'; + +describe('in-app purchase client', () => { + it('names store products by the shared scheme', () => { + expect(productIdFor('start', 'month')).toBe('cloud.start.monthly'); + expect(productIdFor('pro', 'year')).toBe('cloud.pro.yearly'); + }); + + it('the native client is unavailable until the purchase plugin is wired', async () => { + expect(await nativeIapClient.isAvailable()).toBe(false); + expect(await nativeIapClient.purchase('cloud.plus.monthly')).toEqual({ kind: 'failed' }); + }); + + it('the fake client yields a receipt for the product asked for', async () => { + expect(await fakeIapClient.isAvailable()).toBe(true); + const outcome = await fakeIapClient.purchase('cloud.plus.monthly'); + expect(outcome.kind).toBe('bought'); + if (outcome.kind !== 'bought') return; + expect(outcome.purchase.productId).toBe('cloud.plus.monthly'); + expect(outcome.purchase.platform).toBe('apple'); + expect(outcome.purchase.receipt).toContain('cloud.plus.monthly'); + }); +}); diff --git a/client/src/native/iap.ts b/client/src/native/iap.ts new file mode 100644 index 000000000..0707f7548 --- /dev/null +++ b/client/src/native/iap.ts @@ -0,0 +1,89 @@ +/** + * In-app purchase, from the app's side. A seam, like {@link TrekShell}: the + * screens drive a plan to a receipt through this, and never touch the store + * plugin directly. Two implementations stand behind it — a fake one for + * development and preview, so the whole subscription flow can be walked without a + * store, and the native one that will call the platform plugin once the store + * products and accounts exist. Until then the native client reports itself + * unavailable and the plan picker falls back to finishing on the web, so nothing + * half-wired ever faces a customer. + */ + +type IapPlatform = 'apple' | 'google'; + +/** The receipt a completed purchase yields, in the shape `/api/iap/redeem` takes. */ +export interface Purchase { + platform: IapPlatform; + productId: string; + receipt: string; +} + +/** What a purchase attempt came to. `cancelled` is the customer backing out, not an error. */ +type PurchaseOutcome = { kind: 'bought'; purchase: Purchase } | { kind: 'cancelled' } | { kind: 'failed' }; + +export interface IapClient { + /** Whether this build can take a payment: the plugin is present and the store products exist. */ + isAvailable(): Promise; + /** Runs the platform's purchase sheet for a product and resolves with what became of it. */ + purchase(productId: string): Promise; +} + +/** + * The store product id for a plan and interval. Must match the identifiers created + * in App Store Connect and the Play Console, and the control plane's catalog + * (`cloud..`); kept here as the one place the app names them. + */ +export function productIdFor(planId: string, interval: 'month' | 'year'): string { + return `cloud.${planId}.${interval === 'year' ? 'yearly' : 'monthly'}`; +} + +/** + * The fake used in development and preview: it waits a beat, as a real sheet + * would, then returns a receipt the control plane's fake verifier accepts. Never + * reached in a store build. + */ +export const fakeIapClient: IapClient = { + async isAvailable() { + return true; + }, + async purchase(productId) { + await new Promise((resolve) => setTimeout(resolve, 900)); + return { + kind: 'bought', + purchase: { platform: 'apple', productId, receipt: `fake-receipt:${productId}:${Date.now()}` }, + }; + }, +}; + +/** + * The store client. A stub until the purchase plugin is a dependency and the + * products exist: it reports itself unavailable, so the plan picker finishes on + * the web instead of offering a payment it cannot take. When the plugin lands, + * this is where it is wired; the screens do not change. + */ +export const nativeIapClient: IapClient = { + async isAvailable() { + return false; + }, + async purchase() { + return { kind: 'failed' }; + }, +}; + +/** + * Whether to use the fake. On in a development build, and switchable on in a + * preview build with `localStorage['trek-iap-fake'] = '1'`, so the flow can be + * shown without a store. Off in a store build, where the native client decides. + */ +function fakeEnabled(): boolean { + try { + if (import.meta.env?.DEV) return true; + return typeof localStorage !== 'undefined' && localStorage.getItem('trek-iap-fake') === '1'; + } catch { + return false; + } +} + +export function getIapClient(): IapClient { + return fakeEnabled() ? fakeIapClient : nativeIapClient; +} diff --git a/client/src/native/links.ts b/client/src/native/links.ts new file mode 100644 index 000000000..f367a8f9d --- /dev/null +++ b/client/src/native/links.ts @@ -0,0 +1,16 @@ +/** + * Pages the apps link to outside the user's server. They open in the system + * browser: the WebView hands every navigation off the server's own origin to it. + */ + +/** The privacy policy the store listings name too. */ +export const PRIVACY_URL = 'https://liketrek.com/privacy'; + +/** What a TREK server is and how to run one, for someone who has none yet. */ +export const SERVER_DOCS_URL = 'https://github.com/liketrek/TREK#readme'; + +/** The public demo the address screen offers to someone without a server. */ +export const DEMO_SERVER_URL = 'https://demo.liketrek.com'; + +/** TREK Cloud, for someone who wants a hosted TREK rather than running their own. */ +export const CLOUD_URL = 'https://liketrek.com'; diff --git a/client/src/native/nativeApp.test.ts b/client/src/native/nativeApp.test.ts new file mode 100644 index 000000000..7710c502e --- /dev/null +++ b/client/src/native/nativeApp.test.ts @@ -0,0 +1,127 @@ +import { App } from '@capacitor/app'; +import { Keyboard } from '@capacitor/keyboard'; +import { SplashScreen } from '@capacitor/splash-screen'; +import { StatusBar, Style } from '@capacitor/status-bar'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { isEffectivelyOffline } from '../sync/networkMode'; +import { startNativeApp } from './nativeApp'; +import { keepOfflineShellFresh } from './offlineShell'; +import { isNativeApp, isNativeIos } from './platform'; + +vi.mock('@capacitor/app', () => ({ App: { addListener: vi.fn(), minimizeApp: vi.fn() } })); +vi.mock('@capacitor/keyboard', () => ({ Keyboard: { setAccessoryBarVisible: vi.fn() } })); +vi.mock('@capacitor/splash-screen', () => ({ SplashScreen: { hide: vi.fn() } })); +vi.mock('@capacitor/status-bar', () => ({ StatusBar: { setStyle: vi.fn() }, Style: { Dark: 'DARK', Light: 'LIGHT' } })); +vi.mock('./platform', () => ({ isNativeApp: vi.fn(), isNativeIos: vi.fn() })); +vi.mock('./offlineShell', () => ({ keepOfflineShellFresh: vi.fn() })); +vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn() })); + +function backButtonHandler(): (event: { canGoBack: boolean }) => void { + const call = vi.mocked(App.addListener).mock.calls.find(([name]) => name === 'backButton'); + if (!call) throw new Error('no backButton listener'); + return call[1] as unknown as (event: { canGoBack: boolean }) => void; +} + +beforeEach(() => { + vi.useFakeTimers(); + vi.clearAllMocks(); + vi.mocked(isNativeApp).mockReturnValue(true); + vi.mocked(isNativeIos).mockReturnValue(false); + vi.mocked(isEffectivelyOffline).mockReturnValue(false); + vi.mocked(keepOfflineShellFresh).mockResolvedValue(); + document.documentElement.classList.remove('dark'); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +describe('startNativeApp', () => { + it('does nothing in a browser', () => { + vi.mocked(isNativeApp).mockReturnValue(false); + startNativeApp(); + expect(App.addListener).not.toHaveBeenCalled(); + expect(StatusBar.setStyle).not.toHaveBeenCalled(); + }); + + it('hides the splash after the first frame', () => { + startNativeApp(); + vi.runOnlyPendingTimers(); + expect(SplashScreen.hide).toHaveBeenCalled(); + }); + + it('walks back through history before it leaves the app', () => { + const back = vi.spyOn(window.history, 'back').mockImplementation(() => {}); + startNativeApp(); + backButtonHandler()({ canGoBack: true }); + expect(back).toHaveBeenCalled(); + backButtonHandler()({ canGoBack: false }); + expect(App.minimizeApp).toHaveBeenCalled(); + }); + + it('keeps the status bar icons readable when the scheme changes', async () => { + startNativeApp(); + expect(StatusBar.setStyle).toHaveBeenLastCalledWith({ style: Style.Light }); + document.documentElement.classList.add('dark'); + await vi.waitFor(() => expect(StatusBar.setStyle).toHaveBeenLastCalledWith({ style: Style.Dark })); + }); + + it('hides the keyboard accessory bar on iOS only', () => { + startNativeApp(); + expect(Keyboard.setAccessoryBarVisible).not.toHaveBeenCalled(); + vi.mocked(isNativeIos).mockReturnValue(true); + startNativeApp(); + expect(Keyboard.setAccessoryBarVisible).toHaveBeenCalledWith({ isVisible: false }); + }); + + it('refreshes the offline start on iOS once the first screen has settled', () => { + vi.mocked(isNativeIos).mockReturnValue(true); + startNativeApp(); + expect(keepOfflineShellFresh).not.toHaveBeenCalled(); + vi.advanceTimersByTime(15_000); + expect(keepOfflineShellFresh).toHaveBeenCalled(); + }); + + it('skips the refresh while offline, and never on Android', () => { + vi.mocked(isNativeIos).mockReturnValue(true); + vi.mocked(isEffectivelyOffline).mockReturnValue(true); + startNativeApp(); + vi.advanceTimersByTime(15_000); + expect(keepOfflineShellFresh).not.toHaveBeenCalled(); + + vi.mocked(isNativeIos).mockReturnValue(false); + vi.mocked(isEffectivelyOffline).mockReturnValue(false); + startNativeApp(); + vi.advanceTimersByTime(15_000); + expect(keepOfflineShellFresh).not.toHaveBeenCalled(); + }); + + it('logs a failed refresh instead of throwing', async () => { + vi.mocked(isNativeIos).mockReturnValue(true); + vi.mocked(keepOfflineShellFresh).mockRejectedValue(new Error('down')); + const report = vi.fn(); + vi.stubGlobal('reportError', report); + startNativeApp(); + vi.advanceTimersByTime(15_000); + await vi.waitFor(() => expect(report).toHaveBeenCalledWith(expect.any(Error))); + vi.unstubAllGlobals(); + }); + + it('stays quiet when the installed app is older than the offline copy', async () => { + vi.mocked(isNativeIos).mockReturnValue(true); + vi.mocked(keepOfflineShellFresh).mockRejectedValue( + Object.assign(new Error('not implemented'), { code: 'UNIMPLEMENTED' }) + ); + const report = vi.fn(); + vi.stubGlobal('reportError', report); + startNativeApp(); + vi.advanceTimersByTime(15_000); + await vi.waitFor(() => expect(keepOfflineShellFresh).toHaveBeenCalled()); + // Let the rejection reach its handler. + await Promise.resolve(); + await Promise.resolve(); + await Promise.resolve(); + expect(report).not.toHaveBeenCalled(); + vi.unstubAllGlobals(); + }); +}); diff --git a/client/src/native/nativeApp.ts b/client/src/native/nativeApp.ts new file mode 100644 index 000000000..ba57310d6 --- /dev/null +++ b/client/src/native/nativeApp.ts @@ -0,0 +1,60 @@ +import { App } from '@capacitor/app'; +import { Keyboard } from '@capacitor/keyboard'; +import { SplashScreen } from '@capacitor/splash-screen'; +import { StatusBar, Style } from '@capacitor/status-bar'; +import { isEffectivelyOffline } from '../sync/networkMode'; +import { keepOfflineShellFresh } from './offlineShell'; +import { isNativeApp, isNativeIos } from './platform'; +import { reportNativeFailure } from './reportFailure'; +import { isUnimplemented } from './trekShell'; + +/** Long enough that the warm-up never competes with the first screen's requests. */ +const OFFLINE_SHELL_DELAY_MS = 15_000; + +/** + * What the UI does differently when it runs inside the iOS or Android app. + * Everything else is the same UI a browser gets from this server. + */ +export function startNativeApp(): void { + if (!isNativeApp()) return; + + followThemeInStatusBar(); + + // Android's back gesture: through the app's own history first, and only + // then out of the app, the way a browser tab would behave. + void App.addListener('backButton', ({ canGoBack }) => { + if (canGoBack) window.history.back(); + else void App.minimizeApp(); + }); + + requestAnimationFrame(() => { + void SplashScreen.hide(); + }); + + if (isNativeIos()) { + // The "‹ › Done" strip above the keyboard is a web form's, not an app's. + void Keyboard.setAccessoryBarVisible({ isVisible: false }); + window.setTimeout(() => { + if (isEffectivelyOffline()) return; + // Not refreshed this time is no harm: the next launch tries again. An app + // older than the offline copy has no such method, which is no failure. + keepOfflineShellFresh().catch((err: unknown) => { + if (!isUnimplemented(err)) reportNativeFailure(err); + }); + }, OFFLINE_SHELL_DELAY_MS); + } +} + +/** + * Light icons on the dark scheme and dark icons on the light one. Observing + * the class keeps applyAppearance() the only writer of , and it catches + * every way the scheme changes, including "follow the system". + */ +function followThemeInStatusBar(): void { + const root = document.documentElement; + const apply = (): void => { + void StatusBar.setStyle({ style: root.classList.contains('dark') ? Style.Dark : Style.Light }); + }; + apply(); + new MutationObserver(apply).observe(root, { attributes: true, attributeFilter: ['class'] }); +} diff --git a/client/src/native/nativeFiles.test.ts b/client/src/native/nativeFiles.test.ts new file mode 100644 index 000000000..ecf7df911 --- /dev/null +++ b/client/src/native/nativeFiles.test.ts @@ -0,0 +1,53 @@ +import { Directory, Filesystem } from '@capacitor/filesystem'; +import { Share } from '@capacitor/share'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { cacheFileName, fileNameFromUrl, shareFile } from './nativeFiles'; + +vi.mock('@capacitor/filesystem', () => ({ Directory: { Cache: 'CACHE' }, Filesystem: { writeFile: vi.fn() } })); +vi.mock('@capacitor/share', () => ({ Share: { share: vi.fn() } })); + +beforeEach(() => { + vi.mocked(Filesystem.writeFile).mockReset().mockResolvedValue({ uri: 'file:///cache/trip.pdf' }); + vi.mocked(Share.share).mockReset().mockResolvedValue({}); +}); + +describe('cacheFileName', () => { + it('keeps a readable name but nothing that could leave the cache directory', () => { + expect(cacheFileName('Lisbon 2026.pdf')).toBe('Lisbon 2026.pdf'); + expect(cacheFileName('../../etc/passwd')).toBe('_.._etc_passwd'); + expect(cacheFileName('a:b*c?"d"|f\u0001.txt')).toBe('a_b_c__d__e__f_.txt'); + expect(cacheFileName('...hidden')).toBe('hidden'); + expect(cacheFileName(' ')).toBe('download'); + }); +}); + +describe('fileNameFromUrl', () => { + it('takes the decoded last path segment', () => { + expect(fileNameFromUrl('/api/trips/1/files/42/Boarding%20pass.pdf?token=x')).toBe('Boarding pass.pdf'); + expect(fileNameFromUrl('/uploads/files/')).toBe('files'); + expect(fileNameFromUrl('/bad/%E0%A4%A')).toBe('%E0%A4%A'); + }); +}); + +describe('shareFile', () => { + it('writes the blob to the cache and hands it to the share sheet', async () => { + await shareFile(new Blob(['hello'], { type: 'text/plain' }), 'note.txt'); + + expect(Filesystem.writeFile).toHaveBeenCalledWith({ + path: 'note.txt', + data: btoa('hello'), + directory: Directory.Cache, + }); + expect(Share.share).toHaveBeenCalledWith({ files: ['file:///cache/trip.pdf'] }); + }); + + it('treats a dismissed sheet as the user changing their mind', async () => { + vi.mocked(Share.share).mockRejectedValue(new Error('Share canceled')); + await expect(shareFile(new Blob(['x']), 'x.txt')).resolves.toBeUndefined(); + }); + + it('passes a real failure on', async () => { + vi.mocked(Share.share).mockRejectedValue(new Error('No activity found')); + await expect(shareFile(new Blob(['x']), 'x.txt')).rejects.toThrow('No activity found'); + }); +}); diff --git a/client/src/native/nativeFiles.ts b/client/src/native/nativeFiles.ts new file mode 100644 index 000000000..a72b916ec --- /dev/null +++ b/client/src/native/nativeFiles.ts @@ -0,0 +1,49 @@ +import { Directory, Filesystem } from '@capacitor/filesystem'; +import { Share } from '@capacitor/share'; + +function toBase64(blob: Blob): Promise { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => resolve(String(reader.result).slice(String(reader.result).indexOf(',') + 1)); + reader.onerror = () => reject(reader.error); + reader.readAsDataURL(blob); + }); +} + +/** Readable, but safe as a single path segment inside the cache directory. */ +export function cacheFileName(filename: string): string { + const cleaned = Array.from(filename, (ch) => (ch.charCodeAt(0) < 32 || '\\/:*?"<>|'.includes(ch) ? '_' : ch)) + .join('') + .trim(); + return cleaned.replace(/^\.+/, '') || 'download'; +} + +export function fileNameFromUrl(url: string): string { + const [path = ''] = url.split('?', 1); + const last = path.split('/').filter(Boolean).pop() ?? ''; + try { + return decodeURIComponent(last); + } catch { + return last; + } +} + +/** + * The app's WebView cannot save a download on its own, so the file goes into + * the app's cache and from there into the system share sheet, which offers + * saving it to Files, opening it in another app or sending it on. + */ +export async function shareFile(blob: Blob, filename: string): Promise { + const { uri } = await Filesystem.writeFile({ + path: cacheFileName(filename), + data: await toBase64(blob), + directory: Directory.Cache, + }); + try { + await Share.share({ files: [uri] }); + } catch (err) { + // Dismissing the sheet rejects; that is the user's choice, not a failure. + if (/cancel/i.test(String((err as Error)?.message))) return; + throw err; + } +} diff --git a/client/src/native/offlineShell.test.ts b/client/src/native/offlineShell.test.ts new file mode 100644 index 000000000..2c479d514 --- /dev/null +++ b/client/src/native/offlineShell.test.ts @@ -0,0 +1,70 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { keepOfflineShellFresh, manifestFiles } from './offlineShell'; +import { TrekShell } from './trekShell'; + +vi.mock('./trekShell', () => ({ TrekShell: { refreshOfflineCopy: vi.fn() } })); + +const manifest = { + 'index.html': { + file: 'assets/index-a1b2c3d4.js', + css: ['assets/index-e5f6a7b8.css'], + assets: ['assets/poppins-11223344.woff2'], + }, + 'src/pages/AtlasPage.tsx': { file: 'assets/AtlasPage-99887766.js', css: ['assets/index-e5f6a7b8.css'] }, + _shared: { file: 'assets/shared-55443322.js', assets: 'not-a-list' }, + broken: null, +}; + +beforeEach(() => { + vi.mocked(TrekShell.refreshOfflineCopy).mockReset().mockResolvedValue({ saved: true }); +}); + +describe('manifestFiles', () => { + it('collects every chunk, stylesheet and asset once', () => { + expect(manifestFiles(manifest).sort()).toEqual([ + 'assets/AtlasPage-99887766.js', + 'assets/index-a1b2c3d4.js', + 'assets/index-e5f6a7b8.css', + 'assets/poppins-11223344.woff2', + 'assets/shared-55443322.js', + ]); + }); + + it('returns nothing for something that is not a manifest', () => { + expect(manifestFiles(null)).toEqual([]); + expect(manifestFiles('x')).toEqual([]); + }); +}); + +describe('keepOfflineShellFresh', () => { + it('refreshes the stored start page and fetches every file of the build', async () => { + const fetched: string[] = []; + const fetchImpl = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input); + if (url === '/asset-manifest.json') { + expect(init).toEqual({ cache: 'no-store' }); + return new Response(JSON.stringify(manifest)); + } + fetched.push(url); + if (url.includes('shared')) throw new Error('offline for a moment'); + return new Response('x'); + }) as unknown as typeof fetch; + + await keepOfflineShellFresh(fetchImpl); + + expect(TrekShell.refreshOfflineCopy).toHaveBeenCalled(); + expect(fetched.sort()).toEqual([ + '/assets/AtlasPage-99887766.js', + '/assets/index-a1b2c3d4.js', + '/assets/index-e5f6a7b8.css', + '/assets/poppins-11223344.woff2', + '/assets/shared-55443322.js', + ]); + }); + + it('stops after the start page when the build has no manifest', async () => { + const fetchImpl = vi.fn(async () => new Response('', { status: 404 })) as unknown as typeof fetch; + await keepOfflineShellFresh(fetchImpl); + expect(fetchImpl).toHaveBeenCalledTimes(1); + }); +}); diff --git a/client/src/native/offlineShell.ts b/client/src/native/offlineShell.ts new file mode 100644 index 000000000..f509ba160 --- /dev/null +++ b/client/src/native/offlineShell.ts @@ -0,0 +1,54 @@ +import { TrekShell } from './trekShell'; + +/** + * iOS only. WKWebView runs no service worker for a domain the app does not + * list at build time, so the app stands in for it: the native side keeps a + * copy of the start page (TrekShellPlugin.refreshOfflineCopy), and this pulls + * every chunk of the current build into WebKit's HTTP cache. The server marks + * them immutable, so a cold start without network can load the stored start + * page under the server's origin and find all its scripts, including the lazy + * routes nobody has opened yet. + */ + +const MANIFEST_URL = '/asset-manifest.json'; +const CONCURRENCY = 4; + +interface ManifestChunk { + file?: string; + css?: string[]; + assets?: string[]; +} + +export function manifestFiles(manifest: unknown): string[] { + if (typeof manifest !== 'object' || manifest === null) return []; + const files = new Set(); + for (const chunk of Object.values(manifest as Record)) { + if (typeof chunk?.file === 'string') files.add(chunk.file); + for (const list of [chunk?.css, chunk?.assets]) { + if (Array.isArray(list)) list.forEach((f) => typeof f === 'string' && files.add(f)); + } + } + return [...files]; +} + +async function warmCache(files: string[], fetchFile: (path: string) => Promise): Promise { + const queue = [...files]; + const worker = async (): Promise => { + for (let path = queue.shift(); path !== undefined; path = queue.shift()) { + try { + await fetchFile(`/${path}`); + } catch { + // One missing chunk must not stop the rest; the next launch tries again. + } + } + }; + await Promise.all(Array.from({ length: CONCURRENCY }, worker)); +} + +export async function keepOfflineShellFresh(fetchImpl: typeof fetch = fetch): Promise { + await TrekShell.refreshOfflineCopy(); + const response = await fetchImpl(MANIFEST_URL, { cache: 'no-store' }); + if (!response.ok) return; + const files = manifestFiles(await response.json()); + await warmCache(files, (path) => fetchImpl(path).then((r) => r.blob())); +} diff --git a/client/src/native/offlineTiles.test.ts b/client/src/native/offlineTiles.test.ts new file mode 100644 index 000000000..af235b99d --- /dev/null +++ b/client/src/native/offlineTiles.test.ts @@ -0,0 +1,183 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + fromOfflineUrl, + installOfflineProtocol, + offlineProtocol, + offlineStyle, + rewriteDocument, + toOfflineUrl, +} from './offlineTiles'; +import { isNativeIos } from './platform'; + +vi.mock('./platform', () => ({ isNativeIos: vi.fn() })); + +const cached = new Map(); +const cache = { match: vi.fn(async (url: string) => cached.get(url)?.clone()) }; + +beforeEach(() => { + cached.clear(); + vi.mocked(isNativeIos).mockReturnValue(true); + vi.stubGlobal('caches', { open: vi.fn(async () => cache) }); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +function params(url: string, type: 'json' | 'arrayBuffer' | 'image' | 'string') { + return { url, type }; +} + +describe('URL rewriting', () => { + it('moves https URLs onto the protocol and back, and leaves everything else', () => { + expect(toOfflineUrl('https://tiles.openfreemap.org/styles/positron')).toBe( + 'trek-offline://tiles.openfreemap.org/styles/positron' + ); + expect(fromOfflineUrl('trek-offline://tiles.openfreemap.org/styles/positron')).toBe( + 'https://tiles.openfreemap.org/styles/positron' + ); + expect(toOfflineUrl('mapbox://styles/mapbox/streets-v12')).toBe('mapbox://styles/mapbox/streets-v12'); + expect(fromOfflineUrl('https://x.test/a')).toBe('https://x.test/a'); + }); + + it('rewrites the style only inside the iOS app with Cache Storage', () => { + const style = 'https://tiles.openfreemap.org/styles/liberty?key=abc'; + expect(offlineStyle(style)).toBe('trek-offline://tiles.openfreemap.org/styles/liberty?key=abc'); + expect(offlineStyle({ version: 8 })).toEqual({ version: 8 }); + + vi.mocked(isNativeIos).mockReturnValue(false); + expect(offlineStyle(style)).toBe(style); + + vi.mocked(isNativeIos).mockReturnValue(true); + vi.stubGlobal('caches', undefined); + expect(offlineStyle(style)).toBe(style); + }); + + it('points sources, tiles, glyphs and sprites of a style at the protocol', () => { + expect( + rewriteDocument({ + version: 8, + glyphs: 'https://tiles.openfreemap.org/fonts/{fontstack}/{range}.pbf', + sprite: [{ id: 'default', url: 'https://tiles.openfreemap.org/sprites/ofm' }, 'odd'], + sources: { + openmaptiles: { type: 'vector', url: 'https://tiles.openfreemap.org/planet' }, + inline: { type: 'raster', tiles: ['https://a.test/{z}/{x}/{y}.png', 7] }, + broken: null, + }, + layers: [], + }) + ).toEqual({ + version: 8, + glyphs: 'trek-offline://tiles.openfreemap.org/fonts/{fontstack}/{range}.pbf', + sprite: [{ id: 'default', url: 'trek-offline://tiles.openfreemap.org/sprites/ofm' }, 'odd'], + sources: { + openmaptiles: { type: 'vector', url: 'trek-offline://tiles.openfreemap.org/planet' }, + inline: { type: 'raster', tiles: ['trek-offline://a.test/{z}/{x}/{y}.png', 7] }, + broken: null, + }, + layers: [], + }); + }); + + it('handles a TileJSON, a single sprite URL and things that are not documents', () => { + expect(rewriteDocument({ tiles: ['https://t.test/20250101/{z}/{x}/{y}.pbf'] })).toEqual({ + tiles: ['trek-offline://t.test/20250101/{z}/{x}/{y}.pbf'], + }); + expect(rewriteDocument({ sprite: 'https://s.test/sprite' })).toEqual({ sprite: 'trek-offline://s.test/sprite' }); + expect(rewriteDocument('x')).toBe('x'); + expect(rewriteDocument([1])).toEqual([1]); + }); +}); + +describe('offlineProtocol', () => { + it('answers a document from the network and rewrites it', async () => { + const fetchMock = vi.fn(async () => new Response(JSON.stringify({ tiles: ['https://t.test/{z}/{x}/{y}.pbf'] }))); + vi.stubGlobal('fetch', fetchMock); + const result = await offlineProtocol(params('trek-offline://t.test/planet', 'json'), new AbortController()); + expect(fetchMock).toHaveBeenCalledWith('https://t.test/planet', expect.objectContaining({ mode: 'cors' })); + expect(result.data).toEqual({ tiles: ['trek-offline://t.test/{z}/{x}/{y}.pbf'] }); + }); + + it('falls back to the cached document when the network is gone', async () => { + cached.set('https://t.test/style', new Response(JSON.stringify({ version: 8 }))); + vi.stubGlobal( + 'fetch', + vi.fn(async () => { + throw new TypeError('offline'); + }) + ); + const result = await offlineProtocol(params('trek-offline://t.test/style', 'json'), new AbortController()); + expect(result.data).toEqual({ version: 8 }); + }); + + it('serves tiles from the cache without asking the network', async () => { + cached.set('https://t.test/1/2/3.pbf', new Response(new Uint8Array([1, 2, 3]))); + const fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); + const result = await offlineProtocol( + params('trek-offline://t.test/1/2/3.pbf', 'arrayBuffer'), + new AbortController() + ); + expect(new Uint8Array(result.data as ArrayBuffer)).toEqual(new Uint8Array([1, 2, 3])); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('fetches an uncached tile, and returns text for string requests', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('hello')) + ); + const tile = await offlineProtocol(params('trek-offline://t.test/9/9/9.png', 'image'), new AbortController()); + expect(new TextDecoder().decode(tile.data as ArrayBuffer)).toBe('hello'); + const text = await offlineProtocol(params('trek-offline://t.test/a.txt', 'string'), new AbortController()); + expect(text.data).toBe('hello'); + }); + + it('fails loudly on an uncached tile offline or an HTTP error', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => { + throw new TypeError('offline'); + }) + ); + await expect( + offlineProtocol(params('trek-offline://t.test/0/0/0.pbf', 'arrayBuffer'), new AbortController()) + ).rejects.toThrow('offline'); + + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('nope', { status: 404 })) + ); + await expect( + offlineProtocol(params('trek-offline://t.test/0/0/0.pbf', 'arrayBuffer'), new AbortController()) + ).rejects.toThrow('HTTP 404'); + await expect(offlineProtocol(params('trek-offline://t.test/style', 'json'), new AbortController())).rejects.toThrow( + 'Not available offline' + ); + }); + + it('passes an abort straight through for documents', async () => { + const controller = new AbortController(); + controller.abort(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => { + throw new DOMException('aborted', 'AbortError'); + }) + ); + await expect(offlineProtocol(params('trek-offline://t.test/style', 'json'), controller)).rejects.toThrow('aborted'); + }); +}); + +describe('installOfflineProtocol', () => { + it('registers only inside the iOS app', () => { + const addProtocol = vi.fn(); + installOfflineProtocol({ addProtocol }); + expect(addProtocol).toHaveBeenCalledWith('trek-offline', offlineProtocol); + + addProtocol.mockClear(); + vi.mocked(isNativeIos).mockReturnValue(false); + installOfflineProtocol({ addProtocol }); + expect(addProtocol).not.toHaveBeenCalled(); + }); +}); diff --git a/client/src/native/offlineTiles.ts b/client/src/native/offlineTiles.ts new file mode 100644 index 000000000..9f3c2bd31 --- /dev/null +++ b/client/src/native/offlineTiles.ts @@ -0,0 +1,116 @@ +import type { AddProtocolAction, GetResourceResponse, RequestParameters } from 'maplibre-gl'; +import { VECTOR_CACHE } from '../sync/glPrefetcher'; +import { isNativeIos } from './platform'; + +/** + * Offline vector maps for the iOS app. + * + * In a browser the service worker answers MapLibre's requests from the + * 'gl-map-offline' cache that glPrefetcher fills for trips marked for offline. + * The iOS app has no service worker, so nothing reads that cache there. This + * protocol takes the service worker's place: the style URL is rewritten to + * trek-offline://, every https URL inside the style and its TileJSON gets the + * same scheme, and the handler serves them from the cache or the network. + * + * Mapbox GL has no protocol hook, so a Mapbox basemap stays online-only in + * the app. + */ + +const OFFLINE_SCHEME = 'trek-offline'; +const PREFIX = `${OFFLINE_SCHEME}://`; + +function offlineTilesActive(): boolean { + return isNativeIos() && typeof caches !== 'undefined'; +} + +export function toOfflineUrl(url: string): string { + return url.startsWith('https://') ? PREFIX + url.slice('https://'.length) : url; +} + +export function fromOfflineUrl(url: string): string { + return url.startsWith(PREFIX) ? 'https://' + url.slice(PREFIX.length) : url; +} + +/** The style URL to hand MapLibre: rewritten inside the iOS app, untouched anywhere else. */ +export function offlineStyle(style: T): T { + return offlineTilesActive() && typeof style === 'string' ? (toOfflineUrl(style) as T) : style; +} + +type Doc = Record; +/** What a protocol handler may hand MapLibre back. */ +type ProtocolData = Awaited>['data']; + +const isDoc = (value: unknown): value is Doc => typeof value === 'object' && value !== null && !Array.isArray(value); +const rewriteList = (value: unknown): unknown => + Array.isArray(value) ? value.map((v) => (typeof v === 'string' ? toOfflineUrl(v) : v)) : value; + +/** + * Points the URLs inside a style document or a TileJSON at the protocol, so + * that MapLibre asks this handler for the sprite, the glyphs, the TileJSON and + * the tiles as well, not only for the style. + */ +export function rewriteDocument(doc: unknown): unknown { + if (!isDoc(doc)) return doc; + const out: Doc = { ...doc }; + if ('tiles' in out) out.tiles = rewriteList(out.tiles); + if (typeof out.glyphs === 'string') out.glyphs = toOfflineUrl(out.glyphs); + if (typeof out.sprite === 'string') out.sprite = toOfflineUrl(out.sprite); + else if (Array.isArray(out.sprite)) { + out.sprite = out.sprite.map((entry) => + isDoc(entry) && typeof entry.url === 'string' ? { ...entry, url: toOfflineUrl(entry.url) } : entry + ); + } + if (isDoc(out.sources)) { + out.sources = Object.fromEntries( + Object.entries(out.sources).map(([id, source]) => { + if (!isDoc(source)) return [id, source]; + const rewritten: Doc = { ...source }; + if (typeof rewritten.url === 'string') rewritten.url = toOfflineUrl(rewritten.url); + if ('tiles' in rewritten) rewritten.tiles = rewriteList(rewritten.tiles); + return [id, rewritten]; + }) + ); + } + return out; +} + +/** + * Documents are asked of the network first so a changed style shows up, and + * fall back to the cache offline. Tiles, glyphs and sprites never change under + * their URL, so the cache goes first and saves the round trip. + */ +async function load(url: string, networkFirst: boolean, signal: AbortSignal): Promise { + const cache = await caches.open(VECTOR_CACHE); + if (!networkFirst) { + const cached = await cache.match(url); + if (cached) return cached; + } + try { + const response = await fetch(url, { mode: 'cors', signal }); + if (response.ok) return response; + if (!networkFirst) return response; + } catch (err) { + if (signal.aborted || !networkFirst) throw err; + } + const cached = await cache.match(url); + if (cached) return cached; + throw new Error(`Not available offline: ${url}`); +} + +export const offlineProtocol: AddProtocolAction = async ( + params: RequestParameters, + abortController: AbortController +): Promise> => { + const url = fromOfflineUrl(params.url); + const response = await load(url, params.type === 'json', abortController.signal); + if (!response.ok) throw new Error(`HTTP ${response.status} for ${url}`); + if (params.type === 'json') return { data: rewriteDocument(await response.json()) as ProtocolData }; + if (params.type === 'string') return { data: await response.text() }; + return { data: await response.arrayBuffer() }; +}; + +export function installOfflineProtocol(maplibre: { + addProtocol: (name: string, action: AddProtocolAction) => void; +}): void { + if (offlineTilesActive()) maplibre.addProtocol(OFFLINE_SCHEME, offlineProtocol); +} diff --git a/client/src/native/platform.test.ts b/client/src/native/platform.test.ts new file mode 100644 index 000000000..96a50ce77 --- /dev/null +++ b/client/src/native/platform.test.ts @@ -0,0 +1,33 @@ +import { Capacitor } from '@capacitor/core'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { isNativeApp, isNativeIos, nativeServerHost } from './platform'; + +vi.mock('@capacitor/core', () => ({ Capacitor: { isNativePlatform: vi.fn(), getPlatform: vi.fn() } })); + +beforeEach(() => { + vi.mocked(Capacitor.isNativePlatform).mockReturnValue(true); + vi.mocked(Capacitor.getPlatform).mockReturnValue('ios'); +}); + +describe('platform', () => { + it('tells the app from a browser', () => { + expect(isNativeApp()).toBe(true); + vi.mocked(Capacitor.isNativePlatform).mockReturnValue(false); + expect(isNativeApp()).toBe(false); + }); + + it('narrows to iOS', () => { + expect(isNativeIos()).toBe(true); + vi.mocked(Capacitor.getPlatform).mockReturnValue('android'); + expect(isNativeIos()).toBe(false); + vi.mocked(Capacitor.getPlatform).mockReturnValue('ios'); + vi.mocked(Capacitor.isNativePlatform).mockReturnValue(false); + expect(isNativeIos()).toBe(false); + }); + + it('names the server the WebView sits on, only inside the app', () => { + expect(nativeServerHost()).toBe(window.location.host); + vi.mocked(Capacitor.isNativePlatform).mockReturnValue(false); + expect(nativeServerHost()).toBeNull(); + }); +}); diff --git a/client/src/native/platform.ts b/client/src/native/platform.ts new file mode 100644 index 000000000..df1e5c5fd --- /dev/null +++ b/client/src/native/platform.ts @@ -0,0 +1,15 @@ +import { Capacitor } from '@capacitor/core'; + +/** True inside the iOS and Android apps, where the WebView shows this server's UI. */ +export function isNativeApp(): boolean { + return Capacitor.isNativePlatform(); +} + +export function isNativeIos(): boolean { + return isNativeApp() && Capacitor.getPlatform() === 'ios'; +} + +/** The server the app is connected to: the WebView sits on its origin. */ +export function nativeServerHost(): string | null { + return isNativeApp() ? window.location.host : null; +} diff --git a/client/src/native/reportFailure.test.ts b/client/src/native/reportFailure.test.ts new file mode 100644 index 000000000..3cf9dee12 --- /dev/null +++ b/client/src/native/reportFailure.test.ts @@ -0,0 +1,22 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { reportNativeFailure } from './reportFailure'; + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('reportNativeFailure', () => { + it('hands the failure to the page error event', () => { + const report = vi.fn(); + vi.stubGlobal('reportError', report); + const err = new Error('share failed'); + reportNativeFailure(err); + expect(report).toHaveBeenCalledWith(err); + }); + + it('does nothing where the runtime has no reportError', () => { + vi.stubGlobal('reportError', undefined); + expect(() => reportNativeFailure(new Error('x'))).not.toThrow(); + }); +}); diff --git a/client/src/native/reportFailure.ts b/client/src/native/reportFailure.ts new file mode 100644 index 000000000..f02396c61 --- /dev/null +++ b/client/src/native/reportFailure.ts @@ -0,0 +1,9 @@ +/** + * For the app's best-effort calls (a haptic tap, the offline start page, a + * share sheet): the failure is not worth a toast, but it must not vanish + * either. reportError() hands it to the page's error event, which + * utils/globalErrorHandlers.ts logs like any other uncaught error. + */ +export function reportNativeFailure(err: unknown): void { + if (typeof globalThis.reportError === 'function') globalThis.reportError(err); +} diff --git a/client/src/native/serverAddress.test.ts b/client/src/native/serverAddress.test.ts new file mode 100644 index 000000000..a66508093 --- /dev/null +++ b/client/src/native/serverAddress.test.ts @@ -0,0 +1,105 @@ +import { describe, expect, it, vi } from 'vitest'; +import { candidateUrls, probeDemo, probeServer, type ProbeResponse } from './serverAddress'; + +const features = ( + url: string, + data: unknown = { bookingImport: false, aiParsing: false, nativeApp: true } +): ProbeResponse => ({ status: 200, data, url }); + +describe('candidateUrls', () => { + it('tries https before http when no scheme was typed', () => { + expect(candidateUrls('trek.example.com')).toEqual(['https://trek.example.com', 'http://trek.example.com']); + expect(candidateUrls(' 192.168.1.10:3001/ ')).toEqual(['https://192.168.1.10:3001', 'http://192.168.1.10:3001']); + }); + + it('keeps an explicit scheme and path, without query, hash or trailing slashes', () => { + expect(candidateUrls('http://nas.local:3001/trek/?x=1#y')).toEqual(['http://nas.local:3001/trek']); + expect(candidateUrls('HTTPS://Trek.Example.com//')).toEqual(['https://trek.example.com']); + }); + + it('returns nothing for empty input or other schemes', () => { + expect(candidateUrls(' ')).toEqual([]); + expect(candidateUrls('ftp://trek.example.com')).toEqual([]); + expect(candidateUrls('javascript://alert(1)')).toEqual([]); + }); +}); + +describe('probeServer', () => { + it('accepts a server at the minimum native API version or above', async () => { + const data = { bookingImport: false, nativeApp: true, nativeApi: 1 }; + const get = vi.fn().mockResolvedValue(features('https://trek.example.com/api/health/features', data)); + expect(await probeServer('https://trek.example.com', get)).toEqual({ ok: true, url: 'https://trek.example.com' }); + }); + + it('calls a server below the minimum native API version too old', async () => { + const data = { bookingImport: false, nativeApp: true, nativeApi: 0 }; + const get = vi.fn().mockResolvedValue(features('https://trek.example.com/api/health/features', data)); + expect(await probeServer('https://trek.example.com', get)).toEqual({ ok: false, reason: 'tooOld' }); + }); + + it('accepts a server that reports nativeApp and follows its redirect', async () => { + const get = vi.fn().mockResolvedValue(features('https://trek.example.com/api/health/features')); + expect(await probeServer('http://trek.example.com', get)).toEqual({ ok: true, url: 'https://trek.example.com' }); + expect(get).toHaveBeenCalledWith('http://trek.example.com/api/health/features'); + }); + + it('falls back to the candidate itself when the final URL is not the probe path', async () => { + const get = vi.fn().mockResolvedValue(features('https://sso.example.com/login')); + expect(await probeServer('https://trek.example.com', get)).toEqual({ ok: true, url: 'https://trek.example.com' }); + }); + + it('moves on to plain http when https cannot be reached', async () => { + const get = vi + .fn() + .mockRejectedValueOnce(new Error('ECONNREFUSED')) + .mockResolvedValueOnce(features('http://192.168.1.10:3001/api/health/features')); + expect(await probeServer('192.168.1.10:3001', get)).toEqual({ ok: true, url: 'http://192.168.1.10:3001' }); + expect(get).toHaveBeenNthCalledWith(2, 'http://192.168.1.10:3001/api/health/features'); + }); + + it('names a TREK server without the native flag as too old', async () => { + const get = vi + .fn() + .mockResolvedValue( + features('https://old.example.com/api/health/features', { bookingImport: true, aiParsing: false }) + ); + expect(await probeServer('https://old.example.com', get)).toEqual({ ok: false, reason: 'tooOld' }); + }); + + it('tells a server that is not TREK apart from one that is not there', async () => { + const html = vi + .fn() + .mockResolvedValue({ status: 200, data: '', url: 'https://x.example.com/api/health/features' }); + expect(await probeServer('https://x.example.com', html)).toEqual({ ok: false, reason: 'notTrek' }); + + const missing = vi + .fn() + .mockResolvedValue({ status: 404, data: {}, url: 'https://x.example.com/api/health/features' }); + expect(await probeServer('https://x.example.com', missing)).toEqual({ ok: false, reason: 'notTrek' }); + + const down = vi.fn().mockRejectedValue(new Error('timeout')); + expect(await probeServer('x.example.com', down)).toEqual({ ok: false, reason: 'unreachable' }); + }); + + it('keeps the most telling failure across candidates', async () => { + const get = vi + .fn() + .mockResolvedValueOnce(features('https://nas.local/api/health/features', { bookingImport: false })) + .mockRejectedValueOnce(new Error('ECONNREFUSED')); + expect(await probeServer('nas.local', get)).toEqual({ ok: false, reason: 'tooOld' }); + }); + + it('refuses input that is not an address', async () => { + const get = vi.fn(); + expect(await probeServer('', get)).toEqual({ ok: false, reason: 'invalid' }); + expect(get).not.toHaveBeenCalled(); + }); +}); + +describe('probeDemo', () => { + it('probes the public demo server the address screen offers', async () => { + const get = vi.fn().mockResolvedValue(features('https://demo.liketrek.com/api/health/features')); + expect(await probeDemo(get)).toEqual({ ok: true, url: 'https://demo.liketrek.com' }); + expect(get).toHaveBeenCalledWith('https://demo.liketrek.com/api/health/features'); + }); +}); diff --git a/client/src/native/serverAddress.ts b/client/src/native/serverAddress.ts new file mode 100644 index 000000000..d2a51305f --- /dev/null +++ b/client/src/native/serverAddress.ts @@ -0,0 +1,92 @@ +import { DEMO_SERVER_URL } from './links'; + +/** + * Turns what someone typed into the app's address field into a TREK server it + * can load, or a reason it cannot. + */ + +export type ProbeFailure = 'invalid' | 'unreachable' | 'notTrek' | 'tooOld'; +type ProbeResult = { ok: true; url: string; reason?: undefined } | { ok: false; reason: ProbeFailure; url?: undefined }; + +export interface ProbeResponse { + status: number; + data: unknown; + /** The URL after redirects. */ + url: string; +} +export type ProbeGet = (url: string) => Promise; + +const FEATURES_PATH = '/api/health/features'; + +/** + * The oldest server API this app can work with (`nativeApi` in the features + * response). A server from before the field existed answers without it and is + * accepted while the minimum is 1. + */ +const MIN_NATIVE_API = 1; + +function normalize(raw: string): string | null { + let parsed: URL; + try { + parsed = new URL(raw); + } catch { + return null; + } + if ((parsed.protocol !== 'https:' && parsed.protocol !== 'http:') || !parsed.hostname) return null; + return parsed.origin + parsed.pathname.replace(/\/+$/, ''); +} + +/** + * Without a scheme, https comes first and plain http second: a server on the + * home network is often reached as a bare IP and port without TLS. + */ +export function candidateUrls(input: string): string[] { + const trimmed = input.trim(); + if (!trimmed) return []; + const candidates = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) + ? [normalize(trimmed)] + : [normalize(`https://${trimmed}`), normalize(`http://${trimmed}`)]; + return candidates.filter((url): url is string => url !== null); +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null; +} + +function judge(response: ProbeResponse): ProbeResult { + if (response.status !== 200 || !isRecord(response.data)) return { ok: false, reason: 'notTrek' }; + if (response.data.nativeApp === true) { + const api = response.data.nativeApi; + if (typeof api === 'number' && api < MIN_NATIVE_API) return { ok: false, reason: 'tooOld' }; + // Follow a redirect (http to https, a canonical host) so the app loads the + // address the server actually answers on. + const base = response.url.endsWith(FEATURES_PATH) ? response.url.slice(0, -FEATURES_PATH.length) : null; + return { ok: true, url: (base && normalize(base)) || '' }; + } + return 'bookingImport' in response.data ? { ok: false, reason: 'tooOld' } : { ok: false, reason: 'notTrek' }; +} + +const FAILURE_RANK: Record = { invalid: 0, unreachable: 1, notTrek: 2, tooOld: 3 }; + +export async function probeServer(input: string, get: ProbeGet): Promise { + const candidates = candidateUrls(input); + if (!candidates.length) return { ok: false, reason: 'invalid' }; + + let failure: ProbeFailure = 'unreachable'; + for (const candidate of candidates) { + let verdict: ProbeResult; + try { + verdict = judge(await get(candidate + FEATURES_PATH)); + } catch { + continue; + } + if (verdict.ok) return { ok: true, url: verdict.url || candidate }; + if (FAILURE_RANK[verdict.reason] > FAILURE_RANK[failure]) failure = verdict.reason; + } + return { ok: false, reason: failure }; +} + +/** The address screen's "Try the demo": the same probe, against the public demo server. */ +export function probeDemo(get: ProbeGet): Promise { + return probeServer(DEMO_SERVER_URL, get); +} diff --git a/client/src/native/trekShell.ts b/client/src/native/trekShell.ts new file mode 100644 index 000000000..548f12183 --- /dev/null +++ b/client/src/native/trekShell.ts @@ -0,0 +1,45 @@ +import { registerPlugin } from '@capacitor/core'; + +/** + * The app's own native plugin, implemented in + * ios/App/App/TrekShellPlugin.swift and + * android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java. + * + * The app is a frame around the UI the user's server delivers, so what the + * web side needs from it is small: which server that is, a way to change it, + * a system browser for the sign-ins a WebView cannot do, and on iOS the + * offline copy of the start page that stands in for the missing service + * worker. + */ +export interface TrekShellPlugin { + getServer(): Promise<{ url: string | null }>; + /** Remembers the server and loads it. The current page is gone afterwards. */ + setServer(options: { url: string }): Promise; + /** Forgets the server and returns to the address screen. */ + resetServer(): Promise; + /** Loads the remembered server again, after it could not be reached. */ + reload(): Promise; + /** + * Opens `url` in the system browser and resolves with the URL it was sent + * back to under `callbackScheme`. Rejects with code `CANCELLED` when the + * user closes the browser. + */ + authenticate(options: { url: string; callbackScheme: string }): Promise<{ url: string }>; + /** iOS: stores the server's start page for a cold start without network. */ + refreshOfflineCopy(): Promise<{ saved: boolean }>; + /** iOS: loads that copy under the server's origin. False when there is none. */ + openOfflineCopy(): Promise<{ opened: boolean }>; +} + +export const TrekShell = registerPlugin('TrekShell'); + +export const APP_URL_SCHEME = 'com.liketrek.trek'; + +/** + * True for the rejection Capacitor gives when the installed app has no such + * native method: the UI comes from the server, so a newer server can call into + * an app binary that predates the method. + */ +export function isUnimplemented(err: unknown): boolean { + return typeof err === 'object' && err !== null && (err as { code?: unknown }).code === 'UNIMPLEMENTED'; +} diff --git a/client/src/pages/LoginPage.tsx b/client/src/pages/LoginPage.tsx index 8b3cbfe67..5e0d8eae7 100644 --- a/client/src/pages/LoginPage.tsx +++ b/client/src/pages/LoginPage.tsx @@ -17,7 +17,7 @@ import ToggleSwitch from '../components/Settings/ToggleSwitch'; import { SUPPORTED_LANGUAGES, useTranslation } from '../i18n'; import { IDP_LOGIN_URL, useLogin } from './login/useLogin'; import LoginWorld from './login/LoginWorld'; -import { clearSignedOut } from '../utils/signedOut' +import NativeServerLink from './login/NativeServerLink'; import PasswordChecklist from '../components/shared/PasswordChecklist'; /** Fixed so the sky does not reshuffle on every render. */ @@ -85,9 +85,7 @@ export default function LoginPage(): React.ReactElement { configWait, idpSlow, idpName, - handleDemoLogin, - handleSubmit, - handlePasskeyLogin, + handleDemoLogin, handleSubmit, handlePasskeyLogin, handleSsoClick, } = useLogin(); const oidcButtonShown = !!(appConfig?.oidc_configured && appConfig?.oidc_login && !oidcOnly); @@ -490,7 +488,7 @@ export default function LoginPage(): React.ReactElement { {idpSlow && ( {t('login.oidcRedirectSlow', { name: idpName })} @@ -534,7 +532,7 @@ export default function LoginPage(): React.ReactElement {
)}
)} + diff --git a/client/src/pages/NativeHandoffPage.test.tsx b/client/src/pages/NativeHandoffPage.test.tsx new file mode 100644 index 000000000..9bf582e76 --- /dev/null +++ b/client/src/pages/NativeHandoffPage.test.tsx @@ -0,0 +1,55 @@ +// FE-NATIVE-HANDOFF-PAGE-001 to FE-NATIVE-HANDOFF-PAGE-004 +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen } from '../../tests/helpers/render'; +import NativeHandoffPage from './NativeHandoffPage'; +import { useNativeHandoff } from './nativeHandoff/useNativeHandoff'; + +vi.mock('./nativeHandoff/useNativeHandoff', () => ({ useNativeHandoff: vi.fn() })); + +const base = { + valid: true, + ready: true, + userName: 'maria', + status: 'idle' as const, + openApp: vi.fn(), + switchAccount: vi.fn(), +}; + +beforeEach(() => { + vi.mocked(useNativeHandoff).mockReturnValue({ ...base }); +}); + +describe('NativeHandoffPage', () => { + it('FE-NATIVE-HANDOFF-PAGE-001: asks before handing the session to the app', () => { + render(); + expect( + screen.getByText('You are signed in as maria. Open the TREK app to finish signing in there.') + ).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Open the TREK app' })); + expect(base.openApp).toHaveBeenCalled(); + fireEvent.click(screen.getByRole('button', { name: 'Use a different account' })); + expect(base.switchAccount).toHaveBeenCalled(); + }); + + it('FE-NATIVE-HANDOFF-PAGE-002: shows the failure and keeps the button while sending disabled', () => { + vi.mocked(useNativeHandoff).mockReturnValue({ ...base, status: 'failed' }); + const { rerender } = render(); + expect(screen.getByRole('alert')).toHaveTextContent('Signing in did not work. Please try again.'); + + vi.mocked(useNativeHandoff).mockReturnValue({ ...base, status: 'sending' }); + rerender(); + expect(screen.getByRole('button', { name: 'Open the TREK app' })).toBeDisabled(); + }); + + it('FE-NATIVE-HANDOFF-PAGE-003: spins while the session is being checked', () => { + vi.mocked(useNativeHandoff).mockReturnValue({ ...base, ready: false }); + render(); + expect(screen.queryByRole('button')).not.toBeInTheDocument(); + }); + + it('FE-NATIVE-HANDOFF-PAGE-004: says so when the link is broken', () => { + vi.mocked(useNativeHandoff).mockReturnValue({ ...base, valid: false, ready: false }); + render(); + expect(screen.getByText('Signing in did not work. Please try again.')).toBeInTheDocument(); + }); +}); diff --git a/client/src/pages/NativeHandoffPage.tsx b/client/src/pages/NativeHandoffPage.tsx new file mode 100644 index 000000000..706ebf7ba --- /dev/null +++ b/client/src/pages/NativeHandoffPage.tsx @@ -0,0 +1,53 @@ +import { Smartphone } from 'lucide-react'; +import { useTranslation } from '../i18n'; +import { useNativeHandoff } from './nativeHandoff/useNativeHandoff'; + +export default function NativeHandoffPage() { + const { t } = useTranslation(); + const { valid, ready, userName, status, openApp, switchAccount } = useNativeHandoff(); + + return ( +
+
+ + {!valid ? ( +

{t('native.login.failed')}

+ ) : !ready ? ( +
+ ) : ( + <> +

{t('native.handoff.title')}

+

{t('native.handoff.hint', { name: userName })}

+ {status === 'failed' && ( +

+ {t('native.login.failed')} +

+ )} + + + + )} +
+
+ ); +} diff --git a/client/src/pages/login/NativeServerLink.tsx b/client/src/pages/login/NativeServerLink.tsx new file mode 100644 index 000000000..fa68e15ee --- /dev/null +++ b/client/src/pages/login/NativeServerLink.tsx @@ -0,0 +1,18 @@ +import { useNativeServer } from '../../components/Settings/useNativeServer'; +import { useTranslation } from '../../i18n'; + +/** Inside the iOS/Android app only: the way from the sign-in screen back to the address screen. */ +export default function NativeServerLink() { + const { t } = useTranslation(); + const { host, changeServer } = useNativeServer(); + if (!host) return null; + return ( + + ); +} diff --git a/client/src/pages/login/useLogin.native.test.tsx b/client/src/pages/login/useLogin.native.test.tsx new file mode 100644 index 000000000..8930bacd7 --- /dev/null +++ b/client/src/pages/login/useLogin.native.test.tsx @@ -0,0 +1,136 @@ +// FE-LOGIN-NATIVE-001 to FE-LOGIN-NATIVE-006: useLogin inside the iOS/Android app +import { startAuthentication } from '@simplewebauthn/browser'; +import { http, HttpResponse } from 'msw'; +import React from 'react'; +import { MemoryRouter } from 'react-router'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { buildAppConfig } from '../../../tests/helpers/factories'; +import { server } from '../../../tests/helpers/msw/server'; +import { act, renderHook, waitFor } from '../../../tests/helpers/render'; +import { resetAllStores } from '../../../tests/helpers/store'; +import { TranslationProvider } from '../../i18n/TranslationContext'; +import { BrowserSignInCancelled, signInThroughBrowser } from '../../native/browserSignIn'; +import { useAuthStore } from '../../store/authStore'; +import { markSignedOut, wasSignedOut } from '../../utils/signedOut'; +import { useLogin } from './useLogin'; + +// Stable across renders: useLogin's config effect depends on navigate. +const mockNavigate = vi.fn(); +vi.mock('react-router', async () => { + const actual = await vi.importActual('react-router'); + return { ...actual, useNavigate: () => mockNavigate }; +}); +vi.mock('@simplewebauthn/browser', () => ({ startAuthentication: vi.fn() })); +vi.mock('../../native/platform', () => ({ isNativeApp: () => true })); +vi.mock('../../native/browserSignIn', async () => { + const actual = await vi.importActual('../../native/browserSignIn'); + return { ...actual, signInThroughBrowser: vi.fn() }; +}); + +const realLocation = window.location; +const loadUser = vi.fn(async () => {}); + +function renderLogin() { + return renderHook(() => useLogin(), { + wrapper: ({ children }: { children: React.ReactNode }) => ( + + {children} + + ), + }); +} + +function clickEvent() { + return { preventDefault: vi.fn() } as unknown as React.MouseEvent; +} + +beforeEach(() => { + resetAllStores(); + vi.mocked(signInThroughBrowser).mockReset(); + vi.mocked(startAuthentication).mockReset(); + loadUser.mockClear(); + useAuthStore.setState({ loadUser }); + Object.defineProperty(window, 'location', { + configurable: true, + writable: true, + value: { ...realLocation, pathname: '/login', href: 'http://localhost/login', search: '' }, + }); +}); + +afterEach(() => { + vi.useRealTimers(); + Object.defineProperty(window, 'location', { configurable: true, writable: true, value: realLocation }); +}); + +describe('useLogin in the native app', () => { + it('FE-LOGIN-NATIVE-001: remembers the login by default in the app', async () => { + const { result } = renderLogin(); + await waitFor(() => expect(result.current.appConfig).not.toBeNull()); + expect(result.current.rememberMe).toBe(true); + }); + + it('FE-LOGIN-NATIVE-002: does not bounce an OIDC-only install to the IdP inside the WebView', async () => { + server.use( + http.get('/api/auth/app-config', () => + HttpResponse.json(buildAppConfig({ password_login: false, oidc_configured: true, oidc_login: true })) + ) + ); + const { result } = renderLogin(); + await waitFor(() => expect(result.current.appConfig).not.toBeNull()); + expect(window.location.href).toBe('http://localhost/login'); + expect(result.current.oidcOnly).toBe(true); + }); + + it('FE-LOGIN-NATIVE-003: routes the SSO link through the system browser and signs in', async () => { + vi.mocked(signInThroughBrowser).mockResolvedValue(); + markSignedOut(); + const { result } = renderLogin(); + const event = clickEvent(); + + await act(async () => { + result.current.handleSsoClick(event); + }); + + expect(event.preventDefault).toHaveBeenCalled(); + expect(wasSignedOut()).toBe(false); + expect(signInThroughBrowser).toHaveBeenCalledWith('oidc'); + await waitFor(() => expect(loadUser).toHaveBeenCalledWith({ silent: true })); + await waitFor(() => expect(result.current.showTakeoff).toBe(true)); + }); + + it('FE-LOGIN-NATIVE-004: sends the passkey button to the browser instead of WebAuthn', async () => { + vi.mocked(signInThroughBrowser).mockResolvedValue(); + const { result } = renderLogin(); + + await act(async () => { + await result.current.handlePasskeyLogin(); + }); + + expect(signInThroughBrowser).toHaveBeenCalledWith(undefined); + expect(startAuthentication).not.toHaveBeenCalled(); + }); + + it('FE-LOGIN-NATIVE-005: stays quiet when the user closes the browser', async () => { + vi.mocked(signInThroughBrowser).mockRejectedValue(new BrowserSignInCancelled()); + const { result } = renderLogin(); + + await act(async () => { + await result.current.handlePasskeyLogin(); + }); + + expect(result.current.error).toBe(''); + expect(result.current.isLoading).toBe(false); + }); + + it('FE-LOGIN-NATIVE-006: explains a failed hand-off', async () => { + vi.mocked(signInThroughBrowser).mockRejectedValue(new Error('exchange failed')); + const { result } = renderLogin(); + + await act(async () => { + await result.current.handlePasskeyLogin(); + }); + + expect(result.current.error).toBe('Signing in did not work. Please try again.'); + expect(result.current.isLoading).toBe(false); + }); +}); diff --git a/client/src/pages/login/useLogin.ts b/client/src/pages/login/useLogin.ts index 2e0293a6a..e2aaa421f 100644 --- a/client/src/pages/login/useLogin.ts +++ b/client/src/pages/login/useLogin.ts @@ -4,11 +4,13 @@ import { useAuthStore } from '../../store/authStore' import { useSettingsStore, hasStoredLanguage } from '../../store/settingsStore' import { useTranslation, detectBrowserLanguage } from '../../i18n' import { startAuthentication } from '@simplewebauthn/browser' -import { wasSignedOut } from '../../utils/signedOut' +import { clearSignedOut, wasSignedOut } from '../../utils/signedOut' import { authApi, configApi } from '../../api/client' import { getApiErrorMessage } from '../../types' import { START_DESTINATION_ROUTE } from '../../utils/startDestination' import { passwordErrorKey } from '../../utils/passwordError' +import { isNativeApp } from '../../native/platform' +import { BrowserSignInCancelled, signInThroughBrowser, type BrowserSignInStart } from '../../native/browserSignIn' interface AppConfig { has_users: boolean @@ -59,7 +61,10 @@ export function useLogin() { const [username, setUsername] = useState('') const [email, setEmail] = useState('') const [password, setPassword] = useState('') - const [rememberMe, setRememberMe] = useState(false) + // On by default in the app: a session cookie there dies with the app process, + // and nobody expects to sign in again every time the phone unloads an app. + const [rememberMe, setRememberMe] = useState(isNativeApp) + const [nativeApp] = useState(isNativeApp) const [showPassword, setShowPassword] = useState(false) const [isLoading, setIsLoading] = useState(false) const [error, setError] = useState('') @@ -75,7 +80,7 @@ export function useLogin() { const [cachedConfig] = useState(readCachedConfig) const [expectRedirect] = useState(() => { const params = new URLSearchParams(window.location.search) - return isOidcOnly(cachedConfig) && !!cachedConfig?.has_users + return !isNativeApp() && isOidcOnly(cachedConfig) && !!cachedConfig?.has_users && !params.get('invite') && !params.get('oidc_code') && !params.get('oidc_error') }) const [idpRedirect, setIdpRedirect] = useState(false) @@ -183,7 +188,9 @@ export function useLogin() { if (!config.has_users) setMode('register') // Skip auto-redirect when config is from cache — network is unreliable // and auto-redirecting to the IdP could loop if the proxy changed. - if (allowRedirect && !fromCache && isOidcOnly(config) && config.has_users && !invite && !noRedirect) { + // Not in the app: its WebView cannot host the IdP, and opening the + // system browser uninvited on every launch would be worse than a button. + if (allowRedirect && !fromCache && !nativeApp && isOidcOnly(config) && config.has_users && !invite && !noRedirect) { setIdpRedirect(true) window.location.href = IDP_LOGIN_URL } @@ -248,7 +255,7 @@ export function useLogin() { } loadConfig(true) - }, [navigate, t, noRedirect]) + }, [navigate, t, noRedirect, nativeApp]) // Language detection chain (runs once on mount, only if user has no saved preference): // 1. localStorage → already in store initial state, skip @@ -289,7 +296,30 @@ export function useLogin() { } } + /** In the app: SSO and passkeys run in the system browser (native/browserSignIn.ts). */ + const handleBrowserSignIn = async (start?: BrowserSignInStart): Promise => { + setError('') + setIsLoading(true) + try { + await signInThroughBrowser(start) + await loadUser({ silent: true }) + takeOff() + } catch (err: unknown) { + if (!(err instanceof BrowserSignInCancelled)) setError(t('native.login.failed')) + setIsLoading(false) + } + } + + /** The SSO links: a plain navigation in a browser, the system browser in the app. */ + const handleSsoClick = (e: React.MouseEvent): void => { + clearSignedOut() + if (!nativeApp) return + e.preventDefault() + void handleBrowserSignIn('oidc') + } + const handlePasskeyLogin = async (): Promise => { + if (nativeApp) return handleBrowserSignIn() setError('') setIsLoading(true) try { @@ -393,5 +423,6 @@ export function useLogin() { noRedirect, showRegisterOption, oidcOnly, redirectScreen, configWait, idpSlow, idpName, handleDemoLogin, handleSubmit, handlePasskeyLogin, + handleSsoClick, } } diff --git a/client/src/pages/nativeHandoff/useNativeHandoff.test.tsx b/client/src/pages/nativeHandoff/useNativeHandoff.test.tsx new file mode 100644 index 000000000..58a2bae6a --- /dev/null +++ b/client/src/pages/nativeHandoff/useNativeHandoff.test.tsx @@ -0,0 +1,132 @@ +// FE-NATIVE-HANDOFF-001 to FE-NATIVE-HANDOFF-008 +import React from 'react'; +import { MemoryRouter } from 'react-router'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, renderHook, waitFor } from '../../../tests/helpers/render'; +import { resetAllStores } from '../../../tests/helpers/store'; +import { requestHandoffCode } from '../../native/browserSignIn'; +import { useAuthStore } from '../../store/authStore'; +import { useNativeHandoff } from './useNativeHandoff'; + +const mockNavigate = vi.fn(); +vi.mock('react-router', async () => { + const actual = await vi.importActual('react-router'); + return { ...actual, useNavigate: () => mockNavigate }; +}); +vi.mock('../../native/browserSignIn', () => ({ HANDOFF_PATH: '/native-handoff', requestHandoffCode: vi.fn() })); + +const challenge = 'ab'.repeat(32); +const realLocation = window.location; +const logout = vi.fn(async () => {}); + +function setSearch(search: string) { + Object.defineProperty(window, 'location', { + configurable: true, + writable: true, + value: { ...realLocation, search, href: 'http://localhost/native-handoff' + search, replace: vi.fn() }, + }); +} + +function renderHandoff() { + return renderHook(() => useNativeHandoff(), { + wrapper: ({ children }: { children: React.ReactNode }) => {children}, + }); +} + +beforeEach(() => { + resetAllStores(); + mockNavigate.mockClear(); + logout.mockClear(); + vi.mocked(requestHandoffCode).mockReset(); + sessionStorage.clear(); + setSearch(`?challenge=${challenge}`); + useAuthStore.setState({ + isLoading: false, + isAuthenticated: true, + user: { id: 1, username: 'maria' } as never, + logout, + }); +}); + +afterEach(() => { + Object.defineProperty(window, 'location', { configurable: true, writable: true, value: realLocation }); +}); + +describe('useNativeHandoff', () => { + it('FE-NATIVE-HANDOFF-001: is ready for a signed-in user with a valid challenge', () => { + const { result } = renderHandoff(); + expect(result.current.valid).toBe(true); + expect(result.current.ready).toBe(true); + expect(result.current.userName).toBe('maria'); + expect(mockNavigate).not.toHaveBeenCalled(); + }); + + it('FE-NATIVE-HANDOFF-002: rejects a malformed challenge and does nothing with it', () => { + setSearch('?challenge=nope'); + useAuthStore.setState({ isAuthenticated: false }); + const { result } = renderHandoff(); + expect(result.current.valid).toBe(false); + expect(result.current.ready).toBe(false); + expect(mockNavigate).not.toHaveBeenCalled(); + }); + + it('FE-NATIVE-HANDOFF-003: sends a visitor to the login page and back here afterwards', () => { + useAuthStore.setState({ isAuthenticated: false }); + renderHandoff(); + expect(mockNavigate).toHaveBeenCalledWith( + `/login?redirect=${encodeURIComponent(`/native-handoff?challenge=${challenge}`)}`, + { replace: true } + ); + }); + + it('FE-NATIVE-HANDOFF-004: starts SSO straight away when the app asked for it, without looping', () => { + setSearch(`?challenge=${challenge}&start=oidc`); + useAuthStore.setState({ isAuthenticated: false }); + renderHandoff(); + expect(window.location.replace).toHaveBeenCalledWith('/api/auth/oidc/login?remember=1'); + expect(sessionStorage.getItem('oidc_redirect')).toBe(`/native-handoff?challenge=${challenge}`); + }); + + it('FE-NATIVE-HANDOFF-005: waits while the session is still being checked', () => { + useAuthStore.setState({ isAuthenticated: false, isLoading: true }); + const { result } = renderHandoff(); + expect(result.current.ready).toBe(false); + expect(mockNavigate).not.toHaveBeenCalled(); + }); + + it('FE-NATIVE-HANDOFF-006: only mints the code on the tap, then hands it to the app scheme', async () => { + vi.mocked(requestHandoffCode).mockResolvedValue('c/1'); + const { result } = renderHandoff(); + expect(requestHandoffCode).not.toHaveBeenCalled(); + + await act(async () => { + await result.current.openApp(); + }); + + expect(requestHandoffCode).toHaveBeenCalledWith(challenge); + expect(window.location.href).toBe('com.liketrek.trek://auth?code=c%2F1'); + }); + + it('FE-NATIVE-HANDOFF-007: reports a failed hand-off', async () => { + vi.mocked(requestHandoffCode).mockRejectedValue(new Error('401')); + const { result } = renderHandoff(); + await act(async () => { + await result.current.openApp(); + }); + expect(result.current.status).toBe('failed'); + }); + + it('FE-NATIVE-HANDOFF-008: lets the user switch accounts and come back', async () => { + const { result } = renderHandoff(); + await act(async () => { + await result.current.switchAccount(); + }); + expect(logout).toHaveBeenCalled(); + await waitFor(() => + expect(mockNavigate).toHaveBeenCalledWith( + `/login?redirect=${encodeURIComponent(`/native-handoff?challenge=${challenge}`)}`, + { replace: true } + ) + ); + }); +}); diff --git a/client/src/pages/nativeHandoff/useNativeHandoff.ts b/client/src/pages/nativeHandoff/useNativeHandoff.ts new file mode 100644 index 000000000..4acd2df09 --- /dev/null +++ b/client/src/pages/nativeHandoff/useNativeHandoff.ts @@ -0,0 +1,67 @@ +import { useEffect, useState } from 'react'; +import { useNavigate } from 'react-router'; +import { useShallow } from 'zustand/react/shallow'; +import { HANDOFF_PATH, requestHandoffCode } from '../../native/browserSignIn'; +import { APP_URL_SCHEME } from '../../native/trekShell'; +import { useAuthStore } from '../../store/authStore'; + +const CHALLENGE = /^[0-9a-f]{64}$/; + +/** + * The system-browser end of the app's sign-in (see native/browserSignIn.ts). + * Signs the user in here if needed, then hands the session to the app only + * after an explicit tap: a link to this page with somebody else's challenge + * must not be able to pass a session on silently. + */ +export function useNativeHandoff() { + const navigate = useNavigate(); + const { isAuthenticated, isLoading, userName, logout } = useAuthStore( + useShallow((s) => ({ + isAuthenticated: s.isAuthenticated, + isLoading: s.isLoading, + userName: s.user?.username ?? '', + logout: s.logout, + })) + ); + const [params] = useState(() => new URLSearchParams(window.location.search)); + const challenge = params.get('challenge') ?? ''; + const valid = CHALLENGE.test(challenge); + const [status, setStatus] = useState<'idle' | 'sending' | 'failed'>('idle'); + + // Back here once signed in, without `start`, so an SSO round trip cannot loop. + const returnPath = `${HANDOFF_PATH}?challenge=${challenge}`; + + useEffect(() => { + if (!valid || isLoading || isAuthenticated) return; + if (params.get('start') === 'oidc') { + sessionStorage.setItem('oidc_redirect', returnPath); + window.location.replace('/api/auth/oidc/login?remember=1'); + return; + } + void navigate(`/login?redirect=${encodeURIComponent(returnPath)}`, { replace: true }); + }, [valid, isLoading, isAuthenticated, params, returnPath, navigate]); + + const openApp = async (): Promise => { + setStatus('sending'); + try { + const code = await requestHandoffCode(challenge); + window.location.href = `${APP_URL_SCHEME}://auth?code=${encodeURIComponent(code)}`; + } catch { + setStatus('failed'); + } + }; + + const switchAccount = async (): Promise => { + await logout(); + void navigate(`/login?redirect=${encodeURIComponent(returnPath)}`, { replace: true }); + }; + + return { + valid, + ready: valid && !isLoading && isAuthenticated, + userName, + status, + openApp, + switchAccount, + }; +} diff --git a/client/src/sync/glPrefetcher.ts b/client/src/sync/glPrefetcher.ts index af1daf568..be9e0090b 100644 --- a/client/src/sync/glPrefetcher.ts +++ b/client/src/sync/glPrefetcher.ts @@ -35,7 +35,7 @@ const CONCURRENCY = 6 const MAX_VECTOR_TILES = 2000 /** Workbox runtime cache for the vector basemap (see vite.config.js). */ -const VECTOR_CACHE = 'gl-map-offline' +export const VECTOR_CACHE = 'gl-map-offline' /** * Latin glyph ranges. A label needs the range its codepoints fall in, and Latin diff --git a/client/src/utils/donations.test.ts b/client/src/utils/donations.test.ts new file mode 100644 index 000000000..612b428b8 --- /dev/null +++ b/client/src/utils/donations.test.ts @@ -0,0 +1,51 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { isNativeApp } from '../native/platform'; +import { donationsShown, isDonationLink, noticeAsksForDonation, withoutDonationsInApp } from './donations'; + +vi.mock('../native/platform', () => ({ isNativeApp: vi.fn() })); + +const links = [{ href: 'https://ko-fi.com/mauriceboe' }, { href: 'https://discord.gg/x' }]; + +beforeEach(() => { + vi.mocked(isNativeApp).mockReturnValue(false); +}); + +describe('isDonationLink', () => { + it('knows the donation pages, their subdomains too', () => { + expect(isDonationLink('https://ko-fi.com/mauriceboe')).toBe(true); + expect(isDonationLink('https://www.BuyMeACoffee.com/mauriceboe')).toBe(true); + }); + + it('is false for anything else, a missing href or one that is no URL', () => { + expect(isDonationLink('https://github.com/liketrek/TREK')).toBe(false); + expect(isDonationLink('https://notko-fi.com/x')).toBe(false); + expect(isDonationLink(undefined)).toBe(false); + expect(isDonationLink('not a url')).toBe(false); + }); +}); + +describe('in a browser', () => { + it('keeps every link and every notice', () => { + expect(donationsShown()).toBe(true); + expect(withoutDonationsInApp(links)).toEqual(links); + }); +}); + +describe('in the native app', () => { + it('drops the donation links', () => { + vi.mocked(isNativeApp).mockReturnValue(true); + expect(donationsShown()).toBe(false); + expect(withoutDonationsInApp(links)).toEqual([{ href: 'https://discord.gg/x' }]); + }); +}); + +describe('noticeAsksForDonation', () => { + it('looks at both buttons', () => { + expect(noticeAsksForDonation({ cta: { kind: 'link', href: 'https://ko-fi.com/x' } })).toBe(true); + expect(noticeAsksForDonation({ secondaryCta: { kind: 'link', href: 'https://buymeacoffee.com/x' } })).toBe(true); + expect(noticeAsksForDonation({ cta: { kind: 'nav', href: '/settings' }, secondaryCta: null })).toBe(false); + expect(noticeAsksForDonation({ cta: { kind: 'action' } })).toBe(false); + expect(noticeAsksForDonation({})).toBe(false); + }); +}); diff --git a/client/src/utils/donations.ts b/client/src/utils/donations.ts new file mode 100644 index 000000000..41da203ff --- /dev/null +++ b/client/src/utils/donations.ts @@ -0,0 +1,38 @@ +import { isNativeApp } from '../native/platform'; + +/** Where the project takes donations. */ +const DONATION_HOSTS = ['ko-fi.com', 'buymeacoffee.com']; + +/** Whether `href` points at one of the project's donation pages. */ +export function isDonationLink(href: string | undefined): boolean { + if (!href) return false; + let host: string; + try { + host = new URL(href).hostname.toLowerCase(); + } catch { + return false; + } + return DONATION_HOSTS.some((d) => host === d || host.endsWith(`.${d}`)); +} + +/** + * Whether the donation links may show. Not inside the iOS and Android apps: + * the store rules on payments (Apple 3.1.1, Google Play's Payments policy) + * allow no link to an outside payment page there. A browser keeps them. + */ +export function donationsShown(): boolean { + return !isNativeApp(); +} + +/** `links` without the donation pages inside the native apps, unchanged anywhere else. */ +export function withoutDonationsInApp(links: T[]): T[] { + return donationsShown() ? links : links.filter((link) => !isDonationLink(link.href)); +} + +/** A notice button: a link or a navigation carries an href, an action does not. */ +type NoticeButton = { kind: string; href?: string } | null | undefined; + +/** Whether a system notice asks for a donation through one of its buttons. */ +export function noticeAsksForDonation(notice: { cta?: NoticeButton; secondaryCta?: NoticeButton }): boolean { + return isDonationLink(notice.cta?.href) || isDonationLink(notice.secondaryCta?.href); +} diff --git a/client/src/utils/fileDownload.ts b/client/src/utils/fileDownload.ts index 48c1fab70..cf41f732d 100644 --- a/client/src/utils/fileDownload.ts +++ b/client/src/utils/fileDownload.ts @@ -1,6 +1,9 @@ import { getCachedBlob } from '../db/offlineDb' import { isEffectivelyOffline } from '../sync/networkMode' import { isIosStandalone } from './iosDevice' +import { isNativeApp } from '../native/platform' +import { fileNameFromUrl, shareFile } from '../native/nativeFiles' +import { reportNativeFailure } from '../native/reportFailure' // MIME types safe to open inline (will not execute script in any browser). // Everything else (text/html, image/svg+xml, text/javascript, …) is forced to @@ -74,6 +77,10 @@ async function getFileBlob(url: string): Promise { * in the same tick can abort the download in other browsers. */ export function downloadBlob(blob: Blob, filename: string): void { + if (isNativeApp()) { + shareFile(blob, filename).catch(reportNativeFailure) + return + } const blobUrl = URL.createObjectURL(blob) triggerAnchorDownload(blobUrl, filename) } @@ -87,6 +94,7 @@ export function downloadBlob(blob: Blob, filename: string): void { */ export async function downloadFile(url: string, filename?: string): Promise { const blob = await getFileBlob(url) + if (isNativeApp()) return shareFile(blob, filename ?? fileNameFromUrl(url)) const blobUrl = URL.createObjectURL(blob) triggerAnchorDownload(blobUrl, filename) } @@ -110,6 +118,9 @@ export async function downloadFile(url: string, filename?: string): Promise { const blob = await getFileBlob(url) + // The share sheet previews PDFs and images too, and a blob tab has nowhere + // to open inside the app. + if (isNativeApp()) return shareFile(blob, filename ?? fileNameFromUrl(url)) const blobUrl = URL.createObjectURL(blob) // Force download for MIME types that can execute script when rendered inline diff --git a/client/tests/unit/mobile/settings/MSettingsAccount.test.tsx b/client/tests/unit/mobile/settings/MSettingsAccount.test.tsx index 1a662082f..72da1b52d 100644 --- a/client/tests/unit/mobile/settings/MSettingsAccount.test.tsx +++ b/client/tests/unit/mobile/settings/MSettingsAccount.test.tsx @@ -641,7 +641,7 @@ describe('MSettingsAccount – backup codes', () => { expect(createObjectURL).toHaveBeenCalledWith(expect.any(Blob)); expect(downloadName).toBe('trek-mfa-backup-codes.txt'); - expect(revokeObjectURL).toHaveBeenCalledWith('blob:codes'); + await waitFor(() => expect(revokeObjectURL).toHaveBeenCalledWith('blob:codes')); expect(document.querySelector('a[download]')).toBeNull(); createObjectURL.mockRestore(); diff --git a/client/tests/unit/native/donations.native.test.tsx b/client/tests/unit/native/donations.native.test.tsx new file mode 100644 index 000000000..d816950e9 --- /dev/null +++ b/client/tests/unit/native/donations.native.test.tsx @@ -0,0 +1,94 @@ +// FE-NATIVE-DONATIONS-001 to FE-NATIVE-DONATIONS-005 +// Inside the iOS and Android apps no screen links to a donation page: the store +// rules on payments (Apple 3.1.1, Google Play Payments) allow no outside payment +// link there. Every place that shows one is rendered here with the app mocked in. +import { http, HttpResponse } from 'msw'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import GitHubPanel from '../../../src/components/Admin/GitHubPanel'; +import AboutTab from '../../../src/components/Settings/AboutTab'; +import { SystemNoticeHost } from '../../../src/components/SystemNotices/SystemNoticeHost'; +import MAdminGitHubPanel from '../../../src/mobile/screens/admin/MAdminGitHubPanel'; +import MSettingsAbout from '../../../src/mobile/screens/settings/MSettingsAbout'; +import { useSystemNoticeStore, type SystemNoticeDTO } from '../../../src/store/systemNoticeStore'; +import { server } from '../../helpers/msw/server'; +import { render, screen, waitFor } from '../../helpers/render'; +import { resetAllStores } from '../../helpers/store'; + +vi.mock('../../../src/native/platform', () => ({ + isNativeApp: () => true, + isNativeIos: () => false, + nativeServerHost: () => 'trek.example.com', +})); +vi.mock('../../../src/components/SystemNotices/SystemNoticeModal.js', () => ({ + ModalRenderer: ({ notices }: { notices: SystemNoticeDTO[] }) => ( +
{notices.map((n) => n.id).join(',')}
+ ), +})); +vi.mock('../../../src/components/SystemNotices/SystemNoticeBanner.js', () => ({ + BannerRenderer: ({ notices }: { notices: SystemNoticeDTO[] }) => ( +
{notices.map((n) => n.id).join(',')}
+ ), + ToastRenderer: () => null, +})); + +function donationLinks(): Element[] { + return Array.from(document.querySelectorAll('a[href]')).filter((a) => + /ko-fi\.com|buymeacoffee\.com/.test(a.getAttribute('href') ?? '') + ); +} + +beforeEach(() => { + resetAllStores(); + server.use(http.get('/api/admin/github-releases', () => HttpResponse.json([]))); +}); + +afterEach(() => { + server.resetHandlers(); +}); + +describe('donation links inside the native app', () => { + it('FE-NATIVE-DONATIONS-001: the desktop About tab shows none, but keeps the community links', () => { + render(); + expect(donationLinks()).toEqual([]); + expect(screen.getByText('Discord')).toBeInTheDocument(); + }); + + it('FE-NATIVE-DONATIONS-002: the phone About section shows none', () => { + render(); + expect(donationLinks()).toEqual([]); + expect(screen.getByText('Wiki')).toBeInTheDocument(); + }); + + it('FE-NATIVE-DONATIONS-003: the desktop admin GitHub panel shows none', async () => { + render(); + await waitFor(() => expect(screen.getByText('Discord')).toBeInTheDocument()); + expect(donationLinks()).toEqual([]); + }); + + it('FE-NATIVE-DONATIONS-004: the phone admin GitHub panel shows none', async () => { + render(); + await waitFor(() => expect(screen.getByText('Discord')).toBeInTheDocument()); + expect(donationLinks()).toEqual([]); + }); + + it('FE-NATIVE-DONATIONS-005: a system notice asking for a donation stays hidden, any other one shows', () => { + const base = { display: 'banner', severity: 'info', titleKey: 'Title', bodyKey: 'Body', dismissible: true }; + useSystemNoticeStore.setState({ + loaded: true, + fetching: false, + notices: [ + { + ...base, + id: 'support', + cta: { kind: 'link', labelKey: 'Coffee', href: 'https://buymeacoffee.com/mauriceboe' }, + secondaryCta: { kind: 'link', labelKey: 'Ko-fi', href: 'https://ko-fi.com/mauriceboe' }, + }, + { ...base, id: 'maintenance' }, + ] as unknown as SystemNoticeDTO[], + }); + render(); + expect(screen.getByTestId('banners')).toHaveTextContent('maintenance'); + expect(screen.getByTestId('banners')).not.toHaveTextContent('support'); + }); +}); diff --git a/client/tests/unit/utils/fileDownload.native.test.ts b/client/tests/unit/utils/fileDownload.native.test.ts new file mode 100644 index 000000000..203f0b771 --- /dev/null +++ b/client/tests/unit/utils/fileDownload.native.test.ts @@ -0,0 +1,49 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { shareFile } from '../../../src/native/nativeFiles'; +import { downloadBlob, downloadFile, openFile } from '../../../src/utils/fileDownload'; + +vi.mock('../../../src/db/offlineDb', () => ({ getCachedBlob: vi.fn() })); +vi.mock('../../../src/native/platform', () => ({ isNativeApp: () => true })); +vi.mock('../../../src/native/nativeFiles', async () => { + const actual = await vi.importActual( + '../../../src/native/nativeFiles' + ); + return { ...actual, shareFile: vi.fn() }; +}); + +const pdf = new Blob(['%PDF'], { type: 'application/pdf' }); + +beforeEach(() => { + vi.mocked(shareFile).mockReset().mockResolvedValue(); + vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, status: 200, blob: () => Promise.resolve(pdf) })); +}); + +describe('fileDownload inside the native app', () => { + it('hands an in-memory blob to the share sheet instead of an anchor', () => { + const click = vi.spyOn(HTMLAnchorElement.prototype, 'click'); + downloadBlob(pdf, 'report.pdf'); + expect(shareFile).toHaveBeenCalledWith(pdf, 'report.pdf'); + expect(click).not.toHaveBeenCalled(); + }); + + it('logs a share that failed rather than losing it', async () => { + const report = vi.fn(); + vi.stubGlobal('reportError', report); + vi.mocked(shareFile).mockRejectedValue(new Error('no space')); + downloadBlob(pdf, 'report.pdf'); + await vi.waitFor(() => expect(report).toHaveBeenCalledWith(expect.any(Error))); + }); + + it('shares a protected file under its given name, or the one from its URL', async () => { + await downloadFile('/api/trips/1/files/2/download', 'Boarding pass.pdf'); + expect(shareFile).toHaveBeenLastCalledWith(pdf, 'Boarding pass.pdf'); + + await downloadFile('/uploads/files/ticket%20A.pdf'); + expect(shareFile).toHaveBeenLastCalledWith(pdf, 'ticket A.pdf'); + }); + + it('opens files through the share sheet too, since there is no tab to open them in', async () => { + await openFile('/api/trips/1/files/2/download'); + expect(shareFile).toHaveBeenLastCalledWith(pdf, 'download'); + }); +}); diff --git a/client/tsconfig.json b/client/tsconfig.json index d3c51f17e..84641aa31 100644 --- a/client/tsconfig.json +++ b/client/tsconfig.json @@ -26,5 +26,5 @@ "forceConsistentCasingInFileNames": true, "resolveJsonModule": true }, - "include": ["src", "tests"] + "include": ["src", "tests", "native-shell"] } diff --git a/client/vite.config.js b/client/vite.config.js index 78de910c8..af4661cbc 100644 --- a/client/vite.config.js +++ b/client/vite.config.js @@ -307,6 +307,10 @@ export default defineConfig(({ mode }) => ({ // is, so a toolchain bump can't silently change which browsers still work. target: 'es2022', sourcemap: false, + // Served as /asset-manifest.json. The iOS app, which runs no service worker, + // walks it to pull every chunk into WebKit's cache so TREK can start offline + // (src/native/offlineShell.ts). + manifest: 'asset-manifest.json', modulePreload: { polyfill: true }, // Vite 8 bundles with rolldown, not rollup. `rollupOptions` is only an alias // onto `rolldownOptions`, and both `manualChunks` and `advancedChunks` are diff --git a/client/vite.native.config.js b/client/vite.native.config.js new file mode 100644 index 000000000..4c39f31a5 --- /dev/null +++ b/client/vite.native.config.js @@ -0,0 +1,16 @@ +import { defineConfig } from 'vite' +import { fileURLToPath } from 'url' + +// The address screen the native apps ship (native-shell/). Everything past it +// is the UI of the server the user picks, so this build stays tiny and apart +// from the main one: no PWA, no React, only the native strings of each locale. +export default defineConfig({ + root: fileURLToPath(new URL('./native-shell', import.meta.url)), + base: './', + publicDir: false, + build: { + outDir: fileURLToPath(new URL('./native-dist', import.meta.url)), + emptyOutDir: true, + target: ['es2020', 'safari15', 'chrome100'], + }, +}) diff --git a/knip.jsonc b/knip.jsonc index 1fb55aec6..423cad41a 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -21,16 +21,24 @@ "ignoreDependencies": ["unrun", "eslint", "prettier"] }, "client": { - // The app, its scripts, the Playwright specs and the server launcher + // The app, the native apps' address screen, its scripts, the Playwright specs and the server launcher // playwright.config.ts starts (`node e2e/server-launch.mjs`), and the tests. "entry": [ "src/main.tsx", + // The address screen the native apps ship, its own build (vite.native.config.js). + "native-shell/main.ts", "scripts/*.mjs", "e2e/**/*.{ts,mjs}", "src/**/*.test.{ts,tsx}", "tests/**/*.{ts,tsx}" ], - "project": ["src/**/*.{ts,tsx}", "scripts/**/*.mjs", "tests/**/*.{ts,tsx}", "e2e/**/*.{ts,mjs}"] + "project": [ + "src/**/*.{ts,tsx}", + "native-shell/**/*.ts", + "scripts/**/*.mjs", + "tests/**/*.{ts,tsx}", + "e2e/**/*.{ts,mjs}" + ] }, "server": { "entry": [ diff --git a/package-lock.json b/package-lock.json index 981f5af86..846516dc6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -32,6 +32,16 @@ "version": "5.1.0", "dependencies": { "@assistant-ui/react": "0.15.25", + "@capacitor/android": "^8.5.0", + "@capacitor/app": "^8.1.1", + "@capacitor/core": "^8.5.0", + "@capacitor/filesystem": "^8.1.3", + "@capacitor/haptics": "^8.0.2", + "@capacitor/ios": "^8.5.0", + "@capacitor/keyboard": "^8.0.5", + "@capacitor/share": "^8.0.1", + "@capacitor/splash-screen": "^8.0.2", + "@capacitor/status-bar": "^8.0.3", "@fontsource/abril-fatface": "^5.3.0", "@fontsource/alfa-slab-one": "^5.3.0", "@fontsource/allura": "^5.3.0", @@ -69,6 +79,7 @@ "@fontsource/yellowtail": "^5.3.0", "@mapbox/mapbox-gl-rtl-text": "^0.4.0", "@maplibre/maplibre-gl-leaflet": "0.1.4", + "@noble/hashes": "^1.8.0", "@simplewebauthn/browser": "^13.3.0", "@trek/shared": "*", "axios": "^1.20.0", @@ -97,6 +108,7 @@ "zustand": "^5.0.15" }, "devDependencies": { + "@capacitor/cli": "^8.5.0", "@eslint/js": "^10.0.1", "@jscpd/core": "^4.2.5", "@jscpd/tokenizer": "^4.2.6", @@ -2449,6 +2461,220 @@ "@keyv/serialize": "^1.1.1" } }, + "node_modules/@capacitor/android": { + "version": "8.5.3", + "resolved": "https://registry.npmjs.org/@capacitor/android/-/android-8.5.3.tgz", + "integrity": "sha512-ilH4gSSz3DrketMkzDVAvY9JsWJ//rCQnECLTdcFRO7xXDogwAbUvQAnIAbiqefwV/D1xfjEL4Gw1MJXEcaA9g==", + "license": "MIT", + "peerDependencies": { + "@capacitor/core": "^8.5.0" + } + }, + "node_modules/@capacitor/app": { + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/@capacitor/app/-/app-8.1.2.tgz", + "integrity": "sha512-uKBlsrXH0IdvUn69e/KKYbZ32A06pcrUdG8LWuZ/6y33YMXZXLEEdNSwl+jKS/SrsTWqnePs8EqSWaiQM3mUGA==", + "license": "MIT", + "peerDependencies": { + "@capacitor/core": ">=8.0.0" + } + }, + "node_modules/@capacitor/cli": { + "version": "8.5.3", + "resolved": "https://registry.npmjs.org/@capacitor/cli/-/cli-8.5.3.tgz", + "integrity": "sha512-/G6xwna+p4GS3lthSdWN3OThCH2F85O0Ukdy8rv3oAXvgEMeyFgPEIA3PMAS++IkHwUuBYBAKOQJnZfcrh1n0w==", + "dev": true, + "license": "MIT", + "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.0", + "env-paths": "^2.2.0", + "fs-extra": "^11.2.0", + "kleur": "^4.1.5", + "native-run": "^2.0.3", + "open": "^8.4.0", + "plist": "^3.1.0", + "prompts": "^2.4.2", + "rimraf": "^6.0.1", + "semver": "^7.6.3", + "tar": "^7.5.3", + "tslib": "^2.8.1", + "xcode": "^3.0.1", + "xml2js": "^0.6.2" + }, + "bin": { + "cap": "bin/capacitor", + "capacitor": "bin/capacitor" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@capacitor/cli/node_modules/commander": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", + "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@capacitor/cli/node_modules/define-lazy-prop": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/define-lazy-prop/-/define-lazy-prop-2.0.0.tgz", + "integrity": "sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@capacitor/cli/node_modules/is-docker": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz", + "integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==", + "dev": true, + "license": "MIT", + "bin": { + "is-docker": "cli.js" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@capacitor/cli/node_modules/is-wsl": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz", + "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-docker": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@capacitor/cli/node_modules/open": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/open/-/open-8.4.2.tgz", + "integrity": "sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-lazy-prop": "^2.0.0", + "is-docker": "^2.1.1", + "is-wsl": "^2.2.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@capacitor/cli/node_modules/xml2js": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.6.2.tgz", + "integrity": "sha512-T4rieHaC1EXcES0Kxxj4JWgaUQHDk+qwHcYOCFHfiwKz7tOVPLq7Hjq9dM1WCMhylqMEfP7hMcOIChvotiZegA==", + "dev": true, + "license": "MIT", + "dependencies": { + "sax": ">=0.6.0", + "xmlbuilder": "~11.0.0" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/@capacitor/core": { + "version": "8.5.3", + "resolved": "https://registry.npmjs.org/@capacitor/core/-/core-8.5.3.tgz", + "integrity": "sha512-oBE1oGuYE4ZzYYrulC75OuHdSsD6zLUy7d5o1tFwDLG4govGoubY15cxpiI5l0+q87Lm5p0bhbehMdzJg4aFag==", + "license": "MIT", + "dependencies": { + "tslib": "^2.1.0" + } + }, + "node_modules/@capacitor/filesystem": { + "version": "8.1.5", + "resolved": "https://registry.npmjs.org/@capacitor/filesystem/-/filesystem-8.1.5.tgz", + "integrity": "sha512-m1RkI8L83NJeppEKyRWioK3MDp2vjlA+QfUQcF8/xRlcXNC2HYxqoyYJ+K4M0EcVovy+g+4F24S05+bhK4Vgdg==", + "license": "MIT", + "dependencies": { + "@capacitor/synapse": "^1.0.4" + }, + "peerDependencies": { + "@capacitor/core": ">=8.0.0" + } + }, + "node_modules/@capacitor/haptics": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@capacitor/haptics/-/haptics-8.0.2.tgz", + "integrity": "sha512-c2hZzRR5Fk1tbTvhG1jhh2XBAf3EhnIerMIb2sl7Mt41Gxx1fhBJFDa0/BI1IbY4loVepyyuqNC9820/GZuoWQ==", + "license": "MIT", + "peerDependencies": { + "@capacitor/core": ">=8.0.0" + } + }, + "node_modules/@capacitor/ios": { + "version": "8.5.3", + "resolved": "https://registry.npmjs.org/@capacitor/ios/-/ios-8.5.3.tgz", + "integrity": "sha512-HnnV92Jl8+3x0JUloXUMjFcUsQI8wHFVsKwkLn72DfRZXYGZW11tQbmNOWOnRTljaU18FdI1b9ipT09SzzPDNw==", + "license": "MIT", + "peerDependencies": { + "@capacitor/core": "^8.5.0" + } + }, + "node_modules/@capacitor/keyboard": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@capacitor/keyboard/-/keyboard-8.0.6.tgz", + "integrity": "sha512-Bbe+9V0qaT6dzEFJEK7BUWR01l2+vZE8FM5ITF/WgKtx+G6eGZ6d5+YiSMRJBAK0VGjdO59v8yiQ10Doa5KyvQ==", + "license": "MIT", + "peerDependencies": { + "@capacitor/core": ">=8.0.0" + } + }, + "node_modules/@capacitor/share": { + "version": "8.0.3", + "resolved": "https://registry.npmjs.org/@capacitor/share/-/share-8.0.3.tgz", + "integrity": "sha512-gnvZBV1NPu2B8vd1UKncR56G15ueHd0aZLqgDov++t3SmTBG9Q0VrAZ1VnHn5stxlmglVaTb4RwopMgbpLzroA==", + "license": "MIT", + "peerDependencies": { + "@capacitor/core": ">=8.0.0" + } + }, + "node_modules/@capacitor/splash-screen": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@capacitor/splash-screen/-/splash-screen-8.0.2.tgz", + "integrity": "sha512-0C6rYScr13WfAE9nPl4ScOQynmjFv9NT3Th+RZkD4ezYHmER6mcl1/lDYsv7jg3Rj3FOvLrlTlmNkUrr83kZzQ==", + "license": "MIT", + "peerDependencies": { + "@capacitor/core": ">=8.0.0" + } + }, + "node_modules/@capacitor/status-bar": { + "version": "8.0.4", + "resolved": "https://registry.npmjs.org/@capacitor/status-bar/-/status-bar-8.0.4.tgz", + "integrity": "sha512-ZMzBUyHBzwDUxcHadEhvOvmoPmMQGMZgaMRJu8ohELeI6IaxoVH9ZhdF/OHnY3/yykv3Glev8Tnbh4aZY/0B0w==", + "license": "MIT", + "peerDependencies": { + "@capacitor/core": ">=8.0.0" + } + }, + "node_modules/@capacitor/synapse": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@capacitor/synapse/-/synapse-1.0.4.tgz", + "integrity": "sha512-/C1FUo8/OkKuAT4nCIu/34ny9siNHr9qtFezu4kxm6GY1wNFxrCFWjfYx5C1tUhVGz3fxBABegupkpjXvjCHrw==", + "license": "ISC" + }, "node_modules/@csstools/color-helpers": { "version": "6.1.1", "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.1.tgz", @@ -4460,6 +4686,247 @@ } } }, + "node_modules/@ionic/cli-framework-output": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@ionic/cli-framework-output/-/cli-framework-output-2.2.8.tgz", + "integrity": "sha512-TshtaFQsovB4NWRBydbNFawql6yul7d5bMiW1WYYf17hd99V6xdDdk3vtF51bw6sLkxON3bDQpWsnUc9/hVo3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@ionic/utils-terminal": "2.3.5", + "debug": "^4.0.0", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-array": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/@ionic/utils-array/-/utils-array-2.1.6.tgz", + "integrity": "sha512-0JZ1Zkp3wURnv8oq6Qt7fMPo5MpjbLoUoa9Bu2Q4PJuSDWM8H8gwF3dQO7VTeUj3/0o1IB1wGkFWZZYgUXZMUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.0.0", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-fs": { + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/@ionic/utils-fs/-/utils-fs-3.1.7.tgz", + "integrity": "sha512-2EknRvMVfhnyhL1VhFkSLa5gOcycK91VnjfrTB0kbqkTFCOXyXgVLI5whzq7SLrgD9t1aqos3lMMQyVzaQ5gVA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/fs-extra": "^8.0.0", + "debug": "^4.0.0", + "fs-extra": "^9.0.0", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-fs/node_modules/fs-extra": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz", + "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "at-least-node": "^1.0.0", + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@ionic/utils-object": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/@ionic/utils-object/-/utils-object-2.1.6.tgz", + "integrity": "sha512-vCl7sl6JjBHFw99CuAqHljYJpcE88YaH2ZW4ELiC/Zwxl5tiwn4kbdP/gxi2OT3MQb1vOtgAmSNRtusvgxI8ww==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.0.0", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-process": { + "version": "2.1.12", + "resolved": "https://registry.npmjs.org/@ionic/utils-process/-/utils-process-2.1.12.tgz", + "integrity": "sha512-Jqkgyq7zBs/v/J3YvKtQQiIcxfJyplPgECMWgdO0E1fKrrH8EF0QGHNJ9mJCn6PYe2UtHNS8JJf5G21e09DfYg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@ionic/utils-object": "2.1.6", + "@ionic/utils-terminal": "2.3.5", + "debug": "^4.0.0", + "signal-exit": "^3.0.3", + "tree-kill": "^1.2.2", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-process/node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/@ionic/utils-stream": { + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/@ionic/utils-stream/-/utils-stream-3.1.7.tgz", + "integrity": "sha512-eSELBE7NWNFIHTbTC2jiMvh1ABKGIpGdUIvARsNPMNQhxJB3wpwdiVnoBoTYp+5a6UUIww4Kpg7v6S7iTctH1w==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.0.0", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-subprocess": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@ionic/utils-subprocess/-/utils-subprocess-3.0.1.tgz", + "integrity": "sha512-cT4te3AQQPeIM9WCwIg8ohroJ8TjsYaMb2G4ZEgv9YzeDqHZ4JpeIKqG2SoaA3GmVQ3sOfhPM6Ox9sxphV/d1A==", + "dev": true, + "license": "MIT", + "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.3", + "debug": "^4.0.0", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-terminal": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@ionic/utils-terminal/-/utils-terminal-2.3.5.tgz", + "integrity": "sha512-3cKScz9Jx2/Pr9ijj1OzGlBDfcmx7OMVBt4+P1uRR0SSW4cm1/y3Mo4OY3lfkuaYifMNBW8Wz6lQHbs1bihr7A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/slice-ansi": "^4.0.0", + "debug": "^4.0.0", + "signal-exit": "^3.0.3", + "slice-ansi": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0", + "tslib": "^2.0.1", + "untildify": "^4.0.0", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-terminal/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@ionic/utils-terminal/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/@ionic/utils-terminal/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true, + "license": "MIT" + }, + "node_modules/@ionic/utils-terminal/node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/@ionic/utils-terminal/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@ionic/utils-terminal/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@ionic/utils-terminal/node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, "node_modules/@isaacs/cliui": { "version": "9.0.0", "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-9.0.0.tgz", @@ -4470,6 +4937,19 @@ "node": ">=18" } }, + "node_modules/@isaacs/fs-minipass": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz", + "integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "minipass": "^7.0.4" + }, + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/@istanbuljs/schema": { "version": "0.1.6", "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.6.tgz", @@ -6503,7 +6983,6 @@ "version": "1.8.0", "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", - "devOptional": true, "license": "MIT", "engines": { "node": "^14.21.3 || >=16" @@ -9418,8 +9897,7 @@ "optional": true, "os": [ "android" - ], - "peer": true + ] }, "node_modules/@rollup/rollup-android-arm64": { "version": "4.62.0", @@ -9433,8 +9911,7 @@ "optional": true, "os": [ "android" - ], - "peer": true + ] }, "node_modules/@rollup/rollup-darwin-arm64": { "version": "4.62.0", @@ -9448,8 +9925,7 @@ "optional": true, "os": [ "darwin" - ], - "peer": true + ] }, "node_modules/@rollup/rollup-darwin-x64": { "version": "4.62.0", @@ -9463,8 +9939,7 @@ "optional": true, "os": [ "darwin" - ], - "peer": true + ] }, "node_modules/@rollup/rollup-freebsd-arm64": { "version": "4.62.0", @@ -9478,8 +9953,7 @@ "optional": true, "os": [ "freebsd" - ], - "peer": true + ] }, "node_modules/@rollup/rollup-freebsd-x64": { "version": "4.62.0", @@ -9493,8 +9967,7 @@ "optional": true, "os": [ "freebsd" - ], - "peer": true + ] }, "node_modules/@rollup/rollup-linux-arm-gnueabihf": { "version": "4.62.0", @@ -9508,8 +9981,7 @@ "optional": true, "os": [ "linux" - ], - "peer": true + ] }, "node_modules/@rollup/rollup-linux-arm-musleabihf": { "version": "4.62.0", @@ -9523,8 +9995,7 @@ "optional": true, "os": [ "linux" - ], - "peer": true + ] }, "node_modules/@rollup/rollup-linux-arm64-gnu": { "version": "4.62.0", @@ -9538,8 +10009,7 @@ "optional": true, "os": [ "linux" - ], - "peer": true + ] }, "node_modules/@rollup/rollup-linux-arm64-musl": { "version": "4.62.0", @@ -9566,8 +10036,7 @@ "optional": true, "os": [ "linux" - ], - "peer": true + ] }, "node_modules/@rollup/rollup-linux-loong64-musl": { "version": "4.62.0", @@ -9581,8 +10050,7 @@ "optional": true, "os": [ "linux" - ], - "peer": true + ] }, "node_modules/@rollup/rollup-linux-ppc64-gnu": { "version": "4.62.0", @@ -9596,8 +10064,7 @@ "optional": true, "os": [ "linux" - ], - "peer": true + ] }, "node_modules/@rollup/rollup-linux-ppc64-musl": { "version": "4.62.0", @@ -9611,8 +10078,7 @@ "optional": true, "os": [ "linux" - ], - "peer": true + ] }, "node_modules/@rollup/rollup-linux-riscv64-gnu": { "version": "4.62.0", @@ -9626,8 +10092,7 @@ "optional": true, "os": [ "linux" - ], - "peer": true + ] }, "node_modules/@rollup/rollup-linux-riscv64-musl": { "version": "4.62.0", @@ -9641,8 +10106,7 @@ "optional": true, "os": [ "linux" - ], - "peer": true + ] }, "node_modules/@rollup/rollup-linux-s390x-gnu": { "version": "4.62.0", @@ -9656,8 +10120,7 @@ "optional": true, "os": [ "linux" - ], - "peer": true + ] }, "node_modules/@rollup/rollup-linux-x64-gnu": { "version": "4.62.0", @@ -9671,8 +10134,7 @@ "optional": true, "os": [ "linux" - ], - "peer": true + ] }, "node_modules/@rollup/rollup-linux-x64-musl": { "version": "4.62.0", @@ -9699,8 +10161,7 @@ "optional": true, "os": [ "openbsd" - ], - "peer": true + ] }, "node_modules/@rollup/rollup-openharmony-arm64": { "version": "4.62.0", @@ -9714,8 +10175,7 @@ "optional": true, "os": [ "openharmony" - ], - "peer": true + ] }, "node_modules/@rollup/rollup-win32-arm64-msvc": { "version": "4.62.0", @@ -9729,8 +10189,7 @@ "optional": true, "os": [ "win32" - ], - "peer": true + ] }, "node_modules/@rollup/rollup-win32-ia32-msvc": { "version": "4.62.0", @@ -9744,8 +10203,7 @@ "optional": true, "os": [ "win32" - ], - "peer": true + ] }, "node_modules/@rollup/rollup-win32-x64-gnu": { "version": "4.62.0", @@ -9759,8 +10217,7 @@ "optional": true, "os": [ "win32" - ], - "peer": true + ] }, "node_modules/@rollup/rollup-win32-x64-msvc": { "version": "4.62.0", @@ -9774,8 +10231,7 @@ "optional": true, "os": [ "win32" - ], - "peer": true + ] }, "node_modules/@scarf/scarf": { "version": "1.4.0", @@ -10530,6 +10986,16 @@ "@types/send": "*" } }, + "node_modules/@types/fs-extra": { + "version": "8.1.5", + "resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-8.1.5.tgz", + "integrity": "sha512-0dzKcwO+S8s2kuF5Z9oUWatQJj5Uq/iqphEtE3GQJVRRYm/tD1LglU2UnXi2A8jLq5umkGouOXOR9y0n613ZwQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/geojson": { "version": "7946.0.16", "resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz", @@ -10753,6 +11219,13 @@ "@types/node": "*" } }, + "node_modules/@types/slice-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@types/slice-ansi/-/slice-ansi-4.0.0.tgz", + "integrity": "sha512-+OpjSaq85gvlZAYINyzKpLeiFkSC4EsC6IIiT6v6TLSU5k5U83fHGj9Lel8oKEXM0HqgrMVCjXPDPVICtxF7EQ==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/statuses": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/@types/statuses/-/statuses-2.0.6.tgz", @@ -11261,6 +11734,16 @@ "url": "https://opencollective.com/vitest" } }, + "node_modules/@xmldom/xmldom": { + "version": "0.9.12", + "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.9.12.tgz", + "integrity": "sha512-5AXjrcMClTryPe9LgZrygpB1lj7s0S9E0+W+AHaVKAVyHanafK86iPSvG5xHVSp/jC+VH1UXu0TAEmY279xH7A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.6" + } + }, "node_modules/@yuku-codegen/binding-android-arm64": { "version": "0.10.2", "resolved": "https://registry.npmjs.org/@yuku-codegen/binding-android-arm64/-/binding-android-arm64-0.10.2.tgz", @@ -11996,6 +12479,16 @@ "dev": true, "license": "MIT" }, + "node_modules/astral-regex": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", + "integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/async": { "version": "3.2.6", "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", @@ -12291,6 +12784,27 @@ "bare-path": "^3.0.0" } }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, "node_modules/baseline-browser-mapping": { "version": "2.11.25", "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.25.tgz", @@ -12332,6 +12846,16 @@ "require-from-string": "^2.0.2" } }, + "node_modules/big-integer": { + "version": "1.6.52", + "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.52.tgz", + "integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==", + "dev": true, + "license": "Unlicense", + "engines": { + "node": ">=0.6" + } + }, "node_modules/binary-extensions": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", @@ -12418,6 +12942,29 @@ "dev": true, "license": "MIT" }, + "node_modules/bplist-creator": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/bplist-creator/-/bplist-creator-0.1.0.tgz", + "integrity": "sha512-sXaHZicyEEmY86WyueLTQesbeoH/mquvarJaQNbjuOQO+7gbFcDEWqKmcWA4cOTLzFlfgvkiVxolk1k5bBIpmg==", + "dev": true, + "license": "MIT", + "dependencies": { + "stream-buffers": "2.2.x" + } + }, + "node_modules/bplist-parser": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/bplist-parser/-/bplist-parser-0.3.2.tgz", + "integrity": "sha512-apC2+fspHGI3mMKj+dGevkGo/tCqVB8jMb6i+OX+E29p0Iposz07fABkRIfVUPNd5A5VbuOz1bZbnmkKLYF+wQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "big-integer": "1.6.x" + }, + "engines": { + "node": ">= 5.10.0" + } + }, "node_modules/brace-expansion": { "version": "2.1.7", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", @@ -12775,6 +13322,16 @@ "node": ">= 6" } }, + "node_modules/chownr": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", + "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, "node_modules/cli-width": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-4.1.0.tgz", @@ -13689,6 +14246,26 @@ "dev": true, "license": "ISC" }, + "node_modules/elementtree": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/elementtree/-/elementtree-0.1.7.tgz", + "integrity": "sha512-wkgGT6kugeQk/P6VZ/f4T+4HB41BVgNBq5CDIZVbQ02nvTVqAiVTbskxxu3eA/X96lMlfYOwnLQpN2v5E1zDEg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "sax": "1.1.4" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/elementtree/node_modules/sax": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.1.4.tgz", + "integrity": "sha512-5f3k2PbGGp+YtKJjOItpg3P99IMD84E4HOvcfleTb5joCHNXYLsR9yWFPOYGgaeMPDubQILTCMdsFb2OMeOjtg==", + "dev": true, + "license": "ISC" + }, "node_modules/emoji-regex": { "version": "10.6.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", @@ -13727,6 +14304,16 @@ "url": "https://github.com/fb55/entities?sponsor=1" } }, + "node_modules/env-paths": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz", + "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/es-abstract": { "version": "1.24.2", "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.24.2.tgz", @@ -14638,6 +15225,16 @@ "walk-up-path": "^4.0.0" } }, + "node_modules/fd-slicer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz", + "integrity": "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==", + "dev": true, + "license": "MIT", + "dependencies": { + "pend": "~1.2.0" + } + }, "node_modules/file-entry-cache": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", @@ -15667,6 +16264,16 @@ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "license": "ISC" }, + "node_modules/ini": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/ini/-/ini-4.1.3.tgz", + "integrity": "sha512-X7rqawQBvfdjS10YU1y1YVreA3SsLrW9dX2CewP2EbBJM4ypVNLDkO5y04gejPwKIY9lR+7r9gn3rFPt/kmWFg==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, "node_modules/inline-style-parser": { "version": "0.2.7", "resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.7.tgz", @@ -16844,6 +17451,16 @@ "json-buffer": "3.0.1" } }, + "node_modules/kleur": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", + "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/knip": { "version": "6.38.0", "resolved": "https://registry.npmjs.org/knip/-/knip-6.38.0.tgz", @@ -18587,6 +19204,19 @@ "node": ">=16 || 14 >=14.17" } }, + "node_modules/minizlib": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", + "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "minipass": "^7.1.2" + }, + "engines": { + "node": ">= 18" + } + }, "node_modules/modern-screenshot": { "version": "4.7.0", "resolved": "https://registry.npmjs.org/modern-screenshot/-/modern-screenshot-4.7.0.tgz", @@ -18853,6 +19483,32 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, + "node_modules/native-run": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/native-run/-/native-run-2.0.3.tgz", + "integrity": "sha512-U1PllBuzW5d1gfan+88L+Hky2eZx+9gv3Pf6rNBxKbORxi7boHzqiA6QFGSnqMem4j0A9tZ08NMIs5+0m/VS1Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@ionic/utils-fs": "^3.1.7", + "@ionic/utils-terminal": "^2.3.4", + "bplist-parser": "^0.3.2", + "debug": "^4.3.4", + "elementtree": "^0.1.7", + "ini": "^4.1.1", + "plist": "^3.1.0", + "split2": "^4.2.0", + "through2": "^4.0.2", + "tslib": "^2.6.2", + "yauzl": "^2.10.0" + }, + "bin": { + "native-run": "bin/native-run" + }, + "engines": { + "node": ">=16.0.0" + } + }, "node_modules/natural-compare": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", @@ -19483,6 +20139,13 @@ "@napi-rs/canvas": "^0.1.80" } }, + "node_modules/pend": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", + "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==", + "dev": true, + "license": "MIT" + }, "node_modules/pg": { "version": "8.23.0", "resolved": "https://registry.npmjs.org/pg/-/pg-8.23.0.tgz", @@ -19722,6 +20385,31 @@ "node": ">=20" } }, + "node_modules/plist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/plist/-/plist-3.1.1.tgz", + "integrity": "sha512-ZIfcLJC+7E7FBFnDxm9MPmt7D+DidyQ26lewieO75AdhA2ayMtsJSES0iWzqJQbcVRSrTufQoy0DR94xHue0oA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@xmldom/xmldom": "^0.9.10", + "base64-js": "^1.5.1", + "xmlbuilder": "^15.1.1" + }, + "engines": { + "node": ">=10.4.0" + } + }, + "node_modules/plist/node_modules/xmlbuilder": { + "version": "15.1.1", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz", + "integrity": "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.0" + } + }, "node_modules/plyr": { "version": "3.8.4", "resolved": "https://registry.npmjs.org/plyr/-/plyr-3.8.4.tgz", @@ -20158,6 +20846,30 @@ "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", "license": "MIT" }, + "node_modules/prompts": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", + "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "kleur": "^3.0.3", + "sisteransi": "^1.0.5" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/prompts/node_modules/kleur": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", + "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/prop-types": { "version": "15.8.1", "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", @@ -21251,6 +21963,83 @@ "node": ">=0.10.0" } }, + "node_modules/rimraf": { + "version": "6.1.3", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-6.1.3.tgz", + "integrity": "sha512-LKg+Cr2ZF61fkcaK1UdkH2yEBBKnYjTyWzTJT6KNPcSPaiT7HSdhtMXQuN5wkTX0Xu72KQ1l8S42rlmexS2hSA==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "glob": "^13.0.3", + "package-json-from-dist": "^1.0.1" + }, + "bin": { + "rimraf": "dist/esm/bin.mjs" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/rimraf/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/rimraf/node_modules/brace-expansion": { + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/rimraf/node_modules/glob": { + "version": "13.0.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", + "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "minimatch": "^10.2.2", + "minipass": "^7.1.3", + "path-scurry": "^2.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/rimraf/node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/rolldown": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.1.2.tgz", @@ -21927,6 +22716,31 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/simple-plist": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/simple-plist/-/simple-plist-1.3.1.tgz", + "integrity": "sha512-iMSw5i0XseMnrhtIzRb7XpQEXepa9xhWxGUojHBL43SIpQuDQkh3Wpy67ZbDzZVr6EKxvwVChnVpdl8hEVLDiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "bplist-creator": "0.1.0", + "bplist-parser": "0.3.1", + "plist": "^3.0.5" + } + }, + "node_modules/simple-plist/node_modules/bplist-parser": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/bplist-parser/-/bplist-parser-0.3.1.tgz", + "integrity": "sha512-PyJxiNtA5T2PlLIeBot4lbp7rj4OadzjnMZD/G5zuBNt8ei/yCU7+wW0h2bag9vr8c+/WuRWmSxbqAl9hL1rBA==", + "dev": true, + "license": "MIT", + "dependencies": { + "big-integer": "1.6.x" + }, + "engines": { + "node": ">= 5.10.0" + } + }, "node_modules/simple-xml-to-json": { "version": "1.2.7", "resolved": "https://registry.npmjs.org/simple-xml-to-json/-/simple-xml-to-json-1.2.7.tgz", @@ -21936,6 +22750,47 @@ "node": ">=20.12.2" } }, + "node_modules/sisteransi": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", + "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", + "dev": true, + "license": "MIT" + }, + "node_modules/slice-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz", + "integrity": "sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "astral-regex": "^2.0.0", + "is-fullwidth-code-point": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, + "node_modules/slice-ansi/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, "node_modules/smob": { "version": "1.6.2", "resolved": "https://registry.npmjs.org/smob/-/smob-1.6.2.tgz", @@ -22063,6 +22918,16 @@ "node": ">= 0.4" } }, + "node_modules/stream-buffers": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/stream-buffers/-/stream-buffers-2.2.0.tgz", + "integrity": "sha512-uyQK/mx5QjHun80FLJTfaWE7JtwfRMKBLkMne6udYOmvH0CawotVa7TfgYHzAnpphn4+TweIx1QKMnRIbipmUg==", + "dev": true, + "license": "Unlicense", + "engines": { + "node": ">= 0.10.0" + } + }, "node_modules/streamsearch": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", @@ -22518,6 +23383,23 @@ "node": ">=14.0.0" } }, + "node_modules/tar": { + "version": "7.5.22", + "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.22.tgz", + "integrity": "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/fs-minipass": "^4.0.0", + "chownr": "^3.0.0", + "minipass": "^7.1.2", + "minizlib": "^3.1.0", + "yallist": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/tar-stream": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-3.2.0.tgz", @@ -22530,6 +23412,16 @@ "streamx": "^2.15.0" } }, + "node_modules/tar/node_modules/yallist": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", + "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, "node_modules/teex": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/teex/-/teex-1.0.1.tgz", @@ -22647,6 +23539,16 @@ "node": ">=0.2.6" } }, + "node_modules/through2": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/through2/-/through2-4.0.2.tgz", + "integrity": "sha512-iOqSav00cVxEEICeD7TjLB1sueEL+81Wpzp2bY17uZjZN0pWZPuo4suZ/61VujxmqSGFfgOcNuTZ85QJwNZQpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "readable-stream": "3" + } + }, "node_modules/tinybench": { "version": "2.9.0", "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", @@ -23454,6 +24356,16 @@ "url": "https://github.com/sponsors/kettanaito" } }, + "node_modules/untildify": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/untildify/-/untildify-4.0.0.tgz", + "integrity": "sha512-KK8xQ1mkzZeg9inewmFVDNkg3l5LUhoq9kN6iWYB/CC9YMG8HA+c1Q8HwDe6dEX7kErrEVNVBO3fWsVq5iDgtw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/unzipper": { "version": "0.12.5", "resolved": "https://registry.npmjs.org/unzipper/-/unzipper-0.12.5.tgz", @@ -24802,6 +25714,31 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/xcode": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/xcode/-/xcode-3.0.1.tgz", + "integrity": "sha512-kCz5k7J7XbJtjABOvkc5lJmkiDh8VhjVCGNiqdKCscmVpdVUpEAyXv1xmCLkQJ5dsHqx3IPO4XW+NTDhU/fatA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "simple-plist": "^1.1.0", + "uuid": "^7.0.3" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/xcode/node_modules/uuid": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-7.0.3.tgz", + "integrity": "sha512-DPSke0pXhTZgoF/d+WSt2QaKMCFSfx7QegxEWT+JOuHF5aWrKEn0G+ztjuJg/gG8/ItK+rbPCD/yNv8yyih6Cg==", + "deprecated": "uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).", + "dev": true, + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, "node_modules/xml-name-validator": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", @@ -24930,6 +25867,17 @@ "node": "^20.19.0 || ^22.12.0 || >=23" } }, + "node_modules/yauzl": { + "version": "2.10.0", + "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.10.0.tgz", + "integrity": "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "buffer-crc32": "~0.2.3", + "fd-slicer": "~1.1.0" + } + }, "node_modules/yocto-queue": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", diff --git a/server/src/nest/app.module.ts b/server/src/nest/app.module.ts index 59684e517..89143a055 100644 --- a/server/src/nest/app.module.ts +++ b/server/src/nest/app.module.ts @@ -61,6 +61,7 @@ import { ManagedExtModule } from './managed/managed-ext.module'; import { MapsModule } from './maps/maps.module'; import { McpTransportModule } from './mcp-transport/mcp-transport.module'; import { MemoriesModule } from './memories/memories.module'; +import { NativeAuthModule } from './native-auth/native-auth.module'; import { NotificationsModule } from './notifications/notifications.module'; import { OauthModule } from './oauth/oauth.module'; import { OidcModule } from './oidc/oidc.module'; @@ -193,6 +194,7 @@ import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core'; AuthModule, SessionsModule, OidcModule, + NativeAuthModule, OauthModule, AdminModule, AddonsModule, diff --git a/server/src/nest/auth/auth.module.ts b/server/src/nest/auth/auth.module.ts index fad90130b..c4c7e1962 100644 --- a/server/src/nest/auth/auth.module.ts +++ b/server/src/nest/auth/auth.module.ts @@ -39,6 +39,7 @@ import { AuthController } from './auth.controller'; import { AVATAR_FILE_FILTER, MAX_AVATAR_SIZE } from './auth.controller'; import { AuthMcp } from './auth.mcp'; import { AuthService } from './auth.service'; +import { LoginSessionService } from './login-session.service'; import { PasskeyController } from './passkey.controller'; import { PasskeyService } from './passkey.service'; import { RegistrationInvitesService } from './registration-invites.service'; @@ -69,7 +70,8 @@ import { MulterModule } from '@nestjs/platform-express'; * budget.bridge). AuthService is * exported for the in-container consumers (VacayMcp, OidcService, * PasskeyEnabledGuard); PasskeyService for AdminService's passkey - * reset; UserCleanupService for the two account-deletion paths (AdminService) + * reset; LoginSessionService for the native app sign-in hand-off + * (NativeAuthModule); UserCleanupService for the two account-deletion paths (AdminService) * and the guest deletion in TripsService; everything outside the container goes * through auth.bridge.ts. */ @@ -158,6 +160,7 @@ import { MulterModule } from '@nestjs/platform-express'; controllers: [AuthPublicController, AuthController, PasskeyController, SessionsController], providers: [ AuthService, + LoginSessionService, UserProfileService, RegistrationInvitesService, PasskeyService, @@ -166,6 +169,6 @@ import { MulterModule } from '@nestjs/platform-express'; AuthMcp, AuthStorageRefsService, ], - exports: [AuthService, RegistrationInvitesService, PasskeyService, UserCleanupService], + exports: [AuthService, LoginSessionService, RegistrationInvitesService, PasskeyService, UserCleanupService], }) export class AuthModule {} diff --git a/server/src/nest/auth/login-session.service.ts b/server/src/nest/auth/login-session.service.ts new file mode 100644 index 000000000..ce91e43a6 --- /dev/null +++ b/server/src/nest/auth/login-session.service.ts @@ -0,0 +1,33 @@ +import { Users } from '../../db/entities/Users.entity'; +import type { UsersRepository } from '../../db/repositories/Users.repository'; +import { UnitOfWork } from '../database/unit-of-work'; +import type { SessionClient } from '../sessions/sessions.service'; +import { AuthService } from './auth.service'; +import { InjectRepository } from '@mikro-orm/nestjs'; +import { Injectable } from '@nestjs/common'; + +/** + * Signs in an account whose identity another way in has already proven: the + * login is recorded on the account and the session minted in one transaction. + * + * Auth owns the users table, so a domain whose flow ends in a sign-in (the + * native app hand-off) asks here instead of reaching for that table itself. + */ +@Injectable() +export class LoginSessionService { + constructor( + private readonly auth: AuthService, + private readonly uow: UnitOfWork, + @InjectRepository(Users) private readonly users: UsersRepository, + ) {} + + /** The session token, or null when the account no longer exists. */ + async signIn(userId: number, remember: boolean | undefined, client?: SessionClient): Promise { + return this.uow.transactional(async () => { + const passwordVersion = await this.users.getPasswordVersion(userId); + if (passwordVersion === null) return null; + await this.users.touchLastLogin(userId); + return this.auth.generateToken({ id: userId, password_version: passwordVersion }, remember, client); + }); + } +} diff --git a/server/src/nest/common/validate-route-guards.ts b/server/src/nest/common/validate-route-guards.ts index 6af8cec1d..5106a88d2 100644 --- a/server/src/nest/common/validate-route-guards.ts +++ b/server/src/nest/common/validate-route-guards.ts @@ -142,6 +142,9 @@ export const PUBLIC_ROUTE_ALLOW_LIST: string[] = [ 'McpTransportController.delete', 'McpTransportController.get', 'McpTransportController.post', + // The native app redeems a one-time code from the system browser here. The + // code is only good together with the verifier the app kept to itself. + 'NativeAuthController.exchange', 'OauthPublicController.revoke', 'OauthPublicController.token', 'OauthPublicController.userinfo', diff --git a/server/src/nest/health/features.controller.ts b/server/src/nest/health/features.controller.ts index 5b5e4475b..93dfb022e 100644 --- a/server/src/nest/health/features.controller.ts +++ b/server/src/nest/health/features.controller.ts @@ -62,6 +62,14 @@ export class FeaturesController { // Whether the assistant exists on this install at all; whether it can // run for a user is /api/ai/status. A managed install has none. aiAssistant: !readEnv().managed.enabled && (await this.addons.isAddonEnabled(ADDON_IDS.AI_ASSISTANT)), + // The native apps refuse to connect to a server without this: an older + // one serves a UI that knows neither the sign-in hand-off nor the way + // back to the server picker, and the user would be stuck in it. + nativeApp: true, + // The version of what the apps rely on from the server (the hand-off + // routes, the shell bridge in the served UI). Raised only for a change an + // older app cannot follow; the app refuses a server below its minimum. + nativeApi: 1, }; } } diff --git a/server/src/nest/native-auth/native-auth.controller.ts b/server/src/nest/native-auth/native-auth.controller.ts new file mode 100644 index 000000000..256876def --- /dev/null +++ b/server/src/nest/native-auth/native-auth.controller.ts @@ -0,0 +1,72 @@ +import type { User } from '../../types'; +import { AuditService } from '../audit/audit.service'; +import { getClientIp } from '../audit/client-ip'; +import { CookieAuthGuard } from '../auth-core/cookie-auth.guard'; +import { CurrentUser } from '../auth-core/current-user.decorator'; +import { Public } from '../auth-core/public.decorator'; +import { setAuthCookie } from '../common/cookie'; +import { RateLimitService } from '../common/rate-limit.service'; +import { ResponseContract } from '../common/response-contract'; +import { sessionClientFrom } from '../sessions/sessions.service'; +import { NativeExchangeDto, NativeHandoffDto } from './native-auth.dto'; +import { NativeAuthService } from './native-auth.service'; +import { Body, Controller, HttpCode, HttpException, Post, Req, Res, UseGuards } from '@nestjs/common'; +import { + nativeHandoffResponseSchema, + successResponseSchema, + type NativeHandoffResponse, + type SuccessResponse, +} from '@trek/shared'; + +import type { Request, Response } from 'express'; + +const EXCHANGE_WINDOW_MS = 15 * 60 * 1000; +const EXCHANGE_MAX = 20; + +/** + * /api/auth/native: the sign-in hand-off between the system browser and the + * native app. See the contract in @trek/shared for the whole round trip. + */ +@Controller('api/auth/native') +export class NativeAuthController { + constructor( + private readonly nativeAuth: NativeAuthService, + private readonly audit: AuditService, + private readonly rl: RateLimitService, + ) {} + + /** + * Cookie only: an API or MCP bearer token must not be able to mint itself a + * full browser session this way. + */ + @Post('handoff') + @UseGuards(CookieAuthGuard) + @HttpCode(200) + @ResponseContract(nativeHandoffResponseSchema) + async handoff(@Body() body: NativeHandoffDto, @CurrentUser() user: User): Promise { + return { code: await this.nativeAuth.issueCode(user.id, body.challenge) }; + } + + @Post('exchange') + @Public('the one-time code together with its verifier is the credential') + @HttpCode(200) + @ResponseContract(successResponseSchema) + async exchange( + @Body() body: NativeExchangeDto, + @Req() req: Request, + @Res({ passthrough: true }) res: Response, + ): Promise { + if (!(await this.rl.check('native-exchange', req.ip || 'unknown', EXCHANGE_MAX, EXCHANGE_WINDOW_MS, Date.now()))) { + throw new HttpException({ error: 'Too many attempts. Please try again later.' }, 429); + } + const session = await this.nativeAuth.redeem(body.code, body.verifier, sessionClientFrom(req)); + setAuthCookie(res, session.token, req, true); + await this.audit.writeAudit({ + userId: session.userId, + action: 'user.login', + ip: getClientIp(req), + details: { method: 'native_app' }, + }); + return { success: true }; + } +} diff --git a/server/src/nest/native-auth/native-auth.dto.ts b/server/src/nest/native-auth/native-auth.dto.ts new file mode 100644 index 000000000..98737cc2e --- /dev/null +++ b/server/src/nest/native-auth/native-auth.dto.ts @@ -0,0 +1,8 @@ +import { nativeExchangeRequestSchema, nativeHandoffRequestSchema } from '@trek/shared'; + +import { createZodDto } from 'nestjs-zod'; + +/** Body of POST /api/auth/native/handoff: the challenge the app sent into the browser. */ +export class NativeHandoffDto extends createZodDto(nativeHandoffRequestSchema) {} +/** Body of POST /api/auth/native/exchange: the one-time code and the verifier behind its challenge. */ +export class NativeExchangeDto extends createZodDto(nativeExchangeRequestSchema) {} diff --git a/server/src/nest/native-auth/native-auth.module.ts b/server/src/nest/native-auth/native-auth.module.ts new file mode 100644 index 000000000..843c54a3a --- /dev/null +++ b/server/src/nest/native-auth/native-auth.module.ts @@ -0,0 +1,20 @@ +import { AuditModule } from '../audit/audit.module'; +import { AuthModule } from '../auth/auth.module'; +import { RateLimitModule } from '../common/rate-limit.module'; +import { NativeAuthController } from './native-auth.controller'; +import { NativeAuthService } from './native-auth.service'; +import { InMemoryNativeHandoffStore, NativeHandoffStore } from './native-handoff.store'; +import { Module } from '@nestjs/common'; + +/** + * The sign-in hand-off for the native apps (/api/auth/native). The session + * comes from AuthModule's LoginSessionService. The codes wait in this + * process's memory; a store shared between processes would be provided here + * instead. + */ +@Module({ + imports: [AuthModule, AuditModule, RateLimitModule], + controllers: [NativeAuthController], + providers: [NativeAuthService, { provide: NativeHandoffStore, useClass: InMemoryNativeHandoffStore }], +}) +export class NativeAuthModule {} diff --git a/server/src/nest/native-auth/native-auth.service.ts b/server/src/nest/native-auth/native-auth.service.ts new file mode 100644 index 000000000..c0c0ac2c5 --- /dev/null +++ b/server/src/nest/native-auth/native-auth.service.ts @@ -0,0 +1,57 @@ +import { LoginSessionService } from '../auth/login-session.service'; +import { DomainError } from '../common/domain-error'; +import type { SessionClient } from '../sessions/sessions.service'; +import { NATIVE_HANDOFF_CODE_TTL_MS, NativeHandoffStore } from './native-handoff.store'; +import { Injectable } from '@nestjs/common'; + +import { createHash, randomBytes, timingSafeEqual } from 'crypto'; + +const INVALID_CODE = 'Invalid or expired code'; + +/** Constant-time check that sha256(verifier) is the challenge the code was issued for. */ +function verifierMatches(challenge: string, verifier: string): boolean { + const expected = Buffer.from(challenge, 'hex'); + const actual = createHash('sha256').update(verifier, 'utf8').digest(); + return expected.length === actual.length && timingSafeEqual(expected, actual); +} + +/** + * Carries a session from the system browser into the native app's WebView. + * + * The browser, signed in, trades the challenge the app sent along for a + * one-time code; the app redeems that code together with the verifier it kept. + * The session itself comes from the auth domain (LoginSessionService), the + * same way every other sign-in gets one. + */ +@Injectable() +export class NativeAuthService { + constructor( + private readonly logins: LoginSessionService, + private readonly handoffs: NativeHandoffStore, + ) {} + + async issueCode(userId: number, challenge: string): Promise { + const code = randomBytes(32).toString('base64url'); + const stored = await this.handoffs.put(code, { + userId, + challenge, + expiresAt: Date.now() + NATIVE_HANDOFF_CODE_TTL_MS, + }); + if (!stored) throw new DomainError(503, 'Too many sign-ins in progress. Please try again in a minute.'); + return code; + } + + /** + * Burns the code on every attempt, right or wrong, so a code that leaked + * through the URL scheme gets exactly one guess. The session is always the + * long one: an app that forgets its login whenever the system unloads it + * would be useless on the road. + */ + async redeem(code: string, verifier: string, client: SessionClient): Promise<{ token: string; userId: number }> { + const entry = await this.handoffs.take(code); + if (!entry || !verifierMatches(entry.challenge, verifier)) throw new DomainError(400, INVALID_CODE); + const token = await this.logins.signIn(entry.userId, true, client); + if (!token) throw new DomainError(400, INVALID_CODE); + return { token, userId: entry.userId }; + } +} diff --git a/server/src/nest/native-auth/native-handoff.store.ts b/server/src/nest/native-auth/native-handoff.store.ts new file mode 100644 index 000000000..f3a8b1690 --- /dev/null +++ b/server/src/nest/native-auth/native-handoff.store.ts @@ -0,0 +1,54 @@ +/** A sign-in the system browser handed off and the app has not redeemed yet. */ +export interface NativeHandoff { + userId: number; + /** Hex sha256 of the verifier the app kept to itself. */ + challenge: string; + expiresAt: number; +} + +export const NATIVE_HANDOFF_CODE_TTL_MS = 60_000; +export const MAX_PENDING_HANDOFFS = 500; + +/** + * Where the one-time hand-off codes wait between the browser minting one and + * the app redeeming it, as an injectable port. + * + * In memory today, which ties a code to the process that issued it; a code + * lives a minute and a restart only means signing in again, so nothing about + * it is worth a table. A store shared between processes replaces + * InMemoryNativeHandoffStore in NativeAuthModule without touching the + * service. Every method returns a promise, because such a store lives in the + * database or on the network. + */ +export abstract class NativeHandoffStore { + /** Keep `entry` under `code`; false when the store is at capacity. */ + abstract put(code: string, entry: NativeHandoff): Promise; + /** Single use: the entry is removed even when it turns out to be expired, and an expired one is null. */ + abstract take(code: string): Promise; +} + +/** + * The current behaviour: one capped map in this process's memory. Expired + * entries are dropped on the next write instead of by a timer, so the store + * runs no interval of its own and dead codes never fill its cap. + */ +export class InMemoryNativeHandoffStore extends NativeHandoffStore { + private readonly codes = new Map(); + + put(code: string, entry: NativeHandoff): Promise { + const now = Date.now(); + for (const [key, pending] of this.codes) { + if (now > pending.expiresAt) this.codes.delete(key); + } + if (this.codes.size >= MAX_PENDING_HANDOFFS) return Promise.resolve(false); + this.codes.set(code, entry); + return Promise.resolve(true); + } + + take(code: string): Promise { + const entry = this.codes.get(code); + if (!entry) return Promise.resolve(null); + this.codes.delete(code); + return Promise.resolve(Date.now() > entry.expiresAt ? null : entry); + } +} diff --git a/server/src/nest/platform/platform.routes.ts b/server/src/nest/platform/platform.routes.ts index 5e0ddd080..c6b0b905a 100644 --- a/server/src/nest/platform/platform.routes.ts +++ b/server/src/nest/platform/platform.routes.ts @@ -290,6 +290,8 @@ export function applyPlatformSpa(app: express.Application): void { app.get(/.*/, (req: Request, res: Response) => answerUnmatchedGet(req, res)); } +const HASHED_ASSET = /[\\/]assets[\\/][^\\/]+-[\w-]{8,}\.\w+$/; + /** * Production static serving of the built client (JS/CSS/assets). Split out from * applyPlatformSpa because the NestJS bootstrap needs the static files served @@ -305,6 +307,11 @@ export function applyPlatformStatic(app: express.Application): void { setHeaders: (res, filePath) => { if (filePath.endsWith('index.html')) { res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate'); + } else if (HASHED_ASSET.test(filePath)) { + // Vite puts a content hash in every name under assets/, so a file there + // never changes. Without this the iOS app, which has no service worker, + // cannot start offline: WebKit would revalidate each script and fail. + res.setHeader('Cache-Control', 'public, max-age=31536000, immutable'); } }, }), diff --git a/server/tests/e2e/native-auth.e2e.test.ts b/server/tests/e2e/native-auth.e2e.test.ts new file mode 100644 index 000000000..81037cf3f --- /dev/null +++ b/server/tests/e2e/native-auth.e2e.test.ts @@ -0,0 +1,135 @@ +/** + * Native sign-in hand-off e2e: the real CookieAuthGuard, the real cookie + * helpers, the real AuthService and session table over a migrated temp SQLite + * db. Walks the whole round trip the apps make: the browser side mints a code + * for a challenge, the WebView side redeems it with the verifier and walks + * away with a session cookie that /api/auth/me accepts. + */ +import { AuditLog } from '../../src/db/entities/AuditLog.entity'; +import { AuthModule } from '../../src/nest/auth/auth.module'; +import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter'; +import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe'; +import { NativeAuthModule } from '../../src/nest/native-auth/native-auth.module'; +import { MailerService } from '../../src/nest/notifications/mailer/mailer.service'; +import { createSnapshotTestDb } from '../helpers/db-mock'; +import { findRows } from '../helpers/factories/rows'; +import { makeUser } from '../helpers/factories/users'; +import { resetRateLimits } from '../helpers/test-db'; +import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm'; +import { TestUnitOfWorkModule } from '../helpers/test-uow'; +import { sessionCookie, signSession } from './harness'; +import { Test } from '@nestjs/testing'; + +import cookieParser from 'cookie-parser'; +import { createHash, randomBytes } from 'crypto'; +import type { Server } from 'http'; +import request from 'supertest'; +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('../../src/nest/audit/audit-log.logger', () => ({ + LOG_LEVEL: 'error', + logInfo: vi.fn(), + logDebug: vi.fn(), + logError: vi.fn(), + logWarn: vi.fn(), +})); + +const verifier = randomBytes(32).toString('base64url'); +const challenge = createHash('sha256').update(verifier).digest('hex'); + +const db = createSnapshotTestDb(); +let orm: TestOrm; +let server: Server; +let app: Awaited>; +let userId: number; + +async function build() { + const moduleRef = await Test.createTestingModule({ + imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), AuthModule, NativeAuthModule], + }) + .overrideProvider(MailerService) + .useValue({ sendPasswordResetEmail: vi.fn() }) + .compile(); + const nest = moduleRef.createNestApplication(); + nest.use(cookieParser()); + nest.useGlobalFilters(new TrekExceptionFilter()); + nest.useGlobalPipes(new ZodValidationPipe()); + await nest.init(); + return nest; +} + +const handoff = (cookie: string, body: object = { challenge }) => + request(server).post('/api/auth/native/handoff').set('Cookie', cookie).send(body); +const exchange = (body: object) => request(server).post('/api/auth/native/exchange').send(body); + +beforeAll(async () => { + orm = await createTestOrm(db); + userId = (await makeUser(orm, { username: 'native-e2e', email: 'native-e2e@example.test' })).user.id; + app = await build(); + server = app.getHttpServer(); +}); + +beforeEach(async () => { + await resetRateLimits(app); +}); + +afterAll(async () => { + await app.close(); + await orm.close(); +}); + +describe('Native sign-in hand-off e2e', () => { + it('NATIVE-E2E-001: carries a browser session into a fresh session cookie for the app', async () => { + const minted = await handoff(sessionCookie(userId)); + expect(minted.status).toBe(200); + expect(typeof minted.body.code).toBe('string'); + + const redeemed = await exchange({ code: minted.body.code, verifier }); + expect(redeemed.status).toBe(200); + expect(redeemed.body).toEqual({ success: true }); + const cookie = (redeemed.headers['set-cookie'] as unknown as string[]).find((c) => c.startsWith('trek_session=')); + expect(cookie).toMatch(/HttpOnly/); + expect(cookie).toMatch(/Max-Age=\d+/); + + const me = await request(server).get('/api/auth/me').set('Cookie', String(cookie).split(';')[0]); + expect(me.status).toBe(200); + expect(me.body.user.id).toBe(userId); + + const logins = await findRows(orm, AuditLog, { user: userId, action: 'user.login' }); + expect(logins.map((row) => JSON.parse(row.details ?? '{}'))).toContainEqual({ method: 'native_app' }); + }); + + it('NATIVE-E2E-002: refuses to mint a code without a cookie session, even for a valid bearer token', async () => { + const res = await request(server) + .post('/api/auth/native/handoff') + .set('Authorization', `Bearer ${signSession(userId)}`) + .send({ challenge }); + expect(res.status).toBe(401); + expect(res.body.code).toBe('COOKIE_AUTH_REQUIRED'); + }); + + it('NATIVE-E2E-003: validates the challenge shape', async () => { + expect((await handoff(sessionCookie(userId), { challenge: 'not-a-hash' })).status).toBe(400); + }); + + it('NATIVE-E2E-004: refuses a code presented with the wrong verifier, and the code is gone after', async () => { + const { code } = (await handoff(sessionCookie(userId))).body as { code: string }; + const wrong = await exchange({ code, verifier: 'x'.repeat(43) }); + expect(wrong.status).toBe(400); + expect(wrong.body).toEqual({ error: 'Invalid or expired code' }); + expect(wrong.headers['set-cookie']).toBeUndefined(); + + const retry = await exchange({ code, verifier }); + expect(retry.status).toBe(400); + }); + + it('NATIVE-E2E-005: rate-limits the exchange per ip', async () => { + // One after another: twenty requests at once reset the ephemeral test server's connections. + await Array.from({ length: 20 }).reduce>( + (previous, _, i) => previous.then(() => exchange({ code: `nope-${i}`, verifier })), + Promise.resolve(), + ); + const blocked = await exchange({ code: 'nope', verifier }); + expect(blocked.status).toBe(429); + }); +}); diff --git a/server/tests/unit/nest/features.controller.test.ts b/server/tests/unit/nest/features.controller.test.ts index 86dacc7ca..26038ea8f 100644 --- a/server/tests/unit/nest/features.controller.test.ts +++ b/server/tests/unit/nest/features.controller.test.ts @@ -32,12 +32,24 @@ function make(available: boolean, aiEnabled: boolean) { describe('FeaturesController (GET /api/health/features)', () => { it('FEAT-001: reports both flags on', async () => { const { controller } = make(true, true); - expect(await controller.features()).toEqual({ bookingImport: true, aiParsing: true, aiAssistant: true }); + expect(await controller.features()).toEqual({ + bookingImport: true, + aiParsing: true, + aiAssistant: true, + nativeApp: true, + nativeApi: 1, + }); }); it('FEAT-002: reports both flags off', async () => { const { controller } = make(false, false); - expect(await controller.features()).toEqual({ bookingImport: false, aiParsing: false, aiAssistant: false }); + expect(await controller.features()).toEqual({ + bookingImport: false, + aiParsing: false, + aiAssistant: false, + nativeApp: true, + nativeApi: 1, + }); }); it('FEAT-003: the two flags are independent', async () => { @@ -45,11 +57,15 @@ describe('FeaturesController (GET /api/health/features)', () => { bookingImport: true, aiParsing: false, aiAssistant: false, + nativeApp: true, + nativeApi: 1, }); expect(await make(false, true).controller.features()).toEqual({ bookingImport: false, aiParsing: true, aiAssistant: true, + nativeApp: true, + nativeApi: 1, }); }); @@ -71,6 +87,12 @@ describe('FeaturesController (GET /api/health/features)', () => { } }); + it('FEAT-014: tells the native apps it speaks their sign-in hand-off, and at which version', async () => { + const features = await make(false, false).controller.features(); + expect(features.nativeApp).toBe(true); + expect(features.nativeApi).toBe(1); + }); + it('FEAT-005: bookingImport is read live, not cached at construction', async () => { const { controller, extractor } = make(false, false); await controller.features(); diff --git a/server/tests/unit/nest/native-auth.controller.test.ts b/server/tests/unit/nest/native-auth.controller.test.ts new file mode 100644 index 000000000..0075f0061 --- /dev/null +++ b/server/tests/unit/nest/native-auth.controller.test.ts @@ -0,0 +1,102 @@ +/** + * NativeAuthController: the HTTP half of the native sign-in hand-off. The + * handoff route hands the signed-in user's id and the challenge to the + * service; the exchange route is rate-limited per ip before the code is + * touched, sets the remembered session cookie and writes the login row. + */ +import type { AuditService } from '../../../src/nest/audit/audit.service'; +import { DomainError } from '../../../src/nest/common/domain-error'; +import type { RateLimitService } from '../../../src/nest/common/rate-limit.service'; +import { RESPONSE_CONTRACT_KEY } from '../../../src/nest/common/response-contract'; +import { NativeAuthController } from '../../../src/nest/native-auth/native-auth.controller'; +import type { NativeAuthService } from '../../../src/nest/native-auth/native-auth.service'; +import type { User } from '../../../src/types'; +import { nativeHandoffResponseSchema, successResponseSchema } from '@trek/shared'; + +import type { Request, Response } from 'express'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const challenge = 'a'.repeat(64); +const verifier = 'v'.repeat(43); + +function build(opts: { redeem?: () => Promise<{ token: string; userId: number }>; allowed?: boolean } = {}) { + const nativeAuth = { + issueCode: vi.fn().mockResolvedValue('code-1'), + redeem: vi.fn(opts.redeem ?? (() => Promise.resolve({ token: 'jwt', userId: 7 }))), + }; + const audit = { writeAudit: vi.fn().mockResolvedValue(undefined) }; + const rl = { check: vi.fn().mockResolvedValue(opts.allowed ?? true) }; + const controller = new NativeAuthController( + nativeAuth as unknown as NativeAuthService, + audit as unknown as AuditService, + rl as unknown as RateLimitService, + ); + return { controller, nativeAuth, audit, rl }; +} + +const req = { ip: '10.0.0.1', headers: { 'user-agent': 'TREK Android' } } as unknown as Request; + +function makeRes() { + return { cookie: vi.fn() } as unknown as Response & { cookie: ReturnType }; +} + +beforeEach(() => vi.clearAllMocks()); + +describe('NativeAuthController.handoff', () => { + it('NATIVE-CTL-001: issues a code for the signed-in user and the given challenge', async () => { + const { controller, nativeAuth } = build(); + + expect(await controller.handoff({ challenge }, { id: 7 } as User)).toEqual({ code: 'code-1' }); + expect(nativeAuth.issueCode).toHaveBeenCalledWith(7, challenge); + }); +}); + +describe('NativeAuthController.exchange', () => { + it('NATIVE-CTL-002: sets a remembered session cookie, passes the device on and audits the login', async () => { + const { controller, nativeAuth, audit } = build(); + const res = makeRes(); + + expect(await controller.exchange({ code: 'code-1', verifier }, req, res)).toEqual({ success: true }); + expect(nativeAuth.redeem).toHaveBeenCalledWith('code-1', verifier, { userAgent: 'TREK Android' }); + expect(res.cookie).toHaveBeenCalledWith('trek_session', 'jwt', expect.objectContaining({ httpOnly: true })); + expect(audit.writeAudit).toHaveBeenCalledWith( + expect.objectContaining({ userId: 7, action: 'user.login', details: { method: 'native_app' } }), + ); + }); + + it('NATIVE-CTL-003: a code that does not redeem sets no cookie and writes no login', async () => { + const { controller, audit } = build({ + redeem: () => Promise.reject(new DomainError(400, 'Invalid or expired code')), + }); + const res = makeRes(); + + await expect(controller.exchange({ code: 'x', verifier }, req, res)).rejects.toEqual( + expect.objectContaining({ status: 400, response: { error: 'Invalid or expired code' } }), + ); + expect(res.cookie).not.toHaveBeenCalled(); + expect(audit.writeAudit).not.toHaveBeenCalled(); + }); + + it('NATIVE-CTL-004: answers 429 once the per-ip bucket is exhausted, before touching the code', async () => { + const { controller, nativeAuth, rl } = build({ allowed: false }); + + await expect(controller.exchange({ code: 'x', verifier }, req, makeRes())).rejects.toEqual( + expect.objectContaining({ status: 429 }), + ); + expect(rl.check).toHaveBeenCalledWith('native-exchange', '10.0.0.1', 20, 15 * 60 * 1000, expect.any(Number)); + expect(nativeAuth.redeem).not.toHaveBeenCalled(); + }); + + it('NATIVE-CTL-005: buckets requests without an ip under one key', async () => { + const { controller, rl } = build(); + await controller.exchange({ code: 'x', verifier }, { headers: {} } as unknown as Request, makeRes()); + + expect(rl.check).toHaveBeenCalledWith('native-exchange', 'unknown', 20, expect.any(Number), expect.any(Number)); + }); + + it('NATIVE-CTL-006: both routes declare their shared response contracts', () => { + const proto = NativeAuthController.prototype; + expect(Reflect.getMetadata(RESPONSE_CONTRACT_KEY, proto.handoff)).toBe(nativeHandoffResponseSchema); + expect(Reflect.getMetadata(RESPONSE_CONTRACT_KEY, proto.exchange)).toBe(successResponseSchema); + }); +}); diff --git a/server/tests/unit/nest/native-auth.service.test.ts b/server/tests/unit/nest/native-auth.service.test.ts new file mode 100644 index 000000000..92dd96c93 --- /dev/null +++ b/server/tests/unit/nest/native-auth.service.test.ts @@ -0,0 +1,160 @@ +/** + * NativeAuthService and the auth domain's LoginSessionService behind it, over + * the container and a real in-memory SQLite: a code minted for a challenge + * redeems once, with the matching verifier, into a tracked session, and the + * login lands on the account. + */ +import { UserSessions } from '../../../src/db/entities/UserSessions.entity'; +import { LoginSessionService } from '../../../src/nest/auth/login-session.service'; +import { NativeAuthModule } from '../../../src/nest/native-auth/native-auth.module'; +import { NativeAuthService } from '../../../src/nest/native-auth/native-auth.service'; +import { + InMemoryNativeHandoffStore, + MAX_PENDING_HANDOFFS, + NATIVE_HANDOFF_CODE_TTL_MS, + NativeHandoffStore, + type NativeHandoff, +} from '../../../src/nest/native-auth/native-handoff.store'; +import { MailerService } from '../../../src/nest/notifications/mailer/mailer.service'; +import { createSnapshotTestDb } from '../../helpers/db-mock'; +import { countRows, findRow } from '../../helpers/factories/rows'; +import { makeUser, readUser } from '../../helpers/factories/users'; +import { createTestModule, type TestModule } from '../../helpers/test-module'; +import { MikroORM } from '@mikro-orm/core'; + +import { createHash } from 'crypto'; +import jwt from 'jsonwebtoken'; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; + +const verifier = 'v'.repeat(43); +const challenge = createHash('sha256').update(verifier).digest('hex'); +const client = { userAgent: 'TREK iOS' }; + +const db = createSnapshotTestDb(); +let t: TestModule; +let service: NativeAuthService; +const orm = () => t.get(MikroORM); + +beforeAll(async () => { + t = await createTestModule({ + db, + imports: [NativeAuthModule], + overrides: [{ provide: MailerService, useValue: { sendPasswordResetEmail: vi.fn() } }], + }); + service = t.get(NativeAuthService); +}); + +afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); +}); + +afterAll(async () => { + await t.close(); + db.close(); +}); + +const refused = expect.objectContaining({ status: 400, response: { error: 'Invalid or expired code' } }); + +describe('NativeAuthService', () => { + it('NATIVE-SVC-001: redeems a code with the matching verifier into a remembered, tracked session', async () => { + const { user } = await makeUser(orm()); + const before = await readUser(orm(), user.id); + const code = await service.issueCode(user.id, challenge); + + const session = await service.redeem(code, verifier, client); + + expect(session.userId).toBe(user.id); + const claims = jwt.decode(session.token) as { id: number; jti: string; remember?: boolean }; + expect(claims.id).toBe(user.id); + expect(claims.remember).toBe(true); + const row = await findRow(orm(), UserSessions, { id: claims.jti }); + expect(row?.user_id).toBe(user.id); + expect(row?.user_agent).toBe('TREK iOS'); + const after = await readUser(orm(), user.id); + expect(after.login_count).toBe(before.login_count + 1); + expect(after.last_login).toBeTruthy(); + }); + + it('NATIVE-SVC-002: a wrong verifier is refused and burns the code with it', async () => { + const { user } = await makeUser(orm()); + const code = await service.issueCode(user.id, challenge); + + await expect(service.redeem(code, 'w'.repeat(43), client)).rejects.toEqual(refused); + await expect(service.redeem(code, verifier, client)).rejects.toEqual(refused); + }); + + it('NATIVE-SVC-003: a code is single use', async () => { + const { user } = await makeUser(orm()); + const code = await service.issueCode(user.id, challenge); + + await service.redeem(code, verifier, client); + await expect(service.redeem(code, verifier, client)).rejects.toEqual(refused); + }); + + it('NATIVE-SVC-004: an unknown code is refused', async () => { + await expect(service.redeem('nope', verifier, client)).rejects.toEqual(refused); + }); + + it('NATIVE-SVC-005: a code older than its ttl is refused', async () => { + const { user } = await makeUser(orm()); + vi.useFakeTimers({ toFake: ['Date'] }); + const code = await service.issueCode(user.id, challenge); + vi.setSystemTime(Date.now() + NATIVE_HANDOFF_CODE_TTL_MS + 1); + + await expect(service.redeem(code, verifier, client)).rejects.toEqual(refused); + }); + + it('NATIVE-SVC-006: a code whose account is gone mints no session', async () => { + const sessions = await countRows(orm(), UserSessions); + const code = await service.issueCode(987654, challenge); + + await expect(service.redeem(code, verifier, client)).rejects.toEqual(refused); + expect(await countRows(orm(), UserSessions)).toBe(sessions); + }); + + it('NATIVE-SVC-007: a full store refuses to mint another code', async () => { + vi.spyOn(t.get(NativeHandoffStore), 'put').mockResolvedValueOnce(false); + + await expect(service.issueCode(1, challenge)).rejects.toEqual(expect.objectContaining({ status: 503 })); + }); + + it('NATIVE-SVC-008: LoginSessionService answers null for an account that does not exist', async () => { + expect(await t.get(LoginSessionService).signIn(987654, true, client)).toBeNull(); + }); +}); + +describe('InMemoryNativeHandoffStore', () => { + const entry = (expiresAt: number): NativeHandoff => ({ userId: 1, challenge, expiresAt }); + + it('NATIVE-STORE-001: holds at most its cap of live codes', async () => { + const store = new InMemoryNativeHandoffStore(); + const later = Date.now() + 60_000; + const stored = await Promise.all( + Array.from({ length: MAX_PENDING_HANDOFFS }, (_, i) => store.put(`c${i}`, entry(later))), + ); + expect(stored.every(Boolean)).toBe(true); + expect(await store.put('one-too-many', entry(later))).toBe(false); + }); + + it('NATIVE-STORE-002: expired codes are dropped on the next write and make room', async () => { + const store = new InMemoryNativeHandoffStore(); + const past = Date.now() - 1; + await Promise.all(Array.from({ length: MAX_PENDING_HANDOFFS }, (_, i) => store.put(`c${i}`, entry(past)))); + + expect(await store.put('fresh', entry(Date.now() + 60_000))).toBe(true); + expect(await store.take('c0')).toBeNull(); + expect(await store.take('fresh')).toEqual(expect.objectContaining({ userId: 1 })); + }); + + it('NATIVE-STORE-003: take removes the entry, expired or not', async () => { + const store = new InMemoryNativeHandoffStore(); + await store.put('old', entry(Date.now() + 60_000)); + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(Date.now() + 120_000); + + expect(await store.take('old')).toBeNull(); + vi.useRealTimers(); + expect(await store.take('old')).toBeNull(); + }); +}); diff --git a/server/tests/unit/nest/platform.controller.test.ts b/server/tests/unit/nest/platform.controller.test.ts index 6fd7caffc..7d0df8377 100644 --- a/server/tests/unit/nest/platform.controller.test.ts +++ b/server/tests/unit/nest/platform.controller.test.ts @@ -534,6 +534,25 @@ describe('applyPlatformStatic', () => { opts.setHeaders(assetRes, '/some/app.js'); expect(assetRes.headers['Cache-Control']).toBeUndefined(); }); + + it('marks the hashed files under assets/ immutable, and nothing else', async () => { + process.env.NODE_ENV = 'production'; + const expressMod = (await import('express')).default as unknown as { static: ReturnType }; + expressMod.static.mockClear(); + const { app } = fakeApp(); + applyPlatformStatic(app); + const opts = expressMod.static.mock.calls[0][1] as { setHeaders: (res: unknown, p: string) => void }; + const header = (p: string) => { + const res = makeRes(); + opts.setHeaders(res, p); + return res.headers['Cache-Control']; + }; + expect(header('/app/public/assets/index-DbM4_q2x.js')).toBe('public, max-age=31536000, immutable'); + expect(header('C:\\app\\public\\assets\\Map-a1B2c3D4.css')).toBe('public, max-age=31536000, immutable'); + expect(header('/app/public/sw.js')).toBeUndefined(); + expect(header('/app/public/icons/icon-192.png')).toBeUndefined(); + expect(header('/app/public/assets/plain.js')).toBeUndefined(); + }); }); describe('applyPlatformSpa', () => { diff --git a/server/vitest.config.ts b/server/vitest.config.ts index f0c568be5..a057f9a5b 100644 --- a/server/vitest.config.ts +++ b/server/vitest.config.ts @@ -139,6 +139,9 @@ export default defineConfig({ 'src/nest/mcp-shared/**/*.ts': { statements: 84, branches: 59, functions: 99, lines: 88 }, 'src/nest/mcp-transport/**/*.ts': { statements: 89, branches: 79, functions: 87, lines: 90 }, 'src/nest/memories/**/*.ts': { statements: 92, branches: 83, functions: 97, lines: 94 }, + // New domain in this change, fully covered by its unit and e2e suites. + // Pinned a little under that until a full run regenerates the block. + 'src/nest/native-auth/**/*.ts': { statements: 95, branches: 90, functions: 95, lines: 95 }, 'src/nest/notifications/**/*.ts': { statements: 83, branches: 72, functions: 85, lines: 87 }, 'src/nest/oauth/**/*.ts': { statements: 96, branches: 95, functions: 97, lines: 97 }, 'src/nest/oidc/**/*.ts': { statements: 88, branches: 83, functions: 91, lines: 92 }, diff --git a/shared/scripts/i18n-parity.mjs b/shared/scripts/i18n-parity.mjs index bdc20a12f..cf04516e3 100644 --- a/shared/scripts/i18n-parity.mjs +++ b/shared/scripts/i18n-parity.mjs @@ -34,14 +34,14 @@ // first column of the file, matching the regex below). Nested objects, function // bodies, and inline comments are ignored. This matches how `t(key)` calls // resolve at runtime in TranslationContext. - -import { readFileSync } from 'node:fs'; -import { join } from 'node:path'; import { getIntlLanguage } from '../src/i18n/languages.ts'; import { allPluralCategories, integerPluralCategories, pluralFormOf, pluralGroups } from '../src/i18n/plural.ts'; import { I18N_ROOT, listDomainFiles, listLocales, readCatalog } from './i18n-catalog.mjs'; import { compare, countUntranslated, formatGrown, readBaseline } from './i18n-untranslated.mjs'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; + // Match a top-level translation key declaration: leading whitespace, then a // quoted key (must start with a lowercase letter), then a colon. This is the // exact pattern every domain file uses. Keys may hold a colon themselves @@ -102,6 +102,11 @@ export const NOT_PLURAL = [ { key: 'dawarich.duration.hours', because: 'a duration in a unit symbol (h), the same for any number' }, { key: 'dawarich.duration.hoursMinutes', because: 'a duration in unit symbols (h, min), the same for any number' }, { key: 'files.uploadErrorSize', because: 'a size limit in a unit symbol (MB), the same for any number' }, + { key: 'native.plans.storage', because: 'a storage size in a unit symbol (GB), the same for any number' }, + { + key: 'native.plans.aiDocs', + because: 'a monthly document allowance, always in the tens, so no singular ever shows', + }, ]; /** @@ -187,10 +192,7 @@ function checkParity() { if (locale === 'en') continue; const localeFiles = listDomainFiles(locale); - const { missing: missingFiles, extra: extraFiles } = diffSets( - new Set(enFiles), - new Set(localeFiles), - ); + const { missing: missingFiles, extra: extraFiles } = diffSets(new Set(enFiles), new Set(localeFiles)); if (missingFiles.length || extraFiles.length) { report.fileDrift.push({ locale, missing: missingFiles, extra: extraFiles }); @@ -278,7 +280,9 @@ function formatReport(report) { } else if (grown.length === 0) { lines.push( 'Untranslated strings: OK' + - (lowerable ? ` (${lowerable} baseline entries can come down: node scripts/i18n-untranslated.mjs --update)` : ''), + (lowerable + ? ` (${lowerable} baseline entries can come down: node scripts/i18n-untranslated.mjs --update)` + : ''), ); } else { lines.push('Untranslated strings: grew past scripts/i18n-untranslated-baseline.json'); diff --git a/shared/scripts/i18n-untranslated.mjs b/shared/scripts/i18n-untranslated.mjs index 6857ef73d..259ff4070 100644 --- a/shared/scripts/i18n-untranslated.mjs +++ b/shared/scripts/i18n-untranslated.mjs @@ -75,6 +75,8 @@ export const BRAND_NAMES = [ 'Studio', 'Synology', 'Synology Photos', + // The hosted TREK offering, a product name like Vacay and Atlas. + 'TREK Cloud', 'Vacay', 'Webhook', 'wanderer', diff --git a/shared/src/i18n/ar/index.ts b/shared/src/i18n/ar/index.ts index bcc4778a6..403813aa6 100644 --- a/shared/src/i18n/ar/index.ts +++ b/shared/src/i18n/ar/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -101,6 +102,7 @@ const locale = { ...share, ...shared, ...login, + ...native, ...vacay, ...collection, ...atlas, diff --git a/shared/src/i18n/ar/native.ts b/shared/src/i18n/ar/native.ts new file mode 100644 index 000000000..4fbfcd07e --- /dev/null +++ b/shared/src/i18n/ar/native.ts @@ -0,0 +1,77 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': 'الاتصال بـ TREK', + 'native.connect.hint': 'أدخل العنوان الذي تفتح به TREK في متصفحك.', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': 'اتصال', + 'native.connect.checking': 'جارٍ التحقق…', + 'native.connect.tryDemo': 'لا يوجد خادم بعد؟ جرّب النسخة التجريبية', + 'native.connect.whatIsServer': 'ما هو خادم TREK؟', + 'native.connect.errorInvalid': 'لا يبدو هذا عنوان ويب.', + 'native.connect.errorUnreachable': 'لا يستجيب أي خادم على هذا العنوان. تحقق من العنوان ومن اتصالك.', + 'native.connect.errorNotTrek': 'الخادم على هذا العنوان ليس TREK.', + 'native.connect.errorTooOld': 'خادم TREK هذا قديم جدًا بالنسبة للتطبيق. يحتاج إلى تحديث أولًا.', + 'native.offline.title': 'تعذّر الوصول إلى الخادم', + 'native.offline.hint': 'تعذّر على TREK الوصول إلى {server}. تحقق من اتصالك ثم حاول مرة أخرى.', + 'native.offline.retry': 'إعادة المحاولة', + 'native.changeServer': 'تغيير الخادم', + 'native.login.failed': 'تعذّر تسجيل الدخول. يرجى المحاولة مرة أخرى.', + 'native.handoff.title': 'المتابعة في التطبيق', + 'native.handoff.hint': 'لقد سجّلت الدخول باسم {name}. افتح تطبيق TREK لإكمال تسجيل الدخول هناك.', + 'native.handoff.open': 'فتح تطبيق TREK', + 'native.handoff.switchAccount': 'استخدام حساب آخر', + 'native.privacy': 'سياسة الخصوصية', + 'native.settings.server': 'الخادم', + 'native.settings.serverHint': 'هذا التطبيق متصل بـ {server}.', + 'native.welcome.headline': 'خطّطوا رحلاتكم معًا.', + 'native.welcome.sub': 'يجمع TREK كل يوم ومكان وحجز ومصروف في خطة حيّة واحدة تحرّرها المجموعة كلها معًا.', + 'native.welcome.connect': 'اربط TREK الخاص بك', + 'native.welcome.connectSub': 'افتح العنوان الذي تستخدمه بالفعل', + 'native.welcome.getCloud': 'احصل على TREK Cloud', + 'native.welcome.getCloudSub': 'مُستضاف من أجلك، دون إعداد', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': 'نستضيف TREK من أجلك، على عنوانك الخاص. لا شيء لتثبيته أو صيانته: جاهز في دقائق.', + 'native.cloud.f1': 'عنوانك الخاص، على خوادم في ألمانيا', + 'native.cloud.f2': 'جاهز في دقائق، والتحديثات على عاتقنا', + 'native.cloud.f3': 'بياناتك تبقى لك: بلا إعلانات، بلا تتبّع', + 'native.cloud.cta': 'ابدأ', + 'native.cloud.haveServer': 'لديّ TREK بالفعل', + 'native.connecting': 'جارٍ الاتصال بـ {host}', + 'native.back': 'رجوع', + 'native.plans.title': 'اختر خطتك', + 'native.plans.sub': 'TREK مُستضاف على عنوانك الخاص. غيّر أو ألغِ في أي وقت.', + 'native.plans.monthly': 'شهريًا', + 'native.plans.yearly': 'سنويًا', + 'native.plans.save': 'شهران مجانًا', + 'native.plans.perMonth': 'شهريًا', + 'native.plans.perYear': 'سنويًا', + 'native.plans.aiDocs': '{n} مستند بالذكاء الاصطناعي شهريًا', + 'native.plans.noAi': 'بلا مستندات ذكاء اصطناعي', + 'native.plans.storage': '{n} غيغابايت تخزين', + 'native.plans.unlimited': 'أماكن ورحلات وأشخاص بلا حدود', + 'native.plans.subscribe': 'اشترك', + 'native.plans.loadError': 'تعذّر تحميل الخطط. تحقق من اتصالك وحاول مرة أخرى.', + 'native.plans.retry': 'حاول مرة أخرى', + 'native.plans.soon': 'الاشتراكات داخل التطبيق قادمة قريبًا. أكمل الآن على الموقع.', + 'native.claim.title': 'أنشئ TREK الخاص بك', + 'native.claim.sub': 'اختر عنوانك. سنُعدّه على الفور.', + 'native.claim.addressLabel': 'عنوانك', + 'native.claim.taken': 'هذا العنوان مُستخدَم.', + 'native.claim.invalid': 'ثلاثة أحرف أو أرقام أو شرطات أو أكثر.', + 'native.claim.reserved': 'هذا العنوان محجوز.', + 'native.claim.free': 'متاح', + 'native.claim.emailLabel': 'البريد الإلكتروني', + 'native.claim.emailHint': 'لحسابك وإيصالاتك.', + 'native.claim.subscribe': 'اشترك مقابل {price}', + 'native.claim.cancelled': 'تم إلغاء الشراء.', + 'native.claim.failed': 'لم تتم عملية الشراء. حاول مرة أخرى.', + 'native.claim.redeemFailed': 'تعذّر علينا إعداد TREK الخاص بك. حاول مرة أخرى.', + 'native.provisioning.title': 'جارٍ إعداد TREK الخاص بك', + 'native.provisioning.sub': 'نُحضّر {host}. يستغرق هذا دقيقة واحدة فقط.', + 'native.provisioning.failedTitle': 'شارف على الجهوزية', + 'native.provisioning.failedSub': 'TREK الخاص بك في الطريق. حاول مرة أخرى بعد قليل، أو افتح التطبيق لاحقًا.', + 'native.provisioning.retry': 'حاول الآن', +}; + +export default native; diff --git a/shared/src/i18n/az/index.ts b/shared/src/i18n/az/index.ts index 7c371269a..1a0ff1d80 100644 --- a/shared/src/i18n/az/index.ts +++ b/shared/src/i18n/az/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -96,6 +97,7 @@ const locale = { ...share, ...shared, ...login, + ...native, ...vacay, ...collection, ...atlas, diff --git a/shared/src/i18n/az/native.ts b/shared/src/i18n/az/native.ts new file mode 100644 index 000000000..637381f36 --- /dev/null +++ b/shared/src/i18n/az/native.ts @@ -0,0 +1,79 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': 'TREK-ə qoşulun', + 'native.connect.hint': 'TREK-i brauzerdə açdığınız ünvanı daxil edin.', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': 'Qoşul', + 'native.connect.checking': 'Yoxlanılır…', + 'native.connect.tryDemo': 'Hələ serveriniz yoxdur? Demonu sınayın', + 'native.connect.whatIsServer': 'TREK serveri nədir?', + 'native.connect.errorInvalid': 'Bu, veb ünvana bənzəmir.', + 'native.connect.errorUnreachable': 'Bu ünvanda heç bir server cavab vermədi. Ünvanı və bağlantınızı yoxlayın.', + 'native.connect.errorNotTrek': 'Bu ünvandakı server TREK deyil.', + 'native.connect.errorTooOld': 'Bu TREK serveri tətbiq üçün çox köhnədir. Əvvəlcə onu yeniləmək lazımdır.', + 'native.offline.title': 'Serverə çatmaq mümkün deyil', + 'native.offline.hint': 'TREK {server} ünvanına çata bilmədi. Bağlantınızı yoxlayın və yenidən cəhd edin.', + 'native.offline.retry': 'Yenidən cəhd et', + 'native.changeServer': 'Serveri dəyiş', + 'native.login.failed': 'Daxil olmaq alınmadı. Zəhmət olmasa, yenidən cəhd edin.', + 'native.handoff.title': 'Tətbiqdə davam edin', + 'native.handoff.hint': 'Siz {name} kimi daxil olmusunuz. Girişi orada tamamlamaq üçün TREK tətbiqini açın.', + 'native.handoff.open': 'TREK tətbiqini aç', + 'native.handoff.switchAccount': 'Başqa hesabdan istifadə et', + 'native.privacy': 'Məxfilik siyasəti', + 'native.settings.server': 'Server', // same-as-en + 'native.settings.serverHint': 'Bu tətbiq {server} serverinə qoşulub.', + 'native.welcome.headline': 'Səyahətləri birlikdə planlayın.', + 'native.welcome.sub': + 'TREK hər günü, yeri, rezervasiyanı və xərci bütün qrupun birlikdə redaktə etdiyi tək bir canlı planda saxlayır.', + 'native.welcome.connect': 'TREK-inizi qoşun', + 'native.welcome.connectSub': 'Artıq istifadə etdiyiniz ünvanı açın', + 'native.welcome.getCloud': 'TREK Cloud əldə edin', + 'native.welcome.getCloudSub': 'Sizin üçün hostlanır, quraşdırma yoxdur', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': + 'TREK-i sizin üçün, öz ünvanınızda hostlayırıq. Quraşdırmaq lazım deyil, saxlamaq lazım deyil: bir neçə dəqiqəyə hazırdır.', + 'native.cloud.f1': 'Öz ünvanınız, Almaniyadakı serverlərdə', + 'native.cloud.f2': 'Bir neçə dəqiqəyə hazır, yeniləmələr bizdən', + 'native.cloud.f3': 'Məlumatlarınız sizin qalır: reklam yoxdur, izləmə yoxdur', + 'native.cloud.cta': 'Başla', + 'native.cloud.haveServer': 'Artıq TREK-im var', + 'native.connecting': '{host} ünvanına qoşulur', + 'native.back': 'Geri', + 'native.plans.title': 'Planınızı seçin', + 'native.plans.sub': 'Öz ünvanınızda hostlanan TREK. İstənilən vaxt dəyişin və ya ləğv edin.', + 'native.plans.monthly': 'Aylıq', + 'native.plans.yearly': 'İllik', + 'native.plans.save': '2 ay pulsuz', + 'native.plans.perMonth': 'ayda', + 'native.plans.perYear': 'ildə', + 'native.plans.aiDocs': 'ayda {n} süni intellekt sənədi', + 'native.plans.noAi': 'Süni intellekt sənədi yoxdur', + 'native.plans.storage': '{n} GB yaddaş', + 'native.plans.unlimited': 'Limitsiz yer, səyahət və insan', + 'native.plans.subscribe': 'Abunə ol', + 'native.plans.loadError': 'Planları yükləmək mümkün olmadı. Bağlantınızı yoxlayın və yenidən cəhd edin.', + 'native.plans.retry': 'Yenidən cəhd edin', + 'native.plans.soon': 'Tətbiqdaxili abunələr tezliklə gəlir. Hələlik veb saytda tamamlayın.', + 'native.claim.title': 'TREK-inizi yaradın', + 'native.claim.sub': 'Ünvanınızı seçin. Dərhal hazırlayırıq.', + 'native.claim.addressLabel': 'Ünvanınız', + 'native.claim.taken': 'Bu ünvan tutulub.', + 'native.claim.invalid': 'Üç və ya daha çox hərf, rəqəm və defis.', + 'native.claim.reserved': 'Bu ünvan ehtiyat saxlanılıb.', + 'native.claim.free': 'Əlçatandır', + 'native.claim.emailLabel': 'E-poçt', + 'native.claim.emailHint': 'Hesabınız və qəbzləriniz üçün.', + 'native.claim.subscribe': '{price} qarşılığında abunə ol', + 'native.claim.cancelled': 'Alış ləğv edildi.', + 'native.claim.failed': 'Alış baş tutmadı. Zəhmət olmasa yenidən cəhd edin.', + 'native.claim.redeemFailed': 'TREK-inizi hazırlaya bilmədik. Zəhmət olmasa yenidən cəhd edin.', + 'native.provisioning.title': 'TREK-iniz hazırlanır', + 'native.provisioning.sub': '{host} hazırlanır. Bu yalnız bir dəqiqə çəkir.', + 'native.provisioning.failedTitle': 'Demək olar ki hazırdır', + 'native.provisioning.failedSub': 'TREK-iniz yoldadır. Bir azdan yenidən cəhd edin və ya tətbiqi sonra açın.', + 'native.provisioning.retry': 'İndi cəhd edin', +}; + +export default native; diff --git a/shared/src/i18n/br/index.ts b/shared/src/i18n/br/index.ts index af63b0baa..92d2aca27 100644 --- a/shared/src/i18n/br/index.ts +++ b/shared/src/i18n/br/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -101,6 +102,7 @@ const locale = { ...share, ...shared, ...login, + ...native, ...vacay, ...collection, ...atlas, diff --git a/shared/src/i18n/br/native.ts b/shared/src/i18n/br/native.ts new file mode 100644 index 000000000..3e376bcc3 --- /dev/null +++ b/shared/src/i18n/br/native.ts @@ -0,0 +1,79 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': 'Conectar ao TREK', + 'native.connect.hint': 'Digite o endereço em que você abre o TREK no navegador.', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': 'Conectar', + 'native.connect.checking': 'Verificando…', + 'native.connect.tryDemo': 'Ainda não tem servidor? Experimente a demonstração', + 'native.connect.whatIsServer': 'O que é um servidor TREK?', + 'native.connect.errorInvalid': 'Isso não parece um endereço da web.', + 'native.connect.errorUnreachable': 'Nenhum servidor respondeu neste endereço. Verifique o endereço e sua conexão.', + 'native.connect.errorNotTrek': 'O servidor neste endereço não é o TREK.', + 'native.connect.errorTooOld': 'Este servidor TREK é antigo demais para o app. Ele precisa ser atualizado primeiro.', + 'native.offline.title': 'Servidor inacessível', + 'native.offline.hint': 'O TREK não conseguiu acessar {server}. Verifique sua conexão e tente novamente.', + 'native.offline.retry': 'Tentar novamente', + 'native.changeServer': 'Trocar de servidor', + 'native.login.failed': 'Não foi possível entrar. Tente novamente.', + 'native.handoff.title': 'Continuar no app', + 'native.handoff.hint': 'Você entrou como {name}. Abra o app TREK para concluir o login por lá.', + 'native.handoff.open': 'Abrir o app TREK', + 'native.handoff.switchAccount': 'Usar outra conta', + 'native.privacy': 'Política de privacidade', + 'native.settings.server': 'Servidor', + 'native.settings.serverHint': 'Este app está conectado a {server}.', + 'native.welcome.headline': 'Planejem viagens juntos.', + 'native.welcome.sub': + 'O TREK reúne cada dia, lugar, reserva e gasto em um único plano ao vivo que todo o grupo edita junto.', + 'native.welcome.connect': 'Conecte seu TREK', + 'native.welcome.connectSub': 'Abra o endereço que você já usa', + 'native.welcome.getCloud': 'Obter o TREK Cloud', + 'native.welcome.getCloudSub': 'Hospedado para você, sem instalação', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': + 'Nós hospedamos o TREK para você, no seu próprio endereço. Nada para instalar, nada para manter: pronto em minutos.', + 'native.cloud.f1': 'Seu próprio endereço, em servidores na Alemanha', + 'native.cloud.f2': 'Pronto em minutos, com as atualizações por nossa conta', + 'native.cloud.f3': 'Seus dados continuam seus: sem anúncios, sem rastreamento', + 'native.cloud.cta': 'Começar', + 'native.cloud.haveServer': 'Já tenho um TREK', + 'native.connecting': 'Conectando a {host}', + 'native.back': 'Voltar', + 'native.plans.title': 'Escolha seu plano', + 'native.plans.sub': 'TREK hospedado no seu próprio endereço. Altere ou cancele quando quiser.', + 'native.plans.monthly': 'Mensal', + 'native.plans.yearly': 'Anual', + 'native.plans.save': '2 meses grátis', + 'native.plans.perMonth': 'por mês', + 'native.plans.perYear': 'por ano', + 'native.plans.aiDocs': '{n} documentos com IA por mês', + 'native.plans.noAi': 'Sem documentos com IA', + 'native.plans.storage': '{n} GB de armazenamento', + 'native.plans.unlimited': 'Lugares, viagens e pessoas sem limite', + 'native.plans.subscribe': 'Assinar', + 'native.plans.loadError': 'Não foi possível carregar os planos. Verifique sua conexão e tente novamente.', + 'native.plans.retry': 'Tentar de novo', + 'native.plans.soon': 'As assinaturas no app estão chegando. Por enquanto, conclua no site.', + 'native.claim.title': 'Crie seu TREK', + 'native.claim.sub': 'Escolha seu endereço. Preparamos tudo na hora.', + 'native.claim.addressLabel': 'Seu endereço', + 'native.claim.taken': 'Esse endereço já está em uso.', + 'native.claim.invalid': 'Três ou mais letras, números e hifens.', + 'native.claim.reserved': 'Esse endereço está reservado.', + 'native.claim.free': 'Disponível', + 'native.claim.emailLabel': 'E-mail', + 'native.claim.emailHint': 'Para sua conta e os recibos.', + 'native.claim.subscribe': 'Assinar por {price}', + 'native.claim.cancelled': 'Compra cancelada.', + 'native.claim.failed': 'A compra não foi concluída. Tente novamente.', + 'native.claim.redeemFailed': 'Não conseguimos preparar seu TREK. Tente novamente.', + 'native.provisioning.title': 'Preparando seu TREK', + 'native.provisioning.sub': 'Preparando {host}. Isso leva só um minuto.', + 'native.provisioning.failedTitle': 'Quase pronto', + 'native.provisioning.failedSub': 'Seu TREK está a caminho. Tente novamente em instantes ou abra o app mais tarde.', + 'native.provisioning.retry': 'Tentar agora', +}; + +export default native; diff --git a/shared/src/i18n/ca/index.ts b/shared/src/i18n/ca/index.ts index f79d7f19d..5c85fc409 100644 --- a/shared/src/i18n/ca/index.ts +++ b/shared/src/i18n/ca/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -101,6 +102,7 @@ const locale = { ...share, ...shared, ...login, + ...native, ...vacay, ...collection, ...help, diff --git a/shared/src/i18n/ca/native.ts b/shared/src/i18n/ca/native.ts new file mode 100644 index 000000000..5a937923f --- /dev/null +++ b/shared/src/i18n/ca/native.ts @@ -0,0 +1,79 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': 'Connecta amb TREK', + 'native.connect.hint': 'Introdueix l’adreça amb què obres TREK al navegador.', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': 'Connecta', + 'native.connect.checking': 'S’està comprovant…', + 'native.connect.tryDemo': 'Encara no tens servidor? Prova la demostració', + 'native.connect.whatIsServer': 'Què és un servidor TREK?', + 'native.connect.errorInvalid': 'Això no sembla una adreça web.', + 'native.connect.errorUnreachable': 'Cap servidor respon en aquesta adreça. Comprova l’adreça i la connexió.', + 'native.connect.errorNotTrek': 'El servidor d’aquesta adreça no és TREK.', + 'native.connect.errorTooOld': 'Aquest servidor de TREK és massa antic per a l’app. Primer cal actualitzar-lo.', + 'native.offline.title': 'No es pot accedir al servidor', + 'native.offline.hint': 'TREK no ha pogut connectar amb {server}. Comprova la connexió i torna-ho a provar.', + 'native.offline.retry': 'Torna-ho a provar', + 'native.changeServer': 'Canvia de servidor', + 'native.login.failed': 'No s’ha pogut iniciar la sessió. Torna-ho a provar.', + 'native.handoff.title': 'Continua a l’app', + 'native.handoff.hint': 'Has iniciat la sessió com a {name}. Obre l’app de TREK per acabar d’iniciar-hi la sessió.', + 'native.handoff.open': 'Obre l’app de TREK', + 'native.handoff.switchAccount': 'Fes servir un altre compte', + 'native.privacy': 'Política de privadesa', + 'native.settings.server': 'Servidor', + 'native.settings.serverHint': 'Aquesta app està connectada a {server}.', + 'native.welcome.headline': 'Planifiqueu viatges junts.', + 'native.welcome.sub': + 'El TREK recull cada dia, lloc, reserva i despesa en un únic pla en viu que tot el grup edita alhora.', + 'native.welcome.connect': 'Connecta el teu TREK', + 'native.welcome.connectSub': 'Obre l’adreça que ja fas servir', + 'native.welcome.getCloud': 'Obtén el TREK Cloud', + 'native.welcome.getCloudSub': 'Allotjat per tu, sense instal·lació', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': + 'Allotgem el TREK per tu, a la teva pròpia adreça. Res a instal·lar, res a mantenir: a punt en minuts.', + 'native.cloud.f1': 'La teva pròpia adreça, en servidors a Alemanya', + 'native.cloud.f2': 'A punt en minuts, amb les actualitzacions a càrrec nostre', + 'native.cloud.f3': 'Les teves dades segueixen sent teves: sense anuncis, sense seguiment', + 'native.cloud.cta': 'Comença', + 'native.cloud.haveServer': 'Ja tinc un TREK', + 'native.connecting': 'Connectant a {host}', + 'native.back': 'Enrere', + 'native.plans.title': 'Tria el teu pla', + 'native.plans.sub': 'TREK allotjat a la teva pròpia adreça. Canvia o cancel·la quan vulguis.', + 'native.plans.monthly': 'Mensual', + 'native.plans.yearly': 'Anual', + 'native.plans.save': '2 mesos gratis', + 'native.plans.perMonth': 'al mes', + 'native.plans.perYear': 'a l’any', + 'native.plans.aiDocs': '{n} documents amb IA al mes', + 'native.plans.noAi': 'Sense documents amb IA', + 'native.plans.storage': '{n} GB d’emmagatzematge', + 'native.plans.unlimited': 'Llocs, viatges i persones sense límit', + 'native.plans.subscribe': 'Subscriu-te', + 'native.plans.loadError': 'No s’han pogut carregar els plans. Comprova la connexió i torna-ho a provar.', + 'native.plans.retry': 'Torna-ho a provar', + 'native.plans.soon': 'Les subscripcions a l’app arribaran aviat. De moment, acaba al web.', + 'native.claim.title': 'Crea el teu TREK', + 'native.claim.sub': 'Tria la teva adreça. Ho preparem de seguida.', + 'native.claim.addressLabel': 'La teva adreça', + 'native.claim.taken': 'Aquesta adreça ja està ocupada.', + 'native.claim.invalid': 'Tres o més lletres, xifres i guions.', + 'native.claim.reserved': 'Aquesta adreça està reservada.', + 'native.claim.free': 'Disponible', + 'native.claim.emailLabel': 'Correu', + 'native.claim.emailHint': 'Per al teu compte i els rebuts.', + 'native.claim.subscribe': 'Subscriu-te per {price}', + 'native.claim.cancelled': 'Compra cancel·lada.', + 'native.claim.failed': 'La compra no s’ha completat. Torna-ho a provar.', + 'native.claim.redeemFailed': 'No hem pogut preparar el teu TREK. Torna-ho a provar.', + 'native.provisioning.title': 'Preparant el teu TREK', + 'native.provisioning.sub': 'Preparant {host}. Només triga un minut.', + 'native.provisioning.failedTitle': 'Gairebé a punt', + 'native.provisioning.failedSub': 'El teu TREK està en camí. Torna-ho a provar en un moment o obre l’app més tard.', + 'native.provisioning.retry': 'Prova-ho ara', +}; + +export default native; diff --git a/shared/src/i18n/cs/index.ts b/shared/src/i18n/cs/index.ts index bcc4778a6..403813aa6 100644 --- a/shared/src/i18n/cs/index.ts +++ b/shared/src/i18n/cs/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -101,6 +102,7 @@ const locale = { ...share, ...shared, ...login, + ...native, ...vacay, ...collection, ...atlas, diff --git a/shared/src/i18n/cs/native.ts b/shared/src/i18n/cs/native.ts new file mode 100644 index 000000000..f2755e174 --- /dev/null +++ b/shared/src/i18n/cs/native.ts @@ -0,0 +1,79 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': 'Připojit k TREK', + 'native.connect.hint': 'Zadejte adresu, na které otevíráte TREK v prohlížeči.', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': 'Připojit', + 'native.connect.checking': 'Ověřování…', + 'native.connect.tryDemo': 'Ještě nemáte server? Vyzkoušejte demo', + 'native.connect.whatIsServer': 'Co je server TREK?', + 'native.connect.errorInvalid': 'To nevypadá jako webová adresa.', + 'native.connect.errorUnreachable': 'Na této adrese neodpovídá žádný server. Zkontrolujte adresu a připojení.', + 'native.connect.errorNotTrek': 'Server na této adrese není TREK.', + 'native.connect.errorTooOld': 'Tento server TREK je pro aplikaci příliš starý. Nejprve potřebuje aktualizaci.', + 'native.offline.title': 'Server není dostupný', + 'native.offline.hint': 'TREK se nepodařilo spojit s {server}. Zkontrolujte připojení a zkuste to znovu.', + 'native.offline.retry': 'Zkusit znovu', + 'native.changeServer': 'Změnit server', + 'native.login.failed': 'Přihlášení se nezdařilo. Zkuste to prosím znovu.', + 'native.handoff.title': 'Pokračovat v aplikaci', + 'native.handoff.hint': 'Jste přihlášeni jako {name}. Otevřete aplikaci TREK a dokončete přihlášení v ní.', + 'native.handoff.open': 'Otevřít aplikaci TREK', + 'native.handoff.switchAccount': 'Použít jiný účet', + 'native.privacy': 'Zásady ochrany osobních údajů', + 'native.settings.server': 'Server', // same-as-en + 'native.settings.serverHint': 'Tato aplikace je připojena k {server}.', + 'native.welcome.headline': 'Plánujte cesty společně.', + 'native.welcome.sub': + 'TREK drží každý den, místo, rezervaci i výdaj v jednom živém plánu, který celá skupina upravuje společně.', + 'native.welcome.connect': 'Připojte svůj TREK', + 'native.welcome.connectSub': 'Otevřete adresu, kterou už používáte', + 'native.welcome.getCloud': 'Získat TREK Cloud', + 'native.welcome.getCloudSub': 'Hostováno za vás, bez instalace', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': + 'TREK hostujeme za vás, na vaší vlastní adrese. Nic neinstalujete, nic neudržujete: hotovo za pár minut.', + 'native.cloud.f1': 'Vlastní adresa, na serverech v Německu', + 'native.cloud.f2': 'Hotovo za pár minut, aktualizace řešíme my', + 'native.cloud.f3': 'Vaše data zůstávají vaše: žádné reklamy, žádné sledování', + 'native.cloud.cta': 'Začít', + 'native.cloud.haveServer': 'Už mám TREK', + 'native.connecting': 'Připojování k {host}', + 'native.back': 'Zpět', + 'native.plans.title': 'Vyberte si tarif', + 'native.plans.sub': 'TREK hostovaný na vaší vlastní adrese. Kdykoli změňte nebo zrušte.', + 'native.plans.monthly': 'Měsíčně', + 'native.plans.yearly': 'Ročně', + 'native.plans.save': '2 měsíce zdarma', + 'native.plans.perMonth': 'měsíčně', + 'native.plans.perYear': 'ročně', + 'native.plans.aiDocs': '{n} dokumentů s AI měsíčně', + 'native.plans.noAi': 'Žádné dokumenty s AI', + 'native.plans.storage': '{n} GB úložiště', + 'native.plans.unlimited': 'Neomezeně míst, cest a lidí', + 'native.plans.subscribe': 'Předplatit', + 'native.plans.loadError': 'Tarify se nepodařilo načíst. Zkontrolujte připojení a zkuste to znovu.', + 'native.plans.retry': 'Zkusit znovu', + 'native.plans.soon': 'Předplatné v aplikaci brzy dorazí. Zatím to dokončete na webu.', + 'native.claim.title': 'Vytvořte svůj TREK', + 'native.claim.sub': 'Vyberte si adresu. Hned ji připravíme.', + 'native.claim.addressLabel': 'Vaše adresa', + 'native.claim.taken': 'Tato adresa je obsazená.', + 'native.claim.invalid': 'Tři a více písmen, číslic a pomlček.', + 'native.claim.reserved': 'Tato adresa je rezervovaná.', + 'native.claim.free': 'Dostupné', + 'native.claim.emailLabel': 'E-mail', + 'native.claim.emailHint': 'Pro váš účet a účtenky.', + 'native.claim.subscribe': 'Předplatit za {price}', + 'native.claim.cancelled': 'Nákup zrušen.', + 'native.claim.failed': 'Nákup se nezdařil. Zkuste to znovu.', + 'native.claim.redeemFailed': 'Nepodařilo se připravit váš TREK. Zkuste to znovu.', + 'native.provisioning.title': 'Připravujeme váš TREK', + 'native.provisioning.sub': 'Připravujeme {host}. Zabere to jen minutu.', + 'native.provisioning.failedTitle': 'Téměř hotovo', + 'native.provisioning.failedSub': 'Váš TREK je na cestě. Zkuste to za chvíli znovu nebo otevřete aplikaci později.', + 'native.provisioning.retry': 'Zkusit teď', +}; + +export default native; diff --git a/shared/src/i18n/de/index.ts b/shared/src/i18n/de/index.ts index bcc4778a6..403813aa6 100644 --- a/shared/src/i18n/de/index.ts +++ b/shared/src/i18n/de/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -101,6 +102,7 @@ const locale = { ...share, ...shared, ...login, + ...native, ...vacay, ...collection, ...atlas, diff --git a/shared/src/i18n/de/native.ts b/shared/src/i18n/de/native.ts new file mode 100644 index 000000000..a69129bf7 --- /dev/null +++ b/shared/src/i18n/de/native.ts @@ -0,0 +1,80 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': 'Mit TREK verbinden', + 'native.connect.hint': 'Gib die Adresse ein, unter der du TREK im Browser öffnest.', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': 'Verbinden', + 'native.connect.checking': 'Wird geprüft…', + 'native.connect.tryDemo': 'Noch keinen Server? Probier die Demo aus', + 'native.connect.whatIsServer': 'Was ist ein TREK-Server?', + 'native.connect.errorInvalid': 'Das sieht nicht nach einer Webadresse aus.', + 'native.connect.errorUnreachable': + 'Unter dieser Adresse antwortet kein Server. Prüfe die Adresse und deine Verbindung.', + 'native.connect.errorNotTrek': 'Unter dieser Adresse läuft kein TREK.', + 'native.connect.errorTooOld': 'Dieser TREK-Server ist zu alt für die App. Er braucht zuerst ein Update.', + 'native.offline.title': 'Server nicht erreichbar', + 'native.offline.hint': 'TREK konnte {server} nicht erreichen. Prüfe deine Verbindung und versuche es erneut.', + 'native.offline.retry': 'Erneut versuchen', + 'native.changeServer': 'Server wechseln', + 'native.login.failed': 'Die Anmeldung hat nicht geklappt. Bitte versuche es erneut.', + 'native.handoff.title': 'Weiter in der App', + 'native.handoff.hint': 'Du bist als {name} angemeldet. Öffne die TREK-App, um die Anmeldung dort abzuschließen.', + 'native.handoff.open': 'TREK-App öffnen', + 'native.handoff.switchAccount': 'Anderes Konto verwenden', + 'native.privacy': 'Datenschutzerklärung', + 'native.settings.server': 'Server', // same-as-en + 'native.settings.serverHint': 'Diese App ist mit {server} verbunden.', + 'native.welcome.headline': 'Reisen gemeinsam planen.', + 'native.welcome.sub': + 'TREK hält jeden Tag, Ort, jede Buchung und Kosten in einem gemeinsamen Plan, den eure ganze Gruppe live bearbeitet.', + 'native.welcome.connect': 'Mit deinem TREK verbinden', + 'native.welcome.connectSub': 'Die Adresse öffnen, die du schon nutzt', + 'native.welcome.getCloud': 'TREK Cloud holen', + 'native.welcome.getCloudSub': 'Für dich gehostet, ohne Einrichtung', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': + 'Wir hosten TREK für dich, auf deiner eigenen Adresse. Nichts installieren, nichts warten — in Minuten bereit.', + 'native.cloud.f1': 'Eigene Adresse, auf Servern in Deutschland', + 'native.cloud.f2': 'In Minuten eingerichtet, Updates übernehmen wir', + 'native.cloud.f3': 'Deine Daten bleiben deine — keine Werbung, kein Tracking', + 'native.cloud.cta': 'Loslegen', + 'native.cloud.haveServer': 'Ich habe schon ein TREK', + 'native.connecting': 'Verbinde mit {host}', + 'native.back': 'Zurück', + 'native.plans.title': 'Tarif wählen', + 'native.plans.sub': 'Gehostetes TREK auf deiner eigenen Adresse. Jederzeit änder- oder kündbar.', + 'native.plans.monthly': 'Monatlich', + 'native.plans.yearly': 'Jährlich', + 'native.plans.save': '2 Monate gratis', + 'native.plans.perMonth': 'pro Monat', + 'native.plans.perYear': 'pro Jahr', + 'native.plans.aiDocs': '{n} KI-Dokumente im Monat', + 'native.plans.noAi': 'Keine KI-Dokumente', + 'native.plans.storage': '{n} GB Speicher', + 'native.plans.unlimited': 'Unbegrenzt Orte, Reisen und Personen', + 'native.plans.subscribe': 'Abonnieren', + 'native.plans.loadError': 'Die Tarife konnten nicht geladen werden. Prüfe deine Verbindung und versuch es erneut.', + 'native.plans.retry': 'Erneut versuchen', + 'native.plans.soon': 'In-App-Abos kommen bald. Vorerst auf der Website abschließen.', + 'native.claim.title': 'Deine TREK einrichten', + 'native.claim.sub': 'Wähle deine Adresse. Wir richten sie sofort ein.', + 'native.claim.addressLabel': 'Deine Adresse', + 'native.claim.taken': 'Diese Adresse ist vergeben.', + 'native.claim.invalid': 'Mindestens drei Buchstaben, Ziffern und Bindestriche.', + 'native.claim.reserved': 'Diese Adresse ist reserviert.', + 'native.claim.free': 'Verfügbar', + 'native.claim.emailLabel': 'E-Mail', + 'native.claim.emailHint': 'Für dein Konto und die Belege.', + 'native.claim.subscribe': 'Abonnieren für {price}', + 'native.claim.cancelled': 'Kauf abgebrochen.', + 'native.claim.failed': 'Der Kauf hat nicht geklappt. Bitte versuch es erneut.', + 'native.claim.redeemFailed': 'Wir konnten deine TREK nicht einrichten. Bitte versuch es erneut.', + 'native.provisioning.title': 'Deine TREK wird eingerichtet', + 'native.provisioning.sub': '{host} wird vorbereitet. Das dauert nur eine Minute.', + 'native.provisioning.failedTitle': 'Gleich fertig', + 'native.provisioning.failedSub': 'Deine TREK ist unterwegs. Versuch es gleich noch einmal oder öffne die App später.', + 'native.provisioning.retry': 'Jetzt versuchen', +}; + +export default native; diff --git a/shared/src/i18n/en/index.ts b/shared/src/i18n/en/index.ts index bcc4778a6..403813aa6 100644 --- a/shared/src/i18n/en/index.ts +++ b/shared/src/i18n/en/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -101,6 +102,7 @@ const locale = { ...share, ...shared, ...login, + ...native, ...vacay, ...collection, ...atlas, diff --git a/shared/src/i18n/en/native.ts b/shared/src/i18n/en/native.ts new file mode 100644 index 000000000..0a2a82f73 --- /dev/null +++ b/shared/src/i18n/en/native.ts @@ -0,0 +1,79 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': 'Connect to TREK', + 'native.connect.hint': 'Enter the address you open TREK at in your browser.', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': 'Connect', + 'native.connect.checking': 'Checking…', + 'native.connect.tryDemo': 'No server yet? Try the demo', + 'native.connect.whatIsServer': 'What is a TREK server?', + 'native.connect.errorInvalid': 'That does not look like a web address.', + 'native.connect.errorUnreachable': 'No server answered at this address. Check the address and your connection.', + 'native.connect.errorNotTrek': 'The server at this address is not TREK.', + 'native.connect.errorTooOld': 'This TREK server is too old for the app. It needs an update first.', + 'native.offline.title': 'Server not reachable', + 'native.offline.hint': 'TREK could not reach {server}. Check your connection and try again.', + 'native.offline.retry': 'Try again', + 'native.changeServer': 'Change server', + 'native.login.failed': 'Signing in did not work. Please try again.', + 'native.handoff.title': 'Continue in the app', + 'native.handoff.hint': 'You are signed in as {name}. Open the TREK app to finish signing in there.', + 'native.handoff.open': 'Open the TREK app', + 'native.handoff.switchAccount': 'Use a different account', + 'native.privacy': 'Privacy policy', + 'native.settings.server': 'Server', + 'native.settings.serverHint': 'This app is connected to {server}.', + 'native.welcome.headline': 'Plan trips together.', + 'native.welcome.sub': + 'TREK keeps every day, place, booking and cost in one live plan your whole group edits together.', + 'native.welcome.connect': 'Connect your TREK', + 'native.welcome.connectSub': 'Open the address you already use', + 'native.welcome.getCloud': 'Get TREK Cloud', + 'native.welcome.getCloudSub': 'Hosted for you, no setup', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': + 'We host TREK for you, on your own address. Nothing to install, nothing to maintain — ready in minutes.', + 'native.cloud.f1': 'Your own address, on servers in Germany', + 'native.cloud.f2': 'Set up in minutes, updates handled for you', + 'native.cloud.f3': 'Your data stays yours — no ads, no tracking', + 'native.cloud.cta': 'Get started', + 'native.cloud.haveServer': 'I already have a TREK', + 'native.connecting': 'Connecting to {host}', + 'native.back': 'Back', + 'native.plans.title': 'Choose your plan', + 'native.plans.sub': 'Hosted TREK on your own address. Change or cancel anytime.', + 'native.plans.monthly': 'Monthly', + 'native.plans.yearly': 'Yearly', + 'native.plans.save': '2 months free', + 'native.plans.perMonth': 'per month', + 'native.plans.perYear': 'per year', + 'native.plans.aiDocs': '{n} AI documents a month', + 'native.plans.noAi': 'No AI documents', + 'native.plans.storage': '{n} GB storage', + 'native.plans.unlimited': 'Unlimited places, trips and people', + 'native.plans.subscribe': 'Subscribe', + 'native.plans.loadError': 'Could not load the plans. Check your connection and try again.', + 'native.plans.retry': 'Try again', + 'native.plans.soon': 'In-app subscriptions are coming. For now, finish on the website.', + 'native.claim.title': 'Create your TREK', + 'native.claim.sub': 'Choose your address. We set it up right away.', + 'native.claim.addressLabel': 'Your address', + 'native.claim.taken': 'That address is taken.', + 'native.claim.invalid': 'Three or more letters, numbers and hyphens.', + 'native.claim.reserved': 'That address is reserved.', + 'native.claim.free': 'Available', + 'native.claim.emailLabel': 'Email', + 'native.claim.emailHint': 'For your account and receipts.', + 'native.claim.subscribe': 'Subscribe for {price}', + 'native.claim.cancelled': 'Purchase cancelled.', + 'native.claim.failed': 'The purchase did not go through. Please try again.', + 'native.claim.redeemFailed': 'We could not set up your TREK. Please try again.', + 'native.provisioning.title': 'Setting up your TREK', + 'native.provisioning.sub': 'Getting {host} ready. This only takes a minute.', + 'native.provisioning.failedTitle': 'Almost ready', + 'native.provisioning.failedSub': 'Your TREK is on its way. Try again in a moment, or open the app later.', + 'native.provisioning.retry': 'Try now', +}; + +export default native; diff --git a/shared/src/i18n/es/index.ts b/shared/src/i18n/es/index.ts index fde5d8e5b..6010d641c 100644 --- a/shared/src/i18n/es/index.ts +++ b/shared/src/i18n/es/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -101,6 +102,7 @@ const locale = { ...share, ...shared, ...login, + ...native, ...vacay, ...collection, ...atlas, diff --git a/shared/src/i18n/es/native.ts b/shared/src/i18n/es/native.ts new file mode 100644 index 000000000..abdb1a598 --- /dev/null +++ b/shared/src/i18n/es/native.ts @@ -0,0 +1,80 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': 'Conectar con TREK', + 'native.connect.hint': 'Introduce la dirección con la que abres TREK en tu navegador.', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': 'Conectar', + 'native.connect.checking': 'Comprobando…', + 'native.connect.tryDemo': '¿Aún no tienes servidor? Prueba la demo', + 'native.connect.whatIsServer': '¿Qué es un servidor TREK?', + 'native.connect.errorInvalid': 'Eso no parece una dirección web.', + 'native.connect.errorUnreachable': 'Ningún servidor responde en esta dirección. Revisa la dirección y tu conexión.', + 'native.connect.errorNotTrek': 'El servidor de esta dirección no es TREK.', + 'native.connect.errorTooOld': + 'Este servidor de TREK es demasiado antiguo para la app. Primero necesita una actualización.', + 'native.offline.title': 'Servidor no disponible', + 'native.offline.hint': 'TREK no pudo conectar con {server}. Revisa tu conexión e inténtalo de nuevo.', + 'native.offline.retry': 'Reintentar', + 'native.changeServer': 'Cambiar de servidor', + 'native.login.failed': 'No se pudo iniciar sesión. Inténtalo de nuevo.', + 'native.handoff.title': 'Continuar en la app', + 'native.handoff.hint': 'Has iniciado sesión como {name}. Abre la app de TREK para terminar de iniciar sesión allí.', + 'native.handoff.open': 'Abrir la app de TREK', + 'native.handoff.switchAccount': 'Usar otra cuenta', + 'native.privacy': 'Política de privacidad', + 'native.settings.server': 'Servidor', + 'native.settings.serverHint': 'Esta app está conectada a {server}.', + 'native.welcome.headline': 'Planificar viajes juntos.', + 'native.welcome.sub': + 'TREK reúne cada día, lugar, reserva y gasto en un único plan en vivo que todo el grupo edita a la vez.', + 'native.welcome.connect': 'Conecta tu TREK', + 'native.welcome.connectSub': 'Abre la dirección que ya usas', + 'native.welcome.getCloud': 'Obtén TREK Cloud', + 'native.welcome.getCloudSub': 'Alojado para ti, sin instalación', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': + 'Alojamos TREK por ti, en tu propia dirección. Nada que instalar, nada que mantener: listo en minutos.', + 'native.cloud.f1': 'Tu propia dirección, en servidores en Alemania', + 'native.cloud.f2': 'Listo en minutos, con las actualizaciones a nuestro cargo', + 'native.cloud.f3': 'Tus datos siguen siendo tuyos: sin anuncios, sin rastreo', + 'native.cloud.cta': 'Empezar', + 'native.cloud.haveServer': 'Ya tengo un TREK', + 'native.connecting': 'Conectando con {host}', + 'native.back': 'Atrás', + 'native.plans.title': 'Elige tu plan', + 'native.plans.sub': 'TREK alojado en tu propia dirección. Cambia o cancela cuando quieras.', + 'native.plans.monthly': 'Mensual', + 'native.plans.yearly': 'Anual', + 'native.plans.save': '2 meses gratis', + 'native.plans.perMonth': 'al mes', + 'native.plans.perYear': 'al año', + 'native.plans.aiDocs': '{n} documentos con IA al mes', + 'native.plans.noAi': 'Sin documentos con IA', + 'native.plans.storage': '{n} GB de almacenamiento', + 'native.plans.unlimited': 'Lugares, viajes y personas sin límite', + 'native.plans.subscribe': 'Suscribirse', + 'native.plans.loadError': 'No se han podido cargar los planes. Revisa tu conexión e inténtalo de nuevo.', + 'native.plans.retry': 'Reintentar', + 'native.plans.soon': 'Las suscripciones dentro de la app llegarán pronto. Por ahora, termina en la web.', + 'native.claim.title': 'Crea tu TREK', + 'native.claim.sub': 'Elige tu dirección. La preparamos al instante.', + 'native.claim.addressLabel': 'Tu dirección', + 'native.claim.taken': 'Esa dirección ya está ocupada.', + 'native.claim.invalid': 'Tres o más letras, números y guiones.', + 'native.claim.reserved': 'Esa dirección está reservada.', + 'native.claim.free': 'Disponible', + 'native.claim.emailLabel': 'Correo', + 'native.claim.emailHint': 'Para tu cuenta y los recibos.', + 'native.claim.subscribe': 'Suscribirse por {price}', + 'native.claim.cancelled': 'Compra cancelada.', + 'native.claim.failed': 'La compra no se completó. Inténtalo de nuevo.', + 'native.claim.redeemFailed': 'No pudimos preparar tu TREK. Inténtalo de nuevo.', + 'native.provisioning.title': 'Preparando tu TREK', + 'native.provisioning.sub': 'Preparando {host}. Solo tarda un minuto.', + 'native.provisioning.failedTitle': 'Casi listo', + 'native.provisioning.failedSub': 'Tu TREK está en camino. Inténtalo en un momento o abre la app más tarde.', + 'native.provisioning.retry': 'Probar ahora', +}; + +export default native; diff --git a/shared/src/i18n/et/index.ts b/shared/src/i18n/et/index.ts index 7c371269a..1a0ff1d80 100644 --- a/shared/src/i18n/et/index.ts +++ b/shared/src/i18n/et/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -96,6 +97,7 @@ const locale = { ...share, ...shared, ...login, + ...native, ...vacay, ...collection, ...atlas, diff --git a/shared/src/i18n/et/native.ts b/shared/src/i18n/et/native.ts new file mode 100644 index 000000000..f276fe0f7 --- /dev/null +++ b/shared/src/i18n/et/native.ts @@ -0,0 +1,79 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': 'Ühenda TREKiga', + 'native.connect.hint': 'Sisesta aadress, millel avad TREKi brauseris.', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': 'Ühenda', + 'native.connect.checking': 'Kontrollin…', + 'native.connect.tryDemo': 'Serverit veel pole? Proovi demot', + 'native.connect.whatIsServer': 'Mis on TREKi server?', + 'native.connect.errorInvalid': 'See ei näe välja nagu veebiaadress.', + 'native.connect.errorUnreachable': 'Sellel aadressil ei vastanud ükski server. Kontrolli aadressi ja oma ühendust.', + 'native.connect.errorNotTrek': 'Sellel aadressil olev server ei ole TREK.', + 'native.connect.errorTooOld': 'See TREKi server on rakenduse jaoks liiga vana. Seda tuleb esmalt uuendada.', + 'native.offline.title': 'Server pole kättesaadav', + 'native.offline.hint': 'TREK ei jõudnud serverini {server}. Kontrolli oma ühendust ja proovi uuesti.', + 'native.offline.retry': 'Proovi uuesti', + 'native.changeServer': 'Vaheta serverit', + 'native.login.failed': 'Sisselogimine ei õnnestunud. Palun proovi uuesti.', + 'native.handoff.title': 'Jätka rakenduses', + 'native.handoff.hint': 'Oled sisse logitud kui {name}. Ava TREKi rakendus, et sisselogimine seal lõpetada.', + 'native.handoff.open': 'Ava TREKi rakendus', + 'native.handoff.switchAccount': 'Kasuta teist kontot', + 'native.privacy': 'Privaatsuspoliitika', + 'native.settings.server': 'Server', // same-as-en + 'native.settings.serverHint': 'See rakendus on ühendatud serveriga {server}.', + 'native.welcome.headline': 'Planeerige reise koos.', + 'native.welcome.sub': + 'TREK hoiab iga päeva, koha, broneeringu ja kulu ühes elavas plaanis, mida kogu rühm koos muudab.', + 'native.welcome.connect': 'Ühenda oma TREK', + 'native.welcome.connectSub': 'Ava aadress, mida juba kasutad', + 'native.welcome.getCloud': 'Hangi TREK Cloud', + 'native.welcome.getCloudSub': 'Majutatud sinu eest, seadistamiseta', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': + 'Majutame TREK-i sinu eest, sinu enda aadressil. Midagi pole vaja paigaldada ega hallata: valmis mõne minutiga.', + 'native.cloud.f1': 'Sinu enda aadress, Saksamaa serverites', + 'native.cloud.f2': 'Valmis mõne minutiga, uuendused teeme meie', + 'native.cloud.f3': 'Sinu andmed jäävad sinu omaks: reklaamideta, jälgimiseta', + 'native.cloud.cta': 'Alusta', + 'native.cloud.haveServer': 'Mul on juba TREK', + 'native.connecting': 'Ühendumine aadressiga {host}', + 'native.back': 'Tagasi', + 'native.plans.title': 'Vali oma pakett', + 'native.plans.sub': 'TREK majutatud sinu enda aadressil. Muuda või tühista igal ajal.', + 'native.plans.monthly': 'Kuus', + 'native.plans.yearly': 'Aastas', + 'native.plans.save': '2 kuud tasuta', + 'native.plans.perMonth': 'kuus', + 'native.plans.perYear': 'aastas', + 'native.plans.aiDocs': '{n} AI-dokumenti kuus', + 'native.plans.noAi': 'AI-dokumente pole', + 'native.plans.storage': '{n} GB mahtu', + 'native.plans.unlimited': 'Piiramatult kohti, reise ja inimesi', + 'native.plans.subscribe': 'Telli', + 'native.plans.loadError': 'Pakette ei õnnestunud laadida. Kontrolli ühendust ja proovi uuesti.', + 'native.plans.retry': 'Proovi uuesti', + 'native.plans.soon': 'Rakendusesisesed tellimused on tulekul. Praegu lõpeta veebis.', + 'native.claim.title': 'Loo oma TREK', + 'native.claim.sub': 'Vali oma aadress. Seadistame selle kohe.', + 'native.claim.addressLabel': 'Sinu aadress', + 'native.claim.taken': 'See aadress on juba võetud.', + 'native.claim.invalid': 'Vähemalt kolm tähte, numbrit või sidekriipsu.', + 'native.claim.reserved': 'See aadress on reserveeritud.', + 'native.claim.free': 'Saadaval', + 'native.claim.emailLabel': 'E-post', + 'native.claim.emailHint': 'Sinu konto ja kviitungite jaoks.', + 'native.claim.subscribe': 'Telli hinnaga {price}', + 'native.claim.cancelled': 'Ost tühistatud.', + 'native.claim.failed': 'Ost ei õnnestunud. Proovi uuesti.', + 'native.claim.redeemFailed': 'Me ei saanud sinu TREK-i seadistada. Proovi uuesti.', + 'native.provisioning.title': 'Seadistame sinu TREK-i', + 'native.provisioning.sub': 'Valmistame ette aadressi {host}. See võtab vaid minuti.', + 'native.provisioning.failedTitle': 'Peaaegu valmis', + 'native.provisioning.failedSub': 'Sinu TREK on teel. Proovi hetke pärast uuesti või ava rakendus hiljem.', + 'native.provisioning.retry': 'Proovi nüüd', +}; + +export default native; diff --git a/shared/src/i18n/fr/index.ts b/shared/src/i18n/fr/index.ts index bcc4778a6..403813aa6 100644 --- a/shared/src/i18n/fr/index.ts +++ b/shared/src/i18n/fr/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -101,6 +102,7 @@ const locale = { ...share, ...shared, ...login, + ...native, ...vacay, ...collection, ...atlas, diff --git a/shared/src/i18n/fr/native.ts b/shared/src/i18n/fr/native.ts new file mode 100644 index 000000000..d4d0c966f --- /dev/null +++ b/shared/src/i18n/fr/native.ts @@ -0,0 +1,80 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': 'Se connecter à TREK', + 'native.connect.hint': 'Saisissez l’adresse à laquelle vous ouvrez TREK dans votre navigateur.', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': 'Se connecter', + 'native.connect.checking': 'Vérification…', + 'native.connect.tryDemo': 'Pas encore de serveur ? Essayez la démo', + 'native.connect.whatIsServer': 'Qu’est-ce qu’un serveur TREK ?', + 'native.connect.errorInvalid': 'Cela ne ressemble pas à une adresse web.', + 'native.connect.errorUnreachable': 'Aucun serveur ne répond à cette adresse. Vérifiez l’adresse et votre connexion.', + 'native.connect.errorNotTrek': 'Le serveur à cette adresse n’est pas TREK.', + 'native.connect.errorTooOld': 'Ce serveur TREK est trop ancien pour l’application. Il doit d’abord être mis à jour.', + 'native.offline.title': 'Serveur injoignable', + 'native.offline.hint': 'TREK n’a pas pu joindre {server}. Vérifiez votre connexion et réessayez.', + 'native.offline.retry': 'Réessayer', + 'native.changeServer': 'Changer de serveur', + 'native.login.failed': 'La connexion n’a pas abouti. Veuillez réessayer.', + 'native.handoff.title': 'Continuer dans l’application', + 'native.handoff.hint': + 'Vous êtes connecté en tant que {name}. Ouvrez l’application TREK pour y terminer la connexion.', + 'native.handoff.open': 'Ouvrir l’application TREK', + 'native.handoff.switchAccount': 'Utiliser un autre compte', + 'native.privacy': 'Politique de confidentialité', + 'native.settings.server': 'Serveur', + 'native.settings.serverHint': 'Cette application est connectée à {server}.', + 'native.welcome.headline': 'Planifiez vos voyages ensemble.', + 'native.welcome.sub': + 'TREK réunit chaque jour, lieu, réservation et dépense dans un plan commun que tout le groupe modifie en direct.', + 'native.welcome.connect': 'Connecter votre TREK', + 'native.welcome.connectSub': 'Ouvrez l’adresse que vous utilisez déjà', + 'native.welcome.getCloud': 'Obtenir TREK Cloud', + 'native.welcome.getCloudSub': 'Hébergé pour vous, sans installation', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': + 'Nous hébergeons TREK pour vous, sur votre propre adresse. Rien à installer, rien à maintenir : prêt en quelques minutes.', + 'native.cloud.f1': 'Votre propre adresse, sur des serveurs en Allemagne', + 'native.cloud.f2': 'Prêt en quelques minutes, mises à jour prises en charge', + 'native.cloud.f3': 'Vos données restent les vôtres : sans publicité, sans pistage', + 'native.cloud.cta': 'Commencer', + 'native.cloud.haveServer': 'J’ai déjà un TREK', + 'native.connecting': 'Connexion à {host}', + 'native.back': 'Retour', + 'native.plans.title': 'Choisissez votre forfait', + 'native.plans.sub': 'TREK hébergé sur votre propre adresse. Modifiable ou résiliable à tout moment.', + 'native.plans.monthly': 'Mensuel', + 'native.plans.yearly': 'Annuel', + 'native.plans.save': '2 mois offerts', + 'native.plans.perMonth': 'par mois', + 'native.plans.perYear': 'par an', + 'native.plans.aiDocs': '{n} documents IA par mois', + 'native.plans.noAi': 'Pas de documents IA', + 'native.plans.storage': '{n} Go de stockage', + 'native.plans.unlimited': 'Lieux, voyages et personnes sans limite', + 'native.plans.subscribe': 'S’abonner', + 'native.plans.loadError': 'Impossible de charger les forfaits. Vérifiez votre connexion et réessayez.', + 'native.plans.retry': 'Réessayer', + 'native.plans.soon': 'Les abonnements dans l’app arrivent bientôt. Pour l’instant, terminez sur le site.', + 'native.claim.title': 'Créez votre TREK', + 'native.claim.sub': 'Choisissez votre adresse. Nous la préparons aussitôt.', + 'native.claim.addressLabel': 'Votre adresse', + 'native.claim.taken': 'Cette adresse est déjà prise.', + 'native.claim.invalid': 'Au moins trois lettres, chiffres ou traits d’union.', + 'native.claim.reserved': 'Cette adresse est réservée.', + 'native.claim.free': 'Disponible', + 'native.claim.emailLabel': 'E-mail', + 'native.claim.emailHint': 'Pour votre compte et vos reçus.', + 'native.claim.subscribe': 'S’abonner pour {price}', + 'native.claim.cancelled': 'Achat annulé.', + 'native.claim.failed': 'L’achat n’a pas abouti. Réessayez.', + 'native.claim.redeemFailed': 'Nous n’avons pas pu préparer votre TREK. Réessayez.', + 'native.provisioning.title': 'Préparation de votre TREK', + 'native.provisioning.sub': 'Préparation de {host}. Cela ne prend qu’une minute.', + 'native.provisioning.failedTitle': 'Presque prêt', + 'native.provisioning.failedSub': 'Votre TREK arrive. Réessayez dans un instant ou rouvrez l’app plus tard.', + 'native.provisioning.retry': 'Réessayer', +}; + +export default native; diff --git a/shared/src/i18n/gr/index.ts b/shared/src/i18n/gr/index.ts index bcc4778a6..403813aa6 100644 --- a/shared/src/i18n/gr/index.ts +++ b/shared/src/i18n/gr/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -101,6 +102,7 @@ const locale = { ...share, ...shared, ...login, + ...native, ...vacay, ...collection, ...atlas, diff --git a/shared/src/i18n/gr/native.ts b/shared/src/i18n/gr/native.ts new file mode 100644 index 000000000..6bb563f04 --- /dev/null +++ b/shared/src/i18n/gr/native.ts @@ -0,0 +1,81 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': 'Σύνδεση στο TREK', + 'native.connect.hint': 'Πληκτρολογήστε τη διεύθυνση με την οποία ανοίγετε το TREK στο πρόγραμμα περιήγησης.', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': 'Σύνδεση', + 'native.connect.checking': 'Έλεγχος…', + 'native.connect.tryDemo': 'Δεν έχετε ακόμη διακομιστή; Δοκιμάστε την επίδειξη', + 'native.connect.whatIsServer': 'Τι είναι ένας διακομιστής TREK;', + 'native.connect.errorInvalid': 'Αυτό δεν μοιάζει με διεύθυνση ιστού.', + 'native.connect.errorUnreachable': + 'Κανένας διακομιστής δεν απαντά σε αυτή τη διεύθυνση. Ελέγξτε τη διεύθυνση και τη σύνδεσή σας.', + 'native.connect.errorNotTrek': 'Ο διακομιστής σε αυτή τη διεύθυνση δεν είναι TREK.', + 'native.connect.errorTooOld': + 'Αυτός ο διακομιστής TREK είναι πολύ παλιός για την εφαρμογή. Χρειάζεται πρώτα ενημέρωση.', + 'native.offline.title': 'Ο διακομιστής δεν είναι προσβάσιμος', + 'native.offline.hint': 'Το TREK δεν μπόρεσε να συνδεθεί στο {server}. Ελέγξτε τη σύνδεσή σας και δοκιμάστε ξανά.', + 'native.offline.retry': 'Δοκιμάστε ξανά', + 'native.changeServer': 'Αλλαγή διακομιστή', + 'native.login.failed': 'Η σύνδεση δεν ολοκληρώθηκε. Δοκιμάστε ξανά.', + 'native.handoff.title': 'Συνέχεια στην εφαρμογή', + 'native.handoff.hint': 'Έχετε συνδεθεί ως {name}. Ανοίξτε την εφαρμογή TREK για να ολοκληρώσετε εκεί τη σύνδεση.', + 'native.handoff.open': 'Άνοιγμα της εφαρμογής TREK', + 'native.handoff.switchAccount': 'Χρήση άλλου λογαριασμού', + 'native.privacy': 'Πολιτική απορρήτου', + 'native.settings.server': 'Διακομιστής', + 'native.settings.serverHint': 'Αυτή η εφαρμογή είναι συνδεδεμένη στο {server}.', + 'native.welcome.headline': 'Σχεδιάστε ταξίδια μαζί.', + 'native.welcome.sub': + 'Το TREK κρατά κάθε μέρα, μέρος, κράτηση και έξοδο σε ένα ζωντανό πλάνο που όλη η ομάδα επεξεργάζεται μαζί.', + 'native.welcome.connect': 'Συνδέστε το TREK σας', + 'native.welcome.connectSub': 'Ανοίξτε τη διεύθυνση που ήδη χρησιμοποιείτε', + 'native.welcome.getCloud': 'Αποκτήστε το TREK Cloud', + 'native.welcome.getCloudSub': 'Φιλοξενείται για εσάς, χωρίς εγκατάσταση', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': + 'Φιλοξενούμε το TREK για εσάς, στη δική σας διεύθυνση. Τίποτα για εγκατάσταση, τίποτα για συντήρηση: έτοιμο σε λίγα λεπτά.', + 'native.cloud.f1': 'Η δική σας διεύθυνση, σε διακομιστές στη Γερμανία', + 'native.cloud.f2': 'Έτοιμο σε λίγα λεπτά, τις ενημερώσεις τις αναλαμβάνουμε εμείς', + 'native.cloud.f3': 'Τα δεδομένα σας παραμένουν δικά σας: χωρίς διαφημίσεις, χωρίς παρακολούθηση', + 'native.cloud.cta': 'Ξεκινήστε', + 'native.cloud.haveServer': 'Έχω ήδη ένα TREK', + 'native.connecting': 'Σύνδεση με {host}', + 'native.back': 'Πίσω', + 'native.plans.title': 'Επιλέξτε το πλάνο σας', + 'native.plans.sub': 'TREK στη δική σας διεύθυνση. Αλλάξτε ή ακυρώστε όποτε θέλετε.', + 'native.plans.monthly': 'Μηνιαία', + 'native.plans.yearly': 'Ετήσια', + 'native.plans.save': '2 μήνες δωρεάν', + 'native.plans.perMonth': 'τον μήνα', + 'native.plans.perYear': 'τον χρόνο', + 'native.plans.aiDocs': '{n} έγγραφα AI τον μήνα', + 'native.plans.noAi': 'Χωρίς έγγραφα AI', + 'native.plans.storage': '{n} GB αποθηκευτικού χώρου', + 'native.plans.unlimited': 'Απεριόριστα μέρη, ταξίδια και άτομα', + 'native.plans.subscribe': 'Εγγραφή', + 'native.plans.loadError': 'Δεν ήταν δυνατή η φόρτωση των πλάνων. Ελέγξτε τη σύνδεσή σας και δοκιμάστε ξανά.', + 'native.plans.retry': 'Δοκιμάστε ξανά', + 'native.plans.soon': 'Οι συνδρομές εντός εφαρμογής έρχονται. Προς το παρόν, ολοκληρώστε στον ιστότοπο.', + 'native.claim.title': 'Δημιουργήστε το TREK σας', + 'native.claim.sub': 'Επιλέξτε τη διεύθυνσή σας. Το ετοιμάζουμε αμέσως.', + 'native.claim.addressLabel': 'Η διεύθυνσή σας', + 'native.claim.taken': 'Αυτή η διεύθυνση είναι πιασμένη.', + 'native.claim.invalid': 'Τρία ή περισσότερα γράμματα, αριθμοί και παύλες.', + 'native.claim.reserved': 'Αυτή η διεύθυνση είναι δεσμευμένη.', + 'native.claim.free': 'Διαθέσιμη', + 'native.claim.emailLabel': 'Ηλ. ταχυδρομείο', + 'native.claim.emailHint': 'Για τον λογαριασμό και τις αποδείξεις σας.', + 'native.claim.subscribe': 'Εγγραφή για {price}', + 'native.claim.cancelled': 'Η αγορά ακυρώθηκε.', + 'native.claim.failed': 'Η αγορά δεν ολοκληρώθηκε. Δοκιμάστε ξανά.', + 'native.claim.redeemFailed': 'Δεν μπορέσαμε να ετοιμάσουμε το TREK σας. Δοκιμάστε ξανά.', + 'native.provisioning.title': 'Ετοιμάζουμε το TREK σας', + 'native.provisioning.sub': 'Ετοιμάζουμε το {host}. Χρειάζεται μόνο ένα λεπτό.', + 'native.provisioning.failedTitle': 'Σχεδόν έτοιμο', + 'native.provisioning.failedSub': 'Το TREK σας έρχεται. Δοκιμάστε ξανά σε λίγο ή ανοίξτε την εφαρμογή αργότερα.', + 'native.provisioning.retry': 'Δοκιμάστε τώρα', +}; + +export default native; diff --git a/shared/src/i18n/he/index.ts b/shared/src/i18n/he/index.ts index bcc4778a6..9e2a4afbd 100644 --- a/shared/src/i18n/he/index.ts +++ b/shared/src/i18n/he/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -124,6 +125,7 @@ const locale = { ...collab, ...perm, ...undo, + ...native, ...notifications, ...todo, ...notif, diff --git a/shared/src/i18n/he/native.ts b/shared/src/i18n/he/native.ts new file mode 100644 index 000000000..5fb67ce42 --- /dev/null +++ b/shared/src/i18n/he/native.ts @@ -0,0 +1,77 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': 'התחברות ל-TREK', + 'native.connect.hint': 'הזינו את הכתובת שבה אתם פותחים את TREK בדפדפן.', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': 'התחברות', + 'native.connect.checking': 'בודק…', + 'native.connect.tryDemo': 'אין עדיין שרת? נסו את הדמו', + 'native.connect.whatIsServer': 'מהו שרת TREK?', + 'native.connect.errorInvalid': 'זה לא נראה ככתובת אינטרנט.', + 'native.connect.errorUnreachable': 'אף שרת לא ענה בכתובת הזו. בדקו את הכתובת ואת החיבור.', + 'native.connect.errorNotTrek': 'השרת בכתובת הזו אינו TREK.', + 'native.connect.errorTooOld': 'שרת TREK הזה ישן מדי עבור האפליקציה. צריך קודם לעדכן אותו.', + 'native.offline.title': 'השרת לא זמין', + 'native.offline.hint': 'TREK לא הצליח להגיע אל {server}. בדקו את החיבור ונסו שוב.', + 'native.offline.retry': 'נסו שוב', + 'native.changeServer': 'החלפת שרת', + 'native.login.failed': 'ההתחברות נכשלה. אנא נסו שוב.', + 'native.handoff.title': 'המשך באפליקציה', + 'native.handoff.hint': 'אתם מחוברים בתור {name}. פתחו את אפליקציית TREK כדי להשלים שם את ההתחברות.', + 'native.handoff.open': 'פתיחת אפליקציית TREK', + 'native.handoff.switchAccount': 'שימוש בחשבון אחר', + 'native.privacy': 'מדיניות הפרטיות', + 'native.settings.server': 'שרת', + 'native.settings.serverHint': 'האפליקציה הזו מחוברת אל {server}.', + 'native.welcome.headline': 'מתכננים טיולים ביחד.', + 'native.welcome.sub': 'TREK שומר כל יום, מקום, הזמנה והוצאה בתוכנית חיה אחת שכל הקבוצה עורכת ביחד.', + 'native.welcome.connect': 'חיבור ה-TREK שלכם', + 'native.welcome.connectSub': 'פתחו את הכתובת שאתם כבר משתמשים בה', + 'native.welcome.getCloud': 'קבלת TREK Cloud', + 'native.welcome.getCloudSub': 'מתארח עבורכם, בלי התקנה', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': 'אנחנו מארחים את TREK עבורכם, על כתובת משלכם. אין מה להתקין, אין מה לתחזק: מוכן תוך דקות.', + 'native.cloud.f1': 'כתובת משלכם, על שרתים בגרמניה', + 'native.cloud.f2': 'מוכן תוך דקות, העדכונים עלינו', + 'native.cloud.f3': 'הנתונים שלכם נשארים שלכם: בלי פרסומות, בלי מעקב', + 'native.cloud.cta': 'התחלה', + 'native.cloud.haveServer': 'כבר יש לי TREK', + 'native.connecting': 'מתחבר אל {host}', + 'native.back': 'חזרה', + 'native.plans.title': 'בחרו את התוכנית שלכם', + 'native.plans.sub': 'TREK מתארח על כתובת משלכם. שנו או בטלו בכל עת.', + 'native.plans.monthly': 'חודשי', + 'native.plans.yearly': 'שנתי', + 'native.plans.save': 'חודשיים חינם', + 'native.plans.perMonth': 'לחודש', + 'native.plans.perYear': 'לשנה', + 'native.plans.aiDocs': '{n} מסמכי AI בחודש', + 'native.plans.noAi': 'בלי מסמכי AI', + 'native.plans.storage': '{n} GB אחסון', + 'native.plans.unlimited': 'מקומות, טיולים ואנשים ללא הגבלה', + 'native.plans.subscribe': 'הרשמה', + 'native.plans.loadError': 'לא ניתן לטעון את התוכניות. בדקו את החיבור ונסו שוב.', + 'native.plans.retry': 'נסו שוב', + 'native.plans.soon': 'הרשמות בתוך האפליקציה בקרוב. בינתיים, השלימו באתר.', + 'native.claim.title': 'יצירת ה-TREK שלכם', + 'native.claim.sub': 'בחרו את הכתובת שלכם. אנחנו מכינים אותה מיד.', + 'native.claim.addressLabel': 'הכתובת שלכם', + 'native.claim.taken': 'הכתובת הזו תפוסה.', + 'native.claim.invalid': 'שלוש אותיות, ספרות ומקפים או יותר.', + 'native.claim.reserved': 'הכתובת הזו שמורה.', + 'native.claim.free': 'זמין', + 'native.claim.emailLabel': 'אימייל', + 'native.claim.emailHint': 'עבור החשבון והקבלות שלכם.', + 'native.claim.subscribe': 'הרשמה תמורת {price}', + 'native.claim.cancelled': 'הרכישה בוטלה.', + 'native.claim.failed': 'הרכישה לא הושלמה. אנא נסו שוב.', + 'native.claim.redeemFailed': 'לא הצלחנו להכין את ה-TREK שלכם. אנא נסו שוב.', + 'native.provisioning.title': 'מכינים את ה-TREK שלכם', + 'native.provisioning.sub': 'מכינים את {host}. זה לוקח רק דקה.', + 'native.provisioning.failedTitle': 'כמעט מוכן', + 'native.provisioning.failedSub': 'ה-TREK שלכם בדרך. נסו שוב עוד רגע, או פתחו את האפליקציה מאוחר יותר.', + 'native.provisioning.retry': 'נסו עכשיו', +}; + +export default native; diff --git a/shared/src/i18n/hu/index.ts b/shared/src/i18n/hu/index.ts index af63b0baa..92d2aca27 100644 --- a/shared/src/i18n/hu/index.ts +++ b/shared/src/i18n/hu/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -101,6 +102,7 @@ const locale = { ...share, ...shared, ...login, + ...native, ...vacay, ...collection, ...atlas, diff --git a/shared/src/i18n/hu/native.ts b/shared/src/i18n/hu/native.ts new file mode 100644 index 000000000..4729b294c --- /dev/null +++ b/shared/src/i18n/hu/native.ts @@ -0,0 +1,81 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': 'Csatlakozás a TREK-hez', + 'native.connect.hint': 'Add meg azt a címet, amelyen a böngésződben megnyitod a TREK-et.', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': 'Csatlakozás', + 'native.connect.checking': 'Ellenőrzés…', + 'native.connect.tryDemo': 'Még nincs szervered? Próbáld ki a demót', + 'native.connect.whatIsServer': 'Mi az a TREK-szerver?', + 'native.connect.errorInvalid': 'Ez nem úgy néz ki, mint egy webcím.', + 'native.connect.errorUnreachable': 'Ezen a címen nem válaszol szerver. Ellenőrizd a címet és a kapcsolatot.', + 'native.connect.errorNotTrek': 'Az ezen a címen futó szerver nem TREK.', + 'native.connect.errorTooOld': 'Ez a TREK-szerver túl régi az alkalmazáshoz. Előbb frissíteni kell.', + 'native.offline.title': 'A szerver nem érhető el', + 'native.offline.hint': 'A TREK nem érte el ezt: {server}. Ellenőrizd a kapcsolatot, és próbáld újra.', + 'native.offline.retry': 'Újra', + 'native.changeServer': 'Szerver módosítása', + 'native.login.failed': 'A bejelentkezés nem sikerült. Próbáld újra.', + 'native.handoff.title': 'Folytatás az alkalmazásban', + 'native.handoff.hint': + '{name} néven vagy bejelentkezve. Nyisd meg a TREK alkalmazást, hogy ott befejezd a bejelentkezést.', + 'native.handoff.open': 'TREK alkalmazás megnyitása', + 'native.handoff.switchAccount': 'Másik fiók használata', + 'native.privacy': 'Adatvédelmi irányelvek', + 'native.settings.server': 'Szerver', + 'native.settings.serverHint': 'Ez az alkalmazás ehhez csatlakozik: {server}.', + 'native.welcome.headline': 'Tervezzetek utakat együtt.', + 'native.welcome.sub': + 'A TREK minden napot, helyet, foglalást és költséget egyetlen élő tervben tart, amelyet az egész csapat együtt szerkeszt.', + 'native.welcome.connect': 'Csatlakoztasd a TREK-edet', + 'native.welcome.connectSub': 'Nyisd meg a címet, amit már használsz', + 'native.welcome.getCloud': 'TREK Cloud beszerzése', + 'native.welcome.getCloudSub': 'Neked tárolva, telepítés nélkül', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': + 'A TREK-et neked üzemeltetjük, a saját címeden. Semmit nem kell telepíteni, semmit karbantartani: percek alatt kész.', + 'native.cloud.f1': 'Saját cím, németországi szervereken', + 'native.cloud.f2': 'Percek alatt kész, a frissítéseket mi intézzük', + 'native.cloud.f3': 'Az adataid a tieid maradnak: nincs hirdetés, nincs követés', + 'native.cloud.cta': 'Kezdés', + 'native.cloud.haveServer': 'Már van TREK-em', + 'native.connecting': 'Csatlakozás ehhez: {host}', + 'native.back': 'Vissza', + 'native.plans.title': 'Válaszd ki a csomagod', + 'native.plans.sub': 'TREK a saját címeden üzemeltetve. Bármikor módosíthatod vagy lemondhatod.', + 'native.plans.monthly': 'Havi', + 'native.plans.yearly': 'Éves', + 'native.plans.save': '2 hónap ingyen', + 'native.plans.perMonth': 'havonta', + 'native.plans.perYear': 'évente', + 'native.plans.aiDocs': 'havi {n} MI-dokumentum', + 'native.plans.noAi': 'Nincs MI-dokumentum', + 'native.plans.storage': '{n} GB tárhely', + 'native.plans.unlimited': 'Korlátlan hely, utazás és személy', + 'native.plans.subscribe': 'Előfizetés', + 'native.plans.loadError': 'A csomagokat nem sikerült betölteni. Ellenőrizd a kapcsolatot, és próbáld újra.', + 'native.plans.retry': 'Újra', + 'native.plans.soon': 'Az appon belüli előfizetés hamarosan érkezik. Addig fejezd be a weboldalon.', + 'native.claim.title': 'Hozd létre a TREK-edet', + 'native.claim.sub': 'Válaszd ki a címed. Azonnal beállítjuk.', + 'native.claim.addressLabel': 'A címed', + 'native.claim.taken': 'Ez a cím foglalt.', + 'native.claim.invalid': 'Legalább három betű, szám vagy kötőjel.', + 'native.claim.reserved': 'Ez a cím fenntartott.', + 'native.claim.free': 'Szabad', + 'native.claim.emailLabel': 'E-mail', + 'native.claim.emailHint': 'A fiókodhoz és a számlákhoz.', + 'native.claim.subscribe': 'Előfizetés ennyiért: {price}', + 'native.claim.cancelled': 'Vásárlás megszakítva.', + 'native.claim.failed': 'A vásárlás nem sikerült. Próbáld újra.', + 'native.claim.redeemFailed': 'Nem sikerült beállítani a TREK-edet. Próbáld újra.', + 'native.provisioning.title': 'A TREK-edet állítjuk be', + 'native.provisioning.sub': 'A(z) {host} előkészítése. Csak egy percet vesz igénybe.', + 'native.provisioning.failedTitle': 'Majdnem kész', + 'native.provisioning.failedSub': + 'A TREK-ed úton van. Próbáld újra egy pillanat múlva, vagy nyisd meg az appot később.', + 'native.provisioning.retry': 'Próbáld most', +}; + +export default native; diff --git a/shared/src/i18n/id/index.ts b/shared/src/i18n/id/index.ts index bcc4778a6..403813aa6 100644 --- a/shared/src/i18n/id/index.ts +++ b/shared/src/i18n/id/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -101,6 +102,7 @@ const locale = { ...share, ...shared, ...login, + ...native, ...vacay, ...collection, ...atlas, diff --git a/shared/src/i18n/id/native.ts b/shared/src/i18n/id/native.ts new file mode 100644 index 000000000..1c1950ee3 --- /dev/null +++ b/shared/src/i18n/id/native.ts @@ -0,0 +1,80 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': 'Hubungkan ke TREK', + 'native.connect.hint': 'Masukkan alamat yang kamu gunakan untuk membuka TREK di browser.', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': 'Hubungkan', + 'native.connect.checking': 'Memeriksa…', + 'native.connect.tryDemo': 'Belum punya server? Coba demonya', + 'native.connect.whatIsServer': 'Apa itu server TREK?', + 'native.connect.errorInvalid': 'Itu tidak terlihat seperti alamat web.', + 'native.connect.errorUnreachable': 'Tidak ada server yang merespons di alamat ini. Periksa alamat dan koneksimu.', + 'native.connect.errorNotTrek': 'Server di alamat ini bukan TREK.', + 'native.connect.errorTooOld': 'Server TREK ini terlalu lama untuk aplikasi. Server perlu diperbarui terlebih dahulu.', + 'native.offline.title': 'Server tidak dapat dijangkau', + 'native.offline.hint': 'TREK tidak dapat menjangkau {server}. Periksa koneksimu dan coba lagi.', + 'native.offline.retry': 'Coba lagi', + 'native.changeServer': 'Ganti server', + 'native.login.failed': 'Gagal masuk. Silakan coba lagi.', + 'native.handoff.title': 'Lanjutkan di aplikasi', + 'native.handoff.hint': 'Kamu masuk sebagai {name}. Buka aplikasi TREK untuk menyelesaikan proses masuk di sana.', + 'native.handoff.open': 'Buka aplikasi TREK', + 'native.handoff.switchAccount': 'Gunakan akun lain', + 'native.privacy': 'Kebijakan privasi', + 'native.settings.server': 'Server', // same-as-en + 'native.settings.serverHint': 'Aplikasi ini terhubung ke {server}.', + 'native.welcome.headline': 'Rencanakan perjalanan bersama.', + 'native.welcome.sub': + 'TREK menyatukan setiap hari, tempat, pemesanan, dan biaya dalam satu rencana langsung yang diedit seluruh grup bersama.', + 'native.welcome.connect': 'Hubungkan TREK Anda', + 'native.welcome.connectSub': 'Buka alamat yang sudah Anda pakai', + 'native.welcome.getCloud': 'Dapatkan TREK Cloud', + 'native.welcome.getCloudSub': 'Dihosting untuk Anda, tanpa penyiapan', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': + 'Kami menghosting TREK untuk Anda, di alamat Anda sendiri. Tidak ada yang perlu dipasang atau dirawat: siap dalam hitungan menit.', + 'native.cloud.f1': 'Alamat Anda sendiri, di server di Jerman', + 'native.cloud.f2': 'Siap dalam hitungan menit, pembaruan kami yang urus', + 'native.cloud.f3': 'Data Anda tetap milik Anda: tanpa iklan, tanpa pelacakan', + 'native.cloud.cta': 'Mulai', + 'native.cloud.haveServer': 'Saya sudah punya TREK', + 'native.connecting': 'Menghubungkan ke {host}', + 'native.back': 'Kembali', + 'native.plans.title': 'Pilih paket Anda', + 'native.plans.sub': 'TREK dihosting di alamat Anda sendiri. Ubah atau batalkan kapan saja.', + 'native.plans.monthly': 'Bulanan', + 'native.plans.yearly': 'Tahunan', + 'native.plans.save': '2 bulan gratis', + 'native.plans.perMonth': 'per bulan', + 'native.plans.perYear': 'per tahun', + 'native.plans.aiDocs': '{n} dokumen AI per bulan', + 'native.plans.noAi': 'Tanpa dokumen AI', + 'native.plans.storage': 'Penyimpanan {n} GB', + 'native.plans.unlimited': 'Tempat, perjalanan, dan orang tanpa batas', + 'native.plans.subscribe': 'Berlangganan', + 'native.plans.loadError': 'Tidak dapat memuat paket. Periksa koneksi Anda dan coba lagi.', + 'native.plans.retry': 'Coba lagi', + 'native.plans.soon': 'Langganan dalam aplikasi akan hadir. Untuk saat ini, selesaikan di situs web.', + 'native.claim.title': 'Buat TREK Anda', + 'native.claim.sub': 'Pilih alamat Anda. Kami langsung menyiapkannya.', + 'native.claim.addressLabel': 'Alamat Anda', + 'native.claim.taken': 'Alamat itu sudah dipakai.', + 'native.claim.invalid': 'Tiga huruf, angka, atau tanda hubung atau lebih.', + 'native.claim.reserved': 'Alamat itu dicadangkan.', + 'native.claim.free': 'Tersedia', + 'native.claim.emailLabel': 'Email', // same-as-en + 'native.claim.emailHint': 'Untuk akun dan tanda terima Anda.', + 'native.claim.subscribe': 'Berlangganan seharga {price}', + 'native.claim.cancelled': 'Pembelian dibatalkan.', + 'native.claim.failed': 'Pembelian tidak berhasil. Silakan coba lagi.', + 'native.claim.redeemFailed': 'Kami tidak dapat menyiapkan TREK Anda. Silakan coba lagi.', + 'native.provisioning.title': 'Menyiapkan TREK Anda', + 'native.provisioning.sub': 'Menyiapkan {host}. Ini hanya perlu satu menit.', + 'native.provisioning.failedTitle': 'Hampir siap', + 'native.provisioning.failedSub': + 'TREK Anda sedang dalam perjalanan. Coba lagi sebentar lagi, atau buka aplikasi nanti.', + 'native.provisioning.retry': 'Coba sekarang', +}; + +export default native; diff --git a/shared/src/i18n/it/index.ts b/shared/src/i18n/it/index.ts index bcc4778a6..403813aa6 100644 --- a/shared/src/i18n/it/index.ts +++ b/shared/src/i18n/it/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -101,6 +102,7 @@ const locale = { ...share, ...shared, ...login, + ...native, ...vacay, ...collection, ...atlas, diff --git a/shared/src/i18n/it/native.ts b/shared/src/i18n/it/native.ts new file mode 100644 index 000000000..880bcbab8 --- /dev/null +++ b/shared/src/i18n/it/native.ts @@ -0,0 +1,80 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': 'Connetti a TREK', + 'native.connect.hint': 'Inserisci l’indirizzo con cui apri TREK nel browser.', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': 'Connetti', + 'native.connect.checking': 'Verifica in corso…', + 'native.connect.tryDemo': 'Non hai ancora un server? Prova la demo', + 'native.connect.whatIsServer': 'Che cos’è un server TREK?', + 'native.connect.errorInvalid': 'Non sembra un indirizzo web.', + 'native.connect.errorUnreachable': + 'Nessun server risponde a questo indirizzo. Controlla l’indirizzo e la connessione.', + 'native.connect.errorNotTrek': 'Il server a questo indirizzo non è TREK.', + 'native.connect.errorTooOld': 'Questo server TREK è troppo vecchio per l’app. Deve prima essere aggiornato.', + 'native.offline.title': 'Server non raggiungibile', + 'native.offline.hint': 'TREK non è riuscito a raggiungere {server}. Controlla la connessione e riprova.', + 'native.offline.retry': 'Riprova', + 'native.changeServer': 'Cambia server', + 'native.login.failed': 'L’accesso non è riuscito. Riprova.', + 'native.handoff.title': 'Continua nell’app', + 'native.handoff.hint': 'Hai effettuato l’accesso come {name}. Apri l’app TREK per completare lì l’accesso.', + 'native.handoff.open': 'Apri l’app TREK', + 'native.handoff.switchAccount': 'Usa un altro account', + 'native.privacy': 'Informativa sulla privacy', + 'native.settings.server': 'Server', // same-as-en + 'native.settings.serverHint': 'Questa app è collegata a {server}.', + 'native.welcome.headline': 'Pianificate i viaggi insieme.', + 'native.welcome.sub': + 'TREK raccoglie ogni giorno, luogo, prenotazione e spesa in un unico piano dal vivo che tutto il gruppo modifica insieme.', + 'native.welcome.connect': 'Collega il tuo TREK', + 'native.welcome.connectSub': 'Apri l’indirizzo che già usi', + 'native.welcome.getCloud': 'Attiva TREK Cloud', + 'native.welcome.getCloudSub': 'Ospitato per te, senza installazione', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': + 'Ospitiamo TREK per te, sul tuo indirizzo. Niente da installare, niente da mantenere: pronto in pochi minuti.', + 'native.cloud.f1': 'Il tuo indirizzo, su server in Germania', + 'native.cloud.f2': 'Pronto in pochi minuti, aggiornamenti inclusi', + 'native.cloud.f3': 'I tuoi dati restano tuoi: niente pubblicità, niente tracciamento', + 'native.cloud.cta': 'Inizia', + 'native.cloud.haveServer': 'Ho già un TREK', + 'native.connecting': 'Connessione a {host}', + 'native.back': 'Indietro', + 'native.plans.title': 'Scegli il tuo piano', + 'native.plans.sub': 'TREK ospitato sul tuo indirizzo. Modifica o disdici quando vuoi.', + 'native.plans.monthly': 'Mensile', + 'native.plans.yearly': 'Annuale', + 'native.plans.save': '2 mesi gratis', + 'native.plans.perMonth': 'al mese', + 'native.plans.perYear': 'all’anno', + 'native.plans.aiDocs': '{n} documenti con IA al mese', + 'native.plans.noAi': 'Nessun documento con IA', + 'native.plans.storage': '{n} GB di spazio', + 'native.plans.unlimited': 'Luoghi, viaggi e persone senza limiti', + 'native.plans.subscribe': 'Abbonati', + 'native.plans.loadError': 'Impossibile caricare i piani. Controlla la connessione e riprova.', + 'native.plans.retry': 'Riprova', + 'native.plans.soon': 'Gli abbonamenti nell’app arrivano presto. Per ora, completa sul sito.', + 'native.claim.title': 'Crea il tuo TREK', + 'native.claim.sub': 'Scegli il tuo indirizzo. Lo prepariamo subito.', + 'native.claim.addressLabel': 'Il tuo indirizzo', + 'native.claim.taken': 'Questo indirizzo è già occupato.', + 'native.claim.invalid': 'Almeno tre lettere, numeri o trattini.', + 'native.claim.reserved': 'Questo indirizzo è riservato.', + 'native.claim.free': 'Disponibile', + 'native.claim.emailLabel': 'Email', // same-as-en + 'native.claim.emailHint': 'Per il tuo account e le ricevute.', + 'native.claim.subscribe': 'Abbonati per {price}', + 'native.claim.cancelled': 'Acquisto annullato.', + 'native.claim.failed': 'L’acquisto non è andato a buon fine. Riprova.', + 'native.claim.redeemFailed': 'Non siamo riusciti a preparare il tuo TREK. Riprova.', + 'native.provisioning.title': 'Preparazione del tuo TREK', + 'native.provisioning.sub': 'Stiamo preparando {host}. Ci vuole solo un minuto.', + 'native.provisioning.failedTitle': 'Quasi pronto', + 'native.provisioning.failedSub': 'Il tuo TREK sta arrivando. Riprova tra poco o riapri l’app più tardi.', + 'native.provisioning.retry': 'Riprova', +}; + +export default native; diff --git a/shared/src/i18n/ja/index.ts b/shared/src/i18n/ja/index.ts index bcc4778a6..403813aa6 100644 --- a/shared/src/i18n/ja/index.ts +++ b/shared/src/i18n/ja/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -101,6 +102,7 @@ const locale = { ...share, ...shared, ...login, + ...native, ...vacay, ...collection, ...atlas, diff --git a/shared/src/i18n/ja/native.ts b/shared/src/i18n/ja/native.ts new file mode 100644 index 000000000..6b7005b69 --- /dev/null +++ b/shared/src/i18n/ja/native.ts @@ -0,0 +1,80 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': 'TREK に接続', + 'native.connect.hint': 'ブラウザで TREK を開くときのアドレスを入力してください。', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': '接続', + 'native.connect.checking': '確認中…', + 'native.connect.tryDemo': 'まだサーバーがありませんか?デモをお試しください', + 'native.connect.whatIsServer': 'TREK サーバーとは?', + 'native.connect.errorInvalid': 'Web アドレスではないようです。', + 'native.connect.errorUnreachable': 'このアドレスで応答するサーバーがありません。アドレスと接続を確認してください。', + 'native.connect.errorNotTrek': 'このアドレスのサーバーは TREK ではありません。', + 'native.connect.errorTooOld': 'この TREK サーバーはアプリに対して古すぎます。先に更新が必要です。', + 'native.offline.title': 'サーバーに接続できません', + 'native.offline.hint': 'TREK は {server} に接続できませんでした。接続を確認して、もう一度お試しください。', + 'native.offline.retry': '再試行', + 'native.changeServer': 'サーバーを変更', + 'native.login.failed': 'ログインできませんでした。もう一度お試しください。', + 'native.handoff.title': 'アプリで続行', + 'native.handoff.hint': '{name} としてログインしています。TREK アプリを開いて、そちらでログインを完了してください。', + 'native.handoff.open': 'TREK アプリを開く', + 'native.handoff.switchAccount': '別のアカウントを使う', + 'native.privacy': 'プライバシーポリシー', + 'native.settings.server': 'サーバー', + 'native.settings.serverHint': 'このアプリは {server} に接続されています。', + 'native.welcome.headline': 'みんなで旅を計画。', + 'native.welcome.sub': + 'TREKは、毎日・場所・予約・費用を、グループ全員で一緒に編集できる1つのライブプランにまとめます。', + 'native.welcome.connect': 'あなたのTREKに接続', + 'native.welcome.connectSub': 'すでに使っているアドレスを開く', + 'native.welcome.getCloud': 'TREK Cloudを始める', + 'native.welcome.getCloudSub': 'あなたのために用意、設定不要', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': + 'TREKをあなたのために、あなた専用のアドレスでホストします。インストールも管理も不要で、数分で使えます。', + 'native.cloud.f1': '専用アドレス、ドイツのサーバー上', + 'native.cloud.f2': '数分で準備完了、アップデートはお任せ', + 'native.cloud.f3': 'データはあなたのもの。広告なし、追跡なし', + 'native.cloud.cta': '始める', + 'native.cloud.haveServer': 'すでにTREKを持っています', + 'native.connecting': '{host} に接続中', + 'native.back': '戻る', + 'native.plans.title': 'プランを選ぶ', + 'native.plans.sub': 'あなた専用のアドレスでホストされるTREK。いつでも変更・解約できます。', + 'native.plans.monthly': '月額', + 'native.plans.yearly': '年額', + 'native.plans.save': '2か月無料', + 'native.plans.perMonth': '月あたり', + 'native.plans.perYear': '年あたり', + 'native.plans.aiDocs': '月に{n}件のAIドキュメント', + 'native.plans.noAi': 'AIドキュメントなし', + 'native.plans.storage': '{n} GB のストレージ', + 'native.plans.unlimited': '場所・旅行・人数は無制限', + 'native.plans.subscribe': '登録', + 'native.plans.loadError': 'プランを読み込めませんでした。接続を確認してもう一度お試しください。', + 'native.plans.retry': 'もう一度試す', + 'native.plans.soon': 'アプリ内サブスクリプションは近日対応。今はウェブで完了してください。', + 'native.claim.title': 'TREKを作成', + 'native.claim.sub': 'アドレスを選んでください。すぐに用意します。', + 'native.claim.addressLabel': 'あなたのアドレス', + 'native.claim.taken': 'このアドレスは使用中です。', + 'native.claim.invalid': '3文字以上の英字・数字・ハイフン。', + 'native.claim.reserved': 'このアドレスは予約済みです。', + 'native.claim.free': '利用可能', + 'native.claim.emailLabel': 'メール', + 'native.claim.emailHint': 'アカウントと領収書のため。', + 'native.claim.subscribe': '{price} で登録', + 'native.claim.cancelled': '購入をキャンセルしました。', + 'native.claim.failed': '購入できませんでした。もう一度お試しください。', + 'native.claim.redeemFailed': 'TREKを用意できませんでした。もう一度お試しください。', + 'native.provisioning.title': 'TREKを準備中', + 'native.provisioning.sub': '{host} を準備しています。1分ほどで完了します。', + 'native.provisioning.failedTitle': 'もうすぐ完了', + 'native.provisioning.failedSub': + 'TREKはまもなく準備できます。少ししてからもう一度試すか、後でアプリを開いてください。', + 'native.provisioning.retry': '今すぐ試す', +}; + +export default native; diff --git a/shared/src/i18n/ko/index.ts b/shared/src/i18n/ko/index.ts index bcc4778a6..403813aa6 100644 --- a/shared/src/i18n/ko/index.ts +++ b/shared/src/i18n/ko/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -101,6 +102,7 @@ const locale = { ...share, ...shared, ...login, + ...native, ...vacay, ...collection, ...atlas, diff --git a/shared/src/i18n/ko/native.ts b/shared/src/i18n/ko/native.ts new file mode 100644 index 000000000..40c1bdd82 --- /dev/null +++ b/shared/src/i18n/ko/native.ts @@ -0,0 +1,77 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': 'TREK에 연결', + 'native.connect.hint': '브라우저에서 TREK을 여는 주소를 입력하세요.', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': '연결', + 'native.connect.checking': '확인 중…', + 'native.connect.tryDemo': '아직 서버가 없나요? 데모를 사용해 보세요', + 'native.connect.whatIsServer': 'TREK 서버란?', + 'native.connect.errorInvalid': '웹 주소가 아닌 것 같습니다.', + 'native.connect.errorUnreachable': '이 주소에서 응답하는 서버가 없습니다. 주소와 연결 상태를 확인하세요.', + 'native.connect.errorNotTrek': '이 주소의 서버는 TREK이 아닙니다.', + 'native.connect.errorTooOld': '이 TREK 서버는 앱에서 사용하기에 너무 오래되었습니다. 먼저 업데이트가 필요합니다.', + 'native.offline.title': '서버에 연결할 수 없음', + 'native.offline.hint': 'TREK이 {server}에 연결하지 못했습니다. 연결 상태를 확인한 후 다시 시도하세요.', + 'native.offline.retry': '다시 시도', + 'native.changeServer': '서버 변경', + 'native.login.failed': '로그인하지 못했습니다. 다시 시도하세요.', + 'native.handoff.title': '앱에서 계속', + 'native.handoff.hint': '{name}(으)로 로그인되어 있습니다. TREK 앱을 열어 로그인을 완료하세요.', + 'native.handoff.open': 'TREK 앱 열기', + 'native.handoff.switchAccount': '다른 계정 사용', + 'native.privacy': '개인정보 처리방침', + 'native.settings.server': '서버', + 'native.settings.serverHint': '이 앱은 {server}에 연결되어 있습니다.', + 'native.welcome.headline': '함께 여행을 계획하세요.', + 'native.welcome.sub': 'TREK은 모든 날짜, 장소, 예약, 비용을 그룹 전체가 함께 편집하는 하나의 실시간 플랜에 담습니다.', + 'native.welcome.connect': '내 TREK 연결', + 'native.welcome.connectSub': '이미 사용하는 주소 열기', + 'native.welcome.getCloud': 'TREK Cloud 시작하기', + 'native.welcome.getCloudSub': '설정 없이 대신 호스팅', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': 'TREK을 여러분만의 주소로 대신 호스팅합니다. 설치도 관리도 필요 없이 몇 분이면 준비됩니다.', + 'native.cloud.f1': '나만의 주소, 독일 서버에서', + 'native.cloud.f2': '몇 분이면 준비 완료, 업데이트는 저희가', + 'native.cloud.f3': '데이터는 그대로 내 것: 광고 없음, 추적 없음', + 'native.cloud.cta': '시작하기', + 'native.cloud.haveServer': '이미 TREK이 있어요', + 'native.connecting': '{host}에 연결 중', + 'native.back': '뒤로', + 'native.plans.title': '플랜 선택', + 'native.plans.sub': '나만의 주소로 호스팅되는 TREK. 언제든 변경하거나 해지하세요.', + 'native.plans.monthly': '월간', + 'native.plans.yearly': '연간', + 'native.plans.save': '2개월 무료', + 'native.plans.perMonth': '월', + 'native.plans.perYear': '년', + 'native.plans.aiDocs': '월 {n}개의 AI 문서', + 'native.plans.noAi': 'AI 문서 없음', + 'native.plans.storage': '{n} GB 저장공간', + 'native.plans.unlimited': '장소, 여행, 인원 무제한', + 'native.plans.subscribe': '구독', + 'native.plans.loadError': '플랜을 불러오지 못했습니다. 연결을 확인하고 다시 시도하세요.', + 'native.plans.retry': '다시 시도', + 'native.plans.soon': '앱 내 구독이 곧 제공됩니다. 지금은 웹에서 완료하세요.', + 'native.claim.title': 'TREK 만들기', + 'native.claim.sub': '주소를 선택하세요. 바로 준비해 드립니다.', + 'native.claim.addressLabel': '내 주소', + 'native.claim.taken': '이미 사용 중인 주소예요.', + 'native.claim.invalid': '세 글자 이상의 문자, 숫자, 하이픈.', + 'native.claim.reserved': '예약된 주소예요.', + 'native.claim.free': '사용 가능', + 'native.claim.emailLabel': '이메일', + 'native.claim.emailHint': '계정과 영수증용입니다.', + 'native.claim.subscribe': '{price}에 구독', + 'native.claim.cancelled': '구매가 취소되었습니다.', + 'native.claim.failed': '구매가 완료되지 않았습니다. 다시 시도하세요.', + 'native.claim.redeemFailed': 'TREK을 준비하지 못했습니다. 다시 시도하세요.', + 'native.provisioning.title': 'TREK 준비 중', + 'native.provisioning.sub': '{host}을(를) 준비하고 있습니다. 1분이면 됩니다.', + 'native.provisioning.failedTitle': '거의 준비됐어요', + 'native.provisioning.failedSub': 'TREK이 곧 준비됩니다. 잠시 후 다시 시도하거나 나중에 앱을 열어 보세요.', + 'native.provisioning.retry': '지금 시도', +}; + +export default native; diff --git a/shared/src/i18n/nl/index.ts b/shared/src/i18n/nl/index.ts index bcc4778a6..403813aa6 100644 --- a/shared/src/i18n/nl/index.ts +++ b/shared/src/i18n/nl/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -101,6 +102,7 @@ const locale = { ...share, ...shared, ...login, + ...native, ...vacay, ...collection, ...atlas, diff --git a/shared/src/i18n/nl/native.ts b/shared/src/i18n/nl/native.ts new file mode 100644 index 000000000..d42c4d482 --- /dev/null +++ b/shared/src/i18n/nl/native.ts @@ -0,0 +1,79 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': 'Verbinden met TREK', + 'native.connect.hint': 'Voer het adres in waarop je TREK in je browser opent.', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': 'Verbinden', + 'native.connect.checking': 'Controleren…', + 'native.connect.tryDemo': 'Nog geen server? Probeer de demo', + 'native.connect.whatIsServer': 'Wat is een TREK-server?', + 'native.connect.errorInvalid': 'Dat lijkt geen webadres.', + 'native.connect.errorUnreachable': 'Er reageert geen server op dit adres. Controleer het adres en je verbinding.', + 'native.connect.errorNotTrek': 'De server op dit adres is geen TREK.', + 'native.connect.errorTooOld': 'Deze TREK-server is te oud voor de app. Hij moet eerst worden bijgewerkt.', + 'native.offline.title': 'Server niet bereikbaar', + 'native.offline.hint': 'TREK kon {server} niet bereiken. Controleer je verbinding en probeer het opnieuw.', + 'native.offline.retry': 'Opnieuw proberen', + 'native.changeServer': 'Server wijzigen', + 'native.login.failed': 'Inloggen is niet gelukt. Probeer het opnieuw.', + 'native.handoff.title': 'Verder in de app', + 'native.handoff.hint': 'Je bent ingelogd als {name}. Open de TREK-app om daar het inloggen af te ronden.', + 'native.handoff.open': 'TREK-app openen', + 'native.handoff.switchAccount': 'Ander account gebruiken', + 'native.privacy': 'Privacybeleid', + 'native.settings.server': 'Server', // same-as-en + 'native.settings.serverHint': 'Deze app is verbonden met {server}.', + 'native.welcome.headline': 'Plan reizen samen.', + 'native.welcome.sub': + 'TREK houdt elke dag, plek, boeking en kostenpost bij in één live plan dat je hele groep samen bewerkt.', + 'native.welcome.connect': 'Verbind je TREK', + 'native.welcome.connectSub': 'Open het adres dat je al gebruikt', + 'native.welcome.getCloud': 'Neem TREK Cloud', + 'native.welcome.getCloudSub': 'Voor je gehost, zonder installatie', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': + 'Wij hosten TREK voor je, op je eigen adres. Niets te installeren, niets te onderhouden: binnen enkele minuten klaar.', + 'native.cloud.f1': 'Je eigen adres, op servers in Duitsland', + 'native.cloud.f2': 'In enkele minuten klaar, updates doen wij', + 'native.cloud.f3': 'Je gegevens blijven van jou: geen advertenties, geen tracking', + 'native.cloud.cta': 'Aan de slag', + 'native.cloud.haveServer': 'Ik heb al een TREK', + 'native.connecting': 'Verbinden met {host}', + 'native.back': 'Terug', + 'native.plans.title': 'Kies je abonnement', + 'native.plans.sub': 'TREK gehost op je eigen adres. Altijd te wijzigen of op te zeggen.', + 'native.plans.monthly': 'Maandelijks', + 'native.plans.yearly': 'Jaarlijks', + 'native.plans.save': '2 maanden gratis', + 'native.plans.perMonth': 'per maand', + 'native.plans.perYear': 'per jaar', + 'native.plans.aiDocs': '{n} AI-documenten per maand', + 'native.plans.noAi': 'Geen AI-documenten', + 'native.plans.storage': '{n} GB opslag', + 'native.plans.unlimited': 'Onbeperkt plekken, reizen en personen', + 'native.plans.subscribe': 'Abonneren', + 'native.plans.loadError': 'Kan de abonnementen niet laden. Controleer je verbinding en probeer het opnieuw.', + 'native.plans.retry': 'Opnieuw proberen', + 'native.plans.soon': 'Abonneren in de app komt eraan. Rond het voorlopig af op de website.', + 'native.claim.title': 'Maak je TREK', + 'native.claim.sub': 'Kies je adres. We zetten het meteen klaar.', + 'native.claim.addressLabel': 'Je adres', + 'native.claim.taken': 'Dit adres is al bezet.', + 'native.claim.invalid': 'Minstens drie letters, cijfers of streepjes.', + 'native.claim.reserved': 'Dit adres is gereserveerd.', + 'native.claim.free': 'Beschikbaar', + 'native.claim.emailLabel': 'E-mail', + 'native.claim.emailHint': 'Voor je account en bonnen.', + 'native.claim.subscribe': 'Abonneren voor {price}', + 'native.claim.cancelled': 'Aankoop geannuleerd.', + 'native.claim.failed': 'De aankoop is niet gelukt. Probeer het opnieuw.', + 'native.claim.redeemFailed': 'We konden je TREK niet klaarzetten. Probeer het opnieuw.', + 'native.provisioning.title': 'Je TREK wordt klaargezet', + 'native.provisioning.sub': '{host} wordt klaargemaakt. Dit duurt maar een minuut.', + 'native.provisioning.failedTitle': 'Bijna klaar', + 'native.provisioning.failedSub': 'Je TREK is onderweg. Probeer het zo opnieuw of open de app later.', + 'native.provisioning.retry': 'Nu proberen', +}; + +export default native; diff --git a/shared/src/i18n/pl/index.ts b/shared/src/i18n/pl/index.ts index bcc4778a6..403813aa6 100644 --- a/shared/src/i18n/pl/index.ts +++ b/shared/src/i18n/pl/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -101,6 +102,7 @@ const locale = { ...share, ...shared, ...login, + ...native, ...vacay, ...collection, ...atlas, diff --git a/shared/src/i18n/pl/native.ts b/shared/src/i18n/pl/native.ts new file mode 100644 index 000000000..5143e9b20 --- /dev/null +++ b/shared/src/i18n/pl/native.ts @@ -0,0 +1,79 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': 'Połącz z TREK', + 'native.connect.hint': 'Wpisz adres, pod którym otwierasz TREK w przeglądarce.', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': 'Połącz', + 'native.connect.checking': 'Sprawdzanie…', + 'native.connect.tryDemo': 'Nie masz jeszcze serwera? Wypróbuj demo', + 'native.connect.whatIsServer': 'Czym jest serwer TREK?', + 'native.connect.errorInvalid': 'To nie wygląda na adres internetowy.', + 'native.connect.errorUnreachable': 'Pod tym adresem nie odpowiada żaden serwer. Sprawdź adres i połączenie.', + 'native.connect.errorNotTrek': 'Serwer pod tym adresem to nie TREK.', + 'native.connect.errorTooOld': 'Ten serwer TREK jest za stary dla aplikacji. Najpierw wymaga aktualizacji.', + 'native.offline.title': 'Serwer nieosiągalny', + 'native.offline.hint': 'TREK nie mógł połączyć się z {server}. Sprawdź połączenie i spróbuj ponownie.', + 'native.offline.retry': 'Spróbuj ponownie', + 'native.changeServer': 'Zmień serwer', + 'native.login.failed': 'Logowanie się nie powiodło. Spróbuj ponownie.', + 'native.handoff.title': 'Kontynuuj w aplikacji', + 'native.handoff.hint': 'Zalogowano jako {name}. Otwórz aplikację TREK, aby tam dokończyć logowanie.', + 'native.handoff.open': 'Otwórz aplikację TREK', + 'native.handoff.switchAccount': 'Użyj innego konta', + 'native.privacy': 'Polityka prywatności', + 'native.settings.server': 'Serwer', + 'native.settings.serverHint': 'Ta aplikacja jest połączona z {server}.', + 'native.welcome.headline': 'Planujcie podróże razem.', + 'native.welcome.sub': + 'TREK zbiera każdy dzień, miejsce, rezerwację i wydatek w jednym wspólnym planie, który cała grupa edytuje na żywo.', + 'native.welcome.connect': 'Połącz swój TREK', + 'native.welcome.connectSub': 'Otwórz adres, którego już używasz', + 'native.welcome.getCloud': 'Weź TREK Cloud', + 'native.welcome.getCloudSub': 'Hostowany dla Ciebie, bez instalacji', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': + 'Hostujemy TREK za Ciebie, pod Twoim własnym adresem. Nic do instalowania, nic do utrzymywania: gotowe w kilka minut.', + 'native.cloud.f1': 'Twój własny adres, na serwerach w Niemczech', + 'native.cloud.f2': 'Gotowe w kilka minut, aktualizacje po naszej stronie', + 'native.cloud.f3': 'Twoje dane zostają Twoje: bez reklam, bez śledzenia', + 'native.cloud.cta': 'Zacznij', + 'native.cloud.haveServer': 'Mam już TREK', + 'native.connecting': 'Łączenie z {host}', + 'native.back': 'Wstecz', + 'native.plans.title': 'Wybierz plan', + 'native.plans.sub': 'TREK hostowany pod Twoim własnym adresem. Zmieniaj lub anuluj w każdej chwili.', + 'native.plans.monthly': 'Miesięcznie', + 'native.plans.yearly': 'Rocznie', + 'native.plans.save': '2 miesiące gratis', + 'native.plans.perMonth': 'miesięcznie', + 'native.plans.perYear': 'rocznie', + 'native.plans.aiDocs': '{n} dokumentów AI miesięcznie', + 'native.plans.noAi': 'Bez dokumentów AI', + 'native.plans.storage': '{n} GB miejsca', + 'native.plans.unlimited': 'Bez limitu miejsc, podróży i osób', + 'native.plans.subscribe': 'Subskrybuj', + 'native.plans.loadError': 'Nie udało się wczytać planów. Sprawdź połączenie i spróbuj ponownie.', + 'native.plans.retry': 'Spróbuj ponownie', + 'native.plans.soon': 'Subskrypcje w aplikacji już wkrótce. Na razie dokończ na stronie.', + 'native.claim.title': 'Utwórz swój TREK', + 'native.claim.sub': 'Wybierz swój adres. Przygotujemy go od razu.', + 'native.claim.addressLabel': 'Twój adres', + 'native.claim.taken': 'Ten adres jest już zajęty.', + 'native.claim.invalid': 'Co najmniej trzy litery, cyfry lub myślniki.', + 'native.claim.reserved': 'Ten adres jest zarezerwowany.', + 'native.claim.free': 'Dostępny', + 'native.claim.emailLabel': 'E-mail', + 'native.claim.emailHint': 'Do Twojego konta i potwierdzeń.', + 'native.claim.subscribe': 'Subskrybuj za {price}', + 'native.claim.cancelled': 'Zakup anulowany.', + 'native.claim.failed': 'Zakup się nie powiódł. Spróbuj ponownie.', + 'native.claim.redeemFailed': 'Nie udało się przygotować Twojego TREK. Spróbuj ponownie.', + 'native.provisioning.title': 'Przygotowujemy Twój TREK', + 'native.provisioning.sub': 'Przygotowujemy {host}. To zajmie tylko minutę.', + 'native.provisioning.failedTitle': 'Już prawie', + 'native.provisioning.failedSub': 'Twój TREK jest w drodze. Spróbuj za chwilę lub otwórz aplikację później.', + 'native.provisioning.retry': 'Spróbuj teraz', +}; + +export default native; diff --git a/shared/src/i18n/ru/index.ts b/shared/src/i18n/ru/index.ts index bcc4778a6..403813aa6 100644 --- a/shared/src/i18n/ru/index.ts +++ b/shared/src/i18n/ru/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -101,6 +102,7 @@ const locale = { ...share, ...shared, ...login, + ...native, ...vacay, ...collection, ...atlas, diff --git a/shared/src/i18n/ru/native.ts b/shared/src/i18n/ru/native.ts new file mode 100644 index 000000000..cf4dae78c --- /dev/null +++ b/shared/src/i18n/ru/native.ts @@ -0,0 +1,80 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': 'Подключение к TREK', + 'native.connect.hint': 'Введите адрес, по которому вы открываете TREK в браузере.', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': 'Подключиться', + 'native.connect.checking': 'Проверка…', + 'native.connect.tryDemo': 'Ещё нет сервера? Попробуйте демо', + 'native.connect.whatIsServer': 'Что такое сервер TREK?', + 'native.connect.errorInvalid': 'Это не похоже на веб-адрес.', + 'native.connect.errorUnreachable': 'По этому адресу не отвечает ни один сервер. Проверьте адрес и подключение.', + 'native.connect.errorNotTrek': 'Сервер по этому адресу не является TREK.', + 'native.connect.errorTooOld': 'Этот сервер TREK слишком старый для приложения. Сначала его нужно обновить.', + 'native.offline.title': 'Сервер недоступен', + 'native.offline.hint': 'TREK не удалось подключиться к {server}. Проверьте подключение и повторите попытку.', + 'native.offline.retry': 'Повторить', + 'native.changeServer': 'Сменить сервер', + 'native.login.failed': 'Не удалось войти. Попробуйте ещё раз.', + 'native.handoff.title': 'Продолжить в приложении', + 'native.handoff.hint': 'Вы вошли как {name}. Откройте приложение TREK, чтобы завершить вход в нём.', + 'native.handoff.open': 'Открыть приложение TREK', + 'native.handoff.switchAccount': 'Использовать другой аккаунт', + 'native.privacy': 'Политика конфиденциальности', + 'native.settings.server': 'Сервер', + 'native.settings.serverHint': 'Приложение подключено к {server}.', + 'native.welcome.headline': 'Планируйте поездки вместе.', + 'native.welcome.sub': + 'TREK хранит каждый день, место, бронирование и расход в одном живом плане, который вся группа редактирует вместе.', + 'native.welcome.connect': 'Подключите свой TREK', + 'native.welcome.connectSub': 'Откройте адрес, которым уже пользуетесь', + 'native.welcome.getCloud': 'Получить TREK Cloud', + 'native.welcome.getCloudSub': 'Размещён для вас, без настройки', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': + 'Мы разместим TREK для вас, на вашем собственном адресе. Ничего не нужно устанавливать и обслуживать: готово за минуты.', + 'native.cloud.f1': 'Собственный адрес, на серверах в Германии', + 'native.cloud.f2': 'Готово за минуты, обновления берём на себя', + 'native.cloud.f3': 'Ваши данные остаются вашими: без рекламы, без слежки', + 'native.cloud.cta': 'Начать', + 'native.cloud.haveServer': 'У меня уже есть TREK', + 'native.connecting': 'Подключение к {host}', + 'native.back': 'Назад', + 'native.plans.title': 'Выберите тариф', + 'native.plans.sub': 'TREK на вашем собственном адресе. Меняйте или отменяйте в любое время.', + 'native.plans.monthly': 'Ежемесячно', + 'native.plans.yearly': 'Ежегодно', + 'native.plans.save': '2 месяца бесплатно', + 'native.plans.perMonth': 'в месяц', + 'native.plans.perYear': 'в год', + 'native.plans.aiDocs': '{n} ИИ-документов в месяц', + 'native.plans.noAi': 'Без ИИ-документов', + 'native.plans.storage': '{n} ГБ хранилища', + 'native.plans.unlimited': 'Без ограничений на места, поездки и людей', + 'native.plans.subscribe': 'Подписаться', + 'native.plans.loadError': 'Не удалось загрузить тарифы. Проверьте подключение и повторите попытку.', + 'native.plans.retry': 'Повторить', + 'native.plans.soon': 'Подписки в приложении скоро появятся. Пока оформите на сайте.', + 'native.claim.title': 'Создайте свой TREK', + 'native.claim.sub': 'Выберите адрес. Мы сразу всё настроим.', + 'native.claim.addressLabel': 'Ваш адрес', + 'native.claim.taken': 'Этот адрес занят.', + 'native.claim.invalid': 'Три и более букв, цифр и дефисов.', + 'native.claim.reserved': 'Этот адрес зарезервирован.', + 'native.claim.free': 'Доступно', + 'native.claim.emailLabel': 'Эл. почта', + 'native.claim.emailHint': 'Для вашего аккаунта и чеков.', + 'native.claim.subscribe': 'Подписаться за {price}', + 'native.claim.cancelled': 'Покупка отменена.', + 'native.claim.failed': 'Покупка не прошла. Повторите попытку.', + 'native.claim.redeemFailed': 'Не удалось настроить ваш TREK. Повторите попытку.', + 'native.provisioning.title': 'Настраиваем ваш TREK', + 'native.provisioning.sub': 'Готовим {host}. Это займёт всего минуту.', + 'native.provisioning.failedTitle': 'Почти готово', + 'native.provisioning.failedSub': + 'Ваш TREK уже в пути. Повторите попытку через мгновение или откройте приложение позже.', + 'native.provisioning.retry': 'Повторить сейчас', +}; + +export default native; diff --git a/shared/src/i18n/sk/index.ts b/shared/src/i18n/sk/index.ts index 7c371269a..1a0ff1d80 100644 --- a/shared/src/i18n/sk/index.ts +++ b/shared/src/i18n/sk/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -96,6 +97,7 @@ const locale = { ...share, ...shared, ...login, + ...native, ...vacay, ...collection, ...atlas, diff --git a/shared/src/i18n/sk/native.ts b/shared/src/i18n/sk/native.ts new file mode 100644 index 000000000..f9dd48585 --- /dev/null +++ b/shared/src/i18n/sk/native.ts @@ -0,0 +1,79 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': 'Pripojiť k TREK', + 'native.connect.hint': 'Zadajte adresu, na ktorej otvárate TREK v prehliadači.', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': 'Pripojiť', + 'native.connect.checking': 'Overuje sa…', + 'native.connect.tryDemo': 'Ešte nemáte server? Vyskúšajte demo', + 'native.connect.whatIsServer': 'Čo je server TREK?', + 'native.connect.errorInvalid': 'Toto nevyzerá ako webová adresa.', + 'native.connect.errorUnreachable': 'Na tejto adrese neodpovedal žiadny server. Skontrolujte adresu a pripojenie.', + 'native.connect.errorNotTrek': 'Server na tejto adrese nie je TREK.', + 'native.connect.errorTooOld': 'Tento server TREK je pre aplikáciu príliš starý. Najprv ho treba aktualizovať.', + 'native.offline.title': 'Server nie je dostupný', + 'native.offline.hint': 'TREK sa nepodarilo spojiť so serverom {server}. Skontrolujte pripojenie a skúste to znova.', + 'native.offline.retry': 'Skúsiť znova', + 'native.changeServer': 'Zmeniť server', + 'native.login.failed': 'Prihlásenie sa nepodarilo. Skúste to, prosím, znova.', + 'native.handoff.title': 'Pokračovať v aplikácii', + 'native.handoff.hint': 'Ste prihlásení ako {name}. Otvorte aplikáciu TREK a dokončite prihlásenie v nej.', + 'native.handoff.open': 'Otvoriť aplikáciu TREK', + 'native.handoff.switchAccount': 'Použiť iný účet', + 'native.privacy': 'Zásady ochrany osobných údajov', + 'native.settings.server': 'Server', // same-as-en + 'native.settings.serverHint': 'Táto aplikácia je pripojená k serveru {server}.', + 'native.welcome.headline': 'Plánujte cesty spoločne.', + 'native.welcome.sub': + 'TREK drží každý deň, miesto, rezerváciu aj výdavok v jednom živom pláne, ktorý celá skupina upravuje spoločne.', + 'native.welcome.connect': 'Pripojte svoj TREK', + 'native.welcome.connectSub': 'Otvorte adresu, ktorú už používate', + 'native.welcome.getCloud': 'Získať TREK Cloud', + 'native.welcome.getCloudSub': 'Hostované za vás, bez inštalácie', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': + 'TREK hostujeme za vás, na vašej vlastnej adrese. Nič neinštalujete, nič neudržiavate: hotovo za pár minút.', + 'native.cloud.f1': 'Vlastná adresa, na serveroch v Nemecku', + 'native.cloud.f2': 'Hotovo za pár minút, aktualizácie riešime my', + 'native.cloud.f3': 'Vaše údaje zostávajú vaše: žiadne reklamy, žiadne sledovanie', + 'native.cloud.cta': 'Začať', + 'native.cloud.haveServer': 'Už mám TREK', + 'native.connecting': 'Pripájanie k {host}', + 'native.back': 'Späť', + 'native.plans.title': 'Vyberte si tarif', + 'native.plans.sub': 'TREK hostovaný na vašej vlastnej adrese. Kedykoľvek zmeňte alebo zrušte.', + 'native.plans.monthly': 'Mesačne', + 'native.plans.yearly': 'Ročne', + 'native.plans.save': '2 mesiace zadarmo', + 'native.plans.perMonth': 'mesačne', + 'native.plans.perYear': 'ročne', + 'native.plans.aiDocs': '{n} dokumentov s AI mesačne', + 'native.plans.noAi': 'Žiadne dokumenty s AI', + 'native.plans.storage': '{n} GB úložiska', + 'native.plans.unlimited': 'Neobmedzene miest, ciest a ľudí', + 'native.plans.subscribe': 'Predplatiť', + 'native.plans.loadError': 'Tarify sa nepodarilo načítať. Skontrolujte pripojenie a skúste to znova.', + 'native.plans.retry': 'Skúsiť znova', + 'native.plans.soon': 'Predplatné v aplikácii čoskoro príde. Zatiaľ to dokončite na webe.', + 'native.claim.title': 'Vytvorte svoj TREK', + 'native.claim.sub': 'Vyberte si adresu. Hneď ju pripravíme.', + 'native.claim.addressLabel': 'Vaša adresa', + 'native.claim.taken': 'Táto adresa je obsadená.', + 'native.claim.invalid': 'Tri a viac písmen, číslic a pomlčiek.', + 'native.claim.reserved': 'Táto adresa je rezervovaná.', + 'native.claim.free': 'Dostupné', + 'native.claim.emailLabel': 'E-mail', + 'native.claim.emailHint': 'Pre váš účet a účtenky.', + 'native.claim.subscribe': 'Predplatiť za {price}', + 'native.claim.cancelled': 'Nákup zrušený.', + 'native.claim.failed': 'Nákup sa nepodaril. Skúste to znova.', + 'native.claim.redeemFailed': 'Nepodarilo sa pripraviť váš TREK. Skúste to znova.', + 'native.provisioning.title': 'Pripravujeme váš TREK', + 'native.provisioning.sub': 'Pripravujeme {host}. Zaberie to len minútu.', + 'native.provisioning.failedTitle': 'Takmer hotovo', + 'native.provisioning.failedSub': 'Váš TREK je na ceste. Skúste to o chvíľu znova alebo otvorte aplikáciu neskôr.', + 'native.provisioning.retry': 'Skúsiť teraz', +}; + +export default native; diff --git a/shared/src/i18n/sv/index.ts b/shared/src/i18n/sv/index.ts index bcc4778a6..403813aa6 100644 --- a/shared/src/i18n/sv/index.ts +++ b/shared/src/i18n/sv/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -101,6 +102,7 @@ const locale = { ...share, ...shared, ...login, + ...native, ...vacay, ...collection, ...atlas, diff --git a/shared/src/i18n/sv/native.ts b/shared/src/i18n/sv/native.ts new file mode 100644 index 000000000..9bef2c7d6 --- /dev/null +++ b/shared/src/i18n/sv/native.ts @@ -0,0 +1,80 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': 'Anslut till TREK', + 'native.connect.hint': 'Ange adressen du öppnar TREK på i webbläsaren.', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': 'Anslut', + 'native.connect.checking': 'Kontrollerar…', + 'native.connect.tryDemo': 'Ingen server än? Testa demon', + 'native.connect.whatIsServer': 'Vad är en TREK-server?', + 'native.connect.errorInvalid': 'Det ser inte ut som en webbadress.', + 'native.connect.errorUnreachable': + 'Ingen server svarar på den här adressen. Kontrollera adressen och din anslutning.', + 'native.connect.errorNotTrek': 'Servern på den här adressen är inte TREK.', + 'native.connect.errorTooOld': 'Den här TREK-servern är för gammal för appen. Den behöver uppdateras först.', + 'native.offline.title': 'Servern går inte att nå', + 'native.offline.hint': 'TREK kunde inte nå {server}. Kontrollera din anslutning och försök igen.', + 'native.offline.retry': 'Försök igen', + 'native.changeServer': 'Byt server', + 'native.login.failed': 'Inloggningen misslyckades. Försök igen.', + 'native.handoff.title': 'Fortsätt i appen', + 'native.handoff.hint': 'Du är inloggad som {name}. Öppna TREK-appen för att slutföra inloggningen där.', + 'native.handoff.open': 'Öppna TREK-appen', + 'native.handoff.switchAccount': 'Använd ett annat konto', + 'native.privacy': 'Integritetspolicy', + 'native.settings.server': 'Server', // same-as-en + 'native.settings.serverHint': 'Den här appen är ansluten till {server}.', + 'native.welcome.headline': 'Planera resor tillsammans.', + 'native.welcome.sub': + 'TREK samlar varje dag, plats, bokning och kostnad i en levande plan som hela gruppen redigerar tillsammans.', + 'native.welcome.connect': 'Anslut din TREK', + 'native.welcome.connectSub': 'Öppna adressen du redan använder', + 'native.welcome.getCloud': 'Skaffa TREK Cloud', + 'native.welcome.getCloudSub': 'Hostat åt dig, utan installation', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': + 'Vi hostar TREK åt dig, på din egen adress. Inget att installera, inget att underhålla: klart på några minuter.', + 'native.cloud.f1': 'Din egen adress, på servrar i Tyskland', + 'native.cloud.f2': 'Klart på några minuter, uppdateringar sköter vi', + 'native.cloud.f3': 'Dina data förblir dina: inga annonser, ingen spårning', + 'native.cloud.cta': 'Kom igång', + 'native.cloud.haveServer': 'Jag har redan en TREK', + 'native.connecting': 'Ansluter till {host}', + 'native.back': 'Tillbaka', + 'native.plans.title': 'Välj ditt abonnemang', + 'native.plans.sub': 'TREK hostat på din egen adress. Ändra eller avsluta när som helst.', + 'native.plans.monthly': 'Månadsvis', + 'native.plans.yearly': 'Årsvis', + 'native.plans.save': '2 månader gratis', + 'native.plans.perMonth': 'per månad', + 'native.plans.perYear': 'per år', + 'native.plans.aiDocs': '{n} AI-dokument i månaden', + 'native.plans.noAi': 'Inga AI-dokument', + 'native.plans.storage': '{n} GB lagring', + 'native.plans.unlimited': 'Obegränsat med platser, resor och personer', + 'native.plans.subscribe': 'Prenumerera', + 'native.plans.loadError': 'Det gick inte att läsa in abonnemangen. Kontrollera anslutningen och försök igen.', + 'native.plans.retry': 'Försök igen', + 'native.plans.soon': 'Prenumerationer i appen är på väg. Slutför på webben tills vidare.', + 'native.claim.title': 'Skapa din TREK', + 'native.claim.sub': 'Välj din adress. Vi gör i ordning den direkt.', + 'native.claim.addressLabel': 'Din adress', + 'native.claim.taken': 'Den adressen är upptagen.', + 'native.claim.invalid': 'Tre eller fler bokstäver, siffror och bindestreck.', + 'native.claim.reserved': 'Den adressen är reserverad.', + 'native.claim.free': 'Ledig', + 'native.claim.emailLabel': 'E-post', + 'native.claim.emailHint': 'För ditt konto och dina kvitton.', + 'native.claim.subscribe': 'Prenumerera för {price}', + 'native.claim.cancelled': 'Köpet avbröts.', + 'native.claim.failed': 'Köpet gick inte igenom. Försök igen.', + 'native.claim.redeemFailed': 'Vi kunde inte göra i ordning din TREK. Försök igen.', + 'native.provisioning.title': 'Gör i ordning din TREK', + 'native.provisioning.sub': 'Gör i ordning {host}. Det tar bara en minut.', + 'native.provisioning.failedTitle': 'Snart klart', + 'native.provisioning.failedSub': 'Din TREK är på väg. Försök igen om en stund eller öppna appen senare.', + 'native.provisioning.retry': 'Försök nu', +}; + +export default native; diff --git a/shared/src/i18n/th/index.ts b/shared/src/i18n/th/index.ts index 7c371269a..1a0ff1d80 100644 --- a/shared/src/i18n/th/index.ts +++ b/shared/src/i18n/th/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -96,6 +97,7 @@ const locale = { ...share, ...shared, ...login, + ...native, ...vacay, ...collection, ...atlas, diff --git a/shared/src/i18n/th/native.ts b/shared/src/i18n/th/native.ts new file mode 100644 index 000000000..0a9bc3f2d --- /dev/null +++ b/shared/src/i18n/th/native.ts @@ -0,0 +1,77 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': 'เชื่อมต่อกับ TREK', + 'native.connect.hint': 'ป้อนที่อยู่ที่คุณใช้เปิด TREK ในเบราว์เซอร์', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': 'เชื่อมต่อ', + 'native.connect.checking': 'กำลังตรวจสอบ…', + 'native.connect.tryDemo': 'ยังไม่มีเซิร์ฟเวอร์ใช่ไหม ลองใช้เดโม', + 'native.connect.whatIsServer': 'เซิร์ฟเวอร์ TREK คืออะไร', + 'native.connect.errorInvalid': 'ดูเหมือนว่านี่ไม่ใช่ที่อยู่เว็บ', + 'native.connect.errorUnreachable': 'ไม่มีเซิร์ฟเวอร์ตอบกลับที่ที่อยู่นี้ โปรดตรวจสอบที่อยู่และการเชื่อมต่อของคุณ', + 'native.connect.errorNotTrek': 'เซิร์ฟเวอร์ที่ที่อยู่นี้ไม่ใช่ TREK', + 'native.connect.errorTooOld': 'เซิร์ฟเวอร์ TREK นี้เก่าเกินไปสำหรับแอป ต้องอัปเดตก่อน', + 'native.offline.title': 'เข้าถึงเซิร์ฟเวอร์ไม่ได้', + 'native.offline.hint': 'TREK เข้าถึง {server} ไม่ได้ โปรดตรวจสอบการเชื่อมต่อแล้วลองอีกครั้ง', + 'native.offline.retry': 'ลองอีกครั้ง', + 'native.changeServer': 'เปลี่ยนเซิร์ฟเวอร์', + 'native.login.failed': 'เข้าสู่ระบบไม่สำเร็จ โปรดลองอีกครั้ง', + 'native.handoff.title': 'ดำเนินการต่อในแอป', + 'native.handoff.hint': 'คุณเข้าสู่ระบบในชื่อ {name} เปิดแอป TREK เพื่อเข้าสู่ระบบให้เสร็จสิ้นที่นั่น', + 'native.handoff.open': 'เปิดแอป TREK', + 'native.handoff.switchAccount': 'ใช้บัญชีอื่น', + 'native.privacy': 'นโยบายความเป็นส่วนตัว', + 'native.settings.server': 'เซิร์ฟเวอร์', + 'native.settings.serverHint': 'แอปนี้เชื่อมต่อกับ {server} อยู่', + 'native.welcome.headline': 'วางแผนการเดินทางไปด้วยกัน', + 'native.welcome.sub': 'TREK รวมทุกวัน สถานที่ การจอง และค่าใช้จ่ายไว้ในแผนเดียวแบบเรียลไทม์ที่ทั้งกลุ่มแก้ไขร่วมกัน', + 'native.welcome.connect': 'เชื่อมต่อ TREK ของคุณ', + 'native.welcome.connectSub': 'เปิดที่อยู่ที่คุณใช้อยู่แล้ว', + 'native.welcome.getCloud': 'รับ TREK Cloud', + 'native.welcome.getCloudSub': 'โฮสต์ให้คุณ ไม่ต้องตั้งค่า', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': 'เราโฮสต์ TREK ให้คุณ บนที่อยู่ของคุณเอง ไม่ต้องติดตั้ง ไม่ต้องดูแล พร้อมใช้ในไม่กี่นาที', + 'native.cloud.f1': 'ที่อยู่ของคุณเอง บนเซิร์ฟเวอร์ในเยอรมนี', + 'native.cloud.f2': 'พร้อมใช้ในไม่กี่นาที การอัปเดตเราจัดการให้', + 'native.cloud.f3': 'ข้อมูลของคุณยังเป็นของคุณ ไม่มีโฆษณา ไม่มีการติดตาม', + 'native.cloud.cta': 'เริ่มต้น', + 'native.cloud.haveServer': 'ฉันมี TREK อยู่แล้ว', + 'native.connecting': 'กำลังเชื่อมต่อกับ {host}', + 'native.back': 'กลับ', + 'native.plans.title': 'เลือกแพ็กเกจของคุณ', + 'native.plans.sub': 'TREK ที่โฮสต์บนที่อยู่ของคุณเอง เปลี่ยนหรือยกเลิกได้ทุกเมื่อ', + 'native.plans.monthly': 'รายเดือน', + 'native.plans.yearly': 'รายปี', + 'native.plans.save': 'ฟรี 2 เดือน', + 'native.plans.perMonth': 'ต่อเดือน', + 'native.plans.perYear': 'ต่อปี', + 'native.plans.aiDocs': 'เอกสาร AI {n} ฉบับต่อเดือน', + 'native.plans.noAi': 'ไม่มีเอกสาร AI', + 'native.plans.storage': 'พื้นที่เก็บข้อมูล {n} GB', + 'native.plans.unlimited': 'สถานที่ ทริป และผู้คนไม่จำกัด', + 'native.plans.subscribe': 'สมัครสมาชิก', + 'native.plans.loadError': 'โหลดแพ็กเกจไม่สำเร็จ ตรวจสอบการเชื่อมต่อแล้วลองอีกครั้ง', + 'native.plans.retry': 'ลองอีกครั้ง', + 'native.plans.soon': 'การสมัครสมาชิกในแอปกำลังจะมา ตอนนี้ทำให้เสร็จบนเว็บไซต์ก่อน', + 'native.claim.title': 'สร้าง TREK ของคุณ', + 'native.claim.sub': 'เลือกที่อยู่ของคุณ เราจะตั้งค่าให้ทันที', + 'native.claim.addressLabel': 'ที่อยู่ของคุณ', + 'native.claim.taken': 'ที่อยู่นี้ถูกใช้แล้ว', + 'native.claim.invalid': 'ตัวอักษร ตัวเลข และขีดกลาง ตั้งแต่สามตัวขึ้นไป', + 'native.claim.reserved': 'ที่อยู่นี้ถูกสงวนไว้', + 'native.claim.free': 'ว่าง', + 'native.claim.emailLabel': 'อีเมล', + 'native.claim.emailHint': 'สำหรับบัญชีและใบเสร็จของคุณ', + 'native.claim.subscribe': 'สมัครสมาชิกในราคา {price}', + 'native.claim.cancelled': 'ยกเลิกการซื้อแล้ว', + 'native.claim.failed': 'การซื้อไม่สำเร็จ โปรดลองอีกครั้ง', + 'native.claim.redeemFailed': 'เราตั้งค่า TREK ของคุณไม่สำเร็จ โปรดลองอีกครั้ง', + 'native.provisioning.title': 'กำลังตั้งค่า TREK ของคุณ', + 'native.provisioning.sub': 'กำลังเตรียม {host} ใช้เวลาเพียงหนึ่งนาที', + 'native.provisioning.failedTitle': 'เกือบเสร็จแล้ว', + 'native.provisioning.failedSub': 'TREK ของคุณกำลังมา ลองอีกครั้งในอีกสักครู่ หรือเปิดแอปในภายหลัง', + 'native.provisioning.retry': 'ลองตอนนี้', +}; + +export default native; diff --git a/shared/src/i18n/tr/index.ts b/shared/src/i18n/tr/index.ts index bcc4778a6..403813aa6 100644 --- a/shared/src/i18n/tr/index.ts +++ b/shared/src/i18n/tr/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -101,6 +102,7 @@ const locale = { ...share, ...shared, ...login, + ...native, ...vacay, ...collection, ...atlas, diff --git a/shared/src/i18n/tr/native.ts b/shared/src/i18n/tr/native.ts new file mode 100644 index 000000000..3edea167f --- /dev/null +++ b/shared/src/i18n/tr/native.ts @@ -0,0 +1,79 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': 'TREK’e bağlan', + 'native.connect.hint': 'TREK’i tarayıcında açtığın adresi gir.', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': 'Bağlan', + 'native.connect.checking': 'Kontrol ediliyor…', + 'native.connect.tryDemo': 'Henüz sunucun yok mu? Demoyu dene', + 'native.connect.whatIsServer': 'TREK sunucusu nedir?', + 'native.connect.errorInvalid': 'Bu bir web adresine benzemiyor.', + 'native.connect.errorUnreachable': 'Bu adreste yanıt veren bir sunucu yok. Adresi ve bağlantını kontrol et.', + 'native.connect.errorNotTrek': 'Bu adresteki sunucu TREK değil.', + 'native.connect.errorTooOld': 'Bu TREK sunucusu uygulama için çok eski. Önce güncellenmesi gerekiyor.', + 'native.offline.title': 'Sunucuya ulaşılamıyor', + 'native.offline.hint': 'TREK, {server} adresine ulaşamadı. Bağlantını kontrol edip tekrar dene.', + 'native.offline.retry': 'Tekrar dene', + 'native.changeServer': 'Sunucuyu değiştir', + 'native.login.failed': 'Giriş yapılamadı. Lütfen tekrar dene.', + 'native.handoff.title': 'Uygulamada devam et', + 'native.handoff.hint': '{name} olarak giriş yaptın. Girişi tamamlamak için TREK uygulamasını aç.', + 'native.handoff.open': 'TREK uygulamasını aç', + 'native.handoff.switchAccount': 'Başka bir hesap kullan', + 'native.privacy': 'Gizlilik politikası', + 'native.settings.server': 'Sunucu', + 'native.settings.serverHint': 'Bu uygulama {server} adresine bağlı.', + 'native.welcome.headline': 'Gezileri birlikte planlayın.', + 'native.welcome.sub': + 'TREK her günü, yeri, rezervasyonu ve masrafı tüm grubun birlikte düzenlediği tek bir canlı planda tutar.', + 'native.welcome.connect': 'TREK’inizi bağlayın', + 'native.welcome.connectSub': 'Zaten kullandığınız adresi açın', + 'native.welcome.getCloud': 'TREK Cloud’u edinin', + 'native.welcome.getCloudSub': 'Sizin için barındırılır, kurulum yok', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': + 'TREK’i sizin için, kendi adresinizde barındırırız. Kuracak bir şey yok, bakımı yok: dakikalar içinde hazır.', + 'native.cloud.f1': 'Kendi adresiniz, Almanya’daki sunucularda', + 'native.cloud.f2': 'Dakikalar içinde hazır, güncellemeler bizden', + 'native.cloud.f3': 'Verileriniz sizin kalır: reklam yok, takip yok', + 'native.cloud.cta': 'Başla', + 'native.cloud.haveServer': 'Zaten bir TREK’im var', + 'native.connecting': '{host} adresine bağlanılıyor', + 'native.back': 'Geri', + 'native.plans.title': 'Planınızı seçin', + 'native.plans.sub': 'Kendi adresinizde barındırılan TREK. İstediğiniz zaman değiştirin veya iptal edin.', + 'native.plans.monthly': 'Aylık', + 'native.plans.yearly': 'Yıllık', + 'native.plans.save': '2 ay ücretsiz', + 'native.plans.perMonth': 'ayda', + 'native.plans.perYear': 'yılda', + 'native.plans.aiDocs': 'ayda {n} yapay zeka belgesi', + 'native.plans.noAi': 'Yapay zeka belgesi yok', + 'native.plans.storage': '{n} GB depolama', + 'native.plans.unlimited': 'Sınırsız yer, gezi ve kişi', + 'native.plans.subscribe': 'Abone ol', + 'native.plans.loadError': 'Planlar yüklenemedi. Bağlantınızı kontrol edip tekrar deneyin.', + 'native.plans.retry': 'Tekrar dene', + 'native.plans.soon': 'Uygulama içi abonelikler yakında. Şimdilik web sitesinde tamamlayın.', + 'native.claim.title': 'TREK’inizi oluşturun', + 'native.claim.sub': 'Adresinizi seçin. Hemen hazırlıyoruz.', + 'native.claim.addressLabel': 'Adresiniz', + 'native.claim.taken': 'Bu adres alınmış.', + 'native.claim.invalid': 'Üç ya da daha fazla harf, rakam ve tire.', + 'native.claim.reserved': 'Bu adres ayrılmış.', + 'native.claim.free': 'Uygun', + 'native.claim.emailLabel': 'E-posta', + 'native.claim.emailHint': 'Hesabınız ve makbuzlarınız için.', + 'native.claim.subscribe': '{price} karşılığında abone ol', + 'native.claim.cancelled': 'Satın alma iptal edildi.', + 'native.claim.failed': 'Satın alma tamamlanamadı. Lütfen tekrar deneyin.', + 'native.claim.redeemFailed': 'TREK’inizi hazırlayamadık. Lütfen tekrar deneyin.', + 'native.provisioning.title': 'TREK’iniz hazırlanıyor', + 'native.provisioning.sub': '{host} hazırlanıyor. Bu yalnızca bir dakika sürer.', + 'native.provisioning.failedTitle': 'Neredeyse hazır', + 'native.provisioning.failedSub': 'TREK’iniz yolda. Birazdan tekrar deneyin ya da uygulamayı sonra açın.', + 'native.provisioning.retry': 'Şimdi dene', +}; + +export default native; diff --git a/shared/src/i18n/uk/index.ts b/shared/src/i18n/uk/index.ts index bcc4778a6..403813aa6 100644 --- a/shared/src/i18n/uk/index.ts +++ b/shared/src/i18n/uk/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -101,6 +102,7 @@ const locale = { ...share, ...shared, ...login, + ...native, ...vacay, ...collection, ...atlas, diff --git a/shared/src/i18n/uk/native.ts b/shared/src/i18n/uk/native.ts new file mode 100644 index 000000000..04ce76bb8 --- /dev/null +++ b/shared/src/i18n/uk/native.ts @@ -0,0 +1,79 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': 'Підключення до TREK', + 'native.connect.hint': 'Введіть адресу, за якою ви відкриваєте TREK у браузері.', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': 'Підключитися', + 'native.connect.checking': 'Перевірка…', + 'native.connect.tryDemo': 'Ще немає сервера? Спробуйте демо', + 'native.connect.whatIsServer': 'Що таке сервер TREK?', + 'native.connect.errorInvalid': 'Це не схоже на вебадресу.', + 'native.connect.errorUnreachable': 'За цією адресою не відповідає жоден сервер. Перевірте адресу та з’єднання.', + 'native.connect.errorNotTrek': 'Сервер за цією адресою не є TREK.', + 'native.connect.errorTooOld': 'Цей сервер TREK застарий для застосунку. Спершу його потрібно оновити.', + 'native.offline.title': 'Сервер недоступний', + 'native.offline.hint': 'TREK не вдалося підключитися до {server}. Перевірте з’єднання та спробуйте ще раз.', + 'native.offline.retry': 'Спробувати ще раз', + 'native.changeServer': 'Змінити сервер', + 'native.login.failed': 'Не вдалося увійти. Спробуйте ще раз.', + 'native.handoff.title': 'Продовжити в застосунку', + 'native.handoff.hint': 'Ви увійшли як {name}. Відкрийте застосунок TREK, щоб завершити вхід у ньому.', + 'native.handoff.open': 'Відкрити застосунок TREK', + 'native.handoff.switchAccount': 'Використати інший обліковий запис', + 'native.privacy': 'Політика конфіденційності', + 'native.settings.server': 'Сервер', + 'native.settings.serverHint': 'Застосунок підключено до {server}.', + 'native.welcome.headline': 'Плануйте подорожі разом.', + 'native.welcome.sub': + 'TREK зберігає кожен день, місце, бронювання та витрату в одному живому плані, який уся група редагує разом.', + 'native.welcome.connect': 'Підключіть свій TREK', + 'native.welcome.connectSub': 'Відкрийте адресу, якою вже користуєтеся', + 'native.welcome.getCloud': 'Отримати TREK Cloud', + 'native.welcome.getCloudSub': 'Розміщено для вас, без налаштування', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': + 'Ми розміщуємо TREK для вас, на вашій власній адресі. Нічого не потрібно встановлювати чи обслуговувати: готово за кілька хвилин.', + 'native.cloud.f1': 'Власна адреса, на серверах у Німеччині', + 'native.cloud.f2': 'Готово за кілька хвилин, оновлення беремо на себе', + 'native.cloud.f3': 'Ваші дані залишаються вашими: без реклами, без стеження', + 'native.cloud.cta': 'Почати', + 'native.cloud.haveServer': 'У мене вже є TREK', + 'native.connecting': 'Підключення до {host}', + 'native.back': 'Назад', + 'native.plans.title': 'Виберіть тариф', + 'native.plans.sub': 'TREK на вашій власній адресі. Змінюйте або скасовуйте будь-коли.', + 'native.plans.monthly': 'Щомісяця', + 'native.plans.yearly': 'Щороку', + 'native.plans.save': '2 місяці безкоштовно', + 'native.plans.perMonth': 'на місяць', + 'native.plans.perYear': 'на рік', + 'native.plans.aiDocs': '{n} ШІ-документів на місяць', + 'native.plans.noAi': 'Без ШІ-документів', + 'native.plans.storage': '{n} ГБ сховища', + 'native.plans.unlimited': 'Без обмежень на місця, подорожі та людей', + 'native.plans.subscribe': 'Підписатися', + 'native.plans.loadError': 'Не вдалося завантажити тарифи. Перевірте з’єднання та повторіть спробу.', + 'native.plans.retry': 'Повторити', + 'native.plans.soon': 'Підписки в застосунку вже скоро. Поки що завершіть на сайті.', + 'native.claim.title': 'Створіть свій TREK', + 'native.claim.sub': 'Виберіть адресу. Ми одразу все налаштуємо.', + 'native.claim.addressLabel': 'Ваша адреса', + 'native.claim.taken': 'Ця адреса зайнята.', + 'native.claim.invalid': 'Три або більше літер, цифр і дефісів.', + 'native.claim.reserved': 'Ця адреса зарезервована.', + 'native.claim.free': 'Доступно', + 'native.claim.emailLabel': 'Ел. пошта', + 'native.claim.emailHint': 'Для вашого облікового запису та чеків.', + 'native.claim.subscribe': 'Підписатися за {price}', + 'native.claim.cancelled': 'Покупку скасовано.', + 'native.claim.failed': 'Покупка не пройшла. Повторіть спробу.', + 'native.claim.redeemFailed': 'Не вдалося налаштувати ваш TREK. Повторіть спробу.', + 'native.provisioning.title': 'Налаштовуємо ваш TREK', + 'native.provisioning.sub': 'Готуємо {host}. Це займе лише хвилину.', + 'native.provisioning.failedTitle': 'Майже готово', + 'native.provisioning.failedSub': 'Ваш TREK уже в дорозі. Повторіть спробу за мить або відкрийте застосунок пізніше.', + 'native.provisioning.retry': 'Повторити зараз', +}; + +export default native; diff --git a/shared/src/i18n/vi/index.ts b/shared/src/i18n/vi/index.ts index bcc4778a6..403813aa6 100644 --- a/shared/src/i18n/vi/index.ts +++ b/shared/src/i18n/vi/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -101,6 +102,7 @@ const locale = { ...share, ...shared, ...login, + ...native, ...vacay, ...collection, ...atlas, diff --git a/shared/src/i18n/vi/native.ts b/shared/src/i18n/vi/native.ts new file mode 100644 index 000000000..a5b570a20 --- /dev/null +++ b/shared/src/i18n/vi/native.ts @@ -0,0 +1,80 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': 'Kết nối với TREK', + 'native.connect.hint': 'Nhập địa chỉ bạn dùng để mở TREK trong trình duyệt.', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': 'Kết nối', + 'native.connect.checking': 'Đang kiểm tra…', + 'native.connect.tryDemo': 'Chưa có máy chủ? Dùng thử bản demo', + 'native.connect.whatIsServer': 'Máy chủ TREK là gì?', + 'native.connect.errorInvalid': 'Đây có vẻ không phải là địa chỉ web.', + 'native.connect.errorUnreachable': + 'Không có máy chủ nào phản hồi tại địa chỉ này. Hãy kiểm tra địa chỉ và kết nối của bạn.', + 'native.connect.errorNotTrek': 'Máy chủ tại địa chỉ này không phải TREK.', + 'native.connect.errorTooOld': 'Máy chủ TREK này quá cũ đối với ứng dụng. Máy chủ cần được cập nhật trước.', + 'native.offline.title': 'Không kết nối được máy chủ', + 'native.offline.hint': 'TREK không thể kết nối tới {server}. Hãy kiểm tra kết nối và thử lại.', + 'native.offline.retry': 'Thử lại', + 'native.changeServer': 'Đổi máy chủ', + 'native.login.failed': 'Đăng nhập không thành công. Vui lòng thử lại.', + 'native.handoff.title': 'Tiếp tục trong ứng dụng', + 'native.handoff.hint': 'Bạn đã đăng nhập với tên {name}. Mở ứng dụng TREK để hoàn tất đăng nhập ở đó.', + 'native.handoff.open': 'Mở ứng dụng TREK', + 'native.handoff.switchAccount': 'Dùng tài khoản khác', + 'native.privacy': 'Chính sách quyền riêng tư', + 'native.settings.server': 'Máy chủ', + 'native.settings.serverHint': 'Ứng dụng này đang kết nối với {server}.', + 'native.welcome.headline': 'Cùng nhau lên kế hoạch chuyến đi.', + 'native.welcome.sub': + 'TREK giữ mọi ngày, địa điểm, đặt chỗ và chi phí trong một kế hoạch trực tiếp mà cả nhóm cùng chỉnh sửa.', + 'native.welcome.connect': 'Kết nối TREK của bạn', + 'native.welcome.connectSub': 'Mở địa chỉ bạn vẫn dùng', + 'native.welcome.getCloud': 'Nhận TREK Cloud', + 'native.welcome.getCloudSub': 'Được lưu trữ sẵn cho bạn, không cần cài đặt', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': + 'Chúng tôi lưu trữ TREK cho bạn, trên địa chỉ của riêng bạn. Không cần cài đặt, không cần bảo trì: sẵn sàng trong vài phút.', + 'native.cloud.f1': 'Địa chỉ riêng của bạn, trên máy chủ ở Đức', + 'native.cloud.f2': 'Sẵn sàng trong vài phút, bản cập nhật do chúng tôi lo', + 'native.cloud.f3': 'Dữ liệu của bạn vẫn là của bạn: không quảng cáo, không theo dõi', + 'native.cloud.cta': 'Bắt đầu', + 'native.cloud.haveServer': 'Tôi đã có TREK', + 'native.connecting': 'Đang kết nối tới {host}', + 'native.back': 'Quay lại', + 'native.plans.title': 'Chọn gói của bạn', + 'native.plans.sub': 'TREK lưu trữ trên địa chỉ riêng của bạn. Thay đổi hoặc hủy bất cứ lúc nào.', + 'native.plans.monthly': 'Hằng tháng', + 'native.plans.yearly': 'Hằng năm', + 'native.plans.save': 'Miễn phí 2 tháng', + 'native.plans.perMonth': 'mỗi tháng', + 'native.plans.perYear': 'mỗi năm', + 'native.plans.aiDocs': '{n} tài liệu AI mỗi tháng', + 'native.plans.noAi': 'Không có tài liệu AI', + 'native.plans.storage': '{n} GB lưu trữ', + 'native.plans.unlimited': 'Không giới hạn địa điểm, chuyến đi và người', + 'native.plans.subscribe': 'Đăng ký', + 'native.plans.loadError': 'Không thể tải các gói. Hãy kiểm tra kết nối và thử lại.', + 'native.plans.retry': 'Thử lại', + 'native.plans.soon': 'Đăng ký trong ứng dụng sắp ra mắt. Hiện tại, hãy hoàn tất trên trang web.', + 'native.claim.title': 'Tạo TREK của bạn', + 'native.claim.sub': 'Chọn địa chỉ của bạn. Chúng tôi thiết lập ngay.', + 'native.claim.addressLabel': 'Địa chỉ của bạn', + 'native.claim.taken': 'Địa chỉ đó đã có người dùng.', + 'native.claim.invalid': 'Từ ba chữ cái, chữ số và dấu gạch nối trở lên.', + 'native.claim.reserved': 'Địa chỉ đó đã được giữ chỗ.', + 'native.claim.free': 'Có sẵn', + 'native.claim.emailLabel': 'Email', // same-as-en + 'native.claim.emailHint': 'Cho tài khoản và biên nhận của bạn.', + 'native.claim.subscribe': 'Đăng ký với giá {price}', + 'native.claim.cancelled': 'Đã hủy mua.', + 'native.claim.failed': 'Giao dịch mua không thành công. Vui lòng thử lại.', + 'native.claim.redeemFailed': 'Chúng tôi không thể thiết lập TREK của bạn. Vui lòng thử lại.', + 'native.provisioning.title': 'Đang thiết lập TREK của bạn', + 'native.provisioning.sub': 'Đang chuẩn bị {host}. Chỉ mất một phút.', + 'native.provisioning.failedTitle': 'Gần xong', + 'native.provisioning.failedSub': 'TREK của bạn đang trên đường. Hãy thử lại sau giây lát, hoặc mở ứng dụng sau.', + 'native.provisioning.retry': 'Thử ngay', +}; + +export default native; diff --git a/shared/src/i18n/zh-TW/index.ts b/shared/src/i18n/zh-TW/index.ts index 55bbcba91..5a69724d7 100644 --- a/shared/src/i18n/zh-TW/index.ts +++ b/shared/src/i18n/zh-TW/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -101,6 +102,7 @@ const locale = { ...share, ...shared, ...login, + ...native, ...vacay, ...collection, ...atlas, diff --git a/shared/src/i18n/zh-TW/native.ts b/shared/src/i18n/zh-TW/native.ts new file mode 100644 index 000000000..73a8823b9 --- /dev/null +++ b/shared/src/i18n/zh-TW/native.ts @@ -0,0 +1,77 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': '連線到 TREK', + 'native.connect.hint': '請輸入你在瀏覽器中開啟 TREK 時使用的網址。', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': '連線', + 'native.connect.checking': '正在檢查…', + 'native.connect.tryDemo': '還沒有伺服器?試試示範版', + 'native.connect.whatIsServer': '什麼是 TREK 伺服器?', + 'native.connect.errorInvalid': '這看起來不像網址。', + 'native.connect.errorUnreachable': '此網址沒有伺服器回應。請檢查網址與網路連線。', + 'native.connect.errorNotTrek': '此網址上的伺服器不是 TREK。', + 'native.connect.errorTooOld': '此 TREK 伺服器版本過舊,無法用於 App。請先更新伺服器。', + 'native.offline.title': '無法連線到伺服器', + 'native.offline.hint': 'TREK 無法連線到 {server}。請檢查網路連線後再試一次。', + 'native.offline.retry': '再試一次', + 'native.changeServer': '更換伺服器', + 'native.login.failed': '登入未成功,請再試一次。', + 'native.handoff.title': '在 App 中繼續', + 'native.handoff.hint': '你已以 {name} 身分登入。請開啟 TREK App,在那裡完成登入。', + 'native.handoff.open': '開啟 TREK App', + 'native.handoff.switchAccount': '使用其他帳號', + 'native.privacy': '隱私權政策', + 'native.settings.server': '伺服器', + 'native.settings.serverHint': '此 App 已連線到 {server}。', + 'native.welcome.headline': '一起規劃旅行。', + 'native.welcome.sub': 'TREK 將每一天、地點、預訂和花費集中在一個即時計畫中,讓整個團隊共同編輯。', + 'native.welcome.connect': '連線你的 TREK', + 'native.welcome.connectSub': '開啟你已在使用的網址', + 'native.welcome.getCloud': '取得 TREK Cloud', + 'native.welcome.getCloudSub': '為你託管,無需架設', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': '我們為你託管 TREK,使用你自己的網址。無需安裝、無需維護,幾分鐘即可就緒。', + 'native.cloud.f1': '你專屬的網址,伺服器位於德國', + 'native.cloud.f2': '幾分鐘即可就緒,更新由我們負責', + 'native.cloud.f3': '你的資料仍屬於你:沒有廣告,沒有追蹤', + 'native.cloud.cta': '開始', + 'native.cloud.haveServer': '我已經有 TREK 了', + 'native.connecting': '正在連線 {host}', + 'native.back': '返回', + 'native.plans.title': '選擇方案', + 'native.plans.sub': '使用你自己的網址託管的 TREK。隨時變更或取消。', + 'native.plans.monthly': '每月', + 'native.plans.yearly': '每年', + 'native.plans.save': '免費 2 個月', + 'native.plans.perMonth': '每月', + 'native.plans.perYear': '每年', + 'native.plans.aiDocs': '每月 {n} 份 AI 文件', + 'native.plans.noAi': '無 AI 文件', + 'native.plans.storage': '{n} GB 儲存空間', + 'native.plans.unlimited': '地點、行程和人數不限', + 'native.plans.subscribe': '訂閱', + 'native.plans.loadError': '無法載入方案。請檢查網路連線後重試。', + 'native.plans.retry': '重試', + 'native.plans.soon': '應用程式內訂閱即將推出。目前請在網站上完成。', + 'native.claim.title': '建立你的 TREK', + 'native.claim.sub': '選擇你的網址。我們會立即為你準備好。', + 'native.claim.addressLabel': '你的網址', + 'native.claim.taken': '此網址已被使用。', + 'native.claim.invalid': '三個以上的字母、數字和連字號。', + 'native.claim.reserved': '此網址已被保留。', + 'native.claim.free': '可用', + 'native.claim.emailLabel': '電子郵件', + 'native.claim.emailHint': '用於你的帳戶和收據。', + 'native.claim.subscribe': '以 {price} 訂閱', + 'native.claim.cancelled': '已取消購買。', + 'native.claim.failed': '購買未成功。請重試。', + 'native.claim.redeemFailed': '我們無法為你設定 TREK。請重試。', + 'native.provisioning.title': '正在設定你的 TREK', + 'native.provisioning.sub': '正在準備 {host}。只需一分鐘。', + 'native.provisioning.failedTitle': '即將就緒', + 'native.provisioning.failedSub': '你的 TREK 即將就緒。請稍後重試,或稍後開啟應用程式。', + 'native.provisioning.retry': '立即重試', +}; + +export default native; diff --git a/shared/src/i18n/zh/index.ts b/shared/src/i18n/zh/index.ts index bcc4778a6..403813aa6 100644 --- a/shared/src/i18n/zh/index.ts +++ b/shared/src/i18n/zh/index.ts @@ -46,6 +46,7 @@ import mobileNav from './mobileNav'; import mobileSettings from './mobileSettings'; import mobileTrip from './mobileTrip'; import mobileVacay from './mobileVacay'; +import native from './native'; import nav from './nav'; import notif from './notif'; import notifications from './notifications'; @@ -101,6 +102,7 @@ const locale = { ...share, ...shared, ...login, + ...native, ...vacay, ...collection, ...atlas, diff --git a/shared/src/i18n/zh/native.ts b/shared/src/i18n/zh/native.ts new file mode 100644 index 000000000..ac4ad4e33 --- /dev/null +++ b/shared/src/i18n/zh/native.ts @@ -0,0 +1,77 @@ +import type { TranslationStrings } from '../types'; + +const native: TranslationStrings = { + 'native.connect.title': '连接到 TREK', + 'native.connect.hint': '请输入你在浏览器中打开 TREK 时使用的地址。', + 'native.connect.placeholder': 'https://trek.example.com', + 'native.connect.submit': '连接', + 'native.connect.checking': '正在检查…', + 'native.connect.tryDemo': '还没有服务器?试试演示版', + 'native.connect.whatIsServer': '什么是 TREK 服务器?', + 'native.connect.errorInvalid': '这看起来不像网址。', + 'native.connect.errorUnreachable': '此地址没有服务器响应。请检查地址和网络连接。', + 'native.connect.errorNotTrek': '此地址上的服务器不是 TREK。', + 'native.connect.errorTooOld': '此 TREK 服务器版本过旧,无法用于应用。请先更新服务器。', + 'native.offline.title': '无法连接服务器', + 'native.offline.hint': 'TREK 无法连接到 {server}。请检查网络连接后重试。', + 'native.offline.retry': '重试', + 'native.changeServer': '更换服务器', + 'native.login.failed': '登录未成功,请重试。', + 'native.handoff.title': '在应用中继续', + 'native.handoff.hint': '你已以 {name} 身份登录。请打开 TREK 应用,在那里完成登录。', + 'native.handoff.open': '打开 TREK 应用', + 'native.handoff.switchAccount': '使用其他账号', + 'native.privacy': '隐私政策', + 'native.settings.server': '服务器', + 'native.settings.serverHint': '此应用已连接到 {server}。', + 'native.welcome.headline': '一起规划旅行。', + 'native.welcome.sub': 'TREK 将每一天、地点、预订和花费集中在一个实时计划中,整个团队共同编辑。', + 'native.welcome.connect': '连接你的 TREK', + 'native.welcome.connectSub': '打开你已在使用的地址', + 'native.welcome.getCloud': '获取 TREK Cloud', + 'native.welcome.getCloudSub': '为你托管,无需搭建', + 'native.cloud.title': 'TREK Cloud', + 'native.cloud.sub': '我们为你托管 TREK,用你自己的地址。无需安装、无需维护,几分钟即可就绪。', + 'native.cloud.f1': '你专属的地址,服务器位于德国', + 'native.cloud.f2': '几分钟即可就绪,更新由我们负责', + 'native.cloud.f3': '你的数据仍归你所有:没有广告,没有追踪', + 'native.cloud.cta': '开始', + 'native.cloud.haveServer': '我已经有 TREK 了', + 'native.connecting': '正在连接 {host}', + 'native.back': '返回', + 'native.plans.title': '选择方案', + 'native.plans.sub': '用你自己的地址托管的 TREK。随时更改或取消。', + 'native.plans.monthly': '按月', + 'native.plans.yearly': '按年', + 'native.plans.save': '免费 2 个月', + 'native.plans.perMonth': '每月', + 'native.plans.perYear': '每年', + 'native.plans.aiDocs': '每月 {n} 份 AI 文档', + 'native.plans.noAi': '无 AI 文档', + 'native.plans.storage': '{n} GB 存储空间', + 'native.plans.unlimited': '地点、行程和人数不限', + 'native.plans.subscribe': '订阅', + 'native.plans.loadError': '无法加载方案。请检查网络连接后重试。', + 'native.plans.retry': '重试', + 'native.plans.soon': '应用内订阅即将推出。目前请在网站上完成。', + 'native.claim.title': '创建你的 TREK', + 'native.claim.sub': '选择你的地址。我们会立即为你准备好。', + 'native.claim.addressLabel': '你的地址', + 'native.claim.taken': '该地址已被占用。', + 'native.claim.invalid': '三个及以上的字母、数字和连字符。', + 'native.claim.reserved': '该地址已被保留。', + 'native.claim.free': '可用', + 'native.claim.emailLabel': '邮箱', + 'native.claim.emailHint': '用于你的账户和收据。', + 'native.claim.subscribe': '以 {price} 订阅', + 'native.claim.cancelled': '购买已取消。', + 'native.claim.failed': '购买未成功。请重试。', + 'native.claim.redeemFailed': '我们无法为你设置 TREK。请重试。', + 'native.provisioning.title': '正在设置你的 TREK', + 'native.provisioning.sub': '正在准备 {host}。只需一分钟。', + 'native.provisioning.failedTitle': '即将就绪', + 'native.provisioning.failedSub': '你的 TREK 正在路上。请稍后重试,或稍后打开应用。', + 'native.provisioning.retry': '立即重试', +}; + +export default native; diff --git a/shared/src/index.ts b/shared/src/index.ts index 50e408dd6..2b76fbe4e 100644 --- a/shared/src/index.ts +++ b/shared/src/index.ts @@ -231,6 +231,7 @@ export * from './auth/auth.schema'; export * from './auth/password-policy'; export * from './sessions/sessions.schema'; export * from './oidc/oidc.schema'; +export * from './native-auth/native-auth.schema'; export * from './oauth/oauth.schema'; export * from './admin/admin.schema'; export * from './service-identity/service-identity.schema'; diff --git a/shared/src/native-auth/native-auth.schema.spec.ts b/shared/src/native-auth/native-auth.schema.spec.ts new file mode 100644 index 000000000..f3e9bbd18 --- /dev/null +++ b/shared/src/native-auth/native-auth.schema.spec.ts @@ -0,0 +1,27 @@ +import { nativeExchangeRequestSchema, nativeHandoffRequestSchema } from './native-auth.schema'; + +import { describe, it, expect } from 'vitest'; + +const challenge = 'a'.repeat(64); + +describe('nativeHandoffRequestSchema', () => { + it('accepts a lowercase hex sha256', () => { + expect(nativeHandoffRequestSchema.safeParse({ challenge }).success).toBe(true); + }); + + it('rejects anything that is not 64 lowercase hex characters', () => { + expect(nativeHandoffRequestSchema.safeParse({ challenge: 'A'.repeat(64) }).success).toBe(false); + expect(nativeHandoffRequestSchema.safeParse({ challenge: 'a'.repeat(63) }).success).toBe(false); + expect(nativeHandoffRequestSchema.safeParse({ challenge: 'z'.repeat(64) }).success).toBe(false); + expect(nativeHandoffRequestSchema.safeParse({}).success).toBe(false); + }); +}); + +describe('nativeExchangeRequestSchema', () => { + it('requires a code and a verifier of at least 43 characters', () => { + expect(nativeExchangeRequestSchema.safeParse({ code: 'c', verifier: 'v'.repeat(43) }).success).toBe(true); + expect(nativeExchangeRequestSchema.safeParse({ code: 'c', verifier: 'v'.repeat(42) }).success).toBe(false); + expect(nativeExchangeRequestSchema.safeParse({ code: '', verifier: 'v'.repeat(43) }).success).toBe(false); + expect(nativeExchangeRequestSchema.safeParse({ verifier: 'v'.repeat(43) }).success).toBe(false); + }); +}); diff --git a/shared/src/native-auth/native-auth.schema.ts b/shared/src/native-auth/native-auth.schema.ts new file mode 100644 index 000000000..9ce947faf --- /dev/null +++ b/shared/src/native-auth/native-auth.schema.ts @@ -0,0 +1,30 @@ +import { z } from 'zod'; + +/** + * Sign-in hand-off for the native apps, /api/auth/native. + * + * The app shows the TREK web UI inside its own WebView, but SSO and passkeys + * cannot run there, so it signs in through the system browser instead and has + * to carry that session back. The app picks a random verifier and sends only + * its sha256 (the challenge) into the browser. The browser, once signed in, + * trades the challenge for a one-time code, and the WebView redeems the code + * together with the verifier. The code travels through a URL scheme any app + * could claim, so without the verifier it is worth nothing. + */ +const hexSha256 = z.string().regex(/^[0-9a-f]{64}$/); + +export const nativeHandoffRequestSchema = z.object({ + challenge: hexSha256, +}); +export type NativeHandoffRequest = z.infer; + +export const nativeHandoffResponseSchema = z.object({ + code: z.string(), +}); +export type NativeHandoffResponse = z.infer; + +export const nativeExchangeRequestSchema = z.object({ + code: z.string().min(1).max(128), + verifier: z.string().min(43).max(128), +}); +export type NativeExchangeRequest = z.infer; diff --git a/wiki/Native-Apps.md b/wiki/Native-Apps.md new file mode 100644 index 000000000..59ca199f3 --- /dev/null +++ b/wiki/Native-Apps.md @@ -0,0 +1,76 @@ +# Native Apps + +**TREK Travel Planner** is the TREK app for iPhone, iPad and Android, from the App Store and Google Play. It is a client for your TREK server: it asks for the server's address once and then shows the TREK interface that server delivers, in the version the server runs, with the same data, the same accounts and the same settings as in the browser. On the home screen it is called **TREK**. + +The browser keeps working as before, and installing TREK from the browser as a web app is still possible; see [Offline-Mode-and-PWA](Offline-Mode-and-PWA). The app adds what a browser cannot do well on a phone: signing in with single sign-on and passkeys, the system share sheet for exports, haptics, and on iOS a start without network. + +## Connecting to a server + +On first start the app shows its address screen. Enter the address you open TREK at in the browser, for example `trek.example.com` or `192.168.1.10:3001`. Without a scheme the app tries https first and then plain http. + +The app checks that the address answers as a TREK server that knows the apps, and then loads it. If it does not, it says why: + +- **No server answered**: the address is wrong, the server is down, or the phone cannot reach it (see the network section below). +- **Not TREK**: something answered, but not a TREK server. +- **Too old**: a TREK server from before the apps. Update it to a current release. + +No server yet? **Try the demo** connects to the public demo at demo.liketrek.com, which everybody shares and which is reset every hour. **What is a TREK server?** leads to the project page, which explains how to run your own. + +To switch servers later, open **Settings → Account** in the app: the **Server** card names the server and has **Change server**, which returns to the address screen. The sign-in screen has the same link at the bottom. + +## Signing in + +A password works inside the app as in the browser, and **Remember me** is on by default, so the app does not ask again after the phone closed it. + +Single sign-on and passkeys cannot run inside the app's web view: identity providers refuse embedded browsers, and a passkey belongs to your server's domain, which the app cannot be tied to for every server. So the app opens your server's sign-in in the system browser instead. Sign in there as usual, tap **Open the TREK app**, and the app continues signed in. The browser hands over a one-time code that only the app that asked for it can redeem, valid for a minute. The server records the sign-in as a login from the native app. + +Passkeys are managed in the browser for the same reason: the **Passkeys** card is hidden in the app. + +## Offline + +The app keeps the trips you choose offline the same way the browser does, including their maps; see [Offline-Mode-and-PWA](Offline-Mode-and-PWA). On iOS, where the web view runs no service worker, the app stores a copy of the server's start page and of every script of its current version, so it also starts with no network. When the server cannot be reached on start, the app opens that copy, or offers **Try again** and **Change server**. + +## Plain http, the home network and VPNs + +The app accepts plain http on purpose, because a server at home is often reached as `http://192.168.x.x:3001` or over a VPN such as Tailscale. Use https for anything reachable from the internet. iOS asks once for access to the local network; allow it, or the app cannot reach a server on your network. + +## Files and downloads + +Exports, attachments and backup codes open in the system share sheet, from where you save them to Files, open them in another app or send them on. + +## Privacy + +The app sends what you enter to your TREK server and nowhere else; the makers of TREK receive nothing. Map tiles come from the map provider your server is set up with. The privacy policy is at https://liketrek.com/privacy and is linked from the address screen and from **Settings → Account**. How to delete an account: https://liketrek.com/delete-account. + +The app hides the donation links (Ko-fi, Buy Me a Coffee) that the browser shows, because the store rules allow no outside payment links in an app. + +## For maintainers: releasing the apps + +The apps are built from `client/`: Capacitor wraps the address screen in `client/native-shell/`, and the iOS and Android projects are `client/ios/` and `client/android/`. + +- **Every pull request** that touches the native code runs `.github/workflows/native.yml`: an unsigned Android debug and release build (the release build runs R8 with `client/android/app/proguard-rules.pro`), an iOS simulator build with Xcode 26, and a check of the store texts and images. +- **A release** runs `.github/workflows/native-release.yml`, by hand (choose the Play track) or on a `v*` tag. A tag pushed by another workflow with the default token does not start it, so after a release run it by hand on the tag. It builds the signed Android App Bundle and sends it to the chosen Google Play testing track as a draft, and archives the iOS app and uploads it to App Store Connect, where it appears in TestFlight. Promoting a build to production happens in the two consoles. +- **Version numbers**: both stores get the version from `client/package.json` without a prerelease suffix, and the workflow run number plus 1000 as the build number. A prerelease reuses its version with a higher build number and stays on the internal track and in TestFlight. +- **The `store` environment** holds every secret and needs the approval of a required reviewer before a job starts. It only runs in liketrek/TREK, never for a pull request. + +### Secrets in the `store` environment + +| Secret | What | +| --- | --- | +| ANDROID_UPLOAD_KEYSTORE_B64 | The upload keystore, base64 encoded | +| ANDROID_KEYSTORE_PASSWORD, ANDROID_KEY_ALIAS, ANDROID_KEY_PASSWORD | Its password, key alias and key password | +| PLAY_SERVICE_ACCOUNT_JSON | The Google Cloud service account with "Release to testing tracks" in Play Console | +| APPLE_TEAM_ID | The Apple Developer team of [APPLE ORGANISATION ACCOUNT] | +| ASC_KEY_ID, ASC_ISSUER_ID, ASC_KEY_P8_B64 | The App Store Connect team API key (App Manager role), the .p8 file base64 encoded | + +The Play account is [GOOGLE PLAY ORGANISATION ACCOUNT], the Apple account [APPLE ORGANISATION ACCOUNT]. Google Play App Signing holds the app signing key; the upload key above only proves a build comes from us and can be reset through Play support if lost. Its offline backup lives at [KEYSTORE BACKUP LOCATION]. Never commit a keystore, a .p8 key or a service account file: `client/android/.gitignore` ignores them. + +The first Android bundle has to be uploaded by hand once (Play only accepts API uploads after that): run the release workflow, download the bundle from the run's artifacts and upload it to Internal testing in Play Console. + +### Store listings + +The listing texts, the review notes, the policy page drafts and the screenshots live in `client/fastlane/`; its `client/fastlane/README.md` explains how to make the screenshots and upload the listings. App Review gets a separate review server, [REVIEW SERVER URL], with its own accounts, because the public demo blocks account deletion and uploads; the review notes in App Store Connect name it. + +### The server side + +The app relies on two things of the server: `/api/health/features` answers `nativeApp: true` and `nativeApi` (the version of what the apps use), and `/api/auth/native` carries the sign-in hand-off. `nativeApi` is raised only for a change an older app cannot follow; the app refuses a server below the minimum it knows. Keep demo.liketrek.com on a current release for as long as the apps are in the stores, since **Try the demo** connects to it. diff --git a/wiki/_Sidebar.md b/wiki/_Sidebar.md index f6cd68af2..3707c489f 100644 --- a/wiki/_Sidebar.md +++ b/wiki/_Sidebar.md @@ -23,6 +23,7 @@ - [[Dashboard Widgets|Dashboard-Widgets]] - [[Notifications Inbox|Notifications-Inbox]] - [[TREK on a Phone|Mobile-App]] +- [[Native Apps|Native-Apps]] - [[Offline Mode and PWA|Offline-Mode-and-PWA]] - [[Languages]]