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
@@ -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")
]
)
]