wyrm-mcp 7.3.2 → 7.3.3

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 (184) hide show
  1. package/README.md +8 -14
  2. package/dist/activation.js +59 -1
  3. package/dist/agent-daemon.js +281 -4
  4. package/dist/agent-loop.js +332 -7
  5. package/dist/analytics.js +236 -13
  6. package/dist/attribution.js +49 -1
  7. package/dist/audit.js +457 -2
  8. package/dist/auto-capture.js +138 -3
  9. package/dist/auto-orchestrator.js +325 -1
  10. package/dist/autoconfig.d.ts +50 -0
  11. package/dist/autoconfig.d.ts.map +1 -1
  12. package/dist/autoconfig.js +1115 -39
  13. package/dist/autoconfig.js.map +1 -1
  14. package/dist/buddy-runner.js +109 -1
  15. package/dist/buddy.js +564 -14
  16. package/dist/build-flags.js +15 -1
  17. package/dist/capabilities.js +183 -3
  18. package/dist/capture.js +56 -1
  19. package/dist/causality.js +148 -8
  20. package/dist/cli.js +281 -20
  21. package/dist/cloud/cli.js +541 -5
  22. package/dist/cloud/client.js +221 -1
  23. package/dist/cloud/crypto.js +85 -1
  24. package/dist/cloud/machine-id.js +113 -2
  25. package/dist/cloud/recovery.js +60 -1
  26. package/dist/cloud/sync-engine.js +543 -7
  27. package/dist/cloud-backup.js +579 -5
  28. package/dist/cloud-profile.js +138 -1
  29. package/dist/cloud-sync-entrypoint.js +47 -1
  30. package/dist/cloud-sync.js +309 -2
  31. package/dist/connectors/bridge-source.d.ts +46 -0
  32. package/dist/connectors/bridge-source.d.ts.map +1 -0
  33. package/dist/connectors/bridge-source.js +77 -0
  34. package/dist/connectors/bridge-source.js.map +1 -0
  35. package/dist/connectors/index.d.ts +24 -0
  36. package/dist/connectors/index.d.ts.map +1 -0
  37. package/dist/connectors/index.js +69 -0
  38. package/dist/connectors/index.js.map +1 -0
  39. package/dist/connectors/ingest.d.ts +16 -0
  40. package/dist/connectors/ingest.d.ts.map +1 -0
  41. package/dist/connectors/ingest.js +116 -0
  42. package/dist/connectors/ingest.js.map +1 -0
  43. package/dist/connectors/types.d.ts +99 -0
  44. package/dist/connectors/types.d.ts.map +1 -0
  45. package/dist/connectors/types.js +17 -0
  46. package/dist/connectors/types.js.map +1 -0
  47. package/dist/constellation.js +168 -12
  48. package/dist/content-signature.js +45 -1
  49. package/dist/context-build-budgeted.js +144 -4
  50. package/dist/context-ranking.js +69 -1
  51. package/dist/crypto.js +179 -1
  52. package/dist/daemon-write-endpoint.js +290 -1
  53. package/dist/daemon-writer.js +406 -2
  54. package/dist/database.js +1278 -53
  55. package/dist/deprecations.js +162 -2
  56. package/dist/design.js +141 -13
  57. package/dist/event-replication.js +112 -1
  58. package/dist/events-sse.js +43 -7
  59. package/dist/events.js +238 -6
  60. package/dist/failure-patterns.d.ts +107 -0
  61. package/dist/failure-patterns.d.ts.map +1 -1
  62. package/dist/failure-patterns.js +924 -43
  63. package/dist/failure-patterns.js.map +1 -1
  64. package/dist/federation.js +236 -12
  65. package/dist/goals.js +101 -13
  66. package/dist/golden.js +355 -3
  67. package/dist/handlers/agent.js +165 -4
  68. package/dist/handlers/alias-adapters.js +129 -1
  69. package/dist/handlers/aliases.js +171 -1
  70. package/dist/handlers/audit.js +87 -1
  71. package/dist/handlers/boundary.js +221 -1
  72. package/dist/handlers/capture.js +1114 -73
  73. package/dist/handlers/causality.js +119 -9
  74. package/dist/handlers/cloud.js +382 -85
  75. package/dist/handlers/companion.js +459 -28
  76. package/dist/handlers/datalake.js +187 -7
  77. package/dist/handlers/dispatch-context.js +22 -0
  78. package/dist/handlers/entity.js +256 -25
  79. package/dist/handlers/events.js +335 -16
  80. package/dist/handlers/failure.d.ts.map +1 -1
  81. package/dist/handlers/failure.js +408 -13
  82. package/dist/handlers/failure.js.map +1 -1
  83. package/dist/handlers/goals.js +296 -4
  84. package/dist/handlers/intelligence.js +681 -126
  85. package/dist/handlers/invoicing.js +70 -1
  86. package/dist/handlers/mcpclient.js +137 -6
  87. package/dist/handlers/orchestration.js +125 -40
  88. package/dist/handlers/output-schemas.js +24 -1
  89. package/dist/handlers/presence.js +99 -3
  90. package/dist/handlers/project.js +182 -28
  91. package/dist/handlers/prompts.js +157 -6
  92. package/dist/handlers/quest.js +224 -4
  93. package/dist/handlers/recall.js +237 -13
  94. package/dist/handlers/registry.js +167 -1
  95. package/dist/handlers/resources.js +288 -1
  96. package/dist/handlers/review.js +74 -11
  97. package/dist/handlers/run.js +498 -16
  98. package/dist/handlers/search.js +338 -15
  99. package/dist/handlers/session.js +643 -31
  100. package/dist/handlers/share.js +184 -8
  101. package/dist/handlers/shims.js +464 -1
  102. package/dist/handlers/skill.js +449 -67
  103. package/dist/handlers/survivors.js +120 -1
  104. package/dist/handlers/symbols.js +109 -8
  105. package/dist/handlers/syncops.js +302 -4
  106. package/dist/handlers/types.js +27 -1
  107. package/dist/harvest.js +191 -5
  108. package/dist/hours.js +156 -7
  109. package/dist/http-auth.js +321 -3
  110. package/dist/http-fast.js +1302 -22
  111. package/dist/icons.js +47 -1
  112. package/dist/importers.js +268 -1
  113. package/dist/index.js +840 -2
  114. package/dist/indexer.js +145 -4
  115. package/dist/intelligence.js +261 -31
  116. package/dist/internal-dispatch.js +212 -3
  117. package/dist/keyset.js +110 -1
  118. package/dist/knowledge-graph.js +176 -12
  119. package/dist/license.js +441 -2
  120. package/dist/logger.js +199 -2
  121. package/dist/maintenance.js +148 -2
  122. package/dist/mcp-client.js +262 -6
  123. package/dist/memory-artifacts.js +596 -32
  124. package/dist/migrate-prompt.js +124 -2
  125. package/dist/migrations.d.ts.map +1 -1
  126. package/dist/migrations.js +799 -42
  127. package/dist/migrations.js.map +1 -1
  128. package/dist/performance.js +228 -1
  129. package/dist/presence.js +140 -11
  130. package/dist/priority-embed.js +164 -5
  131. package/dist/providers/embedding-provider.js +196 -1
  132. package/dist/readonly-gate.js +29 -1
  133. package/dist/receipt.js +43 -1
  134. package/dist/rehydration.js +157 -9
  135. package/dist/reindex.js +88 -1
  136. package/dist/render-target.js +544 -21
  137. package/dist/render.js +280 -4
  138. package/dist/repl-guard.js +173 -1
  139. package/dist/replication-daemon-entrypoint.js +31 -1
  140. package/dist/replication-daemon.js +262 -2
  141. package/dist/rerank.js +142 -1
  142. package/dist/resilience.js +591 -1
  143. package/dist/reverse-bridge.js +360 -5
  144. package/dist/security.js +244 -1
  145. package/dist/session-seen.js +51 -3
  146. package/dist/setup.js +260 -1
  147. package/dist/skill-author.js +168 -5
  148. package/dist/spec-kit.js +191 -1
  149. package/dist/sqlite-busy.js +154 -1
  150. package/dist/statusline.js +315 -11
  151. package/dist/sub-agent.js +262 -13
  152. package/dist/summarizer.js +139 -13
  153. package/dist/symbols.js +283 -7
  154. package/dist/sync.js +359 -5
  155. package/dist/tasks-dispatch.js +84 -1
  156. package/dist/tasks.js +282 -1
  157. package/dist/token-budget.js +143 -1
  158. package/dist/tool-analytics.js +129 -7
  159. package/dist/tool-annotations.js +365 -1
  160. package/dist/tool-manifest-v2.json +1 -1
  161. package/dist/tool-manifest.json +1 -1
  162. package/dist/tool-profiles.js +75 -1
  163. package/dist/trace-harvest.js +244 -6
  164. package/dist/types.js +30 -1
  165. package/dist/ui-dashboard.js +50 -41
  166. package/dist/ulid.js +81 -1
  167. package/dist/usage-tracker.js +66 -1
  168. package/dist/validate.js +129 -1
  169. package/dist/vault.js +534 -1
  170. package/dist/vector-init.js +67 -1
  171. package/dist/vectors.js +184 -3
  172. package/dist/version-check.js +136 -4
  173. package/dist/visibility.js +155 -19
  174. package/dist/wyrm-cli.js +2845 -101
  175. package/dist/wyrm-cli.js.map +1 -1
  176. package/dist/wyrm-guard.d.ts.map +1 -1
  177. package/dist/wyrm-guard.js +475 -14
  178. package/dist/wyrm-guard.js.map +1 -1
  179. package/dist/wyrm-loop.js +150 -3
  180. package/dist/wyrm-manifest.json +1 -1
  181. package/dist/wyrm-statusline-daemon.js +11 -1
  182. package/dist/wyrm-statusline.js +56 -4
  183. package/dist/wyrm-ui.js +77 -9
  184. package/package.json +1 -1
package/dist/http-auth.js CHANGED
@@ -1,3 +1,321 @@
1
- import{existsSync as w,readFileSync as I,writeFileSync as u,mkdirSync as R}from"fs";import{join as y}from"path";import{homedir as x}from"os";import{randomBytes as O,createHash as T}from"crypto";import{WyrmLogger as k}from"./logger.js";const g=y(x(),".wyrm"),a=y(g,"http-config.json"),L={enabled:!0,requests:100,windowMs:6e4},S=["http://localhost:3333","http://127.0.0.1:3333"],d=new Map;let c=null;const i=new k;function m(e){return T("sha256").update(e).digest("hex")}function P(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e.charCodeAt(n)^t.charCodeAt(n);return r===0}function M(){if(w(g)||R(g,{recursive:!0,mode:448}),w(a))try{const r=JSON.parse(I(a,"utf-8"));return{apiKeyHash:r.apiKeyHash,allowedOrigins:r.allowedOrigins||S,rateLimit:{...L,...r.rateLimit},requireAuth:r.requireAuth??!0,devMode:process.env.WYRM_DEV==="true"}}catch(r){i.error("Failed to load HTTP config, regenerating",{error:r.message})}const e=O(32).toString("hex");i.info("Generated new API key for HTTP server"),console.log(`
2
- `+"\u2550".repeat(60)),console.log("\u{1F510} WYRM API KEY (save this securely, shown once):"),console.log(""),console.log(` ${e}`),console.log(""),console.log(" Use with: Authorization: Bearer <key>"),console.log("\u2550".repeat(60)+`
3
- `);const t={apiKeyHash:m(e),allowedOrigins:S,rateLimit:L,requireAuth:!0,devMode:process.env.WYRM_DEV==="true"};return u(a,JSON.stringify(t,null,2),{mode:384}),t}function s(){return c||(c=M()),c}function N(e){const t=s();if(t.devMode){const h=e.socket.remoteAddress;if(h==="127.0.0.1"||h==="::1"||h==="::ffff:127.0.0.1")return!0}const r=e.socket.remoteAddress??"",n=r==="127.0.0.1"||r==="::1"||r==="::ffff:127.0.0.1",o=(e.headers.host??"").split(":")[0].toLowerCase();if(n&&(o==="localhost"||o==="127.0.0.1"||o==="::1"||o==="[::1]")&&e.headers["x-wyrm-origin"]==="ui")return!0;if(!t.requireAuth)return i.warn("Authentication disabled - API is open"),!0;const l=e.headers.authorization;if(!l||!l.startsWith("Bearer "))return!1;const f=l.slice(7);if(!f||f.length<32)return!1;const C=m(f);return P(C,t.apiKeyHash)}function H(e){const t=s();if(!t.rateLimit.enabled)return{allowed:!0,remaining:1/0,resetAt:0};const r=e.socket.remoteAddress||"unknown",n=Date.now();if(d.size>1e4)for(const[A,l]of d)l.resetAt<n&&d.delete(A);let o=d.get(r);return(!o||o.resetAt<n)&&(o={count:0,resetAt:n+t.rateLimit.windowMs},d.set(r,o)),o.count++,{allowed:o.count<=t.rateLimit.requests,remaining:Math.max(0,t.rateLimit.requests-o.count),resetAt:o.resetAt}}function v(e){const t=s(),r=e.headers.origin;return r&&t.allowedOrigins.includes(r)?r:t.allowedOrigins[0]}function p(e){return{"Access-Control-Allow-Origin":v(e),"Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization","X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Cache-Control":"no-store","Content-Security-Policy":"default-src 'none'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; frame-ancestors 'none'","Referrer-Policy":"no-referrer","Permissions-Policy":"geolocation=(), microphone=(), camera=()","X-Robots-Tag":"noindex, nofollow"}}const D=["/health","/auth/status","/ui"];function J(e,t){if(e.method==="OPTIONS"){const o=p(e);return t.writeHead(204,o),t.end(),{error:!0}}const r=H(e);if(!r.allowed){const o=p(e);return t.writeHead(429,{...o,"X-RateLimit-Remaining":"0","X-RateLimit-Reset":String(r.resetAt),"Retry-After":String(Math.ceil((r.resetAt-Date.now())/1e3))}),t.end(JSON.stringify({error:"Rate limit exceeded"})),i.warn("Rate limit exceeded",{ip:e.socket.remoteAddress,path:e.url}),{error:!0}}const n=new URL(e.url||"/","http://localhost").pathname;if(D.includes(n))return{error:!1};if(!N(e)){const o=p(e);return t.writeHead(401,{...o,"WWW-Authenticate":'Bearer realm="Wyrm API"'}),t.end(JSON.stringify({error:"Unauthorized"})),i.warn("Authentication failed",{ip:e.socket.remoteAddress,path:e.url}),{error:!0}}return{error:!1}}function _(){const e=O(32).toString("hex"),t=s();return t.apiKeyHash=m(e),u(a,JSON.stringify(t,null,2),{mode:384}),c=t,i.info("API key regenerated"),e}function U(e){const t=s();t.allowedOrigins=e,u(a,JSON.stringify(t,null,2),{mode:384}),c=t,i.info("CORS origins updated",{origins:e})}function z(e,t){const r=s();r.rateLimit={enabled:!0,requests:e,windowMs:t},u(a,JSON.stringify(r,null,2),{mode:384}),c=r,i.info("Rate limit updated",{requests:e,windowMs:t})}function B(e){const t=s();t.requireAuth=e,u(a,JSON.stringify(t,null,2),{mode:384}),c=t,e||i.warn("Authentication disabled - API is now open")}function G(){const e=s();e.devMode=!0}function X(){const e=s();return{requireAuth:e.requireAuth,devMode:e.devMode,rateLimit:e.rateLimit,allowedOrigins:e.allowedOrigins}}export{J as authMiddleware,N as authenticate,H as checkRateLimit,G as enableDevMode,X as getAuthStatus,v as getCorsOrigin,p as getSecurityHeaders,_ as regenerateApiKey,U as setAllowedOrigins,z as setRateLimit,B as setRequireAuth};
1
+ /**
2
+ * Wyrm HTTP Authentication - Secure API access control
3
+ *
4
+ * @copyright 2026 Ghost Protocol (Pvt) Ltd.
5
+ * @license Proprietary — (c) 2026 Ghost Protocol (Pvt) Ltd. All rights reserved. See LICENSE.
6
+ * @module http-auth
7
+ * @version 3.0.0
8
+ */
9
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
10
+ import { join } from 'path';
11
+ import { homedir } from 'os';
12
+ import { randomBytes, createHash } from 'crypto';
13
+ import { WyrmLogger } from './logger.js';
14
+ // ==================== CONSTANTS ====================
15
+ const CONFIG_DIR = join(homedir(), '.wyrm');
16
+ const CONFIG_PATH = join(CONFIG_DIR, 'http-config.json');
17
+ const DEFAULT_RATE_LIMIT = { enabled: true, requests: 100, windowMs: 60000 };
18
+ const DEFAULT_ORIGINS = ['http://localhost:3333', 'http://127.0.0.1:3333'];
19
+ // ==================== STATE ====================
20
+ const rateLimitStore = new Map();
21
+ let config = null;
22
+ const logger = new WyrmLogger();
23
+ // ==================== HELPER FUNCTIONS ====================
24
+ /**
25
+ * Hash a token for secure storage
26
+ */
27
+ function hashToken(token) {
28
+ return createHash('sha256').update(token).digest('hex');
29
+ }
30
+ /**
31
+ * Constant-time string comparison to prevent timing attacks
32
+ */
33
+ function constantTimeCompare(a, b) {
34
+ if (a.length !== b.length) {
35
+ return false;
36
+ }
37
+ let result = 0;
38
+ for (let i = 0; i < a.length; i++) {
39
+ result |= a.charCodeAt(i) ^ b.charCodeAt(i);
40
+ }
41
+ return result === 0;
42
+ }
43
+ /**
44
+ * Load or create authentication configuration
45
+ */
46
+ function loadOrCreateConfig() {
47
+ // Ensure config directory exists
48
+ if (!existsSync(CONFIG_DIR)) {
49
+ mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
50
+ }
51
+ // Load existing config
52
+ if (existsSync(CONFIG_PATH)) {
53
+ try {
54
+ const data = JSON.parse(readFileSync(CONFIG_PATH, 'utf-8'));
55
+ return {
56
+ apiKeyHash: data.apiKeyHash,
57
+ allowedOrigins: data.allowedOrigins || DEFAULT_ORIGINS,
58
+ rateLimit: { ...DEFAULT_RATE_LIMIT, ...data.rateLimit },
59
+ requireAuth: data.requireAuth ?? true,
60
+ devMode: process.env.WYRM_DEV === 'true',
61
+ };
62
+ }
63
+ catch (error) {
64
+ logger.error('Failed to load HTTP config, regenerating', { error: error.message });
65
+ }
66
+ }
67
+ // Generate new API key
68
+ const apiKey = randomBytes(32).toString('hex');
69
+ logger.info('Generated new API key for HTTP server');
70
+ console.log('\n' + '═'.repeat(60));
71
+ console.log('🔐 WYRM API KEY (save this securely, shown once):');
72
+ console.log('');
73
+ console.log(` ${apiKey}`);
74
+ console.log('');
75
+ console.log(' Use with: Authorization: Bearer <key>');
76
+ console.log('═'.repeat(60) + '\n');
77
+ const newConfig = {
78
+ apiKeyHash: hashToken(apiKey),
79
+ allowedOrigins: DEFAULT_ORIGINS,
80
+ rateLimit: DEFAULT_RATE_LIMIT,
81
+ requireAuth: true,
82
+ devMode: process.env.WYRM_DEV === 'true',
83
+ };
84
+ // Save config with restrictive permissions
85
+ writeFileSync(CONFIG_PATH, JSON.stringify(newConfig, null, 2), { mode: 0o600 });
86
+ return newConfig;
87
+ }
88
+ /**
89
+ * Get configuration (lazy load)
90
+ */
91
+ function getConfig() {
92
+ if (!config) {
93
+ config = loadOrCreateConfig();
94
+ }
95
+ return config;
96
+ }
97
+ // ==================== AUTHENTICATION ====================
98
+ /**
99
+ * Validate API key from Authorization header
100
+ */
101
+ export function authenticate(req) {
102
+ const cfg = getConfig();
103
+ // Dev mode: allow local connections without auth
104
+ if (cfg.devMode) {
105
+ const remoteAddr = req.socket.remoteAddress;
106
+ if (remoteAddr === '127.0.0.1' || remoteAddr === '::1' || remoteAddr === '::ffff:127.0.0.1') {
107
+ return true;
108
+ }
109
+ }
110
+ // Spec 016: the local Wyrm Web UI announces itself with X-Wyrm-Origin: ui.
111
+ // [sec 6.3.1] Hardened: require an EXACT loopback socket (dropped the broad
112
+ // `startsWith('127.')`) AND a loopback Host header. The Host check defeats
113
+ // DNS-rebinding — a rebinding attack reaches the loopback socket but carries
114
+ // an attacker-domain Host. Header alone is never sufficient. (A per-session
115
+ // UI nonce, tracked separately, will replace this origin-header trust.)
116
+ const remoteAddr = req.socket.remoteAddress ?? '';
117
+ const isLoopback = remoteAddr === '127.0.0.1' || remoteAddr === '::1' || remoteAddr === '::ffff:127.0.0.1';
118
+ const hostName = (req.headers['host'] ?? '').split(':')[0].toLowerCase();
119
+ const hostIsLoopback = hostName === 'localhost' || hostName === '127.0.0.1' || hostName === '::1' || hostName === '[::1]';
120
+ if (isLoopback && hostIsLoopback && req.headers['x-wyrm-origin'] === 'ui') {
121
+ return true;
122
+ }
123
+ // Check if auth is required
124
+ if (!cfg.requireAuth) {
125
+ logger.warn('Authentication disabled - API is open');
126
+ return true;
127
+ }
128
+ // Validate Authorization header
129
+ const authHeader = req.headers['authorization'];
130
+ if (!authHeader || !authHeader.startsWith('Bearer ')) {
131
+ return false;
132
+ }
133
+ const token = authHeader.slice(7);
134
+ if (!token || token.length < 32) {
135
+ return false;
136
+ }
137
+ // Constant-time comparison
138
+ const tokenHash = hashToken(token);
139
+ return constantTimeCompare(tokenHash, cfg.apiKeyHash);
140
+ }
141
+ // ==================== RATE LIMITING ====================
142
+ /**
143
+ * Check and update rate limit for a client
144
+ */
145
+ export function checkRateLimit(req) {
146
+ const cfg = getConfig();
147
+ if (!cfg.rateLimit.enabled) {
148
+ return { allowed: true, remaining: Infinity, resetAt: 0 };
149
+ }
150
+ const clientId = req.socket.remoteAddress || 'unknown';
151
+ const now = Date.now();
152
+ // Clean up expired entries periodically
153
+ if (rateLimitStore.size > 10000) {
154
+ for (const [key, entry] of rateLimitStore) {
155
+ if (entry.resetAt < now) {
156
+ rateLimitStore.delete(key);
157
+ }
158
+ }
159
+ }
160
+ let entry = rateLimitStore.get(clientId);
161
+ if (!entry || entry.resetAt < now) {
162
+ entry = { count: 0, resetAt: now + cfg.rateLimit.windowMs };
163
+ rateLimitStore.set(clientId, entry);
164
+ }
165
+ entry.count++;
166
+ return {
167
+ allowed: entry.count <= cfg.rateLimit.requests,
168
+ remaining: Math.max(0, cfg.rateLimit.requests - entry.count),
169
+ resetAt: entry.resetAt,
170
+ };
171
+ }
172
+ // ==================== CORS ====================
173
+ /**
174
+ * Get CORS origin for response
175
+ */
176
+ export function getCorsOrigin(req) {
177
+ const cfg = getConfig();
178
+ const origin = req.headers['origin'];
179
+ if (origin && cfg.allowedOrigins.includes(origin)) {
180
+ return origin;
181
+ }
182
+ // Return first allowed origin if request origin not in list
183
+ return cfg.allowedOrigins[0];
184
+ }
185
+ /**
186
+ * Get security headers for response
187
+ */
188
+ export function getSecurityHeaders(req) {
189
+ return {
190
+ 'Access-Control-Allow-Origin': getCorsOrigin(req),
191
+ 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
192
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization',
193
+ 'X-Content-Type-Options': 'nosniff',
194
+ 'X-Frame-Options': 'DENY',
195
+ 'Cache-Control': 'no-store',
196
+ 'Content-Security-Policy': "default-src 'none'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; frame-ancestors 'none'",
197
+ 'Referrer-Policy': 'no-referrer',
198
+ 'Permissions-Policy': 'geolocation=(), microphone=(), camera=()',
199
+ 'X-Robots-Tag': 'noindex, nofollow',
200
+ };
201
+ }
202
+ // ==================== MIDDLEWARE ====================
203
+ // Public endpoints that don't require authentication
204
+ const PUBLIC_ENDPOINTS = ['/health', '/auth/status', '/ui'];
205
+ /**
206
+ * Authentication middleware for HTTP server
207
+ * Returns error response if auth fails, null if auth passes
208
+ */
209
+ export function authMiddleware(req, res) {
210
+ // Handle CORS preflight
211
+ if (req.method === 'OPTIONS') {
212
+ const headers = getSecurityHeaders(req);
213
+ res.writeHead(204, headers);
214
+ res.end();
215
+ return { error: true }; // Request handled, stop processing
216
+ }
217
+ // Check rate limit (applies to all endpoints)
218
+ const rateLimit = checkRateLimit(req);
219
+ if (!rateLimit.allowed) {
220
+ const headers = getSecurityHeaders(req);
221
+ res.writeHead(429, {
222
+ ...headers,
223
+ 'X-RateLimit-Remaining': '0',
224
+ 'X-RateLimit-Reset': String(rateLimit.resetAt),
225
+ 'Retry-After': String(Math.ceil((rateLimit.resetAt - Date.now()) / 1000)),
226
+ });
227
+ res.end(JSON.stringify({ error: 'Rate limit exceeded' }));
228
+ logger.warn('Rate limit exceeded', {
229
+ ip: req.socket.remoteAddress,
230
+ path: req.url,
231
+ });
232
+ return { error: true };
233
+ }
234
+ // Skip auth for public endpoints
235
+ const pathname = new URL(req.url || '/', `http://localhost`).pathname;
236
+ if (PUBLIC_ENDPOINTS.includes(pathname)) {
237
+ return { error: false };
238
+ }
239
+ // Check authentication
240
+ if (!authenticate(req)) {
241
+ const headers = getSecurityHeaders(req);
242
+ res.writeHead(401, {
243
+ ...headers,
244
+ 'WWW-Authenticate': 'Bearer realm="Wyrm API"',
245
+ });
246
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
247
+ logger.warn('Authentication failed', {
248
+ ip: req.socket.remoteAddress,
249
+ path: req.url,
250
+ });
251
+ return { error: true };
252
+ }
253
+ // Add rate limit headers to successful response later
254
+ return { error: false };
255
+ }
256
+ // ==================== CONFIGURATION MANAGEMENT ====================
257
+ /**
258
+ * Regenerate API key
259
+ */
260
+ export function regenerateApiKey() {
261
+ const apiKey = randomBytes(32).toString('hex');
262
+ const cfg = getConfig();
263
+ cfg.apiKeyHash = hashToken(apiKey);
264
+ writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2), { mode: 0o600 });
265
+ config = cfg;
266
+ logger.info('API key regenerated');
267
+ return apiKey;
268
+ }
269
+ /**
270
+ * Update allowed CORS origins
271
+ */
272
+ export function setAllowedOrigins(origins) {
273
+ const cfg = getConfig();
274
+ cfg.allowedOrigins = origins;
275
+ writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2), { mode: 0o600 });
276
+ config = cfg;
277
+ logger.info('CORS origins updated', { origins });
278
+ }
279
+ /**
280
+ * Update rate limit configuration
281
+ */
282
+ export function setRateLimit(requests, windowMs) {
283
+ const cfg = getConfig();
284
+ cfg.rateLimit = { enabled: true, requests, windowMs };
285
+ writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2), { mode: 0o600 });
286
+ config = cfg;
287
+ logger.info('Rate limit updated', { requests, windowMs });
288
+ }
289
+ /**
290
+ * Enable/disable authentication requirement
291
+ */
292
+ export function setRequireAuth(require) {
293
+ const cfg = getConfig();
294
+ cfg.requireAuth = require;
295
+ writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2), { mode: 0o600 });
296
+ config = cfg;
297
+ if (!require) {
298
+ logger.warn('Authentication disabled - API is now open');
299
+ }
300
+ }
301
+ /**
302
+ * Enable dev mode at runtime (e.g. for --ui flag)
303
+ * Safe because auth still verifies remoteAddress is localhost
304
+ */
305
+ export function enableDevMode() {
306
+ const cfg = getConfig();
307
+ cfg.devMode = true;
308
+ }
309
+ /**
310
+ * Get current configuration (without exposing API key hash)
311
+ */
312
+ export function getAuthStatus() {
313
+ const cfg = getConfig();
314
+ return {
315
+ requireAuth: cfg.requireAuth,
316
+ devMode: cfg.devMode,
317
+ rateLimit: cfg.rateLimit,
318
+ allowedOrigins: cfg.allowedOrigins,
319
+ };
320
+ }
321
+ //# sourceMappingURL=http-auth.js.map