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

+3
View File
@@ -667,6 +667,9 @@ abstract class CloseCodes {
static const stale = 4014;
/// `/sync`: no frame for the silence limit; the member is `gone`.
static const silent = 4015;
/// `/sync`: the hosting app stopped sharing its server; the member has
/// left (feed `leave`, reason `closed`) and nothing reconnects.
static const closed = 4016;
/// `/sync`: the member left (`bye`, or grace over).
static const left = 1000;
}
+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);
+138
View File
@@ -0,0 +1,138 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:sync_relay_core/core.dart';
import 'package:sync_relay_server/server.dart';
import 'package:test/test.dart';
/// A bare client: the wire only.
class _Raw {
final WebSocket ws;
final msgs = <Map<String, Object?>>[];
final done = Completer<int?>();
_Raw(this.ws) {
ws.listen((m) => msgs.add(Map<String, Object?>.from(jsonDecode('$m') as Map)),
onDone: () => done.complete(ws.closeCode), onError: (_) {});
}
static Future<_Raw> join(String host, int port, String name,
{String secret = '', String hostKey = '', String client = ''}) async {
final r = _Raw(await WebSocket.connect('ws://$host:$port/sync'));
r.ws.add(jsonEncode(HelloMessage(
secret: secret, user: HelloUser(name: name), hostKey: hostKey, client: client, seq: 1)
.toJson()));
await r.next('welcome');
return r;
}
Future<Map<String, Object?>> next(String type, {bool Function(Map<String, Object?>)? where}) async {
final deadline = DateTime.now().add(const Duration(seconds: 8));
while (DateTime.now().isBefore(deadline)) {
for (final m in msgs) {
if (m['t'] == type && (where == null || where(m))) {
msgs.remove(m);
return m;
}
}
if (done.isCompleted) throw StateError('closed (${ws.closeCode}) before $type');
await Future.delayed(const Duration(milliseconds: 50));
}
fail('timed out waiting for $type');
}
}
Future<void> _poll(bool Function() cond, String what) async {
final deadline = DateTime.now().add(const Duration(seconds: 8));
while (DateTime.now().isBefore(deadline)) {
if (cond()) return;
await Future.delayed(const Duration(milliseconds: 50));
}
fail('timed out: $what');
}
/// This machine's first non-loopback IPv4 address, if it has one.
Future<InternetAddress?> _lanAddress() async {
for (final i in await NetworkInterface.list(type: InternetAddressType.IPv4)) {
for (final a in i.addresses) {
if (!a.isLoopback) return a;
}
}
return null;
}
void main() {
test('share and unshare: one hub, the host and Up next stay, guests are told', () async {
final server = SyncServer(const AppConfig(port: 0, secret: '', name: 'own', hostKey: 'HK'), loopbackOnly: true);
await server.start();
_Raw? host, guest;
try {
host = await _Raw.join('127.0.0.1', server.boundPort, 'me', hostKey: 'HK', client: 'hostclient00000000000a');
await host.next('state');
final hostId = server.hub.engine.members.values.single.id;
host.ws.add(jsonEncode({
't': 'queue',
'op': 'add',
'item': {
'media': {'name': 'a', 'size': 0, 'duration': 0, 'url': 'http://example.com/a.mp4'},
'how': 'direct',
'title': 'A',
},
}));
await _poll(() => server.hub.engine.queue.items.length == 1, 'queued');
final lan = await _lanAddress();
if (lan != null) {
await expectLater(Socket.connect(lan, server.boundPort, timeout: const Duration(seconds: 3)),
throwsA(isA<SocketException>()),
reason: 'not shared: loopback only');
}
final port = await server.share(port: 0, secret: 'pw');
expect(server.sharedPort, port);
// A guest without the password is refused; with it, joins.
await expectLater(_Raw.join('127.0.0.1', port, 'nopw'), throwsA(anything));
guest = await _Raw.join(lan?.address ?? '127.0.0.1', port, 'guest', secret: 'pw', client: 'guestclient0000000000a');
await _poll(() => server.hub.engine.members.length == 2, 'guest in');
expect(server.hub.engine.members.values.map((m) => m.id), contains(hostId));
// The host's own reconnect needs no password (its key).
expect(host.done.isCompleted, isFalse, reason: 'sharing does not touch the host');
await server.unshare();
expect(server.sharedPort, isNull);
expect(await guest.done.future.timeout(const Duration(seconds: 5)), CloseCodes.closed);
await _poll(() => server.hub.engine.members.length == 1, 'guest left');
expect(server.hub.engine.members.values.single.id, hostId, reason: 'the same member, never reconnected');
expect(server.hub.engine.queue.items, hasLength(1), reason: 'Up next stays');
expect(host.done.isCompleted, isFalse);
expect(server.session.secret, '');
final leave = await host.next('feed', where: (m) => m['action'] == 'leave');
expect(leave['reason'], 'closed');
await expectLater(Socket.connect(InternetAddress.loopbackIPv4, port, timeout: const Duration(seconds: 3)),
throwsA(isA<SocketException>()),
reason: 'the listener is gone');
// Shared again: same hub, the queue still there.
final again = await server.share(port: port, secret: '');
expect(again, port);
final g2 = await _Raw.join('127.0.0.1', port, 'guest2', client: 'guestclient0000000000b');
final st = await g2.next('state');
expect((st['queue'] as List), hasLength(1));
await g2.ws.close();
} finally {
await host?.ws.close();
await guest?.ws.close();
await server.stop();
}
});
test('the host key stands in for the password', () async {
final server = SyncServer(const AppConfig(port: 0, secret: 'pw', name: 'own', hostKey: 'HK'));
await server.start();
try {
final host = await _Raw.join('127.0.0.1', server.boundPort, 'me', hostKey: 'HK');
await host.ws.close();
await expectLater(_Raw.join('127.0.0.1', server.boundPort, 'x', hostKey: 'nope'), throwsA(anything));
} finally {
await server.stop();
}
});
}