# CybSin in Flutter / Dart — http + web_socket_channel + cryptography

`flutter pub add http web_socket_channel cryptography device_info_plus package_info_plus`

```dart
import 'dart:async';
import 'dart:convert';
import 'dart:io' show Platform;
import 'dart:typed_data';
import 'package:cryptography/cryptography.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:http/http.dart' as http;
import 'package:package_info_plus/package_info_plus.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

const server = 'https://cybsin.com';
const appKey = 'cs_app_REPLACE_ME';

Future<Map<String, dynamic>> deviceIdentity() async {
  final info = DeviceInfoPlugin(); final pkg = await PackageInfo.fromPlatform();
  final d = <String, dynamic>{'bundle_id': pkg.packageName, 'app_version': pkg.version, 'locale': Platform.localeName};
  if (Platform.isIOS) { final i = await info.iosInfo; d.addAll({'name': i.name, 'platform': 'ios', 'model': i.utsname.machine, 'os_version': i.systemVersion, 'vendor_id': i.identifierForVendor ?? ''}); }
  else if (Platform.isAndroid) { final a = await info.androidInfo; d.addAll({'name': '${a.manufacturer} ${a.model}', 'platform': 'android', 'model': a.model, 'os_version': a.version.release, 'android_id': a.id}); }
  else if (Platform.isMacOS) { final m = await info.macOsInfo; d.addAll({'name': m.computerName, 'platform': 'macos', 'model': m.model, 'os_version': m.osRelease, 'hostname': m.hostName}); }
  else if (Platform.isWindows) { final w = await info.windowsInfo; d.addAll({'name': w.computerName, 'platform': 'windows', 'os_version': w.displayVersion, 'hostname': w.computerName, 'os_user': w.userName}); }
  else { d.addAll({'name': Platform.localHostname, 'platform': 'linux', 'hostname': Platform.localHostname}); }
  return d;
}

class CybSinClient {
  String? token; int? deviceId;
  Future<Map<String, dynamic>> _post(String path, Map<String, dynamic> body, {bool auth = false}) async {
    final r = await http.post(Uri.parse('$server$path'), headers: {'X-App-Key': appKey, 'Content-Type': 'application/json',
        if (auth) 'Authorization': 'Bearer $token'}, body: jsonEncode(body));
    final j = r.body.isEmpty ? <String, dynamic>{} : jsonDecode(r.body) as Map<String, dynamic>;
    if (r.statusCode == 402) throw StateError('payment_required: ${j['detail']}');     // show a human message
    if (r.statusCode >= 300) throw StateError('HTTP ${r.statusCode}: $j');
    return j;
  }
  Future<void> signIn(String email, String password, {bool register = false}) async {
    final r = await _post('/api/v1/${register ? 'register' : 'login'}', {'email': email, 'password': password, 'device': await deviceIdentity()});
    token = r['token'] as String; deviceId = r['device_id'] as int?;
  }
  Future<Map<String, dynamic>> pairNew() => _post('/api/v1/pair/new', {'device_id': deviceId}, auth: true);
  Future<String> pairJoin(String code) async => (await _post('/api/v1/pair/join', {'code': code, 'device_id': deviceId}, auth: true))['session_id'] as String;

  Future<Tunnel> connect(String session, bool host, String code) async {
    final url = '${server.replaceFirst('http', 'ws')}/ws/relay/$session?token=$token&role=${host ? 'host' : 'guest'}&app_key=$appKey&device_id=${deviceId ?? 0}';
    final ch = WebSocketChannel.connect(Uri.parse(url));
    final inbox = StreamQueue(ch.stream);
    while (true) {                                                       // wait for joined
      final m = await inbox.next;
      if (m is String) { final t = jsonDecode(m); if (t['t'] == 'joined') break; if (t['t'] == 'expired' || t['code'] != null) throw StateError(m); }
    }
    return Tunnel.handshake(ch, inbox, host, code);
  }
}

class Tunnel {
  final WebSocketChannel ch; final StreamQueue inbox; final SecretKey key; final int dirMe, dirThem; final String sas;
  int _tx = 0, _rx = 0;
  static final _aead = Chacha20.poly1305Aead();
  Tunnel._(this.ch, this.inbox, this.key, this.dirMe, this.dirThem, this.sas);

  static Future<Tunnel> handshake(WebSocketChannel ch, StreamQueue inbox, bool host, String code) async {
    final x = X25519(); final kp = await x.newKeyPair(); final mine = (await kp.extractPublicKey()).bytes;
    ch.sink.add(Uint8List.fromList(mine));
    List<int>? theirs;
    while (theirs == null) { final m = await inbox.next; if (m is List<int> && m.length == 32) theirs = m; }
    final shared = await x.sharedSecretKey(keyPair: kp, remotePublicKey: SimplePublicKey(theirs, type: KeyPairType.x25519));
    final key = await Hkdf(hmac: Hmac.sha256(), outputLength: 32).deriveKey(secretKey: shared, nonce: utf8.encode(code), info: utf8.encode('cybsin-v1'));
    final hp = host ? mine : theirs, gp = host ? theirs : mine;
    final fp = (await Sha256().hash([...hp, ...gp])).bytes;
    String h(int b) => b.toRadixString(16).toUpperCase().padLeft(2, '0');
    return Tunnel._(ch, inbox, key, host ? 1 : 2, host ? 2 : 1, '${h(fp[0])}${h(fp[1])} · ${h(fp[2])}${h(fp[3])}');
  }
  List<int> _nonce(int dir, int counter) { final n = ByteData(12); n.setUint8(0, dir); n.setUint64(4, counter); return n.buffer.asUint8List(); }
  Future<void> send(List<int> plaintext) async {
    final box = await _aead.encrypt(plaintext, secretKey: key, nonce: _nonce(dirMe, _tx++));
    ch.sink.add(Uint8List.fromList([...box.cipherText, ...box.mac.bytes]));           // ciphertext||tag
  }
  /// payload bytes, or null when the peer left; throws SecretBoxAuthenticationError on failure (fatal).
  Future<List<int>?> receive() async {
    while (true) {
      final m = await inbox.next;
      if (m is String) { if (m.contains('peer_left') || m.contains('expired')) return null; continue; }
      final ct = m as List<int>; final n = _nonce(dirThem, _rx++);
      return _aead.decrypt(SecretBox(ct.sublist(0, ct.length - 16), nonce: n, mac: Mac(ct.sublist(ct.length - 16))), secretKey: key);
    }
  }
  void close() => ch.sink.close();
}

/// minimal pull-queue over a Stream
class StreamQueue { final _q = <dynamic>[]; final _waiters = <Completer<dynamic>>[];
  StreamQueue(Stream s) { s.listen((e) { if (_waiters.isNotEmpty) _waiters.removeAt(0).complete(e); else _q.add(e); },
      onDone: () { final e = '{"t":"peer_left"}'; if (_waiters.isNotEmpty) _waiters.removeAt(0).complete(e); else _q.add(e); }); }
  Future<dynamic> get next { if (_q.isNotEmpty) return Future.value(_q.removeAt(0)); final c = Completer<dynamic>(); _waiters.add(c); return c.future; }
}
```

Notes
- `cryptography` package's `Chacha20.poly1305Aead()` is the IETF variant (12-byte nonce) — matches the recipe.
- Store the token with `flutter_secure_storage`. Scan the pairing QR with `mobile_scanner`.
