bstkchat 2.2.0__tar.gz → 2.4.0__tar.gz

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.
@@ -0,0 +1,149 @@
1
+ Metadata-Version: 2.4
2
+ Name: bstkchat
3
+ Version: 2.4.0
4
+ Summary: A real-time Terminal-based Chatting Application using unique room IDs.
5
+ Author: BSTK Developers
6
+ Project-URL: Homepage, https://github.com/BTKcreations/BSTKCHAT
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Environment :: Console
11
+ Requires-Python: >=3.7
12
+ Description-Content-Type: text/markdown
13
+ Requires-Dist: paho-mqtt>=1.6.1
14
+ Requires-Dist: rich>=13.0.0
15
+ Requires-Dist: prompt-toolkit>=3.0.0
16
+ Requires-Dist: cryptography>=41.0.0
17
+ Dynamic: author
18
+ Dynamic: requires-python
19
+
20
+ # BSTK Chat (`bstkchat`)
21
+
22
+ **BSTK Chat** is a real-time, zero-configuration terminal chat client with optional **AES-256-GCM end-to-end encryption (E2EE)**, Rich Markdown rendering, and a modern interactive TUI. Anyone who launches `bstkchat` and enters the same Room ID (and optional password) joins a shared room instantly—no server setup required.
23
+
24
+ ---
25
+
26
+ ## Features
27
+
28
+ - **Browser Web UI (`--web` / `/web`):** Launch a local, token-authenticated browser interface (`bstkchat --web`) with Dark/Light themes, live peer sidebar, file drag-and-drop, and SSE real-time updates—while keeping all E2EE and decentralized chain storage locally on your machine.
29
+ - **Zero Configuration + CLI Flags:** Connects automatically over MQTT (`broker.hivemq.com`) with TLS (`8883`) enabled by default, or use `--nick`, `--room`, `--password`, `--broker`, `--port`, `--no-tls`, `--web`, and `--web-port`.
30
+ - **End-to-End Encryption (E2EE):** Protect rooms with a password using `scrypt` key derivation, per-message random 96-bit nonces, **AES-256-GCM** authenticated encryption, and topic-bound AAD.
31
+ - **Encrypted File Sharing:** Send files up to 512 KB with `/send <filepath>`, verified with SHA-256 and saved safely via `/accept [id]`.
32
+ - **Modern Terminal UI/UX:**
33
+ - Non-blocking input powered by `prompt_toolkit` with `Alt+Enter` multi-line editing (or `/multiline` toggle).
34
+ - Live bottom status bar showing connection state, active `#room`, E2EE badge, online count, logging state, and live `typing...` indicators.
35
+ - Switchable toolbar themes (`/theme dark|light|ansi`) and compact single-line mode (`/compact`).
36
+ - Context-aware autocomplete for `/` commands, `/msg`, `/accept`, `/theme`, `/log`, and `@mentions`, plus `↑`/`↓` command history.
37
+ - **Rich Markdown, DMs & Presence:** Send formatted Markdown, encrypted DMs (`/msg`), audio/mention alerts (`/mute` to toggle), auto-away status, and `/who` user tables.
38
+ - **Decentralized Encrypted Room Chain & Peer Sync:** Every room maintains an append-only, SHA-256 hash-linked encrypted store (`~/.bstkchat/chains/<room>.json`) on each participant's device. When new peers join, online peers automatically sync missing encrypted messages (`/chain`, `/sync`, or `--no-store` to opt out).
39
+ - **Local Logs, History & Search:** Saves sanitized transcripts to `~/.bstkchat/logs/<room>.log` with `/history`, `/search`, `/log on|off|ephemeral`, and saved preferences in `~/.bstkchat/config.json`.
40
+
41
+ ---
42
+
43
+ ## Installation
44
+
45
+ ### Option 1: Using `uv` (Recommended)
46
+ Run without installing:
47
+ ```bash
48
+ uvx bstkchat
49
+ ```
50
+
51
+ Or install globally:
52
+ ```bash
53
+ uv tool install bstkchat
54
+ bstkchat
55
+ ```
56
+
57
+ ### Option 2: Using `pip`
58
+ ```bash
59
+ pip install bstkchat
60
+ bstkchat
61
+ ```
62
+
63
+ ### Option 3: From Source
64
+ ```bash
65
+ git clone https://github.com/BTKcreations/BSTKCHAT.git
66
+ cd BSTKCHAT
67
+ pip install .
68
+ bstkchat
69
+ ```
70
+
71
+ ---
72
+
73
+ ## Quick Start & Examples
74
+
75
+ ### 1. Start a Private Encrypted Room
76
+ 1. Launch `bstkchat`:
77
+ ```bash
78
+ bstkchat
79
+ ```
80
+ 2. Enter your **Nickname** (or press `Enter` for a random `User-XXX` name).
81
+ 3. Enter a **Room ID** (e.g., `dev-sync-42`) or press `Enter` to use the generated phonetic ID (e.g., `quantum-beacon-55`).
82
+ 4. Enter a **Room Password** to enable AES-256-GCM E2EE.
83
+ 5. Share the **Room ID** and **Password** with your teammates—anyone with both can join and decrypt messages.
84
+
85
+ ### 2. Example In-Chat Workflow
86
+ ```text
87
+ # Send Rich Markdown and code snippets
88
+ Alice > Hey @Bob, check this: `pip install bstkchat`
89
+
90
+ # Send an encrypted private Direct Message to Bob
91
+ Alice > /msg Bob Can you review PR #12?
92
+
93
+ # Set your status
94
+ Alice > /status In a meeting
95
+
96
+ # Switch to another encrypted room (use quotes for passwords with spaces)
97
+ Alice > /room release-ops "my secret passphrase"
98
+
99
+ # Check who is online
100
+ Alice > /who
101
+
102
+ # Pause local logging
103
+ Alice > /log off
104
+ ```
105
+
106
+ ---
107
+
108
+ ## Use Cases
109
+
110
+ - **Quick Developer Syncs:** Spin up a temporary room in seconds from any terminal without opening a browser or creating an account.
111
+ - **Pair Programming & Code Sharing:** Share formatted Markdown and code snippets directly in the terminal while staying in your coding workflow.
112
+ - **Ad-Hoc Encrypted Discussions:** Use a shared passphrase for private conversations where payloads are encrypted before leaving your terminal.
113
+ - **Remote / SSH / Headless Environments:** Chat from minimal Linux/Windows/macOS terminals or over SSH sessions where GUI chat apps aren't available.
114
+
115
+ ---
116
+
117
+ ## Slash Commands
118
+
119
+ | Command | Description |
120
+ | :--- | :--- |
121
+ | `/help` | Displays a formatted table of all available commands |
122
+ | `/room <id> [password\|--lock]` | Switches rooms; use `--lock` to prompt for password without saving it in history |
123
+ | `/nick <name>` | Changes your nickname and notifies peers in the room |
124
+ | `/msg <user> <message>` | Sends an encrypted private direct message (DM) to a user |
125
+ | `/send <filepath>` | Sends an encrypted file (up to 512 KB) with SHA-256 verification |
126
+ | `/accept [id]` | Accepts a pending file transfer and saves it to `~/Downloads/bstkchat/` |
127
+ | `/status <text>` | Sets your custom status message (e.g., `AFK`, `Coding`) |
128
+ | `/who` or `/users` | Lists all online participants, statuses, and last-seen times |
129
+ | `/invite` | Prints a copyable `bstkchat --room ...` command to invite others |
130
+ | `/history [N]` | Displays the last `N` lines (default 15) from the room's local log |
131
+ | `/search <query>` | Searches the current room's local log file |
132
+ | `/chain` | Shows the decentralized room chain block count, integrity check, and path |
133
+ | `/sync [N]` | Requests up to `N` missing encrypted messages from online peers |
134
+ | `/log [on\|off\|ephemeral]` | Controls local logging (`ephemeral` deletes the room log on exit) |
135
+ | `/mute` | Toggles terminal bell alerts for mentions, DMs, and file offers |
136
+ | `/compact` | Toggles compact single-line message rendering |
137
+ | `/multiline` | Toggles multi-line input (`Enter` = newline, `Alt+Enter` = send) |
138
+ | `/theme <dark\|light\|ansi>` | Switches the bottom status bar theme |
139
+ | `/web` | Opens the local browser Web UI for the active session |
140
+ | `/clear` | Clears the terminal screen and redraws the room banner |
141
+ | `/exit` or `/quit` | Announces departure and exits cleanly |
142
+
143
+ ---
144
+
145
+ ## Security Notes
146
+
147
+ - **Password-protected rooms** derive a 256-bit key with `scrypt` and encrypt each message using **AES-256-GCM** with a unique random 96-bit nonce and room-topic AAD.
148
+ - **Public rooms (no password)** still use a room-derived key for transport formatting, so anyone who knows the Room ID can read messages—always set a password for confidential chats.
149
+ - **Local logs** are stored in plain text under `~/.bstkchat/logs/` when logging is enabled; use `/log off` if you do not want transcripts saved to disk.
@@ -0,0 +1,130 @@
1
+ # BSTK Chat (`bstkchat`)
2
+
3
+ **BSTK Chat** is a real-time, zero-configuration terminal chat client with optional **AES-256-GCM end-to-end encryption (E2EE)**, Rich Markdown rendering, and a modern interactive TUI. Anyone who launches `bstkchat` and enters the same Room ID (and optional password) joins a shared room instantly—no server setup required.
4
+
5
+ ---
6
+
7
+ ## Features
8
+
9
+ - **Browser Web UI (`--web` / `/web`):** Launch a local, token-authenticated browser interface (`bstkchat --web`) with Dark/Light themes, live peer sidebar, file drag-and-drop, and SSE real-time updates—while keeping all E2EE and decentralized chain storage locally on your machine.
10
+ - **Zero Configuration + CLI Flags:** Connects automatically over MQTT (`broker.hivemq.com`) with TLS (`8883`) enabled by default, or use `--nick`, `--room`, `--password`, `--broker`, `--port`, `--no-tls`, `--web`, and `--web-port`.
11
+ - **End-to-End Encryption (E2EE):** Protect rooms with a password using `scrypt` key derivation, per-message random 96-bit nonces, **AES-256-GCM** authenticated encryption, and topic-bound AAD.
12
+ - **Encrypted File Sharing:** Send files up to 512 KB with `/send <filepath>`, verified with SHA-256 and saved safely via `/accept [id]`.
13
+ - **Modern Terminal UI/UX:**
14
+ - Non-blocking input powered by `prompt_toolkit` with `Alt+Enter` multi-line editing (or `/multiline` toggle).
15
+ - Live bottom status bar showing connection state, active `#room`, E2EE badge, online count, logging state, and live `typing...` indicators.
16
+ - Switchable toolbar themes (`/theme dark|light|ansi`) and compact single-line mode (`/compact`).
17
+ - Context-aware autocomplete for `/` commands, `/msg`, `/accept`, `/theme`, `/log`, and `@mentions`, plus `↑`/`↓` command history.
18
+ - **Rich Markdown, DMs & Presence:** Send formatted Markdown, encrypted DMs (`/msg`), audio/mention alerts (`/mute` to toggle), auto-away status, and `/who` user tables.
19
+ - **Decentralized Encrypted Room Chain & Peer Sync:** Every room maintains an append-only, SHA-256 hash-linked encrypted store (`~/.bstkchat/chains/<room>.json`) on each participant's device. When new peers join, online peers automatically sync missing encrypted messages (`/chain`, `/sync`, or `--no-store` to opt out).
20
+ - **Local Logs, History & Search:** Saves sanitized transcripts to `~/.bstkchat/logs/<room>.log` with `/history`, `/search`, `/log on|off|ephemeral`, and saved preferences in `~/.bstkchat/config.json`.
21
+
22
+ ---
23
+
24
+ ## Installation
25
+
26
+ ### Option 1: Using `uv` (Recommended)
27
+ Run without installing:
28
+ ```bash
29
+ uvx bstkchat
30
+ ```
31
+
32
+ Or install globally:
33
+ ```bash
34
+ uv tool install bstkchat
35
+ bstkchat
36
+ ```
37
+
38
+ ### Option 2: Using `pip`
39
+ ```bash
40
+ pip install bstkchat
41
+ bstkchat
42
+ ```
43
+
44
+ ### Option 3: From Source
45
+ ```bash
46
+ git clone https://github.com/BTKcreations/BSTKCHAT.git
47
+ cd BSTKCHAT
48
+ pip install .
49
+ bstkchat
50
+ ```
51
+
52
+ ---
53
+
54
+ ## Quick Start & Examples
55
+
56
+ ### 1. Start a Private Encrypted Room
57
+ 1. Launch `bstkchat`:
58
+ ```bash
59
+ bstkchat
60
+ ```
61
+ 2. Enter your **Nickname** (or press `Enter` for a random `User-XXX` name).
62
+ 3. Enter a **Room ID** (e.g., `dev-sync-42`) or press `Enter` to use the generated phonetic ID (e.g., `quantum-beacon-55`).
63
+ 4. Enter a **Room Password** to enable AES-256-GCM E2EE.
64
+ 5. Share the **Room ID** and **Password** with your teammates—anyone with both can join and decrypt messages.
65
+
66
+ ### 2. Example In-Chat Workflow
67
+ ```text
68
+ # Send Rich Markdown and code snippets
69
+ Alice > Hey @Bob, check this: `pip install bstkchat`
70
+
71
+ # Send an encrypted private Direct Message to Bob
72
+ Alice > /msg Bob Can you review PR #12?
73
+
74
+ # Set your status
75
+ Alice > /status In a meeting
76
+
77
+ # Switch to another encrypted room (use quotes for passwords with spaces)
78
+ Alice > /room release-ops "my secret passphrase"
79
+
80
+ # Check who is online
81
+ Alice > /who
82
+
83
+ # Pause local logging
84
+ Alice > /log off
85
+ ```
86
+
87
+ ---
88
+
89
+ ## Use Cases
90
+
91
+ - **Quick Developer Syncs:** Spin up a temporary room in seconds from any terminal without opening a browser or creating an account.
92
+ - **Pair Programming & Code Sharing:** Share formatted Markdown and code snippets directly in the terminal while staying in your coding workflow.
93
+ - **Ad-Hoc Encrypted Discussions:** Use a shared passphrase for private conversations where payloads are encrypted before leaving your terminal.
94
+ - **Remote / SSH / Headless Environments:** Chat from minimal Linux/Windows/macOS terminals or over SSH sessions where GUI chat apps aren't available.
95
+
96
+ ---
97
+
98
+ ## Slash Commands
99
+
100
+ | Command | Description |
101
+ | :--- | :--- |
102
+ | `/help` | Displays a formatted table of all available commands |
103
+ | `/room <id> [password\|--lock]` | Switches rooms; use `--lock` to prompt for password without saving it in history |
104
+ | `/nick <name>` | Changes your nickname and notifies peers in the room |
105
+ | `/msg <user> <message>` | Sends an encrypted private direct message (DM) to a user |
106
+ | `/send <filepath>` | Sends an encrypted file (up to 512 KB) with SHA-256 verification |
107
+ | `/accept [id]` | Accepts a pending file transfer and saves it to `~/Downloads/bstkchat/` |
108
+ | `/status <text>` | Sets your custom status message (e.g., `AFK`, `Coding`) |
109
+ | `/who` or `/users` | Lists all online participants, statuses, and last-seen times |
110
+ | `/invite` | Prints a copyable `bstkchat --room ...` command to invite others |
111
+ | `/history [N]` | Displays the last `N` lines (default 15) from the room's local log |
112
+ | `/search <query>` | Searches the current room's local log file |
113
+ | `/chain` | Shows the decentralized room chain block count, integrity check, and path |
114
+ | `/sync [N]` | Requests up to `N` missing encrypted messages from online peers |
115
+ | `/log [on\|off\|ephemeral]` | Controls local logging (`ephemeral` deletes the room log on exit) |
116
+ | `/mute` | Toggles terminal bell alerts for mentions, DMs, and file offers |
117
+ | `/compact` | Toggles compact single-line message rendering |
118
+ | `/multiline` | Toggles multi-line input (`Enter` = newline, `Alt+Enter` = send) |
119
+ | `/theme <dark\|light\|ansi>` | Switches the bottom status bar theme |
120
+ | `/web` | Opens the local browser Web UI for the active session |
121
+ | `/clear` | Clears the terminal screen and redraws the room banner |
122
+ | `/exit` or `/quit` | Announces departure and exits cleanly |
123
+
124
+ ---
125
+
126
+ ## Security Notes
127
+
128
+ - **Password-protected rooms** derive a 256-bit key with `scrypt` and encrypt each message using **AES-256-GCM** with a unique random 96-bit nonce and room-topic AAD.
129
+ - **Public rooms (no password)** still use a room-derived key for transport formatting, so anyone who knows the Room ID can read messages—always set a password for confidential chats.
130
+ - **Local logs** are stored in plain text under `~/.bstkchat/logs/` when logging is enabled; use `/log off` if you do not want transcripts saved to disk.
@@ -0,0 +1,152 @@
1
+ """Decentralized, tamper-evident encrypted hash-chain storage for BSTK Chat rooms."""
2
+
3
+ import hashlib
4
+ import json
5
+ import os
6
+ import threading
7
+ from typing import Dict, List, Optional, Set, Tuple
8
+
9
+ from bstkchat.crypto import sanitize_room_id
10
+
11
+ GENESIS_HASH = "GENESIS"
12
+
13
+
14
+ def compute_block_hash(block: dict) -> str:
15
+ """Computes the SHA-256 integrity hash for a chain block."""
16
+ payload = "|".join([
17
+ str(block.get("prev_hash", GENESIS_HASH)),
18
+ str(block.get("id", "")),
19
+ f"{float(block.get('ts', 0.0)):.6f}",
20
+ str(block.get("time", "")),
21
+ str(block.get("sender", "")),
22
+ str(block.get("type", "message")),
23
+ str(block.get("ciphertext", "")),
24
+ ])
25
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()
26
+
27
+
28
+ class RoomChain:
29
+ """Thread-safe, append-only encrypted message chain stored per room."""
30
+
31
+ def __init__(self, room_id: str, store_dir: str = "", enabled: bool = True):
32
+ self.room_id = sanitize_room_id(room_id)
33
+ self.enabled = enabled
34
+ self._lock = threading.Lock()
35
+ self.store_dir = store_dir or os.path.expanduser("~/.bstkchat/chains")
36
+ self.filepath = os.path.join(self.store_dir, f"{self.room_id}.json")
37
+ self.blocks: List[dict] = []
38
+ self._seen_ids: Set[str] = set()
39
+ if self.enabled:
40
+ self._load()
41
+
42
+ def _load(self) -> None:
43
+ if not os.path.exists(self.filepath):
44
+ return
45
+ try:
46
+ with open(self.filepath, "r", encoding="utf-8") as f:
47
+ data = json.load(f)
48
+ if isinstance(data, list):
49
+ valid_blocks = [
50
+ b for b in data
51
+ if isinstance(b, dict) and b.get("id") and b.get("hash") == compute_block_hash(b)
52
+ ]
53
+ valid_blocks.sort(key=lambda b: (float(b.get("ts", 0.0)), str(b.get("id", ""))))
54
+ self.blocks = valid_blocks
55
+ self._seen_ids = {str(b["id"]) for b in valid_blocks}
56
+ except (OSError, json.JSONDecodeError, ValueError):
57
+ self.blocks = []
58
+ self._seen_ids = set()
59
+
60
+ def _save(self) -> None:
61
+ if not self.enabled:
62
+ return
63
+ try:
64
+ os.makedirs(os.path.dirname(self.filepath), exist_ok=True)
65
+ with open(self.filepath, "w", encoding="utf-8") as f:
66
+ json.dump(self.blocks, f, indent=2)
67
+ except OSError:
68
+ pass
69
+
70
+ def append_message(
71
+ self,
72
+ msg_id: str,
73
+ ts: float,
74
+ time_str: str,
75
+ sender: str,
76
+ msg_type: str,
77
+ ciphertext: str,
78
+ ) -> Optional[dict]:
79
+ """Creates, hashes, and persists a new encrypted block if not already present."""
80
+ if not self.enabled or not msg_id:
81
+ return None
82
+
83
+ with self._lock:
84
+ if msg_id in self._seen_ids:
85
+ return None
86
+
87
+ prev_hash = self.blocks[-1]["hash"] if self.blocks else GENESIS_HASH
88
+ block = {
89
+ "id": msg_id,
90
+ "ts": float(ts),
91
+ "time": time_str,
92
+ "sender": sender,
93
+ "type": msg_type,
94
+ "ciphertext": ciphertext,
95
+ "prev_hash": prev_hash,
96
+ }
97
+ block["hash"] = compute_block_hash(block)
98
+
99
+ self.blocks.append(block)
100
+ self.blocks.sort(key=lambda b: (float(b.get("ts", 0.0)), str(b.get("id", ""))))
101
+ self._seen_ids.add(msg_id)
102
+ self._save()
103
+ return block
104
+
105
+ def merge_blocks(self, incoming_blocks: List[dict]) -> List[dict]:
106
+ """Verifies hashes, deduplicates, merges, and persists blocks from peers."""
107
+ if not self.enabled or not incoming_blocks:
108
+ return []
109
+
110
+ added: List[dict] = []
111
+ with self._lock:
112
+ for block in incoming_blocks:
113
+ if not isinstance(block, dict):
114
+ continue
115
+ msg_id = str(block.get("id", ""))
116
+ if not msg_id or msg_id in self._seen_ids:
117
+ continue
118
+ if block.get("hash") != compute_block_hash(block):
119
+ continue
120
+ self.blocks.append(block)
121
+ self._seen_ids.add(msg_id)
122
+ added.append(block)
123
+
124
+ if added:
125
+ self.blocks.sort(key=lambda b: (float(b.get("ts", 0.0)), str(b.get("id", ""))))
126
+ self._save()
127
+
128
+ added.sort(key=lambda b: (float(b.get("ts", 0.0)), str(b.get("id", ""))))
129
+ return added
130
+
131
+ def get_known_ids(self, limit: int = 500) -> List[str]:
132
+ with self._lock:
133
+ return [str(b["id"]) for b in self.blocks[-limit:]]
134
+
135
+ def get_missing_blocks(self, peer_known_ids: Set[str], limit: int = 100) -> List[dict]:
136
+ with self._lock:
137
+ missing = [b for b in self.blocks if str(b.get("id")) not in peer_known_ids]
138
+ return missing[-limit:]
139
+
140
+ def get_recent_blocks(self, limit: int = 20) -> List[dict]:
141
+ if limit <= 0:
142
+ return []
143
+ with self._lock:
144
+ return list(self.blocks[-limit:])
145
+
146
+ def verify_integrity(self) -> Tuple[bool, int]:
147
+ """Verifies every block's SHA-256 hash in the local chain."""
148
+ with self._lock:
149
+ for block in self.blocks:
150
+ if block.get("hash") != compute_block_hash(block):
151
+ return False, len(self.blocks)
152
+ return True, len(self.blocks)