neuralbrain 0.0.0-stage → 0.0.1

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 (293) hide show
  1. package/.dockerignore +11 -0
  2. package/.env.example +245 -0
  3. package/Dockerfile +65 -0
  4. package/LICENSE +44 -0
  5. package/README.md +312 -2
  6. package/dist/ai/chat.d.ts +45 -0
  7. package/dist/ai/chat.d.ts.map +1 -0
  8. package/dist/ai/chat.js +153 -0
  9. package/dist/ai/chat.js.map +1 -0
  10. package/dist/ai/circuitBreaker.d.ts +35 -0
  11. package/dist/ai/circuitBreaker.d.ts.map +1 -0
  12. package/dist/ai/circuitBreaker.js +95 -0
  13. package/dist/ai/circuitBreaker.js.map +1 -0
  14. package/dist/ai/config.d.ts +88 -0
  15. package/dist/ai/config.d.ts.map +1 -0
  16. package/dist/ai/config.js +255 -0
  17. package/dist/ai/config.js.map +1 -0
  18. package/dist/ai/vendors.d.ts +58 -0
  19. package/dist/ai/vendors.d.ts.map +1 -0
  20. package/dist/ai/vendors.js +223 -0
  21. package/dist/ai/vendors.js.map +1 -0
  22. package/dist/app.d.ts +4 -0
  23. package/dist/app.d.ts.map +1 -0
  24. package/dist/app.js +1013 -0
  25. package/dist/app.js.map +1 -0
  26. package/dist/cli.d.ts +133 -0
  27. package/dist/cli.d.ts.map +1 -0
  28. package/dist/cli.js +912 -0
  29. package/dist/cli.js.map +1 -0
  30. package/dist/consolidation/candidates.d.ts +34 -0
  31. package/dist/consolidation/candidates.d.ts.map +1 -0
  32. package/dist/consolidation/candidates.js +150 -0
  33. package/dist/consolidation/candidates.js.map +1 -0
  34. package/dist/consolidation/fixtures.d.ts +25 -0
  35. package/dist/consolidation/fixtures.d.ts.map +1 -0
  36. package/dist/consolidation/fixtures.js +400 -0
  37. package/dist/consolidation/fixtures.js.map +1 -0
  38. package/dist/consolidation/gate.d.ts +39 -0
  39. package/dist/consolidation/gate.d.ts.map +1 -0
  40. package/dist/consolidation/gate.js +286 -0
  41. package/dist/consolidation/gate.js.map +1 -0
  42. package/dist/consolidation/runner.d.ts +63 -0
  43. package/dist/consolidation/runner.d.ts.map +1 -0
  44. package/dist/consolidation/runner.js +171 -0
  45. package/dist/consolidation/runner.js.map +1 -0
  46. package/dist/dashboard/clientScript.d.ts +2 -0
  47. package/dist/dashboard/clientScript.d.ts.map +1 -0
  48. package/dist/dashboard/clientScript.js +4212 -0
  49. package/dist/dashboard/clientScript.js.map +1 -0
  50. package/dist/dashboard/html.d.ts +2 -0
  51. package/dist/dashboard/html.d.ts.map +1 -0
  52. package/dist/dashboard/html.js +554 -0
  53. package/dist/dashboard/html.js.map +1 -0
  54. package/dist/dashboard/styles.d.ts +2 -0
  55. package/dist/dashboard/styles.d.ts.map +1 -0
  56. package/dist/dashboard/styles.js +1283 -0
  57. package/dist/dashboard/styles.js.map +1 -0
  58. package/dist/index.d.ts +3 -0
  59. package/dist/index.d.ts.map +1 -0
  60. package/dist/index.js +124 -0
  61. package/dist/index.js.map +1 -0
  62. package/dist/learning/embedWorker.d.ts +58 -0
  63. package/dist/learning/embedWorker.d.ts.map +1 -0
  64. package/dist/learning/embedWorker.js +552 -0
  65. package/dist/learning/embedWorker.js.map +1 -0
  66. package/dist/learning/embedding.d.ts +52 -0
  67. package/dist/learning/embedding.d.ts.map +1 -0
  68. package/dist/learning/embedding.js +511 -0
  69. package/dist/learning/embedding.js.map +1 -0
  70. package/dist/learning/engine.d.ts +20 -0
  71. package/dist/learning/engine.d.ts.map +1 -0
  72. package/dist/learning/engine.js +69 -0
  73. package/dist/learning/engine.js.map +1 -0
  74. package/dist/learning/search.d.ts +4 -0
  75. package/dist/learning/search.d.ts.map +1 -0
  76. package/dist/learning/search.js +509 -0
  77. package/dist/learning/search.js.map +1 -0
  78. package/dist/learning/storeMeta.d.ts +11 -0
  79. package/dist/learning/storeMeta.d.ts.map +1 -0
  80. package/dist/learning/storeMeta.js +100 -0
  81. package/dist/learning/storeMeta.js.map +1 -0
  82. package/dist/learning/types.d.ts +101 -0
  83. package/dist/learning/types.d.ts.map +1 -0
  84. package/dist/learning/types.js +3 -0
  85. package/dist/learning/types.js.map +1 -0
  86. package/dist/lib/brainHome.d.ts +28 -0
  87. package/dist/lib/brainHome.d.ts.map +1 -0
  88. package/dist/lib/brainHome.js +104 -0
  89. package/dist/lib/brainHome.js.map +1 -0
  90. package/dist/lib/db.d.ts +10 -0
  91. package/dist/lib/db.d.ts.map +1 -0
  92. package/dist/lib/db.js +589 -0
  93. package/dist/lib/db.js.map +1 -0
  94. package/dist/lib/logger.d.ts +3 -0
  95. package/dist/lib/logger.d.ts.map +1 -0
  96. package/dist/lib/logger.js +11 -0
  97. package/dist/lib/logger.js.map +1 -0
  98. package/dist/lib/projectSlug.d.ts +61 -0
  99. package/dist/lib/projectSlug.d.ts.map +1 -0
  100. package/dist/lib/projectSlug.js +273 -0
  101. package/dist/lib/projectSlug.js.map +1 -0
  102. package/dist/lib/redactSecrets.d.ts +7 -0
  103. package/dist/lib/redactSecrets.d.ts.map +1 -0
  104. package/dist/lib/redactSecrets.js +90 -0
  105. package/dist/lib/redactSecrets.js.map +1 -0
  106. package/dist/lib/scope.d.ts +54 -0
  107. package/dist/lib/scope.d.ts.map +1 -0
  108. package/dist/lib/scope.js +103 -0
  109. package/dist/lib/scope.js.map +1 -0
  110. package/dist/lib/spool.d.ts +23 -0
  111. package/dist/lib/spool.d.ts.map +1 -0
  112. package/dist/lib/spool.js +317 -0
  113. package/dist/lib/spool.js.map +1 -0
  114. package/dist/lib/sqlite.d.ts +50 -0
  115. package/dist/lib/sqlite.d.ts.map +1 -0
  116. package/dist/lib/sqlite.js +130 -0
  117. package/dist/lib/sqlite.js.map +1 -0
  118. package/dist/lib/tls.d.ts +34 -0
  119. package/dist/lib/tls.d.ts.map +1 -0
  120. package/dist/lib/tls.js +212 -0
  121. package/dist/lib/tls.js.map +1 -0
  122. package/dist/mcp/server.d.ts +231 -0
  123. package/dist/mcp/server.d.ts.map +1 -0
  124. package/dist/mcp/server.js +615 -0
  125. package/dist/mcp/server.js.map +1 -0
  126. package/dist/memory/actionStore.d.ts +75 -0
  127. package/dist/memory/actionStore.d.ts.map +1 -0
  128. package/dist/memory/actionStore.js +239 -0
  129. package/dist/memory/actionStore.js.map +1 -0
  130. package/dist/memory/deadLetterStore.d.ts +30 -0
  131. package/dist/memory/deadLetterStore.d.ts.map +1 -0
  132. package/dist/memory/deadLetterStore.js +91 -0
  133. package/dist/memory/deadLetterStore.js.map +1 -0
  134. package/dist/memory/embedQueueStore.d.ts +32 -0
  135. package/dist/memory/embedQueueStore.d.ts.map +1 -0
  136. package/dist/memory/embedQueueStore.js +143 -0
  137. package/dist/memory/embedQueueStore.js.map +1 -0
  138. package/dist/memory/failurePatternStore.d.ts +37 -0
  139. package/dist/memory/failurePatternStore.d.ts.map +1 -0
  140. package/dist/memory/failurePatternStore.js +179 -0
  141. package/dist/memory/failurePatternStore.js.map +1 -0
  142. package/dist/memory/graphStore.d.ts +38 -0
  143. package/dist/memory/graphStore.d.ts.map +1 -0
  144. package/dist/memory/graphStore.js +229 -0
  145. package/dist/memory/graphStore.js.map +1 -0
  146. package/dist/memory/noteStore.d.ts +58 -0
  147. package/dist/memory/noteStore.d.ts.map +1 -0
  148. package/dist/memory/noteStore.js +280 -0
  149. package/dist/memory/noteStore.js.map +1 -0
  150. package/dist/memory/observationStore.d.ts +40 -0
  151. package/dist/memory/observationStore.d.ts.map +1 -0
  152. package/dist/memory/observationStore.js +213 -0
  153. package/dist/memory/observationStore.js.map +1 -0
  154. package/dist/memory/projectRename.d.ts +14 -0
  155. package/dist/memory/projectRename.d.ts.map +1 -0
  156. package/dist/memory/projectRename.js +105 -0
  157. package/dist/memory/projectRename.js.map +1 -0
  158. package/dist/memory/rollupSweeper.d.ts +36 -0
  159. package/dist/memory/rollupSweeper.d.ts.map +1 -0
  160. package/dist/memory/rollupSweeper.js +235 -0
  161. package/dist/memory/rollupSweeper.js.map +1 -0
  162. package/dist/memory/sessionStore.d.ts +81 -0
  163. package/dist/memory/sessionStore.d.ts.map +1 -0
  164. package/dist/memory/sessionStore.js +285 -0
  165. package/dist/memory/sessionStore.js.map +1 -0
  166. package/dist/memory/trajectoryStore.d.ts +86 -0
  167. package/dist/memory/trajectoryStore.d.ts.map +1 -0
  168. package/dist/memory/trajectoryStore.js +528 -0
  169. package/dist/memory/trajectoryStore.js.map +1 -0
  170. package/dist/middleware/auth.d.ts +30 -0
  171. package/dist/middleware/auth.d.ts.map +1 -0
  172. package/dist/middleware/auth.js +387 -0
  173. package/dist/middleware/auth.js.map +1 -0
  174. package/dist/middleware/rateLimiter.d.ts +13 -0
  175. package/dist/middleware/rateLimiter.d.ts.map +1 -0
  176. package/dist/middleware/rateLimiter.js +153 -0
  177. package/dist/middleware/rateLimiter.js.map +1 -0
  178. package/dist/middleware/tracing.d.ts +15 -0
  179. package/dist/middleware/tracing.d.ts.map +1 -0
  180. package/dist/middleware/tracing.js +53 -0
  181. package/dist/middleware/tracing.js.map +1 -0
  182. package/dist/routes/dashboard.d.ts +2 -0
  183. package/dist/routes/dashboard.d.ts.map +1 -0
  184. package/dist/routes/dashboard.js +443 -0
  185. package/dist/routes/dashboard.js.map +1 -0
  186. package/dist/routes/learning.d.ts +2 -0
  187. package/dist/routes/learning.d.ts.map +1 -0
  188. package/dist/routes/learning.js +46 -0
  189. package/dist/routes/learning.js.map +1 -0
  190. package/dist/routes/mcp.d.ts +8 -0
  191. package/dist/routes/mcp.d.ts.map +1 -0
  192. package/dist/routes/mcp.js +316 -0
  193. package/dist/routes/mcp.js.map +1 -0
  194. package/dist/routes/memories.d.ts +2 -0
  195. package/dist/routes/memories.d.ts.map +1 -0
  196. package/dist/routes/memories.js +33 -0
  197. package/dist/routes/memories.js.map +1 -0
  198. package/dist/scripts/createApiKey.d.ts +2 -0
  199. package/dist/scripts/createApiKey.d.ts.map +1 -0
  200. package/dist/scripts/createApiKey.js +78 -0
  201. package/dist/scripts/createApiKey.js.map +1 -0
  202. package/dist/scripts/doctor.d.ts +24 -0
  203. package/dist/scripts/doctor.d.ts.map +1 -0
  204. package/dist/scripts/doctor.js +332 -0
  205. package/dist/scripts/doctor.js.map +1 -0
  206. package/dist/scripts/installAgent.d.ts +80 -0
  207. package/dist/scripts/installAgent.d.ts.map +1 -0
  208. package/dist/scripts/installAgent.js +1046 -0
  209. package/dist/scripts/installAgent.js.map +1 -0
  210. package/dist/scripts/migrateAgentMemory.d.ts +16 -0
  211. package/dist/scripts/migrateAgentMemory.d.ts.map +1 -0
  212. package/dist/scripts/migrateAgentMemory.js +209 -0
  213. package/dist/scripts/migrateAgentMemory.js.map +1 -0
  214. package/dist/scripts/smokeTest.d.ts +16 -0
  215. package/dist/scripts/smokeTest.d.ts.map +1 -0
  216. package/dist/scripts/smokeTest.js +150 -0
  217. package/dist/scripts/smokeTest.js.map +1 -0
  218. package/docker-compose.qdrant-port.yml +7 -0
  219. package/docker-compose.yml +107 -0
  220. package/npm-shrinkwrap.json +7635 -0
  221. package/package.json +106 -4
  222. package/plugin/hooks/postToolUse.js +513 -0
  223. package/plugin/hooks/sessionStart.js +416 -0
  224. package/plugin/hooks/sessionStop.js +346 -0
  225. package/plugin/hooks.json +30 -0
  226. package/plugin/mcp_config.json +13 -0
  227. package/plugin/plugin.json +15 -0
  228. package/plugin/rules/AGENTS.md +66 -0
  229. package/plugin/skills/brain-memory/REFERENCE.md +64 -0
  230. package/plugin/skills/brain-memory/SKILL.md +68 -0
  231. package/plugin/skills/brain-memory/TROUBLESHOOTING.md +24 -0
  232. package/plugin/skills/digest/SKILL.md +54 -0
  233. package/plugin/skills/digest/TROUBLESHOOTING.md +24 -0
  234. package/plugin/skills/handoff/SKILL.md +59 -0
  235. package/plugin/skills/handoff/TROUBLESHOOTING.md +24 -0
  236. package/plugin/skills/save/SKILL.md +76 -0
  237. package/plugin/skills/save/TROUBLESHOOTING.md +24 -0
  238. package/plugin/skills/search/SKILL.md +60 -0
  239. package/plugin/skills/search/TROUBLESHOOTING.md +24 -0
  240. package/src/ai/chat.ts +214 -0
  241. package/src/ai/circuitBreaker.ts +120 -0
  242. package/src/ai/config.ts +311 -0
  243. package/src/ai/vendors.ts +292 -0
  244. package/src/app.ts +1150 -0
  245. package/src/cli.ts +1080 -0
  246. package/src/consolidation/candidates.ts +219 -0
  247. package/src/consolidation/fixtures.ts +461 -0
  248. package/src/consolidation/gate.ts +408 -0
  249. package/src/consolidation/runner.ts +220 -0
  250. package/src/dashboard/clientScript.ts +4208 -0
  251. package/src/dashboard/html.ts +550 -0
  252. package/src/dashboard/styles.ts +1279 -0
  253. package/src/index.ts +139 -0
  254. package/src/learning/embedWorker.ts +651 -0
  255. package/src/learning/embedding.ts +522 -0
  256. package/src/learning/engine.ts +86 -0
  257. package/src/learning/search.ts +568 -0
  258. package/src/learning/storeMeta.ts +147 -0
  259. package/src/learning/types.ts +111 -0
  260. package/src/lib/brainHome.ts +101 -0
  261. package/src/lib/db.ts +627 -0
  262. package/src/lib/logger.ts +7 -0
  263. package/src/lib/projectSlug.ts +286 -0
  264. package/src/lib/redactSecrets.ts +87 -0
  265. package/src/lib/scope.ts +121 -0
  266. package/src/lib/spool.ts +372 -0
  267. package/src/lib/sqlite.ts +158 -0
  268. package/src/lib/tls.ts +252 -0
  269. package/src/mcp/server.ts +793 -0
  270. package/src/memory/actionStore.ts +378 -0
  271. package/src/memory/deadLetterStore.ts +141 -0
  272. package/src/memory/embedQueueStore.ts +176 -0
  273. package/src/memory/failurePatternStore.ts +221 -0
  274. package/src/memory/graphStore.ts +352 -0
  275. package/src/memory/noteStore.ts +403 -0
  276. package/src/memory/observationStore.ts +303 -0
  277. package/src/memory/projectRename.ts +147 -0
  278. package/src/memory/rollupSweeper.ts +309 -0
  279. package/src/memory/sessionStore.ts +410 -0
  280. package/src/memory/trajectoryStore.ts +775 -0
  281. package/src/middleware/auth.ts +450 -0
  282. package/src/middleware/rateLimiter.ts +186 -0
  283. package/src/middleware/tracing.ts +70 -0
  284. package/src/routes/dashboard.ts +496 -0
  285. package/src/routes/learning.ts +51 -0
  286. package/src/routes/mcp.ts +349 -0
  287. package/src/routes/memories.ts +33 -0
  288. package/src/scripts/createApiKey.ts +109 -0
  289. package/src/scripts/doctor.ts +359 -0
  290. package/src/scripts/installAgent.ts +1278 -0
  291. package/src/scripts/migrateAgentMemory.ts +263 -0
  292. package/src/scripts/smokeTest.ts +189 -0
  293. package/tsconfig.json +21 -0
@@ -0,0 +1,450 @@
1
+ import { Request, Response, NextFunction } from 'express';
2
+ import crypto from 'crypto';
3
+ import fs from 'fs';
4
+ import path from 'path';
5
+ import { getDb, getDbPath, isDatabaseUnavailableError } from '../lib/db';
6
+ import { logger } from '../lib/logger';
7
+ import { getCorrelationId } from './tracing';
8
+
9
+ export interface AuthRequest extends Request {
10
+ apiKeyId?: string;
11
+ apiKeyName?: string;
12
+ }
13
+
14
+ export function hashApiKey(rawKey: string): string {
15
+ return crypto.createHash('sha256').update(rawKey).digest('hex');
16
+ }
17
+
18
+ let DASHBOARD_SESSION_TOKEN = crypto.randomBytes(32).toString('hex');
19
+
20
+ export function getDashboardSessionToken(): string {
21
+ return DASHBOARD_SESSION_TOKEN;
22
+ }
23
+
24
+ export function resetDashboardSessionTokenForTesting(): string {
25
+ DASHBOARD_SESSION_TOKEN = crypto.randomBytes(32).toString('hex');
26
+ return DASHBOARD_SESSION_TOKEN;
27
+ }
28
+
29
+ function isAuthExempt(path: string): boolean {
30
+ return (
31
+ path === '/' ||
32
+ path === '/health' ||
33
+ path === '/favicon.ico' ||
34
+ path === '/dashboard' ||
35
+ path === '/dashboard/' ||
36
+ path === '/dashboard/styles.css' ||
37
+ path === '/dashboard/app.js' ||
38
+ path === '/dashboard/api/auth-status' ||
39
+ path === '/dashboard/api/session'
40
+ );
41
+ }
42
+
43
+ let cachedSessionSecret: string | null = null;
44
+
45
+ export function getSessionSecret(): string {
46
+ if (cachedSessionSecret) return cachedSessionSecret;
47
+ if (process.env.BRAIN_SESSION_SECRET) {
48
+ cachedSessionSecret = process.env.BRAIN_SESSION_SECRET.trim();
49
+ return cachedSessionSecret;
50
+ }
51
+ try {
52
+ const dbPath = getDbPath();
53
+ if (dbPath !== ':memory:' && process.env.NODE_ENV !== 'test') {
54
+ const secretFile = path.join(path.dirname(path.resolve(dbPath)), '.session-secret');
55
+ if (fs.existsSync(secretFile)) {
56
+ cachedSessionSecret = fs.readFileSync(secretFile, 'utf8').trim();
57
+ } else {
58
+ cachedSessionSecret = crypto.randomBytes(32).toString('hex');
59
+ fs.writeFileSync(secretFile, cachedSessionSecret, { mode: 0o600 });
60
+ }
61
+ return cachedSessionSecret;
62
+ }
63
+ } catch {
64
+ // fallback
65
+ }
66
+ cachedSessionSecret = crypto.randomBytes(32).toString('hex');
67
+ return cachedSessionSecret;
68
+ }
69
+
70
+ function computeKeyVersion(storedKeyHash: string): string {
71
+ return crypto
72
+ .createHmac('sha256', getSessionSecret())
73
+ .update(storedKeyHash)
74
+ .digest('hex')
75
+ .slice(0, 16);
76
+ }
77
+
78
+ export function createDashboardSessionToken(
79
+ apiKeyId: string,
80
+ apiKeyName: string,
81
+ storedKeyHash?: string
82
+ ): string {
83
+ let keyHash = storedKeyHash;
84
+ if (!keyHash) {
85
+ try {
86
+ const row = getDb()
87
+ .prepare(`SELECT key FROM api_keys WHERE id = ?`)
88
+ .get(apiKeyId) as { key: string } | undefined;
89
+ keyHash = row?.key || '';
90
+ } catch {
91
+ keyHash = '';
92
+ }
93
+ }
94
+ const keyVersion = keyHash ? computeKeyVersion(keyHash) : '';
95
+ const expiresAt = Date.now() + 7 * 24 * 3600 * 1000; // 7 days
96
+ const payload = `${apiKeyId}:${apiKeyName}:${keyVersion}:${expiresAt}`;
97
+ const sig = crypto.createHmac('sha256', getSessionSecret()).update(payload).digest('hex');
98
+ return Buffer.from(`${payload}:${sig}`).toString('base64url');
99
+ }
100
+
101
+ export function parseDashboardSessionCookie(cookieHeader?: string): { apiKeyId: string; apiKeyName: string } | null {
102
+ if (!cookieHeader) return null;
103
+ const match = cookieHeader.match(/(?:^|;\s*)brain_session=([^;]+)/);
104
+ if (!match) return null;
105
+ const rawToken = match[1];
106
+ try {
107
+ const decoded = Buffer.from(rawToken, 'base64url').toString('utf8');
108
+ const parts = decoded.split(':');
109
+ if (parts.length !== 5) return null;
110
+ const [apiKeyId, apiKeyName, keyVersion, expiresAtStr, sig] = parts;
111
+ const expiresAt = Number(expiresAtStr);
112
+ if (!Number.isFinite(expiresAt) || expiresAt < Date.now()) return null;
113
+
114
+ const payload = `${apiKeyId}:${apiKeyName}:${keyVersion}:${expiresAtStr}`;
115
+ const expectedSig = crypto.createHmac('sha256', getSessionSecret()).update(payload).digest('hex');
116
+ const sigBuf = Buffer.from(sig, 'utf8');
117
+ const expectedBuf = Buffer.from(expectedSig, 'utf8');
118
+ if (sigBuf.length !== expectedBuf.length || !crypto.timingSafeEqual(sigBuf, expectedBuf)) {
119
+ return null;
120
+ }
121
+
122
+ const db = getDb();
123
+ const keyRecord = db.prepare(
124
+ `SELECT id, name, key FROM api_keys WHERE id = ? AND revoked_at IS NULL AND (expires_at IS NULL OR expires_at > datetime('now'))`
125
+ ).get(apiKeyId) as { id: string; name: string; key: string } | undefined;
126
+
127
+ if (!keyRecord) return null;
128
+ const expectedVersion = computeKeyVersion(keyRecord.key);
129
+ const verBuf = Buffer.from(keyVersion, 'utf8');
130
+ const expectedVerBuf = Buffer.from(expectedVersion, 'utf8');
131
+ if (verBuf.length !== expectedVerBuf.length || !crypto.timingSafeEqual(verBuf, expectedVerBuf)) {
132
+ return null;
133
+ }
134
+
135
+ return { apiKeyId: keyRecord.id, apiKeyName: keyRecord.name };
136
+ } catch {
137
+ return null;
138
+ }
139
+ }
140
+
141
+ export function setDashboardSessionCookie(
142
+ res: Response,
143
+ apiKeyId: string,
144
+ apiKeyName: string,
145
+ isSecure = false,
146
+ storedKeyHash?: string
147
+ ): void {
148
+ const token = createDashboardSessionToken(apiKeyId, apiKeyName, storedKeyHash);
149
+ const secureFlag = isSecure ? '; Secure' : '';
150
+ res.setHeader(
151
+ 'Set-Cookie',
152
+ [
153
+ `brain_session=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=604800${secureFlag}`,
154
+ `brain_session=; HttpOnly; SameSite=Strict; Path=/dashboard; Max-Age=0`
155
+ ]
156
+ );
157
+ }
158
+
159
+ export function clearDashboardSessionCookie(res: Response): void {
160
+ res.setHeader(
161
+ 'Set-Cookie',
162
+ [
163
+ `brain_session=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0`,
164
+ `brain_session=; HttpOnly; SameSite=Strict; Path=/dashboard; Max-Age=0`
165
+ ]
166
+ );
167
+ }
168
+
169
+ export function hasActiveApiKeys(): boolean {
170
+ try {
171
+ const db = getDb();
172
+ const row = db
173
+ .prepare(
174
+ `SELECT 1 FROM api_keys
175
+ WHERE revoked_at IS NULL AND (expires_at IS NULL OR expires_at > datetime('now'))
176
+ LIMIT 1`
177
+ )
178
+ .get();
179
+ return Boolean(row);
180
+ } catch {
181
+ return false;
182
+ }
183
+ }
184
+
185
+ export function apiKeyAuth(req: AuthRequest, res: Response, next: NextFunction) {
186
+ // Skip auth for explicitly public endpoints
187
+ if (isAuthExempt(req.path)) {
188
+ return next();
189
+ }
190
+
191
+ // Bypass auth if BRAIN_REQUIRE_API_KEY is explicitly '0'
192
+ if (process.env.BRAIN_REQUIRE_API_KEY === '0') {
193
+ return next();
194
+ }
195
+
196
+ const activeKeysExist = hasActiveApiKeys();
197
+
198
+ // First-time bootstrap claim:
199
+ // If 0 active keys exist in the database, allow an initial unauthenticated
200
+ // POST /maintenance/api-keys with X-Requested-With: XMLHttpRequest to claim the first key.
201
+ if (!activeKeysExist && req.method === 'POST' && req.path === '/maintenance/api-keys') {
202
+ const xRequestedWith = req.headers['x-requested-with'];
203
+ const isXhr = typeof xRequestedWith === 'string' && xRequestedWith.toLowerCase() === 'xmlhttprequest';
204
+ if (isXhr) {
205
+ req.apiKeyId = 'bootstrap-claim';
206
+ req.apiKeyName = 'initial-bootstrap-claim';
207
+ return next();
208
+ } else {
209
+ logger.warn({ path: req.path, traceId: getCorrelationId(req) }, 'bootstrap key creation requires X-Requested-With header');
210
+ return res.status(401).json({
211
+ error: {
212
+ code: 'UNAUTHORIZED',
213
+ message: 'Bootstrap key creation requires X-Requested-With header',
214
+ trace_id: getCorrelationId(req),
215
+ },
216
+ });
217
+ }
218
+ }
219
+
220
+ const authHeader = req.headers.authorization;
221
+ const traceId = getCorrelationId(req);
222
+
223
+ if (authHeader && authHeader.startsWith('Bearer ')) {
224
+ const apiKey = authHeader.slice(7).trim();
225
+ if (!apiKey) {
226
+ logger.warn({ path: req.path, traceId }, 'empty api key provided');
227
+ return res.status(401).json({
228
+ error: {
229
+ code: 'UNAUTHORIZED',
230
+ message: 'Invalid or expired API key',
231
+ trace_id: traceId,
232
+ },
233
+ });
234
+ }
235
+
236
+ // Dashboard session token check (requires X-Requested-With: XMLHttpRequest to prevent CSRF)
237
+ // ONLY accepted when no active keys exist yet! Once hasActiveApiKeys() === true,
238
+ // all windows must authenticate with a real API key.
239
+ if (!activeKeysExist) {
240
+ const sessionToken = getDashboardSessionToken();
241
+ const sessionTokenBuf = Buffer.from(sessionToken, 'utf8');
242
+ const tokenBuf = Buffer.from(apiKey, 'utf8');
243
+
244
+ if (tokenBuf.length === sessionTokenBuf.length && crypto.timingSafeEqual(tokenBuf, sessionTokenBuf)) {
245
+ const xRequestedWith = req.headers['x-requested-with'];
246
+ const isXhr = typeof xRequestedWith === 'string' && xRequestedWith.toLowerCase() === 'xmlhttprequest';
247
+ if (isXhr) {
248
+ req.apiKeyId = 'dashboard-session';
249
+ req.apiKeyName = 'dashboard-operator';
250
+ return next();
251
+ } else {
252
+ logger.warn({ path: req.path, traceId }, 'dashboard session token used without X-Requested-With header');
253
+ return res.status(401).json({
254
+ error: {
255
+ code: 'UNAUTHORIZED',
256
+ message: 'Dashboard session token requires X-Requested-With header',
257
+ trace_id: traceId,
258
+ },
259
+ });
260
+ }
261
+ }
262
+ }
263
+
264
+ const hashedKey = hashApiKey(apiKey);
265
+
266
+ try {
267
+ const db = getDb();
268
+ // Query matching either hashedKey or rawKey to maintain 100% backward compatibility
269
+ // with unit tests inserting raw keys directly into api_keys table
270
+ const keyRecords = db
271
+ .prepare(
272
+ `SELECT id, name, key, last_used_at FROM api_keys
273
+ WHERE (key = ? OR key = ?) AND revoked_at IS NULL AND
274
+ (expires_at IS NULL OR expires_at > datetime('now'))`
275
+ )
276
+ .all(hashedKey, apiKey) as Array<{ id: string; name: string; key: string; last_used_at: string }>;
277
+
278
+ const matched = keyRecords.find((rec) => {
279
+ const candidateBuf = Buffer.from(rec.key, 'utf8');
280
+ const hashedBuf = Buffer.from(hashedKey, 'utf8');
281
+ const rawBuf = Buffer.from(apiKey, 'utf8');
282
+
283
+ if (candidateBuf.length === hashedBuf.length && crypto.timingSafeEqual(candidateBuf, hashedBuf)) {
284
+ return true;
285
+ }
286
+ if (candidateBuf.length === rawBuf.length && crypto.timingSafeEqual(candidateBuf, rawBuf)) {
287
+ return true;
288
+ }
289
+ return false;
290
+ });
291
+
292
+ if (!matched) {
293
+ logger.warn({ path: req.path, traceId }, 'invalid api key');
294
+ return res.status(401).json({
295
+ error: {
296
+ code: 'UNAUTHORIZED',
297
+ message: 'Invalid or expired API key',
298
+ trace_id: traceId,
299
+ },
300
+ });
301
+ }
302
+
303
+ // Update last_used_at
304
+ db.prepare(`UPDATE api_keys SET last_used_at = datetime('now') WHERE id = ?`).run(matched.id);
305
+
306
+ req.apiKeyId = matched.id;
307
+ req.apiKeyName = matched.name;
308
+
309
+ return next();
310
+ } catch (error) {
311
+ if (isDatabaseUnavailableError(error)) {
312
+ logger.error({ error: error.message, path: req.path, traceId }, 'database unavailable during auth check');
313
+ return res.status(503).json({
314
+ error: {
315
+ code: 'DATABASE_UNAVAILABLE',
316
+ message: 'Database is unavailable',
317
+ trace_id: traceId,
318
+ },
319
+ });
320
+ }
321
+
322
+ logger.error(
323
+ { error: error instanceof Error ? error.message : String(error), path: req.path, traceId },
324
+ 'error verifying api key'
325
+ );
326
+ return res.status(500).json({
327
+ error: {
328
+ code: 'INTERNAL_SERVER_ERROR',
329
+ message: 'Error verifying api key',
330
+ trace_id: traceId,
331
+ },
332
+ });
333
+ }
334
+ }
335
+
336
+ // 2. Check HttpOnly dashboard session cookie (for /dashboard requests)
337
+ const session = parseDashboardSessionCookie(req.headers.cookie);
338
+ if (session) {
339
+ req.apiKeyId = session.apiKeyId;
340
+ req.apiKeyName = session.apiKeyName;
341
+ return next();
342
+ }
343
+
344
+ logger.warn({ path: req.path, traceId }, 'missing or invalid authorization header');
345
+ return res.status(401).json({
346
+ error: {
347
+ code: 'UNAUTHORIZED',
348
+ message: 'Missing or invalid Authorization header. Use: Authorization: Bearer YOUR_API_KEY',
349
+ trace_id: traceId,
350
+ },
351
+ });
352
+ }
353
+
354
+ export interface BootstrapApiKeyOptions {
355
+ dbPath?: string;
356
+ forceBootstrap?: boolean;
357
+ }
358
+
359
+ export interface BootstrapApiKeyResult {
360
+ envKeyConfigured: boolean;
361
+ bootstrapKeyGenerated: boolean;
362
+ rawKey?: string;
363
+ keyFilePath?: string;
364
+ }
365
+
366
+ export function ensureBootstrapApiKey(options?: BootstrapApiKeyOptions): BootstrapApiKeyResult {
367
+ const db = getDb();
368
+ let envKeyConfigured = false;
369
+ let bootstrapKeyGenerated = false;
370
+ let rawKey: string | undefined;
371
+ let keyFilePath: string | undefined;
372
+
373
+ // 1. If BRAIN_API_KEY is set (non-empty), compute SHA-256 and insert/update
374
+ const envApiKey = process.env.BRAIN_API_KEY?.trim();
375
+ if (envApiKey) {
376
+ const hashed = hashApiKey(envApiKey);
377
+ const existing = db
378
+ .prepare(`SELECT id, key FROM api_keys WHERE id = 'env-configured-key'`)
379
+ .get() as { id: string; key: string } | undefined;
380
+ if (!existing) {
381
+ db.prepare(`INSERT OR IGNORE INTO api_keys (id, name, key) VALUES ('env-configured-key', 'env-brain-api-key', ?)`).run(hashed);
382
+ } else if (existing.key !== hashed) {
383
+ db.prepare(`UPDATE api_keys SET key = ?, revoked_at = NULL WHERE id = 'env-configured-key'`).run(hashed);
384
+ }
385
+ envKeyConfigured = true;
386
+ logger.info('configured BRAIN_API_KEY from environment registered');
387
+ }
388
+
389
+ // 2. Only auto-generate default-bootstrap-key if explicitly forced or requested via BRAIN_AUTO_BOOTSTRAP_KEY === '1'
390
+ const shouldForceBootstrap = options?.forceBootstrap === true || process.env.BRAIN_AUTO_BOOTSTRAP_KEY === '1';
391
+
392
+ const countRow = db.prepare(`
393
+ SELECT count(*) as count FROM api_keys
394
+ WHERE revoked_at IS NULL AND (expires_at IS NULL OR expires_at > datetime('now'))
395
+ `).get() as { count: number };
396
+
397
+ if (shouldForceBootstrap && countRow.count === 0) {
398
+ rawKey = crypto.randomBytes(32).toString('hex');
399
+ const hashed = hashApiKey(rawKey);
400
+
401
+ const existingBootstrap = db
402
+ .prepare(`SELECT id FROM api_keys WHERE id = 'default-bootstrap-key'`)
403
+ .get() as { id: string } | undefined;
404
+
405
+ if (!existingBootstrap) {
406
+ db.prepare(`
407
+ INSERT INTO api_keys (id, name, key)
408
+ VALUES ('default-bootstrap-key', 'default-bootstrap-key', ?)
409
+ `).run(hashed);
410
+ } else {
411
+ db.prepare(`
412
+ UPDATE api_keys SET key = ?, revoked_at = NULL WHERE id = 'default-bootstrap-key'
413
+ `).run(hashed);
414
+ }
415
+
416
+ bootstrapKeyGenerated = true;
417
+
418
+ const dbPath = options?.dbPath || getDbPath();
419
+ const dir = path.dirname(path.resolve(dbPath));
420
+ const candidateKeyFile = path.join(dir, 'api-key.txt');
421
+
422
+ if (dbPath !== ':memory:' && process.env.NODE_ENV !== 'test') {
423
+ try {
424
+ if (!fs.existsSync(dir)) {
425
+ fs.mkdirSync(dir, { recursive: true });
426
+ }
427
+ fs.writeFileSync(candidateKeyFile, rawKey + '\n', { mode: 0o600 });
428
+ keyFilePath = candidateKeyFile;
429
+ logger.info(
430
+ { path: candidateKeyFile },
431
+ 'bootstrap API key automatically generated and saved to ' + candidateKeyFile
432
+ );
433
+ } catch (err) {
434
+ logger.error(
435
+ { error: err instanceof Error ? err.message : String(err), path: candidateKeyFile },
436
+ 'failed to write bootstrap API key to file'
437
+ );
438
+ }
439
+ } else {
440
+ logger.info('bootstrap API key generated in-memory');
441
+ }
442
+ }
443
+
444
+ return {
445
+ envKeyConfigured,
446
+ bootstrapKeyGenerated,
447
+ rawKey,
448
+ keyFilePath,
449
+ };
450
+ }
@@ -0,0 +1,186 @@
1
+ import { Request, Response, NextFunction } from 'express';
2
+ import { logger } from '../lib/logger';
3
+ import { getCorrelationId } from './tracing';
4
+
5
+ export interface RateLimitConfig {
6
+ windowMs?: number;
7
+ maxRequests?: number;
8
+ skipSuccessfulRequests?: boolean;
9
+ skipFailedRequests?: boolean;
10
+ }
11
+
12
+ interface RateLimitEntry {
13
+ count: number;
14
+ resetTime: number;
15
+ }
16
+
17
+ const rateLimitStore = new Map<string, RateLimitEntry>();
18
+ const MAX_STORE_ENTRIES = 10_000;
19
+
20
+ export function normalizePathForRateLimit(path: string): string {
21
+ // Normalize /files/<path>/notes -> /files/:path/notes
22
+ if (path.startsWith('/files/') && path.endsWith('/notes')) {
23
+ return '/files/:path/notes';
24
+ }
25
+ // Normalize /notes/<id>/scope -> /notes/:id/scope
26
+ if (/^\/notes\/[^/]+\/scope$/.test(path)) {
27
+ return '/notes/:id/scope';
28
+ }
29
+ // Normalize /notes/<id> -> /notes/:id
30
+ if (/^\/notes\/[^/]+$/.test(path)) {
31
+ return '/notes/:id';
32
+ }
33
+ // Normalize /observations/<id> -> /observations/:id
34
+ if (/^\/observations\/[^/]+$/.test(path)) {
35
+ return '/observations/:id';
36
+ }
37
+ // Normalize /trajectories/<id> -> /trajectories/:id
38
+ if (/^\/trajectories\/[^/]+$/.test(path)) {
39
+ return '/trajectories/:id';
40
+ }
41
+ // Normalize /summaries/<id> -> /summaries/:id
42
+ if (/^\/summaries\/[^/]+$/.test(path)) {
43
+ return '/summaries/:id';
44
+ }
45
+ return path;
46
+ }
47
+
48
+ function getExemptPrefixes(): string[] {
49
+ const envVal = process.env.BRAIN_RATE_LIMIT_EXEMPT || '/health,/capture';
50
+ return envVal
51
+ .split(',')
52
+ .map((s) => s.trim())
53
+ .filter(Boolean);
54
+ }
55
+
56
+ function isPathExempt(path: string): boolean {
57
+ if (
58
+ path === '/' ||
59
+ path === '/health' ||
60
+ path === '/favicon.ico' ||
61
+ path === '/dashboard' ||
62
+ path.startsWith('/dashboard/') ||
63
+ path.startsWith('/capture')
64
+ ) {
65
+ return true;
66
+ }
67
+ const exemptPrefixes = getExemptPrefixes();
68
+ return exemptPrefixes.some((prefix) => path === prefix || path.startsWith(prefix));
69
+ }
70
+
71
+ export function createRateLimiter(config?: RateLimitConfig) {
72
+ const defaultWindow = parseInt(process.env.BRAIN_RATE_LIMIT_WINDOW_MS || '60000', 10);
73
+ const defaultMax = parseInt(process.env.BRAIN_RATE_LIMIT_MAX || '100', 10);
74
+
75
+ const windowMs = config?.windowMs ?? (Number.isFinite(defaultWindow) ? defaultWindow : 60000);
76
+ const maxRequests = config?.maxRequests ?? (Number.isFinite(defaultMax) ? defaultMax : 100);
77
+ const skipSuccessfulRequests = config?.skipSuccessfulRequests ?? false;
78
+ const skipFailedRequests = config?.skipFailedRequests ?? false;
79
+
80
+ // Clean up old entries periodically and unref so Jest tests do not hang
81
+ const interval = setInterval(() => {
82
+ const now = Date.now();
83
+ for (const [key, entry] of rateLimitStore.entries()) {
84
+ if (entry.resetTime < now) {
85
+ rateLimitStore.delete(key);
86
+ }
87
+ }
88
+ }, windowMs);
89
+ interval.unref();
90
+
91
+ return (req: Request, res: Response, next: NextFunction) => {
92
+ // Skip rate limiting for exempt paths (health checks and capture hot-paths)
93
+ if (isPathExempt(req.path)) {
94
+ return next();
95
+ }
96
+
97
+ const clientId = (req as any).apiKeyId || req.ip || 'unknown';
98
+ const normalizedPath = normalizePathForRateLimit(req.path);
99
+ const key = `${req.method}:${normalizedPath}:${clientId}`;
100
+ const now = Date.now();
101
+
102
+ let entry = rateLimitStore.get(key);
103
+
104
+ // Reset if window expired
105
+ if (!entry || entry.resetTime < now) {
106
+ if (rateLimitStore.size >= MAX_STORE_ENTRIES && !rateLimitStore.has(key)) {
107
+ // Evict expired entries
108
+ for (const [k, v] of rateLimitStore.entries()) {
109
+ if (v.resetTime < now) {
110
+ rateLimitStore.delete(k);
111
+ }
112
+ }
113
+ // If still at or above cap, evict oldest
114
+ while (rateLimitStore.size >= MAX_STORE_ENTRIES) {
115
+ const oldestKey = rateLimitStore.keys().next().value;
116
+ if (oldestKey !== undefined) {
117
+ rateLimitStore.delete(oldestKey);
118
+ } else {
119
+ break;
120
+ }
121
+ }
122
+ }
123
+
124
+ entry = {
125
+ count: 0,
126
+ resetTime: now + windowMs,
127
+ };
128
+ rateLimitStore.set(key, entry);
129
+ }
130
+
131
+ // Increment counter
132
+ entry.count++;
133
+
134
+ // Set rate limit headers
135
+ const remaining = Math.max(0, maxRequests - entry.count);
136
+ const resetTime = new Date(entry.resetTime);
137
+
138
+ res.setHeader('X-RateLimit-Limit', maxRequests.toString());
139
+ res.setHeader('X-RateLimit-Remaining', remaining.toString());
140
+ res.setHeader('X-RateLimit-Reset', resetTime.toISOString());
141
+
142
+ // Check if limit exceeded
143
+ if (entry.count > maxRequests) {
144
+ const traceId = getCorrelationId(req);
145
+ const retryAfter = Math.ceil((entry.resetTime - now) / 1000);
146
+
147
+ logger.warn(
148
+ { clientId, key, count: entry.count, limit: maxRequests, traceId },
149
+ 'rate limit exceeded'
150
+ );
151
+
152
+ return res.status(429).json({
153
+ error: {
154
+ code: 'RATE_LIMIT_EXCEEDED',
155
+ message: 'Too many requests. Please try again later.',
156
+ trace_id: traceId,
157
+ },
158
+ retryAfter,
159
+ });
160
+ }
161
+
162
+ // Add a callback to potentially skip based on response
163
+ const originalJson = res.json.bind(res);
164
+ (res as any).json = function (body: any) {
165
+ if (skipSuccessfulRequests && res.statusCode >= 200 && res.statusCode < 300) {
166
+ entry!.count--;
167
+ } else if (skipFailedRequests && res.statusCode >= 400) {
168
+ entry!.count--;
169
+ }
170
+ return originalJson.call(this, body);
171
+ };
172
+
173
+ next();
174
+ };
175
+ }
176
+
177
+ // Default API rate limiter using environment configuration
178
+ export const apiRateLimiter = createRateLimiter();
179
+
180
+ export const createApiRateLimiter = (maxRequests = 100) =>
181
+ createRateLimiter({ windowMs: 60000, maxRequests });
182
+
183
+ export function resetRateLimitStore(): void {
184
+ rateLimitStore.clear();
185
+ }
186
+
@@ -0,0 +1,70 @@
1
+ import { Request, Response, NextFunction } from 'express';
2
+ import { randomUUID } from 'crypto';
3
+ import { logger } from '../lib/logger';
4
+
5
+ export interface TracedRequest extends Request {
6
+ correlationId: string;
7
+ startTime: number;
8
+ }
9
+
10
+ export function requestTracing(req: Request, res: Response, next: NextFunction) {
11
+ const tracedReq = req as TracedRequest;
12
+
13
+ // Use correlation ID from header or generate new one
14
+ const correlationId = (req.headers['x-correlation-id'] as string) || (req.headers['x-trace-id'] as string) || randomUUID();
15
+ tracedReq.correlationId = correlationId;
16
+ tracedReq.startTime = Date.now();
17
+
18
+ // Add correlation ID to response headers
19
+ res.setHeader('X-Correlation-ID', correlationId);
20
+ res.setHeader('X-Trace-ID', correlationId);
21
+
22
+ // Log request start
23
+ logger.info(
24
+ {
25
+ correlationId,
26
+ method: req.method,
27
+ path: req.path,
28
+ ip: req.ip,
29
+ userAgent: req.get('user-agent'),
30
+ },
31
+ 'request_start'
32
+ );
33
+
34
+ // Hook into response to log completion
35
+ const originalSend = res.send.bind(res);
36
+
37
+ res.send = function (data: any) {
38
+ const duration = Date.now() - tracedReq.startTime;
39
+
40
+ logger.info(
41
+ {
42
+ correlationId,
43
+ method: req.method,
44
+ path: req.path,
45
+ statusCode: res.statusCode,
46
+ durationMs: duration,
47
+ },
48
+ 'request_end'
49
+ );
50
+
51
+ return originalSend(data);
52
+ };
53
+
54
+ next();
55
+ }
56
+
57
+ // Middleware to add correlation ID to all logger calls
58
+ export function getCorrelationId(req: Request): string {
59
+ return (req as TracedRequest).correlationId || (req.headers['x-correlation-id'] as string) || (req.headers['x-trace-id'] as string) || 'unknown';
60
+ }
61
+
62
+ export function formatErrorResponse(code: string, message: string, traceId: string) {
63
+ return {
64
+ error: {
65
+ code,
66
+ message,
67
+ trace_id: traceId,
68
+ },
69
+ };
70
+ }