@nabasolution/runtime 0.0.0-stage → 0.1.0

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 (47) hide show
  1. package/LICENSE +21 -0
  2. package/dist/src/app.d.ts +60 -0
  3. package/dist/src/app.d.ts.map +1 -0
  4. package/dist/src/app.js +649 -0
  5. package/dist/src/app.js.map +1 -0
  6. package/dist/src/audit.d.ts +42 -0
  7. package/dist/src/audit.d.ts.map +1 -0
  8. package/dist/src/audit.js +53 -0
  9. package/dist/src/audit.js.map +1 -0
  10. package/dist/src/auth-guard.d.ts +27 -0
  11. package/dist/src/auth-guard.d.ts.map +1 -0
  12. package/dist/src/auth-guard.js +29 -0
  13. package/dist/src/auth-guard.js.map +1 -0
  14. package/dist/src/index.d.ts +14 -0
  15. package/dist/src/index.d.ts.map +1 -0
  16. package/dist/src/index.js +9 -0
  17. package/dist/src/index.js.map +1 -0
  18. package/dist/src/metrics.d.ts +26 -0
  19. package/dist/src/metrics.d.ts.map +1 -0
  20. package/dist/src/metrics.js +54 -0
  21. package/dist/src/metrics.js.map +1 -0
  22. package/dist/src/rate-limit.d.ts +40 -0
  23. package/dist/src/rate-limit.d.ts.map +1 -0
  24. package/dist/src/rate-limit.js +71 -0
  25. package/dist/src/rate-limit.js.map +1 -0
  26. package/dist/src/router.d.ts +21 -0
  27. package/dist/src/router.d.ts.map +1 -0
  28. package/dist/src/router.js +55 -0
  29. package/dist/src/router.js.map +1 -0
  30. package/dist/src/security.d.ts +35 -0
  31. package/dist/src/security.d.ts.map +1 -0
  32. package/dist/src/security.js +106 -0
  33. package/dist/src/security.js.map +1 -0
  34. package/dist/src/services.d.ts +10 -0
  35. package/dist/src/services.d.ts.map +1 -0
  36. package/dist/src/services.js +23 -0
  37. package/dist/src/services.js.map +1 -0
  38. package/dist/test/hardening.test.d.ts +2 -0
  39. package/dist/test/hardening.test.d.ts.map +1 -0
  40. package/dist/test/hardening.test.js +795 -0
  41. package/dist/test/hardening.test.js.map +1 -0
  42. package/dist/test/runtime.test.d.ts +2 -0
  43. package/dist/test/runtime.test.d.ts.map +1 -0
  44. package/dist/test/runtime.test.js +143 -0
  45. package/dist/test/runtime.test.js.map +1 -0
  46. package/package.json +47 -3
  47. package/README.md +0 -3
@@ -0,0 +1,649 @@
1
+ import { createServer } from "node:http";
2
+ import { createLogger, EventBus, getCountry, getRegistry, NabaError, normalizeTenantId } from "@nabasolution/core";
3
+ import { AuditLogger } from "./audit.js";
4
+ import { MetricsRegistry } from "./metrics.js";
5
+ import { FixedWindowRateLimiter } from "./rate-limit.js";
6
+ import { Router } from "./router.js";
7
+ import { clientKeyFromHeaders, finalizeResponse, isExemptPath, normalizePath, REQUEST_ID_HEADER, resolveRequestId } from "./security.js";
8
+ import { ServiceContainer } from "./services.js";
9
+ /** Re-type a handler's `NabaRequest` so runtime fields are required. */
10
+ export function routeContext(context) {
11
+ return context;
12
+ }
13
+ export function json(data, init) {
14
+ const headers = new Headers(init?.headers);
15
+ if (!headers.has("content-type")) {
16
+ headers.set("content-type", "application/json; charset=utf-8");
17
+ }
18
+ return new Response(JSON.stringify(data), { ...init, headers });
19
+ }
20
+ export function problem(status, code, message, details) {
21
+ return json({ error: { code, message, ...(details === undefined ? {} : { details }) } }, { status });
22
+ }
23
+ const MAX_BODY_BYTES = 5 * 1024 * 1024;
24
+ const DEFAULT_EXEMPT_PATHS = ["/api/health", "/metrics", "/"];
25
+ const STATE_CHANGING_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
26
+ class NabaApplication {
27
+ services = new ServiceContainer();
28
+ events = new EventBus();
29
+ routes = [];
30
+ config;
31
+ modules;
32
+ logger;
33
+ router = new Router();
34
+ startedAt = Date.now();
35
+ metrics = new MetricsRegistry();
36
+ metricsEnabled;
37
+ rateLimiter;
38
+ rateLimitExemptPaths = [...DEFAULT_EXEMPT_PATHS];
39
+ trustProxy;
40
+ auditPath;
41
+ injectedAuditSink;
42
+ authorizeHook;
43
+ audit;
44
+ initPromise;
45
+ started = false;
46
+ registered = false;
47
+ server;
48
+ stopped = false;
49
+ constructor(options) {
50
+ this.config = options.config;
51
+ this.modules = options.modules;
52
+ this.logger = options.logger ?? createLogger();
53
+ this.metricsEnabled = options.config.runtime?.metrics !== false;
54
+ this.trustProxy = options.config.runtime?.rateLimit?.trustProxy === true;
55
+ const rateLimit = options.config.runtime?.rateLimit;
56
+ if (rateLimit) {
57
+ this.rateLimitExemptPaths.push(...(rateLimit.exemptPaths ?? []));
58
+ }
59
+ if (options.rateLimiter) {
60
+ this.rateLimiter = options.rateLimiter;
61
+ }
62
+ else if (rateLimit) {
63
+ try {
64
+ this.rateLimiter = new FixedWindowRateLimiter({
65
+ windowMs: rateLimit.windowMs,
66
+ max: rateLimit.max
67
+ });
68
+ }
69
+ catch (error) {
70
+ throw new NabaError("INVALID_CONFIG", error instanceof Error ? error.message : "Invalid runtime.rateLimit configuration", { status: 500 });
71
+ }
72
+ }
73
+ this.auditPath = resolveAuditPath(options.config.runtime?.auditLog);
74
+ this.injectedAuditSink = options.auditSink;
75
+ this.authorizeHook = options.authorize;
76
+ this.registerBuiltinRoutes();
77
+ }
78
+ registerBuiltinRoutes() {
79
+ this.addRoute({
80
+ method: "GET",
81
+ path: "/api/health",
82
+ handler: () => json({
83
+ status: "ok",
84
+ app: this.config.app.name,
85
+ version: this.config.app.version ?? "0.1.0",
86
+ country: this.config.country.primary,
87
+ uptimeMs: Date.now() - this.startedAt,
88
+ modules: this.modules.map((module) => module.name)
89
+ })
90
+ });
91
+ this.addRoute({
92
+ method: "GET",
93
+ path: "/api/meta",
94
+ handler: () => {
95
+ const country = getCountry(this.config.country.primary);
96
+ const registry = getRegistry();
97
+ const providerOptions = (kind, ids) => ids.map((id) => ({ id, label: registry.getProvider(id, kind)?.label ?? id }));
98
+ return json({
99
+ app: {
100
+ name: this.config.app.name,
101
+ environment: this.config.app.environment ?? "development"
102
+ },
103
+ country: {
104
+ code: this.config.country.primary,
105
+ supported: this.config.country.supported ?? [this.config.country.primary],
106
+ ...(country
107
+ ? {
108
+ name: country.name,
109
+ flag: country.flag,
110
+ currency: country.currency,
111
+ locale: country.locale,
112
+ timezone: country.timezone,
113
+ phonePrefix: country.phonePrefix,
114
+ postalCode: country.postalCode,
115
+ tax: country.tax
116
+ }
117
+ : {})
118
+ },
119
+ frontend: this.config.frontend ?? { framework: "none" },
120
+ database: this.config.database ?? { provider: "memory" },
121
+ architecture: this.config.architecture ?? "modular-monolith",
122
+ integrations: this.config.integrations,
123
+ providers: {
124
+ payments: providerOptions("payment", this.config.integrations.payments),
125
+ shipping: providerOptions("shipping", this.config.integrations.shipping),
126
+ sms: providerOptions("sms", this.config.integrations.sms ?? []),
127
+ email: providerOptions("email", this.config.integrations.email ?? [])
128
+ },
129
+ modules: this.modules.map((module) => module.name)
130
+ });
131
+ }
132
+ });
133
+ this.addRoute({
134
+ method: "GET",
135
+ path: "/api/routes",
136
+ handler: () => json({ routes: this.router.list() })
137
+ });
138
+ if (this.metricsEnabled) {
139
+ this.addRoute({
140
+ method: "GET",
141
+ path: "/metrics",
142
+ handler: () => new Response(this.metrics.render(this.uptimeSeconds()), {
143
+ status: 200,
144
+ headers: {
145
+ "content-type": "text/plain; version=0.0.4; charset=utf-8",
146
+ "cache-control": "no-store"
147
+ }
148
+ })
149
+ });
150
+ }
151
+ }
152
+ addRoute(route) {
153
+ this.router.add(route);
154
+ this.routes.push({ method: route.method, path: route.path });
155
+ }
156
+ initialize() {
157
+ if (!this.initPromise) {
158
+ this.initPromise = this.initializeAll();
159
+ }
160
+ return this.initPromise;
161
+ }
162
+ async initializeAll() {
163
+ if (this.injectedAuditSink) {
164
+ // Injected sink wins over runtime.auditLog.
165
+ this.audit = this.injectedAuditSink;
166
+ }
167
+ else if (this.auditPath && !this.audit) {
168
+ try {
169
+ this.audit = await AuditLogger.create(this.auditPath);
170
+ }
171
+ catch (error) {
172
+ throw new NabaError("AUDIT_LOG_UNAVAILABLE", `Could not initialize audit log at ${this.auditPath}`, {
173
+ status: 500,
174
+ details: { path: this.auditPath, reason: error instanceof Error ? error.message : String(error) }
175
+ });
176
+ }
177
+ }
178
+ await this.initializeModules();
179
+ }
180
+ async initializeModules() {
181
+ const context = {
182
+ config: this.config,
183
+ events: this.events,
184
+ logger: this.logger,
185
+ services: this.services,
186
+ addRoute: (route) => this.addRoute(route)
187
+ };
188
+ for (const module of this.modules) {
189
+ try {
190
+ await module.register(context);
191
+ this.logger.debug("module registered", { module: module.name });
192
+ }
193
+ catch (error) {
194
+ this.logger.error("module registration failed", {
195
+ module: module.name,
196
+ error: error instanceof Error ? error.message : String(error)
197
+ });
198
+ throw error;
199
+ }
200
+ }
201
+ this.registered = true;
202
+ }
203
+ async handle(request) {
204
+ const requestId = resolveRequestId(request.headers.get(REQUEST_ID_HEADER));
205
+ const clientKey = clientKeyFromHeaders(request.headers, this.trustProxy);
206
+ let tenantId = tenantFromHeaders(this.config, request.headers);
207
+ const url = new URL(request.url);
208
+ const pathname = url.pathname;
209
+ const started = performance.now();
210
+ let response;
211
+ try {
212
+ await this.initialize();
213
+ // Rate-limit first so unauthenticated floods do not bypass the limiter
214
+ // (authorization failures must consume quota too).
215
+ response = await this.checkRateLimit(request.method, pathname, clientKey);
216
+ if (!response) {
217
+ const principal = await this.runAuthorization(request, pathname);
218
+ if (principal && typeof principal["tenantId"] === "string") {
219
+ tenantId = normalizeTenantId(principal["tenantId"]);
220
+ }
221
+ }
222
+ if (!response) {
223
+ const declared = Number(request.headers.get("content-length") ?? "0");
224
+ if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) {
225
+ response = problem(413, "PAYLOAD_TOO_LARGE", "Request body exceeds 5 MB");
226
+ }
227
+ }
228
+ if (!response) {
229
+ response = await this.dispatch(request, requestId, clientKey, tenantId);
230
+ }
231
+ }
232
+ catch (error) {
233
+ response = this.toErrorResponse(error);
234
+ }
235
+ const durationMs = performance.now() - started;
236
+ this.recordRequestMetrics(pathname, response.status, durationMs);
237
+ if (STATE_CHANGING_METHODS.has(request.method)) {
238
+ this.recordAudit({
239
+ timestamp: new Date().toISOString(),
240
+ requestId,
241
+ method: request.method,
242
+ path: pathname,
243
+ status: response.status,
244
+ durationMs: roundMs(durationMs),
245
+ clientKey,
246
+ tenantId
247
+ });
248
+ }
249
+ return finalizeResponse(response, requestId);
250
+ }
251
+ /**
252
+ * Optional enforcement hook. Public routes, metrics, health/meta, CORS
253
+ * preflights, auth token/verify and webhook callbacks are never gated.
254
+ */
255
+ async runAuthorization(request, pathname) {
256
+ if (!this.authorizeHook)
257
+ return;
258
+ if (isAuthorizationExempt(request.method, pathname))
259
+ return;
260
+ try {
261
+ return await this.authorizeHook(request);
262
+ }
263
+ catch (error) {
264
+ // Authorization primitives should surface as 401/403 even when the hook
265
+ // forgot to set a status on its NabaError.
266
+ if (error instanceof NabaError) {
267
+ const status = error.code === "UNAUTHORIZED" ? 401 : error.code === "FORBIDDEN" ? 403 : error.status;
268
+ if (status !== error.status) {
269
+ throw new NabaError(error.code, error.message, { status, details: error.details });
270
+ }
271
+ }
272
+ throw error;
273
+ }
274
+ }
275
+ /**
276
+ * Returns a 429 response when the client is over its window, otherwise
277
+ * undefined. OPTIONS preflights and exempt paths never consume quota.
278
+ */
279
+ async checkRateLimit(method, pathname, clientKey) {
280
+ if (!this.rateLimiter)
281
+ return undefined;
282
+ if (method === "OPTIONS")
283
+ return undefined;
284
+ if (isExemptPath(pathname, this.rateLimitExemptPaths))
285
+ return undefined;
286
+ const decision = await this.rateLimiter.consume(clientKey);
287
+ if (decision.allowed)
288
+ return undefined;
289
+ this.metrics.recordRateLimited();
290
+ const response = problem(429, "RATE_LIMITED", "Too many requests", {
291
+ retryAfter: decision.retryAfter
292
+ });
293
+ response.headers.set("retry-after", String(decision.retryAfter));
294
+ return response;
295
+ }
296
+ async dispatch(request, requestId, clientKey, tenantId) {
297
+ const url = new URL(request.url);
298
+ if (request.method === "OPTIONS") {
299
+ return new Response(null, { status: 204 });
300
+ }
301
+ if (url.pathname === "/" && request.method === "GET") {
302
+ return new Response(this.indexHtml(), {
303
+ status: 200,
304
+ headers: { "content-type": "text/html; charset=utf-8" }
305
+ });
306
+ }
307
+ const matched = this.router.match(request.method, url.pathname);
308
+ if (!matched) {
309
+ return problem(404, "ROUTE_NOT_FOUND", `No route for ${request.method} ${url.pathname}`);
310
+ }
311
+ const context = {
312
+ request,
313
+ params: matched.params,
314
+ query: url.searchParams,
315
+ services: this.services,
316
+ requestId,
317
+ clientKey,
318
+ tenantId,
319
+ json: async () => {
320
+ try {
321
+ return (await request.clone().json());
322
+ }
323
+ catch {
324
+ throw new NabaError("INVALID_JSON", "Request body must be valid JSON", { status: 400 });
325
+ }
326
+ }
327
+ };
328
+ return matched.route.handler(context);
329
+ }
330
+ recordRequestMetrics(pathname, status, durationMs) {
331
+ // Scrapes are excluded so the counters describe real traffic, not the
332
+ // monitor. The endpoint itself is still CORS/security-headered.
333
+ if (normalizePath(pathname) === "/metrics")
334
+ return;
335
+ this.metrics.recordRequest();
336
+ this.metrics.recordResponse(status, durationMs);
337
+ }
338
+ recordAudit(entry) {
339
+ if (!this.audit)
340
+ return;
341
+ try {
342
+ const result = this.audit.record(entry);
343
+ if (result && typeof result.then === "function") {
344
+ void result.catch((error) => {
345
+ this.logger.error("audit sink record failed", {
346
+ error: error instanceof Error ? error.message : String(error)
347
+ });
348
+ });
349
+ }
350
+ }
351
+ catch (error) {
352
+ this.logger.error("audit sink record failed", {
353
+ error: error instanceof Error ? error.message : String(error)
354
+ });
355
+ }
356
+ }
357
+ uptimeSeconds() {
358
+ return (Date.now() - this.startedAt) / 1000;
359
+ }
360
+ toErrorResponse(error) {
361
+ if (error instanceof NabaError) {
362
+ return problem(error.status, error.code, error.message, error.details);
363
+ }
364
+ this.logger.error("unhandled request error", {
365
+ error: error instanceof Error ? error.message : String(error)
366
+ });
367
+ return problem(500, "INTERNAL_ERROR", "An unexpected error occurred");
368
+ }
369
+ indexHtml() {
370
+ const name = escapeHtml(this.config.app.name);
371
+ const country = escapeHtml(this.config.country.primary);
372
+ return `<!doctype html>
373
+ <html lang="en">
374
+ <head>
375
+ <meta charset="utf-8" />
376
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
377
+ <title>${name} · NABA</title>
378
+ <style>
379
+ :root { color-scheme: dark; --bg:#070b12; --panel:#0f1724; --text:#e8f0ff; --muted:#8ba0bd; --accent:#39e0b0; }
380
+ * { box-sizing: border-box; }
381
+ body { margin:0; min-height:100vh; display:grid; place-items:center; font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; background: radial-gradient(60% 60% at 50% 0%, #10253b 0%, var(--bg) 70%); color:var(--text); }
382
+ main { width:min(620px, 92vw); background:linear-gradient(180deg,#0f1b2b,#0a111c); border:1px solid #1d2f46; border-radius:20px; padding:36px; box-shadow:0 30px 80px rgba(0,0,0,.5); }
383
+ .badge { display:inline-flex; gap:8px; align-items:center; font-size:12px; letter-spacing:.12em; text-transform:uppercase; color:var(--accent); border:1px solid #1f5a4a; background:#0b2a23; padding:6px 10px; border-radius:999px; }
384
+ h1 { font-size:34px; margin:18px 0 6px; letter-spacing:-.03em; }
385
+ p { color:var(--muted); line-height:1.6; margin:0 0 22px; }
386
+ .links { display:flex; flex-wrap:wrap; gap:10px; }
387
+ a { color:var(--text); text-decoration:none; border:1px solid #24405e; background:#101c2c; padding:10px 14px; border-radius:10px; font-size:14px; }
388
+ a:hover, a:focus-visible { border-color:var(--accent); outline:none; }
389
+ code { color:var(--accent); background:#0b2a23; padding:2px 6px; border-radius:6px; }
390
+ footer { margin-top:26px; color:#61748e; font-size:12px; }
391
+ </style>
392
+ </head>
393
+ <body>
394
+ <main>
395
+ <span class="badge">NABA runtime · ${country}</span>
396
+ <h1>${name}</h1>
397
+ <p>Your generated application is running. Explore the JSON API or open the React storefront in <code>apps/web</code>.</p>
398
+ <div class="links">
399
+ <a href="/api/health">Health</a>
400
+ <a href="/api/meta">Meta</a>
401
+ <a href="/api/catalog">Catalog</a>
402
+ <a href="/api/routes">Routes</a>
403
+ </div>
404
+ <footer>NABA v0.1 · modular monolith · country-aware</footer>
405
+ </main>
406
+ </body>
407
+ </html>`;
408
+ }
409
+ async listen(port, host) {
410
+ await this.initialize();
411
+ if (!this.started) {
412
+ for (const module of this.modules) {
413
+ await module.start?.();
414
+ }
415
+ this.started = true;
416
+ }
417
+ const listenPort = port ?? this.config.runtime?.port ?? 3000;
418
+ const listenHost = host ?? this.config.runtime?.host ?? "127.0.0.1";
419
+ this.server = createServer((req, res) => {
420
+ void this.handleNodeRequest(req, res);
421
+ });
422
+ await new Promise((resolve, reject) => {
423
+ this.server?.once("error", reject);
424
+ this.server?.listen(listenPort, listenHost, () => resolve());
425
+ });
426
+ const address = this.server.address();
427
+ const actualPort = typeof address === "object" && address ? address.port : listenPort;
428
+ const displayHost = listenHost === "0.0.0.0" || listenHost === "127.0.0.1" ? "localhost" : listenHost;
429
+ return { url: `http://${displayHost}:${actualPort}`, close: () => this.close() };
430
+ }
431
+ async handleNodeRequest(req, res) {
432
+ try {
433
+ const headers = nodeHeaders(req);
434
+ // Reject declared-oversized bodies before buffering anything. Draining the
435
+ // request (rather than destroying the socket) keeps the 413 deliverable.
436
+ const declared = Number(req.headers["content-length"] ?? "0");
437
+ if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) {
438
+ req.resume();
439
+ await this.rejectNodeRequest(req, res, headers, 413, "PAYLOAD_TOO_LARGE", "Request body exceeds 5 MB");
440
+ return;
441
+ }
442
+ const chunks = [];
443
+ let totalBytes = 0;
444
+ let tooLarge = false;
445
+ for await (const chunk of req) {
446
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
447
+ totalBytes += buffer.length;
448
+ if (totalBytes > MAX_BODY_BYTES) {
449
+ // Stop buffering but finish reading so the response can be flushed.
450
+ tooLarge = true;
451
+ chunks.length = 0;
452
+ continue;
453
+ }
454
+ if (!tooLarge)
455
+ chunks.push(buffer);
456
+ }
457
+ if (tooLarge) {
458
+ await this.rejectNodeRequest(req, res, headers, 413, "PAYLOAD_TOO_LARGE", "Request body exceeds 5 MB");
459
+ return;
460
+ }
461
+ const method = req.method ?? "GET";
462
+ const hasBody = method !== "GET" && method !== "HEAD" && chunks.length > 0;
463
+ const request = new Request(`http://${req.headers.host ?? "localhost"}${req.url ?? "/"}`, {
464
+ method,
465
+ headers,
466
+ ...(hasBody ? { body: new Uint8Array(Buffer.concat(chunks)) } : {})
467
+ });
468
+ const response = await this.handle(request);
469
+ await this.writeNodeResponse(res, response);
470
+ }
471
+ catch (error) {
472
+ this.logger.error("node request failed", {
473
+ error: error instanceof Error ? error.message : String(error)
474
+ });
475
+ const response = finalizeResponse(problem(500, "INTERNAL_ERROR", "Request failed"), resolveRequestId(null));
476
+ if (!res.headersSent) {
477
+ await this.writeNodeResponse(res, response);
478
+ }
479
+ else {
480
+ res.end();
481
+ }
482
+ }
483
+ }
484
+ /**
485
+ * Oversized bodies are rejected in the node adapter before a Request can be
486
+ * built. They still go through rate limiting, metrics, audit and the same
487
+ * header finalizer as every other response.
488
+ */
489
+ async rejectNodeRequest(req, res, headers, status, code, message) {
490
+ const method = req.method ?? "GET";
491
+ const pathname = (req.url ?? "/").split("?")[0] || "/";
492
+ const requestId = resolveRequestId(headers.get(REQUEST_ID_HEADER));
493
+ const clientKey = clientKeyFromHeaders(headers, this.trustProxy);
494
+ let tenantId = tenantFromHeaders(this.config, headers);
495
+ const started = performance.now();
496
+ let response;
497
+ response = await this.checkRateLimit(method, pathname, clientKey);
498
+ if (!response) {
499
+ try {
500
+ // Authorization still applies to oversized requests. The body is not
501
+ // available (and must not be buffered), so the hook only sees metadata.
502
+ const authHeaders = new Headers();
503
+ headers.forEach((value, key) => {
504
+ if (key === "content-length" || key === "transfer-encoding")
505
+ return;
506
+ authHeaders.set(key, value);
507
+ });
508
+ const authRequest = new Request(`http://${req.headers.host ?? "localhost"}${req.url ?? "/"}`, { method, headers: authHeaders });
509
+ const principal = await this.runAuthorization(authRequest, pathname);
510
+ if (principal && typeof principal["tenantId"] === "string") {
511
+ tenantId = normalizeTenantId(principal["tenantId"]);
512
+ }
513
+ }
514
+ catch (error) {
515
+ response = this.toErrorResponse(error);
516
+ }
517
+ }
518
+ if (!response)
519
+ response = problem(status, code, message);
520
+ const durationMs = performance.now() - started;
521
+ this.recordRequestMetrics(pathname, response.status, durationMs);
522
+ if (STATE_CHANGING_METHODS.has(method)) {
523
+ this.recordAudit({
524
+ timestamp: new Date().toISOString(),
525
+ requestId,
526
+ method,
527
+ path: pathname,
528
+ status: response.status,
529
+ durationMs: roundMs(durationMs),
530
+ clientKey,
531
+ tenantId
532
+ });
533
+ }
534
+ await this.writeNodeResponse(res, finalizeResponse(response, requestId));
535
+ }
536
+ async writeNodeResponse(res, response) {
537
+ const responseHeaders = {};
538
+ response.headers.forEach((value, key) => {
539
+ responseHeaders[key] = value;
540
+ });
541
+ res.writeHead(response.status, responseHeaders);
542
+ const body = Buffer.from(await response.arrayBuffer());
543
+ res.end(body.length > 0 ? body : undefined);
544
+ }
545
+ async close() {
546
+ if (this.stopped)
547
+ return;
548
+ this.stopped = true;
549
+ if (this.server) {
550
+ await new Promise((resolve) => {
551
+ this.server?.close(() => resolve());
552
+ });
553
+ this.server = undefined;
554
+ }
555
+ if (this.registered) {
556
+ for (const module of [...this.modules].reverse()) {
557
+ await module.stop?.();
558
+ }
559
+ this.started = false;
560
+ this.registered = false;
561
+ }
562
+ const sink = this.audit ?? this.injectedAuditSink;
563
+ this.audit = undefined;
564
+ if (sink) {
565
+ try {
566
+ await sink.flush();
567
+ }
568
+ finally {
569
+ await sink.close();
570
+ }
571
+ }
572
+ }
573
+ }
574
+ function resolveAuditPath(configured) {
575
+ if (configured === false)
576
+ return undefined;
577
+ if (typeof configured === "string" && configured.trim())
578
+ return configured.trim();
579
+ const fromEnv = process.env.NABA_AUDIT_LOG?.trim();
580
+ return fromEnv ? fromEnv : undefined;
581
+ }
582
+ const TENANT_HEADER = "x-naba-tenant";
583
+ const AUTH_EXEMPT_PATHS = new Set(["/", "/api/health", "/api/meta", "/metrics"]);
584
+ /**
585
+ * Authorization is never required for the landing page, probes, metrics,
586
+ * preflights, token/verify endpoints or inbound webhook callbacks.
587
+ */
588
+ function isAuthorizationExempt(method, pathname) {
589
+ if (method === "OPTIONS")
590
+ return true;
591
+ const path = normalizePath(pathname);
592
+ if (AUTH_EXEMPT_PATHS.has(path))
593
+ return true;
594
+ return (path === "/api/auth" ||
595
+ path.startsWith("/api/auth/") ||
596
+ path === "/api/webhooks" ||
597
+ path.startsWith("/api/webhooks/"));
598
+ }
599
+ /**
600
+ * Derive the tenant for this request.
601
+ *
602
+ * The tenant header is a development/integration convenience only. Production
603
+ * ignores it unless NABA_ALLOW_TENANT_HEADER=1 is explicitly set (for
604
+ * deployments where a trusted gateway sets it). x-forwarded-* is never used.
605
+ */
606
+ function tenantFromHeaders(config, headers) {
607
+ if (process.env.NABA_ALLOW_TENANT_HEADER !== "1")
608
+ return normalizeTenantId(undefined);
609
+ return normalizeTenantId(headers.get(TENANT_HEADER));
610
+ }
611
+ function roundMs(value) {
612
+ return Math.round(value * 100) / 100;
613
+ }
614
+ function nodeHeaders(req) {
615
+ const headers = new Headers();
616
+ for (const [key, value] of Object.entries(req.headers)) {
617
+ if (value === undefined)
618
+ continue;
619
+ if (Array.isArray(value))
620
+ headers.set(key, value.join(", "));
621
+ else
622
+ headers.set(key, value);
623
+ }
624
+ if (!headers.has("x-real-ip") && req.socket.remoteAddress) {
625
+ headers.set("x-real-ip", req.socket.remoteAddress);
626
+ }
627
+ if (req.socket.remoteAddress) {
628
+ // Always overwrite: rate limiting must never trust a client-supplied value.
629
+ headers.set("x-naba-remote-address", req.socket.remoteAddress);
630
+ }
631
+ return headers;
632
+ }
633
+ export function createApp(options) {
634
+ if (!options.config?.app?.name) {
635
+ throw new NabaError("INVALID_CONFIG", "config.app.name is required", { status: 500 });
636
+ }
637
+ if (!Array.isArray(options.modules)) {
638
+ throw new NabaError("INVALID_CONFIG", "modules must be an array", { status: 500 });
639
+ }
640
+ return new NabaApplication(options);
641
+ }
642
+ function escapeHtml(value) {
643
+ return value
644
+ .replaceAll("&", "&amp;")
645
+ .replaceAll("<", "&lt;")
646
+ .replaceAll(">", "&gt;")
647
+ .replaceAll('"', "&quot;");
648
+ }
649
+ //# sourceMappingURL=app.js.map