Restructure step 3: your server, Invite, version gate, AppGraph

- One server per app run (loopback, no password); Invite attaches an
  all-interfaces listener to the same server and Stop sharing detaches
  it (guests told with 4016); members, media and Up next never reset.
  No solo mode: you're home on your own server unless in a friend's.
- Navigation: none / yours / friend; a join passes a version gate on
  /health first (clear "they/you need to update", update offer).
- Invite as a value (host, port, name, password flag, version, fp
  reserved); addresses filtered (loopback, link-local, 198.18/15,
  bridges) and ranked; Sharing chip, Copy invite, Stop sharing.
- Alone looks like a plain player (alone replaces solo).
- AppGraph builds and disposes systems; widgets use AppScope;
  SessionState deleted; a test caps the remaining singletons.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
foxyzandClaude Opus 5.5 committed 2026-10-15 22:52:52 +03:00
1 parent 629be0d9ed
commit 4d00b7455e
86 files changed
+2993 -2071

No files matched your search

+28 -2
View File
@@ -17,9 +17,14 @@ import 'sync_server.dart';
/// completes once it is down. `{'t':'file','path':p,'reply':SendPort}` makes
/// a file on this machine the hosted file (the hosting app's in-session file
/// swap; a following `swap` with its name and size puts it up) and answers
/// `{'ok':true,'name':n,'size':s}` or `{'ok':false}`. Without [events] a
/// `{'ok':true,'name':n,'size':s}` or `{'ok':false}`.
/// `{'t':'share','port':p,'secret':s,'jellyfin':map?,'reply':SendPort}`
/// opens the running server to the network ([SyncServer.share]) and
/// answers `{'ok':true,'port':p}` or `{'ok':false,'message':m}`;
/// `{'t':'unshare','reply':SendPort}` closes it again
/// ([SyncServer.unshare]) and answers `{'ok':true}`. Without [events] a
/// start failure throws. `'loopbackOnly': true` in [config] (next to the
/// [AppConfig] keys) binds 127.0.0.1 only: the app's solo session;
/// [AppConfig] keys) binds 127.0.0.1 only: the hosting app's own server;
/// `'logDir'` is the folder of the session log ([SyncServer.logDir]).
Future<void> serve(Map<String, Object?> config, {SendPort? events}) async {
StreamSubscription<pkg_logging.LogRecord>? logs;
@@ -50,6 +55,27 @@ Future<void> serve(Map<String, Object?> config, {SendPort? events}) async {
await for (final msg in control) {
if (msg is! Map) continue;
if (msg['t'] == 'stop') break;
if (msg['t'] == 'share' && msg['reply'] is SendPort) {
final reply = msg['reply'] as SendPort;
try {
final port = await server.share(
port: (msg['port'] as num?)?.toInt() ?? 0,
secret: (msg['secret'] as String?) ?? '',
jellyfin: JellyfinCredential.fromMap(msg['jellyfin']));
reply.send({'ok': true, 'port': port});
} catch (e) {
reply.send({'ok': false, 'message': '$e'});
}
continue;
}
if (msg['t'] == 'unshare' && msg['reply'] is SendPort) {
final reply = msg['reply'] as SendPort;
try {
await server.unshare();
} catch (_) {}
reply.send({'ok': true});
continue;
}
if (msg['t'] == 'file' && msg['path'] is String && msg['reply'] is SendPort) {
final reply = msg['reply'] as SendPort;
try {
+21 -1
View File
@@ -487,6 +487,24 @@ class ServerHub {
changed();
}
/// The hosting app stopped sharing: every member but the host leaves
/// now (feed `leave`, reason `closed`), its socket closed with
/// [CloseCodes.closed] so its app does not reconnect. Returns how many
/// left.
int closeGuests() {
final guests = [
for (final m in engine.members.values)
if (!m.host) m.token,
];
for (final token in guests) {
final ws = sockets.remove(token);
if (ws != null) unawaited(closeWith(ws, CloseCodes.closed, 'the server stopped sharing'));
engine.applyLeave(token, reason: 'closed');
}
if (guests.isNotEmpty) changed();
return guests.length;
}
/// `bye`: [token]'s member leaves now.
void bye(String token) {
engine.applyLeave(token, reason: 'bye');
@@ -953,7 +971,9 @@ void mountSyncRoute(
return;
}
final session = hub.session;
if (session.secret.isNotEmpty && hello.secret != session.secret) {
// The hosting app's own client (its host key) needs no password: the
// password may change while it is connected ([SyncServer.share]).
if (session.secret.isNotEmpty && hello.secret != session.secret && !hub.isHostKey(hello.hostKey)) {
await refuse(const ErrorFrame(code: ErrCode.secret, message: 'wrong secret', forType: 'hello'),
CloseCodes.secret, '${cleanMemberName(hello.user.name)}: wrong secret');
return;
+3 -1
View File
@@ -56,7 +56,9 @@ class SessionMedia {
class Session {
final String id;
final String secret;
/// The server password; '' is an open server. The hosting app changes it
/// when it starts sharing ([SyncServer.share]).
String secret;
final Map<String, ViewerToken> tokens = {};
SessionMedia? media;
final _random = Random.secure();
+69 -2
View File
@@ -53,10 +53,14 @@ class SyncServer {
/// Upstream connections of the Jellyfin relay; created on first use.
HttpClient? _relayClient;
/// Listen on 127.0.0.1 only (the app's solo session), not on every
/// IPv4 interface.
/// Listen on 127.0.0.1 only (the hosting app's own server until it
/// shares it, see [share]), not on every IPv4 interface.
final bool loopbackOnly;
/// The second listener [share] attaches: every IPv4 interface, its own
/// port; null while not shared.
RelicServer? _shared;
/// The folder of the session log (`session-YYYY-MM-DD.log`, every
/// member's diagnostics and the server's records merged); null: none.
final String? logDir;
@@ -79,6 +83,9 @@ class SyncServer {
bool get isRunning => _server != null;
int get boundPort => _server?.port ?? config.port;
/// The port friends dial while shared ([share]); null otherwise.
int? get sharedPort => _shared?.port;
Session get session => sessions.getOrCreate('default', config.secret);
Future<bool> setLocalFile(String path) async {
@@ -205,8 +212,68 @@ class SyncServer {
_log.info('jellyfin relay on for server ${hub.jellyfin!.serverId}');
}
/// Opens the running server to the network: a second listener on
/// every IPv4 interface at [port] (0: a free one), the password
/// [secret] ('' : open) and the Jellyfin relay login [jellyfin]. Members
/// already in (on the first listener) stay connected; nothing restarts.
/// Shared already: the listener moves to [port] when it differs. Returns
/// the bound port; throws when it cannot bind.
Future<int> share({required int port, required String secret, JellyfinCredential? jellyfin}) async {
if (_server == null) throw StateError('the server is not running');
final was = _shared;
if (was != null && (port == 0 || port == was.port)) {
_applyShareSettings(secret, jellyfin);
await _resolveJellyfinServerId();
return was.port;
}
if (was != null) {
_shared = null;
await was.close(force: true);
}
final listener = RelicServer(() => IOAdapter.bind(InternetAddress.anyIPv4, port: port, shared: true));
try {
await listener.mountAndStart(_app.asHandler);
} catch (e) {
try {
await listener.close(force: true);
} catch (_) {}
rethrow;
}
_shared = listener;
_applyShareSettings(secret, jellyfin);
await _resolveJellyfinServerId();
if (secret.isEmpty) _log.warning('shared without a password: anyone who can reach port ${listener.port} can join');
_log.info('server "${config.name}" shared on port ${listener.port}');
return listener.port;
}
void _applyShareSettings(String secret, JellyfinCredential? jellyfin) {
session.secret = secret;
if (jellyfin != null) hub.jellyfin = jellyfin;
}
/// Closes the network listener [share] opened: everyone but the host
/// leaves ([ServerHub.closeGuests]), the password goes; the host's own
/// member, the media and Up next stay as they are.
Future<void> unshare() async {
final listener = _shared;
if (listener == null) return;
_shared = null;
final left = hub.closeGuests();
session.secret = '';
await listener.close(force: true);
_log.info('server "${config.name}" no longer shared${left == 0 ? '' : ' ($left left)'}');
}
Future<void> stop() async {
if (_server == null) return;
final shared = _shared;
_shared = null;
if (shared != null) {
try {
await shared.close(force: true);
} catch (_) {}
}
_heartbeat?.cancel();
_heartbeat = null;
_relayClient?.close(force: true);