-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-bans.ts
More file actions
271 lines (236 loc) · 8.32 KB
/
test-bans.ts
File metadata and controls
271 lines (236 loc) · 8.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
#!/usr/bin/env bun
/**
* Ban Management Integration Test
* Tests ban system: duration parser, database, plugin, router enforcement
*/
import { DatabaseManager } from './src/database/db';
import { BanManagerPlugin } from './src/plugins/ban-manager';
import { CommandRouter } from './src/core/command-router';
import { PermissionLevel, BanType } from './src/types/permissions';
import { parseDuration, formatTimeRemaining } from './src/utils/duration-parser';
import { existsSync, rmSync } from 'fs';
const TEST_DB_PATH = './test-data/test-bans-bot.db';
console.log('🧪 Ban Management Integration Test');
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
// Clean up test database
if (existsSync(TEST_DB_PATH)) {
rmSync(TEST_DB_PATH, { force: true });
console.log('✅ Cleaned up old test database\n');
}
// Test 1: Database Initialization
console.log('📝 Test 1: Database Initialization');
const db = new DatabaseManager(TEST_DB_PATH);
console.log('✅ Database initialized successfully');
console.log(` Path: ${TEST_DB_PATH}\n`);
// Test 2: Create Test Users
console.log('📝 Test 2: Create Test Users');
db.upsertUser({
mattermostId: 'test-admin-id',
username: 'test-admin',
permissionLevel: PermissionLevel.ADMIN,
customFlags: [],
createdAt: Date.now(),
updatedAt: Date.now(),
});
console.log('✅ Created admin user');
db.upsertUser({
mattermostId: 'test-spammer-id',
username: 'test-spammer',
permissionLevel: PermissionLevel.USER,
customFlags: [],
createdAt: Date.now(),
updatedAt: Date.now(),
});
console.log('✅ Created spammer user (to be banned)');
db.upsertUser({
mattermostId: 'test-abuser-id',
username: 'test-abuser',
permissionLevel: PermissionLevel.USER,
customFlags: [],
createdAt: Date.now(),
updatedAt: Date.now(),
});
console.log('✅ Created abuser user (to be banned permanently)\n');
// Test 3: Duration Parser
console.log('📝 Test 3: Duration Parser');
try {
const oneHour = parseDuration('1h');
console.log('✅ Parsed "1h":', oneHour ? 'timestamp' : 'failed');
const sevenDays = parseDuration('7d');
console.log('✅ Parsed "7d":', sevenDays ? 'timestamp' : 'failed');
const permanent = parseDuration('permanent');
console.log('✅ Parsed "permanent":', permanent === undefined ? 'undefined (correct)' : 'failed');
// Test formatTimeRemaining
const futureTime = Date.now() + (2 * 60 * 60 * 1000); // 2 hours from now
const formatted = formatTimeRemaining(futureTime);
console.log('✅ Format time remaining:', formatted);
} catch (error) {
console.error('❌ Duration parser failed:', error);
}
console.log();
// Test 4: Temporary Ban Creation
console.log('📝 Test 4: Temporary Ban Creation');
const plugin = new BanManagerPlugin(db);
const tempBanResult = await plugin.handleBan({
mattermostUserId: 'test-admin-id',
mattermostUsername: 'test-admin',
channelId: 'test-channel',
args: ['@test-spammer', 'Spam messages', '24h'],
});
console.log('✅ Temporary ban result:');
console.log(tempBanResult);
console.log();
// Test 5: Check if Banned
console.log('📝 Test 5: Check if Banned');
const isSpammerBanned = db.isBanned('test-spammer-id');
console.log('✅ Spammer is banned:', isSpammerBanned);
const ban = db.getBan('test-spammer-id');
console.log('✅ Ban details:', {
reason: ban?.reason,
banType: ban?.banType,
expiresAt: ban?.expiresAt ? new Date(ban.expiresAt).toISOString() : 'N/A',
});
console.log();
// Test 6: Permanent Ban Creation
console.log('📝 Test 6: Permanent Ban Creation');
const permBanResult = await plugin.handleBan({
mattermostUserId: 'test-admin-id',
mattermostUsername: 'test-admin',
channelId: 'test-channel',
args: ['@test-abuser', 'Abusive behavior', 'permanent'],
});
console.log('✅ Permanent ban result:');
console.log(permBanResult);
console.log();
// Test 7: Ban List
console.log('📝 Test 7: Ban List');
const banlistResult = await plugin.handleBanlist({
mattermostUserId: 'test-admin-id',
mattermostUsername: 'test-admin',
channelId: 'test-channel',
args: [],
});
console.log('✅ Banlist result:');
console.log(banlistResult);
console.log();
// Test 8: Cannot Ban Admin
console.log('📝 Test 8: Cannot Ban Admin');
const banAdminResult = await plugin.handleBan({
mattermostUserId: 'test-admin-id',
mattermostUsername: 'test-admin',
channelId: 'test-channel',
args: ['@test-admin', 'Testing', '1h'],
});
console.log('✅ Ban admin result (should fail):', banAdminResult);
console.log();
// Test 9: Unban User
console.log('📝 Test 9: Unban User');
const unbanResult = await plugin.handleUnban({
mattermostUserId: 'test-admin-id',
mattermostUsername: 'test-admin',
channelId: 'test-channel',
args: ['@test-spammer'],
});
console.log('✅ Unban result:');
console.log(unbanResult);
const isStillBanned = db.isBanned('test-spammer-id');
console.log('✅ Spammer still banned after unban:', isStillBanned);
console.log();
// Test 10: Auto-Expiration (simulate expired ban)
console.log('📝 Test 10: Auto-Expiration of Temporary Bans');
// Create a ban that expired 1 hour ago
const expiredBan = {
mattermostId: 'test-spammer-id',
bannedBy: 'test-admin-id',
reason: 'Expired ban test',
banType: BanType.TEMPORARY,
expiresAt: Date.now() - (60 * 60 * 1000), // 1 hour ago
createdAt: Date.now(),
};
db.createBan(expiredBan);
console.log('✅ Created expired ban (1 hour ago)');
const isExpiredBanned = db.isBanned('test-spammer-id');
console.log('✅ User is banned after checking expired ban:', isExpiredBanned);
console.log(' (Should be false - ban auto-removed)');
console.log();
// Test 11: Router-Level Ban Enforcement
console.log('📝 Test 11: Router-Level Ban Enforcement');
const router = new CommandRouter({
prefix: '!',
enableBuiltins: true,
db: db,
});
// Ban the spammer again for router test
await plugin.handleBan({
mattermostUserId: 'test-admin-id',
mattermostUsername: 'test-admin',
channelId: 'test-channel',
args: ['@test-spammer', 'Router test', '1h'],
});
const routerResult = await router.execute('!ping', {
userId: 'test-spammer-id',
channelId: 'test-channel',
});
console.log('✅ Router enforcement result:');
console.log(' Success:', routerResult.success);
console.log(' Message preview:', routerResult.message.substring(0, 100) + '...');
console.log();
// Test 12: Audit Log Verification
console.log('📝 Test 12: Audit Log Verification');
const auditLogs = db.getAuditLog(10);
console.log(`✅ Retrieved ${auditLogs.length} audit log entries`);
const banEvents = auditLogs.filter(log => log.eventType === 'ban');
console.log(`✅ Found ${banEvents.length} ban-related events`);
for (const log of banEvents) {
const action = (log.details as any)?.action || 'unknown';
const targetUser = (log.details as any)?.targetUsername || 'unknown';
console.log(` - ${action}: @${targetUser}`);
}
console.log();
// Test 13: Permission Denial for Non-Admin
console.log('📝 Test 13: Permission Denial for Non-Admin');
db.upsertUser({
mattermostId: 'test-regular-id',
username: 'test-regular',
permissionLevel: PermissionLevel.USER,
customFlags: [],
createdAt: Date.now(),
updatedAt: Date.now(),
});
const deniedBanResult = await plugin.handleBan({
mattermostUserId: 'test-regular-id',
mattermostUsername: 'test-regular',
channelId: 'test-channel',
args: ['@test-spammer', 'Should fail', '1h'],
});
console.log('✅ Non-admin ban attempt (should fail):', deniedBanResult);
console.log();
// Test 14: Cleanup Expired Bans
console.log('📝 Test 14: Cleanup Expired Bans');
// Create multiple expired bans
for (let i = 0; i < 3; i++) {
db.upsertUser({
mattermostId: `test-expired-${i}`,
username: `expired-${i}`,
permissionLevel: PermissionLevel.USER,
customFlags: [],
createdAt: Date.now(),
updatedAt: Date.now(),
});
db.createBan({
mattermostId: `test-expired-${i}`,
bannedBy: 'test-admin-id',
reason: 'Cleanup test',
banType: BanType.TEMPORARY,
expiresAt: Date.now() - (60 * 1000), // 1 minute ago
createdAt: Date.now(),
});
}
const cleaned = db.cleanupExpiredBans();
console.log(`✅ Cleaned up ${cleaned} expired bans`);
console.log();
// Cleanup
db.close();
console.log('✅ Database closed\n');
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
console.log('✅ All ban management tests passed!\n');