terminalchat-cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/engine.js ADDED
@@ -0,0 +1,407 @@
1
+ /**
2
+ * src/engine.js — application core (EventEmitter)
3
+ *
4
+ * Owns the data directory, identity, friends, invites, outbox, state, and
5
+ * the Network layer. Exposes a clean method/event surface that the Ink UI
6
+ * (and the integration test) consumes — the UI never touches DHT or storage
7
+ * directly.
8
+ *
9
+ * Methods:
10
+ * start()
11
+ * sendMessage(friendKeyHex, body) → seq
12
+ * createInvite() → string (base58 code)
13
+ * join(code) → { friendKeyHex, name }
14
+ * addFriend(name, keyHex)
15
+ * getHistory(friendKeyHex, n) → Promise<entry[]>
16
+ * whoami() → { name, publicKey: hex }
17
+ * shutdown()
18
+ *
19
+ * Events:
20
+ * 'ready'
21
+ * 'friend-added' (friendKeyHex, name)
22
+ * 'friend-online' (friendKeyHex)
23
+ * 'friend-offline'(friendKeyHex)
24
+ * 'message' (friendKeyHex, entry) — entry has direction:'in'|'out'
25
+ * 'ack' (friendKeyHex, seq) — seq confirmed delivered
26
+ * 'error' (err)
27
+ */
28
+ import { EventEmitter } from 'node:events'
29
+ import { randomBytes } from 'node:crypto'
30
+ import { resolve } from 'node:path'
31
+ import { homedir } from 'node:os'
32
+ import b4a from 'b4a'
33
+ import { Network } from './network.js'
34
+ import { createStore } from './store.js'
35
+ import { loadOrCreate, bufferToHex, hexToBuffer } from './identity.js'
36
+ import { encodeInvite, decodeInvite } from './protocol.js'
37
+ import {
38
+ allocateSeq,
39
+ processAck,
40
+ getOutbox,
41
+ createInboxTracker,
42
+ buildSeenSet,
43
+ isSeen,
44
+ markSeen,
45
+ } from './outbox.js'
46
+
47
+ export class Engine extends EventEmitter {
48
+ /**
49
+ * @param {object} [opts]
50
+ * @param {string} [opts.dataDir] override data directory (default: ~/.terminalchat or TCHAT_DATA_DIR)
51
+ * @param {object} [opts.dhtOptions] extra options for `new DHT(...)` (e.g. { bootstrap })
52
+ * @param {Function} [opts.namePrompt] async () → string; for test use
53
+ */
54
+ constructor (opts = {}) {
55
+ super()
56
+ const baseDir = opts.dataDir
57
+ ?? process.env.TCHAT_DATA_DIR
58
+ ?? resolve(homedir(), '.terminalchat')
59
+
60
+ this._store = createStore(baseDir)
61
+ this._dhtOptions = opts.dhtOptions ?? {}
62
+ this._namePrompt = opts.namePrompt ?? undefined
63
+
64
+ this._identity = null
65
+ this._network = null
66
+
67
+ this._friends = {}
68
+ this._invites = {}
69
+ this._outboxData = {}
70
+ this._seqState = { nextSeq: {}, ackedUpTo: {} }
71
+
72
+ this._inboxTrackers = {} // { [keyHex]: InboxTracker }
73
+ this._seenSets = {} // { [keyHex]: Set<"sender:seq"> }
74
+
75
+ this._started = false
76
+ this._destroyed = false
77
+ }
78
+
79
+ // ---------------------------------------------------------------------------
80
+ // start
81
+ // ---------------------------------------------------------------------------
82
+
83
+ async start () {
84
+ if (this._started) return
85
+ this._store.ensure()
86
+
87
+ this._identity = await loadOrCreate(this._store, this._namePrompt)
88
+
89
+ this._friends = this._store.friends.load() ?? {}
90
+ this._invites = this._store.invites.load() ?? {}
91
+ this._outboxData = this._store.outbox.load() ?? {}
92
+ this._seqState = this._store.state.load() ?? { nextSeq: {}, ackedUpTo: {} }
93
+
94
+ this._pruneInvites()
95
+
96
+ for (const keyHex of Object.keys(this._friends)) {
97
+ await this._loadSeenSet(keyHex)
98
+ }
99
+
100
+ this._network = new Network(
101
+ {
102
+ keyPair: {
103
+ publicKey: this._identity.publicKey,
104
+ secretKey: this._identity.secretKey,
105
+ },
106
+ name: this._identity.name,
107
+ dhtOptions: this._dhtOptions,
108
+ },
109
+ {
110
+ isFriend: (k) => k in this._friends,
111
+ checkInvite: (s) => this._checkInvite(s),
112
+ consumeInvite: (s) => this._consumeInvite(s),
113
+ onHandshake: (k, n) => this._onHandshake(k, n),
114
+ onInviteAccepted: (k, n) => this._onInviteAccepted(k, n),
115
+ onFrame: (k, f) => this._onFrame(k, f),
116
+ onDisconnect: (k) => this._onDisconnect(k),
117
+ getHello: () => ({ type: 'hello', name: this._identity.name }),
118
+ getOutbox: (k) => getOutbox(this._outboxData, k),
119
+ }
120
+ )
121
+
122
+ await this._network.start()
123
+ await this._network.connectAll(Object.keys(this._friends))
124
+
125
+ this._started = true
126
+ this.emit('ready')
127
+ }
128
+
129
+ // ---------------------------------------------------------------------------
130
+ // sendMessage
131
+ // ---------------------------------------------------------------------------
132
+
133
+ sendMessage (friendKeyHex, body) {
134
+ if (!(friendKeyHex in this._friends)) throw new Error('Unknown friend')
135
+ if (typeof body !== 'string' || !body.trim()) throw new Error('Empty message')
136
+
137
+ const ts = Date.now()
138
+ const seq = allocateSeq(this._outboxData, this._seqState, friendKeyHex, ts, body)
139
+
140
+ this._saveOutbox()
141
+ this._saveState()
142
+
143
+ const entry = {
144
+ direction: 'out',
145
+ sender: bufferToHex(this._identity.publicKey),
146
+ seq,
147
+ ts,
148
+ body,
149
+ delivered: false,
150
+ }
151
+ this._store.appendHistory(friendKeyHex, entry)
152
+ this.emit('message', friendKeyHex, entry)
153
+
154
+ this._network.send(friendKeyHex, { type: 'msg', seq, ts, body })
155
+
156
+ return seq
157
+ }
158
+
159
+ // ---------------------------------------------------------------------------
160
+ // createInvite
161
+ // ---------------------------------------------------------------------------
162
+
163
+ createInvite () {
164
+ const secret = randomBytes(16)
165
+ const secretHex = b4a.toString(secret, 'hex')
166
+ this._invites[secretHex] = { createdAt: Date.now() }
167
+ this._store.invites.save(this._invites)
168
+ return encodeInvite(this._identity.publicKey, secret)
169
+ }
170
+
171
+ // ---------------------------------------------------------------------------
172
+ // join (joiner side)
173
+ // ---------------------------------------------------------------------------
174
+
175
+ async join (code) {
176
+ const { publicKey, secret } = decodeInvite(code)
177
+ const inviterKeyHex = bufferToHex(publicKey)
178
+ const secretHex = bufferToHex(secret)
179
+
180
+ return new Promise((resolve, reject) => {
181
+ const wasAlreadyFriend = !!this._friends[inviterKeyHex]
182
+
183
+ // Pre-add the inviter so our _handleHello accepts their responding hello.
184
+ // The name will be overwritten by _onHandshake once we receive their hello.
185
+ if (!wasAlreadyFriend) {
186
+ this._friends[inviterKeyHex] = { name: '…', addedAt: Date.now() }
187
+ }
188
+
189
+ // Once the inviter comes online (network accepted their hello), we're done.
190
+ const onOnline = (keyHex) => {
191
+ if (keyHex !== inviterKeyHex) return
192
+ this.off('friend-online', onOnline)
193
+ const name = this._friends[inviterKeyHex]?.name ?? ''
194
+ // Persist the friend now that the join succeeded
195
+ this._store.friends.save(this._friends)
196
+ this.emit('friend-added', inviterKeyHex, name)
197
+ resolve({ friendKeyHex: inviterKeyHex, name })
198
+ }
199
+ this.on('friend-online', onOnline)
200
+
201
+ // Patch getHello to include the invite secret for this one connection
202
+ const origGetHello = this._network._handlers.getHello
203
+ this._network._handlers.getHello = () => ({
204
+ type: 'hello', name: this._identity.name, invite: secretHex,
205
+ })
206
+
207
+ this._network._connectTo(inviterKeyHex)
208
+ .then(() => { this._network._handlers.getHello = origGetHello })
209
+ .catch(err => {
210
+ this._network._handlers.getHello = origGetHello
211
+ this.off('friend-online', onOnline)
212
+ if (!wasAlreadyFriend) delete this._friends[inviterKeyHex]
213
+ reject(err)
214
+ })
215
+
216
+ const timer = setTimeout(() => {
217
+ this.off('friend-online', onOnline)
218
+ this._network._handlers.getHello = origGetHello
219
+ if (!wasAlreadyFriend) delete this._friends[inviterKeyHex]
220
+ reject(new Error('Join timed out'))
221
+ }, 30_000)
222
+ timer.unref?.()
223
+ })
224
+ }
225
+
226
+ // ---------------------------------------------------------------------------
227
+ // addFriend (manual / both-sides-add path)
228
+ // ---------------------------------------------------------------------------
229
+
230
+ addFriend (name, keyHex) {
231
+ if (this._friends[keyHex]) {
232
+ this._friends[keyHex].name = name
233
+ } else {
234
+ this._friends[keyHex] = { name, addedAt: Date.now() }
235
+ }
236
+ this._store.friends.save(this._friends)
237
+ this.emit('friend-added', keyHex, name)
238
+ }
239
+
240
+ // ---------------------------------------------------------------------------
241
+ // getHistory / whoami
242
+ // ---------------------------------------------------------------------------
243
+
244
+ async getHistory (friendKeyHex, n = 50) {
245
+ return this._store.readHistory(friendKeyHex, n)
246
+ }
247
+
248
+ whoami () {
249
+ return {
250
+ name: this._identity.name,
251
+ publicKey: bufferToHex(this._identity.publicKey),
252
+ }
253
+ }
254
+
255
+ // ---------------------------------------------------------------------------
256
+ // shutdown
257
+ // ---------------------------------------------------------------------------
258
+
259
+ async shutdown () {
260
+ if (this._destroyed) return
261
+ this._destroyed = true
262
+ this._saveOutbox()
263
+ this._saveState()
264
+ if (this._network) await this._network.destroy()
265
+ }
266
+
267
+ // ---------------------------------------------------------------------------
268
+ // Online status helpers (for UI)
269
+ // ---------------------------------------------------------------------------
270
+
271
+ isOnline (friendKeyHex) {
272
+ return this._network?.isOnline(friendKeyHex) ?? false
273
+ }
274
+
275
+ getFriends () {
276
+ return Object.entries(this._friends).map(([keyHex, info]) => ({
277
+ keyHex,
278
+ name: info.name,
279
+ online: this.isOnline(keyHex),
280
+ addedAt: info.addedAt,
281
+ }))
282
+ }
283
+
284
+ // ---------------------------------------------------------------------------
285
+ // Internal: network callbacks
286
+ // ---------------------------------------------------------------------------
287
+
288
+ _onHandshake (keyHex, name) {
289
+ if (this._friends[keyHex] && this._friends[keyHex].name !== name) {
290
+ this._friends[keyHex].name = name
291
+ this._store.friends.save(this._friends)
292
+ }
293
+ this._inboxTrackers[keyHex] = this._trackerFromSeen(keyHex)
294
+ this.emit('friend-online', keyHex)
295
+ }
296
+
297
+ _onInviteAccepted (keyHex, name) {
298
+ this._friends[keyHex] = { name, addedAt: Date.now() }
299
+ this._store.friends.save(this._friends)
300
+ this._inboxTrackers[keyHex] = createInboxTracker()
301
+ this._seenSets[keyHex] = new Set()
302
+ this.emit('friend-added', keyHex, name)
303
+ this.emit('friend-online', keyHex)
304
+ }
305
+
306
+ _trackerFromSeen (senderKeyHex) {
307
+ const tracker = createInboxTracker()
308
+ const seen = [...(this._seenSets[senderKeyHex] ?? [])]
309
+ .filter(id => id.startsWith(`${senderKeyHex}:`))
310
+ .map(id => Number(id.slice(senderKeyHex.length + 1)))
311
+ .filter(Number.isSafeInteger)
312
+ .sort((a, b) => a - b)
313
+ for (const seq of seen) tracker.receive(senderKeyHex, seq)
314
+ return tracker
315
+ }
316
+
317
+ _onDisconnect (keyHex) {
318
+ delete this._inboxTrackers[keyHex]
319
+ this.emit('friend-offline', keyHex)
320
+ }
321
+
322
+ _onFrame (keyHex, frame) {
323
+ switch (frame.type) {
324
+ case 'msg': this._handleMsg(keyHex, frame); break
325
+ case 'ack': this._handleAck(keyHex, frame); break
326
+ }
327
+ }
328
+
329
+ _handleMsg (senderKeyHex, frame) {
330
+ const tracker = this._inboxTrackers[senderKeyHex]
331
+ if (!tracker) return
332
+
333
+ const seenSet = this._seenSets[senderKeyHex] ?? (this._seenSets[senderKeyHex] = new Set())
334
+
335
+ if (isSeen(seenSet, senderKeyHex, frame.seq)) {
336
+ const ackUpTo = tracker.getAck(senderKeyHex)
337
+ this._network.send(senderKeyHex, { type: 'ack', upTo: ackUpTo })
338
+ return
339
+ }
340
+
341
+ const { stored, ackUpTo } = tracker.receive(senderKeyHex, frame.seq)
342
+ if (stored) {
343
+ markSeen(seenSet, senderKeyHex, frame.seq)
344
+ const entry = {
345
+ direction: 'in',
346
+ sender: senderKeyHex,
347
+ seq: frame.seq,
348
+ ts: frame.ts,
349
+ body: frame.body,
350
+ delivered: true,
351
+ }
352
+ this._store.appendHistory(senderKeyHex, entry)
353
+ this.emit('message', senderKeyHex, entry)
354
+ }
355
+
356
+ this._network.send(senderKeyHex, { type: 'ack', upTo: ackUpTo })
357
+ }
358
+
359
+ _handleAck (friendKeyHex, frame) {
360
+ const pruned = processAck(this._outboxData, this._seqState, friendKeyHex, frame.upTo)
361
+ if (pruned > 0) {
362
+ this._saveOutbox()
363
+ this._saveState()
364
+ this.emit('ack', friendKeyHex, frame.upTo)
365
+ }
366
+ }
367
+
368
+ // ---------------------------------------------------------------------------
369
+ // Internal: invites
370
+ // ---------------------------------------------------------------------------
371
+
372
+ _checkInvite (secretHex) {
373
+ const inv = this._invites[secretHex]
374
+ if (!inv) return false
375
+ if (Date.now() - inv.createdAt > 24 * 60 * 60 * 1000) {
376
+ delete this._invites[secretHex]
377
+ this._store.invites.save(this._invites)
378
+ return false
379
+ }
380
+ return true
381
+ }
382
+
383
+ _consumeInvite (secretHex) {
384
+ delete this._invites[secretHex]
385
+ this._store.invites.save(this._invites)
386
+ }
387
+
388
+ _pruneInvites () {
389
+ const now = Date.now()
390
+ let changed = false
391
+ for (const [hex, inv] of Object.entries(this._invites)) {
392
+ if (now - inv.createdAt > 24 * 60 * 60 * 1000) {
393
+ delete this._invites[hex]
394
+ changed = true
395
+ }
396
+ }
397
+ if (changed) this._store.invites.save(this._invites)
398
+ }
399
+
400
+ async _loadSeenSet (keyHex) {
401
+ const history = await this._store.readHistory(keyHex, 10_000)
402
+ this._seenSets[keyHex] = buildSeenSet(history)
403
+ }
404
+
405
+ _saveOutbox () { this._store.outbox.save(this._outboxData) }
406
+ _saveState () { this._store.state.save(this._seqState) }
407
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * src/identity.js — per-device Ed25519 key pair + display name
3
+ *
4
+ * On first run we ask for a display name, generate a key pair with
5
+ * DHT.keyPair(), and persist it to <dataDir>/identity.json (mode 0600).
6
+ *
7
+ * Stored format:
8
+ * { publicKey: "<hex>", secretKey: "<hex>", name: "<display name>" }
9
+ *
10
+ * Public API:
11
+ * loadOrCreate(store, promptName) → { publicKey<Buffer>, secretKey<Buffer>, name<string> }
12
+ * bufferToHex / hexToBuffer helpers
13
+ */
14
+ import { createInterface } from 'node:readline'
15
+ import b4a from 'b4a'
16
+ import DHT from 'hyperdht'
17
+
18
+ // ---------------------------------------------------------------------------
19
+ // Helpers
20
+ // ---------------------------------------------------------------------------
21
+
22
+ export function bufferToHex (buf) {
23
+ return b4a.toString(buf, 'hex')
24
+ }
25
+
26
+ export function hexToBuffer (hex) {
27
+ return b4a.from(hex, 'hex')
28
+ }
29
+
30
+ // ---------------------------------------------------------------------------
31
+ // Interactive name prompt (only used on first run, before Ink mounts)
32
+ // ---------------------------------------------------------------------------
33
+
34
+ function stdinPromptName () {
35
+ return new Promise((resolve) => {
36
+ const rl = createInterface({ input: process.stdin, output: process.stdout })
37
+ rl.question('Welcome to TerminalChat! Enter your display name: ', (answer) => {
38
+ rl.close()
39
+ resolve(answer.trim() || 'Anonymous')
40
+ })
41
+ })
42
+ }
43
+
44
+ // ---------------------------------------------------------------------------
45
+ // Load or create (called at startup before the TUI mounts)
46
+ // ---------------------------------------------------------------------------
47
+
48
+ /**
49
+ * Load the identity from the given store, or create a new one.
50
+ *
51
+ * @param {object} store A store instance from createStore().
52
+ * @param {Function} [namePrompt] async () → string. Defaults to stdin readline.
53
+ */
54
+ export async function loadOrCreate (store, namePrompt = stdinPromptName) {
55
+ store.ensure()
56
+
57
+ const raw = store.identity.load()
58
+ if (raw) {
59
+ return {
60
+ publicKey: hexToBuffer(raw.publicKey),
61
+ secretKey: hexToBuffer(raw.secretKey),
62
+ name: raw.name,
63
+ }
64
+ }
65
+
66
+ const name = await namePrompt()
67
+ const keyPair = DHT.keyPair()
68
+
69
+ store.identity.save({
70
+ publicKey: bufferToHex(keyPair.publicKey),
71
+ secretKey: bufferToHex(keyPair.secretKey),
72
+ name,
73
+ })
74
+
75
+ return {
76
+ publicKey: keyPair.publicKey,
77
+ secretKey: keyPair.secretKey,
78
+ name,
79
+ }
80
+ }
package/src/network.js ADDED
@@ -0,0 +1,224 @@
1
+ /**
2
+ * src/network.js — HyperDHT peer management
3
+ *
4
+ * Owns a DHT node, a server that listens on the identity key pair, and a
5
+ * map of live connections. Calls back into the Engine via event handlers
6
+ * supplied at construction time — no direct dependency on Engine to keep
7
+ * the boundary clean and testable.
8
+ *
9
+ * Rules (from the spec):
10
+ * - Listen on the identity key pair at startup.
11
+ * - On startup: attempt outbound connections to all known friends in parallel.
12
+ * Ignore failures (friend likely offline).
13
+ * - No polling/timer reconnect — reconnect only at startup and when an
14
+ * inbound connection arrives (and we also try to connect back outbound).
15
+ * - Accept inbound only from known friends OR from peers presenting a valid
16
+ * unused invite secret in their hello frame.
17
+ * - On any established connection: send our hello, then flush the unacked
18
+ * outbox for that friend.
19
+ */
20
+ import DHT from 'hyperdht'
21
+ import b4a from 'b4a'
22
+ import { createLineAssembler, parseFrame, encodeFrame } from './protocol.js'
23
+
24
+ export class Network {
25
+ /**
26
+ * @param {object} opts
27
+ * @param {object} opts.keyPair identity key pair { publicKey, secretKey }
28
+ * @param {string} opts.name our display name
29
+ * @param {object} [opts.dhtOptions] extra options for `new DHT(...)` (e.g. { bootstrap })
30
+ * @param {object} handlers callbacks into the Engine
31
+ * @param {function} handlers.isFriend (pubKeyHex) → bool
32
+ * @param {function} handlers.checkInvite (secretHex) → bool (true = valid+unused)
33
+ * @param {function} handlers.consumeInvite (secretHex) → void
34
+ * @param {function} handlers.onHandshake (pubKeyHex, name) → void (new/returning friend connected)
35
+ * @param {function} handlers.onInviteAccepted (pubKeyHex, name) → void (invite used → new friend)
36
+ * @param {function} handlers.onFrame (pubKeyHex, frame) → void
37
+ * @param {function} handlers.onDisconnect (pubKeyHex) → void
38
+ * @param {function} handlers.getHello () → {type:'hello', name, invite?}
39
+ * @param {function} handlers.getOutbox (pubKeyHex) → [{seq,ts,body}]
40
+ */
41
+ constructor (opts, handlers) {
42
+ this._keyPair = opts.keyPair
43
+ this._name = opts.name
44
+ this._dhtOpts = opts.dhtOptions ?? {}
45
+ this._handlers = handlers
46
+
47
+ this._node = null
48
+ this._server = null
49
+ // pubKeyHex → socket
50
+ this._sockets = new Map()
51
+ this._destroyed = false
52
+ }
53
+
54
+ // ---------------------------------------------------------------------------
55
+ // Lifecycle
56
+ // ---------------------------------------------------------------------------
57
+
58
+ async start () {
59
+ this._node = new DHT(this._dhtOpts)
60
+ this._server = this._node.createServer()
61
+
62
+ this._server.on('connection', socket => this._onConnection(socket, false))
63
+
64
+ await this._server.listen(this._keyPair)
65
+ }
66
+
67
+ async connectAll (friendKeys) {
68
+ await Promise.allSettled(
69
+ friendKeys.map(keyHex => this._connectTo(keyHex))
70
+ )
71
+ }
72
+
73
+ async destroy () {
74
+ this._destroyed = true
75
+ for (const socket of this._sockets.values()) {
76
+ socket.destroy()
77
+ }
78
+ if (this._server) await this._server.close().catch(() => {})
79
+ if (this._node) await this._node.destroy().catch(() => {})
80
+ }
81
+
82
+ // ---------------------------------------------------------------------------
83
+ // Send helpers (callable by Engine)
84
+ // ---------------------------------------------------------------------------
85
+
86
+ send (pubKeyHex, frame) {
87
+ const socket = this._sockets.get(pubKeyHex)
88
+ if (!socket || socket.destroyed) return false
89
+ try {
90
+ socket.write(encodeFrame(frame))
91
+ return true
92
+ } catch {
93
+ return false
94
+ }
95
+ }
96
+
97
+ isOnline (pubKeyHex) {
98
+ const s = this._sockets.get(pubKeyHex)
99
+ return !!(s && !s.destroyed)
100
+ }
101
+
102
+ onlinePeers () {
103
+ return [...this._sockets.keys()]
104
+ }
105
+
106
+ // ---------------------------------------------------------------------------
107
+ // Outbound connect
108
+ // ---------------------------------------------------------------------------
109
+
110
+ async _connectTo (pubKeyHex) {
111
+ if (this._destroyed) return
112
+ const pubKey = b4a.from(pubKeyHex, 'hex')
113
+ try {
114
+ const socket = this._node.connect(pubKey, { keyPair: this._keyPair })
115
+ await this._onConnection(socket, true)
116
+ } catch {
117
+ // Peer offline — that's normal, ignore
118
+ }
119
+ }
120
+
121
+ // ---------------------------------------------------------------------------
122
+ // Connection handler (inbound + outbound)
123
+ // ---------------------------------------------------------------------------
124
+
125
+ async _onConnection (socket, isOutbound) {
126
+ const remoteHex = b4a.toString(socket.remotePublicKey, 'hex')
127
+
128
+ // Replace any existing stale socket for this peer
129
+ const existing = this._sockets.get(remoteHex)
130
+ if (existing && !existing.destroyed) existing.destroy()
131
+
132
+ // We haven't done the hello handshake yet, so don't register in _sockets
133
+ // until we know they're allowed in.
134
+
135
+ let hello = null // their hello frame, populated during handshake
136
+
137
+ const la = createLineAssembler({
138
+ onLine: line => {
139
+ let frame
140
+ try {
141
+ frame = parseFrame(line)
142
+ } catch {
143
+ socket.destroy()
144
+ return
145
+ }
146
+
147
+ if (!hello) {
148
+ // Expect first frame to be hello
149
+ if (frame.type !== 'hello') {
150
+ socket.destroy()
151
+ return
152
+ }
153
+ hello = frame
154
+ this._handleHello(socket, remoteHex, hello, isOutbound)
155
+ return
156
+ }
157
+
158
+ // After handshake, deliver frames to engine
159
+ if (this._sockets.has(remoteHex)) {
160
+ this._handlers.onFrame(remoteHex, frame)
161
+ }
162
+ },
163
+ onError: () => socket.destroy(),
164
+ })
165
+
166
+ socket.on('data', chunk => la.push(chunk))
167
+ socket.on('error', () => {
168
+ this._cleanup(remoteHex, socket)
169
+ })
170
+ socket.on('close', () => {
171
+ this._cleanup(remoteHex, socket)
172
+ })
173
+
174
+ // Send our hello immediately
175
+ socket.write(encodeFrame(this._handlers.getHello()))
176
+ }
177
+
178
+ _handleHello (socket, remoteHex, hello, isOutbound) {
179
+ const { isFriend, checkInvite, consumeInvite, onHandshake, onInviteAccepted, getOutbox } = this._handlers
180
+
181
+ if (isFriend(remoteHex)) {
182
+ // Known friend — register and flush outbox
183
+ this._sockets.set(remoteHex, socket)
184
+ onHandshake(remoteHex, hello.name)
185
+ this._flushOutbox(remoteHex, getOutbox(remoteHex))
186
+
187
+ return
188
+ }
189
+
190
+ // Unknown peer — only allowed if they carry a valid invite
191
+ if (hello.invite) {
192
+ const secretHex = b4a.toString(b4a.from(hello.invite, 'hex'), 'hex')
193
+ if (checkInvite(secretHex)) {
194
+ consumeInvite(secretHex)
195
+ this._sockets.set(remoteHex, socket)
196
+ onInviteAccepted(remoteHex, hello.name)
197
+ this._flushOutbox(remoteHex, getOutbox(remoteHex))
198
+ return
199
+ }
200
+ }
201
+
202
+ // Not a friend, no valid invite → reject
203
+ socket.destroy()
204
+ }
205
+
206
+ _flushOutbox (pubKeyHex, messages) {
207
+ if (!messages.length) return
208
+ const socket = this._sockets.get(pubKeyHex)
209
+ if (!socket || socket.destroyed) return
210
+ for (const m of messages) {
211
+ socket.write(encodeFrame({ type: 'msg', seq: m.seq, ts: m.ts, body: m.body }))
212
+ }
213
+ }
214
+
215
+ _cleanup (pubKeyHex, socket) {
216
+ // Only remove if this is still the registered socket
217
+ if (this._sockets.get(pubKeyHex) === socket) {
218
+ this._sockets.delete(pubKeyHex)
219
+ if (!this._destroyed) {
220
+ this._handlers.onDisconnect(pubKeyHex)
221
+ }
222
+ }
223
+ }
224
+ }