terminalchat-cli 0.0.0-stage → 0.1.1

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/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
+ }
package/src/outbox.js ADDED
@@ -0,0 +1,159 @@
1
+ /**
2
+ * src/outbox.js — pure seq/ack/dedup/ordering engine
3
+ *
4
+ * This module is intentionally side-effect-free: every function takes
5
+ * state objects and returns new/mutated state. No I/O, no DHT, no Ink.
6
+ * That makes it trivially unit-testable and re-usable from both network.js
7
+ * and the integration test.
8
+ *
9
+ * Terminology:
10
+ * outbox = { [friendKeyHex]: [ {seq, ts, body}, … ] } unacked sent msgs
11
+ * seqState = { nextSeq: { [friendKeyHex]: n }, ackedUpTo: { [friendKeyHex]: n } }
12
+ * inbox = internal per-friend map of received { [senderKeyHex]: Set<seq> }
13
+ * and the last contiguous seq per sender (for cumulative acks)
14
+ *
15
+ * Message identity: (senderPubKeyHex, seq) — globally unique because seq is
16
+ * per-sender-per-receiver pair and each device owns one identity.
17
+ */
18
+
19
+ // ---------------------------------------------------------------------------
20
+ // Outbox: allocate + prune
21
+ // ---------------------------------------------------------------------------
22
+
23
+ /**
24
+ * Allocate the next seq number for a message to `friendKey`, mutate seqState,
25
+ * append to outbox, and return { seq }.
26
+ */
27
+ export function allocateSeq (outboxData, seqState, friendKey, ts, body) {
28
+ const nextSeq = seqState.nextSeq[friendKey] ?? 1
29
+ seqState.nextSeq[friendKey] = nextSeq + 1
30
+
31
+ if (!outboxData[friendKey]) outboxData[friendKey] = []
32
+ outboxData[friendKey].push({ seq: nextSeq, ts, body })
33
+
34
+ return nextSeq
35
+ }
36
+
37
+ /**
38
+ * Process a cumulative ack {upTo:N} from `friendKey`.
39
+ * Removes all outbox entries for that friend with seq ≤ N.
40
+ * Updates seqState.ackedUpTo.
41
+ * Returns the number of entries pruned.
42
+ */
43
+ export function processAck (outboxData, seqState, friendKey, upTo) {
44
+ seqState.ackedUpTo[friendKey] = Math.max(
45
+ seqState.ackedUpTo[friendKey] ?? 0,
46
+ upTo
47
+ )
48
+ if (!outboxData[friendKey]) return 0
49
+ const before = outboxData[friendKey].length
50
+ outboxData[friendKey] = outboxData[friendKey].filter(m => m.seq > upTo)
51
+ return before - outboxData[friendKey].length
52
+ }
53
+
54
+ /**
55
+ * Return the full outbox for a given friend (for flushing on connect).
56
+ * Returns [] if empty.
57
+ */
58
+ export function getOutbox (outboxData, friendKey) {
59
+ return (outboxData[friendKey] ?? []).slice().sort((a, b) => a.seq - b.seq)
60
+ }
61
+
62
+ // ---------------------------------------------------------------------------
63
+ // Inbox: dedup + cumulative ack tracking
64
+ // ---------------------------------------------------------------------------
65
+
66
+ /**
67
+ * Create a fresh per-connection inbox tracker for one peer.
68
+ *
69
+ * Returns an object with:
70
+ * receive(senderKey, seq, ts, body) → { stored: bool, ackUpTo: number }
71
+ * getAck(senderKey) → number (last contiguous seq)
72
+ *
73
+ * The tracker is in-memory only; it is re-created each time a connection
74
+ * is established (re-established connections re-deliver from the outbox,
75
+ * and duplicates are detected via the persistent history dedup below).
76
+ */
77
+ export function createInboxTracker () {
78
+ // seqs we've seen per sender, as a sorted array
79
+ const received = {} // senderKey → Set<seq>
80
+ const contiguous = {} // senderKey → last contiguous seq (starts at 0)
81
+
82
+ return {
83
+ /**
84
+ * Record receipt of (senderKey, seq).
85
+ * Returns { stored: bool, ackUpTo: number }.
86
+ * stored=false means it's a duplicate; still ack it.
87
+ */
88
+ receive (senderKey, seq) {
89
+ if (!received[senderKey]) {
90
+ received[senderKey] = new Set()
91
+ contiguous[senderKey] = 0
92
+ }
93
+ const set = received[senderKey]
94
+ const c0 = contiguous[senderKey]
95
+
96
+ // Already fully delivered: seq is at or below the contiguous mark,
97
+ // OR it's in the pending-gap set (arrived out of order before).
98
+ const isDup = seq <= c0 || set.has(seq)
99
+ if (!isDup) set.add(seq)
100
+
101
+ // Advance contiguous pointer past any now-consecutive pending seqs
102
+ let c = c0
103
+ while (set.has(c + 1)) {
104
+ c++
105
+ set.delete(c) // safe: entry is now "contiguous", not needed in set
106
+ }
107
+ contiguous[senderKey] = c
108
+
109
+ return { stored: !isDup, ackUpTo: c }
110
+ },
111
+
112
+ getAck (senderKey) {
113
+ return contiguous[senderKey] ?? 0
114
+ },
115
+ }
116
+ }
117
+
118
+ // ---------------------------------------------------------------------------
119
+ // History-level dedup (persistent, across reconnects)
120
+ // ---------------------------------------------------------------------------
121
+
122
+ /**
123
+ * Build a Set of "<senderKey>:<seq>" from an array of history entries.
124
+ * Used to skip duplicate messages that survived a reconnect cycle.
125
+ */
126
+ export function buildSeenSet (historyEntries) {
127
+ const seen = new Set()
128
+ for (const e of historyEntries) {
129
+ if (e.sender && e.seq != null) {
130
+ seen.add(`${e.sender}:${e.seq}`)
131
+ }
132
+ }
133
+ return seen
134
+ }
135
+
136
+ export function isSeen (seenSet, senderKey, seq) {
137
+ return seenSet.has(`${senderKey}:${seq}`)
138
+ }
139
+
140
+ export function markSeen (seenSet, senderKey, seq) {
141
+ seenSet.add(`${senderKey}:${seq}`)
142
+ }
143
+
144
+ // ---------------------------------------------------------------------------
145
+ // Display ordering
146
+ // ---------------------------------------------------------------------------
147
+
148
+ /**
149
+ * Sort an array of history entries for display.
150
+ * Primary: ts (timestamp ms). Tiebreak: (sender, seq) lexicographic.
151
+ */
152
+ export function sortMessages (messages) {
153
+ return messages.slice().sort((a, b) => {
154
+ if (a.ts !== b.ts) return a.ts - b.ts
155
+ if (a.sender < b.sender) return -1
156
+ if (a.sender > b.sender) return 1
157
+ return a.seq - b.seq
158
+ })
159
+ }
@@ -0,0 +1,175 @@
1
+ /**
2
+ * src/protocol.js — wire protocol framing + inline base58
3
+ *
4
+ * Wire: newline-delimited JSON over the Noise-encrypted HyperDHT stream.
5
+ *
6
+ * Frame types:
7
+ * {type:"hello", name, invite?} first frame each direction
8
+ * {type:"msg", seq, ts, body} body UTF-8, max 8 KB
9
+ * {type:"ack", upTo} cumulative ack
10
+ *
11
+ * Line limits: single line > 64 KB → drop connection.
12
+ * Body limit: body > 8 KB → drop connection.
13
+ *
14
+ * Invite codes: base58( publicKey[32] ‖ secret[16] ) → 48+ char string
15
+ */
16
+ import b4a from 'b4a'
17
+
18
+ // ---------------------------------------------------------------------------
19
+ // Constants
20
+ // ---------------------------------------------------------------------------
21
+
22
+ export const MAX_LINE_BYTES = 64 * 1024 // 64 KB hard limit per line
23
+ export const MAX_BODY_BYTES = 8 * 1024 // 8 KB body limit
24
+
25
+ // ---------------------------------------------------------------------------
26
+ // Inline base58
27
+ // ---------------------------------------------------------------------------
28
+
29
+ const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
30
+ const BASE = 58n
31
+
32
+ function base58Encode (buf) {
33
+ if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)
34
+ let num = BigInt('0x' + buf.toString('hex') || '0')
35
+ let str = ''
36
+ while (num > 0n) {
37
+ str = ALPHABET[Number(num % BASE)] + str
38
+ num = num / BASE
39
+ }
40
+ // Leading zero bytes → '1'
41
+ for (const byte of buf) {
42
+ if (byte !== 0) break
43
+ str = '1' + str
44
+ }
45
+ return str
46
+ }
47
+
48
+ function base58Decode (str) {
49
+ let num = 0n
50
+ for (const ch of str) {
51
+ const idx = ALPHABET.indexOf(ch)
52
+ if (idx < 0) throw new Error(`Invalid base58 character: ${ch}`)
53
+ num = num * BASE + BigInt(idx)
54
+ }
55
+ // Count leading '1's → leading zero bytes
56
+ let leadingZeros = 0
57
+ for (const ch of str) {
58
+ if (ch !== '1') break
59
+ leadingZeros++
60
+ }
61
+ const hex = num.toString(16).padStart(2, '0')
62
+ const paddedHex = (hex.length % 2 ? '0' : '') + hex
63
+ const bytes = Buffer.from(paddedHex, 'hex')
64
+ return Buffer.concat([Buffer.alloc(leadingZeros), bytes])
65
+ }
66
+
67
+ // ---------------------------------------------------------------------------
68
+ // Invite code encode / decode
69
+ // ---------------------------------------------------------------------------
70
+
71
+ /** Build a one-time invite code from a public key (32 bytes) and a 16-byte secret. */
72
+ export function encodeInvite (publicKey, secret) {
73
+ const pk = b4a.isBuffer(publicKey) ? publicKey : b4a.from(publicKey, 'hex')
74
+ const sec = b4a.isBuffer(secret) ? secret : b4a.from(secret, 'hex')
75
+ if (pk.length !== 32) throw new Error('publicKey must be 32 bytes')
76
+ if (sec.length !== 16) throw new Error('secret must be 16 bytes')
77
+ return base58Encode(Buffer.concat([pk, sec]))
78
+ }
79
+
80
+ /** Parse a one-time invite code. Returns { publicKey<Buffer>, secret<Buffer> }. */
81
+ export function decodeInvite (code) {
82
+ const buf = base58Decode(code)
83
+ if (buf.length !== 48) throw new Error(`Invalid invite code (expected 48 bytes, got ${buf.length})`)
84
+ return {
85
+ publicKey: buf.slice(0, 32),
86
+ secret: buf.slice(32, 48),
87
+ }
88
+ }
89
+
90
+ // ---------------------------------------------------------------------------
91
+ // Frame encode / decode
92
+ // ---------------------------------------------------------------------------
93
+
94
+ /** Serialise a frame object to a newline-terminated JSON string. */
95
+ export function encodeFrame (frame) {
96
+ return JSON.stringify(frame) + '\n'
97
+ }
98
+
99
+ /**
100
+ * Parse and validate a single JSON line (without the trailing newline).
101
+ * Throws if invalid or violates limits.
102
+ */
103
+ export function parseFrame (line) {
104
+ if (Buffer.byteLength(line, 'utf8') > MAX_LINE_BYTES) {
105
+ throw new Error('Frame too large')
106
+ }
107
+ let frame
108
+ try {
109
+ frame = JSON.parse(line)
110
+ } catch {
111
+ throw new Error('Malformed JSON frame')
112
+ }
113
+ if (!frame || typeof frame.type !== 'string') {
114
+ throw new Error('Frame missing type')
115
+ }
116
+ switch (frame.type) {
117
+ case 'hello':
118
+ if (typeof frame.name !== 'string') throw new Error('hello: missing name')
119
+ break
120
+ case 'msg':
121
+ if (typeof frame.seq !== 'number') throw new Error('msg: missing seq')
122
+ if (typeof frame.ts !== 'number') throw new Error('msg: missing ts')
123
+ if (typeof frame.body !== 'string') throw new Error('msg: missing body')
124
+ if (Buffer.byteLength(frame.body, 'utf8') > MAX_BODY_BYTES) {
125
+ throw new Error('msg: body too large')
126
+ }
127
+ break
128
+ case 'ack':
129
+ if (typeof frame.upTo !== 'number') throw new Error('ack: missing upTo')
130
+ break
131
+ default:
132
+ throw new Error(`Unknown frame type: ${frame.type}`)
133
+ }
134
+ return frame
135
+ }
136
+
137
+ // ---------------------------------------------------------------------------
138
+ // Line assembler (stateful, feeds raw chunk data)
139
+ // ---------------------------------------------------------------------------
140
+
141
+ /**
142
+ * Create a line assembler that buffers incoming data and emits complete lines.
143
+ *
144
+ * Usage:
145
+ * const la = createLineAssembler({ onLine, onError })
146
+ * socket.on('data', chunk => la.push(chunk))
147
+ *
148
+ * onLine(line: string) — called with each '\n'-terminated line (without '\n')
149
+ * onError(err) — called on oversized line or other error; caller should close the socket
150
+ */
151
+ export function createLineAssembler ({ onLine, onError }) {
152
+ let buf = ''
153
+ let totalBytes = 0
154
+
155
+ return {
156
+ push (chunk) {
157
+ const str = typeof chunk === 'string' ? chunk : b4a.toString(chunk, 'utf8')
158
+ totalBytes += Buffer.byteLength(str, 'utf8')
159
+
160
+ if (totalBytes > MAX_LINE_BYTES) {
161
+ onError(new Error('Line too large; dropping connection'))
162
+ return
163
+ }
164
+
165
+ buf += str
166
+ let idx
167
+ while ((idx = buf.indexOf('\n')) !== -1) {
168
+ const line = buf.slice(0, idx)
169
+ buf = buf.slice(idx + 1)
170
+ totalBytes = Buffer.byteLength(buf, 'utf8')
171
+ onLine(line)
172
+ }
173
+ },
174
+ }
175
+ }