@zaaxch/grasp-server 0.0.0-stage → 0.2.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.
package/dist/http.js ADDED
@@ -0,0 +1,640 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { existsSync } from 'node:fs';
3
+ import { resolve } from 'node:path';
4
+ import { BILLING_INTERVALS, GraspError, getProcedureContract, getStreamContract, okEnvelope, parseContractInput, parseContractOutput, parseOperationPath, parseStreamEvent, serializeUnknownError, } from '@zaaxch/grasp-core';
5
+ import express, {} from 'express';
6
+ import { z } from 'zod';
7
+ import { assertProcedureEntitlement } from './billing.js';
8
+ import { createBaseContext, graspHttpResponseBuilder, } from './features.js';
9
+ function getRequestId(res) {
10
+ return res.locals.requestId ?? randomUUID();
11
+ }
12
+ function extractBearerToken(req) {
13
+ const raw = req.header('authorization');
14
+ if (!raw)
15
+ return undefined;
16
+ const match = /^Bearer\s+(.+)$/i.exec(raw.trim());
17
+ return match?.[1]?.trim() || undefined;
18
+ }
19
+ const planCheckoutSchema = z.object({
20
+ planId: z.string().min(1),
21
+ interval: z.enum(BILLING_INTERVALS),
22
+ successUrl: z.url().optional(),
23
+ cancelUrl: z.url().optional(),
24
+ });
25
+ const creditCheckoutSchema = z.object({
26
+ packId: z.string().min(1),
27
+ successUrl: z.url().optional(),
28
+ cancelUrl: z.url().optional(),
29
+ });
30
+ const portalSchema = z.object({
31
+ returnUrl: z.url().optional(),
32
+ });
33
+ const devTokenBodySchema = z.object({
34
+ uid: z.string().min(1),
35
+ });
36
+ const LOCAL_DEV_ORIGIN_REGEX = /^https?:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?$/i;
37
+ function createCorsOriginMatcher(config, env) {
38
+ const exactOrigins = new Set([
39
+ ...config.cors.origins,
40
+ ...(config.app.domain === 'localhost' ? [] : [`https://${config.app.domain}`]),
41
+ ]);
42
+ const baseUrl = env['APP_BASE_URL']?.trim();
43
+ if (baseUrl) {
44
+ try {
45
+ exactOrigins.add(new URL(baseUrl).origin);
46
+ }
47
+ catch {
48
+ // Ignore malformed APP_BASE_URL override
49
+ }
50
+ }
51
+ if (config.cors.originsEnvVar) {
52
+ const rawCsv = env[config.cors.originsEnvVar];
53
+ if (rawCsv) {
54
+ for (const entry of rawCsv.split(',')) {
55
+ const trimmed = entry.trim();
56
+ if (trimmed)
57
+ exactOrigins.add(trimmed);
58
+ }
59
+ }
60
+ }
61
+ const patterns = config.cors.originPatterns.map((p) => new RegExp(p));
62
+ const isProd = env['NODE_ENV'] === 'production';
63
+ return (origin) => {
64
+ if (exactOrigins.has(origin))
65
+ return true;
66
+ if (patterns.some((re) => re.test(origin)))
67
+ return true;
68
+ if (!isProd && LOCAL_DEV_ORIGIN_REGEX.test(origin))
69
+ return true;
70
+ return false;
71
+ };
72
+ }
73
+ export function createGraspServer(options) {
74
+ const { config, appContract, features, store, redis, auth, devAuth, billing, email, logger } = options;
75
+ const env = options.env ?? process.env;
76
+ if (devAuth !== undefined && env['NODE_ENV'] === 'production') {
77
+ throw GraspError.internal('Dev auth cannot be mounted in production');
78
+ }
79
+ const app = express();
80
+ app.disable('x-powered-by');
81
+ if (options.trustProxy !== undefined) {
82
+ app.set('trust proxy', options.trustProxy);
83
+ }
84
+ const isOriginAllowed = createCorsOriginMatcher(config, env);
85
+ app.use((req, res, next) => {
86
+ const requestId = req.header('x-request-id')?.trim() || randomUUID();
87
+ res.locals.requestId = requestId;
88
+ res.setHeader('x-request-id', requestId);
89
+ res.setHeader('x-content-type-options', 'nosniff');
90
+ res.setHeader('x-frame-options', 'DENY');
91
+ res.setHeader('referrer-policy', 'strict-origin-when-cross-origin');
92
+ const origin = req.header('origin')?.trim();
93
+ if (origin) {
94
+ const allowed = isOriginAllowed(origin);
95
+ res.setHeader('Vary', 'Origin');
96
+ if (allowed) {
97
+ res.setHeader('Access-Control-Allow-Origin', origin);
98
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
99
+ res.setHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type, X-Grasp-Client, X-Requested-With, X-Request-Id');
100
+ res.setHeader('Access-Control-Max-Age', '600');
101
+ }
102
+ if (req.method === 'OPTIONS') {
103
+ if (!allowed) {
104
+ res
105
+ .status(403)
106
+ .json(GraspError.forbidden(`Origin "${origin}" is not allowed`).toEnvelope(requestId));
107
+ return;
108
+ }
109
+ res.status(204).end();
110
+ return;
111
+ }
112
+ }
113
+ next();
114
+ });
115
+ // Stripe webhook requires exact unmodified raw request bytes; isolated BEFORE JSON parsing & CSRF header check
116
+ app.post('/api/webhooks/stripe', express.raw({ type: 'application/json', limit: '2mb' }), async (req, res, next) => {
117
+ try {
118
+ const signature = req.header('stripe-signature');
119
+ if (!signature) {
120
+ throw GraspError.forbidden('Missing stripe-signature header');
121
+ }
122
+ const rawBody = Buffer.isBuffer(req.body)
123
+ ? req.body
124
+ : typeof req.body === 'string'
125
+ ? Buffer.from(req.body, 'utf8')
126
+ : Buffer.alloc(0);
127
+ const outcome = await billing.processWebhook({ rawBody, signature });
128
+ res.json(okEnvelope(outcome));
129
+ }
130
+ catch (err) {
131
+ next(err);
132
+ }
133
+ });
134
+ const resolveActor = async (mode, req) => {
135
+ if (mode === 'public' || !config.auth.enabled) {
136
+ if (mode === 'user' && !config.auth.enabled) {
137
+ throw GraspError.unauthenticated('Authentication is disabled for this application');
138
+ }
139
+ return { user: null, principal: null, entitlement: null };
140
+ }
141
+ const token = extractBearerToken(req);
142
+ if (!token) {
143
+ if (mode === 'user') {
144
+ throw GraspError.unauthenticated('Authentication required');
145
+ }
146
+ return { user: null, principal: null, entitlement: null };
147
+ }
148
+ const principal = await auth.verifyBearerToken(token);
149
+ const storedUser = await store.users.upsertBySubject({
150
+ id: principal.uid,
151
+ email: principal.email ?? null,
152
+ displayName: principal.displayName ?? null,
153
+ avatarUrl: principal.avatarUrl ?? null,
154
+ });
155
+ const user = {
156
+ ...storedUser,
157
+ emailVerified: Boolean(principal.emailVerified),
158
+ };
159
+ const entitlement = await billing.resolveEntitlementForUser(user.id);
160
+ return { user, principal, entitlement };
161
+ };
162
+ const buildRequestContext = (requestId, actor) => ({
163
+ ...createBaseContext({
164
+ db: options.db ?? store,
165
+ store,
166
+ locks: redis.locks,
167
+ cache: redis.cache,
168
+ sseBus: redis.sseBus,
169
+ notifyWakeup: () => redis.notifyWakeup('outbox'),
170
+ email,
171
+ log: logger.child({ requestId, ...(actor.user ? { userId: actor.user.id } : {}) }),
172
+ }),
173
+ requestId,
174
+ user: actor.user,
175
+ principal: actor.principal,
176
+ entitlement: actor.entitlement,
177
+ });
178
+ // Mount declared feature HTTP routes (OAuth callbacks, custom redirects/webhooks) before CSRF & /api catch-all
179
+ const jsonParser = express.json({ limit: options.jsonLimit ?? '1mb' });
180
+ for (const feature of Object.values(features)) {
181
+ for (const [routeKey, routeDef] of Object.entries(feature.httpContracts)) {
182
+ const handler = feature.httpRoutes[routeKey];
183
+ if (!handler) {
184
+ throw GraspError.internal(`No server handler registered for HTTP route "${feature.name}.${routeKey}"`);
185
+ }
186
+ const methodKey = routeDef.method.toLowerCase();
187
+ app[methodKey](routeDef.path, jsonParser, async (req, res, next) => {
188
+ try {
189
+ const requestId = getRequestId(res);
190
+ const actor = await resolveActor(routeDef.auth, req);
191
+ if (routeDef.rateLimit) {
192
+ const subjectKey = routeDef.rateLimit.scope === 'user' && actor.user
193
+ ? `user:${actor.user.id}`
194
+ : `ip:${req.ip || 'unknown'}`;
195
+ await redis.rateLimiter.assertWithinLimit(`http:${feature.name}.${routeKey}:${subjectKey}`, routeDef.rateLimit);
196
+ }
197
+ assertProcedureEntitlement(config, actor.entitlement, routeDef.entitlement);
198
+ const parsedParams = routeDef.hasParams
199
+ ? parseContractInput(routeDef.params, req.params)
200
+ : req.params;
201
+ const parsedQuery = routeDef.hasQuery
202
+ ? parseContractInput(routeDef.query, req.query)
203
+ : req.query;
204
+ const parsedBody = routeDef.hasBody
205
+ ? parseContractInput(routeDef.body, req.body)
206
+ : req.body;
207
+ const ctx = buildRequestContext(requestId, actor);
208
+ const outcome = await handler(ctx, {
209
+ method: routeDef.method,
210
+ path: req.path,
211
+ params: parsedParams,
212
+ query: parsedQuery,
213
+ body: parsedBody,
214
+ headers: req.headers,
215
+ }, graspHttpResponseBuilder);
216
+ if (outcome.headers) {
217
+ for (const [k, v] of Object.entries(outcome.headers)) {
218
+ res.setHeader(k, v);
219
+ }
220
+ }
221
+ if (outcome.kind === 'redirect') {
222
+ res.redirect(outcome.status, outcome.url);
223
+ }
224
+ else if (outcome.kind === 'json') {
225
+ res.status(outcome.status).json(outcome.data);
226
+ }
227
+ else if (outcome.kind === 'text') {
228
+ res.status(outcome.status).type('text/plain; charset=utf-8').send(outcome.body);
229
+ }
230
+ else {
231
+ res.status(outcome.status).end();
232
+ }
233
+ }
234
+ catch (err) {
235
+ next(err);
236
+ }
237
+ });
238
+ }
239
+ }
240
+ const apiRouter = express.Router();
241
+ apiRouter.use(jsonParser);
242
+ // Require explicit custom request header on all browser-invoked mutating API calls (CSRF protection)
243
+ apiRouter.use((req, _res, next) => {
244
+ if (req.method !== 'GET' && req.method !== 'HEAD' && req.method !== 'OPTIONS') {
245
+ if (req.header('x-grasp-client') !== '1') {
246
+ next(GraspError.forbidden('Missing required x-grasp-client header'));
247
+ return;
248
+ }
249
+ }
250
+ next();
251
+ });
252
+ apiRouter.get('/health', (_req, res) => {
253
+ res.json(okEnvelope({ status: 'ok', app: config.app.name }));
254
+ });
255
+ apiRouter.get('/ready', async (_req, res) => {
256
+ const [dbCheck, redisCheck] = await Promise.all([
257
+ store.readiness.check(),
258
+ redis.readiness.check(),
259
+ ]);
260
+ const ready = dbCheck.ok && redisCheck.ok;
261
+ if (!ready) {
262
+ res.status(503).json(GraspError.unavailable('One or more backend dependencies are not ready', {
263
+ metadata: {
264
+ dbOk: dbCheck.ok,
265
+ redisOk: redisCheck.ok,
266
+ },
267
+ }).toEnvelope(getRequestId(res)));
268
+ return;
269
+ }
270
+ res.json(okEnvelope({
271
+ status: 'ready',
272
+ checks: {
273
+ [store.readiness.name]: dbCheck,
274
+ [redis.readiness.name]: redisCheck,
275
+ },
276
+ }));
277
+ });
278
+ apiRouter.get('/shell/session', async (req, res, next) => {
279
+ try {
280
+ const actor = await resolveActor('optional', req);
281
+ res.json(okEnvelope({
282
+ user: actor.user,
283
+ entitlement: actor.entitlement,
284
+ devMode: devAuth !== undefined,
285
+ }));
286
+ }
287
+ catch (err) {
288
+ next(err);
289
+ }
290
+ });
291
+ if (devAuth !== undefined) {
292
+ apiRouter.get('/shell/dev-auth/personas', (_req, res) => {
293
+ res.json(okEnvelope({ personas: devAuth.personas }));
294
+ });
295
+ apiRouter.post('/shell/dev-auth/token', async (req, res, next) => {
296
+ try {
297
+ const parsed = parseContractInput(devTokenBodySchema, req.body);
298
+ const persona = devAuth.personas.find((p) => p.uid === parsed.uid);
299
+ if (!persona) {
300
+ throw GraspError.notFound(`Unknown dev persona "${parsed.uid}"`);
301
+ }
302
+ const token = devAuth.mintToken(persona);
303
+ const storedUser = await store.users.upsertBySubject({
304
+ id: persona.uid,
305
+ email: persona.email,
306
+ displayName: persona.displayName,
307
+ avatarUrl: persona.avatarUrl ?? null,
308
+ });
309
+ const user = {
310
+ ...storedUser,
311
+ emailVerified: persona.emailVerified ?? true,
312
+ };
313
+ const entitlement = await billing.resolveEntitlementForUser(user.id);
314
+ res.json(okEnvelope({ token, user, entitlement }));
315
+ }
316
+ catch (err) {
317
+ next(err);
318
+ }
319
+ });
320
+ }
321
+ apiRouter.delete('/shell/account', async (req, res, next) => {
322
+ try {
323
+ const requestId = getRequestId(res);
324
+ const actor = await resolveActor('user', req);
325
+ const userId = actor.user.id;
326
+ await billing.cancelUserSubscriptionsOnDelete(userId);
327
+ const erasers = Object.values(features).flatMap((f) => [
328
+ ...f.erasers,
329
+ ]);
330
+ const allCollections = new Set([
331
+ '_grasp_users',
332
+ '_grasp_entitlements',
333
+ '_grasp_credit_balances',
334
+ '_grasp_credits_ledger',
335
+ '_grasp_quota_scopes',
336
+ ]);
337
+ for (const eraser of erasers) {
338
+ for (const c of eraser.collections) {
339
+ allCollections.add(c);
340
+ }
341
+ }
342
+ const audit = await store.withTransaction(async (tx) => {
343
+ for (const eraser of erasers) {
344
+ await eraser.erase({
345
+ userId,
346
+ tx,
347
+ db: options.db ?? store,
348
+ log: logger.child({ requestId, userId, eraser: eraser.name }),
349
+ });
350
+ }
351
+ return store.users.deleteUserAndRecordAudit({
352
+ userId,
353
+ deletedCollections: [...allCollections].sort(),
354
+ }, tx);
355
+ });
356
+ await auth.deleteExternalUser(userId);
357
+ res.json(okEnvelope({
358
+ deleted: true,
359
+ deletedCollections: audit.deletedCollections,
360
+ }));
361
+ }
362
+ catch (err) {
363
+ next(err);
364
+ }
365
+ });
366
+ apiRouter.get('/shell/billing', async (req, res, next) => {
367
+ try {
368
+ const actor = await resolveActor('user', req);
369
+ const summary = await billing.getBillingSummary(actor.user.id);
370
+ res.json(okEnvelope(summary));
371
+ }
372
+ catch (err) {
373
+ next(err);
374
+ }
375
+ });
376
+ apiRouter.post('/shell/billing/checkout/plan', async (req, res, next) => {
377
+ try {
378
+ const actor = await resolveActor('user', req);
379
+ const parsed = parseContractInput(planCheckoutSchema, req.body);
380
+ const session = await billing.createPlanCheckout({
381
+ userId: actor.user.id,
382
+ email: actor.user.email,
383
+ planId: parsed.planId,
384
+ interval: parsed.interval,
385
+ ...(parsed.successUrl !== undefined ? { successUrl: parsed.successUrl } : {}),
386
+ ...(parsed.cancelUrl !== undefined ? { cancelUrl: parsed.cancelUrl } : {}),
387
+ });
388
+ res.json(okEnvelope(session));
389
+ }
390
+ catch (err) {
391
+ next(err);
392
+ }
393
+ });
394
+ apiRouter.post('/shell/billing/checkout/credits', async (req, res, next) => {
395
+ try {
396
+ const actor = await resolveActor('user', req);
397
+ const parsed = parseContractInput(creditCheckoutSchema, req.body);
398
+ const session = await billing.createCreditPackCheckout({
399
+ userId: actor.user.id,
400
+ email: actor.user.email,
401
+ packId: parsed.packId,
402
+ ...(parsed.successUrl !== undefined ? { successUrl: parsed.successUrl } : {}),
403
+ ...(parsed.cancelUrl !== undefined ? { cancelUrl: parsed.cancelUrl } : {}),
404
+ });
405
+ res.json(okEnvelope(session));
406
+ }
407
+ catch (err) {
408
+ next(err);
409
+ }
410
+ });
411
+ apiRouter.post('/shell/billing/portal', async (req, res, next) => {
412
+ try {
413
+ const actor = await resolveActor('user', req);
414
+ const parsed = parseContractInput(portalSchema, req.body ?? {});
415
+ const session = await billing.createPortal({
416
+ userId: actor.user.id,
417
+ ...(parsed.returnUrl !== undefined ? { returnUrl: parsed.returnUrl } : {}),
418
+ });
419
+ res.json(okEnvelope(session));
420
+ }
421
+ catch (err) {
422
+ next(err);
423
+ }
424
+ });
425
+ apiRouter.post('/rpc/:operationPath', async (req, res, next) => {
426
+ try {
427
+ const requestId = getRequestId(res);
428
+ const operationPath = String(req.params['operationPath'] ?? '');
429
+ const proc = getProcedureContract(appContract, operationPath);
430
+ if (!proc) {
431
+ throw GraspError.notFound(`Unknown RPC procedure "${operationPath}"`);
432
+ }
433
+ const { feature, operation } = parseOperationPath(operationPath);
434
+ const handler = features[feature]?.procedures[operation];
435
+ if (!handler) {
436
+ throw GraspError.internal(`No server handler registered for "${operationPath}"`);
437
+ }
438
+ const actor = await resolveActor(proc.auth, req);
439
+ if (proc.rateLimit) {
440
+ const subjectKey = proc.rateLimit.scope === 'user' && actor.user
441
+ ? `user:${actor.user.id}`
442
+ : `ip:${req.ip || 'unknown'}`;
443
+ await redis.rateLimiter.assertWithinLimit(`rpc:${operationPath}:${subjectKey}`, proc.rateLimit);
444
+ }
445
+ assertProcedureEntitlement(config, actor.entitlement, proc.entitlement);
446
+ const rawInput = proc.hasInput ? req.body : undefined;
447
+ const validatedInput = parseContractInput(proc.input, rawInput);
448
+ const ctx = buildRequestContext(requestId, actor);
449
+ const rawOutput = proc.hasInput
450
+ ? await handler(ctx, validatedInput)
451
+ : await handler(ctx);
452
+ const validatedOutput = parseContractOutput(proc.output, rawOutput);
453
+ res.json(okEnvelope(validatedOutput));
454
+ }
455
+ catch (err) {
456
+ next(err);
457
+ }
458
+ });
459
+ apiRouter.get('/stream/:operationPath', async (req, res, next) => {
460
+ const requestId = getRequestId(res);
461
+ try {
462
+ const operationPath = String(req.params['operationPath'] ?? '');
463
+ const streamDef = getStreamContract(appContract, operationPath);
464
+ if (!streamDef) {
465
+ throw GraspError.notFound(`Unknown SSE stream "${operationPath}"`);
466
+ }
467
+ const { feature, operation } = parseOperationPath(operationPath);
468
+ const handler = features[feature]?.streams[operation];
469
+ if (!handler) {
470
+ throw GraspError.internal(`No server stream handler registered for "${operationPath}"`);
471
+ }
472
+ const actor = await resolveActor(streamDef.auth, req);
473
+ if (streamDef.rateLimit) {
474
+ const subjectKey = streamDef.rateLimit.scope === 'user' && actor.user
475
+ ? `user:${actor.user.id}`
476
+ : `ip:${req.ip || 'unknown'}`;
477
+ await redis.rateLimiter.assertWithinLimit(`sse:${operationPath}:${subjectKey}`, streamDef.rateLimit);
478
+ }
479
+ assertProcedureEntitlement(config, actor.entitlement, streamDef.entitlement);
480
+ let rawInput = undefined;
481
+ if (streamDef.hasInput) {
482
+ const queryInput = req.query['input'];
483
+ if (typeof queryInput === 'string' && queryInput.length > 0) {
484
+ try {
485
+ rawInput = JSON.parse(queryInput);
486
+ }
487
+ catch (err) {
488
+ throw GraspError.badRequest('Malformed JSON in stream input query parameter', {
489
+ cause: err,
490
+ });
491
+ }
492
+ }
493
+ }
494
+ const validatedInput = parseContractInput(streamDef.input, rawInput);
495
+ const ctx = buildRequestContext(requestId, actor);
496
+ res.status(200);
497
+ res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
498
+ res.setHeader('Cache-Control', 'no-cache, no-transform');
499
+ res.setHeader('Connection', 'keep-alive');
500
+ res.setHeader('X-Accel-Buffering', 'no');
501
+ res.flushHeaders();
502
+ res.write(`event: ready\ndata: {}\n\n`);
503
+ const abortController = new AbortController();
504
+ const cleanups = [];
505
+ let closed = false;
506
+ const cleanupAll = async () => {
507
+ if (closed)
508
+ return;
509
+ closed = true;
510
+ abortController.abort();
511
+ while (cleanups.length > 0) {
512
+ const fn = cleanups.pop();
513
+ if (fn) {
514
+ await fn().catch(() => { });
515
+ }
516
+ }
517
+ };
518
+ req.on('close', () => {
519
+ void cleanupAll();
520
+ });
521
+ const writeEvent = (rawEvent) => {
522
+ if (closed || res.writableEnded)
523
+ return;
524
+ const validated = parseStreamEvent(streamDef.event, rawEvent);
525
+ res.write(`event: message\ndata: ${JSON.stringify(validated)}\n\n`);
526
+ };
527
+ const emitter = {
528
+ signal: abortController.signal,
529
+ emit: writeEvent,
530
+ async subscribe(channel, filter) {
531
+ const unsub = await redis.sseBus.subscribe(channel, (payload) => {
532
+ const event = filter ? filter(payload) : payload;
533
+ if (event !== null && event !== undefined) {
534
+ try {
535
+ writeEvent(event);
536
+ }
537
+ catch (err) {
538
+ logger.error('SSE event validation failed', {
539
+ requestId,
540
+ operationPath,
541
+ error: err,
542
+ });
543
+ }
544
+ }
545
+ });
546
+ cleanups.push(unsub);
547
+ return unsub;
548
+ },
549
+ };
550
+ try {
551
+ if (streamDef.hasInput) {
552
+ await handler(ctx, validatedInput, emitter);
553
+ }
554
+ else {
555
+ await handler(ctx, emitter);
556
+ }
557
+ if (!closed && !res.writableEnded) {
558
+ res.write(`event: done\ndata: {}\n\n`);
559
+ res.end();
560
+ }
561
+ }
562
+ catch (err) {
563
+ if (!closed && !res.writableEnded) {
564
+ const payload = serializeUnknownError(err, { requestId });
565
+ res.write(`event: error\ndata: ${JSON.stringify(payload)}\n\n`);
566
+ res.end();
567
+ }
568
+ }
569
+ finally {
570
+ await cleanupAll();
571
+ }
572
+ }
573
+ catch (err) {
574
+ next(err);
575
+ }
576
+ });
577
+ // Any unmatched /api route always fails closed with JSON 404 (never serves SPA index.html)
578
+ apiRouter.use((req, res) => {
579
+ res
580
+ .status(404)
581
+ .json(GraspError.notFound(`Unknown API route ${req.method} ${req.originalUrl}`).toEnvelope(getRequestId(res)));
582
+ });
583
+ app.use('/api', apiRouter);
584
+ if (options.publicDir && existsSync(options.publicDir)) {
585
+ const resolvedPublic = resolve(options.publicDir);
586
+ const indexHtmlPath = resolve(resolvedPublic, 'index.html');
587
+ app.use(express.static(resolvedPublic, { index: false }));
588
+ if (existsSync(indexHtmlPath)) {
589
+ app.use((req, res, next) => {
590
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
591
+ next();
592
+ return;
593
+ }
594
+ res.sendFile(indexHtmlPath);
595
+ });
596
+ }
597
+ }
598
+ app.use((err, req, res, _next) => {
599
+ const requestId = getRequestId(res);
600
+ const payload = serializeUnknownError(err, { requestId });
601
+ const status = err instanceof GraspError ? err.httpStatus : payload.code === 'VALIDATION_ERROR' ? 400 : 500;
602
+ if (status >= 500) {
603
+ logger.error('Unhandled server error', {
604
+ requestId,
605
+ method: req.method,
606
+ path: req.originalUrl,
607
+ error: err,
608
+ });
609
+ }
610
+ if (res.headersSent) {
611
+ res.end();
612
+ return;
613
+ }
614
+ res.status(status).json({ ok: false, error: payload });
615
+ });
616
+ let activeServer;
617
+ return {
618
+ app,
619
+ listen(port = 0, host = '127.0.0.1') {
620
+ return new Promise((resolveListen, rejectListen) => {
621
+ const srv = app.listen(port, host, () => {
622
+ activeServer = srv;
623
+ const addr = srv.address();
624
+ const resolvedPort = typeof addr === 'object' && addr !== null ? addr.port : port;
625
+ resolveListen({ port: resolvedPort, server: srv });
626
+ });
627
+ srv.on('error', rejectListen);
628
+ });
629
+ },
630
+ async close() {
631
+ if (!activeServer)
632
+ return;
633
+ await new Promise((resolveClose, rejectClose) => {
634
+ activeServer.close((err) => (err ? rejectClose(err) : resolveClose()));
635
+ });
636
+ activeServer = undefined;
637
+ },
638
+ };
639
+ }
640
+ //# sourceMappingURL=http.js.map