| 58 | // --------------------------------------------------------------------------- |
| 59 | |
| 60 | export class LanBeacon extends EventEmitter { |
| 61 | private socket: DgramSocket | null = null |
| 62 | private announceTimer: ReturnType<typeof setInterval> | null = null |
| 63 | private cleanupTimer: ReturnType<typeof setInterval> | null = null |
| 64 | private peers: Map<string, LanAnnounce> = new Map() |
| 65 | private announce: LanAnnounce |
| 66 | |
| 67 | constructor(announce: Omit<LanAnnounce, 'proto' | 'ts'>) { |
| 68 | super() |
| 69 | this.announce = { |
| 70 | ...announce, |
| 71 | proto: 'claude-pipe-v1', |
| 72 | ts: Date.now(), |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | /** |
| 77 | * Start broadcasting announcements and listening for peers. |
| 78 | */ |
| 79 | start(): void { |
| 80 | if (this.socket) return |
| 81 | |
| 82 | try { |
| 83 | this.socket = createSocket({ type: 'udp4', reuseAddr: true }) |
| 84 | |
| 85 | this.socket.on('error', err => { |
| 86 | logError(err) |
| 87 | // Non-fatal — multicast may not be supported on this network |
| 88 | }) |
| 89 | |
| 90 | this.socket.on('message', (buf, _rinfo) => { |
| 91 | try { |
| 92 | const msg = JSON.parse(buf.toString()) as LanAnnounce |
| 93 | if (msg.proto !== 'claude-pipe-v1') return |
| 94 | if (msg.pipeName === this.announce.pipeName) return // ignore self |
| 95 | |
| 96 | const isNew = !this.peers.has(msg.pipeName) |
| 97 | this.peers.set(msg.pipeName, { ...msg, ts: Date.now() }) |
| 98 | |
| 99 | if (isNew) { |
| 100 | this.emit('peer-discovered', msg) |
| 101 | } |
| 102 | } catch { |
| 103 | // Malformed packet — ignore |
| 104 | } |
| 105 | }) |
| 106 | |
| 107 | this.socket.bind(MULTICAST_PORT, () => { |
| 108 | try { |
| 109 | // Specify the local LAN interface for multicast membership. |
| 110 | // Without this, Windows may bind to a WSL/Docker virtual adapter |
| 111 | // and multicast packets never reach the real LAN. |
| 112 | const localIp = this.announce.ip |
| 113 | this.socket!.addMembership(MULTICAST_GROUP, localIp) |
| 114 | this.socket!.setMulticastInterface(localIp) |
| 115 | this.socket!.setMulticastTTL(1) // link-local only |
| 116 | this.socket!.setBroadcast(true) |
| 117 | } catch (err) { |
nothing calls this directly
no outgoing calls
no test coverage detected