feat(native): the apps load the server's own UI

The apps ship only an address screen now. Once a server is picked, the
native side points the WebView at it: TrekBridgeViewController on iOS and a
config copy with server.url on Android. The UI then comes from that server,
in the version it runs and on its own origin, so the session cookie,
uploads, /ws and plugins work exactly as in a browser and no app release
has to keep pace with the servers out there.

The address screen (native-shell/, built into native-dist/) probes
/api/health/features through native HTTP, tries https before http when no
scheme was typed, and refuses servers without the nativeApp flag. It also
serves as the error page when the remembered server does not load: retry,
change server, or on iOS the stored copy of the server's start page.

TrekShell is the app's own plugin for all of that: remember, change and
reload the server, sign in through ASWebAuthenticationSession or a Custom
Tab, and on iOS keep and open the offline copy of the start page, because
WKWebView runs no service worker for a domain the app does not list.

Plugins the frame does not use are gone (push, camera, geolocation,
calendar, file transfer, in-app browser and more): the WebView covers the
camera and location itself, and push needs a relay before it is worth
shipping. With them go the push entitlement, the calendar usage strings
and the Firebase bits. The iOS scheme falls back to capacitor://, since
Capacitor drops an iosScheme of https, and the arm64 capability replaces
armv7.
This commit is contained in:
Maurice
2026-09-24 12:30:32 +02:00
parent 9832d12751
commit c5765bbf15
79 changed files with 1600 additions and 448 deletions
+4
View File
@@ -6,3 +6,7 @@ playwright/.cache/
# vite-plugin-pwa dev output (devOptions.enabled)
dev-dist/
# The native apps' address screen (npm run build:native), copied into
# android/ and ios/ by `cap sync`
native-dist/
+1
View File
@@ -35,6 +35,7 @@ dependencies {
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"
-12
View File
@@ -10,23 +10,11 @@ android {
apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
dependencies {
implementation project(':capacitor-app')
implementation project(':capacitor-browser')
implementation project(':capacitor-calendar')
implementation project(':capacitor-camera')
implementation project(':capacitor-file-transfer')
implementation project(':capacitor-filesystem')
implementation project(':capacitor-geolocation')
implementation project(':capacitor-haptics')
implementation project(':capacitor-inappbrowser')
implementation project(':capacitor-keyboard')
implementation project(':capacitor-local-notifications')
implementation project(':capacitor-network')
implementation project(':capacitor-preferences')
implementation project(':capacitor-push-notifications')
implementation project(':capacitor-share')
implementation project(':capacitor-splash-screen')
implementation project(':capacitor-status-bar')
implementation project(':capacitor-toast')
}
+11 -90
View File
@@ -24,16 +24,17 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!-- Deep links (@capacitor/app appUrlOpen).
<!-- Deep links.
The scheme is @string/custom_url_scheme (com.liketrek.trek).
launchMode is singleTask above, so a link delivers into the
running task via onNewIntent rather than starting a second copy
of the app on top of the first.
This is the return path for native OIDC/OAuth login: the flow
opens in a Custom Tab and the provider redirects back to
com.liketrek.trek://… , which lands here.
This is the return path for SSO and passkey sign-in: TrekShell
opens the server's login page in a Custom Tab, and after the
hand-off it redirects to com.liketrek.trek://auth?code=…, which
lands here and in TrekShellPlugin.handleOnNewIntent.
Not an App Link (autoVerify + https). App Links are verified
against a specific domain via assetlinks.json, and TREK is
@@ -59,101 +60,21 @@
android:resource="@xml/file_paths"></meta-data>
</provider>
<!-- Notification icon, shared by @capacitor/push-notifications (via this
FCM meta-data) and @capacitor/local-notifications (via the smallIcon
option in capacitor.config.ts).
It must be a white silhouette on transparency; the launcher icon is a
full-colour square and Android would render it as a white blob.
notification_icon is generated from public/icons/icon-white.svg by
scripts/generate-native-icons.mjs.
default_notification_channel_id names the channel FCM uses for any
message that does not carry its own. The channel itself still has to
be created at runtime with PushNotifications.createChannel() using
this exact id — Android drops notifications for a channel that was
never created, and FCM silently falls back to its own channel.
No default_notification_color on purpose. TREK's palette is neutral
and user-selectable, so there is no one brand colour to tint with;
left unset, Android tints the small icon with the system accent,
which stays legible in both the light and dark shade. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/notification_icon" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/default_notification_channel_id" />
<!-- Asks Play services to install the backported Android photo picker on
Android 11/12 devices, so @capacitor/camera gets the modern picker
instead of falling back to ACTION_OPEN_DOCUMENT. Disabled by design:
it is a dependency declaration, not a service that runs.
Drop this block if TREK ever ships a Play-services-free build
(F-Droid); the fallback picker keeps working without it. -->
<service
android:name="com.google.android.gms.metadata.ModuleDependencies"
android:enabled="false"
android:exported="false"
tools:ignore="MissingClass">
<intent-filter>
<action android:name="com.google.android.gms.metadata.MODULE_DEPENDENCIES" />
</intent-filter>
<meta-data android:name="photopicker_activity:0:required" android:value="" />
</service>
</application>
<!-- Permissions.
Declared here only where the app itself needs them. Plugins that ship
their own manifest contribute theirs through the merge and are NOT
repeated: @capacitor/haptics (VIBRATE), @capacitor/calendar
(READ_CALENDAR, WRITE_CALENDAR) and @capacitor/local-notifications
(RECEIVE_BOOT_COMPLETED, WAKE_LOCK, SCHEDULE_EXACT_ALARM). -->
<!-- Permissions. Only what the WebView itself needs: the file picker's
camera option and navigator.geolocation for "locate me" on the map,
both granted at runtime through Capacitor's WebChromeClient. -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Reachability: connectivity.ts probes the server on an interval, and on
native we want to skip the probe entirely when there is no transport.
@capacitor/network declares this too; kept explicit because
connectivity.ts depends on it directly. -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- Android 13+ gates notifications behind a runtime grant. firebase-messaging
and @capacitor/local-notifications declare this too, but relying on a
transitive manifest merge for a permission the app must request by hand is
a silent-failure waiting to happen — it must be requested via
requestPermissions() before register()/schedule(). -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<!-- @capacitor/geolocation. Declares no permissions of its own, so both are
required here. COARSE is listed first because it is the weaker grant and
is enough for "what city am I in" — request FINE only where the map
genuinely needs it. -->
<!-- COARSE is listed first because it is the weaker grant and is enough
for "what city am I in". -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- required="false" on purpose: TREK is a planner, and everything except
"locate me" works without GPS hardware. Marking it required would have
Play hide the app from tablets and other GPS-less devices. -->
<uses-feature android:name="android.hardware.location.gps" android:required="false" />
<!-- @capacitor/camera. Not strictly required — the plugin launches the system
camera activity, which carries its own permission — but io.ionic.libs's
inappbrowser transitively declares CAMERA anyway, and once it is declared
Android routes the plugin through the runtime-grant path. Declared here
explicitly so it is a decision rather than something inherited. -->
<uses-permission android:name="android.permission.CAMERA" />
<!-- Stripped from the merge. io.ionic.libs:ioninappbrowser-android declares
RECORD_AUDIO and MODIFY_AUDIO_SETTINGS so that pages opened in its WebView
mode can use getUserMedia for microphone capture. TREK records no audio
anywhere, and shipping these would put "Microphone" on the store listing
and in the app's permission screen for a capability that does not exist.
Revisit only if a feature genuinely needs mic input in an embedded page. -->
<uses-permission android:name="android.permission.RECORD_AUDIO" tools:node="remove" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" tools:node="remove" />
<!-- Deliberately NOT declared: READ/WRITE_EXTERNAL_STORAGE.
@capacitor/camera needs storage permissions only for saveToGallery, and
TREK uploads photos to the server rather than writing them to the device
gallery. Add them the day a feature actually needs them. -->
<uses-feature android:name="android.hardware.camera" android:required="false" />
</manifest>
@@ -1,5 +1,21 @@
package com.liketrek.trek;
import android.os.Bundle;
import com.getcapacitor.BridgeActivity;
public class MainActivity extends 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().
String server = TrekServerStore.getUrl(this);
if (server != null) {
config = TrekServerStore.configFor(this, server);
}
super.onCreate(savedInstanceState);
}
}
@@ -0,0 +1,79 @@
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 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();
}
/**
* The bundled capacitor.config.json with server.url set. Capacitor only
* takes the server URL from a config file, so this writes a copy into the
* app's private storage and loads that. Falls back to the bundled config,
* which shows the address screen, if the copy cannot be written.
*/
static CapConfig configFor(Context context, String url) {
try {
JSONObject json = new JSONObject(readAsset(context, "capacitor.config.json"));
JSONObject server = json.optJSONObject("server");
if (server == null) {
server = new JSONObject();
json.put("server", server);
}
server.put("url", url);
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 point the app at " + url, ex);
return CapConfig.loadDefault(context);
}
}
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);
}
}
@@ -0,0 +1,148 @@
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() {
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);
}
}
@@ -4,8 +4,4 @@
<string name="title_activity_main">TREK - Plan your trips!</string>
<string name="package_name">com.liketrek.trek</string>
<string name="custom_url_scheme">com.liketrek.trek</string>
<!-- Referenced by the FCM default_notification_channel_id meta-data in
AndroidManifest.xml. A channel with this exact id must also be created
at runtime via PushNotifications.createChannel(). -->
<string name="default_notification_channel_id">trek_default</string>
</resources>
-36
View File
@@ -5,45 +5,12 @@ project(':capacitor-android').projectDir = new File('../../node_modules/@capacit
include ':capacitor-app'
project(':capacitor-app').projectDir = new File('../../node_modules/@capacitor/app/android')
include ':capacitor-browser'
project(':capacitor-browser').projectDir = new File('../../node_modules/@capacitor/browser/android')
include ':capacitor-calendar'
project(':capacitor-calendar').projectDir = new File('../../node_modules/@capacitor/calendar/android')
include ':capacitor-camera'
project(':capacitor-camera').projectDir = new File('../../node_modules/@capacitor/camera/android')
include ':capacitor-file-transfer'
project(':capacitor-file-transfer').projectDir = new File('../../node_modules/@capacitor/file-transfer/android')
include ':capacitor-filesystem'
project(':capacitor-filesystem').projectDir = new File('../../node_modules/@capacitor/filesystem/android')
include ':capacitor-geolocation'
project(':capacitor-geolocation').projectDir = new File('../../node_modules/@capacitor/geolocation/android')
include ':capacitor-haptics'
project(':capacitor-haptics').projectDir = new File('../../node_modules/@capacitor/haptics/android')
include ':capacitor-inappbrowser'
project(':capacitor-inappbrowser').projectDir = new File('../../node_modules/@capacitor/inappbrowser/android')
include ':capacitor-keyboard'
project(':capacitor-keyboard').projectDir = new File('../../node_modules/@capacitor/keyboard/android')
include ':capacitor-local-notifications'
project(':capacitor-local-notifications').projectDir = new File('../../node_modules/@capacitor/local-notifications/android')
include ':capacitor-network'
project(':capacitor-network').projectDir = new File('../../node_modules/@capacitor/network/android')
include ':capacitor-preferences'
project(':capacitor-preferences').projectDir = new File('../../node_modules/@capacitor/preferences/android')
include ':capacitor-push-notifications'
project(':capacitor-push-notifications').projectDir = new File('../../node_modules/@capacitor/push-notifications/android')
include ':capacitor-share'
project(':capacitor-share').projectDir = new File('../../node_modules/@capacitor/share/android')
@@ -52,6 +19,3 @@ project(':capacitor-splash-screen').projectDir = new File('../../node_modules/@c
include ':capacitor-status-bar'
project(':capacitor-status-bar').projectDir = new File('../../node_modules/@capacitor/status-bar/android')
include ':capacitor-toast'
project(':capacitor-toast').projectDir = new File('../../node_modules/@capacitor/toast/android')
@@ -1,44 +0,0 @@
{
"_comment": [
"Template only — this file is not read by the build.",
"",
"To enable Android push notifications:",
" 1. Create a Firebase project at https://console.firebase.google.com",
" 2. Add an Android app with package name com.liketrek.trek",
" 3. Download the generated google-services.json",
" 4. Place it at client/android/app/google-services.json (gitignored)",
"",
"Without it, app/build.gradle skips the google-services plugin and the app",
"still builds and runs — PushNotifications.register() simply fails at runtime.",
"",
"The server that SENDS the notifications needs a service-account key from the",
"SAME Firebase project. See docs for the self-hosting implications."
],
"project_info": {
"project_number": "000000000000",
"project_id": "your-firebase-project-id",
"storage_bucket": "your-firebase-project-id.appspot.com"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:000000000000:android:0000000000000000000000",
"android_client_info": {
"package_name": "com.liketrek.trek"
}
},
"oauth_client": [],
"api_key": [
{
"current_key": "REPLACE_WITH_YOUR_ANDROID_API_KEY"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": []
}
}
}
],
"configuration_version": "1"
}
+3 -9
View File
@@ -1,10 +1,5 @@
ext {
// 26, not Capacitor's default 24: @capacitor/inappbrowser requires a minimum
// target of 26. This drops Android 7.0/7.1 (~1% of devices and no longer
// receiving security updates). Removing @capacitor/inappbrowser — its system-
// browser mode overlaps @capacitor/browser almost exactly — would allow 24
// again.
minSdkVersion = 26
minSdkVersion = 24
compileSdkVersion = 36
targetSdkVersion = 36
androidxActivityVersion = '1.11.0'
@@ -18,7 +13,6 @@ ext {
androidxJunitVersion = '1.3.0'
androidxEspressoCoreVersion = '3.7.0'
cordovaAndroidVersion = '14.0.1'
// Consumed by @capacitor/push-notifications. Pinned rather than left to the
// plugin's default so an FCM SDK bump is a visible, reviewable change here.
firebaseMessagingVersion = '25.0.1'
// Custom Tabs for SSO and passkey sign-in (TrekShellPlugin.authenticate).
androidxBrowserVersion = '1.8.0'
}
+17 -32
View File
@@ -1,5 +1,3 @@
/// <reference types="@capacitor/push-notifications" />
/// <reference types="@capacitor/local-notifications" />
/// <reference types="@capacitor/splash-screen" />
/// <reference types="@capacitor/keyboard" />
import type { CapacitorConfig } from '@capacitor/cli';
@@ -8,40 +6,33 @@ import { KeyboardResize } from '@capacitor/keyboard';
const config: CapacitorConfig = {
appId: 'com.liketrek.trek',
appName: 'TREK - Plan your trips!',
webDir: 'dist',
// TREK is self-hosted: the server the app talks to is whatever the user
// enters, so every request is cross-origin. Both schemes stay https so the
// webview origin is a secure context (crypto.subtle, WebAuthn, service
// workers, IndexedDB persistence all require it).
// 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',
iosScheme: 'https',
// Shown, from the app bundle, whenever the server fails to load. The page
// knows a server is remembered and offers to retry or pick another one;
// on iOS it first tries the stored offline copy of the server's start page.
errorPath: 'index.html',
},
plugins: {
PushNotifications: {
// No `badge`: TREK has no unread count the OS could keep honest, and a
// badge that only ever grows is worse than none.
presentationOptions: ['sound', 'banner', 'list'],
},
LocalNotifications: {
// Same white-on-transparent mask as FCM uses; generated by
// scripts/generate-native-icons.mjs. Without it Android falls back to the
// launcher icon and renders a white blob.
smallIcon: 'notification_icon',
presentationOptions: ['sound', 'banner', 'list'],
},
SplashScreen: {
// Matches <meta name="theme-color"> 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',
launchShowDuration: 500,
// Deliberately true. With `false` the splash stays up until JS calls
// SplashScreen.hide(), and until that call exists a failure to boot the
// bundle looks like a frozen app. Flip this to false — and drop
// launchShowDuration — in the same change that adds the hide() call once
// the React tree has mounted.
// 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',
@@ -54,13 +45,7 @@ const config: CapacitorConfig = {
// Android-only workaround: with an edge-to-edge status bar the webview
// otherwise does not resize at all when the keyboard opens.
resizeOnFullScreen: true,
// No `style`: TREK has a real appearance system, so the keyboard should
// follow the device/app theme rather than being pinned here.
},
// No StatusBar block on purpose. From Android 15 / Capacitor 8 the app is
// always edge-to-edge, so `overlaysWebView` and `backgroundColor` no longer
// do anything. The status-bar style has to follow the user's chosen scheme
// at runtime — call StatusBar.setStyle() from applyAppearance().
},
};
+6 -6
View File
@@ -30,12 +30,12 @@ export default tseslint.config(
'public',
'test-results',
'playwright-report',
// Capacitor native shells. `npx cap sync` copies the built bundle from
// dist/ into both platforms, so without these ESLint lints the minified
// output and `npm run lint` reports tens of thousands of errors that have
// nothing to do with the source. 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.
// 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/**',
@@ -17,6 +17,8 @@
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 */
@@ -33,6 +35,8 @@
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 = "<group>"; };
7A1E00022C0000000000A002 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = PrivacyInfo.xcprivacy; sourceTree = "<group>"; };
7A1E00042C0000000000A004 /* TrekBridgeViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TrekBridgeViewController.swift; sourceTree = "<group>"; };
7A1E00062C0000000000A006 /* TrekShellPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TrekShellPlugin.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -70,6 +74,8 @@
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 */,
@@ -171,6 +177,8 @@
files = (
504EC3081FED79650016851F /* AppDelegate.swift in Sources */,
9582B6832FE993A70072D4E8 /* SceneDelegate.swift in Sources */,
7A1E00052C0000000000A005 /* TrekBridgeViewController.swift in Sources */,
7A1E00072C0000000000A007 /* TrekShellPlugin.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
-15
View File
@@ -2,20 +2,5 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<!--
The Push Notifications capability. Xcode normally writes this when you tick
"Push Notifications" under Signing & Capabilities; it is committed here so a
clean checkout builds with push already enabled.
`development` is correct for debug builds and for TestFlight. Xcode's
automatic signing rewrites this to `production` when archiving for
distribution, so it does not need a second value here.
Enabling the capability in the Apple Developer portal for the App ID
com.liketrek.trek is a separate, manual step — the entitlement alone will
fail to sign until the App ID has it too.
-->
<key>aps-environment</key>
<string>development</string>
</dict>
</plist>
@@ -11,7 +11,7 @@
<!--Bridge View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="CAPBridgeViewController" customModule="Capacitor" sceneMemberID="viewController"/>
<viewController id="BYZ-38-t0r" customClass="TrekBridgeViewController" customModule="App" customModuleProvider="target" sceneMemberID="viewController"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
</scene>
+7 -21
View File
@@ -51,39 +51,25 @@
logs "Local network prohibited" instead of a useful error. -->
<key>NSLocalNetworkUsageDescription</key>
<string>TREK connects to the TREK server you choose, which is often running on your home or office network.</string>
<!-- Permission usage descriptions. iOS does not merely deny a missing one —
<!-- Permission usage descriptions. iOS does not merely deny a missing one:
it terminates the app the first time the API is touched, so every key
below is load-bearing even where the feature is optional.
@capacitor/camera -->
The WebView's file picker offers "Take Photo" and "Photo Library". -->
<key>NSCameraUsageDescription</key>
<string>TREK uses the camera so you can photograph a place, a journey entry or a booking document and add it to your trip.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>TREK needs access to your photos so you can add them to trips, places and journey entries.</string>
<!-- "Save Image" in the share sheet that exports and downloads open in. -->
<key>NSPhotoLibraryAddUsageDescription</key>
<string>TREK saves photos and exports you download from your trips back to your photo library.</string>
<!-- @capacitor/geolocation. NSLocationAlwaysAndWhenInUse is required by
Apple because the underlying ion-ios-geolocation library is capable of
background reporting; TREK never asks for it, so the user only ever sees
the when-in-use prompt. -->
<!-- navigator.geolocation in the WebView ("locate me" on the map). -->
<key>NSLocationWhenInUseUsageDescription</key>
<string>TREK uses your location to centre the map on you and to find places near you.</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>TREK uses your location to centre the map on you and to find places near you.</string>
<!-- @capacitor/calendar. iOS 17 split calendar access into full and
write-only, each with its own key; the pre-17 key stays for older
devices. Adding a trip to the device calendar needs only write-only
access, which is the weaker prompt. -->
<key>NSCalendarsWriteOnlyAccessUsageDescription</key>
<string>TREK adds your trip days and bookings to your calendar.</string>
<key>NSCalendarsFullAccessUsageDescription</key>
<string>TREK reads your calendar to show existing commitments alongside your trip, and adds trip events to it.</string>
<key>NSCalendarsUsageDescription</key>
<string>TREK adds your trip days and bookings to your calendar.</string>
<!-- Deep links (@capacitor/app appUrlOpen), matching the intent-filter in
AndroidManifest.xml and @string/custom_url_scheme there. This is the
return path for native OIDC/OAuth login, which opens in an
SFSafariViewController and redirects back to com.liketrek.trek://…
return path for SSO and passkey sign-in, which runs in an
ASWebAuthenticationSession and redirects back to com.liketrek.trek://…
Not a Universal Link: those are verified against one specific domain via
apple-app-site-association, and a self-hosted app has no single domain to
@@ -127,7 +113,7 @@
<string>Main</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
<string>arm64</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
+7 -10
View File
@@ -4,19 +4,15 @@
<dict>
<!--
Apple's required-reason API declaration. App Store Connect rejects uploads
that call these APIs without an entry here.
NSPrivacyAccessedAPICategoryFileTimestamp / C617.1 is required by
@capacitor/filesystem, which @capacitor/file-transfer depends on to resolve
a native path before it can download or upload. Capacitor's own frameworks
that call these APIs without an entry here. Capacitor's own frameworks
ship their own PrivacyInfo; this file covers the app target only.
Add to this file when adding a plugin that touches a required-reason API —
UserDefaults (CA92.1) for @capacitor/preferences, disk space (E174.1),
system boot time (35F9.1).
Add to this file when adding a plugin that touches a required-reason API,
e.g. disk space (E174.1) or system boot time (35F9.1).
-->
<key>NSPrivacyAccessedAPITypes</key>
<array>
<!-- @capacitor/filesystem, which writes exports and downloads before
they are handed to the share sheet. -->
<dict>
<key>NSPrivacyAccessedAPIType</key>
<string>NSPrivacyAccessedAPICategoryFileTimestamp</string>
@@ -25,7 +21,8 @@
<string>C617.1</string>
</array>
</dict>
<!-- @capacitor/preferences, which backs the saved server profiles. -->
<!-- TrekServerStore (TrekBridgeViewController.swift) keeps the chosen
server in UserDefaults. -->
<dict>
<key>NSPrivacyAccessedAPIType</key>
<string>NSPrivacyAccessedAPICategoryUserDefaults</string>
+1 -1
View File
@@ -8,7 +8,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
guard let windowScene = scene as? UIWindowScene else { return }
window = UIWindow(windowScene: windowScene)
window?.rootViewController = CAPBridgeViewController()
window?.rootViewController = TrekBridgeViewController()
window?.makeKeyAndVisible()
SceneDelegateProxy.shared.scene(scene, willConnectTo: session, options: connectionOptions)
@@ -0,0 +1,41 @@
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 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")
}
}
+139
View File
@@ -0,0 +1,139 @@
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) {
guard let raw = TrekServerStore.url, let url = URL(string: 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)
}
}
}
+3 -27
View File
@@ -11,25 +11,13 @@ let package = Package(
targets: ["CapApp-SPM"])
],
dependencies: [
.package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", exact: "8.5.0"),
.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: "CapacitorBrowser", path: "../../../../node_modules/@capacitor/browser"),
.package(name: "CapacitorCalendar", path: "../../../../node_modules/@capacitor/calendar"),
.package(name: "CapacitorCamera", path: "../../../../node_modules/@capacitor/camera"),
.package(name: "CapacitorFileTransfer", path: "../../../../node_modules/@capacitor/file-transfer"),
.package(name: "CapacitorFilesystem", path: "../../../../node_modules/@capacitor/filesystem"),
.package(name: "CapacitorGeolocation", path: "../../../../node_modules/@capacitor/geolocation"),
.package(name: "CapacitorHaptics", path: "../../../../node_modules/@capacitor/haptics"),
.package(name: "CapacitorInappbrowser", path: "../../../../node_modules/@capacitor/inappbrowser"),
.package(name: "CapacitorKeyboard", path: "../../../../node_modules/@capacitor/keyboard"),
.package(name: "CapacitorLocalNotifications", path: "../../../../node_modules/@capacitor/local-notifications"),
.package(name: "CapacitorNetwork", path: "../../../../node_modules/@capacitor/network"),
.package(name: "CapacitorPreferences", path: "../../../../node_modules/@capacitor/preferences"),
.package(name: "CapacitorPushNotifications", path: "../../../../node_modules/@capacitor/push-notifications"),
.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"),
.package(name: "CapacitorToast", path: "../../../../node_modules/@capacitor/toast")
.package(name: "CapacitorStatusBar", path: "../../../../node_modules/@capacitor/status-bar")
],
targets: [
.target(
@@ -38,23 +26,11 @@ let package = Package(
.product(name: "Capacitor", package: "capacitor-swift-pm"),
.product(name: "Cordova", package: "capacitor-swift-pm"),
.product(name: "CapacitorApp", package: "CapacitorApp"),
.product(name: "CapacitorBrowser", package: "CapacitorBrowser"),
.product(name: "CapacitorCalendar", package: "CapacitorCalendar"),
.product(name: "CapacitorCamera", package: "CapacitorCamera"),
.product(name: "CapacitorFileTransfer", package: "CapacitorFileTransfer"),
.product(name: "CapacitorFilesystem", package: "CapacitorFilesystem"),
.product(name: "CapacitorGeolocation", package: "CapacitorGeolocation"),
.product(name: "CapacitorHaptics", package: "CapacitorHaptics"),
.product(name: "CapacitorInappbrowser", package: "CapacitorInappbrowser"),
.product(name: "CapacitorKeyboard", package: "CapacitorKeyboard"),
.product(name: "CapacitorLocalNotifications", package: "CapacitorLocalNotifications"),
.product(name: "CapacitorNetwork", package: "CapacitorNetwork"),
.product(name: "CapacitorPreferences", package: "CapacitorPreferences"),
.product(name: "CapacitorPushNotifications", package: "CapacitorPushNotifications"),
.product(name: "CapacitorShare", package: "CapacitorShare"),
.product(name: "CapacitorSplashScreen", package: "CapacitorSplashScreen"),
.product(name: "CapacitorStatusBar", package: "CapacitorStatusBar"),
.product(name: "CapacitorToast", package: "CapacitorToast")
.product(name: "CapacitorStatusBar", package: "CapacitorStatusBar")
]
)
]
+34
View File
@@ -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<TranslationStrings>('../../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, string> = {}): string => {
const template = strings[key] ?? fallback[key] ?? key
return typeof template === 'string'
? template.replace(/\{(\w+)\}/g, (whole, name: string) => params[name] ?? whole)
: key
}
}
+14
View File
@@ -0,0 +1,14 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="color-scheme" content="dark light" />
<meta name="theme-color" content="#09090b" />
<title>TREK</title>
</head>
<body>
<main id="shell" class="shell" aria-live="polite"></main>
<script type="module" src="./main.ts"></script>
</body>
</html>
+119
View File
@@ -0,0 +1,119 @@
import { CapacitorHttp } from '@capacitor/core'
import { SplashScreen } from '@capacitor/splash-screen'
import { TrekShell } from '../src/native/trekShell'
import { probeServer, type ProbeFailure, type ProbeGet } from '../src/native/serverAddress'
import { pickLocale, translator } from './i18n'
import logoUrl from '../public/icons/icon-white.svg'
import './shell.css'
/**
* The only page the app ships itself. It asks for a server on first start and
* stands in when the remembered one cannot be reached; everything else 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
// 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 }
}
const FAILURE_KEYS: Record<ProbeFailure, string> = {
invalid: 'native.connect.errorInvalid',
unreachable: 'native.connect.errorUnreachable',
notTrek: 'native.connect.errorNotTrek',
tooOld: 'native.connect.errorTooOld',
}
function el<K extends keyof HTMLElementTagNameMap>(tag: K, props: Partial<HTMLElementTagNameMap[K]> = {}, ...children: (Node | string)[]) {
const node = Object.assign(document.createElement(tag), props)
node.append(...children)
return node
}
function header(title: string, hint: string) {
return [
el('img', { src: logoUrl, alt: '', className: 'shell-logo' }),
el('h1', { className: 'shell-title' }, title),
el('p', { className: 'shell-hint' }, hint),
]
}
function showConnect(prefill = '') {
const input = el('input', {
type: 'url',
className: 'shell-input',
placeholder: t('native.connect.placeholder'),
value: prefill,
autocapitalize: 'off',
spellcheck: false,
required: true,
})
input.setAttribute('inputmode', 'url')
input.setAttribute('autocomplete', 'url')
input.setAttribute('aria-label', t('native.connect.title'))
const error = el('p', { className: 'shell-error', role: 'alert' })
const submit = el('button', { type: 'submit', className: 'shell-button' }, t('native.connect.submit'))
const form = el('form', { className: 'shell-form', noValidate: true }, input, submit, error)
form.addEventListener('submit', async (event) => {
event.preventDefault()
error.textContent = ''
input.disabled = true
submit.disabled = true
submit.textContent = t('native.connect.checking')
const result = await probeServer(input.value, get)
if (result.ok) {
await TrekShell.setServer({ url: result.url })
return
}
error.textContent = t(FAILURE_KEYS[result.reason])
input.disabled = false
submit.disabled = false
submit.textContent = t('native.connect.submit')
input.focus()
})
root.replaceChildren(...header(t('native.connect.title'), t('native.connect.hint')), form)
}
function showUnreachable(server: string) {
const retry = el('button', { type: 'button', className: 'shell-button' }, t('native.offline.retry'))
retry.addEventListener('click', () => {
retry.disabled = true
void TrekShell.reload()
})
const change = el('button', { type: 'button', className: 'shell-link' }, t('native.changeServer'))
change.addEventListener('click', () => { void TrekShell.resetServer() })
root.replaceChildren(
...header(t('native.offline.title'), t('native.offline.hint', { server: new URL(server).host })),
el('div', { className: 'shell-form' }, retry, change),
)
}
async function start() {
const { url } = await TrekShell.getServer()
if (!url) {
showConnect()
} 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()
+90
View File
@@ -0,0 +1,90 @@
/* Mirrors the app's neutral default scheme (client/src/index.css), dark first:
this page shares the launch screen's background and must not flash. */
:root {
--bg: #09090b;
--surface: #18181b;
--edge: #27272a;
--ink: #fafafa;
--muted: #a1a1aa;
--accent: #e4e4e7;
--accent-ink: #09090b;
--danger: #f87171;
color-scheme: dark;
}
@media (prefers-color-scheme: light) {
:root {
--bg: #ffffff;
--surface: #f4f4f5;
--edge: #e4e4e7;
--ink: #111827;
--muted: #6b7280;
--accent: #111827;
--accent-ink: #ffffff;
--danger: #dc2626;
color-scheme: light;
}
.shell-logo { filter: invert(1); }
}
* { box-sizing: border-box; }
html, body {
margin: 0;
min-height: 100%;
background: var(--bg);
color: var(--ink);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
-webkit-text-size-adjust: 100%;
}
.shell {
min-height: 100vh;
min-height: 100dvh;
display: flex;
flex-direction: column;
justify-content: center;
gap: 12px;
max-width: 420px;
margin: 0 auto;
padding: calc(env(safe-area-inset-top) + 24px) 24px calc(env(safe-area-inset-bottom) + 24px);
}
.shell-logo { width: 56px; height: 56px; margin-bottom: 8px; }
.shell-title { font-size: 1.5rem; font-weight: 600; margin: 0; }
.shell-hint { color: var(--muted); margin: 0 0 12px; line-height: 1.5; overflow-wrap: anywhere; }
.shell-form { display: flex; flex-direction: column; gap: 12px; }
.shell-input {
font: inherit;
font-size: 1rem;
padding: 14px 16px;
border-radius: 12px;
border: 1px solid var(--edge);
background: var(--surface);
color: var(--ink);
outline: none;
}
.shell-input:focus { border-color: var(--accent); }
.shell-button {
font: inherit;
font-weight: 600;
padding: 14px 16px;
border: 0;
border-radius: 12px;
background: var(--accent);
color: var(--accent-ink);
}
.shell-button:disabled { opacity: 0.6; }
.shell-link {
font: inherit;
padding: 10px;
border: 0;
background: none;
color: var(--muted);
}
.shell-error { color: var(--danger); margin: 0; min-height: 1.5em; line-height: 1.5; }
+2 -12
View File
@@ -7,6 +7,8 @@
"dev": "vite",
"prebuild": "node scripts/patch-maplibre.mjs && node scripts/generate-icons.mjs",
"icons:native": "node scripts/generate-native-icons.mjs",
"build:native": "vite build --config vite.native.config.js",
"cap:sync": "npm run build:native && cap sync",
"build": "vite build",
"build:analyze": "vite build --mode analyze",
"preview": "vite preview",
@@ -34,25 +36,13 @@
"dependencies": {
"@capacitor/android": "^8.5.0",
"@capacitor/app": "^8.1.1",
"@capacitor/browser": "^8.0.4",
"@capacitor/calendar": "^1.0.1",
"@capacitor/camera": "^8.2.3",
"@capacitor/core": "^8.5.0",
"@capacitor/file-transfer": "^2.0.5",
"@capacitor/filesystem": "^8.1.3",
"@capacitor/geolocation": "^8.2.2",
"@capacitor/haptics": "^8.0.2",
"@capacitor/inappbrowser": "^4.0.3",
"@capacitor/ios": "^8.5.0",
"@capacitor/keyboard": "^8.0.5",
"@capacitor/local-notifications": "^8.3.1",
"@capacitor/network": "^8.0.1",
"@capacitor/preferences": "^8.0.1",
"@capacitor/push-notifications": "^8.1.2",
"@capacitor/share": "^8.0.1",
"@capacitor/splash-screen": "^8.0.2",
"@capacitor/status-bar": "^8.0.3",
"@capacitor/toast": "^8.0.1",
"@fontsource/bebas-neue": "^5.3.0",
"@fontsource/eb-garamond": "^5.3.0",
"@fontsource/geist-sans": "^5.2.5",
+73
View File
@@ -0,0 +1,73 @@
import { describe, it, expect, vi } from 'vitest'
import { candidateUrls, 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 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: '<html>', 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()
})
})
+78
View File
@@ -0,0 +1,78 @@
/**
* 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'
export 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<ProbeResponse>
const FEATURES_PATH = '/api/health/features'
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<string, unknown> {
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) {
// 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<ProbeFailure, number> = { invalid: 0, unreachable: 1, notTrek: 2, tooOld: 3 }
export async function probeServer(input: string, get: ProbeGet): Promise<ProbeResult> {
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 }
}
+36
View File
@@ -0,0 +1,36 @@
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<void>
/** Forgets the server and returns to the address screen. */
resetServer(): Promise<void>
/** Loads the remembered server again, after it could not be reached. */
reload(): Promise<void>
/**
* 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<TrekShellPlugin>('TrekShell')
export const APP_URL_SCHEME = 'com.liketrek.trek'
+1 -1
View File
@@ -26,5 +26,5 @@
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true
},
"include": ["src", "tests"]
"include": ["src", "tests", "native-shell"]
}
+16
View File
@@ -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'],
},
})