Files
DriverVault/Phone App/lib/servers.dart
T
tajniak81andClaude Opus 5 12ec10a797 Phone App: more than one server, and a session for each
The web app can be pointed at two DriverVault stacks and switch between them in
a click. The phone had one address and one session: reaching a second garage
meant retyping the API base in Server settings and signing in again, losing the
first server's token on the way — the same act, undone, every time you switched
back.

So lib/servers.dart is the web's servers.js ported rather than reinvented, down
to the storage keys: cc_servers holds the list, cc_active_server the one being
read, cc_session_<id> the token minted by that server and no other. The two apps
describe the same thing the same way, and the upgrade path falls out of it —
cc_token, cc_user and cc_server_url are read once at boot and folded onto the
home entry, so the build carrying this signs nobody out.

Home is the address the build ships with (kDefaultApiBase, still overridable per
device from the login screen) and cannot be removed: it is what a dropped session
falls back to. Any other server is added by address, with /api appended if the
path is left off, because a server a phone can reach is internet-facing already.

The part worth reading twice is which session a rejection ends. ApiClient no
longer holds a base or a token — it pins the active server's id, base and token
at the moment a request goes out, so a 401 arriving after a switch clears the
session of the server that actually refused it rather than whichever one is
active by then. The fallback is the web's: a remote server timing out drops its
own token, the app returns to home while home is still signed in, and only when
nothing is left to fall back to does the login screen come back. Log out still
clears every server at once, since leaving the app means leaving all of them.

Switching rebuilds the shell, keyed on the active id, because record ids belong
to the server that issued them — a garage, a charging page and a settings panel
still holding the other server's rows would each have to be told to forget them
separately. The appearance prefs come across with the profile of whoever owns
the account on the server now active.

Where the picker lives is the one place the phone cannot copy the web. There is
no app rail here, so it became the first button in the Garage header, beside the
theme toggle and log out, which is that same cluster. It names the active server
once there is a choice and goes straight to adding the second when there isn't;
the eyebrow reads GARAGE · Work for the reason the rail names it — two garages
otherwise look identical. The login screen gets its own way in, because a remote
session can expire and land you there with that server still active, and a
picker reachable only from inside the app would leave nowhere to go.

One judgment call inside the sheet: saving a connected server at a new address
saves and stops, rather than falling through to the sign-in it now needs. The
token was minted by the PocketBase behind the old address and is dropped with
it, but the credentials to replace it were never asked for, so treating the save
as a login would report an empty password as the error.

The strings are copied out of Web App/web/src/i18n/ like the rest of the shared
wording. Two are not the web's: home reads "the address this app ships with"
rather than "served with this app", since the phone has no origin to be served
from, and sameOrigin has no meaning here at all and was dropped.

Biometric sign-in stays global. It was never per-server and replays its stored
credentials against whichever server is active; making it per-server is a change
of its own, and the login screen now names the server it is about to sign into.

Nothing changes on the API Server. On Android there is no origin to allow, so
the CORS list the web app has to satisfy to reach a second server doesn't enter
into it.

Verified: flutter analyze is clean and flutter test passes, 35 tests to 46. The
new ones cover the registry — a bare origin gaining its /api, a fresh install
knowing one unnamed server on the built-in address, the legacy keys landing on
home and being cleared, two servers holding their tokens apart, a rename keeping
a session where a move drops it, removing the active server falling back to a
home that is still signed in, home refusing to be removed, and a restart reading
the list, the active id and every session back.

Not verified: none of it has been run. There is no device or emulator on this
machine and no API Server to answer, so the picker, the add sheet, a real
connect, the 401 fallback and the shell rebuild on a switch exist only as code
the analyzer is happy with — the tests reach the registry, not a screen. No APK
was built. The legacy migration was exercised against mocked SharedPreferences,
which is not a phone that had the old build on it: that is the first thing to
check on a device, since the failure mode is a silent sign-out.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-23 21:47:01 +02:00

292 lines
9.6 KiB
Dart

import "dart:convert";
import "package:flutter/foundation.dart";
import "package:shared_preferences/shared_preferences.dart";
import "config.dart";
import "i18n.dart";
import "models.dart";
/// The phone can be pointed at more than one DriverVault API Server. One is the
/// "home" server — the address this build ships with, or whatever the login
/// screen's Server settings overrode it to — and any number of others are added
/// by URL, which works because an API Server a phone can reach is
/// internet-facing already.
///
/// Each server is its own PocketBase with its own users, so a session cannot be
/// carried across: every server holds its own token under its own key. Only one
/// is active at a time and the whole app reads from it, so switching swaps the
/// garage, the charging page and the settings together.
///
/// Mirrors the web app's servers.js, down to the storage keys — the same three
/// legacy ones are read once at boot so an upgrade doesn't sign anyone out or
/// forget the server they had pointed the app at.
const String kHomeServerId = "home";
/// One server the app can read from. An empty [url] means [kDefaultApiBase],
/// which only the home entry is allowed — anything else without an address is
/// unusable.
class ServerEntry {
final String id;
String name;
String url;
ServerEntry({required this.id, this.name = "", this.url = ""});
bool get isHome => id == kHomeServerId;
Map<String, dynamic> toJson() => {"id": id, "name": name, "url": url};
factory ServerEntry.fromJson(Map<String, dynamic> json) => ServerEntry(
id: json["id"].toString(),
name: (json["name"] ?? "").toString(),
url: normalizeServerUrl((json["url"] ?? "").toString()),
);
}
/// What is held for a signed-in server: PocketBase's own token and the user it
/// was minted for.
class ServerSession {
final String token;
final AuthUser? user;
const ServerSession(this.token, this.user);
}
/// A server address as typed. Trailing slashes go, and a bare origin gets
/// "/api" appended — every API Server route lives under it, so entering just
/// "https://garage.example.com" should work without the user knowing that.
String normalizeServerUrl(String url) {
final trimmed = url.trim().replaceAll(RegExp(r"/+$"), "");
if (trimmed.isEmpty) return "";
final parsed = Uri.tryParse(trimmed);
if (parsed != null &&
parsed.hasScheme &&
parsed.hasAuthority &&
(parsed.path.isEmpty || parsed.path == "/")) {
return "${parsed.scheme}://${parsed.authority}/api";
}
return trimmed;
}
class ServerRegistry extends ChangeNotifier {
static const _listKey = "cc_servers";
static const _activeKey = "cc_active_server";
static String _sessionKey(String id) => "cc_session_$id";
// Pre-multi-server keys, read once by [_migrateLegacy].
static const _legacyTokenKey = "cc_token";
static const _legacyUserKey = "cc_user";
static const _legacyServerKey = "cc_server_url";
final List<ServerEntry> list = [];
String activeId = kHomeServerId;
final Map<String, ServerSession> _sessions = {};
// Captured once in [load] so every later write is a plain call rather than an
// await: the registry is read on the way into every request, and a switch has
// to be in effect the moment it returns.
SharedPreferences? _prefs;
/// Reads the stored servers and their sessions. Call once in main() before
/// the first request; everything below is synchronous afterwards.
Future<void> load() async {
final prefs = await SharedPreferences.getInstance();
_prefs = prefs;
_migrateLegacy();
list
..clear()
..addAll(_loadList());
_sessions.clear();
for (final server in list) {
final session = _loadSession(server.id);
if (session != null) _sessions[server.id] = session;
}
final stored = prefs.getString(_activeKey);
activeId = list.any((s) => s.id == stored) ? stored! : kHomeServerId;
}
List<ServerEntry> _loadList() {
final raw = _prefs?.getString(_listKey);
final decoded = raw == null ? null : _tryDecode(raw);
final entries = <ServerEntry>[];
if (decoded is List) {
for (final item in decoded) {
if (item is Map && item["id"] != null) {
final entry = ServerEntry.fromJson(Map<String, dynamic>.from(item));
if (entry.isHome || entry.url.isNotEmpty) entries.add(entry);
}
}
}
if (!entries.any((s) => s.isHome)) {
entries.insert(0, ServerEntry(id: kHomeServerId));
}
return entries;
}
ServerSession? _loadSession(String id) {
final raw = _prefs?.getString(_sessionKey(id));
final decoded = raw == null ? null : _tryDecode(raw);
if (decoded is! Map || decoded["token"] == null) return null;
final user = decoded["user"];
return ServerSession(
decoded["token"].toString(),
user is Map ? AuthUser.fromJson(Map<String, dynamic>.from(user)) : null,
);
}
/// Carries a pre-multi-server session onto the home server. Any override the
/// user had set in the login screen's Server settings becomes home's URL, so
/// the same server keeps answering after the upgrade.
void _migrateLegacy() {
final prefs = _prefs!;
final token = prefs.getString(_legacyTokenKey);
final legacyUrl = prefs.getString(_legacyServerKey);
if (token == null && legacyUrl == null) return;
if (token != null && prefs.getString(_sessionKey(kHomeServerId)) == null) {
final rawUser = prefs.getString(_legacyUserKey);
final user = rawUser == null ? null : _tryDecode(rawUser);
prefs.setString(
_sessionKey(kHomeServerId),
jsonEncode({"token": token, "user": user is Map ? user : null}),
);
}
if (legacyUrl != null && legacyUrl.isNotEmpty && prefs.getString(_listKey) == null) {
prefs.setString(
_listKey,
jsonEncode([ServerEntry(id: kHomeServerId, url: normalizeServerUrl(legacyUrl)).toJson()]),
);
}
prefs.remove(_legacyTokenKey);
prefs.remove(_legacyUserKey);
prefs.remove(_legacyServerKey);
}
void _saveList() =>
_prefs?.setString(_listKey, jsonEncode(list.map((s) => s.toJson()).toList()));
// --- reading -------------------------------------------------------------
ServerEntry get active =>
byId(activeId) ?? (list.isNotEmpty ? list.first : ServerEntry(id: kHomeServerId));
ServerEntry? byId(String id) {
for (final server in list) {
if (server.id == id) return server;
}
return null;
}
/// The base URL requests against [server] go to.
String baseFor(ServerEntry? server) {
final url = server?.url.trim() ?? "";
return url.isEmpty ? kDefaultApiBase : url;
}
String get activeBase => baseFor(active);
ServerSession? sessionFor(String id) => _sessions[id];
ServerSession? get activeSession => _sessions[activeId];
String? get activeToken => activeSession?.token;
bool isConnected(String id) => _sessions[id] != null;
/// What to call a server in the UI: the name it was given, else the host it
/// answers on, else — for an untouched home entry — a generic label.
String displayName(ServerEntry? server) {
if (server == null) return "";
if (server.name.isNotEmpty) return server.name;
if (server.url.isEmpty) return t("servers.home");
final host = Uri.tryParse(server.url)?.host ?? "";
return host.isEmpty ? server.url : host;
}
// --- writing -------------------------------------------------------------
void setSession(String id, String token, AuthUser? user) {
_sessions[id] = ServerSession(token, user);
_prefs?.setString(
_sessionKey(id),
jsonEncode({"token": token, "user": user?.toJson()}),
);
notifyListeners();
}
void clearSession(String id) {
_sessions.remove(id);
_prefs?.remove(_sessionKey(id));
notifyListeners();
}
void clearAllSessions() {
for (final server in list) {
_sessions.remove(server.id);
_prefs?.remove(_sessionKey(server.id));
}
notifyListeners();
}
void setActive(String id) {
if (byId(id) == null || id == activeId) return;
activeId = id;
_prefs?.setString(_activeKey, id);
notifyListeners();
}
ServerEntry add({String name = "", String url = ""}) {
final server = ServerEntry(
id: "s${DateTime.now().microsecondsSinceEpoch.toRadixString(36)}",
name: name.trim(),
url: normalizeServerUrl(url),
);
list.add(server);
_saveList();
notifyListeners();
return server;
}
ServerEntry? update(String id, {String? name, String? url}) {
final server = byId(id);
if (server == null) return null;
if (name != null) server.name = name.trim();
if (url != null) {
final next = normalizeServerUrl(url);
// Moving a server to a different address invalidates the token held for
// it: it was minted by the PocketBase behind the old one.
if (next != server.url) clearSession(id);
server.url = next;
}
_saveList();
notifyListeners();
return server;
}
/// Removing a server forgets its session too. Home cannot be removed — it is
/// the address the app ships with, and there would be nothing left to fall
/// back to.
void remove(String id) {
if (id == kHomeServerId) return;
clearSession(id);
list.removeWhere((s) => s.id == id);
_saveList();
if (activeId == id) {
activeId = kHomeServerId;
_prefs?.setString(_activeKey, kHomeServerId);
}
notifyListeners();
}
static dynamic _tryDecode(String raw) {
try {
return jsonDecode(raw);
} catch (_) {
return null;
}
}
}
/// App-wide singleton (mirrors biometricAuth in biometric.dart).
final serverRegistry = ServerRegistry();