// Keyfern client for Dart and Flutter: iOS, Android, macOS, Windows, Linux (not Flutter web). // One file; the only dependency is `cryptography` (pure-Dart Ed25519). // // final kf = Keyfern(product: 'prod_xxx', publicKey: '', // storage: FileStorage('${(await getApplicationSupportDirectory()).path}/keyfern.license')); // final lic = await kf.activateOrCached('ABCDE-FGHIJ-KLMNO-PQRST', await Keyfern.machineId()); // if (lic.has(5)) { ... } // // Every answer is Ed25519-signed; only answers that verify with the embedded PUBLIC key are trusted, and the // nonce must match the one we sent (no replay). With `storage` the last signed answer is kept, so the app runs // offline until `leaseUntil`; setting the clock back is detected. The cache needs no encryption: editing it // breaks the signature. import 'dart:convert'; import 'dart:io'; import 'dart:math'; import 'package:cryptography/cryptography.dart'; class KeyfernException implements Exception { final String code; final String? message; KeyfernException(this.code, [this.message]); @override String toString() => 'KeyfernException($code${message == null ? '' : ': $message'})'; } class KeyfernNetworkException implements Exception { final String message; KeyfernNetworkException(this.message); @override String toString() => 'KeyfernNetworkException($message)'; } /// Where the last signed license is kept for offline use. abstract class LicenseStorage { Future get(); Future set(String value); Future remove(); } /// A file (written atomically). In Flutter put it in getApplicationSupportDirectory() (path_provider). class FileStorage implements LicenseStorage { final String path; FileStorage(this.path); @override Future get() async { final f = File(path); return await f.exists() ? f.readAsString() : null; } @override Future set(String value) async { final tmp = File('$path.tmp'); await tmp.writeAsString(value, flush: true); await tmp.rename(path); } @override Future remove() async { final f = File(path); if (await f.exists()) await f.delete(); } } /// The verified license. [raw] holds every field of the signed payload; [signed] is {payload, sig}. class License { final Map raw; final Map signed; License(this.raw, this.signed); String get product => raw['product'] as String; String get key => raw['key'] as String; String? get machine => raw['machine'] as String?; String? get nonce => raw['nonce'] as String?; /// 'active', 'expired' or 'blocked'. String get status => raw['status'] as String; /// Server time of the answer (unix seconds). int get iat => (raw['iat'] as num).toInt(); /// Unix seconds, null = never expires. int? get expires => (raw['expires'] as num?)?.toInt(); /// Offline use is allowed until this moment (unix seconds, null = unlimited). int? get leaseUntil => (raw['lease_until'] as num?)?.toInt(); List get features => [for (final f in (raw['features'] as List? ?? const [])) (f as num).toInt()]; int get maxMachines => (raw['max_machines'] as num?)?.toInt() ?? 0; int get machinesUsed => (raw['machines_used'] as num?)?.toInt() ?? 0; String? get customerName => (raw['customer'] as Map?)?['name'] as String?; String? get customerEmail => (raw['customer'] as Map?)?['email'] as String?; Map get meta => Map.from(raw['meta'] as Map? ?? const {}); bool has(int feature) => features.contains(feature); @override String toString() => 'License($key $status features=$features expires=$expires)'; } class Keyfern { final String product; final String url; final LicenseStorage? storage; final Duration timeout; final SimplePublicKey _pub; Keyfern({required this.product, required String publicKey, String url = 'https://keyfern.com', this.storage, this.timeout = const Duration(seconds: 15)}) : url = url.replaceAll(RegExp(r'/+$'), ''), _pub = SimplePublicKey(_b64d(publicKey), type: KeyPairType.ed25519); static List _b64d(String s) => base64Url.decode(base64Url.normalize(s)); static double _now() => DateTime.now().millisecondsSinceEpoch / 1000; Future> _post(String path, Map body) async { final client = HttpClient()..connectionTimeout = timeout; int code; Map j; try { final req = await client.postUrl(Uri.parse(url + path)).timeout(timeout); req.headers.contentType = ContentType.json; req.add(utf8.encode(jsonEncode(body))); final res = await req.close().timeout(timeout); code = res.statusCode; j = jsonDecode(await res.transform(utf8.decoder).join().timeout(timeout)) as Map; } catch (e) { throw KeyfernNetworkException(e.toString()); } finally { client.close(force: true); } if (code >= 500 || code == 429) throw KeyfernNetworkException(j['message'] as String? ?? 'HTTP $code'); if (code >= 400) throw KeyfernException(j['error'] as String? ?? 'error', j['message'] as String?); return j; } /// Verify a {payload, sig} answer. Throws KeyfernException on any mismatch. Future verify(Map signed, [String? nonce]) async { List? bytes; var ok = false; try { bytes = _b64d(signed['payload']!); ok = await Ed25519().verify(bytes, signature: Signature(_b64d(signed['sig']!), publicKey: _pub)); } catch (_) {/* not valid = not trusted */} if (!ok) throw KeyfernException('bad_signature', 'License answer failed signature verification'); final p = jsonDecode(utf8.decode(bytes!)) as Map; if (p['product'] != product) throw KeyfernException('bad_signature', 'License answer is for another product'); if (nonce != null && p['nonce'] != nonce) throw KeyfernException('replay', 'License answer does not match this request'); return License(p, Map.unmodifiable(signed)); } Future _call(String path, Map extra) async { final rnd = Random.secure(); final nonce = List.generate(16, (_) => rnd.nextInt(256).toRadixString(16).padLeft(2, '0')).join(); final r = await _post(path, {'product': product, 'nonce': nonce, ...extra}); return verify({'payload': r['payload'] as String, 'sig': r['sig'] as String}, nonce); } Future _save(Map signed, String? machine, double lastSeen) => storage!.set(jsonEncode({'resp': signed, 'machine': machine, 'last_seen': lastSeen})); /// Registers this machine. Throws unless the license is active; saves it to [storage]. Future activate(String key, String machine, [String? name]) async { final lic = await _call('/v1/activate', {'key': key, 'machine': machine, 'name': name}); if (lic.status != 'active') throw KeyfernException(lic.status, 'License is ${lic.status}'); if (storage != null) await _save(lic.signed, machine, _now()); return lic; } /// Read-only info (works for expired keys too, e.g. to show a Renew button). Future validate(String key, [String? machine]) => _call('/v1/validate', {'key': key, 'machine': machine}); Future deactivate(String key, String machine) => _post('/v1/deactivate', {'product': product, 'key': key, 'machine': machine}); Future trial(String machine) => _call('/v1/trial', {'machine': machine}); /// Check a license cached earlier without the network: signature, machine, clock, expiry, lease. Future checkCached(Map signed, [String? machine, double lastSeen = 0]) async { final p = await verify(signed); final t = _now(); if (machine != null && p.machine != machine) throw KeyfernException('wrong_machine', 'Cached license belongs to another machine'); if (t < max(lastSeen, p.iat.toDouble()) - 3600) throw KeyfernException('clock_rollback', 'System clock was set back'); // 1 h tolerance if (p.expires != null && p.expires! <= t) throw KeyfernException('expired'); if (p.leaseUntil != null && p.leaseUntil! <= t) throw KeyfernException('lease_expired', 'Connect to the internet once to refresh the license'); return p; } /// The license kept in [storage], checked offline. Throws KeyfernException('no_cache') when nothing is stored. Future cached([String? machine]) async { Map? d; try { final s = await storage?.get(); d = s == null ? null : jsonDecode(s) as Map; } catch (_) {/* unreadable = none */} final r = d?['resp']; if (r is! Map || r['payload'] is! String || r['sig'] is! String) throw KeyfernException('no_cache', 'No cached license'); final signed = {'payload': r['payload'] as String, 'sig': r['sig'] as String}; final lastSeen = (d!['last_seen'] as num?)?.toDouble() ?? 0; final lic = await checkCached(signed, machine, lastSeen); await _save(signed, d['machine'] as String?, max(lastSeen, _now())); return lic; } /// Normal start-up call: online activation when possible, the cached license when offline. Future activateOrCached(String key, String machine, [String? name]) async { try { return await activate(key, machine, name); } on KeyfernNetworkException { return cached(machine); } on KeyfernException catch (e) { if (const {'blocked', 'expired', 'invalid_key', 'machine_limit'}.contains(e.code)) await storage?.remove(); rethrow; } } /// Desktop (Windows, macOS, Linux): stable hashed id of this computer, same value as the Python/JS/Kotlin SDKs. /// On iOS/Android use [installId] or your own id (identifierForVendor, ANDROID_ID). static Future machineId([String salt = 'keyfern']) async { var raw = ''; try { if (Platform.isWindows) { final o = await Process.run('reg', ['query', r'HKLM\SOFTWARE\Microsoft\Cryptography', '/v', 'MachineGuid', '/reg:64']); raw = RegExp(r'MachineGuid\s+REG_SZ\s+(\S+)').firstMatch('${o.stdout}')?.group(1) ?? ''; } else if (Platform.isMacOS) { final o = await Process.run('ioreg', ['-rd1', '-c', 'IOPlatformExpertDevice']); raw = RegExp(r'"IOPlatformUUID" = "([^"]+)"').firstMatch('${o.stdout}')?.group(1) ?? ''; } else { for (final f in ['/etc/machine-id', '/var/lib/dbus/machine-id']) { if (File(f).existsSync()) { raw = File(f).readAsStringSync().trim(); break; } } } } catch (_) {/* fall back below */} if (raw.isEmpty) raw = Platform.localHostname; final h = await Sha256().hash(utf8.encode('$salt|$raw')); return h.bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join().substring(0, 32); } /// A random id created on first use and kept in [path] (e.g. in getApplicationSupportDirectory()). static Future installId(String path) async { final f = File(path); if (await f.exists()) { final s = (await f.readAsString()).trim(); if (s.isNotEmpty) return s; } final rnd = Random.secure(); final id = List.generate(16, (_) => rnd.nextInt(256).toRadixString(16).padLeft(2, '0')).join(); await f.writeAsString(id, flush: true); return id; } }