klvrchat 0.0.0-stage → 0.4.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/README.md +82 -2
- package/cli.js +37 -0
- package/client.js +124 -0
- package/discovery.js +75 -0
- package/invite.js +13 -0
- package/package.json +35 -4
- package/server.js +149 -0
- package/share.js +28 -0
package/README.md
CHANGED
|
@@ -1,3 +1,83 @@
|
|
|
1
|
-
#
|
|
1
|
+
# KLVRChat
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A dependency-free Node.js terminal chat prototype.
|
|
4
|
+
|
|
5
|
+
Run `npm start` for the interactive menu, or `npm link` to install the local `klvrchat` command. The package is prepared for public npm publication after release verification.
|
|
6
|
+
|
|
7
|
+
## Getting started
|
|
8
|
+
|
|
9
|
+
Requires Node.js 18 or newer. No npm install needed.
|
|
10
|
+
|
|
11
|
+
In terminal 1:
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
npm run server
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
In terminals 2 and 3:
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
npm run chat
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Choose a different username in each client, then type messages. Use /quit to leave.
|
|
24
|
+
|
|
25
|
+
## Commands
|
|
26
|
+
|
|
27
|
+
- `/join ROOM`: create or enter a room. Everyone starts in lobby.
|
|
28
|
+
- `/rooms`: list active rooms.
|
|
29
|
+
- `/users`: list users in your current room.
|
|
30
|
+
- `/dm USER MESSAGE`: send a direct message to an online user in any room.
|
|
31
|
+
- `/history`: show local history.
|
|
32
|
+
- `/clear`: clear the terminal.
|
|
33
|
+
- `/help`: list commands.
|
|
34
|
+
- `/quit`: disconnect.
|
|
35
|
+
|
|
36
|
+
Emoji and Unicode messages are supported by UTF-8. Username colours are assigned by the server in join order: blue, yellow, red, pink, green, cyan, purple, white, then shades. Active users get distinct palette slots until the palette is exhausted. Set NO_COLOR=1 to disable colours. Update both server and clients together. Private messages are routed only to sender and recipient, but LAN messages are not encrypted. Online TLS protects transport, not end-to-end content.
|
|
37
|
+
|
|
38
|
+
## Local history
|
|
39
|
+
|
|
40
|
+
Type `/history` to display the last 20 saved entries for the current server. Messages and presence notices are appended to a plaintext log under `~/.termichat/`. Clients on the same computer using the same OS account and server address share this log, so duplicate entries are possible. Different computers keep separate copies. Room messages have unique IDs and the server replays up to 100 recent messages per room when you join. The server cache is in memory (up to 100 rooms), so restarts erase it. Private messages are not replayed. Rooms are public to connected users. Local history is shared within an OS account and server address, not isolated by username.
|
|
41
|
+
|
|
42
|
+
## Local Wi-Fi
|
|
43
|
+
|
|
44
|
+
On the host, run `npm run server:lan` (macOS, Linux or Windows). On another device run `npm run discover` and select a discovered server. Discovery uses IPv4 UDP port 5051 and works only when the network permits local broadcasts; manual connection remains available. Discovered servers are not authenticated, so select only a trusted host. On another device with this repository, run `npm run chat -- HOST_IP 5050`, replacing HOST_IP with the host's LAN address. Allow TCP port 5050 and UDP port 5051 through the host firewall only on a trusted private network.
|
|
45
|
+
|
|
46
|
+
## Self-hosted online rooms (experimental)
|
|
47
|
+
|
|
48
|
+
No paid hosting is required. The host runs KLVRChat on their own machine. For connections across networks, use a reachable public IP with TCP port forwarding, or a private overlay network such as Tailscale (both participants must have access). KLVRChat does not implement automatic NAT traversal.
|
|
49
|
+
|
|
50
|
+
Install OpenSSL on the host, then run:
|
|
51
|
+
|
|
52
|
+
```sh
|
|
53
|
+
klvrchat share REACHABLE_IP 5050
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Share the generated TC1 invite privately. Guests run `klvrchat` and select option 7 to paste it, or use `klvrchat join INVITE` (the latter may expose the invite in shell history). The host can join using the same invite in another terminal. The invite includes a random shared secret and the TLS certificate fingerprint; keep it secret and verify it came from the host. A new hosting session generates a new invite. Stop the host process to close the session. Certificate pinning authenticates the host before the client sends its secret. This is not end-to-end encryption or individual identity verification.
|
|
57
|
+
|
|
58
|
+
## Online mode (manual TLS configuration)
|
|
59
|
+
|
|
60
|
+
Use a host with a reachable TCP port, a DNS hostname and a valid TLS certificate and key. Do not commit credentials or certificates' private keys. Configure these environment variables on the server:
|
|
61
|
+
|
|
62
|
+
- TERMICHAT_TOKEN: a randomly generated shared secret (24–256 characters, no whitespace).
|
|
63
|
+
- TERMICHAT_KEY: path to TLS private key.
|
|
64
|
+
- TERMICHAT_CERT: path to certificate chain.
|
|
65
|
+
- PORT: optional TCP port (defaults to 5050).
|
|
66
|
+
|
|
67
|
+
Run `npm run server:online`. On each client, set TERMICHAT_TOKEN to the same secret and run `npm run chat -- chat.example.com 5050 --tls`. The hostname must match the certificate; for a private CA, set TERMICHAT_CA to the trusted CA certificate path. Never disable certificate verification. Online mode has shared access control, not individual accounts or end-to-end encryption. It is not deployed or production audited.
|
|
68
|
+
|
|
69
|
+
## Limitations
|
|
70
|
+
|
|
71
|
+
Prototype only. Messages are plaintext, usernames are not authenticated, and local history is stored unencrypted. Do not expose plaintext LAN mode to the internet or use this prototype for sensitive information.
|
|
72
|
+
|
|
73
|
+
## Roadmap
|
|
74
|
+
|
|
75
|
+
- [x] Local chat history
|
|
76
|
+
- [x] Rooms and private messages
|
|
77
|
+
- [x] Emoji and username colours
|
|
78
|
+
- [x] LAN server discovery
|
|
79
|
+
- [x] Experimental TLS online mode
|
|
80
|
+
- [x] Bounded room replay
|
|
81
|
+
- [x] Local CLI packaging
|
|
82
|
+
- [x] Self-hosted online invites
|
|
83
|
+
- Individual accounts, durable synchronization, automatic NAT traversal, production security testing and npm publication
|
package/cli.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
const { spawn } = require('node:child_process');
|
|
3
|
+
const readline = require('node:readline');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
function run(command, args = []) {
|
|
6
|
+
const env = { ...process.env };
|
|
7
|
+
if (command === 'join') {
|
|
8
|
+
try { require('./invite').decode(args[0]); } catch { console.error('Invalid invite.'); process.exitCode = 1; return; }
|
|
9
|
+
env.TERMICHAT_INVITE = args.shift(); command = 'chat';
|
|
10
|
+
}
|
|
11
|
+
const files = { share: 'share.js', host: 'server.js', local: 'server.js', online: 'server.js', chat: 'client.js', discover: 'discovery.js' };
|
|
12
|
+
if (!files[command]) { console.error('Unknown command. Run klvrchat --help.'); process.exitCode = 1; return; }
|
|
13
|
+
if (command === 'host' || command === 'online') env.HOST = '0.0.0.0';
|
|
14
|
+
if (command === 'online') env.TERMICHAT_TLS = '1';
|
|
15
|
+
const child = spawn(process.execPath, [path.join(__dirname, files[command]), ...args], { env, stdio: 'inherit' });
|
|
16
|
+
child.on('error', error => { console.error(error.message); process.exitCode = 1; });
|
|
17
|
+
child.on('exit', code => { process.exitCode = code ?? 1; });
|
|
18
|
+
}
|
|
19
|
+
const [command, ...args] = process.argv.slice(2);
|
|
20
|
+
if (command === '--help' || command === '-h') {
|
|
21
|
+
console.log('klvrchat [host|local|discover|chat HOST PORT [--tls]|online|share HOST PORT|join INVITE]');
|
|
22
|
+
} else if (command) run(command, args);
|
|
23
|
+
else {
|
|
24
|
+
console.log('\n K L V R C H A T\n 1. Host LAN chat\n 2. Discover LAN servers\n 3. Connect locally\n 4. Connect to online server (TLS)\n 5. Exit\n 6. Host online with invite\n 7. Join with invite\n');
|
|
25
|
+
const input = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
26
|
+
input.question('Select: ', answer => {
|
|
27
|
+
if (answer === '6' || answer === '7') return input.question(answer === '6' ? 'Reachable IP or hostname: ' : 'Private invite: ', value => { input.close(); run(answer === '6' ? 'share' : 'join', [value.trim()]); });
|
|
28
|
+
if (answer === '4') return input.question('Server hostname: ', host => {
|
|
29
|
+
input.question('Port [5050]: ', port => { input.close(); run('chat', [host.trim(), port.trim() || '5050', '--tls']); });
|
|
30
|
+
});
|
|
31
|
+
input.close();
|
|
32
|
+
if (answer === '1') run('host');
|
|
33
|
+
else if (answer === '2') run('discover');
|
|
34
|
+
else if (answer === '3') run('chat');
|
|
35
|
+
else if (answer !== '5') console.error('Invalid selection.');
|
|
36
|
+
});
|
|
37
|
+
}
|
package/client.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
const net = require('node:net');
|
|
2
|
+
const tls = require('node:tls');
|
|
3
|
+
const readline = require('node:readline');
|
|
4
|
+
const fs = require('node:fs');
|
|
5
|
+
const os = require('node:os');
|
|
6
|
+
const path = require('node:path');
|
|
7
|
+
|
|
8
|
+
const args = process.argv.slice(2);
|
|
9
|
+
const invitation = process.env.TERMICHAT_INVITE ? require('./invite').decode(process.env.TERMICHAT_INVITE) : null;
|
|
10
|
+
const secure = !!invitation || args.includes('--tls');
|
|
11
|
+
const positional = args.filter(arg => arg !== '--tls');
|
|
12
|
+
const host = invitation?.host || positional[0] || '127.0.0.1';
|
|
13
|
+
const port = invitation?.port || Number(positional[1] || 5050);
|
|
14
|
+
const token = invitation?.token || process.env.TERMICHAT_TOKEN;
|
|
15
|
+
if (secure && !token) { console.error('Set TERMICHAT_TOKEN before connecting.'); process.exit(1); }
|
|
16
|
+
const historyDir = path.join(os.homedir(), '.termichat');
|
|
17
|
+
const historyFile = path.join(historyDir, Buffer.from((secure ? 'tls:' : '') + host + ':' + port).toString('hex') + '.log');
|
|
18
|
+
let historyEnabled = true;
|
|
19
|
+
try {
|
|
20
|
+
fs.mkdirSync(historyDir, { recursive: true, mode: 0o700 });
|
|
21
|
+
} catch (error) {
|
|
22
|
+
historyEnabled = false;
|
|
23
|
+
console.error('History unavailable: ' + error.message);
|
|
24
|
+
}
|
|
25
|
+
function saveMessage(line) {
|
|
26
|
+
if (!historyEnabled) return;
|
|
27
|
+
try {
|
|
28
|
+
fs.appendFileSync(historyFile, new Date().toISOString() + ' ' + line + '\n', { encoding: 'utf8', mode: 0o600 });
|
|
29
|
+
} catch (error) {
|
|
30
|
+
historyEnabled = false;
|
|
31
|
+
console.error('History unavailable: ' + error.message);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
function showHistory() {
|
|
35
|
+
try {
|
|
36
|
+
if (!historyEnabled || !fs.existsSync(historyFile)) return console.log('No local history yet.');
|
|
37
|
+
const lines = fs.readFileSync(historyFile, 'utf8').trimEnd().split('\n').slice(-20);
|
|
38
|
+
console.log('\n--- Local history (last 20 entries) ---');
|
|
39
|
+
console.log(lines.map(line => line.replace(/^(\S+ )(.*)$/, (_, timestamp, message) => timestamp + formatMessage(message))).join('\n'));
|
|
40
|
+
console.log('--- End of history ---\n');
|
|
41
|
+
} catch (error) {
|
|
42
|
+
console.error('Could not read history: ' + error.message);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
const seenFile = historyFile + '.ids';
|
|
46
|
+
const seen = new Set();
|
|
47
|
+
try {
|
|
48
|
+
if (fs.existsSync(seenFile)) for (const id of fs.readFileSync(seenFile, 'utf8').split('\n')) if (id) seen.add(id);
|
|
49
|
+
} catch {}
|
|
50
|
+
const options = { host, port };
|
|
51
|
+
if (secure) {
|
|
52
|
+
if (!net.isIP(host)) options.servername = host;
|
|
53
|
+
if (invitation) options.rejectUnauthorized = false;
|
|
54
|
+
if (process.env.TERMICHAT_CA) options.ca = fs.readFileSync(process.env.TERMICHAT_CA);
|
|
55
|
+
}
|
|
56
|
+
const socket = secure ? tls.connect(options) : net.createConnection(options);
|
|
57
|
+
let verified = !secure;
|
|
58
|
+
const input = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
59
|
+
socket.setEncoding('utf8');
|
|
60
|
+
const messages = readline.createInterface({ input: socket, crlfDelay: Infinity });
|
|
61
|
+
|
|
62
|
+
socket.on(secure ? 'secureConnect' : 'connect', () => {
|
|
63
|
+
if (invitation && require('./invite').fingerprint(socket.getPeerCertificate()) !== invitation.fingerprint) {
|
|
64
|
+
console.error('Host certificate does not match invite.'); socket.destroy(); return;
|
|
65
|
+
}
|
|
66
|
+
verified = true;
|
|
67
|
+
console.log('\n KLVRCHAT | ' + (secure ? 'ONLINE / TLS' : 'LOCAL / LAN'));
|
|
68
|
+
console.log(' ' + host + ':' + port + ' | /help /history /quit\n');
|
|
69
|
+
});
|
|
70
|
+
const useColor = process.stdout.isTTY && !('NO_COLOR' in process.env) && process.env.TERM !== 'dumb';
|
|
71
|
+
const palette = [34, 33, 31, 95, 32, 36, 35, 37, 94, 93, 91, 92, 96, 90];
|
|
72
|
+
const colors = new Map();
|
|
73
|
+
function colorName(name) {
|
|
74
|
+
if (!useColor) return name;
|
|
75
|
+
const color = colors.get(name.toLowerCase());
|
|
76
|
+
return color ? '\x1b[' + color + 'm' + name + '\x1b[0m' : name;
|
|
77
|
+
}
|
|
78
|
+
function formatMessage(line) {
|
|
79
|
+
line = line.replace(/[\x00-\x1f\x7f-\x9f]/g, '');
|
|
80
|
+
const room = line.match(/^(\[#[\w-]+\] )([\w-]+)(: | (?:joined|left) the chat\.$)(.*)$/u);
|
|
81
|
+
if (room) return room[1] + colorName(room[2]) + room[3] + room[4];
|
|
82
|
+
const dm = line.match(/^\[DM ([\w-]+) -> ([\w-]+)\] (.*)$/u);
|
|
83
|
+
if (dm) return '[DM ' + colorName(dm[1]) + ' -> ' + colorName(dm[2]) + '] ' + dm[3];
|
|
84
|
+
return line;
|
|
85
|
+
}
|
|
86
|
+
messages.on('line', line => {
|
|
87
|
+
if (line === '@auth') {
|
|
88
|
+
if (!secure || !verified) { console.error('Refusing to send token over plaintext.'); return socket.destroy(); }
|
|
89
|
+
return socket.write(token + '\n');
|
|
90
|
+
}
|
|
91
|
+
if (line.startsWith('@message ')) {
|
|
92
|
+
try {
|
|
93
|
+
const entry = JSON.parse(line.slice(9));
|
|
94
|
+
if (!/^[a-f0-9-]{36}$/.test(entry.id) || typeof entry.line !== 'string' || /[\x00-\x1f\x7f-\x9f]/.test(entry.line)) return;
|
|
95
|
+
if (seen.has(entry.id)) return;
|
|
96
|
+
seen.add(entry.id);
|
|
97
|
+
console.log('[' + new Date(entry.time).toLocaleTimeString() + '] ' + formatMessage(entry.line));
|
|
98
|
+
saveMessage(entry.line);
|
|
99
|
+
if (historyEnabled) fs.appendFileSync(seenFile, entry.id + '\n', { mode: 0o600 });
|
|
100
|
+
} catch (error) { console.error('Message/history error: ' + error.message); }
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
const assignment = line.match(/^@color ([a-zA-Z0-9_-]{1,24}) (\d{2})$/);
|
|
104
|
+
if (assignment && palette.includes(Number(assignment[2]))) {
|
|
105
|
+
colors.set(assignment[1].toLowerCase(), Number(assignment[2]));
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
console.log(formatMessage(line.replace(/[\x00-\x1f\x7f-\x9f]/g, '')));
|
|
109
|
+
if (/^(?:\[#[\w-]+\] [\w-]+(?:: | (?:joined|left) the chat\.$)|\[DM [\w-]+ -> [\w-]+\] |[\w-]+(?:: | (?:joined|left) the chat\.$))/.test(line)) saveMessage(line.replace(/[\x00-\x1f\x7f-\x9f]/g, ''));
|
|
110
|
+
});
|
|
111
|
+
input.on('line', line => {
|
|
112
|
+
if (!verified) return;
|
|
113
|
+
if (line === '/history') return showHistory();
|
|
114
|
+
if (line === '/clear') return console.clear();
|
|
115
|
+
if (line === '/quit') {
|
|
116
|
+
socket.end('/quit\n');
|
|
117
|
+
input.close();
|
|
118
|
+
} else if (!socket.destroyed && socket.writable) {
|
|
119
|
+
socket.write(line + '\n');
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
input.on('close', () => { if (!socket.destroyed && socket.writable) socket.end(); });
|
|
123
|
+
socket.on('error', error => { console.error('Connection error: ' + error.message); process.exitCode = 1; });
|
|
124
|
+
socket.on('close', () => { messages.close(); input.close(); });
|
package/discovery.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
const dgram = require('node:dgram');
|
|
2
|
+
const os = require('node:os');
|
|
3
|
+
const readline = require('node:readline');
|
|
4
|
+
const { spawn } = require('node:child_process');
|
|
5
|
+
const path = require('node:path');
|
|
6
|
+
const DISCOVERY_PORT = 5051;
|
|
7
|
+
const PROBE = 'TERMICHAT_DISCOVER_V1';
|
|
8
|
+
function advertise(port) {
|
|
9
|
+
const socket = dgram.createSocket('udp4');
|
|
10
|
+
socket.on('error', error => {
|
|
11
|
+
console.error('LAN discovery unavailable: ' + error.message);
|
|
12
|
+
try { socket.close(); } catch {}
|
|
13
|
+
});
|
|
14
|
+
socket.on('message', (message, peer) => {
|
|
15
|
+
if (message.toString() !== PROBE) return;
|
|
16
|
+
const reply = Buffer.from(JSON.stringify({ service: 'termichat-v1', port }));
|
|
17
|
+
socket.send(reply, peer.port, peer.address, () => {});
|
|
18
|
+
});
|
|
19
|
+
socket.bind(DISCOVERY_PORT, '0.0.0.0');
|
|
20
|
+
return { close() { try { socket.close(); } catch {} } };
|
|
21
|
+
}
|
|
22
|
+
function discover() {
|
|
23
|
+
return new Promise((resolve, reject) => {
|
|
24
|
+
const socket = dgram.createSocket('udp4');
|
|
25
|
+
const found = new Map();
|
|
26
|
+
let timer;
|
|
27
|
+
socket.on('error', error => {
|
|
28
|
+
clearTimeout(timer);
|
|
29
|
+
try { socket.close(); } catch {}
|
|
30
|
+
reject(error);
|
|
31
|
+
});
|
|
32
|
+
socket.on('message', (message, peer) => {
|
|
33
|
+
try {
|
|
34
|
+
const data = JSON.parse(message.toString());
|
|
35
|
+
if (data.service !== 'termichat-v1' || !Number.isInteger(data.port) || data.port < 1 || data.port > 65535) return;
|
|
36
|
+
found.set(peer.address + ':' + data.port, { host: peer.address, port: data.port });
|
|
37
|
+
} catch {}
|
|
38
|
+
});
|
|
39
|
+
socket.bind(0, () => {
|
|
40
|
+
socket.setBroadcast(true);
|
|
41
|
+
const destinations = new Set(['255.255.255.255', '127.0.0.1']);
|
|
42
|
+
for (const addresses of Object.values(os.networkInterfaces())) {
|
|
43
|
+
for (const entry of addresses || []) {
|
|
44
|
+
if (entry.family !== 'IPv4' || entry.internal) continue;
|
|
45
|
+
const ip = entry.address.split('.').map(Number);
|
|
46
|
+
const mask = entry.netmask.split('.').map(Number);
|
|
47
|
+
destinations.add(ip.map((n, i) => (n | (~mask[i] & 255))).join('.'));
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
for (const address of destinations) socket.send(PROBE, DISCOVERY_PORT, address, () => {});
|
|
51
|
+
timer = setTimeout(() => { socket.close(); resolve([...found.values()]); }, 1500);
|
|
52
|
+
});
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
async function main() {
|
|
56
|
+
console.log('Looking for KLVRChat servers on your local network...');
|
|
57
|
+
const servers = await discover();
|
|
58
|
+
if (!servers.length) {
|
|
59
|
+
console.log('No servers found. Start a LAN server or connect manually: npm run chat -- HOST_IP 5050');
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
servers.forEach((server, i) => console.log((i + 1) + '. ' + server.host + ':' + server.port));
|
|
63
|
+
const input = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
64
|
+
input.question('Select a server (number, or q to quit): ', answer => {
|
|
65
|
+
input.close();
|
|
66
|
+
if (answer.trim().toLowerCase() === 'q') return;
|
|
67
|
+
const selected = servers[Number(answer) - 1];
|
|
68
|
+
if (!selected) { console.error('Invalid selection. Run discovery again.'); return; }
|
|
69
|
+
const child = spawn(process.execPath, [path.join(__dirname, 'client.js'), selected.host, String(selected.port)], { stdio: 'inherit' });
|
|
70
|
+
child.on('error', error => { console.error(error.message); process.exitCode = 1; });
|
|
71
|
+
child.on('exit', code => { process.exitCode = code ?? 1; });
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
module.exports = { advertise, discover };
|
|
75
|
+
if (require.main === module) main().catch(error => { console.error(error.message); process.exitCode = 1; });
|
package/invite.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
const crypto = require('node:crypto');
|
|
2
|
+
const net = require('node:net');
|
|
3
|
+
function encode(host, port, token, fingerprint) {
|
|
4
|
+
return 'TC1.' + Buffer.from(JSON.stringify({host,port,token,fingerprint})).toString('base64url');
|
|
5
|
+
}
|
|
6
|
+
function decode(code) {
|
|
7
|
+
if (typeof code !== 'string' || !code.startsWith('TC1.') || code.length > 2048) throw new Error('Invalid invite.');
|
|
8
|
+
const data = JSON.parse(Buffer.from(code.slice(4),'base64url').toString());
|
|
9
|
+
if (!data || typeof data.host !== 'string' || !(net.isIP(data.host) || /^[a-z0-9][a-z0-9.-]{0,252}$/i.test(data.host)) || !Number.isInteger(data.port) || data.port < 1 || data.port > 65535 || !/^[a-f0-9]{64}$/.test(data.token) || !/^[a-f0-9]{64}$/.test(data.fingerprint)) throw new Error('Invalid invite.');
|
|
10
|
+
return data;
|
|
11
|
+
}
|
|
12
|
+
function fingerprint(cert) { return crypto.createHash('sha256').update(cert.raw).digest('hex'); }
|
|
13
|
+
module.exports = {encode,decode,fingerprint};
|
package/package.json
CHANGED
|
@@ -1,6 +1,37 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "klvrchat",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "Terminal chat over TCP",
|
|
5
|
+
"scripts": {
|
|
6
|
+
"server": "node server.js",
|
|
7
|
+
"chat": "node client.js",
|
|
8
|
+
"discover": "node discovery.js",
|
|
9
|
+
"server:lan": "node -e \"process.env.HOST='0.0.0.0';require('./server')\"",
|
|
10
|
+
"start": "node cli.js",
|
|
11
|
+
"server:online": "node cli.js online",
|
|
12
|
+
"test": "node --test",
|
|
13
|
+
"prepublishOnly": "npm test"
|
|
14
|
+
},
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=18"
|
|
17
|
+
},
|
|
18
|
+
"bin": {
|
|
19
|
+
"klvrchat": "cli.js"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"cli.js",
|
|
23
|
+
"client.js",
|
|
24
|
+
"server.js",
|
|
25
|
+
"discovery.js",
|
|
26
|
+
"README.md",
|
|
27
|
+
"invite.js",
|
|
28
|
+
"share.js"
|
|
29
|
+
],
|
|
30
|
+
"repository": {
|
|
31
|
+
"type": "git",
|
|
32
|
+
"url": "git+https://github.com/cloverhimself/TermiChat.git"
|
|
33
|
+
},
|
|
34
|
+
"publishConfig": {
|
|
35
|
+
"access": "public"
|
|
36
|
+
}
|
|
37
|
+
}
|
package/server.js
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
const net = require('node:net');
|
|
2
|
+
const tls = require('node:tls');
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const crypto = require('node:crypto');
|
|
5
|
+
const secure = process.env.TERMICHAT_TLS === '1';
|
|
6
|
+
const secret = process.env.TERMICHAT_TOKEN;
|
|
7
|
+
if (secure && (!secret || secret.length < 24 || secret.length > 256 || /\s/.test(secret))) throw new Error('Online mode requires TERMICHAT_TOKEN of at least 24 characters.');
|
|
8
|
+
const roomHistory = new Map();
|
|
9
|
+
function matchesToken(value) {
|
|
10
|
+
const digest = text => crypto.createHash('sha256').update(text).digest();
|
|
11
|
+
return crypto.timingSafeEqual(digest(value), digest(secret));
|
|
12
|
+
}
|
|
13
|
+
function remember(room, line) {
|
|
14
|
+
if (!roomHistory.has(room)) {
|
|
15
|
+
if (roomHistory.size >= 100) roomHistory.delete(roomHistory.keys().next().value);
|
|
16
|
+
roomHistory.set(room, []);
|
|
17
|
+
}
|
|
18
|
+
const entries = roomHistory.get(room);
|
|
19
|
+
entries.push({ id: crypto.randomUUID(), line, time: new Date().toISOString() });
|
|
20
|
+
if (entries.length > 100) entries.shift();
|
|
21
|
+
return entries[entries.length - 1];
|
|
22
|
+
}
|
|
23
|
+
function replay(socket, room) {
|
|
24
|
+
for (const entry of roomHistory.get(room) || []) send(socket, '@message ' + JSON.stringify(entry));
|
|
25
|
+
}
|
|
26
|
+
const host = process.env.HOST || '127.0.0.1';
|
|
27
|
+
const port = Number(process.env.PORT || 5050);
|
|
28
|
+
const clients = new Map();
|
|
29
|
+
const palette = [34, 33, 31, 95, 32, 36, 35, 37, 94, 93, 91, 92, 96, 90];
|
|
30
|
+
function assignColor() {
|
|
31
|
+
const used = new Set([...clients.values()].map(u => u.color));
|
|
32
|
+
return palette.find(color => !used.has(color)) ?? palette[clients.size % palette.length];
|
|
33
|
+
}
|
|
34
|
+
function announceColors(socket) {
|
|
35
|
+
for (const user of clients.values()) send(socket, '@color ' + user.name + ' ' + user.color);
|
|
36
|
+
}
|
|
37
|
+
const validName = /^[a-zA-Z0-9_-]{1,24}$/;
|
|
38
|
+
function send(socket, message) {
|
|
39
|
+
if (!socket.destroyed && socket.writable) {
|
|
40
|
+
if (socket.writableLength > 262144) return socket.destroy();
|
|
41
|
+
socket.write(message + '\n');
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function broadcast(room, message) {
|
|
45
|
+
for (const [socket, user] of clients) if (user.room === room) send(socket, message);
|
|
46
|
+
}
|
|
47
|
+
function handleConnection(socket) {
|
|
48
|
+
if (server.connectionsCount >= 100) return socket.destroy();
|
|
49
|
+
server.connectionsCount = (server.connectionsCount || 0) + 1;
|
|
50
|
+
let authenticated = !secure;
|
|
51
|
+
const authTimer = setTimeout(() => { if (!clients.has(socket)) socket.destroy(); }, 30000);
|
|
52
|
+
let pending = '';
|
|
53
|
+
socket.setEncoding('utf8');
|
|
54
|
+
send(socket, secure ? '@auth' : 'Enter your username:');
|
|
55
|
+
function onLine(line) {
|
|
56
|
+
const value = line.trim();
|
|
57
|
+
if (!value) return;
|
|
58
|
+
if (!authenticated) {
|
|
59
|
+
if (!matchesToken(value)) { send(socket, 'Access denied.'); return socket.end(); }
|
|
60
|
+
authenticated = true;
|
|
61
|
+
return send(socket, 'Enter your username:');
|
|
62
|
+
}
|
|
63
|
+
if (value === '/quit') return socket.end();
|
|
64
|
+
if (value.length > 2000 || /[\x00-\x1f\x7f-\x9f]/.test(value)) {
|
|
65
|
+
return send(socket, 'Invalid message. Use plain text up to 2000 characters.');
|
|
66
|
+
}
|
|
67
|
+
const user = clients.get(socket);
|
|
68
|
+
if (!user) {
|
|
69
|
+
if (!validName.test(value) || [...clients.values()].some(u => u.name.toLowerCase() === value.toLowerCase())) {
|
|
70
|
+
return send(socket, 'Choose a unique username (1-24 letters, numbers, _ or -):');
|
|
71
|
+
}
|
|
72
|
+
clients.set(socket, { name: value, room: 'lobby', color: assignColor() });
|
|
73
|
+
clearTimeout(authTimer);
|
|
74
|
+
announceColors(socket);
|
|
75
|
+
replay(socket, 'lobby');
|
|
76
|
+
for (const other of clients.keys()) if (other !== socket) send(other, '@color ' + value + ' ' + clients.get(socket).color);
|
|
77
|
+
broadcast('lobby', '[#lobby] ' + value + ' joined the chat.');
|
|
78
|
+
return send(socket, 'Type /help for commands.');
|
|
79
|
+
}
|
|
80
|
+
const [command, ...args] = value.split(/\s+/);
|
|
81
|
+
if (command === '/help') return send(socket, '/join ROOM | /rooms | /users | /dm USER MESSAGE | /history | /clear | /quit');
|
|
82
|
+
if (command === '/rooms') return send(socket, 'Rooms: ' + [...new Set(['lobby', ...[...clients.values()].map(u => u.room)])].join(', '));
|
|
83
|
+
if (command === '/users') return send(socket, 'Online in #' + user.room + ': ' + [...clients.values()].filter(u => u.room === user.room).map(u => u.name).join(', '));
|
|
84
|
+
if (command === '/join') {
|
|
85
|
+
if (args.length !== 1 || !validName.test(args[0])) return send(socket, 'Usage: /join ROOM (letters, numbers, _ or -)');
|
|
86
|
+
const room = args[0].toLowerCase();
|
|
87
|
+
if (room === user.room) return send(socket, 'Already in #' + room);
|
|
88
|
+
broadcast(user.room, '[#' + user.room + '] ' + user.name + ' left the chat.');
|
|
89
|
+
user.room = room;
|
|
90
|
+
replay(socket, room);
|
|
91
|
+
return broadcast(room, '[#' + room + '] ' + user.name + ' joined the chat.');
|
|
92
|
+
}
|
|
93
|
+
if (command === '/dm') {
|
|
94
|
+
const match = value.match(/^\/dm\s+(\S+)\s+(.+)$/);
|
|
95
|
+
if (!match) return send(socket, 'Usage: /dm USER MESSAGE');
|
|
96
|
+
const target = [...clients].find(([, u]) => u.name.toLowerCase() === match[1].toLowerCase());
|
|
97
|
+
if (!target) return send(socket, 'User is not online.');
|
|
98
|
+
const message = '[DM ' + user.name + ' -> ' + target[1].name + '] ' + match[2];
|
|
99
|
+
send(socket, message);
|
|
100
|
+
if (target[0] !== socket) send(target[0], message);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
if (value.startsWith('/')) return send(socket, 'Unknown command. Type /help.');
|
|
104
|
+
const entry = remember(user.room, '[#' + user.room + '] ' + user.name + ': ' + value);
|
|
105
|
+
broadcast(user.room, '@message ' + JSON.stringify(entry));
|
|
106
|
+
}
|
|
107
|
+
socket.on('data', chunk => {
|
|
108
|
+
pending += chunk;
|
|
109
|
+
let end;
|
|
110
|
+
while ((end = pending.indexOf('\n')) !== -1) {
|
|
111
|
+
if (end > 4096) return socket.destroy();
|
|
112
|
+
const line = pending.slice(0, end);
|
|
113
|
+
pending = pending.slice(end + 1);
|
|
114
|
+
onLine(line);
|
|
115
|
+
if (socket.destroyed || !socket.writable) return;
|
|
116
|
+
}
|
|
117
|
+
if (pending.length > 4096) socket.destroy();
|
|
118
|
+
});
|
|
119
|
+
socket.on('error', () => socket.destroy());
|
|
120
|
+
socket.on('close', () => {
|
|
121
|
+
clearTimeout(authTimer);
|
|
122
|
+
server.connectionsCount--;
|
|
123
|
+
const user = clients.get(socket);
|
|
124
|
+
clients.delete(socket);
|
|
125
|
+
if (user) broadcast(user.room, '[#' + user.room + '] ' + user.name + ' left the chat.');
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
const server = secure ? tls.createServer({
|
|
129
|
+
key: fs.readFileSync(process.env.TERMICHAT_KEY),
|
|
130
|
+
cert: fs.readFileSync(process.env.TERMICHAT_CERT),
|
|
131
|
+
minVersion: 'TLSv1.2',
|
|
132
|
+
handshakeTimeout: 10000
|
|
133
|
+
}, handleConnection) : net.createServer(handleConnection);
|
|
134
|
+
server.maxConnections = 100;
|
|
135
|
+
server.on('tlsClientError', () => {});
|
|
136
|
+
server.on('error', error => { console.error(error.message); process.exitCode = 1; });
|
|
137
|
+
server.listen(port, host, () => {
|
|
138
|
+
console.log('KLVRChat listening on ' + host + ':' + server.address().port);
|
|
139
|
+
if (secure && process.env.TERMICHAT_INVITE) {
|
|
140
|
+
console.log('Share this private invite with trusted participants:');
|
|
141
|
+
console.log(process.env.TERMICHAT_INVITE);
|
|
142
|
+
console.log('Host stays online until you stop this process.');
|
|
143
|
+
}
|
|
144
|
+
if (!secure && host === '0.0.0.0') {
|
|
145
|
+
const { advertise } = require('./discovery');
|
|
146
|
+
const discovery = advertise(server.address().port);
|
|
147
|
+
server.on('close', () => discovery.close());
|
|
148
|
+
}
|
|
149
|
+
});
|
package/share.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
const crypto = require('node:crypto');
|
|
2
|
+
const fs = require('node:fs');
|
|
3
|
+
const os = require('node:os');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const net = require('node:net');
|
|
6
|
+
const { spawnSync } = require('node:child_process');
|
|
7
|
+
const { encode, fingerprint } = require('./invite');
|
|
8
|
+
const host = process.argv[2];
|
|
9
|
+
if (!host || !(net.isIP(host) || /^[a-z0-9][a-z0-9.-]{0,252}$/i.test(host))) {
|
|
10
|
+
console.error('Usage: klvrchat share REACHABLE_IP_OR_HOSTNAME [PORT]');
|
|
11
|
+
process.exit(1);
|
|
12
|
+
}
|
|
13
|
+
const port = Number(process.argv[3] || 5050);
|
|
14
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('Invalid port.');
|
|
15
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(),'klvrchat-'));
|
|
16
|
+
const key = path.join(dir,'key.pem');
|
|
17
|
+
const cert = path.join(dir,'cert.pem');
|
|
18
|
+
process.on('exit',()=>fs.rmSync(dir,{recursive:true,force:true}));
|
|
19
|
+
const result = spawnSync('openssl',['req','-x509','-newkey','rsa:2048','-nodes','-keyout',key,'-out',cert,'-days','1','-subj','/CN=KLVRChat'],{stdio:'ignore'});
|
|
20
|
+
if (result.status !== 0) {
|
|
21
|
+
console.error('OpenSSL is required for hosting an invite. Install OpenSSL and retry.');
|
|
22
|
+
process.exit(1);
|
|
23
|
+
}
|
|
24
|
+
const token=crypto.randomBytes(32).toString('hex');
|
|
25
|
+
const pin=fingerprint(new crypto.X509Certificate(fs.readFileSync(cert)));
|
|
26
|
+
Object.assign(process.env,{HOST:'0.0.0.0',PORT:String(port),TERMICHAT_TLS:'1',TERMICHAT_TOKEN:token,TERMICHAT_KEY:key,TERMICHAT_CERT:cert});
|
|
27
|
+
process.env.TERMICHAT_INVITE=encode(host,port,token,pin);
|
|
28
|
+
require('./server');
|