feat(native): a proxy's sign-in page in the app has a way out and says what cannot work there

Behind Pangolin or authentik the app shows the proxy's sign-in page itself, and
nothing on it led back to the address screen: a failed passkey left users stuck
on every launch. A bar over that page now offers to change the server and says
that passkeys and security keys do not work there, as a web view cannot use them
for a domain the app is not tied to. It steps aside while the keyboard is up.
On iOS the page also gets the room the keyboard takes, so a button under it can
be scrolled into view. The address screen hands the bar its words in the user's
language when it connects.
This commit is contained in:
Maurice
2026-11-10 09:36:50 +01:00
parent 1454b58ea1
commit 0b3d2873c2
36 changed files with 322 additions and 3 deletions
@@ -1,11 +1,20 @@
package com.liketrek.trek;
import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.KeyboardShortcutGroup;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowInsets;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.getcapacitor.BridgeActivity;
import com.liketrek.trek.screen.TrekKeyCommands;
import com.liketrek.trek.tiles.TrekTileStore;
@@ -37,7 +46,11 @@ public class MainActivity extends BridgeActivity {
// 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, TrekServerStore.getSignInHosts(this)));
if (onServer) {
bridge.setWebViewClient(
new TrekWebViewClient(bridge, this::showAddressScreen, this::showSignInBar, TrekServerStore.getSignInHosts(this))
);
}
TrekSharedFiles.receive(this, getIntent());
// Android 15's widget picker draws the widgets live from a sample trip.
TrekWidgetUpdater.publishPreviews(this);
@@ -69,6 +82,88 @@ public class MainActivity extends BridgeActivity {
private boolean leavingServer;
private View signInBar;
/** Whether the page is a proxy's sign-in page, and whether the keyboard is up over it. */
private boolean onSignInPage;
private boolean keyboardUp;
/**
* Over a proxy's sign-in page (Pangolin, authentik, ...): the server's UI is
* not there, so nothing else would lead back to the address screen, and a
* passkey cannot work in a web view for a domain the app is not tied to.
* The bar says so and offers to change the server.
*/
private void showSignInBar(boolean show) {
runOnUiThread(() -> {
onSignInPage = show;
if (show && signInBar == null) signInBar = buildSignInBar();
updateSignInBar();
});
}
/** Out of the way while the keyboard is up: the form needs the room, and the bar is there again once it closes. */
private void updateSignInBar() {
if (signInBar != null) signInBar.setVisibility(onSignInPage && !keyboardUp ? View.VISIBLE : View.GONE);
}
private View buildSignInBar() {
float dp = getResources().getDisplayMetrics().density;
LinearLayout bar = new LinearLayout(this);
bar.setOrientation(LinearLayout.HORIZONTAL);
bar.setGravity(Gravity.CENTER_VERTICAL);
bar.setPadding(Math.round(14 * dp), Math.round(10 * dp), Math.round(8 * dp), Math.round(10 * dp));
GradientDrawable background = new GradientDrawable();
background.setColor(0xF2111827);
background.setCornerRadius(16 * dp);
bar.setBackground(background);
bar.setElevation(6 * dp);
TextView hint = new TextView(this);
hint.setText(TrekServerStore.signInHintLabel(this));
hint.setTextColor(0xFFE5E7EB);
hint.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12.5f);
bar.addView(hint, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f));
Button change = new Button(this, null, android.R.attr.borderlessButtonStyle);
change.setText(TrekServerStore.changeServerLabel(this));
change.setAllCaps(false);
change.setTextColor(0xFFFFFFFF);
change.setOnClickListener((v) -> {
TrekServerStore.setUrl(this, null);
TrekServerStore.markRestart(this);
recreate();
});
bar.addView(change, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
int margin = Math.round(12 * dp);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
Gravity.BOTTOM
);
params.setMargins(margin, 0, margin, margin);
FrameLayout root = findViewById(android.R.id.content);
root.addView(bar, params);
// Above the gesture bar, and above the keyboard while it is up.
bar.setOnApplyWindowInsetsListener((v, insets) -> {
boolean modern = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R;
int bottom = modern ? insets.getInsets(WindowInsets.Type.systemBars()).bottom : insets.getStableInsetBottom();
boolean imeVisible = modern ? insets.isVisible(WindowInsets.Type.ime()) : insets.getSystemWindowInsetBottom() > bottom * 3;
if (imeVisible != keyboardUp) {
keyboardUp = imeVisible;
updateSignInBar();
}
FrameLayout.LayoutParams p = (FrameLayout.LayoutParams) v.getLayoutParams();
if (p.bottomMargin != margin + bottom) {
p.bottomMargin = margin + bottom;
v.setLayoutParams(p);
}
return insets;
});
bar.requestApplyInsets();
return bar;
}
/**
* The server did not load: back to the address screen, which offers retry
* and change. A fresh task rather than recreate(), because this usually
@@ -24,6 +24,8 @@ final class TrekServerStore {
private static final String KEY_URL = "server_url";
private static final String KEY_PREVIOUS_URL = "previous_server_url";
private static final String KEY_SERVER_CHECK = "server_check";
private static final String KEY_LABEL_SIGN_IN_HINT = "label_sign_in_hint";
private static final String KEY_LABEL_CHANGE_SERVER = "label_change_server";
/**
* The server API this build needs (MIN_NATIVE_API in serverAddress.ts). A
@@ -76,6 +78,29 @@ final class TrekServerStore {
editor.commit();
}
/**
* The words of the bar over a proxy's sign-in page, in the user's language,
* as the address screen passed them (setServer's `labels`): the server's UI
* is not there to say them. Null keeps the English fallback.
*/
static void setLabels(Context context, String signInHint, String changeServer) {
SharedPreferences.Editor editor = prefs(context).edit();
if (signInHint != null) editor.putString(KEY_LABEL_SIGN_IN_HINT, signInHint);
if (changeServer != null) editor.putString(KEY_LABEL_CHANGE_SERVER, changeServer);
editor.commit();
}
static String signInHintLabel(Context context) {
return prefs(context).getString(
KEY_LABEL_SIGN_IN_HINT,
"Passkeys and security keys do not work on this page in the app. Sign in with a password, or let the app through your proxy."
);
}
static String changeServerLabel(Context context) {
return prefs(context).getString(KEY_LABEL_CHANGE_SERVER, "Change server");
}
/** The server an update asked to check again, until a server is set. */
static String getPreviousUrl(Context context) {
return prefs(context).getString(KEY_PREVIOUS_URL, null);
@@ -326,6 +326,10 @@ public class TrekShellPlugin extends Plugin {
return;
}
TrekServerStore.setServer(getContext(), url, signInHostsOf(call));
JSObject labels = call.getObject("labels");
if (labels != null) {
TrekServerStore.setLabels(getContext(), labels.getString("signInHint"), labels.getString("changeServer"));
}
// A TREK Cloud purchase: the code that signs the buyer in, opened once after the first page.
String welcome = call.getString("welcome");
TrekServerStore.setWelcome(getContext(), welcome != null && welcome.matches("[A-Za-z0-9_-]{43}") ? welcome : null);
@@ -12,6 +12,7 @@ import com.liketrek.trek.clientcert.TrekClientIdentity;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import java.util.function.Consumer;
/**
* Used while the WebView shows the user's server. When that server cannot be
@@ -24,13 +25,16 @@ import java.util.Set;
class TrekWebViewClient extends BridgeWebViewClient {
private final Runnable onUnreachable;
/** Told whether the page now shown is a proxy's sign-in page, for the bar with the way out. */
private final Consumer<Boolean> onSignInPage;
private final Set<String> signInHosts;
/** A page of the server has shown since launch; from then on no sign-in host is learned (SignInRedirect). */
private boolean serverShown;
TrekWebViewClient(Bridge bridge, Runnable onUnreachable, Set<String> signInHosts) {
TrekWebViewClient(Bridge bridge, Runnable onUnreachable, Consumer<Boolean> onSignInPage, Set<String> signInHosts) {
super(bridge);
this.onUnreachable = onUnreachable;
this.onSignInPage = onSignInPage;
this.signInHosts = new HashSet<>(signInHosts);
}
@@ -61,6 +65,13 @@ class TrekWebViewClient extends BridgeWebViewClient {
return super.shouldOverrideUrlLoading(view, request);
}
/** Every page the main frame shows, pushState included: is it a proxy's sign-in page? */
@Override
public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
super.doUpdateVisitedHistory(view, url, isReload);
onSignInPage.accept(url != null && isSignInHost(Uri.parse(url)));
}
/** After the server's first page, a pending welcome code opens the welcome page once (TrekServerStore.takeWelcomeUrl). */
@Override
public void onPageFinished(WebView view, String url) {
@@ -45,6 +45,7 @@ class TrekBridgeViewController: CAPBridgeViewController {
webView.navigationDelegate = proxy
}
guardBridgeMessages()
watchSignInPages()
bridge?.registerPluginInstance(TrekShellPlugin())
// WebKit's own swipe back slides away a screenshot of the whole page,
// closes no sheet and takes every drag near the edge from the UI. The UI
@@ -56,6 +57,117 @@ class TrekBridgeViewController: CAPBridgeViewController {
webView?.allowsLinkPreview = false
}
// MARK: - A proxy's sign-in page
/// Over a proxy's sign-in page (Pangolin, authentik, ...) the server's UI is
/// not there, so nothing else leads back to the address screen, and a passkey
/// cannot work in a web view for a domain the app is not tied to. A bar says
/// so and offers to change the server; the keyboard gets room on that page,
/// which TREK's own script makes everywhere else (native/keepFieldInView.ts).
private var signInBar: UIView?
private var urlObservation: NSKeyValueObservation?
private var onSignInPage = false
private var keyboardUp = false
private func watchSignInPages() {
urlObservation = webView?.observe(\.url, options: [.initial, .new]) { [weak self] webView, _ in
let signIn = TrekServerStore.isSignInHost(webView.url)
DispatchQueue.main.async { self?.signInPageChanged(signIn) }
}
let center = NotificationCenter.default
center.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
center.addObserver(self, selector: #selector(keyboardDidShow(_:)), name: UIResponder.keyboardDidShowNotification, object: nil)
center.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
private func signInPageChanged(_ signIn: Bool) {
onSignInPage = signIn
if signIn && signInBar == nil { signInBar = makeSignInBar() }
updateSignInBar()
}
/// Out of the way while the keyboard is up: the form needs the room.
private func updateSignInBar() {
signInBar?.isHidden = !(onSignInPage && !keyboardUp)
}
@objc private func keyboardWillShow() {
keyboardUp = true
updateSignInBar()
}
/// The keyboard plugin sizes the body to the visible area and resets the
/// scroll inset on every frame change, which left a foreign page with no way
/// to scroll a button under the keyboard into view. After its last change,
/// the page gets its height back and as much room below as the keyboard takes.
@objc private func keyboardDidShow(_ note: Notification) {
guard onSignInPage, let frame = note.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return }
let room = max(0, frame.height - view.safeAreaInsets.bottom)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in
guard let self, self.onSignInPage, self.keyboardUp, let webView = self.webView else { return }
webView.evaluateJavaScript("document.body.style.height = ''", completionHandler: nil)
webView.scrollView.contentInset.bottom = room
webView.scrollView.verticalScrollIndicatorInsets.bottom = room
}
}
@objc private func keyboardWillHide() {
keyboardUp = false
updateSignInBar()
guard onSignInPage, let webView else { return }
webView.scrollView.contentInset.bottom = 0
webView.scrollView.verticalScrollIndicatorInsets.bottom = 0
}
private func makeSignInBar() -> UIView {
let labels = TrekServerStore.labels
let bar = UIView()
bar.backgroundColor = UIColor(red: 17 / 255, green: 24 / 255, blue: 39 / 255, alpha: 0.95)
bar.layer.cornerRadius = 16
bar.layer.cornerCurve = .continuous
bar.translatesAutoresizingMaskIntoConstraints = false
let hint = UILabel()
hint.text = labels["signInHint"]
?? "Passkeys and security keys do not work on this page in the app. Sign in with a password, or let the app through your proxy."
hint.textColor = UIColor(white: 0.9, alpha: 1)
hint.font = .preferredFont(forTextStyle: .footnote)
hint.adjustsFontForContentSizeCategory = true
hint.numberOfLines = 0
hint.translatesAutoresizingMaskIntoConstraints = false
let change = UIButton(type: .system)
change.setTitle(labels["changeServer"] ?? "Change server", for: .normal)
change.setTitleColor(.white, for: .normal)
change.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold)
change.addTarget(self, action: #selector(changeServerFromSignIn), for: .touchUpInside)
change.translatesAutoresizingMaskIntoConstraints = false
change.setContentHuggingPriority(.required, for: .horizontal)
change.setContentCompressionResistancePriority(.required, for: .horizontal)
bar.addSubview(hint)
bar.addSubview(change)
view.addSubview(bar)
NSLayoutConstraint.activate([
bar.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 12),
bar.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -12),
bar.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -8),
hint.leadingAnchor.constraint(equalTo: bar.leadingAnchor, constant: 14),
hint.topAnchor.constraint(equalTo: bar.topAnchor, constant: 10),
hint.bottomAnchor.constraint(equalTo: bar.bottomAnchor, constant: -10),
change.leadingAnchor.constraint(equalTo: hint.trailingAnchor, constant: 8),
change.trailingAnchor.constraint(equalTo: bar.trailingAnchor, constant: -12),
change.centerYAnchor.constraint(equalTo: bar.centerYAnchor),
])
return bar
}
/// What resetServer does from the UI: forget the server, back to the address screen.
@objc private func changeServerFromSignIn() {
TrekServerStore.url = nil
view.window?.rootViewController = TrekBridgeViewController()
}
/// Kept alive here: the content controller holds it, but only for as long as it is registered.
private var messageGuard: TrekBridgeMessageGuard?
@@ -162,6 +274,16 @@ enum TrekServerStore {
private static let checkedKey = "TrekServerCheck"
private static let labelsKey = "TrekShellLabels"
/// The words of the bar over a proxy's sign-in page, in the user's language,
/// as the address screen passed them (setServer's `labels`): the server's UI
/// is not there to say them. Empty keeps the English fallback.
static var labels: [String: String] {
get { UserDefaults.standard.dictionary(forKey: labelsKey) as? [String: String] ?? [:] }
set { UserDefaults.standard.set(newValue, forKey: labelsKey) }
}
/// The server API this build needs (MIN_NATIVE_API in serverAddress.ts).
/// A server remembered under a lower value is checked once more: the first
/// launch after an update that raised it puts the address screen back up,
+2
View File
@@ -360,6 +360,8 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
return
}
TrekServerStore.url = raw
let labels = (call.getObject("labels") ?? [:]).compactMapValues { $0 as? String }
if !labels.isEmpty { TrekServerStore.labels = labels }
// After the URL: setting it clears the hosts of the server before.
let hosts = (call.getArray("signInHosts", String.self) ?? []).filter { $0.range(of: "^[A-Za-z0-9.-]+(:[0-9]+)?$", options: .regularExpression) != nil }
TrekServerStore.signInHosts = Set(hosts.map { $0.lowercased() })
+1
View File
@@ -1206,6 +1206,7 @@ async function connected(url: string, signInHosts: string[] = [], welcome?: stri
await new Promise((r) => setTimeout(r, 700));
await TrekShell.setServer({
url,
labels: { signInHint: t('native.signInBar.hint'), changeServer: t('native.changeServer') },
...(signInHosts.length ? { signInHosts } : {}),
...(welcome ? { welcome } : {}),
});
+8 -1
View File
@@ -26,8 +26,15 @@ export interface TrekShellPlugin {
* `welcome` is the one-time code of a TREK Cloud purchase: the first load
* opens the server's welcome page with it, which signs the buyer in. A build
* without this option ignores it and opens the server as usual.
* `labels` are the words of the bar the app shows over a proxy's sign-in page,
* in the user's language: the server's UI is not there to say them.
*/
setServer(options: { url: string; signInHosts?: string[]; welcome?: string }): Promise<void>;
setServer(options: {
url: string;
signInHosts?: string[];
welcome?: string;
labels?: { signInHint: string; changeServer: 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. */