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/README.md CHANGED
@@ -1,3 +1,554 @@
1
- # Temporary Holding Version
1
+ # TerminalChat (Tchat)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Private, serverless peer-to-peer chat for your terminal.**
4
+
5
+ TerminalChat lets two people communicate directly over the internet without an
6
+ application server, account system, or hosted message relay. Each installation
7
+ has its own cryptographic identity. Friends connect by public key through
8
+ [HyperDHT](https://github.com/holepunchto/hyperdht), while HyperDHT's Noise
9
+ transport provides authenticated encryption for the connection.
10
+
11
+ The application is distributed as the `terminalchat` npm package and provides
12
+ both `terminalchat` and the shorter `tchat` command.
13
+
14
+ > **Project status:** TerminalChat is an early-stage CLI application. The
15
+ > networking core, persistence, offline queue, protocol framing, and automated
16
+ > integration tests are implemented. The TUI is usable but may continue to
17
+ > evolve as the project matures.
18
+
19
+ ## Contents
20
+
21
+ - [Features](#features)
22
+ - [Requirements](#requirements)
23
+ - [Installation](#installation)
24
+ - [Launching TerminalChat](#launching-terminalchat)
25
+ - [First run and identity](#first-run-and-identity)
26
+ - [Using the TUI](#using-the-tui)
27
+ - [Adding friends](#adding-friends)
28
+ - [Messaging and delivery](#messaging-and-delivery)
29
+ - [Data and storage](#data-and-storage)
30
+ - [Security and trust model](#security-and-trust-model)
31
+ - [Architecture](#architecture)
32
+ - [Troubleshooting](#troubleshooting)
33
+ - [Development](#development)
34
+ - [Testing](#testing)
35
+ - [Packaging and publishing](#packaging-and-publishing)
36
+ - [Limitations](#limitations)
37
+ - [License](#license)
38
+
39
+ ## Features
40
+
41
+ - Direct peer-to-peer connections using HyperDHT.
42
+ - Noise-encrypted transport with cryptographic peer identities.
43
+ - One-time, expiring invite codes.
44
+ - Friend list with online/offline status.
45
+ - Store-and-forward delivery for messages sent while a friend is offline.
46
+ - Persistent sequence numbers and cumulative acknowledgements.
47
+ - Duplicate detection across reconnects and restarts.
48
+ - Append-only conversation history stored locally.
49
+ - Fully interactive keyboard-driven Ink TUI.
50
+ - No application server, sign-up flow, hosted account, or central message database.
51
+
52
+ ## Requirements
53
+
54
+ - **Node.js 22 or newer**
55
+ - A terminal with interactive stdin/stdout support
56
+ - Network access for real peer-to-peer communication
57
+
58
+ Node.js 22 is required because the current Ink TUI stack targets Node 22 or
59
+ newer. The automated test suite uses HyperDHT's local testnet and does not
60
+ require access to the public internet.
61
+
62
+ Check your Node.js version with:
63
+
64
+ ```sh
65
+ node --version
66
+ ```
67
+
68
+ ## Installation
69
+
70
+ ### Install globally from npm
71
+
72
+ ```sh
73
+ npm install --global terminalchat-cli
74
+ ```
75
+
76
+ Then launch the application:
77
+
78
+ ```sh
79
+ tchat
80
+ ```
81
+
82
+ ### Run without a global installation
83
+
84
+ ```sh
85
+ npx terminalchat-cli
86
+ ```
87
+
88
+ ### Install from a local checkout
89
+
90
+ ```sh
91
+ git clone <repository-url>
92
+ cd tchat
93
+ npm install
94
+ npm start
95
+ ```
96
+
97
+ The package exposes two equivalent binaries:
98
+
99
+ ```sh
100
+ terminalchat
101
+ tchat
102
+ ```
103
+
104
+ ## Launching TerminalChat
105
+
106
+ The application is intentionally TUI-first. There are no normal shell
107
+ subcommands for inviting, joining, or messaging.
108
+
109
+ ```text
110
+ terminalchat Launch the interactive TUI
111
+ tchat Launch the interactive TUI
112
+ tchat --help Show command and keyboard help
113
+ tchat --version Print the installed version
114
+ ```
115
+
116
+ `--help` and `--version` work without a TTY, which makes them suitable for
117
+ scripts and CI. The interactive application itself requires a TTY.
118
+
119
+ ## First run and identity
120
+
121
+ On the first launch, TerminalChat asks for a display name and creates a
122
+ cryptographic identity:
123
+
124
+ ```text
125
+ Welcome to TerminalChat! Enter your display name: Alice
126
+ ```
127
+
128
+ The identity consists of:
129
+
130
+ - A public key, which identifies you to friends.
131
+ - A secret key, which must remain private to your device.
132
+ - A display name, which is only a human-readable label.
133
+
134
+ The identity is saved under `~/.terminalchat/identity.json` with restrictive
135
+ file permissions. Existing identities are reused automatically on subsequent
136
+ launches, so friends continue to recognize the same device.
137
+
138
+ Your display name can change without changing your identity. The public key is
139
+ the actual identity used by the network.
140
+
141
+ ## Using the TUI
142
+
143
+ The main screen contains two panes:
144
+
145
+ ```text
146
+ ┌──────────────────────────┬─────────────────────────────────────────────┐
147
+ │ Friends │ Chat with Bob │
148
+ │ │ │
149
+ │ ● Bob │ Bob: Hello │
150
+ │ ○ Carol │ you: Hi ✓ │
151
+ │ │ │
152
+ │ │ > Type a message │
153
+ └──────────────────────────┴─────────────────────────────────────────────┘
154
+ ```
155
+
156
+ ### Keyboard controls
157
+
158
+ | Key | Action |
159
+ |---|---|
160
+ | `Tab` | Switch focus between the friend list and message input |
161
+ | `↑` / `↓` | Move through friends when the sidebar is focused |
162
+ | `Enter` | Send the message in the input; select a focused friend |
163
+ | `Ctrl+N` | Open the actions menu |
164
+ | `Esc` | Close the current menu or overlay |
165
+ | `Ctrl+C` | Shut down cleanly and quit |
166
+
167
+ The actions menu provides:
168
+
169
+ - **Invite** — create a one-time invite code.
170
+ - **Add friend** — add a known public key manually.
171
+ - **Join** — enter a friend's invite code.
172
+ - **Who am I?** — display your name and public key.
173
+ - **History** — view recent messages for the selected friend.
174
+
175
+ Messages sent by you show:
176
+
177
+ - `…` while they are waiting for delivery acknowledgement.
178
+ - `✓` after the receiving peer has acknowledged them.
179
+
180
+ Incoming messages for a friend other than the currently selected conversation
181
+ increase that friend's unread badge.
182
+
183
+ ## Adding friends
184
+
185
+ The recommended way to connect two installations is the invite flow.
186
+
187
+ ### Step 1: Create an invite
188
+
189
+ On the inviter's device:
190
+
191
+ 1. Launch `tchat`.
192
+ 2. Press `Ctrl+N`.
193
+ 3. Choose **Invite**.
194
+ 4. Copy the displayed code and send it to the other person through a trusted
195
+ channel.
196
+
197
+ An invite contains the inviter's public key and a random secret. It does not
198
+ contain your private key or message history.
199
+
200
+ ### Step 2: Join the invite
201
+
202
+ On the joiner's device:
203
+
204
+ 1. Launch `tchat`.
205
+ 2. Press `Ctrl+N`.
206
+ 3. Choose **Join**.
207
+ 4. Paste the invite code.
208
+ 5. Press `Enter`.
209
+
210
+ The joiner connects to the inviter, both peers exchange display names, and the
211
+ new conversation is focused automatically.
212
+
213
+ ### Invite lifetime
214
+
215
+ Invites are:
216
+
217
+ - Valid for up to **24 hours**.
218
+ - Valid for **one successful use**.
219
+ - Stored only by the inviter until they expire or are consumed.
220
+
221
+ Treat an invite code like a short-lived access credential. Anyone who obtains a
222
+ valid unused code can use it to initiate the corresponding friendship.
223
+
224
+ ### Manual public-key setup
225
+
226
+ If both people already know and trust each other's public keys, use **Add
227
+ friend** instead:
228
+
229
+ 1. Press `Ctrl+N`.
230
+ 2. Choose **Add friend**.
231
+ 3. Enter a display name.
232
+ 4. Enter the friend's 64-character public key in hexadecimal.
233
+ 5. Press `Enter`.
234
+
235
+ Manual setup requires the friend to add your public key as well, unless one
236
+ side completes the invite flow.
237
+
238
+ ## Messaging and delivery
239
+
240
+ TerminalChat stores outgoing messages locally until the receiving peer
241
+ acknowledges them.
242
+
243
+ ### Online delivery
244
+
245
+ When both peers are available:
246
+
247
+ 1. HyperDHT establishes a direct connection.
248
+ 2. The peers authenticate during the Noise handshake.
249
+ 3. Unacknowledged messages are sent in sequence-number order.
250
+ 4. The receiver writes each new message to local history.
251
+ 5. The receiver sends a cumulative acknowledgement.
252
+ 6. The sender removes acknowledged messages from its outbox.
253
+
254
+ ### Offline delivery
255
+
256
+ If a friend is offline, messages remain in the sender's local outbox. When the
257
+ friend starts TerminalChat and the connection is established, the queued
258
+ messages are flushed automatically.
259
+
260
+ There is no hosted mailbox or relay. Both peers must eventually be online at
261
+ the same time for delivery to complete.
262
+
263
+ ### Ordering and duplicates
264
+
265
+ Every outgoing message has a monotonically increasing sequence number per
266
+ friend. The receiver tracks the highest contiguous sequence it has received.
267
+ Out-of-order messages can be held until a missing message arrives.
268
+
269
+ Messages are also deduplicated against persisted history. A reconnect or
270
+ retransmission therefore does not create duplicate visible messages.
271
+
272
+ ## Data and storage
273
+
274
+ By default, TerminalChat stores all local state under:
275
+
276
+ ```text
277
+ ~/.terminalchat/
278
+ ```
279
+
280
+ The directory contains:
281
+
282
+ ```text
283
+ ~/.terminalchat/
284
+ ├── identity.json Device identity and display name
285
+ ├── friends.json Known friends and display names
286
+ ├── invites.json Your pending invite secrets
287
+ ├── outbox.json Unacknowledged outgoing messages
288
+ ├── state.json Sequence and acknowledgement state
289
+ └── history/
290
+ └── <friend-public-key>.jsonl
291
+ ```
292
+
293
+ ### Important storage details
294
+
295
+ - JSON state files are written through a temporary file and rename operation to
296
+ avoid partial writes.
297
+ - `identity.json` is written with mode `0600`.
298
+ - History is append-only JSON Lines data.
299
+ - The secret key is stored locally and is never sent as a wire-protocol field.
300
+ - Deleting the data directory creates a new identity and disconnects the device
301
+ from its previous identity.
302
+
303
+ Back up `~/.terminalchat/` if identity continuity and local history matter.
304
+ Protect backups as carefully as the original directory.
305
+
306
+ ### Custom data directory
307
+
308
+ For development, testing, or isolated profiles, set `TCHAT_DATA_DIR`:
309
+
310
+ ```sh
311
+ TCHAT_DATA_DIR=/tmp/tchat-alice tchat
312
+ ```
313
+
314
+ This is useful for running multiple independent identities on one machine.
315
+ Never point two simultaneously running instances at the same data directory.
316
+
317
+ ## Security and trust model
318
+
319
+ TerminalChat is designed to minimize centralized infrastructure, but users
320
+ still need to make trust decisions.
321
+
322
+ ### What is protected
323
+
324
+ - Connections use HyperDHT's Noise-encrypted transport.
325
+ - Peer identity is authenticated by the remote public key exposed by the
326
+ authenticated connection.
327
+ - Unknown peers are rejected unless they present a valid invite.
328
+ - Invite secrets are random, one-time, and expire after 24 hours.
329
+ - Private identity keys remain in local storage and are not included in chat
330
+ frames.
331
+
332
+ ### What is not protected
333
+
334
+ - Display names are not identities and are not proof of a person's real-world
335
+ identity.
336
+ - Anyone who receives an unused invite can use it.
337
+ - Local messages and keys are readable by anyone who can read your data
338
+ directory or an unprotected backup.
339
+ - The application has no account recovery. Losing the secret key means losing
340
+ access to that identity.
341
+ - Network metadata required by the underlying DHT may be visible to the DHT
342
+ infrastructure and participating peers.
343
+
344
+ Verify public keys or share invite codes through a trusted channel when
345
+ identity authenticity matters.
346
+
347
+ ## Architecture
348
+
349
+ TerminalChat separates the headless application core from the terminal UI:
350
+
351
+ ```text
352
+ ┌──────────────────────────────┐
353
+ │ Ink TUI │
354
+ │ App / Sidebar / ChatPane │
355
+ │ Overlays / useEngine │
356
+ └──────────────┬───────────────┘
357
+ │ EventEmitter API
358
+ ┌──────────────▼───────────────┐
359
+ │ Engine │
360
+ │ identity / store / outbox │
361
+ │ history / events / lifecycle │
362
+ └──────────────┬───────────────┘
363
+ │ callbacks
364
+ ┌──────────────▼───────────────┐
365
+ │ Network │
366
+ │ HyperDHT / Noise / framing │
367
+ └──────────────────────────────┘
368
+ ```
369
+
370
+ Core modules:
371
+
372
+ | Module | Responsibility |
373
+ |---|---|
374
+ | `src/identity.js` | Create and load the local key pair |
375
+ | `src/store.js` | Atomic JSON persistence and history files |
376
+ | `src/protocol.js` | Newline-delimited JSON framing and invite encoding |
377
+ | `src/outbox.js` | Sequence, acknowledgement, deduplication, and ordering logic |
378
+ | `src/network.js` | HyperDHT server, connections, handshakes, and frames |
379
+ | `src/engine.js` | Application-level bridge between storage and networking |
380
+ | `src/ui/` | Ink presentation and keyboard interaction |
381
+ | `bin/terminalchat.js` | CLI entry point and TTY startup handling |
382
+
383
+ ### Wire protocol
384
+
385
+ The connection uses newline-delimited JSON frames over the encrypted stream:
386
+
387
+ ```json
388
+ {"type":"hello","name":"Alice"}
389
+ {"type":"msg","seq":1,"ts":1730000000000,"body":"Hello"}
390
+ {"type":"ack","upTo":1}
391
+ ```
392
+
393
+ Protocol limits include a maximum line size of 64 KiB and a maximum message
394
+ body size of 8 KiB. Invalid, oversized, or unexpected frames cause the
395
+ connection to be dropped.
396
+
397
+ ## Troubleshooting
398
+
399
+ ### `terminalchat: requires an interactive terminal (TTY)`
400
+
401
+ The main application is an interactive TUI and cannot run with redirected or
402
+ non-interactive stdin/stdout. Run it directly in a terminal:
403
+
404
+ ```sh
405
+ tchat
406
+ ```
407
+
408
+ Use `tchat --help` or `tchat --version` for non-interactive checks.
409
+
410
+ ### `node: command not found` or an unsupported Node version
411
+
412
+ Install Node.js 22 or newer, then verify:
413
+
414
+ ```sh
415
+ node --version
416
+ npm --version
417
+ ```
418
+
419
+ ### A friend appears offline
420
+
421
+ Check the following:
422
+
423
+ 1. Both devices are running TerminalChat.
424
+ 2. The friend was added with the correct public key.
425
+ 3. The network allows outbound UDP/TCP traffic required by HyperDHT.
426
+ 4. The invite has not expired or already been used.
427
+ 5. Restart both clients to retry startup connections.
428
+
429
+ TerminalChat intentionally does not poll continuously for unavailable peers.
430
+
431
+ ### Messages remain pending
432
+
433
+ Pending messages are retained in `outbox.json` until acknowledged. Keep both
434
+ clients online long enough for a connection to form. Do not delete the data
435
+ directory while messages are pending.
436
+
437
+ ### Resetting a development identity
438
+
439
+ To start a fresh local profile, stop TerminalChat and move the data directory
440
+ to a safe location:
441
+
442
+ ```sh
443
+ mv ~/.terminalchat ~/.terminalchat.backup
444
+ ```
445
+
446
+ This creates a new identity on the next launch. Do not do this if you need the
447
+ old identity or queued messages.
448
+
449
+ ## Development
450
+
451
+ Clone the repository and install dependencies:
452
+
453
+ ```sh
454
+ git clone <repository-url>
455
+ cd tchat
456
+ npm install
457
+ ```
458
+
459
+ Useful commands:
460
+
461
+ ```sh
462
+ npm test # Run unit and integration tests
463
+ npm start # Launch the local TUI
464
+ npm pack --dry-run # Inspect the files that would be published
465
+ ```
466
+
467
+ The implementation is ESM-based (`"type": "module"` in `package.json`) and
468
+ uses:
469
+
470
+ - Node.js built-in modules for persistence and process integration.
471
+ - `hyperdht` for peer discovery and encrypted connections.
472
+ - `b4a` for buffer conversion.
473
+ - `ink`, `react`, and `ink-text-input` for the TUI.
474
+
475
+ The networking and storage core is designed to be exercised independently of
476
+ Ink. The integration test constructs two `Engine` instances with separate
477
+ temporary data directories and a local HyperDHT testnet.
478
+
479
+ ## Testing
480
+
481
+ Run the complete suite:
482
+
483
+ ```sh
484
+ npm test
485
+ ```
486
+
487
+ The tests cover:
488
+
489
+ - Sequence allocation and persistence.
490
+ - Cumulative acknowledgements.
491
+ - Out-of-order delivery and gap handling.
492
+ - Duplicate detection.
493
+ - Display ordering.
494
+ - Invite-code base58 encoding and decoding.
495
+ - Protocol validation and size limits.
496
+ - Invite-to-join peer setup.
497
+ - Bidirectional message exchange.
498
+ - Offline queue delivery after restart.
499
+ - Duplicate retransmission behavior.
500
+
501
+ The integration suite uses `hyperdht/testnet.js`, so it does not contact the
502
+ public DHT network.
503
+
504
+ ## Packaging and publishing
505
+
506
+ Inspect the package before publishing:
507
+
508
+ ```sh
509
+ npm pack --dry-run
510
+ ```
511
+
512
+ Create a local tarball:
513
+
514
+ ```sh
515
+ npm pack
516
+ ```
517
+
518
+ Test the tarball in a temporary global prefix:
519
+
520
+ ```sh
521
+ PACKAGE_TARBALL="$(npm pack --silent)"
522
+ PREFIX="$(mktemp -d)"
523
+ npm install --global --prefix "$PREFIX" "$PACKAGE_TARBALL"
524
+ "$PREFIX/bin/tchat" --version
525
+ rm -rf "$PREFIX" "$PACKAGE_TARBALL"
526
+ ```
527
+
528
+ Publish only after running the tests and verifying the package contents:
529
+
530
+ ```sh
531
+ npm publish
532
+ ```
533
+
534
+ The published package includes the CLI, `src/`, and `README.md`; development
535
+ files and tests are excluded by the `files` list in `package.json`.
536
+
537
+ ## Limitations
538
+
539
+ - Both peers must eventually overlap online; there is no hosted relay or
540
+ mailbox.
541
+ - Reconnection is attempted at startup rather than through a continuous
542
+ polling loop.
543
+ - Display names are not unique or independently verified.
544
+ - One data directory represents one identity.
545
+ - Losing `~/.terminalchat/identity.json` permanently loses access to that
546
+ identity.
547
+ - Local history is not synchronized between multiple devices.
548
+ - The TUI requires Node.js 22 or newer and an interactive terminal.
549
+ - Network connectivity may be affected by restrictive firewalls, NATs, or
550
+ blocked UDP/TCP traffic.
551
+
552
+ ## License
553
+
554
+ MIT
@@ -0,0 +1,85 @@
1
+ #!/usr/bin/env node
2
+ import React from 'react'
3
+ import { readFileSync } from 'node:fs'
4
+ import { createInterface } from 'node:readline'
5
+ import { fileURLToPath } from 'node:url'
6
+ import { resolve, dirname } from 'node:path'
7
+
8
+ const __dirname = dirname(fileURLToPath(import.meta.url))
9
+ const pkg = JSON.parse(readFileSync(resolve(__dirname, '../package.json'), 'utf8'))
10
+
11
+ const arg = process.argv[2]
12
+
13
+ if (arg === '--version' || arg === '-v') {
14
+ console.log(pkg.version)
15
+ process.exit(0)
16
+ }
17
+
18
+ if (arg === '--help' || arg === '-h') {
19
+ console.log(`
20
+ TerminalChat (Tchat) v${pkg.version}
21
+ A serverless, peer-to-peer terminal chat over HyperDHT.
22
+
23
+ Usage:
24
+ terminalchat Launch the interactive TUI
25
+ tchat Same as above (short alias)
26
+
27
+ --help, -h Show this help
28
+ --version, -v Print version
29
+
30
+ Inside the TUI:
31
+ ↑ / ↓ Navigate friend list
32
+ Tab Toggle focus sidebar ↔ message input
33
+ Enter Select friend / send message
34
+ Ctrl+N Open actions menu (Invite, Add, Join, Whoami, History)
35
+ Esc Close overlay / menu
36
+ Ctrl+C Quit (flushes state to disk)
37
+
38
+ Data is stored in ~/.terminalchat/
39
+ `.trim())
40
+ process.exit(0)
41
+ }
42
+
43
+ // Require a TTY for the TUI
44
+ if (!process.stdout.isTTY) {
45
+ console.error('terminalchat: requires an interactive terminal (TTY).')
46
+ process.exit(1)
47
+ }
48
+
49
+ // Dynamically import Ink + App so non-TTY paths (__help/__version) stay fast
50
+ const { render } = await import('ink')
51
+ const { Engine } = await import('../src/engine.js')
52
+ const { default: App } = await import('../src/ui/App.js')
53
+
54
+ const engine = new Engine({
55
+ namePrompt: () => new Promise(resolve => {
56
+ const rl = createInterface({ input: process.stdin, output: process.stdout })
57
+ rl.question('Welcome to TerminalChat! Enter your display name: ', answer => {
58
+ rl.close()
59
+ resolve(answer.trim() || 'Anonymous')
60
+ })
61
+ }),
62
+ })
63
+
64
+ try {
65
+ await engine.start()
66
+ } catch (error) {
67
+ console.error(`terminalchat: ${error.message}`)
68
+ process.exit(1)
69
+ }
70
+
71
+ const { unmount, waitUntilExit } = render(
72
+ React.createElement(App, { engine }),
73
+ { exitOnCtrlC: false }
74
+ )
75
+
76
+ process.on('SIGINT', () => {
77
+ // App handles Ctrl+C → engine.shutdown() then calls process.exit()
78
+ // This handler is just a safety net in case the App isn't mounted yet.
79
+ engine.shutdown().finally(() => {
80
+ unmount()
81
+ process.exit(0)
82
+ })
83
+ })
84
+
85
+ await waitUntilExit()
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "terminalchat-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "TerminalChat (Tchat) — a serverless, peer-to-peer terminal chat over HyperDHT. No server of ours; NAT hole-punching and Noise encryption built in.",
5
+ "type": "module",
6
+ "bin": {
7
+ "terminalchat": "bin/terminalchat.js",
8
+ "tchat": "bin/terminalchat.js"
9
+ },
10
+ "files": [
11
+ "bin",
12
+ "src",
13
+ "README.md"
14
+ ],
15
+ "scripts": {
16
+ "test": "node --test",
17
+ "start": "node ./bin/terminalchat.js"
18
+ },
19
+ "engines": {
20
+ "node": ">=22"
21
+ },
22
+ "keywords": [
23
+ "chat",
24
+ "p2p",
25
+ "terminal",
26
+ "tui",
27
+ "hyperdht",
28
+ "cli",
29
+ "serverless",
30
+ "decentralized"
31
+ ],
32
+ "license": "MIT",
33
+ "dependencies": {
34
+ "b4a": "^1.9.0",
35
+ "hyperdht": "^6.36.0",
36
+ "ink": "^8.0.0",
37
+ "ink-text-input": "^6.0.0",
38
+ "react": "^19.3.1"
39
+ }
40
+ }