Skip to content

Commit 1fdc0fa

Browse files
committed
docs: comprehensive documentation audit and update
- Update command count from 12 to 15 across all docs - Add /notifications, /stats, /logs, /deleteaccount to all references - Document AES-256-GCM credential encryption (crypto.ts) - Add loot_totals table to database schema documentation - Fix type definition path from src/lib/ to src/bot/api/types/ - Expand test inventory from 3 to 11 files (110+ tests) - Fix DB table names (redeemed_codes, backfill_operations) - Update Bun version from 1.0 to 1.3.14 in docs/mise.md - Add detailed command sections for new commands in full-documentation.md - Update CHANGELOG [Unreleased] with all new features - Update security-assessment with AES-256-GCM and /deleteaccount mitigations - Update .instructions.md and SECURITY.md slash command counts Signed-off-by: Michael Cramer <michael@bigmichi1.de>
1 parent 03e6fb7 commit 1fdc0fa

12 files changed

Lines changed: 369 additions & 90 deletions

.instructions.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ For developers, contributors, and project governance, the following documentatio
135135

136136
- **[docs/system-design.md](docs/system-design.md)** - System architecture and design with:
137137
- All system actors (Discord users, servers, bot, API, database)
138-
- All system actions (9 slash commands, message scanning, backfill, API interactions)
138+
- All system actions (15 slash commands, message scanning, backfill, API interactions)
139139
- Complete data flow diagrams for each major operation
140140
- Component interactions and subsystems
141141
- Database schema and data models
@@ -146,7 +146,7 @@ For developers, contributors, and project governance, the following documentatio
146146
- [OSPS-SA-01.01]
147147

148148
- **[docs/api-reference.md](docs/api-reference.md)** - External software interfaces and API documentation with:
149-
- Discord Bot API: 9 slash commands with full parameter and response documentation
149+
- Discord Bot API: 15 slash commands with full parameter and response documentation
150150
- Discord Message Event API: Automatic code detection patterns and behavior
151151
- Request/response schemas with data types and examples
152152
- Error codes, causes, and resolution procedures

CHANGELOG.md

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,65 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
88

99
### Added
1010

11+
- **`/stats` command** - Server-wide statistics and aggregate loot totals
12+
- Shows total unique codes seen, total redemption events, registered user count
13+
- Displays server-wide aggregate chest and item loot counts from `loot_totals` table
14+
- Available to all users — no special permissions required
15+
16+
- **`/logs` command** - Real-time log viewing for administrators
17+
- Shows last N lines (1–100, default 20) of `logs/combined.log`
18+
- Restricted to users with Discord `Administrator` permission
19+
- Returns ephemeral response
20+
21+
- **`/notifications` command** - Configurable per-user DM notification preferences
22+
- `dm_on_code` (default: false) — DM user when a new code is detected in the channel
23+
- `dm_on_success` (default: true) — DM user when auto-redeem succeeds
24+
- `dm_on_failure` (default: false) — DM user when auto-redeem fails
25+
- With no parameters, shows current preferences
26+
- Settings persisted in `users` table
27+
28+
- **`/deleteaccount` command** - GDPR-compliant self-service account deletion
29+
- Requires explicit confirmation via Yes / Cancel button prompt (30-second timeout)
30+
- Deletes: credentials, all redeemed code records, audit log entries, backfill operation history
31+
- Refuses deletion while a user-initiated backfill is in progress
32+
- Returns per-category deletion summary
33+
34+
- **AES-256-GCM credential encryption** - Credentials now encrypted at rest
35+
- `users.user_id` and `users.user_hash` stored as AES-256-GCM ciphertext (`enc1:<iv>:<authTag>:<ct>`)
36+
- 12-byte random IV and 16-byte auth tag per ciphertext
37+
- Key loaded from `ENCRYPTION_KEY` env var (64-char hex = 32 bytes)
38+
- `isEncrypted()` / `encrypt()` / `decrypt()` helpers in `src/bot/utils/crypto.ts`
39+
- `migratePlaintextCredentials()` in UserManager migrates existing plaintext rows on startup
40+
41+
- **`loot_totals` table** - Aggregate loot cache
42+
- Pre-computed per-user and server-wide loot totals updated on every redemption
43+
- Composite primary key: `(loot_key, scope)` where scope is `discordId` or `__server__`
44+
- `backfillLootTotals()` rebuilds the cache from existing `redeemed_codes` rows
45+
- Powers the `/stats` aggregate loot display
46+
47+
- **Winston structured logging** (`src/bot/utils/logger.ts`)
48+
- Logs to `logs/combined.log` (all levels, 20 rotated files, 5 MB each)
49+
- Logs errors to `logs/error.log` (10 rotated files)
50+
- Console output colour-coded with timestamps
51+
- Default level `info`; override with `LOG_LEVEL=debug` in `.env`
52+
- `/logs` command reads `combined.log` for in-Discord admin access
53+
54+
- **`/backfill` command** - Recover missed codes from channel history (admin only)
55+
- Fetches message history in batches of 100 via Discord API
56+
- Global concurrency lock: only one backfill runs at a time
57+
- Per-user rate limit: 1 backfill per hour
58+
- Startup backfill: runs automatically on bot start if last run was > 6 hours ago
59+
- Progress reported via interaction follow-ups
60+
- Returns `{ codesFound, codesRedeemed, pendingCodes, errors }` summary
61+
62+
- **DM notification fan-out in `bot.ts`** - On code detection
63+
- `getAllUsersWithDmOnCode()` fetches users with `dm_on_code = true`
64+
- Sends a DM to each matching user when a new code is detected in the monitored channel
65+
66+
- **`/codes` pagination** - `/codes` now paginates results (5 per page) with Prev/Next buttons
67+
- `buildCodesPage()` helper generates paginated embeds
68+
- Each entry shows code, status, loot detail, and timestamp
69+
1170
- **`/catchup` command** - Redeem all known valid codes in one step
1271
- Collects every code the bot has seen (successful redeems from any user + pending codes)
1372
- Skips codes already redeemed by the requesting user and codes marked as expired

README.md

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,16 +84,19 @@ See [docker-compose.example.yml](docker-compose.example.yml) for all available c
8484

8585
## ✨ Features
8686

87-
- 🤖 **Slash Commands** - `/setup`, `/redeem`, `/catchup`, `/autoredeem`, `/inventory`, `/open`, `/blacksmith`, `/codes`, `/makepublic`, `/backfill`, `/deleteaccount`, `/help`
87+
- 🤖 **Slash Commands** - `/setup`, `/redeem`, `/catchup`, `/autoredeem`, `/inventory`, `/open`, `/blacksmith`, `/codes`, `/makepublic`, `/backfill`, `/notifications`, `/stats`, `/logs`, `/deleteaccount`, `/help`
8888
- 🔄 **Auto Code Detection** - Scans Discord messages for codes automatically
8989
- ⏮️ **Message History Backfill** - Recover missed codes from message history with built-in rate limiting
9090
- 🔁 **Catch Up** - Redeem all known valid codes in one command (great for new members)
9191
- 🤖 **Auto-Redeem Toggle** - Enable or disable automatic code redemption per user (`/autoredeem`)
92+
- 🔔 **DM Notifications** - Configurable per-user DM alerts for new codes, successes, and failures (`/notifications`)
93+
- 📊 **Server Stats** - Aggregate loot totals and redemption statistics (`/stats`)
9294
- 🎁 **Code Redemption** - Submit codes and get rewards
9395
- 📦 **Chest Management** - Open chests and view loot
9496
- ⚒️ **Blacksmith** - Upgrade heroes with contracts
95-
- 📊 **Inventory** - View gold, rubies, equipment, and progress
97+
- 📋 **Inventory** - View gold, rubies, equipment, and progress
9698
- 🗑️ **Account Deletion** - GDPR-friendly self-service data removal (`/deleteaccount`)
99+
- 🔐 **Encrypted Credentials** - AES-256-GCM encryption for stored user credentials
97100
- 💾 **Secure Storage** - SQLite database keeps credentials safe and local
98101
- 👥 **Multi-User** - Each user manages their own account
99102
-**Fast** - Built on Bun for 3-4x performance vs Node.js

SECURITY.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -521,7 +521,7 @@ For complete dependency management details, see [docs/dependency-management.md](
521521
The project includes comprehensive design documentation describing all actors and actions within the system. See [docs/system-design.md](docs/system-design.md) for:
522522

523523
- **Actors**: Discord users, Discord servers, Discord bot, Idle Champions API, SQLite database
524-
- **Actions**: 9 slash commands, message scanning, backfill operations, API interactions, database operations
524+
- **Actions**: 15 slash commands, message scanning, backfill operations, API interactions, database operations
525525
- **Data Flows**: Complete flow diagrams for each major operation
526526
- **Architecture**: Component interactions, subsystems, deployment
527527
- **Data Models**: User credentials, code history, backfill state, API logs
@@ -532,7 +532,7 @@ The project includes comprehensive design documentation describing all actors an
532532

533533
The project includes complete API documentation for all external software interfaces. See [docs/api-reference.md](docs/api-reference.md) for:
534534

535-
- **Discord Bot API**: 9 slash commands with parameters, responses, and error handling
535+
- **Discord Bot API**: 15 slash commands with parameters, responses, and error handling
536536
- **Command Parameters**: Detailed description of each parameter and valid values
537537
- **Response Formats**: Discord embeds, ephemeral responses, data structures
538538
- **Error Responses**: Error codes, causes, and resolution steps

docs/api-reference.md

Lines changed: 129 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ The Discord bot responds to slash commands in Discord channels. All commands ret
2929

3030
**Response Format**: Discord Embeds (rich message format) or Ephemeral Text
3131

32-
**Total commands**: 12 (`/setup`, `/redeem`, `/catchup`, `/autoredeem`, `/inventory`, `/open`, `/blacksmith`, `/codes`, `/makepublic`, `/backfill`, `/deleteaccount`, `/help`)
32+
**Total commands**: 15 (`/setup`, `/redeem`, `/catchup`, `/autoredeem`, `/inventory`, `/open`, `/blacksmith`, `/codes`, `/makepublic`, `/notifications`, `/stats`, `/logs`, `/backfill`, `/deleteaccount`, `/help`)
3333

3434
---
3535

@@ -754,7 +754,119 @@ Bot (ephemeral): ✅ Account Deleted
754754

755755
---
756756

757-
### 12. `/help`
757+
### 13. `/notifications`
758+
759+
View and update DM notification preferences.
760+
761+
**Invocation**:
762+
```
763+
/notifications [dm_on_code:<true|false>] [dm_on_success:<true|false>] [dm_on_failure:<true|false>]
764+
```
765+
766+
**Parameters**:
767+
768+
| Parameter | Type | Required | Description |
769+
|-----------|------|----------|-------------|
770+
| `dm_on_code` | boolean | No | DM when a new code is detected in the channel (default: false) |
771+
| `dm_on_success` | boolean | No | DM when auto-redeem succeeds (default: true) |
772+
| `dm_on_failure` | boolean | No | DM when auto-redeem fails (default: false) |
773+
774+
**Behaviour**: With no parameters, shows current preferences. With parameters, updates specified preferences.
775+
776+
**Response Format** (Ephemeral):
777+
```
778+
┌─────────────────────────────────────────┐
779+
│ 🔔 Notification Preferences │
780+
│ │
781+
│ DM on code detected: ❌ Off │
782+
│ DM on redeem success: ✅ On │
783+
│ DM on redeem failure: ❌ Off │
784+
└─────────────────────────────────────────┘
785+
```
786+
787+
**Error Responses**:
788+
789+
| Error | Cause | Resolution |
790+
|-------|-------|-----------|
791+
| `NO_CREDENTIALS` | User hasn't run `/setup` | Run `/setup` first |
792+
793+
---
794+
795+
### 14. `/stats`
796+
797+
Show server-wide code redemption statistics and aggregate loot totals.
798+
799+
**Invocation**:
800+
```
801+
/stats
802+
```
803+
804+
**Parameters**: None
805+
806+
**Response Format** (Public Embed):
807+
```
808+
┌───────────────────────────────────────┐
809+
│ 📊 Server Statistics │
810+
│ │
811+
│ Unique codes tracked: 142 │
812+
│ Total redemptions: 1,087 │
813+
│ Registered users: 12 │
814+
│ │
815+
│ **Aggregate Loot (all users)** │
816+
│ Sapphire Chest: 2,340 │
817+
│ Gold Chest: 810 │
818+
│ Modron Chest: 156 │
819+
│ ... │
820+
└───────────────────────────────────────┘
821+
```
822+
823+
**Data Returned**:
824+
- Total unique codes seen by the bot
825+
- Total successful redemption events
826+
- Number of registered users
827+
- Server-wide aggregate chest and item loot counts
828+
829+
---
830+
831+
### 15. `/logs`
832+
833+
Show the last N lines of the bot's combined log file. Admin only.
834+
835+
**Invocation**:
836+
```
837+
/logs [lines:<number>]
838+
```
839+
840+
**Parameters**:
841+
842+
| Parameter | Type | Required | Description |
843+
|-----------|------|----------|-------------|
844+
| `lines` | integer | No | Number of log lines to show (1-100, default: 20) |
845+
846+
**Permissions**: Requires the `Administrator` permission on the Discord server.
847+
848+
**Response Format** (Ephemeral):
849+
```
850+
┌─────────────────────────────────────────────┐
851+
│ 📋 Last 20 log lines │
852+
│ │
853+
│ [2026-05-24 10:15:01] [info] Bot ready │
854+
│ [2026-05-24 10:15:42] [info] Code detected │
855+
│ [2026-05-24 10:15:43] [info] Redeemed OK │
856+
│ ... │
857+
└─────────────────────────────────────────────┘
858+
```
859+
860+
**Error Responses**:
861+
862+
| Error | Cause | Resolution |
863+
|-------|-------|-----------|
864+
| `PERMISSION_DENIED` | User is not an administrator | Requires Administrator permission |
865+
| `LOG_NOT_FOUND` | Log file does not exist | Bot has not run long enough to create logs |
866+
867+
---
868+
869+
### 16. `/help`
758870

759871
Display command reference and usage instructions.
760872

@@ -796,7 +908,13 @@ Display command reference and usage instructions.
796908
│ **Utilities** │
797909
│ /autoredeem enabled:<on|off> │
798910
│ Toggle automatic code redemption │
799-
│ /backfill [channel:<channel>] │
911+
│ /notifications │
912+
│ View/update DM notification preferences │
913+
│ /stats │
914+
│ Server-wide stats and aggregate loot │
915+
│ /logs [lines:<num>] (admin) │
916+
│ Show last N lines of the bot log │
917+
│ /backfill [channel:<channel>] (admin) │
800918
│ Recover codes from message history │
801919
│ /deleteaccount │
802920
│ Permanently delete all your stored data │
@@ -827,18 +945,19 @@ The bot automatically scans all messages in the monitored channel for promo code
827945

828946
**Detection Pattern**:
829947
```regex
830-
\b([A-Z0-9]{4,20})\b
948+
(?:[A-Z0-9*!@#$%^&*]-?){12}(?:(?:[A-Z0-9*!@#$%^&*]-?){4})?
831949
```
832950

951+
Applied after stripping Discord emoji tags (`<:name:id>`, `<a:name:id>`) and URLs from message content.
952+
833953
Matches:
834-
- `IDLE2024`
835-
- `CHAMPIONS500`
836-
- `PROMO100`
954+
- 12-character or 16-character sequences of uppercase alphanumeric and symbol characters
955+
- Characters may be separated by single hyphens (e.g., `ABCD-EFGH-IJKL`)
837956

838957
Does NOT match:
839-
- `ABC` (too short, <4 chars) ❌
840-
- `ABC-123` (contains hyphen) ❌
841-
- `abc123` (all lowercase, needs validation per API) ⚠️
958+
- Shorter sequences (< 12 characters)
959+
- Discord emoji markup (stripped before matching)
960+
- URLs (stripped before matching)
842961

843962
**Detection Behavior**:
844963

0 commit comments

Comments
 (0)