@panguard-ai/panguard 0.3.2 → 0.3.4

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.
Files changed (53) hide show
  1. package/dist/cli/auth-guard.d.ts +15 -50
  2. package/dist/cli/auth-guard.d.ts.map +1 -1
  3. package/dist/cli/auth-guard.js +22 -126
  4. package/dist/cli/auth-guard.js.map +1 -1
  5. package/dist/cli/commands/audit.d.ts.map +1 -1
  6. package/dist/cli/commands/audit.js +18 -11
  7. package/dist/cli/commands/audit.js.map +1 -1
  8. package/dist/cli/commands/doctor.d.ts.map +1 -1
  9. package/dist/cli/commands/doctor.js +15 -12
  10. package/dist/cli/commands/doctor.js.map +1 -1
  11. package/dist/cli/commands/guard.d.ts.map +1 -1
  12. package/dist/cli/commands/guard.js +11 -8
  13. package/dist/cli/commands/guard.js.map +1 -1
  14. package/dist/cli/commands/hacktivity.d.ts.map +1 -1
  15. package/dist/cli/commands/hacktivity.js +1 -3
  16. package/dist/cli/commands/hacktivity.js.map +1 -1
  17. package/dist/cli/commands/init.d.ts.map +1 -1
  18. package/dist/cli/commands/init.js.map +1 -1
  19. package/dist/cli/commands/manager.d.ts.map +1 -1
  20. package/dist/cli/commands/manager.js.map +1 -1
  21. package/dist/cli/commands/scan.js +4 -1
  22. package/dist/cli/commands/scan.js.map +1 -1
  23. package/dist/cli/commands/serve.d.ts.map +1 -1
  24. package/dist/cli/commands/serve.js +693 -33
  25. package/dist/cli/commands/serve.js.map +1 -1
  26. package/dist/cli/commands/setup-skill-scan.d.ts.map +1 -1
  27. package/dist/cli/commands/setup-skill-scan.js +31 -11
  28. package/dist/cli/commands/setup-skill-scan.js.map +1 -1
  29. package/dist/cli/commands/setup.d.ts.map +1 -1
  30. package/dist/cli/commands/setup.js +137 -39
  31. package/dist/cli/commands/setup.js.map +1 -1
  32. package/dist/cli/commands/status.js.map +1 -1
  33. package/dist/cli/commands/threat.d.ts.map +1 -1
  34. package/dist/cli/commands/threat.js +213 -0
  35. package/dist/cli/commands/threat.js.map +1 -1
  36. package/dist/cli/commands/upgrade.d.ts +2 -4
  37. package/dist/cli/commands/upgrade.d.ts.map +1 -1
  38. package/dist/cli/commands/upgrade.js +14 -22
  39. package/dist/cli/commands/upgrade.js.map +1 -1
  40. package/dist/cli/commands/whoami.d.ts.map +1 -1
  41. package/dist/cli/commands/whoami.js +5 -1
  42. package/dist/cli/commands/whoami.js.map +1 -1
  43. package/dist/cli/index.js +22 -21
  44. package/dist/cli/index.js.map +1 -1
  45. package/dist/cli/interactive.d.ts.map +1 -1
  46. package/dist/cli/interactive.js +95 -40
  47. package/dist/cli/interactive.js.map +1 -1
  48. package/dist/init/steps.d.ts.map +1 -1
  49. package/dist/init/steps.js.map +1 -1
  50. package/dist/init/wizard-runner.d.ts.map +1 -1
  51. package/dist/init/wizard-runner.js +27 -13
  52. package/dist/init/wizard-runner.js.map +1 -1
  53. package/package.json +13 -7
@@ -11,7 +11,7 @@ import { homedir } from 'node:os';
11
11
  import { fileURLToPath } from 'node:url';
12
12
  import { c, banner } from '@panguard-ai/core';
13
13
  import { PANGUARD_VERSION } from '../../index.js';
14
- import { AuthDB, createAuthHandlers, sendExpirationWarningEmail, initErrorTracking, captureRequestError, generateOpenApiSpec, generateSwaggerHtml, ManagerProxy, } from '@panguard-ai/panguard-auth';
14
+ import { AuthDB, createAuthHandlers, sendExpirationWarningEmail, initErrorTracking, captureRequestError, generateOpenApiSpec, generateSwaggerHtml, ManagerProxy, authenticateRequest, requireAdmin, } from '@panguard-ai/panguard-auth';
15
15
  import { ManagerServer, DEFAULT_MANAGER_CONFIG } from '@panguard-ai/manager';
16
16
  export function serveCommand() {
17
17
  return new Command('serve')
@@ -31,9 +31,6 @@ export function serveCommand() {
31
31
  const errors = [];
32
32
  const warnings = [];
33
33
  // Critical in production
34
- if (isProd && !process.env['JWT_SECRET']) {
35
- errors.push('JWT_SECRET not set in production — refusing to start with fallback key');
36
- }
37
34
  if (isProd && !process.env['PANGUARD_BASE_URL']) {
38
35
  errors.push('PANGUARD_BASE_URL not set in production — OAuth and email links will break');
39
36
  }
@@ -50,15 +47,18 @@ export function serveCommand() {
50
47
  if (!process.env['RESEND_API_KEY'] && !process.env['SMTP_HOST']) {
51
48
  warnings.push('No email config (RESEND_API_KEY or SMTP_HOST) — password reset and waitlist emails disabled');
52
49
  }
53
- if (!isProd && !process.env['JWT_SECRET']) {
54
- warnings.push('JWT_SECRET not set — using fallback key (OK for dev, NOT for production)');
55
- }
56
50
  if (!process.env['SENTRY_DSN']) {
57
51
  warnings.push('SENTRY_DSN not set — error tracking disabled');
58
52
  }
59
- if (!process.env['MANAGER_AUTH_TOKEN']) {
53
+ if (isProd && !process.env['MANAGER_AUTH_TOKEN']) {
54
+ errors.push('MANAGER_AUTH_TOKEN not set in production — Manager API would allow unauthenticated access');
55
+ }
56
+ if (!isProd && !process.env['MANAGER_AUTH_TOKEN']) {
60
57
  warnings.push('MANAGER_AUTH_TOKEN not set — Manager API allows unauthenticated access (OK for dev)');
61
58
  }
59
+ if (!process.env['TC_API_KEY']) {
60
+ warnings.push('TC_API_KEY not set — Threat Cloud write API disabled in production, open in dev');
61
+ }
62
62
  if (errors.length > 0) {
63
63
  console.error(` ${c.critical('FATAL — Missing required environment variables:')}`);
64
64
  for (const e of errors) {
@@ -79,6 +79,88 @@ export function serveCommand() {
79
79
  await initErrorTracking();
80
80
  // Initialize database
81
81
  const db = new AuthDB(options.db);
82
+ // Initialize Threat Cloud database (optional — graceful if unavailable)
83
+ let threatDb = null;
84
+ try {
85
+ const tcMod = '@panguard-ai/threat-cloud';
86
+ const tc = await import(/* webpackIgnore: true */ tcMod);
87
+ const threatDbPath = join(dirname(options.db), 'threat-cloud.db');
88
+ threatDb = new tc.ThreatCloudDB(threatDbPath);
89
+ console.log(` ${c.safe('Threat Cloud DB')} initialized at ${c.dim(threatDbPath)}`);
90
+ // Auto-seed rules on first startup if rules table is empty
91
+ const stats = threatDb.getStats();
92
+ if (stats.totalRules === 0) {
93
+ console.log(` ${c.sage('Seeding rules...')} (first startup detected)`);
94
+ const seeded = await seedRulesFromBundled(threatDb);
95
+ console.log(` ${c.safe(`Seeded ${seeded} rules`)} into Threat Cloud DB`);
96
+ }
97
+ else {
98
+ console.log(` ${c.dim(`Threat Cloud: ${stats.totalRules} rules, ${stats.totalThreats} threats`)}`);
99
+ }
100
+ console.log('');
101
+ }
102
+ catch {
103
+ console.log(` ${c.dim('Threat Cloud DB not available — threat API routes disabled')}`);
104
+ console.log('');
105
+ }
106
+ // Initialize LLM Reviewer for ATR proposals (optional — needs ANTHROPIC_API_KEY)
107
+ let llmReviewer = null;
108
+ if (threatDb && process.env['ANTHROPIC_API_KEY']) {
109
+ try {
110
+ const tcMod = '@panguard-ai/threat-cloud';
111
+ const tc = await import(/* webpackIgnore: true */ tcMod);
112
+ llmReviewer = new tc.LLMReviewer(process.env['ANTHROPIC_API_KEY'], threatDb);
113
+ console.log(` ${c.safe('LLM Reviewer')} enabled for ATR proposal review`);
114
+ }
115
+ catch {
116
+ console.log(` ${c.dim('LLM Reviewer not available')}`);
117
+ }
118
+ }
119
+ // Promotion cron: every 15 minutes, promote confirmed + LLM-approved proposals to rules
120
+ let promotionTimer = null;
121
+ if (threatDb) {
122
+ promotionTimer = setInterval(() => {
123
+ try {
124
+ const promoted = threatDb.promoteConfirmedProposals();
125
+ if (promoted > 0) {
126
+ console.log(` [Promotion] ${promoted} proposal(s) promoted to rules`);
127
+ }
128
+ }
129
+ catch (err) {
130
+ console.error(` [Promotion] Error: ${err instanceof Error ? err.message : String(err)}`);
131
+ }
132
+ }, 15 * 60 * 1000);
133
+ }
134
+ // Periodic database backup (every 6 hours)
135
+ let backupTimer = null;
136
+ if (threatDb) {
137
+ try {
138
+ const tcMod2 = '@panguard-ai/threat-cloud';
139
+ const tc2 = await import(/* webpackIgnore: true */ tcMod2);
140
+ const backupDir = join(dirname(options.db), 'backups');
141
+ const threatBackup = new tc2.BackupManager(join(dirname(options.db), 'threat-cloud.db'), backupDir, 7);
142
+ const authBackup = new tc2.BackupManager(options.db, backupDir, 7);
143
+ const runBackups = () => {
144
+ try {
145
+ const r1 = threatBackup.backup();
146
+ const r2 = authBackup.backup();
147
+ console.log(` [Backup] threat-cloud.db (${tc2.BackupManager.formatSize(r1.sizeBytes)}), auth.db (${tc2.BackupManager.formatSize(r2.sizeBytes)})`);
148
+ }
149
+ catch (err) {
150
+ console.error(` [Backup] Failed: ${err instanceof Error ? err.message : String(err)}`);
151
+ }
152
+ };
153
+ // Initial backup on startup
154
+ runBackups();
155
+ // Every 6 hours
156
+ backupTimer = setInterval(runBackups, 6 * 60 * 60 * 1000);
157
+ if (backupTimer.unref)
158
+ backupTimer.unref();
159
+ }
160
+ catch {
161
+ console.log(` ${c.dim('Backup manager not available — auto-backups disabled')}`);
162
+ }
163
+ }
82
164
  // Build config from environment
83
165
  // Prefer Resend API when RESEND_API_KEY is set; fall back to raw SMTP
84
166
  const emailConfig = process.env['RESEND_API_KEY']
@@ -144,7 +226,7 @@ export function serveCommand() {
144
226
  ];
145
227
  const adminDir = adminDirs.find((d) => existsSync(d));
146
228
  const server = createServer((req, res) => {
147
- void handleRequest(req, res, handlers, db, adminDir, managerProxy);
229
+ void handleRequest(req, res, handlers, db, adminDir, managerProxy, threatDb, llmReviewer);
148
230
  });
149
231
  // Build Manager config from environment / 從環境變數建構 Manager 設定
150
232
  const managerPort = parseInt(options.managerPort, 10);
@@ -174,6 +256,11 @@ export function serveCommand() {
174
256
  console.log(` ${c.dim('/openapi.json')} OpenAPI 3.0 Spec`);
175
257
  console.log(` ${c.dim('/health')} Health check`);
176
258
  console.log(` ${c.dim('/api/manager/*')} Manager API (port ${managerPort})`);
259
+ if (threatDb) {
260
+ console.log(` ${c.dim('/api/threats')} Threat Cloud API (POST)`);
261
+ console.log(` ${c.dim('/api/rules')} Rule Distribution (GET/POST)`);
262
+ console.log(` ${c.dim('/api/stats')} Threat Statistics (GET)`);
263
+ }
177
264
  console.log('');
178
265
  console.log(` Services:`);
179
266
  console.log(` Email: ${emailConfig ? ('apiKey' in emailConfig ? c.safe('Resend API') : c.safe('SMTP')) : c.caution('Not configured')}`);
@@ -183,10 +270,13 @@ export function serveCommand() {
183
270
  console.log(` Manager: ${c.safe(`port ${managerPort}`)}${process.env['MANAGER_AUTH_TOKEN'] ? '' : c.dim(' (no auth)')}`);
184
271
  console.log('');
185
272
  // Start Manager server after auth server is listening / 在 Auth 伺服器啟動後啟動 Manager 伺服器
186
- managerServer.start().then(() => {
273
+ managerServer
274
+ .start()
275
+ .then(() => {
187
276
  console.log(` ${c.safe('Manager server started')} on ${c.bold(`http://${host}:${managerPort}`)}`);
188
277
  console.log('');
189
- }).catch((err) => {
278
+ })
279
+ .catch((err) => {
190
280
  const message = err instanceof Error ? err.message : String(err);
191
281
  console.log(` ${c.caution('Manager server failed to start:')} ${message}`);
192
282
  console.log(` ${c.dim('Auth server continues running without Manager')}`);
@@ -221,9 +311,15 @@ export function serveCommand() {
221
311
  const shutdown = () => {
222
312
  console.log('\n Shutting down...');
223
313
  clearInterval(planCheckTimer);
314
+ if (backupTimer)
315
+ clearInterval(backupTimer);
316
+ if (promotionTimer)
317
+ clearInterval(promotionTimer);
224
318
  managerServer.stop().catch(() => { });
225
319
  server.close(() => {
226
320
  db.close();
321
+ if (threatDb)
322
+ threatDb.close();
227
323
  process.exit(0);
228
324
  });
229
325
  };
@@ -231,7 +327,7 @@ export function serveCommand() {
231
327
  process.on('SIGTERM', shutdown);
232
328
  });
233
329
  }
234
- async function handleRequest(req, res, handlers, _db, adminDir, managerProxy) {
330
+ async function handleRequest(req, res, handlers, _db, adminDir, managerProxy, threatDb, llmReviewer) {
235
331
  const url = req.url ?? '/';
236
332
  const pathname = url.split('?')[0] ?? '/';
237
333
  // Security headers
@@ -275,45 +371,411 @@ async function handleRequest(req, res, handlers, _db, adminDir, managerProxy) {
275
371
  res.end(html);
276
372
  return;
277
373
  }
278
- // Health check (with DB probe + service status)
374
+ // Health check (minimal public response detailed status behind /api/admin/health)
279
375
  if (pathname === '/health') {
280
- const mem = process.memoryUsage();
281
- const services = {
282
- email: !!(process.env['RESEND_API_KEY'] || process.env['SMTP_HOST']),
283
- oauth: !!process.env['GOOGLE_CLIENT_ID'],
284
- billing: !!process.env['LEMON_SQUEEZY_API_KEY'],
285
- errorTracking: !!process.env['SENTRY_DSN'],
286
- };
287
376
  try {
288
377
  _db.healthCheck();
289
378
  sendJson(res, 200, {
290
379
  ok: true,
291
380
  data: {
292
381
  status: 'healthy',
293
- version: process.env['npm_package_version'] ?? '0.0.0',
294
382
  uptime: Math.round(process.uptime()),
295
383
  db: 'connected',
296
- memory: {
297
- rss: Math.round(mem.rss / 1024 / 1024),
298
- heapUsed: Math.round(mem.heapUsed / 1024 / 1024),
299
- },
300
- services,
384
+ threatCloud: threatDb ? 'connected' : 'unavailable',
301
385
  },
302
386
  });
303
387
  }
304
388
  catch {
305
389
  sendJson(res, 503, {
306
390
  ok: false,
307
- data: {
308
- status: 'unhealthy',
309
- uptime: Math.round(process.uptime()),
310
- db: 'disconnected',
311
- services,
312
- },
391
+ data: { status: 'unhealthy', db: 'disconnected' },
313
392
  });
314
393
  }
315
394
  return;
316
395
  }
396
+ // Detailed health (admin-only) — includes memory, services, threat stats
397
+ if (pathname === '/api/admin/health' && req.method === 'GET') {
398
+ const mem = process.memoryUsage();
399
+ const services = {
400
+ email: !!(process.env['RESEND_API_KEY'] || process.env['SMTP_HOST']),
401
+ oauth: !!process.env['GOOGLE_CLIENT_ID'],
402
+ billing: !!process.env['LEMON_SQUEEZY_API_KEY'],
403
+ errorTracking: !!process.env['SENTRY_DSN'],
404
+ threatCloud: !!threatDb,
405
+ tcApiKey: !!process.env['TC_API_KEY'],
406
+ };
407
+ let threatStats = null;
408
+ if (threatDb) {
409
+ try {
410
+ const s = threatDb.getStats();
411
+ threatStats = { rules: s.totalRules, threats: s.totalThreats };
412
+ }
413
+ catch { /* ignore */ }
414
+ }
415
+ sendJson(res, 200, {
416
+ ok: true,
417
+ data: {
418
+ status: 'healthy',
419
+ version: process.env['npm_package_version'] ?? '0.0.0',
420
+ uptime: Math.round(process.uptime()),
421
+ db: 'connected',
422
+ threatStats,
423
+ memory: { rss: Math.round(mem.rss / 1024 / 1024), heapUsed: Math.round(mem.heapUsed / 1024 / 1024) },
424
+ services,
425
+ },
426
+ });
427
+ return;
428
+ }
429
+ // ── Threat Cloud API Routes ────────────────────────────────────
430
+ // Security: rate limiting, auth, input validation
431
+ // Rate limit for Threat Cloud endpoints (per-IP, shared state)
432
+ if (threatDb && pathname.startsWith('/api/') && ['/api/threats', '/api/rules', '/api/stats', '/api/atr-proposals', '/api/atr-feedback', '/api/skill-threats', '/api/atr-rules', '/api/yara-rules', '/api/feeds/ip-blocklist', '/api/feeds/domain-blocklist'].some((p) => pathname === p)) {
433
+ const clientIP = req.socket.remoteAddress ?? 'unknown';
434
+ if (!checkTCRateLimit(clientIP)) {
435
+ sendJson(res, 429, { ok: false, error: 'Rate limit exceeded. Try again later.' });
436
+ return;
437
+ }
438
+ }
439
+ // POST /api/threats - Upload anonymized threat data
440
+ if (pathname === '/api/threats' && req.method === 'POST') {
441
+ if (!threatDb) {
442
+ sendJson(res, 503, { ok: false, error: 'Threat Cloud not available' });
443
+ return;
444
+ }
445
+ if (!requireTCWriteAuth(req, res))
446
+ return;
447
+ if (!requireJsonContentType(req, res))
448
+ return;
449
+ const body = await readRequestBody(req);
450
+ let data;
451
+ try {
452
+ data = JSON.parse(body);
453
+ }
454
+ catch {
455
+ sendJson(res, 400, { ok: false, error: 'Invalid JSON body' });
456
+ return;
457
+ }
458
+ if (!data['attackSourceIP'] || !data['attackType'] || !data['mitreTechnique'] || !data['sigmaRuleMatched'] || !data['timestamp'] || !data['region']) {
459
+ sendJson(res, 400, { ok: false, error: 'Missing required fields' });
460
+ return;
461
+ }
462
+ // Anonymize IP (zero last octet)
463
+ const ip = String(data['attackSourceIP']);
464
+ if (ip.includes('.')) {
465
+ const parts = ip.split('.');
466
+ if (parts.length === 4) {
467
+ parts[3] = '0';
468
+ data['attackSourceIP'] = parts.join('.');
469
+ }
470
+ }
471
+ threatDb.insertThreat(data);
472
+ sendJson(res, 201, { ok: true, data: { message: 'Threat data received' } });
473
+ return;
474
+ }
475
+ // GET /api/rules - Fetch rules (optional ?since= filter, paginated)
476
+ if (pathname === '/api/rules' && req.method === 'GET') {
477
+ if (!threatDb) {
478
+ sendJson(res, 503, { ok: false, error: 'Threat Cloud not available' });
479
+ return;
480
+ }
481
+ const urlObj = new URL(url, `http://${req.headers.host ?? 'localhost'}`);
482
+ const since = urlObj.searchParams.get('since');
483
+ // Validate since parameter format (ISO 8601)
484
+ if (since && !/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2})?/.test(since)) {
485
+ sendJson(res, 400, { ok: false, error: 'Invalid since parameter: must be ISO 8601' });
486
+ return;
487
+ }
488
+ const rawLimit = parseInt(urlObj.searchParams.get('limit') ?? '1000', 10);
489
+ const limit = isNaN(rawLimit) || rawLimit < 1 ? 1000 : Math.min(rawLimit, 5000);
490
+ const rules = since ? threatDb.getRulesSince(since) : threatDb.getAllRules(limit);
491
+ sendJson(res, 200, { ok: true, data: rules });
492
+ return;
493
+ }
494
+ // POST /api/rules - Publish a new community rule
495
+ if (pathname === '/api/rules' && req.method === 'POST') {
496
+ if (!threatDb) {
497
+ sendJson(res, 503, { ok: false, error: 'Threat Cloud not available' });
498
+ return;
499
+ }
500
+ if (!requireTCWriteAuth(req, res))
501
+ return;
502
+ if (!requireJsonContentType(req, res))
503
+ return;
504
+ const body = await readRequestBody(req);
505
+ let rule;
506
+ try {
507
+ rule = JSON.parse(body);
508
+ }
509
+ catch {
510
+ sendJson(res, 400, { ok: false, error: 'Invalid JSON body' });
511
+ return;
512
+ }
513
+ if (!rule['ruleId'] || !rule['ruleContent'] || !rule['source']) {
514
+ sendJson(res, 400, { ok: false, error: 'Missing required fields: ruleId, ruleContent, source' });
515
+ return;
516
+ }
517
+ // Field-level size limits
518
+ if (String(rule['ruleContent']).length > 65_536) {
519
+ sendJson(res, 400, { ok: false, error: 'ruleContent exceeds maximum size of 64KB' });
520
+ return;
521
+ }
522
+ if (String(rule['ruleId']).length > 256) {
523
+ sendJson(res, 400, { ok: false, error: 'ruleId exceeds maximum length of 256' });
524
+ return;
525
+ }
526
+ rule['publishedAt'] = rule['publishedAt'] || new Date().toISOString();
527
+ threatDb.upsertRule(rule);
528
+ sendJson(res, 201, { ok: true, data: { message: 'Rule published', ruleId: rule['ruleId'] } });
529
+ return;
530
+ }
531
+ // GET /api/stats - Threat statistics
532
+ if (pathname === '/api/stats' && req.method === 'GET') {
533
+ if (!threatDb) {
534
+ sendJson(res, 503, { ok: false, error: 'Threat Cloud not available' });
535
+ return;
536
+ }
537
+ const stats = threatDb.getStats();
538
+ sendJson(res, 200, { ok: true, data: stats });
539
+ return;
540
+ }
541
+ // POST /api/atr-proposals - Submit ATR rule proposal
542
+ if (pathname === '/api/atr-proposals' && req.method === 'POST') {
543
+ if (!threatDb) {
544
+ sendJson(res, 503, { ok: false, error: 'Threat Cloud not available' });
545
+ return;
546
+ }
547
+ if (!requireTCWriteAuth(req, res))
548
+ return;
549
+ if (!requireJsonContentType(req, res))
550
+ return;
551
+ const body = await readRequestBody(req);
552
+ let proposal;
553
+ try {
554
+ proposal = JSON.parse(body);
555
+ }
556
+ catch {
557
+ sendJson(res, 400, { ok: false, error: 'Invalid JSON body' });
558
+ return;
559
+ }
560
+ if (!proposal['patternHash'] || !proposal['ruleContent'] || !proposal['llmProvider'] || !proposal['llmModel'] || !proposal['selfReviewVerdict']) {
561
+ sendJson(res, 400, { ok: false, error: 'Missing required fields' });
562
+ return;
563
+ }
564
+ // Validate and sanitize client ID
565
+ const rawClientId = req.headers['x-panguard-client-id'];
566
+ const clientId = typeof rawClientId === 'string' && /^[a-zA-Z0-9_-]{1,64}$/.test(rawClientId) ? rawClientId : null;
567
+ proposal['clientId'] = clientId;
568
+ // Check if this pattern already has a proposal - if so, increment confirmation
569
+ const pHash = String(proposal['patternHash']);
570
+ const existing = threatDb.getATRProposals().find((p) => p['pattern_hash'] === pHash);
571
+ if (existing) {
572
+ threatDb.confirmATRProposal(pHash);
573
+ sendJson(res, 200, { ok: true, data: { message: 'Confirmation recorded', patternHash: pHash } });
574
+ }
575
+ else {
576
+ threatDb.insertATRProposal(proposal);
577
+ // Fire-and-forget LLM review on first submission
578
+ if (llmReviewer?.isAvailable()) {
579
+ void llmReviewer.reviewProposal(pHash, String(proposal['ruleContent'])).catch((err) => {
580
+ console.error(`LLM review error for ${pHash}:`, err);
581
+ });
582
+ }
583
+ sendJson(res, 201, { ok: true, data: { message: 'Proposal submitted', patternHash: pHash } });
584
+ }
585
+ return;
586
+ }
587
+ // GET /api/atr-proposals - List proposals (admin-only)
588
+ if (pathname === '/api/atr-proposals' && req.method === 'GET') {
589
+ if (!threatDb) {
590
+ sendJson(res, 503, { ok: false, error: 'Threat Cloud not available' });
591
+ return;
592
+ }
593
+ if (!requireTCAdminAuth(req, res, _db))
594
+ return;
595
+ const urlObj = new URL(url, `http://${req.headers.host ?? 'localhost'}`);
596
+ const status = urlObj.searchParams.get('status') ?? undefined;
597
+ const proposals = threatDb.getATRProposals(status);
598
+ sendJson(res, 200, { ok: true, data: proposals });
599
+ return;
600
+ }
601
+ // POST /api/atr-feedback - Report ATR rule match feedback
602
+ if (pathname === '/api/atr-feedback' && req.method === 'POST') {
603
+ if (!threatDb) {
604
+ sendJson(res, 503, { ok: false, error: 'Threat Cloud not available' });
605
+ return;
606
+ }
607
+ if (!requireTCWriteAuth(req, res))
608
+ return;
609
+ if (!requireJsonContentType(req, res))
610
+ return;
611
+ const body = await readRequestBody(req);
612
+ let feedback;
613
+ try {
614
+ feedback = JSON.parse(body);
615
+ }
616
+ catch {
617
+ sendJson(res, 400, { ok: false, error: 'Invalid JSON body' });
618
+ return;
619
+ }
620
+ if (!feedback['ruleId'] || typeof feedback['isTruePositive'] !== 'boolean') {
621
+ sendJson(res, 400, { ok: false, error: 'Missing or invalid fields: ruleId (string), isTruePositive (boolean)' });
622
+ return;
623
+ }
624
+ const rawCid = req.headers['x-panguard-client-id'];
625
+ const cid = typeof rawCid === 'string' && /^[a-zA-Z0-9_-]{1,64}$/.test(rawCid) ? rawCid : null;
626
+ threatDb.insertATRFeedback(String(feedback['ruleId']), feedback['isTruePositive'], cid);
627
+ sendJson(res, 201, { ok: true, data: { message: 'Feedback recorded' } });
628
+ return;
629
+ }
630
+ // POST /api/skill-threats - Submit skill audit result
631
+ if (pathname === '/api/skill-threats' && req.method === 'POST') {
632
+ if (!threatDb) {
633
+ sendJson(res, 503, { ok: false, error: 'Threat Cloud not available' });
634
+ return;
635
+ }
636
+ if (!requireTCWriteAuth(req, res))
637
+ return;
638
+ if (!requireJsonContentType(req, res))
639
+ return;
640
+ const body = await readRequestBody(req);
641
+ let submission;
642
+ try {
643
+ submission = JSON.parse(body);
644
+ }
645
+ catch {
646
+ sendJson(res, 400, { ok: false, error: 'Invalid JSON body' });
647
+ return;
648
+ }
649
+ const VALID_RISK_LEVELS = new Set(['LOW', 'MEDIUM', 'HIGH', 'CRITICAL']);
650
+ if (!submission['skillHash'] || !submission['skillName']) {
651
+ sendJson(res, 400, { ok: false, error: 'Missing required fields: skillHash, skillName' });
652
+ return;
653
+ }
654
+ const riskScore = submission['riskScore'];
655
+ if (typeof riskScore !== 'number' || !isFinite(riskScore) || riskScore < 0 || riskScore > 100) {
656
+ sendJson(res, 400, { ok: false, error: 'riskScore must be a number between 0 and 100' });
657
+ return;
658
+ }
659
+ if (!VALID_RISK_LEVELS.has(String(submission['riskLevel']))) {
660
+ sendJson(res, 400, { ok: false, error: 'riskLevel must be one of: LOW, MEDIUM, HIGH, CRITICAL' });
661
+ return;
662
+ }
663
+ const rawCid2 = req.headers['x-panguard-client-id'];
664
+ submission['clientId'] = typeof rawCid2 === 'string' && /^[a-zA-Z0-9_-]{1,64}$/.test(rawCid2) ? rawCid2 : null;
665
+ threatDb.insertSkillThreat(submission);
666
+ sendJson(res, 201, { ok: true, data: { message: 'Skill threat recorded' } });
667
+ return;
668
+ }
669
+ // GET /api/skill-threats - List skill threats (admin-only)
670
+ if (pathname === '/api/skill-threats' && req.method === 'GET') {
671
+ if (!threatDb) {
672
+ sendJson(res, 503, { ok: false, error: 'Threat Cloud not available' });
673
+ return;
674
+ }
675
+ if (!requireTCAdminAuth(req, res, _db))
676
+ return;
677
+ const urlObj = new URL(url, `http://${req.headers.host ?? 'localhost'}`);
678
+ const rawLimit = parseInt(urlObj.searchParams.get('limit') ?? '50', 10);
679
+ const limit = isNaN(rawLimit) || rawLimit < 1 ? 50 : Math.min(rawLimit, 500);
680
+ const threats = threatDb.getSkillThreats(limit);
681
+ sendJson(res, 200, { ok: true, data: threats });
682
+ return;
683
+ }
684
+ // GET /api/atr-rules - Fetch confirmed ATR rules (for Guard sync)
685
+ if (pathname === '/api/atr-rules' && req.method === 'GET') {
686
+ if (!threatDb) {
687
+ sendJson(res, 503, { ok: false, error: 'Threat Cloud not available' });
688
+ return;
689
+ }
690
+ const urlObj = new URL(url, `http://${req.headers.host ?? 'localhost'}`);
691
+ const since = urlObj.searchParams.get('since') ?? undefined;
692
+ const rules = threatDb.getConfirmedATRRules(since);
693
+ sendJson(res, 200, { ok: true, data: rules });
694
+ return;
695
+ }
696
+ // GET /api/yara-rules - Fetch YARA rules (for Guard sync)
697
+ if (pathname === '/api/yara-rules' && req.method === 'GET') {
698
+ if (!threatDb) {
699
+ sendJson(res, 503, { ok: false, error: 'Threat Cloud not available' });
700
+ return;
701
+ }
702
+ const urlObj = new URL(url, `http://${req.headers.host ?? 'localhost'}`);
703
+ const since = urlObj.searchParams.get('since') ?? undefined;
704
+ const rules = threatDb.getRulesBySource('yara', since);
705
+ sendJson(res, 200, { ok: true, data: rules });
706
+ return;
707
+ }
708
+ // GET /api/feeds/ip-blocklist - IP blocklist feed (plain text)
709
+ if (pathname === '/api/feeds/ip-blocklist' && req.method === 'GET') {
710
+ if (!threatDb) {
711
+ sendJson(res, 503, { ok: false, error: 'Threat Cloud not available' });
712
+ return;
713
+ }
714
+ const urlObj = new URL(url, `http://${req.headers.host ?? 'localhost'}`);
715
+ const minReputation = Number(urlObj.searchParams.get('minReputation') ?? '70');
716
+ const ips = threatDb.getIPBlocklist(minReputation);
717
+ res.setHeader('Content-Type', 'text/plain');
718
+ res.writeHead(200);
719
+ res.end(ips.join('\n'));
720
+ return;
721
+ }
722
+ // GET /api/feeds/domain-blocklist - Domain blocklist feed (plain text)
723
+ if (pathname === '/api/feeds/domain-blocklist' && req.method === 'GET') {
724
+ if (!threatDb) {
725
+ sendJson(res, 503, { ok: false, error: 'Threat Cloud not available' });
726
+ return;
727
+ }
728
+ const urlObj = new URL(url, `http://${req.headers.host ?? 'localhost'}`);
729
+ const minReputation = Number(urlObj.searchParams.get('minReputation') ?? '70');
730
+ const domains = threatDb.getDomainBlocklist(minReputation);
731
+ res.setHeader('Content-Type', 'text/plain');
732
+ res.writeHead(200);
733
+ res.end(domains.join('\n'));
734
+ return;
735
+ }
736
+ // POST /api/skill-whitelist - Report safe skill (audit passed)
737
+ if (pathname === '/api/skill-whitelist' && req.method === 'POST') {
738
+ if (!threatDb) {
739
+ sendJson(res, 503, { ok: false, error: 'Threat Cloud not available' });
740
+ return;
741
+ }
742
+ if (!requireTCWriteAuth(req, res))
743
+ return;
744
+ if (!requireJsonContentType(req, res))
745
+ return;
746
+ const body = await readRequestBody(req);
747
+ let data;
748
+ try {
749
+ data = JSON.parse(body);
750
+ }
751
+ catch {
752
+ sendJson(res, 400, { ok: false, error: 'Invalid JSON body' });
753
+ return;
754
+ }
755
+ const skills = 'skills' in data && Array.isArray(data['skills'])
756
+ ? data['skills']
757
+ : [data];
758
+ let count = 0;
759
+ for (const skill of skills) {
760
+ const name = skill['skillName'];
761
+ if (!name || typeof name !== 'string')
762
+ continue;
763
+ threatDb.reportSafeSkill(name, typeof skill['fingerprintHash'] === 'string' ? skill['fingerprintHash'] : undefined);
764
+ count++;
765
+ }
766
+ sendJson(res, 201, { ok: true, data: { message: `${count} skill(s) reported`, count } });
767
+ return;
768
+ }
769
+ // GET /api/skill-whitelist - Fetch community whitelist
770
+ if (pathname === '/api/skill-whitelist' && req.method === 'GET') {
771
+ if (!threatDb) {
772
+ sendJson(res, 503, { ok: false, error: 'Threat Cloud not available' });
773
+ return;
774
+ }
775
+ const whitelist = threatDb.getSkillWhitelist();
776
+ sendJson(res, 200, { ok: true, data: whitelist });
777
+ return;
778
+ }
317
779
  // Auth API routes
318
780
  if (pathname === '/api/auth/register') {
319
781
  await handlers.handleRegister(req, res);
@@ -545,7 +1007,6 @@ async function handleRequest(req, res, handlers, _db, adminDir, managerProxy) {
545
1007
  smtp: !!process.env['SMTP_HOST'],
546
1008
  },
547
1009
  security: {
548
- jwtSecret: !!process.env['JWT_SECRET'],
549
1010
  totpEnabled: true,
550
1011
  },
551
1012
  threatCloud: {
@@ -765,4 +1226,203 @@ function sendJson(res, status, data) {
765
1226
  res.writeHead(status, { 'Content-Type': 'application/json' });
766
1227
  res.end(JSON.stringify(data));
767
1228
  }
1229
+ // ── Threat Cloud Security Helpers ──────────────────────────────
1230
+ /** Timing-safe string comparison to prevent side-channel attacks */
1231
+ function timingSafeCompare(a, b) {
1232
+ const { timingSafeEqual } = require('node:crypto');
1233
+ const ab = Buffer.from(a);
1234
+ const bb = Buffer.from(b);
1235
+ if (ab.length !== bb.length) {
1236
+ // Compare against self to maintain constant time
1237
+ timingSafeEqual(ab, ab);
1238
+ return false;
1239
+ }
1240
+ return timingSafeEqual(ab, bb);
1241
+ }
1242
+ /**
1243
+ * Require TC_API_KEY auth for write endpoints.
1244
+ * In production: BLOCK if TC_API_KEY not set (refuse unauthenticated writes).
1245
+ * In dev: allow passthrough with warning.
1246
+ */
1247
+ function requireTCWriteAuth(req, res) {
1248
+ const tcApiKey = process.env['TC_API_KEY'];
1249
+ if (!tcApiKey) {
1250
+ if (process.env['NODE_ENV'] === 'production') {
1251
+ sendJson(res, 503, { ok: false, error: 'Threat Cloud write API not configured (TC_API_KEY missing)' });
1252
+ return false;
1253
+ }
1254
+ return true; // dev passthrough
1255
+ }
1256
+ const authHeader = req.headers.authorization ?? '';
1257
+ const token = authHeader.replace('Bearer ', '');
1258
+ if (!timingSafeCompare(token, tcApiKey)) {
1259
+ sendJson(res, 401, { ok: false, error: 'Invalid API key' });
1260
+ return false;
1261
+ }
1262
+ return true;
1263
+ }
1264
+ /**
1265
+ * Require admin session auth for admin-only GET endpoints.
1266
+ * Verifies the Bearer token is a valid session with admin role.
1267
+ */
1268
+ function requireTCAdminAuth(req, res, db) {
1269
+ const user = authenticateRequest(req, db);
1270
+ if (!user) {
1271
+ sendJson(res, 401, { ok: false, error: 'Authentication required' });
1272
+ return false;
1273
+ }
1274
+ if (!requireAdmin(user)) {
1275
+ sendJson(res, 403, { ok: false, error: 'Admin access required' });
1276
+ return false;
1277
+ }
1278
+ return true;
1279
+ }
1280
+ /** Validate Content-Type is application/json for POST requests */
1281
+ function requireJsonContentType(req, res) {
1282
+ const ct = req.headers['content-type'] ?? '';
1283
+ if (!ct.includes('application/json')) {
1284
+ sendJson(res, 400, { ok: false, error: 'Content-Type must be application/json' });
1285
+ return false;
1286
+ }
1287
+ return true;
1288
+ }
1289
+ /** Per-IP rate limiter for Threat Cloud endpoints (120 req/min) */
1290
+ const tcRateLimits = new Map();
1291
+ function checkTCRateLimit(ip) {
1292
+ const now = Date.now();
1293
+ const entry = tcRateLimits.get(ip);
1294
+ if (!entry || now > entry.resetAt) {
1295
+ tcRateLimits.set(ip, { count: 1, resetAt: now + 60_000 });
1296
+ return true;
1297
+ }
1298
+ entry.count++;
1299
+ return entry.count <= 120;
1300
+ }
1301
+ /** Read request body with 1MB size limit */
1302
+ function readRequestBody(req) {
1303
+ return new Promise((resolve, reject) => {
1304
+ const chunks = [];
1305
+ let size = 0;
1306
+ const MAX_BODY = 1_048_576; // 1MB
1307
+ req.on('data', (chunk) => {
1308
+ size += chunk.length;
1309
+ if (size > MAX_BODY) {
1310
+ req.destroy();
1311
+ reject(new Error('Request body too large'));
1312
+ return;
1313
+ }
1314
+ chunks.push(chunk);
1315
+ });
1316
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')));
1317
+ req.on('error', reject);
1318
+ });
1319
+ }
1320
+ /**
1321
+ * Seed rules from bundled config/ directory into Threat Cloud DB.
1322
+ * Reads Sigma YAML, YARA, and ATR YAML files.
1323
+ * Returns count of rules seeded.
1324
+ */
1325
+ async function seedRulesFromBundled(threatDb) {
1326
+ const { readdirSync, readFileSync: readFs, statSync } = await import('node:fs');
1327
+ const { join: joinPath, basename, relative } = await import('node:path');
1328
+ let seeded = 0;
1329
+ const now = new Date().toISOString();
1330
+ // Resolve config directory (Docker: /app/config, monorepo: ../../config)
1331
+ const configDirs = [
1332
+ join(process.cwd(), 'config'),
1333
+ join(dirname(fileURLToPath(import.meta.url)), '..', '..', '..', '..', '..', 'config'),
1334
+ ];
1335
+ const configDir = configDirs.find((d) => {
1336
+ try {
1337
+ return statSync(d).isDirectory();
1338
+ }
1339
+ catch {
1340
+ return false;
1341
+ }
1342
+ });
1343
+ if (!configDir) {
1344
+ console.log(` ${c.dim(' No config/ directory found — skipping rule seeding')}`);
1345
+ return 0;
1346
+ }
1347
+ /** Recursively collect files matching extensions */
1348
+ function collectFiles(dir, extensions) {
1349
+ const results = [];
1350
+ try {
1351
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
1352
+ const fullPath = joinPath(dir, entry.name);
1353
+ if (entry.isDirectory()) {
1354
+ results.push(...collectFiles(fullPath, extensions));
1355
+ }
1356
+ else if (extensions.some((ext) => entry.name.endsWith(ext))) {
1357
+ results.push(fullPath);
1358
+ }
1359
+ }
1360
+ }
1361
+ catch { /* skip unreadable dirs */ }
1362
+ return results;
1363
+ }
1364
+ // 1. Sigma rules (.yml, .yaml)
1365
+ const sigmaDir = joinPath(configDir, 'sigma-rules');
1366
+ try {
1367
+ const sigmaFiles = collectFiles(sigmaDir, ['.yml', '.yaml']);
1368
+ for (const file of sigmaFiles) {
1369
+ const content = readFs(file, 'utf-8');
1370
+ const ruleId = `sigma:${relative(sigmaDir, file).replace(/\//g, ':')}`;
1371
+ threatDb.upsertRule({ ruleId, ruleContent: content, publishedAt: now, source: 'sigma' });
1372
+ seeded++;
1373
+ }
1374
+ }
1375
+ catch { /* no sigma rules */ }
1376
+ // 2. YARA rules (.yar, .yara)
1377
+ const yaraDir = joinPath(configDir, 'yara-rules');
1378
+ try {
1379
+ const yaraFiles = collectFiles(yaraDir, ['.yar', '.yara']);
1380
+ for (const file of yaraFiles) {
1381
+ const content = readFs(file, 'utf-8');
1382
+ // Split multi-rule YARA files
1383
+ const ruleMatches = content.match(/rule\s+\w+/g);
1384
+ if (ruleMatches && ruleMatches.length > 1) {
1385
+ // Multi-rule file: store each rule name as sub-ID
1386
+ for (const match of ruleMatches) {
1387
+ const ruleName = match.replace('rule ', '');
1388
+ const ruleId = `yara:${basename(file, '.yar').replace('.yara', '')}:${ruleName}`;
1389
+ threatDb.upsertRule({ ruleId, ruleContent: content, publishedAt: now, source: 'yara' });
1390
+ seeded++;
1391
+ }
1392
+ }
1393
+ else {
1394
+ const ruleId = `yara:${relative(yaraDir, file).replace(/\//g, ':')}`;
1395
+ threatDb.upsertRule({ ruleId, ruleContent: content, publishedAt: now, source: 'yara' });
1396
+ seeded++;
1397
+ }
1398
+ }
1399
+ }
1400
+ catch { /* no yara rules */ }
1401
+ // 3. ATR rules (.yaml, .yml) from atr package
1402
+ const atrDirs = [
1403
+ joinPath(process.cwd(), 'node_modules', 'agent-threat-rules', 'rules'),
1404
+ joinPath(dirname(fileURLToPath(import.meta.url)), '..', '..', '..', '..', '..', 'packages', 'atr', 'rules'),
1405
+ ];
1406
+ const atrDir = atrDirs.find((d) => {
1407
+ try {
1408
+ return statSync(d).isDirectory();
1409
+ }
1410
+ catch {
1411
+ return false;
1412
+ }
1413
+ });
1414
+ if (atrDir) {
1415
+ try {
1416
+ const atrFiles = collectFiles(atrDir, ['.yaml', '.yml']);
1417
+ for (const file of atrFiles) {
1418
+ const content = readFs(file, 'utf-8');
1419
+ const ruleId = `atr:${relative(atrDir, file).replace(/\//g, ':')}`;
1420
+ threatDb.upsertRule({ ruleId, ruleContent: content, publishedAt: now, source: 'atr' });
1421
+ seeded++;
1422
+ }
1423
+ }
1424
+ catch { /* no atr rules */ }
1425
+ }
1426
+ return seeded;
1427
+ }
768
1428
  //# sourceMappingURL=serve.js.map