// The pairing link the desktop shows as a QR code: `openchamber://connect?v=2` // with a base64url JSON payload. It carries the one-time secret and the ways // to reach the server — direct URLs and, when enabled, the private relay with // the host's encryption key (the E2EE trust anchor). import 'dart:convert'; const _maxPayloadLength = 16384; class PairingCandidate { final String type; // lan | tunnel | relay final String url; // direct candidates final String relayUrl; // relay candidates final String serverId; final Map? hostKey; final String? grant; final int priority; const PairingCandidate.direct({ required this.type, required this.url, this.priority = 100, }) : relayUrl = '', serverId = '', hostKey = null, grant = null; const PairingCandidate.relay({ required String this.relayUrl, required this.serverId, required Map this.hostKey, this.grant, this.priority = 100, }) : type = 'relay', url = ''; bool get isRelay => type == 'relay'; } class PairingPayload { final String pairingId; final String secret; final String? label; final String? fingerprint; final DateTime? expiresAt; final List candidates; const PairingPayload({ required this.pairingId, required this.secret, this.label, this.fingerprint, this.expiresAt, required this.candidates, }); } /// Parses a link or payload. Returns null when it is not a valid, unexpired /// pairing link. Direct candidates come before relay, each by priority, so a /// reachable LAN address is tried before the tunnel. PairingPayload? parsePairingLink(String raw) { final text = raw.trim(); if (text.isEmpty || text.length > _maxPayloadLength) return null; String? encoded; final start = text.indexOf('?'); if (start >= 0) { final head = text.substring(0, start); if (RegExp(r'^openchamber://connect/?$', caseSensitive: false) .hasMatch(head)) { for (final part in text.substring(start + 1).split('&')) { final eq = part.indexOf('='); if (eq < 0) continue; final key = part.substring(0, eq); final value = part.substring(eq + 1); if (key == 'p') encoded = value; if (key == 'v' && value != '2') return null; } } } encoded ??= text; if (encoded.length > _maxPayloadLength) return null; final Object? decoded; try { decoded = jsonDecode(utf8.decode(_base64UrlDecode(encoded))); } catch (_) { return null; } if (decoded is! Map) return null; final pairingId = decoded['pairingId']; final secret = decoded['secret']; if (decoded['v'] != 2 || pairingId is! String || secret is! String) { return null; } if (pairingId.trim().isEmpty || secret.trim().isEmpty) return null; DateTime? expiresAt; final rawExpiry = decoded['expiresAt']; if (rawExpiry is String && rawExpiry.isNotEmpty) { expiresAt = DateTime.tryParse(rawExpiry); if (expiresAt != null && !expiresAt.isAfter(DateTime.now())) return null; } final rawCandidates = decoded['candidates']; final candidates = []; if (rawCandidates is List) { for (final raw in rawCandidates) { final candidate = _candidate(raw); if (candidate != null) candidates.add(candidate); } } if (candidates.isEmpty) return null; candidates.sort((a, b) { if (a.isRelay != b.isRelay) return a.isRelay ? 1 : -1; return a.priority.compareTo(b.priority); }); final label = decoded['label']; final fingerprint = decoded['fingerprint']; return PairingPayload( pairingId: pairingId.trim(), secret: secret.trim(), label: label is String && label.trim().isNotEmpty ? label.trim() : null, fingerprint: fingerprint is String && fingerprint.trim().isNotEmpty ? fingerprint.trim() : null, expiresAt: expiresAt, candidates: candidates, ); } PairingCandidate? _candidate(Object? raw) { if (raw is! Map) return null; final priority = raw['priority'] is num ? (raw['priority'] as num).toInt() : 100; final type = raw['type']; if (type == 'lan' || type == 'tunnel') { final url = _httpUrl(raw['url']); if (url == null) return null; return PairingCandidate.direct(type: type as String, url: url, priority: priority); } if (type == 'relay') { final relayUrl = _wsUrl(raw['relayUrl']); final serverId = raw['serverId']; final key = _ecPublicJwk(raw['hostEncPubJwk']); if (relayUrl == null || serverId is! String || serverId.trim().isEmpty || key == null) { return null; } final grant = raw['grant']; return PairingCandidate.relay( relayUrl: relayUrl, serverId: serverId.trim(), hostKey: key, grant: grant is String && grant.trim().isNotEmpty ? grant.trim() : null, priority: priority, ); } return null; } String? _httpUrl(Object? raw) { if (raw is! String) return null; final uri = Uri.tryParse(raw.trim()); if (uri == null || (uri.scheme != 'http' && uri.scheme != 'https')) { return null; } if (uri.host.isEmpty) return null; return uri.removeFragment().toString().replaceAll(RegExp(r'/+$'), ''); } String? _wsUrl(Object? raw) { if (raw is! String) return null; final uri = Uri.tryParse(raw.trim()); if (uri == null || (uri.scheme != 'ws' && uri.scheme != 'wss')) return null; if (uri.host.isEmpty) return null; return uri.removeFragment().toString(); } Map? _ecPublicJwk(Object? raw) { if (raw is! Map) return null; if (raw['kty'] != 'EC' || raw['crv'] != 'P-256') return null; final x = raw['x']; final y = raw['y']; if (x is! String || y is! String || x.isEmpty || y.isEmpty) return null; return {'kty': 'EC', 'crv': 'P-256', 'x': x, 'y': y}; } List _base64UrlDecode(String value) { final padded = value.padRight((value.length + 3) ~/ 4 * 4, '='); return base64Url.decode(padded); }