# Source excerpts referenced by the findings, taken from the cloned HEAD d955d0ec7d46b11332a12de41937320490fde8bd # and the pinned protocol b9246900205cf822739965e87cf601f6af3bdffb. Line numbers are those of HEAD. === lib/core/singlink_service.dart:96-101 (git show HEAD:lib/core/singlink_service.dart) 96 @override 97 Future start({required String link, required String listen}) => 98 _op(() { 99 final cfg = jsonEncode({'link': link, 'listen': listen}); 100 return _json((b) => b.start(cfg)); 101 }); === core/ffi/main.go:97-113 (git show HEAD:core/ffi/main.go) 97 //export SingLinkStart 98 func SingLinkStart(config *C.char) (res *C.char) { 99 defer guard(&res) 100 var cfg struct { 101 Link string `json:"link"` 102 Listen string `json:"listen"` 103 Auth bool `json:"auth"` 104 } 105 if err := json.Unmarshal([]byte(C.GoString(config)), &cfg); err != nil { 106 return fail(err) 107 } 108 if err := eng.Start(cfg.Link, cfg.Listen, engine.Options{Auth: cfg.Auth}); err != nil { 109 return fail(err) 110 } 111 user, pass := eng.Credentials() 112 return out(map[string]any{"ok": true, "username": user, "password": pass}) 113 } === singlink-protocol@b924690 engine/engine.go:50-58 50 // Options tunes Start. 51 type Options struct { 52 // Auth requires a random SOCKS5 username/password (returned by 53 // Credentials) so other local users and apps cannot use the tunnel. 54 // Leave it off when the port is used as the system proxy, since many 55 // applications do not support SOCKS5 authentication. 56 Auth bool 57 } 58 === singlink-protocol@b924690 socks5/socks5.go:30-40 30 31 // Server accepts SOCKS5 clients. 32 type Server struct { 33 Client *singlink.Client 34 // Username and Password, if set, require RFC 1929 authentication so 35 // other local users and apps cannot borrow the tunnel. 36 Username, Password string 37 // MaxSessions caps concurrent client connections (default 512). 38 MaxSessions int 39 40 mu sync.Mutex === core/ffi/main.go:145-191 (git show HEAD:core/ffi/main.go) 145 // SingLinkTunStart relays all device traffic arriving on a TUN file 146 // descriptor from the OS VPN API through the node in config: 147 // 148 // {"link":"singlink://...","mtu":1500,"dns":"1.1.1.1:53","appleHeader":false} 149 // 150 // appleHeader must be true for the utun descriptor of an Apple Network 151 // Extension. 152 // 153 // Descriptor ownership does not depend on the result: the core never takes 154 // fd. It works on its own close-on-exec duplicate, which it always consumes: 155 // closed before returning on any failure (bad config, busy engine, node 156 // unreachable, handshake failure, a Stop that cancelled the start before or 157 // after the tunnel took the duplicate), otherwise closed by SingLinkTunStop / 158 // SingLinkStop or when the TUN fails. The caller keeps fd and closes it 159 // exactly once after this call has returned, whatever it returned (Android: 160 // the bridge's detached descriptor; Apple: the extension's utun, owned by 161 // the Network Extension). The caller must not close fd while the call is in 162 // progress: the number could be reused before the duplicate is made. 163 // 164 //export SingLinkTunStart 165 func SingLinkTunStart(fd C.int, config *C.char) (res *C.char) { 166 defer guard(&res) 167 var cfg struct { 168 Link string `json:"link"` 169 MTU int `json:"mtu"` 170 DNS string `json:"dns"` 171 AppleHeader bool `json:"appleHeader"` 172 } 173 if err := json.Unmarshal([]byte(C.GoString(config)), &cfg); err != nil { 174 return fail(err) 175 } 176 dev, err := tunnel.DupFDDevice(int(fd), cfg.AppleHeader) 177 if err != nil { 178 return fail(fmt.Errorf("cannot duplicate the TUN descriptor: %w", err)) 179 } 180 if err := startTun(&eng, dev, cfg.Link, tunnel.Config{MTU: cfg.MTU, DNSUpstream: cfg.DNS}); err != nil { 181 return fail(err) 182 } 183 return out(map[string]any{"ok": true}) 184 } 185 186 //export SingLinkTunStop 187 func SingLinkTunStop() (res *C.char) { 188 defer guard(&res) 189 eng.Stop() 190 return out(map[string]any{"ok": true}) 191 } === core/ffi/tunstart.go:33-81 (git show HEAD:core/ffi/tunstart.go) 33 func startTun(e *engine.Engine, dev tunnel.Device, link string, cfg tunnel.Config) error { 34 // handedOff becomes true only when the cleanup that closes dev is 35 // returned to the engine, which then runs it on every later failure 36 // (engine.finish) or stop. Until then this function owns dev, or the 37 // tunnel t that took it. 38 var t *tunnel.Tunnel 39 handedOff := false 40 defer func() { 41 if handedOff { 42 return 43 } 44 if t != nil { 45 t.Close() // closes dev once 46 } else { 47 dev.Close() 48 } 49 }() 50 return e.StartWith(link, "tun", func(c *singlink.Client) (func(), error) { 51 cfg.Client = c 52 started, err := tunnel.Start(dev, cfg) 53 if err != nil { 54 return nil, err // tunnel.Start does not close dev; the defer does 55 } 56 t = started 57 cleanup := func() { 58 tunMu.Lock() 59 if curTun == started { 60 curTun = nil 61 } 62 tunMu.Unlock() 63 started.Close() 64 } 65 tunMu.Lock() 66 curTun = started 67 tunMu.Unlock() 68 // If the OS tears this TUN down, stop the engine as well (but never 69 // a newer session started after this one). This also clears the 70 // engine's pending start if a panic unwinds through here. 71 go func() { 72 <-started.Done() 73 e.StopClient(c) 74 }() 75 if testHookTunAcquired != nil { 76 testHookTunAcquired() 77 } 78 handedOff = true 79 return cleanup, nil 80 }) 81 } === core/tunnel/fd.go:31-58 (git show HEAD:core/tunnel/fd.go) 31 // NewFDDevice returns a Device that takes ownership of fd: closing the 32 // Device closes fd. Set appleHeader on macOS/iOS utun. 33 func NewFDDevice(fd int, appleHeader bool) Device { 34 syscall.SetNonblock(fd, true) 35 return &fdDevice{f: os.NewFile(uintptr(fd), "tun"), afHdr: appleHeader} 36 } 37 38 // DupFDDevice returns a Device over a close-on-exec duplicate of fd and 39 // never takes fd itself: the caller still owns fd and must close it, and 40 // closing the Device closes only the duplicate. On error nothing was 41 // duplicated and there is nothing to close. 42 // 43 // This is the ownership contract of SingLinkTunStart: whatever the start 44 // result, the core consumes exactly its own duplicate and the OS VPN layer 45 // closes exactly its original, so a failed or cancelled start can never 46 // make both sides close the same descriptor number. 47 func DupFDDevice(fd int, appleHeader bool) (Device, error) { 48 if fd < 0 { 49 return nil, syscall.EBADF 50 } 51 // F_DUPFD_CLOEXEC duplicates and marks close-on-exec atomically, so no 52 // child forked meanwhile (by Go, Java or native code) inherits it. 53 dup, err := unix.FcntlInt(uintptr(fd), unix.F_DUPFD_CLOEXEC, 0) 54 if err != nil { 55 return nil, err 56 } 57 return NewFDDevice(dup, appleHeader), nil 58 } === core/ffi/tunstart_test.go:339-357 (git show HEAD:core/ffi/tunstart_test.go) 339 // FFI-level contract with real descriptors: dup, start, cancel after the 340 // tunnel took the duplicate. Exactly the duplicate is closed by the core; 341 // the caller's descriptor stays valid for its single close. 342 func TestTunStartRealFDCancelAfterAcquisition(t *testing.T) { 343 link := syntheticLink(t) 344 p := newPipeFD(t) 345 ino := inode(t, p.r) 346 var e engine.Engine 347 setHook(t, func() { e.Stop() }) 348 dev, err := tunnel.DupFDDevice(p.r, false) 349 if err != nil { 350 t.Fatal(err) 351 } 352 if err := startTun(&e, dev, link, tunnel.Config{}); !errors.Is(err, context.Canceled) { 353 t.Fatalf("err = %v, want context.Canceled", err) 354 } 355 checkOnlyDuplicateClosed(t, p, ino) 356 } 357 === android/app/src/main/kotlin/com/singlinklabs/singlinkvpn/VpnBridge.kt:45-96 (git show HEAD:android/app/src/main/kotlin/com/singlinklabs/singlinkvpn/VpnBridge.kt) 45 fun establishDone(fd: Int, generation: Long) { 46 if (!isPending(generation)) { 47 try { ParcelFileDescriptor.adoptFd(fd).close() } catch (_: Exception) {} 48 return 49 } 50 handedOut = true 51 heldFds.add(fd) 52 pendingEstablish?.success(fd) 53 pendingEstablish = null 54 } 55 56 /** 57 * Descriptors handed to Dart and not closed yet. The bridge always owns 58 * them: SingLinkTunStart works on its own duplicate and never closes 59 * these, whatever its result. Dart releases each one exactly once, after 60 * the core call returned (or when the start was abandoned before it), so 61 * this is the only place they are closed, and only once. 62 */ 63 private val heldFds = mutableSetOf() 64 65 /** Closes [fd] if this bridge handed it out and has not closed it yet. */ 66 fun release(fd: Int) { 67 if (fd < 0 || !heldFds.remove(fd)) return 68 try { 69 ParcelFileDescriptor.adoptFd(fd).close() 70 } catch (_: Exception) { 71 } 72 } 73 74 fun establishFailed(code: String, message: String) { 75 pendingEstablish?.error(code, message, null) 76 pendingEstablish = null 77 } 78 79 /** 80 * Stops the service. It never closes a descriptor: one Dart still holds 81 * may be on its way into SingLinkTunStart (closing it now could let the 82 * number be reused before the core duplicates it); Dart releases it once 83 * that call has returned. 84 */ 85 fun stop() { 86 epoch += 1 87 handedOut = false 88 establishFailed("stopped", "VPN stopped") 89 service?.shutdown() 90 } 91 92 /** onRevoke: the core still holds its duplicate; Dart stops it. */ 93 fun revoked() { 94 handedOut = false 95 main.post { channel?.invokeMethod("revoked", null) } 96 } === android/app/src/main/kotlin/com/singlinklabs/singlinkvpn/SingLinkVpnService.kt:53-107 (git show HEAD:android/app/src/main/kotlin/com/singlinklabs/singlinkvpn/SingLinkVpnService.kt) 53 override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { 54 if (intent?.action != ACTION_CONNECT) { 55 // Started by the system (for example always-on VPN) without the 56 // app: there is no session to resume, so do not stay around. 57 stopSelf() 58 return START_NOT_STICKY 59 } 60 val generation = intent.getLongExtra("generation", -1) 61 // Started with startForegroundService: Android requires startForeground 62 // even for a start that is already obsolete, or it kills the app. 63 val foreground = try { goForeground(); null } catch (e: Exception) { e } 64 if (!VpnBridge.isPending(generation)) { 65 if (!VpnBridge.hasSession()) { 66 stopForeground(STOP_FOREGROUND_REMOVE) 67 stopSelf(startId) 68 } 69 return START_NOT_STICKY 70 } 71 if (foreground != null) { 72 val e = foreground 73 VpnBridge.establishFailed("foreground", e.message ?: e.toString()) 74 stopSelf() 75 return START_NOT_STICKY 76 } 77 try { 78 val fd = establishTun(VpnBridge.pendingMtu) 79 VpnBridge.establishDone(fd, generation) 80 } catch (e: Exception) { 81 VpnBridge.establishFailed("establish", e.message ?: e.toString()) 82 shutdown() 83 } 84 return START_NOT_STICKY 85 } 86 87 /** Builds the interface and returns its detached descriptor. */ 88 private fun establishTun(mtu: Int): Int { 89 val builder = Builder() 90 .setSession(SESSION) 91 .setMtu(mtu) 92 .addAddress(ADDRESS_V4, PREFIX_V4) 93 .addAddress(ADDRESS_V6, PREFIX_V6) 94 .addRoute("0.0.0.0", 0) 95 .addRoute("::", 0) 96 .addDnsServer(DNS_SERVER) 97 // The core's own sockets (to the node) must not loop back into 98 // the tunnel. 99 .addDisallowedApplication(packageName) 100 .setConfigureIntent(openAppIntent()) 101 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) builder.setMetered(false) 102 val pfd = builder.establish() 103 ?: throw IllegalStateException("VPN permission was not granted") 104 // The raw descriptor now belongs to VpnBridge, which closes it exactly 105 // once (the core only ever closes its own duplicate). 106 return pfd.detachFd() 107 } === lib/platform/android.dart:204-260 (git show HEAD:lib/platform/android.dart) 204 final granted = await channel.invokeMethod('prepare') ?? false; 205 if (!_current(generation)) return cancelled; 206 if (!granted) return const OpResult(false, vpnPermissionDenied); 207 final fd = await channel.invokeMethod('establish', {'mtu': mtu}); 208 if (!_current(generation)) { 209 // A stop landed after Kotlin handed over the descriptor: the core 210 // never saw it, so close it here or the VPN interface stays up. 211 if (fd != null && fd >= 0) await _releaseFd(fd); 212 return cancelled; 213 } 214 if (fd == null || fd < 0) { 215 await _stopService(); 216 return const OpResult(false, 'cannot establish the VPN interface'); 217 } 218 _owner = generation; 219 final cfg = jsonEncode({ 220 'link': link, 221 'mtu': mtu, 222 'dns': dnsUpstream, 223 'appleHeader': false, 224 }); 225 OpResult res; 226 var threw = false; 227 try { 228 res = OpResult.fromJson(await _json(() => calls.tunStart(fd, cfg))); 229 } catch (_) { 230 threw = true; 231 res = const OpResult(false, 'The native tunnel could not start.'); 232 } finally { 233 // The core call has returned (or never ran): it only ever used its 234 // own duplicate, so the bridge's original is closed now, exactly 235 // once, on success, failure and cancellation alike. A running 236 // session keeps the interface up through the core's duplicate. 237 await _releaseFd(fd); 238 } 239 if (threw) { 240 // The reply was lost, so the core may have started after all: stop 241 // it (a no-op when nothing runs) so it closes its duplicate. 242 try { 243 await calls.tunStop(); 244 } catch (_) {} 245 } 246 if (!_current(generation)) { 247 if (_owner == generation) { 248 // The core closes its duplicate on stop (a failed start already 249 // closed it). 250 if (res.ok) await calls.tunStop(); 251 await _stopService(); 252 _owner = null; 253 } 254 return cancelled; 255 } 256 if (!res.ok) { 257 await _stopService(); 258 return res; 259 } 260 _active = true; === core/tunnel/dns.go:23-63 (git show HEAD:core/tunnel/dns.go) 23 // slots bounds the queries in flight across every DNS flow of the 24 // tunnel; a query arriving when it is full gets SERVFAIL at once. 25 slots chan struct{} 26 } 27 28 const maxIdleDNS = 4 29 30 // maxOutstandingDNS caps concurrent upstream DNS queries per tunnel (each 31 // one holds a goroutine and possibly a SingLink connection for up to ~18 s). 32 // Ordinary devices stay far below it; a flood beyond it is answered locally. 33 var maxOutstandingDNS = 64 34 35 func newDNSClient(t *Tunnel) *dnsClient { 36 return &dnsClient{t: t, slots: make(chan struct{}, maxOutstandingDNS)} 37 } 38 39 func (d *dnsClient) serve(local *gonet.UDPConn) { 40 buf := make([]byte, 4096) 41 for { 42 local.SetReadDeadline(time.Now().Add(30 * time.Second)) 43 n, from, err := local.ReadFrom(buf) 44 if err != nil { 45 return 46 } 47 select { 48 case d.slots <- struct{}{}: 49 default: 50 if n >= 3 { // has an ID and flags to answer 51 local.WriteTo(servfail(buf[:n]), from) 52 } 53 continue 54 } 55 q := append([]byte(nil), buf[:n]...) 56 go func() { 57 defer func() { <-d.slots }() 58 if resp, err := d.query(q); err == nil { 59 local.WriteTo(resp, from) 60 } 61 }() 62 } 63 } === lib/models/profile.dart:141-153 (git show HEAD:lib/models/profile.dart) 141 final _idRandom = Random.secure(); 142 143 /// A new profile ID: 128 random bits from the platform CSPRNG as 32 lowercase 144 /// hex digits. Unlike the earlier timestamp IDs it reveals nothing about when 145 /// a profile was added and cannot collide for profiles created together. 146 /// IDs already stored (including legacy timestamp IDs) are kept unchanged. 147 String newProfileId() { 148 final b = StringBuffer(); 149 for (var i = 0; i < 16; i++) { 150 b.write(_idRandom.nextInt(256).toRadixString(16).padLeft(2, '0')); 151 } 152 return b.toString(); 153 } === lib/core/singlink_bindings.dart:171-207 (git show HEAD:lib/core/singlink_bindings.dart) 171 /// Only 1 exists in release builds: a release app loads exclusively the core 172 /// packaged with it, never a library named by the environment, the working 173 /// directory or a parent folder (A-H02). [developmentFallbacks] defaults to 174 /// true only in debug/profile builds and tests. 175 List singLinkLibCandidates({ 176 String? executable, 177 Map? environment, 178 String? workingDirectory, 179 bool developmentFallbacks = !isReleaseBuild, 180 }) { 181 final sep = Platform.pathSeparator; 182 final exe = File(executable ?? Platform.resolvedExecutable).absolute; 183 final env = environment ?? Platform.environment; 184 final cwd = workingDirectory ?? Directory.current.path; 185 if (Platform.isAndroid) return [libFileName]; 186 if (Platform.isIOS) return [processLibrary]; 187 final name = libFileName; 188 // The app's own core build (with TUN support) first, then the protocol 189 // repo's plain build. 190 final platformDir = Platform.isWindows ? 'windows' : 'macos'; 191 final appRel = 'core${sep}build$sep$platformDir$sep$name'; 192 final rel = 'singlink-protocol${sep}build$sep$name'; 193 final out = []; 194 195 void add(String p) { 196 final norm = File(p).absolute.uri.normalizePath().toFilePath(); 197 if (!out.contains(norm)) out.add(norm); 198 } 199 200 // .../X.app/Contents/MacOS/exe -> .../X.app/Contents/Frameworks/lib 201 if (Platform.isMacOS) { 202 add('${exe.parent.parent.path}${sep}Frameworks$sep$name'); 203 } else { 204 add('${exe.parent.path}$sep$name'); 205 } 206 207 if (!developmentFallbacks) return out; === ios/Runner/SingLinkVpnPlugin.swift:194-247 (git show HEAD:ios/Runner/SingLinkVpnPlugin.swift) 194 static func stopAction(for status: NEVPNStatus) -> StopAction { 195 switch status { 196 case .connected, .connecting, .reasserting: return .requestStop 197 case .disconnecting: return .waitOnly 198 case .disconnected, .invalid: return .none 199 @unknown default: return .requestStop 200 } 201 } 202 203 /// Only an observed disconnected/invalid status counts as stopped. 204 static func isStopped(_ status: NEVPNStatus) -> Bool { 205 status == .disconnected || status == .invalid 206 } 207 208 /// nil when [final] (the last status seen, nil on timeout) shows the 209 /// tunnel down, else the error to report. 210 static func stopError(final: NEVPNStatus?) -> String? { 211 guard let final else { return "timeout while stopping the VPN" } 212 return isStopped(final) ? nil : "the VPN did not stop (\(name(final)))" 213 } 214 215 /// Stops [m]'s tunnel and calls [then] with nil only once iOS reports it 216 /// disconnected (or invalid); a timeout is reported, never treated as 217 /// success (A-H06). 218 private func stopIfActive(_ m: NETunnelProviderManager, _ then: @escaping (String?) -> Void) { 219 switch Self.stopAction(for: m.connection.status) { 220 case .none: 221 then(nil) 222 case .requestStop, .waitOnly: 223 userStopped = true 224 if Self.stopAction(for: m.connection.status) == .requestStop { 225 m.connection.stopVPNTunnel() 226 } 227 waitForStatus(m.connection, timeout: Self.stopTimeout, until: { s, _ in 228 Self.isStopped(s) 229 }) { final in then(Self.stopError(final: final)) } 230 } 231 } 232 233 private func stop(_ reply: @escaping (String) -> Void) { 234 generation &+= 1 235 let operation = generation 236 loadManager { m, error in 237 guard operation == self.generation else { return reply(Self.cancelled) } 238 // A manager that could not be loaded may still be running a tunnel: 239 // report the failure instead of claiming it stopped. 240 if let error { return reply(Self.fail(error)) } 241 guard let m else { return reply(Self.json(["ok": true])) } 242 self.stopIfActive(m) { stopError in 243 if let stopError { return reply(Self.json(["ok": false, "error": stopError])) } 244 reply(Self.json(["ok": true])) 245 } 246 } 247 } === ios/Runner/SingLinkVpnPlugin.swift:106-116 (git show HEAD:ios/Runner/SingLinkVpnPlugin.swift) 106 let previous = m.protocolConfiguration as? NETunnelProviderProtocol 107 let migratedOrphan = (previous?.providerConfiguration?["migratedLegacy"] as? Bool == true) 108 ? previous?.providerConfiguration?["secretRef"] as? String : nil 109 let proto = NETunnelProviderProtocol() 110 proto.providerBundleIdentifier = Self.tunnelBundleId 111 proto.serverAddress = "SingLinkVPN" 112 proto.providerConfiguration = ["secretRef": reference] 113 proto.disconnectOnSleep = false 114 m.protocolConfiguration = proto 115 m.localizedDescription = "SingLinkVPN" 116 m.isEnabled = true === ios/PacketTunnel/PacketTunnelProvider.swift:47-57 (git show HEAD:ios/PacketTunnel/PacketTunnelProvider.swift) 47 override func startTunnel( 48 options: [String: NSObject]?, 49 completionHandler: @escaping (Error?) -> Void 50 ) { 51 SharedState.setLastError(nil) 52 let operation = beginSession(stopping: false) 53 let fail = { (message: String) in 54 os_log("start failed: %{public}@", log: log, type: .error, message) 55 SharedState.setLastError(message) 56 completionHandler(TunnelError(message)) 57 } === ios/PacketTunnel/PacketTunnelProvider.swift:120-132 (git show HEAD:ios/PacketTunnel/PacketTunnelProvider.swift) 120 override func stopTunnel( 121 with reason: NEProviderStopReason, 122 completionHandler: @escaping () -> Void 123 ) { 124 os_log("stop, reason %ld", log: log, type: .info, reason.rawValue) 125 let operation = beginSession(stopping: true) 126 watchdog?.cancel() 127 watchdog = nil 128 coreQueue.async { 129 if self.ownsGeneration(operation) { _ = Core.tunStop() } 130 completionHandler() 131 } 132 } === ios/PacketTunnel/PacketTunnelProvider.swift:170-211 (git show HEAD:ios/PacketTunnel/PacketTunnelProvider.swift) 170 private func startWatchdog(operation: UInt64) { 171 let timer = DispatchSource.makeTimerSource(queue: coreQueue) 172 timer.schedule(deadline: .now() + 5, repeating: 5) 173 timer.setEventHandler { [weak self] in 174 guard let self, self.isCurrent(operation) else { return } 175 let status = Core.decode(Core.statusRaw()) 176 if status["running"] as? Bool == false { 177 let reason = (status["lastError"] as? String).flatMap { $0.isEmpty ? nil : $0 } 178 ?? "the tunnel stopped" 179 os_log("core stopped: %{public}@", log: log, type: .error, reason) 180 SharedState.setLastError(reason) 181 self.watchdog?.cancel() 182 self.watchdog = nil 183 self.cancelTunnelWithError(TunnelError(reason)) 184 } 185 } 186 watchdog?.cancel() 187 watchdog = timer 188 timer.resume() 189 } 190 191 // MARK: - Network settings 192 193 static func networkSettings(remote: String) -> NEPacketTunnelNetworkSettings { 194 let settings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: remote) 195 196 let v4 = NEIPv4Settings(addresses: ["172.19.0.1"], subnetMasks: ["255.255.255.252"]) 197 v4.includedRoutes = [NEIPv4Route.default()] 198 settings.ipv4Settings = v4 199 200 let v6 = NEIPv6Settings(addresses: ["fd66:6c69:6e6b::1"], networkPrefixLengths: [126]) 201 v6.includedRoutes = [NEIPv6Route.default()] 202 settings.ipv6Settings = v6 203 204 // The core answers DNS on port 53 of any address (over TCP through the 205 // node), so the resolver only has to be inside the tunnel. 206 let dns = NEDNSSettings(servers: ["172.19.0.2"]) 207 dns.matchDomains = [""] 208 settings.dnsSettings = dns 209 210 settings.mtu = 1500 211 return settings === lib/core/client_controller.dart:113-124 (git show HEAD:lib/core/client_controller.dart) 113 /// Headline and subtitle for the connected state, worded for what this 114 /// platform actually routes (A-H03): a device-wide VPN on mobile; on 115 /// desktop only apps that use the system proxy (or the local proxy port). 116 (String, String) get connectedSummary { 117 if (!core.usesLocalProxy) { 118 return ('Protected', 'Traffic encrypted by SingLinkVPN'); 119 } 120 if (systemProxySupported && systemProxyEnabled && proxyWarning == null) { 121 return ('Protected', 'System proxy on — apps using it are protected'); 122 } 123 return ('Connected', 'Apps set to use proxy $listen are protected'); 124 } === android/app/build.gradle.kts:64-86 (git show HEAD:android/app/build.gradle.kts) 64 val releaseStore = providers.environmentVariable("SINGLINK_RELEASE_STORE_FILE").orNull 65 val releasePassword = providers.environmentVariable("SINGLINK_RELEASE_STORE_PASSWORD").orNull 66 val releaseAlias = providers.environmentVariable("SINGLINK_RELEASE_KEY_ALIAS").orNull 67 val releaseKeyPassword = providers.environmentVariable("SINGLINK_RELEASE_KEY_PASSWORD").orNull 68 val releaseConfigured = !releaseStore.isNullOrBlank() && !releasePassword.isNullOrBlank() && 69 !releaseAlias.isNullOrBlank() && !releaseKeyPassword.isNullOrBlank() && 70 file(releaseStore).isFile && file(releaseStore).name != "debug.keystore" && 71 file(releaseStore).parentFile?.name != ".android" 72 signingConfigs { 73 create("protectedRelease") { 74 if (releaseConfigured) { 75 storeFile = file(releaseStore!!); storePassword = releasePassword 76 keyAlias = releaseAlias; keyPassword = releaseKeyPassword 77 } 78 } 79 } 80 buildTypes { release { signingConfig = signingConfigs.getByName("protectedRelease") } } 81 gradle.taskGraph.whenReady { 82 val releaseRequested = allTasks.any { it.project == project && it.name.contains("Release") } 83 if (releaseRequested && !releaseConfigured) { 84 throw GradleException("Release signing is missing. Configure external protected signing inputs; debug fallback is disabled.") 85 } 86 } === android/app/src/main/kotlin/com/singlinklabs/singlinkvpn/CredentialStore.kt:29-65 (git show HEAD:android/app/src/main/kotlin/com/singlinklabs/singlinkvpn/CredentialStore.kt) 29 private fun key(create: Boolean): SecretKey { 30 val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } 31 if (store.containsAlias(keyAlias)) return store.getKey(keyAlias, null) as SecretKey 32 check(create) { "missing key" } 33 return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").run { 34 init(KeyGenParameterSpec.Builder(keyAlias, 35 KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT) 36 .setKeySize(256).setBlockModes(KeyProperties.BLOCK_MODE_GCM) 37 .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).build()) 38 generateKey() 39 } 40 } 41 @Synchronized fun read(ref: String): String? { 42 val file = file(ref) 43 if (!file.baseFile.exists() && !File(file.baseFile.path + ".bak").exists()) return null 44 val data = file.readFully() 45 require(data.size in 30..66000 && data[0] == 1.toByte() && data[1] == 12.toByte()) 46 val cipher = Cipher.getInstance("AES/GCM/NoPadding") 47 cipher.init(Cipher.DECRYPT_MODE, key(false), GCMParameterSpec(128, data.copyOfRange(2, 14))) 48 cipher.updateAAD(ref.toByteArray(Charsets.UTF_8)) 49 val plain = cipher.doFinal(data.copyOfRange(14, data.size)) 50 return plain.toString(Charsets.UTF_8).also { require(it.isNotEmpty()) } 51 } 52 @Synchronized fun write(ref: String, value: String) { 53 require(value.isNotEmpty() && value.toByteArray(Charsets.UTF_8).size <= 65536) 54 val file = file(ref) 55 val existing = read(ref) // AtomicFile also recovers a backup-only write. 56 if (existing != null) { check(existing == value); return } 57 val cipher = Cipher.getInstance("AES/GCM/NoPadding") 58 cipher.init(Cipher.ENCRYPT_MODE, key(true)) // OS generates a fresh IV. 59 require(cipher.iv.size == 12) 60 cipher.updateAAD(ref.toByteArray(Charsets.UTF_8)) 61 val blob = byteArrayOf(1, 12) + cipher.iv + cipher.doFinal(value.toByteArray(Charsets.UTF_8)) 62 var stream: java.io.FileOutputStream? = null 63 try { stream = file.startWrite(); stream.write(blob); file.finishWrite(stream) } 64 catch (e: Exception) { file.failWrite(stream); throw e } 65 } === apple/CredentialKeychain.swift:36-85 (git show HEAD:apple/CredentialKeychain.swift) 36 private static func query(_ ref: String) throws -> [String: Any] { 37 guard valid(ref) else { throw CredentialStorageError.invalid } 38 var q: [String: Any] = [kSecClass as String: kSecClassGenericPassword, 39 kSecAttrService as String: service, kSecAttrAccount as String: ref, 40 kSecAttrSynchronizable as String: false] 41 #if os(iOS) 42 guard let group = Bundle.main.object(forInfoDictionaryKey: "CredentialAccessGroup") as? String, 43 !group.isEmpty, !group.contains("$(") else { throw CredentialStorageError.unavailable } 44 q[kSecAttrAccessGroup as String] = group 45 #endif 46 return q 47 } 48 private static func checked(_ status: OSStatus) throws { 49 switch status { 50 case errSecSuccess: return 51 case errSecInteractionNotAllowed, errSecNotAvailable: throw CredentialStorageError.locked 52 case errSecAuthFailed, errSecMissingEntitlement: throw CredentialStorageError.permission 53 default: throw CredentialStorageError.unavailable 54 } 55 } 56 static func read(_ ref: String) throws -> String? { 57 var q = try query(ref) 58 q[kSecReturnData as String] = true 59 q[kSecMatchLimit as String] = kSecMatchLimitOne 60 var item: CFTypeRef? 61 let status = SecItemCopyMatching(q as CFDictionary, &item) 62 if status == errSecItemNotFound { return nil } 63 try checked(status) 64 guard let data = item as? Data, let text = String(data: data, encoding: .utf8) else { 65 throw CredentialStorageError.corrupt 66 } 67 return text 68 } 69 static func write(_ ref: String, value: String) throws { 70 guard !value.isEmpty, value.utf8.count <= 65536 else { 71 throw CredentialStorageError.corrupt 72 } 73 var q = try query(ref) 74 q[kSecValueData as String] = Data(value.utf8) 75 #if os(iOS) 76 q[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly 77 #endif 78 // References are immutable. A duplicate must already contain the same value. 79 let status = SecItemAdd(q as CFDictionary, nil) 80 if status == errSecDuplicateItem { 81 guard try read(ref) == value else { throw CredentialStorageError.corrupt } 82 return 83 } 84 try checked(status) 85 } === windows/runner/credential_store.cpp:144-160 (git show HEAD:windows/runner/credential_store.cpp) 144 void Write(const std::string& ref, const std::string& value) { 145 if (!ValidSecret(value)) throw StoreError("corrupt"); 146 auto path = SecretPath(ref); 147 const auto previous = Read(ref); 148 if (previous) { 149 if (*previous != value) throw StoreError("corrupt"); 150 return; 151 } 152 DATA_BLOB plain{static_cast(value.size()), 153 reinterpret_cast(const_cast(value.data()))}; 154 DATA_BLOB entropy{static_cast(ref.size()), 155 reinterpret_cast(const_cast(ref.data()))}; 156 ScopedBlob encrypted; 157 // Default DPAPI scope is the current user, never LOCAL_MACHINE. 158 if (!CryptProtectData(&plain, L"SingLinkVPN credential", &entropy, nullptr, 159 nullptr, CRYPTPROTECT_UI_FORBIDDEN, &encrypted.data)) 160 throw StoreError("locked"); === lib/core/credential_migration.dart:16-37 (git show HEAD:lib/core/credential_migration.dart) 16 Future protect(Profile profile) async { 17 if (profile.link.isEmpty) { 18 if (!isSecretReference(profile.secretRef)) { 19 throw const SecretStoreException('missing'); 20 } 21 return profile; 22 } 23 final encoded = ProtectedCredential( 24 profile.link, 25 profile.acknowledgedWarnings, 26 ).encode(); 27 var ref = profile.secretRef; 28 if (!isSecretReference(ref) || await secrets.read(ref) != encoded) { 29 ref = newSecretReference(); 30 await onAllocate?.call(ref); 31 await secrets.write(ref, encoded); 32 } 33 if (await secrets.read(ref) != encoded) { 34 throw const SecretStoreException('verification'); 35 } 36 return profile.withCredential(reference: ref); 37 } === android/app/src/main/AndroidManifest.xml:1-47 (git show HEAD:android/app/src/main/AndroidManifest.xml) 1 2 3 4 5 6 13 22 26 30 31 32 33 34 35 36 41 42 43 44 47 === macos/Runner/Release.entitlements:1-16 (git show HEAD:macos/Runner/Release.entitlements) 1 2 3 4 5 9 com.apple.security.app-sandbox 10 11 12 com.apple.security.network.client 13 14 com.apple.security.network.server 15 16 === grep -c HARDENED macos/Runner.xcodeproj/project.pbxproj 0 === core/go.mod:1-6 (git show HEAD:core/go.mod) 1 module github.com/SingLinkLabs/singlink-vpn-app/core 2 3 go 1.27.3 4 5 require ( 6 github.com/SingLinkLabs/singlink-protocol v0.0.0-20261117132120-b9246900205c === .github/workflows/build.yml:18-24 (git show HEAD:.github/workflows/build.yml) 18 19 # Least privilege: nothing by default; each job grants only what it needs. 20 # Every third-party action is pinned to a full commit SHA (tag in the comment). 21 permissions: {} 22 23 concurrency: 24 group: build-${{ github.ref }} === .github/workflows/build.yml:128-136 (git show HEAD:.github/workflows/build.yml) 128 cache-dependency-path: singlink-vpn-app/core/go.sum 129 - name: MinGW-w64 gcc (cgo) 130 shell: pwsh 131 run: | 132 if (-not (Get-Command gcc -ErrorAction SilentlyContinue)) { 133 choco install mingw --no-progress -y 134 "C:\ProgramData\mingw64\mingw64\bin" | Out-File -Append -Encoding utf8 $env:GITHUB_PATH 135 } 136 - name: Build singlink.dll === android/gradle/wrapper/gradle-wrapper.properties:1-5 (git show HEAD:android/gradle/wrapper/gradle-wrapper.properties) 1 distributionBase=GRADLE_USER_HOME 2 distributionPath=wrapper/dists 3 zipStoreBase=GRADLE_USER_HOME 4 zipStorePath=wrapper/dists 5 distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-all.zip