@mastra/express 1.5.23-alpha.9 → 1.5.24-alpha.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/index.cjs CHANGED
@@ -61,6 +61,11 @@ function createAuthMiddleware({ mastra, requiresAuth = true }) {
61
61
  }
62
62
  //#endregion
63
63
  //#region src/index.ts
64
+ var BodyLimitExceededError = class extends Error {
65
+ constructor(limit) {
66
+ super(`Request body size limit exceeded (max: ${limit} bytes)`);
67
+ }
68
+ };
64
69
  let _hasPermissionPromise;
65
70
  function loadHasPermission() {
66
71
  if (!_hasPermissionPromise) _hasPermissionPromise = import("@mastra/core/auth/ee").then((m) => m.hasPermission).catch(() => {
@@ -74,8 +79,10 @@ function loadHasPermission() {
74
79
  function toWebRequest(req) {
75
80
  const url = `${req.protocol || "http"}://${req.get("host") || "localhost"}${req.originalUrl || req.url}`;
76
81
  const headers = new Headers();
77
- for (const [key, value] of Object.entries(req.headers)) if (value) if (Array.isArray(value)) value.forEach((v) => headers.append(key, v));
78
- else headers.set(key, value);
82
+ for (const [key, value] of Object.entries(req.headers)) if (value) {
83
+ if (Array.isArray(value)) value.forEach((v) => headers.append(key, v));
84
+ else headers.set(key, value);
85
+ }
79
86
  return new globalThis.Request(url, {
80
87
  method: req.method,
81
88
  headers
@@ -172,18 +179,20 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
172
179
  const queryParams = (0, _mastra_server_server_adapter.normalizeQueryParams)(request.query);
173
180
  let body;
174
181
  let bodyParseError;
175
- if (route.method === "POST" || route.method === "PUT" || route.method === "PATCH" || route.method === "DELETE") if ((request.headers["content-type"] || "").includes("multipart/form-data")) try {
176
- const maxFileSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;
177
- body = await this.parseMultipartFormData(request, maxFileSize);
178
- } catch (error) {
179
- this.mastra.getLogger()?.error("Failed to parse multipart form data", { error: error instanceof Error ? {
180
- message: error.message,
181
- stack: error.stack
182
- } : error });
183
- if (error instanceof Error && error.message.toLowerCase().includes("size")) throw error;
184
- bodyParseError = { message: error instanceof Error ? error.message : "Failed to parse multipart form data" };
182
+ if (route.method === "POST" || route.method === "PUT" || route.method === "PATCH" || route.method === "DELETE") {
183
+ if ((request.headers["content-type"] || "").includes("multipart/form-data")) try {
184
+ const maxFileSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;
185
+ body = await this.parseMultipartFormData(request, maxFileSize);
186
+ } catch (error) {
187
+ if (error instanceof BodyLimitExceededError) throw error;
188
+ this.mastra.getLogger()?.error("Failed to parse multipart form data", { error: error instanceof Error ? {
189
+ message: error.message,
190
+ stack: error.stack
191
+ } : error });
192
+ bodyParseError = { message: error instanceof Error ? error.message : "Failed to parse multipart form data" };
193
+ }
194
+ else body = request.body;
185
195
  }
186
- else body = request.body;
187
196
  return {
188
197
  urlParams,
189
198
  queryParams,
@@ -203,8 +212,24 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
203
212
  const result = {};
204
213
  const busboy = new _fastify_busboy.Busboy({
205
214
  headers: { "content-type": request.headers["content-type"] },
206
- limits: maxFileSize ? { fileSize: maxFileSize } : void 0
215
+ limits: maxFileSize ? {
216
+ fileSize: maxFileSize,
217
+ fieldSize: maxFileSize
218
+ } : void 0
207
219
  });
220
+ if (maxFileSize !== void 0) {
221
+ let received = 0;
222
+ const onData = (chunk) => {
223
+ received += chunk.length;
224
+ if (received > maxFileSize) {
225
+ request.off("data", onData);
226
+ request.unpipe(busboy);
227
+ request.pause();
228
+ reject(new BodyLimitExceededError(maxFileSize));
229
+ }
230
+ };
231
+ request.on("data", onData);
232
+ }
208
233
  busboy.on("file", (fieldname, file) => {
209
234
  const chunks = [];
210
235
  let limitExceeded = false;
@@ -213,7 +238,7 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
213
238
  });
214
239
  file.on("limit", () => {
215
240
  limitExceeded = true;
216
- reject(/* @__PURE__ */ new Error(`File size limit exceeded${maxFileSize ? ` (max: ${maxFileSize} bytes)` : ""}`));
241
+ reject(new BodyLimitExceededError(maxFileSize));
217
242
  });
218
243
  file.on("end", () => {
219
244
  if (!limitExceeded && (0, _mastra_server_server_adapter.isSafeObjectKey)(fieldname)) result[fieldname] = Buffer.concat(chunks);
@@ -332,17 +357,19 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
332
357
  "DELETE"
333
358
  ].includes(route.method.toUpperCase());
334
359
  const middlewares = [];
360
+ const sendBodyTooLarge = (res) => {
361
+ let errorResponse = { error: "Request body too large" };
362
+ if (route.maxBodySize === void 0 && this.bodyLimitOptions) try {
363
+ errorResponse = this.bodyLimitOptions.onError(errorResponse);
364
+ } catch {}
365
+ res.setHeader("Connection", "close");
366
+ return res.status(413).json(errorResponse);
367
+ };
335
368
  if (isBodyMethod && maxSize !== void 0) {
336
369
  const bodyLimitMiddleware = (req, res, next) => {
337
370
  const contentLength = req.headers["content-length"];
338
371
  const parsedLength = contentLength === void 0 && req.body !== void 0 ? Buffer.byteLength(JSON.stringify(req.body), "utf8") : 0;
339
- if (contentLength && parseInt(contentLength, 10) > maxSize || parsedLength > maxSize) {
340
- let errorResponse = { error: "Request body too large" };
341
- if (route.maxBodySize === void 0 && this.bodyLimitOptions) try {
342
- errorResponse = this.bodyLimitOptions.onError(errorResponse);
343
- } catch {}
344
- return res.status(413).json(errorResponse);
345
- }
372
+ if (contentLength && parseInt(contentLength, 10) > maxSize || parsedLength > maxSize) return sendBodyTooLarge(res);
346
373
  next();
347
374
  };
348
375
  middlewares.push(bodyLimitMiddleware);
@@ -362,7 +389,13 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
362
389
  if (authResult.headers) for (const [key, value] of Object.entries(authResult.headers)) res.setHeader(key, value);
363
390
  if (authResult.error) return res.status(authResult.status).json({ error: authResult.error });
364
391
  }
365
- const params = await this.getParams(route, req);
392
+ let params;
393
+ try {
394
+ params = await this.getParams(route, req);
395
+ } catch (error) {
396
+ if (error instanceof BodyLimitExceededError) return sendBodyTooLarge(res);
397
+ throw error;
398
+ }
366
399
  if (params.bodyParseError) return res.status(400).json({
367
400
  error: "Invalid request body",
368
401
  issues: [{
@@ -439,11 +472,11 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
439
472
  routePrefix: prefix,
440
473
  request: toWebRequest(req)
441
474
  };
442
- if (this.mastra.getServer()?.auth) {
475
+ if (this.mastra.getStudio?.()?.auth || this.mastra.getServer()?.auth) {
443
476
  const hasPermission = await loadHasPermission();
444
477
  if (hasPermission) {
445
478
  const userPermissions = res.locals.requestContext.get("mastra__userPermissions");
446
- const permissionError = this.checkRoutePermission(route, userPermissions, hasPermission);
479
+ const permissionError = this.checkRoutePermission(route, userPermissions, hasPermission, res.locals.requestContext);
447
480
  if (permissionError) return res.status(permissionError.status).json({
448
481
  error: permissionError.error,
449
482
  message: permissionError.message
@@ -481,12 +514,8 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
481
514
  res.status(customResponse.status).end(Buffer.from(await customResponse.arrayBuffer()));
482
515
  return;
483
516
  }
484
- let status = 500;
485
- if (error && typeof error === "object") {
486
- if ("status" in error) status = error.status;
487
- else if ("details" in error && error.details && typeof error.details === "object" && "status" in error.details) status = error.details.status;
488
- }
489
- res.status(status).json({ error: error instanceof Error ? error.message : "Unknown error" });
517
+ const { status, body } = (0, _mastra_server_server_adapter.getHTTPErrorResponse)(error);
518
+ res.status(status).json(body);
490
519
  }
491
520
  });
492
521
  }
@@ -524,11 +553,11 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
524
553
  if (authResult.headers) for (const [key, value] of Object.entries(authResult.headers)) res.setHeader(key, value);
525
554
  if (authResult.error) return res.status(authResult.status).json({ error: authResult.error });
526
555
  }
527
- if (this.mastra.getServer()?.auth) {
556
+ if (this.mastra.getStudio?.()?.auth || this.mastra.getServer()?.auth) {
528
557
  const hasPermission = await loadHasPermission();
529
558
  if (hasPermission) {
530
559
  const userPermissions = res.locals.requestContext.get("mastra__userPermissions");
531
- const permissionError = this.checkRoutePermission(serverRoute, userPermissions, hasPermission);
560
+ const permissionError = this.checkRoutePermission(serverRoute, userPermissions, hasPermission, res.locals.requestContext);
532
561
  if (permissionError) return res.status(permissionError.status).json({
533
562
  error: permissionError.error,
534
563
  message: permissionError.message
@@ -537,9 +566,9 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
537
566
  }
538
567
  }
539
568
  const fgaError = await (0, _mastra_server_server_adapter.checkRouteFGA)(this.mastra, serverRoute, res.locals.requestContext, {
540
- ...matchedRoute?.params ?? {},
541
569
  ...req.query,
542
- ...typeof req.body === "object" && req.body !== null ? req.body : {}
570
+ ...typeof req.body === "object" && req.body !== null ? req.body : {},
571
+ ...matchedRoute?.params ?? {}
543
572
  });
544
573
  if (fgaError) return res.status(fgaError.status).json({
545
574
  error: fgaError.error,
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["toWebRequest","RequestContext","MastraServerBase","Busboy"],"sources":["../src/auth-middleware.ts","../src/index.ts"],"sourcesContent":["import type { Mastra } from '@mastra/core/mastra';\nimport { RequestContext } from '@mastra/core/request-context';\nimport { coreAuthMiddleware, isCustomRoutePublic } from '@mastra/server/auth';\nimport type { NextFunction, Request, Response } from 'express';\n\nexport interface ExpressAuthMiddlewareOptions {\n mastra: Mastra;\n requiresAuth?: boolean;\n}\n\nfunction toWebRequest(req: Request): globalThis.Request {\n const protocol = req.protocol || 'http';\n const host = req.get('host') || 'localhost';\n const url = `${protocol}://${host}${req.originalUrl || req.url}`;\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (!value) continue;\n if (Array.isArray(value)) {\n value.forEach(v => headers.append(key, v));\n } else {\n headers.set(key, value);\n }\n }\n\n return new globalThis.Request(url, {\n method: req.method,\n headers,\n });\n}\n\nexport function createAuthMiddleware({\n mastra,\n requiresAuth = true,\n}: ExpressAuthMiddlewareOptions): (req: Request, res: Response, next: NextFunction) => Promise<void> {\n return async (req: Request, res: Response, next: NextFunction) => {\n if (!requiresAuth) {\n next();\n return;\n }\n\n const authConfig = mastra.getServer()?.auth;\n if (!authConfig) {\n next();\n return;\n }\n\n const requestContext = res.locals.requestContext ?? new RequestContext();\n res.locals.requestContext = requestContext;\n res.locals.mastra = res.locals.mastra ?? mastra;\n\n const path = String(req.path || '/');\n const method = String(req.method || 'GET');\n const customRouteAuthConfig = new Map<string, boolean>(res.locals.customRouteAuthConfig ?? []);\n // Don't reclassify a custom route the app declared public (requiresAuth: false).\n if (!isCustomRoutePublic(path, method, customRouteAuthConfig)) {\n customRouteAuthConfig.set(`${method}:${path}`, true);\n }\n\n const authHeader = req.headers.authorization;\n let token: string | null = authHeader ? authHeader.replace('Bearer ', '') : null;\n if (!token && req.query.apiKey) {\n token = (req.query.apiKey as string) || null;\n }\n\n const result = await coreAuthMiddleware({\n path,\n method,\n getHeader: name => req.headers[name.toLowerCase()] as string | undefined,\n mastra,\n authConfig,\n customRouteAuthConfig,\n requestContext,\n rawRequest: toWebRequest(req),\n token,\n buildAuthorizeContext: () => toWebRequest(req),\n });\n\n for (const [key, value] of Object.entries(result.headers ?? {})) {\n if (key.toLowerCase() === 'set-cookie') {\n res.append(key, value);\n } else {\n res.setHeader(key, value);\n }\n }\n\n if (result.action === 'next') {\n next();\n return;\n }\n\n res.status(result.status).json(result.body);\n };\n}\n","import { Busboy } from '@fastify/busboy';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { InMemoryTaskStore } from '@mastra/server/a2a/store';\nimport { findMatchingCustomRoute, isProtectedCustomRoute } from '@mastra/server/auth';\nimport type { MCPHttpTransportResult, MCPSseTransportResult } from '@mastra/server/handlers/mcp';\nimport type { ParsedRequestParams, ServerRoute } from '@mastra/server/server-adapter';\nimport {\n MastraServer as MastraServerBase,\n checkRouteFGA,\n getCustomHTTPExceptionResponse,\n isSafeObjectKey,\n isZodError,\n normalizeQueryParams,\n redactStreamChunk,\n serializeStreamChunk,\n} from '@mastra/server/server-adapter';\nimport type { Application, NextFunction, Request, Response } from 'express';\nexport { createAuthMiddleware } from './auth-middleware';\nexport type { ExpressAuthMiddlewareOptions } from './auth-middleware';\n\ntype HasPermissionFn = (userPerms: string[], required: string) => boolean;\ntype AuthErrorWithHeaders = { status: number; error: string; headers?: Record<string, string> };\nlet _hasPermissionPromise: Promise<HasPermissionFn | undefined> | undefined;\nfunction loadHasPermission(): Promise<HasPermissionFn | undefined> {\n if (!_hasPermissionPromise) {\n _hasPermissionPromise = import('@mastra/core/auth/ee')\n .then(m => m.hasPermission)\n .catch(() => {\n console.error(\n '[@mastra/express] Auth features require @mastra/core >= 1.6.0. Please upgrade: npm install @mastra/core@latest',\n );\n return undefined;\n });\n }\n return _hasPermissionPromise;\n}\n\n/**\n * Convert Express request to Web API Request for cookie-based auth providers.\n */\nfunction toWebRequest(req: Request): globalThis.Request {\n const protocol = req.protocol || 'http';\n const host = req.get('host') || 'localhost';\n const url = `${protocol}://${host}${req.originalUrl || req.url}`;\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value) {\n if (Array.isArray(value)) {\n value.forEach(v => headers.append(key, v));\n } else {\n headers.set(key, value);\n }\n }\n }\n\n return new globalThis.Request(url, {\n method: req.method,\n headers,\n });\n}\n\n// Extend Express types to include Mastra context\ndeclare global {\n namespace Express {\n interface Locals {\n mastra: Mastra;\n requestContext: RequestContext;\n abortSignal: AbortSignal;\n registeredTools: ToolsInput;\n taskStore: InMemoryTaskStore;\n customRouteAuthConfig?: Map<string, boolean>;\n }\n }\n}\n\nexport class MastraServer extends MastraServerBase<Application, Request, Response> {\n createContextMiddleware(): (req: Request, res: Response, next: NextFunction) => Promise<void> {\n return async (req: Request, res: Response, next: NextFunction) => {\n // Parse request context from request body and add to context\n let bodyRequestContext: Record<string, any> | undefined;\n let paramsRequestContext: Record<string, any> | undefined;\n\n // Parse request context from request body (POST/PUT)\n if (req.method === 'POST' || req.method === 'PUT') {\n const contentType = req.headers['content-type'];\n if (contentType?.includes('application/json') && req.body) {\n if (req.body.requestContext) {\n bodyRequestContext = req.body.requestContext;\n }\n }\n }\n\n // Parse request context from query params.\n if (req.method === 'GET' || req.method === 'POST') {\n try {\n const encodedRequestContext = req.query.requestContext;\n if (typeof encodedRequestContext === 'string') {\n // Try JSON first\n try {\n paramsRequestContext = JSON.parse(encodedRequestContext);\n } catch {\n // Fallback to base64(JSON)\n try {\n const json = Buffer.from(encodedRequestContext, 'base64').toString('utf-8');\n paramsRequestContext = JSON.parse(json);\n } catch {\n // ignore if still invalid\n }\n }\n }\n } catch {\n // ignore query parsing errors\n }\n }\n\n const requestContext = this.mergeRequestContext({ paramsRequestContext, bodyRequestContext });\n this.applyRequestMetadataToContext({\n requestContext,\n getHeader: name => req.get(name),\n });\n\n // Set context in res.locals\n res.locals.requestContext = requestContext;\n res.locals.mastra = this.mastra;\n res.locals.registeredTools = this.tools || {};\n if (this.taskStore) {\n res.locals.taskStore = this.taskStore;\n }\n res.locals.customRouteAuthConfig = this.customRouteAuthConfig;\n const controller = new AbortController();\n // Use res.on('close') instead of req.on('close') because the request's 'close' event\n // fires when the request body is fully consumed (e.g., after express.json() parses it),\n // NOT when the client disconnects. The response's 'close' event fires when the underlying\n // connection is actually closed, which is the correct signal for stream cleanup.\n res.on('close', () => {\n // Only abort if the response wasn't successfully completed\n if (!res.writableFinished) {\n controller.abort();\n }\n });\n res.locals.abortSignal = controller.signal;\n next();\n };\n }\n async stream(route: ServerRoute, res: Response, result: { fullStream: ReadableStream }): Promise<void> {\n const streamFormat = route.streamFormat || 'stream';\n\n if (streamFormat === 'sse') {\n res.setHeader('Content-Type', 'text/event-stream');\n res.setHeader('Cache-Control', 'no-cache');\n res.setHeader('Connection', 'keep-alive');\n res.setHeader('X-Accel-Buffering', 'no');\n } else {\n res.setHeader('Content-Type', 'text/plain');\n }\n res.setHeader('Transfer-Encoding', 'chunked');\n res.flushHeaders();\n\n if (streamFormat === 'sse' && route.sseFlushOnConnect) {\n res.write(': connected\\n\\n');\n }\n\n const readableStream = result instanceof ReadableStream ? result : result.fullStream;\n const reader = readableStream.getReader();\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n if (value) {\n if (streamFormat === 'sse' && typeof value === 'string' && value.startsWith(':')) {\n res.write(value);\n continue;\n }\n\n // Optionally redact sensitive data (system prompts, tool definitions, API keys) before sending to the client\n const shouldRedact = this.streamOptions?.redact ?? true;\n const outputValue = shouldRedact ? redactStreamChunk(value) : value;\n // A chunk that can't be serialized must not kill the stream — skip it and keep streaming\n const serialized = serializeStreamChunk(outputValue);\n if (!serialized.ok) {\n this.mastra.getLogger()?.error('Failed to serialize stream chunk, skipping', {\n path: route.path,\n chunkType: (outputValue as { type?: string })?.type,\n error: serialized.error.message,\n });\n continue;\n }\n if (streamFormat === 'sse') {\n res.write(`data: ${serialized.json}\\n\\n`);\n } else {\n res.write(serialized.json + '\\x1E');\n }\n }\n }\n } catch (error) {\n this.mastra.getLogger()?.error('Error in stream processing', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n } finally {\n res.end();\n }\n }\n\n async getParams(route: ServerRoute, request: Request): Promise<ParsedRequestParams> {\n const urlParams = request.params as Record<string, string>;\n // Express's req.query can contain string | string[] | ParsedQs | ParsedQs[]\n const queryParams = normalizeQueryParams(request.query as Record<string, unknown>);\n let body: unknown;\n let bodyParseError: { message: string } | undefined;\n\n if (route.method === 'POST' || route.method === 'PUT' || route.method === 'PATCH' || route.method === 'DELETE') {\n const contentType = request.headers['content-type'] || '';\n\n if (contentType.includes('multipart/form-data')) {\n try {\n const maxFileSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;\n body = await this.parseMultipartFormData(request, maxFileSize);\n } catch (error) {\n this.mastra.getLogger()?.error('Failed to parse multipart form data', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n // Re-throw size limit errors, let others fall through to validation\n if (error instanceof Error && error.message.toLowerCase().includes('size')) {\n throw error;\n }\n bodyParseError = {\n message: error instanceof Error ? error.message : 'Failed to parse multipart form data',\n };\n }\n } else {\n body = request.body;\n }\n }\n\n return { urlParams, queryParams, body, bodyParseError };\n }\n\n /**\n * Parse multipart/form-data using @fastify/busboy.\n * Converts file uploads to Buffers and parses JSON field values.\n *\n * @param request - The Express request object\n * @param maxFileSize - Optional maximum file size in bytes\n */\n private parseMultipartFormData(request: Request, maxFileSize?: number): Promise<Record<string, unknown>> {\n return new Promise((resolve, reject) => {\n const result: Record<string, unknown> = {};\n\n const busboy = new Busboy({\n headers: {\n 'content-type': request.headers['content-type'] as string,\n },\n limits: maxFileSize ? { fileSize: maxFileSize } : undefined,\n });\n\n busboy.on('file', (fieldname: string, file: NodeJS.ReadableStream) => {\n const chunks: Buffer[] = [];\n let limitExceeded = false;\n\n file.on('data', (chunk: Buffer) => {\n chunks.push(chunk);\n });\n\n file.on('limit', () => {\n limitExceeded = true;\n reject(new Error(`File size limit exceeded${maxFileSize ? ` (max: ${maxFileSize} bytes)` : ''}`));\n });\n\n file.on('end', () => {\n if (!limitExceeded && isSafeObjectKey(fieldname)) {\n result[fieldname] = Buffer.concat(chunks);\n }\n });\n });\n\n busboy.on('field', (fieldname: string, value: string) => {\n if (!isSafeObjectKey(fieldname)) {\n return;\n }\n // Try to parse JSON strings (like 'options')\n try {\n result[fieldname] = JSON.parse(value);\n } catch {\n result[fieldname] = value;\n }\n });\n\n busboy.on('finish', () => {\n resolve(result);\n });\n\n busboy.on('error', (error: Error) => {\n reject(error);\n });\n\n request.pipe(busboy);\n });\n }\n\n async sendResponse(\n route: ServerRoute,\n response: Response,\n result: unknown,\n request?: Request,\n prefix?: string,\n ): Promise<void> {\n const resolvedPrefix = prefix ?? this.prefix ?? '';\n\n // Apply refresh headers from transparent session refresh (e.g. Set-Cookie after token refresh)\n if (result && typeof result === 'object' && '__refreshHeaders' in result) {\n const refreshHeaders = (result as any).__refreshHeaders as Record<string, string>;\n for (const [key, value] of Object.entries(refreshHeaders)) {\n response.setHeader(key, value);\n }\n delete (result as any).__refreshHeaders;\n }\n\n if (route.responseType === 'json') {\n response.json(result);\n } else if (route.responseType === 'stream') {\n await this.stream(route, response, result as { fullStream: ReadableStream });\n } else if (route.responseType === 'datastream-response') {\n // Handle AI SDK Response objects - pipe Response.body to Express response\n const fetchResponse = result as globalThis.Response;\n fetchResponse.headers.forEach((value, key) => response.setHeader(key, value));\n response.status(fetchResponse.status);\n if (fetchResponse.body) {\n const reader = fetchResponse.body.getReader();\n\n const onResError = (err: unknown) => {\n this.mastra.getLogger()?.error('Error writing datastream response', {\n error: err instanceof Error ? { message: err.message, stack: err.stack } : err,\n });\n void reader.cancel('response write error').catch(() => {});\n };\n response.once('error', onResError);\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n response.write(value);\n }\n } catch (error) {\n this.mastra.getLogger()?.error('Error in datastream processing', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n } finally {\n response.off('error', onResError);\n response.end();\n }\n } else {\n response.end();\n }\n } else if (route.responseType === 'mcp-http') {\n // MCP Streamable HTTP transport - request is required\n if (!request) {\n response.status(500).json({ error: 'Request object required for MCP transport' });\n return;\n }\n\n const { server, httpPath, mcpOptions: routeMcpOptions } = result as MCPHttpTransportResult;\n\n try {\n // Merge class-level mcpOptions with route-specific options (route takes precedence)\n const options = { ...this.mcpOptions, ...routeMcpOptions };\n\n await server.startHTTP({\n url: new URL(request.url, `http://${request.headers.host}`),\n httpPath: `${resolvedPrefix}${httpPath}`,\n req: request,\n res: response,\n options: Object.keys(options).length > 0 ? options : undefined,\n });\n // Response handled by startHTTP\n } catch {\n if (!response.headersSent) {\n response.status(500).json({\n jsonrpc: '2.0',\n error: { code: -32603, message: 'Internal server error' },\n id: null,\n });\n }\n }\n } else if (route.responseType === 'mcp-sse') {\n // MCP SSE transport - request is required\n if (!request) {\n response.status(500).json({ error: 'Request object required for MCP transport' });\n return;\n }\n\n const { server, ssePath, messagePath } = result as MCPSseTransportResult;\n\n try {\n await server.startSSE({\n url: new URL(request.url, `http://${request.headers.host}`),\n ssePath: `${resolvedPrefix}${ssePath}`,\n messagePath: `${resolvedPrefix}${messagePath}`,\n req: request,\n res: response,\n });\n // Response handled by startSSE\n } catch {\n if (!response.headersSent) {\n response.status(500).json({ error: 'Error handling MCP SSE request' });\n }\n }\n } else {\n response.sendStatus(500);\n }\n }\n\n async registerRoute(\n app: Application,\n route: ServerRoute,\n { prefix: prefixParam }: { prefix?: string } = {},\n ): Promise<void> {\n // Default prefix to this.prefix if not provided, or empty string\n const prefix = prefixParam ?? this.prefix ?? '';\n\n const maxSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;\n const isBodyMethod = ['POST', 'PUT', 'PATCH', 'DELETE'].includes(route.method.toUpperCase());\n\n // Create middleware array\n const middlewares: Array<(req: Request, res: Response, next: NextFunction) => void> = [];\n\n // Add body limit middleware if needed\n if (isBodyMethod && maxSize !== undefined) {\n const bodyLimitMiddleware = (req: Request, res: Response, next: NextFunction) => {\n const contentLength = req.headers['content-length'];\n // A host-level parser may run before this route middleware, so this is a\n // post-parse safeguard when Content-Length is unavailable.\n const parsedLength =\n contentLength === undefined && req.body !== undefined\n ? Buffer.byteLength(JSON.stringify(req.body), 'utf8')\n : 0;\n if ((contentLength && parseInt(contentLength, 10) > maxSize) || parsedLength > maxSize) {\n let errorResponse: unknown = { error: 'Request body too large' };\n if (route.maxBodySize === undefined && this.bodyLimitOptions) {\n try {\n errorResponse = this.bodyLimitOptions.onError(errorResponse);\n } catch {\n // Fall back to the default response.\n }\n }\n return res.status(413).json(errorResponse);\n }\n next();\n };\n middlewares.push(bodyLimitMiddleware);\n }\n\n app[route.method.toLowerCase() as keyof Application](\n `${prefix}${route.path}`,\n ...middlewares,\n async (req: Request, res: Response) => {\n // Check route-level authentication/authorization\n const authError = await this.checkRouteAuth(route, {\n path: String(req.path || '/'),\n method: String(req.method || 'GET'),\n getHeader: name => req.headers[name.toLowerCase()] as string | undefined,\n getQuery: name => req.query[name] as string | undefined,\n requestContext: res.locals.requestContext,\n request: toWebRequest(req),\n buildAuthorizeContext: () => toWebRequest(req),\n });\n\n if (authError) {\n const authResult = authError as AuthErrorWithHeaders;\n // Apply any refresh headers (e.g. Set-Cookie from transparent session refresh)\n if (authResult.headers) {\n for (const [key, value] of Object.entries(authResult.headers)) {\n res.setHeader(key, value);\n }\n }\n\n // If this is an auth error (not just a success-with-headers), return error response\n if (authResult.error) {\n return res.status(authResult.status).json({ error: authResult.error });\n }\n }\n\n const params = await this.getParams(route, req);\n\n // Return 400 Bad Request if body parsing failed (e.g., malformed multipart data)\n if (params.bodyParseError) {\n return res.status(400).json({\n error: 'Invalid request body',\n issues: [{ field: 'body', message: params.bodyParseError.message }],\n });\n }\n\n if (params.queryParams) {\n try {\n params.queryParams = await this.parseQueryParams(route, params.queryParams);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing query params', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (isZodError(error)) {\n const { status, body } = this.resolveValidationError(route, error, 'query');\n return res.status(status).json(body);\n }\n return res.status(400).json({\n error: 'Invalid query parameters',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n });\n }\n }\n\n if (params.body !== undefined || route.bodySchema) {\n try {\n params.body = await this.parseBody(route, params.body);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing body', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (isZodError(error)) {\n const { status, body } = this.resolveValidationError(route, error, 'body');\n return res.status(status).json(body);\n }\n return res.status(400).json({\n error: 'Invalid request body',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n });\n }\n }\n\n // Parse path params through pathParamSchema for type coercion (e.g., z.coerce.number())\n if (params.urlParams) {\n try {\n params.urlParams = await this.parsePathParams(route, params.urlParams);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing path params', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (isZodError(error)) {\n const { status, body } = this.resolveValidationError(route, error, 'path');\n return res.status(status).json(body);\n }\n return res.status(400).json({\n error: 'Invalid path parameters',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n });\n }\n }\n\n const handlerParams = {\n ...params.urlParams,\n ...params.queryParams,\n ...(typeof params.body === 'object' ? params.body : {}),\n requestContext: res.locals.requestContext,\n mastra: this.mastra,\n registeredTools: res.locals.registeredTools,\n taskStore: res.locals.taskStore,\n abortSignal: res.locals.abortSignal,\n routePrefix: prefix,\n request: toWebRequest(req),\n };\n\n // Check route permission requirement (EE feature)\n // Uses convention-based permission derivation: permissions are auto-derived\n // from route path/method unless explicitly set or route is public\n const authConfig = this.mastra.getServer()?.auth;\n if (authConfig) {\n const hasPermission = await loadHasPermission();\n if (hasPermission) {\n const userPermissions = res.locals.requestContext.get('mastra__userPermissions') as string[] | undefined;\n const permissionError = this.checkRoutePermission(route, userPermissions, hasPermission);\n\n if (permissionError) {\n return res.status(permissionError.status).json({\n error: permissionError.error,\n message: permissionError.message,\n });\n }\n }\n }\n\n // Check FGA authorization (EE feature)\n const fgaError = await checkRouteFGA(this.mastra, route, res.locals.requestContext, {\n ...params.urlParams,\n ...params.queryParams,\n ...(typeof params.body === 'object' ? params.body : {}),\n });\n if (fgaError) {\n return res.status(fgaError.status).json({ error: fgaError.error, message: fgaError.message });\n }\n\n try {\n const result = await route.handler(handlerParams);\n await this.sendResponse(route, res, result, req, prefix);\n } catch (error) {\n const httpStatus =\n error && typeof error === 'object' ? ((error as any).status ?? (error as any).details?.status) : undefined;\n const isClientError = typeof httpStatus === 'number' && httpStatus >= 400 && httpStatus < 500;\n if (!isClientError) {\n // 501 means an optional capability isn't provided by the configured storage or core: expected, not a server fault.\n const logLevel = httpStatus === 501 ? 'warn' : 'error';\n this.mastra.getLogger()?.[logLevel]('Error calling handler', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n path: route.path,\n method: route.method,\n });\n }\n const customResponse = getCustomHTTPExceptionResponse(error);\n if (customResponse) {\n customResponse.headers.forEach((value, name) => res.setHeader(name, value));\n res.status(customResponse.status).end(Buffer.from(await customResponse.arrayBuffer()));\n return;\n }\n\n // Check if it's an HTTPException or MastraError with a status code\n let status = 500;\n if (error && typeof error === 'object') {\n // Check for direct status property (HTTPException)\n if ('status' in error) {\n status = (error as any).status;\n }\n // Check for MastraError with status in details\n else if (\n 'details' in error &&\n error.details &&\n typeof error.details === 'object' &&\n 'status' in error.details\n ) {\n status = (error.details as any).status;\n }\n }\n res.status(status).json({ error: error instanceof Error ? error.message : 'Unknown error' });\n }\n },\n );\n }\n\n async registerCustomApiRoutes(): Promise<void> {\n const routes = await this.registerSchemaApiRoutes();\n if (!(await this.buildCustomRouteHandler(routes))) return;\n\n this.app.use(async (req: Request, res: Response, next: NextFunction) => {\n // Check if this request matches a protected custom route and run auth\n const path = String(req.path || '/');\n const method = String(req.method || 'GET');\n const matchedRoute = findMatchingCustomRoute(\n path,\n method,\n this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes,\n );\n const shouldRunCustomRouteAuth = isProtectedCustomRoute(path, method, this.customRouteAuthConfig);\n const shouldRunCustomRouteFGA = !!matchedRoute?.route.fga;\n\n if (shouldRunCustomRouteAuth || shouldRunCustomRouteFGA) {\n const serverRoute: ServerRoute = {\n method: (matchedRoute?.route.method ?? method) as any,\n path: matchedRoute?.route.path ?? path,\n responseType: 'json',\n handler: async () => {},\n requiresAuth: matchedRoute?.route.requiresAuth,\n requiresPermission: matchedRoute?.route.requiresPermission,\n fga: matchedRoute?.route.fga,\n };\n\n if (shouldRunCustomRouteAuth) {\n const authError = await this.checkRouteAuth(serverRoute, {\n path,\n method,\n getHeader: name => req.headers[name.toLowerCase()] as string | undefined,\n getQuery: name => req.query[name] as string | undefined,\n requestContext: res.locals.requestContext,\n request: toWebRequest(req),\n buildAuthorizeContext: () => toWebRequest(req),\n });\n\n if (authError) {\n const authResult = authError as AuthErrorWithHeaders;\n if (authResult.headers) {\n for (const [key, value] of Object.entries(authResult.headers)) {\n res.setHeader(key, value);\n }\n }\n if (authResult.error) {\n return res.status(authResult.status).json({ error: authResult.error });\n }\n }\n\n const authConfig = this.mastra.getServer()?.auth;\n if (authConfig) {\n const hasPermission = await loadHasPermission();\n if (hasPermission) {\n const userPermissions = res.locals.requestContext.get('mastra__userPermissions') as string[] | undefined;\n const permissionError = this.checkRoutePermission(serverRoute, userPermissions, hasPermission);\n if (permissionError) {\n return res.status(permissionError.status).json({\n error: permissionError.error,\n message: permissionError.message,\n });\n }\n }\n }\n }\n\n // Check FGA authorization (EE feature)\n const fgaError = await checkRouteFGA(this.mastra, serverRoute, res.locals.requestContext, {\n ...(matchedRoute?.params ?? {}),\n ...(req.query as Record<string, string>),\n ...(typeof req.body === 'object' && req.body !== null ? req.body : {}),\n });\n if (fgaError) {\n return res.status(fgaError.status).json({ error: fgaError.error, message: fgaError.message });\n }\n }\n\n const response = await this.handleCustomRouteRequest(\n `${req.protocol}://${req.get('host') || 'localhost'}${req.originalUrl}`,\n req.method,\n req.headers as Record<string, string | string[] | undefined>,\n req.body,\n res.locals.requestContext,\n res.locals.abortSignal,\n );\n if (!response) return next();\n await this.writeCustomRouteResponse(response, res, res.locals.abortSignal);\n });\n }\n\n registerContextMiddleware(): void {\n this.app.use(this.createContextMiddleware());\n this.app.use((req, res, next) => {\n const path = String(req.path || '/');\n const method = String(req.method || 'GET');\n res.on('finish', () => {\n this.warnIfUnregisteredChannelWebhook(path, method, res.statusCode);\n });\n next();\n });\n }\n\n registerAuthMiddleware(): void {\n // Auth is handled per-route in registerRoute() and registerCustomApiRoutes()\n // No global middleware needed\n }\n\n registerHttpLoggingMiddleware(): void {\n if (!this.httpLoggingConfig?.enabled) {\n return;\n }\n\n this.app.use((req, res, next) => {\n if (!this.shouldLogRequest(req.path)) {\n return next();\n }\n\n const start = Date.now();\n const method = req.method;\n const path = req.path;\n\n res.on('finish', () => {\n const duration = Date.now() - start;\n const status = res.statusCode;\n const level = this.httpLoggingConfig?.level || 'info';\n\n const logData: Record<string, any> = {\n method,\n path,\n status,\n duration: `${duration}ms`,\n };\n\n if (this.httpLoggingConfig?.includeQueryParams) {\n logData.query = req.query;\n }\n\n if (this.httpLoggingConfig?.includeHeaders) {\n const headers = { ...req.headers };\n const redactHeaders = this.httpLoggingConfig.redactHeaders || [];\n redactHeaders.forEach(h => {\n const key = h.toLowerCase();\n if (headers[key] !== undefined) {\n headers[key] = '[REDACTED]';\n }\n });\n logData.headers = headers;\n }\n\n this.logger[level](`${method} ${path} ${status} ${duration}ms`, logData);\n });\n\n next();\n });\n }\n}\n"],"mappings":";;;;;;AAUA,SAASA,eAAa,KAAkC;CAGtD,MAAM,MAAM,GAFK,IAAI,YAAY,OAET,KADX,IAAI,IAAI,MAAM,KAAK,cACI,IAAI,eAAe,IAAI;CAE3D,MAAM,UAAU,IAAI,QAAQ;CAC5B,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,IAAI,OAAO,GAAG;EACtD,IAAI,CAAC,OAAO;EACZ,IAAI,MAAM,QAAQ,KAAK,GACrB,MAAM,SAAQ,MAAK,QAAQ,OAAO,KAAK,CAAC,CAAC;OAEzC,QAAQ,IAAI,KAAK,KAAK;CAE1B;CAEA,OAAO,IAAI,WAAW,QAAQ,KAAK;EACjC,QAAQ,IAAI;EACZ;CACF,CAAC;AACH;AAEA,SAAgB,qBAAqB,EACnC,QACA,eAAe,QACoF;CACnG,OAAO,OAAO,KAAc,KAAe,SAAuB;EAChE,IAAI,CAAC,cAAc;GACjB,KAAK;GACL;EACF;EAEA,MAAM,aAAa,OAAO,UAAU,CAAC,EAAE;EACvC,IAAI,CAAC,YAAY;GACf,KAAK;GACL;EACF;EAEA,MAAM,iBAAiB,IAAI,OAAO,kBAAkB,IAAIC,6BAAAA,eAAe;EACvE,IAAI,OAAO,iBAAiB;EAC5B,IAAI,OAAO,SAAS,IAAI,OAAO,UAAU;EAEzC,MAAM,OAA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,CAAC,KAAK,iBAAiB,IAAI,IAAI,GACjC,OAAO,KAAK;GAGd,MAAM,QAAQ,KAAK,IAAI;GACvB,MAAM,SAAS,IAAI;GACnB,MAAM,OAAO,IAAI;GAEjB,IAAI,GAAG,gBAAgB;IACrB,MAAM,WAAW,KAAK,IAAI,IAAI;IAC9B,MAAM,SAAS,IAAI;IACnB,MAAM,QAAQ,KAAK,mBAAmB,SAAS;IAE/C,MAAM,UAA+B;KACnC;KACA;KACA;KACA,UAAU,GAAG,SAAS;IACxB;IAEA,IAAI,KAAK,mBAAmB,oBAC1B,QAAQ,QAAQ,IAAI;IAGtB,IAAI,KAAK,mBAAmB,gBAAgB;KAC1C,MAAM,UAAU,EAAE,GAAG,IAAI,QAAQ;KAEjC,CADsB,KAAK,kBAAkB,iBAAiB,CAAC,EAAA,CACjD,SAAQ,MAAK;MACzB,MAAM,MAAM,EAAE,YAAY;MAC1B,IAAI,QAAQ,SAAS,KAAA,GACnB,QAAQ,OAAO;KAEnB,CAAC;KACD,QAAQ,UAAU;IACpB;IAEA,KAAK,OAAO,MAAM,CAAC,GAAG,OAAO,GAAG,KAAK,GAAG,OAAO,GAAG,SAAS,KAAK,OAAO;GACzE,CAAC;GAED,KAAK;EACP,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["toWebRequest","RequestContext","isCustomRoutePublic","coreAuthMiddleware","MastraServerBase","redactStreamChunk","serializeStreamChunk","normalizeQueryParams","Busboy","isSafeObjectKey","isZodError","checkRouteFGA","getCustomHTTPExceptionResponse","getHTTPErrorResponse","findMatchingCustomRoute","isProtectedCustomRoute"],"sources":["../src/auth-middleware.ts","../src/index.ts"],"sourcesContent":["import type { Mastra } from '@mastra/core/mastra';\nimport { RequestContext } from '@mastra/core/request-context';\nimport { coreAuthMiddleware, isCustomRoutePublic } from '@mastra/server/auth';\nimport type { NextFunction, Request, Response } from 'express';\n\nexport interface ExpressAuthMiddlewareOptions {\n mastra: Mastra;\n requiresAuth?: boolean;\n}\n\nfunction toWebRequest(req: Request): globalThis.Request {\n const protocol = req.protocol || 'http';\n const host = req.get('host') || 'localhost';\n const url = `${protocol}://${host}${req.originalUrl || req.url}`;\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (!value) continue;\n if (Array.isArray(value)) {\n value.forEach(v => headers.append(key, v));\n } else {\n headers.set(key, value);\n }\n }\n\n return new globalThis.Request(url, {\n method: req.method,\n headers,\n });\n}\n\nexport function createAuthMiddleware({\n mastra,\n requiresAuth = true,\n}: ExpressAuthMiddlewareOptions): (req: Request, res: Response, next: NextFunction) => Promise<void> {\n return async (req: Request, res: Response, next: NextFunction) => {\n if (!requiresAuth) {\n next();\n return;\n }\n\n const authConfig = mastra.getServer()?.auth;\n if (!authConfig) {\n next();\n return;\n }\n\n const requestContext = res.locals.requestContext ?? new RequestContext();\n res.locals.requestContext = requestContext;\n res.locals.mastra = res.locals.mastra ?? mastra;\n\n const path = String(req.path || '/');\n const method = String(req.method || 'GET');\n const customRouteAuthConfig = new Map<string, boolean>(res.locals.customRouteAuthConfig ?? []);\n // Don't reclassify a custom route the app declared public (requiresAuth: false).\n if (!isCustomRoutePublic(path, method, customRouteAuthConfig)) {\n customRouteAuthConfig.set(`${method}:${path}`, true);\n }\n\n const authHeader = req.headers.authorization;\n let token: string | null = authHeader ? authHeader.replace('Bearer ', '') : null;\n if (!token && req.query.apiKey) {\n token = (req.query.apiKey as string) || null;\n }\n\n const result = await coreAuthMiddleware({\n path,\n method,\n getHeader: name => req.headers[name.toLowerCase()] as string | undefined,\n mastra,\n authConfig,\n customRouteAuthConfig,\n requestContext,\n rawRequest: toWebRequest(req),\n token,\n buildAuthorizeContext: () => toWebRequest(req),\n });\n\n for (const [key, value] of Object.entries(result.headers ?? {})) {\n if (key.toLowerCase() === 'set-cookie') {\n res.append(key, value);\n } else {\n res.setHeader(key, value);\n }\n }\n\n if (result.action === 'next') {\n next();\n return;\n }\n\n res.status(result.status).json(result.body);\n };\n}\n","import { Busboy } from '@fastify/busboy';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { InMemoryTaskStore } from '@mastra/server/a2a/store';\nimport { findMatchingCustomRoute, isProtectedCustomRoute } from '@mastra/server/auth';\nimport type { MCPHttpTransportResult, MCPSseTransportResult } from '@mastra/server/handlers/mcp';\nimport type { ParsedRequestParams, ServerRoute } from '@mastra/server/server-adapter';\nimport {\n MastraServer as MastraServerBase,\n checkRouteFGA,\n getCustomHTTPExceptionResponse,\n getHTTPErrorResponse,\n isSafeObjectKey,\n isZodError,\n normalizeQueryParams,\n redactStreamChunk,\n serializeStreamChunk,\n} from '@mastra/server/server-adapter';\nimport type { Application, NextFunction, Request, Response } from 'express';\nexport { createAuthMiddleware } from './auth-middleware';\nexport type { ExpressAuthMiddlewareOptions } from './auth-middleware';\n\nclass BodyLimitExceededError extends Error {\n constructor(limit: number) {\n super(`Request body size limit exceeded (max: ${limit} bytes)`);\n }\n}\n\ntype HasPermissionFn = (userPerms: string[], required: string) => boolean;\ntype AuthErrorWithHeaders = { status: number; error: string; headers?: Record<string, string> };\nlet _hasPermissionPromise: Promise<HasPermissionFn | undefined> | undefined;\nfunction loadHasPermission(): Promise<HasPermissionFn | undefined> {\n if (!_hasPermissionPromise) {\n _hasPermissionPromise = import('@mastra/core/auth/ee')\n .then(m => m.hasPermission)\n .catch(() => {\n console.error(\n '[@mastra/express] Auth features require @mastra/core >= 1.6.0. Please upgrade: npm install @mastra/core@latest',\n );\n return undefined;\n });\n }\n return _hasPermissionPromise;\n}\n\n/**\n * Convert Express request to Web API Request for cookie-based auth providers.\n */\nfunction toWebRequest(req: Request): globalThis.Request {\n const protocol = req.protocol || 'http';\n const host = req.get('host') || 'localhost';\n const url = `${protocol}://${host}${req.originalUrl || req.url}`;\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value) {\n if (Array.isArray(value)) {\n value.forEach(v => headers.append(key, v));\n } else {\n headers.set(key, value);\n }\n }\n }\n\n return new globalThis.Request(url, {\n method: req.method,\n headers,\n });\n}\n\n// Extend Express types to include Mastra context\ndeclare global {\n namespace Express {\n interface Locals {\n mastra: Mastra;\n requestContext: RequestContext;\n abortSignal: AbortSignal;\n registeredTools: ToolsInput;\n taskStore: InMemoryTaskStore;\n customRouteAuthConfig?: Map<string, boolean>;\n }\n }\n}\n\nexport class MastraServer extends MastraServerBase<Application, Request, Response> {\n createContextMiddleware(): (req: Request, res: Response, next: NextFunction) => Promise<void> {\n return async (req: Request, res: Response, next: NextFunction) => {\n // Parse request context from request body and add to context\n let bodyRequestContext: Record<string, any> | undefined;\n let paramsRequestContext: Record<string, any> | undefined;\n\n // Parse request context from request body (POST/PUT)\n if (req.method === 'POST' || req.method === 'PUT') {\n const contentType = req.headers['content-type'];\n if (contentType?.includes('application/json') && req.body) {\n if (req.body.requestContext) {\n bodyRequestContext = req.body.requestContext;\n }\n }\n }\n\n // Parse request context from query params.\n if (req.method === 'GET' || req.method === 'POST') {\n try {\n const encodedRequestContext = req.query.requestContext;\n if (typeof encodedRequestContext === 'string') {\n // Try JSON first\n try {\n paramsRequestContext = JSON.parse(encodedRequestContext);\n } catch {\n // Fallback to base64(JSON)\n try {\n const json = Buffer.from(encodedRequestContext, 'base64').toString('utf-8');\n paramsRequestContext = JSON.parse(json);\n } catch {\n // ignore if still invalid\n }\n }\n }\n } catch {\n // ignore query parsing errors\n }\n }\n\n const requestContext = this.mergeRequestContext({ paramsRequestContext, bodyRequestContext });\n this.applyRequestMetadataToContext({\n requestContext,\n getHeader: name => req.get(name),\n });\n\n // Set context in res.locals\n res.locals.requestContext = requestContext;\n res.locals.mastra = this.mastra;\n res.locals.registeredTools = this.tools || {};\n if (this.taskStore) {\n res.locals.taskStore = this.taskStore;\n }\n res.locals.customRouteAuthConfig = this.customRouteAuthConfig;\n const controller = new AbortController();\n // Use res.on('close') instead of req.on('close') because the request's 'close' event\n // fires when the request body is fully consumed (e.g., after express.json() parses it),\n // NOT when the client disconnects. The response's 'close' event fires when the underlying\n // connection is actually closed, which is the correct signal for stream cleanup.\n res.on('close', () => {\n // Only abort if the response wasn't successfully completed\n if (!res.writableFinished) {\n controller.abort();\n }\n });\n res.locals.abortSignal = controller.signal;\n next();\n };\n }\n async stream(route: ServerRoute, res: Response, result: { fullStream: ReadableStream }): Promise<void> {\n const streamFormat = route.streamFormat || 'stream';\n\n if (streamFormat === 'sse') {\n res.setHeader('Content-Type', 'text/event-stream');\n res.setHeader('Cache-Control', 'no-cache');\n res.setHeader('Connection', 'keep-alive');\n res.setHeader('X-Accel-Buffering', 'no');\n } else {\n res.setHeader('Content-Type', 'text/plain');\n }\n res.setHeader('Transfer-Encoding', 'chunked');\n res.flushHeaders();\n\n if (streamFormat === 'sse' && route.sseFlushOnConnect) {\n res.write(': connected\\n\\n');\n }\n\n const readableStream = result instanceof ReadableStream ? result : result.fullStream;\n const reader = readableStream.getReader();\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n if (value) {\n if (streamFormat === 'sse' && typeof value === 'string' && value.startsWith(':')) {\n res.write(value);\n continue;\n }\n\n // Optionally redact sensitive data (system prompts, tool definitions, API keys) before sending to the client\n const shouldRedact = this.streamOptions?.redact ?? true;\n const outputValue = shouldRedact ? redactStreamChunk(value) : value;\n // A chunk that can't be serialized must not kill the stream — skip it and keep streaming\n const serialized = serializeStreamChunk(outputValue);\n if (!serialized.ok) {\n this.mastra.getLogger()?.error('Failed to serialize stream chunk, skipping', {\n path: route.path,\n chunkType: (outputValue as { type?: string })?.type,\n error: serialized.error.message,\n });\n continue;\n }\n if (streamFormat === 'sse') {\n res.write(`data: ${serialized.json}\\n\\n`);\n } else {\n res.write(serialized.json + '\\x1E');\n }\n }\n }\n } catch (error) {\n this.mastra.getLogger()?.error('Error in stream processing', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n } finally {\n res.end();\n }\n }\n\n async getParams(route: ServerRoute, request: Request): Promise<ParsedRequestParams> {\n const urlParams = request.params as Record<string, string>;\n // Express's req.query can contain string | string[] | ParsedQs | ParsedQs[]\n const queryParams = normalizeQueryParams(request.query as Record<string, unknown>);\n let body: unknown;\n let bodyParseError: { message: string } | undefined;\n\n if (route.method === 'POST' || route.method === 'PUT' || route.method === 'PATCH' || route.method === 'DELETE') {\n const contentType = request.headers['content-type'] || '';\n\n if (contentType.includes('multipart/form-data')) {\n try {\n const maxFileSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;\n body = await this.parseMultipartFormData(request, maxFileSize);\n } catch (error) {\n if (error instanceof BodyLimitExceededError) {\n throw error;\n }\n this.mastra.getLogger()?.error('Failed to parse multipart form data', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n bodyParseError = {\n message: error instanceof Error ? error.message : 'Failed to parse multipart form data',\n };\n }\n } else {\n body = request.body;\n }\n }\n\n return { urlParams, queryParams, body, bodyParseError };\n }\n\n /**\n * Parse multipart/form-data using @fastify/busboy.\n * Converts file uploads to Buffers and parses JSON field values.\n *\n * @param request - The Express request object\n * @param maxFileSize - Optional maximum file size in bytes\n */\n private parseMultipartFormData(request: Request, maxFileSize?: number): Promise<Record<string, unknown>> {\n return new Promise((resolve, reject) => {\n const result: Record<string, unknown> = {};\n\n const busboy = new Busboy({\n headers: {\n 'content-type': request.headers['content-type'] as string,\n },\n limits: maxFileSize ? { fileSize: maxFileSize, fieldSize: maxFileSize } : undefined,\n });\n\n // Content-Length is checked up front, but chunked bodies have none, so cap\n // the total bytes pulled from the request while streaming into busboy.\n if (maxFileSize !== undefined) {\n let received = 0;\n const onData = (chunk: Buffer) => {\n received += chunk.length;\n if (received > maxFileSize) {\n request.off('data', onData);\n request.unpipe(busboy);\n request.pause();\n reject(new BodyLimitExceededError(maxFileSize));\n }\n };\n request.on('data', onData);\n }\n\n busboy.on('file', (fieldname: string, file: NodeJS.ReadableStream) => {\n const chunks: Buffer[] = [];\n let limitExceeded = false;\n\n file.on('data', (chunk: Buffer) => {\n chunks.push(chunk);\n });\n\n file.on('limit', () => {\n limitExceeded = true;\n reject(new BodyLimitExceededError(maxFileSize!));\n });\n\n file.on('end', () => {\n if (!limitExceeded && isSafeObjectKey(fieldname)) {\n result[fieldname] = Buffer.concat(chunks);\n }\n });\n });\n\n busboy.on('field', (fieldname: string, value: string) => {\n if (!isSafeObjectKey(fieldname)) {\n return;\n }\n // Try to parse JSON strings (like 'options')\n try {\n result[fieldname] = JSON.parse(value);\n } catch {\n result[fieldname] = value;\n }\n });\n\n busboy.on('finish', () => {\n resolve(result);\n });\n\n busboy.on('error', (error: Error) => {\n reject(error);\n });\n\n request.pipe(busboy);\n });\n }\n\n async sendResponse(\n route: ServerRoute,\n response: Response,\n result: unknown,\n request?: Request,\n prefix?: string,\n ): Promise<void> {\n const resolvedPrefix = prefix ?? this.prefix ?? '';\n\n // Apply refresh headers from transparent session refresh (e.g. Set-Cookie after token refresh)\n if (result && typeof result === 'object' && '__refreshHeaders' in result) {\n const refreshHeaders = (result as any).__refreshHeaders as Record<string, string>;\n for (const [key, value] of Object.entries(refreshHeaders)) {\n response.setHeader(key, value);\n }\n delete (result as any).__refreshHeaders;\n }\n\n if (route.responseType === 'json') {\n response.json(result);\n } else if (route.responseType === 'stream') {\n await this.stream(route, response, result as { fullStream: ReadableStream });\n } else if (route.responseType === 'datastream-response') {\n // Handle AI SDK Response objects - pipe Response.body to Express response\n const fetchResponse = result as globalThis.Response;\n fetchResponse.headers.forEach((value, key) => response.setHeader(key, value));\n response.status(fetchResponse.status);\n if (fetchResponse.body) {\n const reader = fetchResponse.body.getReader();\n\n const onResError = (err: unknown) => {\n this.mastra.getLogger()?.error('Error writing datastream response', {\n error: err instanceof Error ? { message: err.message, stack: err.stack } : err,\n });\n void reader.cancel('response write error').catch(() => {});\n };\n response.once('error', onResError);\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n response.write(value);\n }\n } catch (error) {\n this.mastra.getLogger()?.error('Error in datastream processing', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n } finally {\n response.off('error', onResError);\n response.end();\n }\n } else {\n response.end();\n }\n } else if (route.responseType === 'mcp-http') {\n // MCP Streamable HTTP transport - request is required\n if (!request) {\n response.status(500).json({ error: 'Request object required for MCP transport' });\n return;\n }\n\n const { server, httpPath, mcpOptions: routeMcpOptions } = result as MCPHttpTransportResult;\n\n try {\n // Merge class-level mcpOptions with route-specific options (route takes precedence)\n const options = { ...this.mcpOptions, ...routeMcpOptions };\n\n await server.startHTTP({\n url: new URL(request.url, `http://${request.headers.host}`),\n httpPath: `${resolvedPrefix}${httpPath}`,\n req: request,\n res: response,\n options: Object.keys(options).length > 0 ? options : undefined,\n });\n // Response handled by startHTTP\n } catch {\n if (!response.headersSent) {\n response.status(500).json({\n jsonrpc: '2.0',\n error: { code: -32603, message: 'Internal server error' },\n id: null,\n });\n }\n }\n } else if (route.responseType === 'mcp-sse') {\n // MCP SSE transport - request is required\n if (!request) {\n response.status(500).json({ error: 'Request object required for MCP transport' });\n return;\n }\n\n const { server, ssePath, messagePath } = result as MCPSseTransportResult;\n\n try {\n await server.startSSE({\n url: new URL(request.url, `http://${request.headers.host}`),\n ssePath: `${resolvedPrefix}${ssePath}`,\n messagePath: `${resolvedPrefix}${messagePath}`,\n req: request,\n res: response,\n });\n // Response handled by startSSE\n } catch {\n if (!response.headersSent) {\n response.status(500).json({ error: 'Error handling MCP SSE request' });\n }\n }\n } else {\n response.sendStatus(500);\n }\n }\n\n async registerRoute(\n app: Application,\n route: ServerRoute,\n { prefix: prefixParam }: { prefix?: string } = {},\n ): Promise<void> {\n // Default prefix to this.prefix if not provided, or empty string\n const prefix = prefixParam ?? this.prefix ?? '';\n\n const maxSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;\n const isBodyMethod = ['POST', 'PUT', 'PATCH', 'DELETE'].includes(route.method.toUpperCase());\n\n // Create middleware array\n const middlewares: Array<(req: Request, res: Response, next: NextFunction) => void> = [];\n\n const sendBodyTooLarge = (res: Response) => {\n let errorResponse: unknown = { error: 'Request body too large' };\n if (route.maxBodySize === undefined && this.bodyLimitOptions) {\n try {\n errorResponse = this.bodyLimitOptions.onError(errorResponse);\n } catch {\n // Fall back to the default response.\n }\n }\n // Close the connection instead of draining the rest of the oversized body.\n res.setHeader('Connection', 'close');\n return res.status(413).json(errorResponse);\n };\n\n // Add body limit middleware if needed\n if (isBodyMethod && maxSize !== undefined) {\n const bodyLimitMiddleware = (req: Request, res: Response, next: NextFunction) => {\n const contentLength = req.headers['content-length'];\n // A host-level parser may run before this route middleware, so this is a\n // post-parse safeguard when Content-Length is unavailable.\n const parsedLength =\n contentLength === undefined && req.body !== undefined\n ? Buffer.byteLength(JSON.stringify(req.body), 'utf8')\n : 0;\n if ((contentLength && parseInt(contentLength, 10) > maxSize) || parsedLength > maxSize) {\n return sendBodyTooLarge(res);\n }\n next();\n };\n middlewares.push(bodyLimitMiddleware);\n }\n\n app[route.method.toLowerCase() as keyof Application](\n `${prefix}${route.path}`,\n ...middlewares,\n async (req: Request, res: Response) => {\n // Check route-level authentication/authorization\n const authError = await this.checkRouteAuth(route, {\n path: String(req.path || '/'),\n method: String(req.method || 'GET'),\n getHeader: name => req.headers[name.toLowerCase()] as string | undefined,\n getQuery: name => req.query[name] as string | undefined,\n requestContext: res.locals.requestContext,\n request: toWebRequest(req),\n buildAuthorizeContext: () => toWebRequest(req),\n });\n\n if (authError) {\n const authResult = authError as AuthErrorWithHeaders;\n // Apply any refresh headers (e.g. Set-Cookie from transparent session refresh)\n if (authResult.headers) {\n for (const [key, value] of Object.entries(authResult.headers)) {\n res.setHeader(key, value);\n }\n }\n\n // If this is an auth error (not just a success-with-headers), return error response\n if (authResult.error) {\n return res.status(authResult.status).json({ error: authResult.error });\n }\n }\n\n let params: ParsedRequestParams;\n try {\n params = await this.getParams(route, req);\n } catch (error) {\n if (error instanceof BodyLimitExceededError) {\n return sendBodyTooLarge(res);\n }\n throw error;\n }\n\n // Return 400 Bad Request if body parsing failed (e.g., malformed multipart data)\n if (params.bodyParseError) {\n return res.status(400).json({\n error: 'Invalid request body',\n issues: [{ field: 'body', message: params.bodyParseError.message }],\n });\n }\n\n if (params.queryParams) {\n try {\n params.queryParams = await this.parseQueryParams(route, params.queryParams);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing query params', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (isZodError(error)) {\n const { status, body } = this.resolveValidationError(route, error, 'query');\n return res.status(status).json(body);\n }\n return res.status(400).json({\n error: 'Invalid query parameters',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n });\n }\n }\n\n if (params.body !== undefined || route.bodySchema) {\n try {\n params.body = await this.parseBody(route, params.body);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing body', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (isZodError(error)) {\n const { status, body } = this.resolveValidationError(route, error, 'body');\n return res.status(status).json(body);\n }\n return res.status(400).json({\n error: 'Invalid request body',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n });\n }\n }\n\n // Parse path params through pathParamSchema for type coercion (e.g., z.coerce.number())\n if (params.urlParams) {\n try {\n params.urlParams = await this.parsePathParams(route, params.urlParams);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing path params', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (isZodError(error)) {\n const { status, body } = this.resolveValidationError(route, error, 'path');\n return res.status(status).json(body);\n }\n return res.status(400).json({\n error: 'Invalid path parameters',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n });\n }\n }\n\n const handlerParams = {\n ...params.urlParams,\n ...params.queryParams,\n ...(typeof params.body === 'object' ? params.body : {}),\n requestContext: res.locals.requestContext,\n mastra: this.mastra,\n registeredTools: res.locals.registeredTools,\n taskStore: res.locals.taskStore,\n abortSignal: res.locals.abortSignal,\n routePrefix: prefix,\n request: toWebRequest(req),\n };\n\n // Check route permission requirement (EE feature)\n // Uses convention-based permission derivation: permissions are auto-derived\n // from route path/method unless explicitly set or route is public\n // Check if any auth is configured (studio or server) for RBAC\n const hasAuth = this.mastra.getStudio?.()?.auth || this.mastra.getServer()?.auth;\n if (hasAuth) {\n const hasPermission = await loadHasPermission();\n if (hasPermission) {\n const userPermissions = res.locals.requestContext.get('mastra__userPermissions') as string[] | undefined;\n const permissionError = this.checkRoutePermission(\n route,\n userPermissions,\n hasPermission,\n res.locals.requestContext,\n );\n\n if (permissionError) {\n return res.status(permissionError.status).json({\n error: permissionError.error,\n message: permissionError.message,\n });\n }\n }\n }\n\n // Check FGA authorization (EE feature)\n const fgaError = await checkRouteFGA(this.mastra, route, res.locals.requestContext, {\n ...params.urlParams,\n ...params.queryParams,\n ...(typeof params.body === 'object' ? params.body : {}),\n });\n if (fgaError) {\n return res.status(fgaError.status).json({ error: fgaError.error, message: fgaError.message });\n }\n\n try {\n const result = await route.handler(handlerParams);\n await this.sendResponse(route, res, result, req, prefix);\n } catch (error) {\n const httpStatus =\n error && typeof error === 'object' ? ((error as any).status ?? (error as any).details?.status) : undefined;\n const isClientError = typeof httpStatus === 'number' && httpStatus >= 400 && httpStatus < 500;\n if (!isClientError) {\n // 501 means an optional capability isn't provided by the configured storage or core: expected, not a server fault.\n const logLevel = httpStatus === 501 ? 'warn' : 'error';\n this.mastra.getLogger()?.[logLevel]('Error calling handler', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n path: route.path,\n method: route.method,\n });\n }\n const customResponse = getCustomHTTPExceptionResponse(error);\n if (customResponse) {\n customResponse.headers.forEach((value, name) => res.setHeader(name, value));\n res.status(customResponse.status).end(Buffer.from(await customResponse.arrayBuffer()));\n return;\n }\n\n const { status, body } = getHTTPErrorResponse(error);\n res.status(status).json(body);\n }\n },\n );\n }\n\n async registerCustomApiRoutes(): Promise<void> {\n const routes = await this.registerSchemaApiRoutes();\n if (!(await this.buildCustomRouteHandler(routes))) return;\n\n this.app.use(async (req: Request, res: Response, next: NextFunction) => {\n // Check if this request matches a protected custom route and run auth\n const path = String(req.path || '/');\n const method = String(req.method || 'GET');\n const matchedRoute = findMatchingCustomRoute(\n path,\n method,\n this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes,\n );\n const shouldRunCustomRouteAuth = isProtectedCustomRoute(path, method, this.customRouteAuthConfig);\n const shouldRunCustomRouteFGA = !!matchedRoute?.route.fga;\n\n if (shouldRunCustomRouteAuth || shouldRunCustomRouteFGA) {\n const serverRoute: ServerRoute = {\n method: (matchedRoute?.route.method ?? method) as any,\n path: matchedRoute?.route.path ?? path,\n responseType: 'json',\n handler: async () => {},\n requiresAuth: matchedRoute?.route.requiresAuth,\n requiresPermission: matchedRoute?.route.requiresPermission,\n fga: matchedRoute?.route.fga,\n };\n\n if (shouldRunCustomRouteAuth) {\n const authError = await this.checkRouteAuth(serverRoute, {\n path,\n method,\n getHeader: name => req.headers[name.toLowerCase()] as string | undefined,\n getQuery: name => req.query[name] as string | undefined,\n requestContext: res.locals.requestContext,\n request: toWebRequest(req),\n buildAuthorizeContext: () => toWebRequest(req),\n });\n\n if (authError) {\n const authResult = authError as AuthErrorWithHeaders;\n if (authResult.headers) {\n for (const [key, value] of Object.entries(authResult.headers)) {\n res.setHeader(key, value);\n }\n }\n if (authResult.error) {\n return res.status(authResult.status).json({ error: authResult.error });\n }\n }\n\n // Check if any auth is configured (studio or server) for RBAC\n const hasAuth = this.mastra.getStudio?.()?.auth || this.mastra.getServer()?.auth;\n if (hasAuth) {\n const hasPermission = await loadHasPermission();\n if (hasPermission) {\n const userPermissions = res.locals.requestContext.get('mastra__userPermissions') as string[] | undefined;\n const permissionError = this.checkRoutePermission(\n serverRoute,\n userPermissions,\n hasPermission,\n res.locals.requestContext,\n );\n if (permissionError) {\n return res.status(permissionError.status).json({\n error: permissionError.error,\n message: permissionError.message,\n });\n }\n }\n }\n }\n\n // Check FGA authorization (EE feature)\n // Path params last: the custom handler reads them from the URL, so query/body\n // values must not be able to change which resource FGA checks.\n const fgaError = await checkRouteFGA(this.mastra, serverRoute, res.locals.requestContext, {\n ...(req.query as Record<string, string>),\n ...(typeof req.body === 'object' && req.body !== null ? req.body : {}),\n ...(matchedRoute?.params ?? {}),\n });\n if (fgaError) {\n return res.status(fgaError.status).json({ error: fgaError.error, message: fgaError.message });\n }\n }\n\n const response = await this.handleCustomRouteRequest(\n `${req.protocol}://${req.get('host') || 'localhost'}${req.originalUrl}`,\n req.method,\n req.headers as Record<string, string | string[] | undefined>,\n req.body,\n res.locals.requestContext,\n res.locals.abortSignal,\n );\n if (!response) return next();\n await this.writeCustomRouteResponse(response, res, res.locals.abortSignal);\n });\n }\n\n registerContextMiddleware(): void {\n this.app.use(this.createContextMiddleware());\n this.app.use((req, res, next) => {\n const path = String(req.path || '/');\n const method = String(req.method || 'GET');\n res.on('finish', () => {\n this.warnIfUnregisteredChannelWebhook(path, method, res.statusCode);\n });\n next();\n });\n }\n\n registerAuthMiddleware(): void {\n // Auth is handled per-route in registerRoute() and registerCustomApiRoutes()\n // No global middleware needed\n }\n\n registerHttpLoggingMiddleware(): void {\n if (!this.httpLoggingConfig?.enabled) {\n return;\n }\n\n this.app.use((req, res, next) => {\n if (!this.shouldLogRequest(req.path)) {\n return next();\n }\n\n const start = Date.now();\n const method = req.method;\n const path = req.path;\n\n res.on('finish', () => {\n const duration = Date.now() - start;\n const status = res.statusCode;\n const level = this.httpLoggingConfig?.level || 'info';\n\n const logData: Record<string, any> = {\n method,\n path,\n status,\n duration: `${duration}ms`,\n };\n\n if (this.httpLoggingConfig?.includeQueryParams) {\n logData.query = req.query;\n }\n\n if (this.httpLoggingConfig?.includeHeaders) {\n const headers = { ...req.headers };\n const redactHeaders = this.httpLoggingConfig.redactHeaders || [];\n redactHeaders.forEach(h => {\n const key = h.toLowerCase();\n if (headers[key] !== undefined) {\n headers[key] = '[REDACTED]';\n }\n });\n logData.headers = headers;\n }\n\n this.logger[level](`${method} ${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import { Busboy } from "@fastify/busboy";
2
2
  import { coreAuthMiddleware, findMatchingCustomRoute, isCustomRoutePublic, isProtectedCustomRoute } from "@mastra/server/auth";
3
- import { MastraServer as MastraServer$1, checkRouteFGA, getCustomHTTPExceptionResponse, isSafeObjectKey, isZodError, normalizeQueryParams, redactStreamChunk, serializeStreamChunk } from "@mastra/server/server-adapter";
3
+ import { MastraServer as MastraServer$1, checkRouteFGA, getCustomHTTPExceptionResponse, getHTTPErrorResponse, isSafeObjectKey, isZodError, normalizeQueryParams, redactStreamChunk, serializeStreamChunk } from "@mastra/server/server-adapter";
4
4
  import { RequestContext } from "@mastra/core/request-context";
5
5
  //#region src/auth-middleware.ts
6
6
  function toWebRequest$1(req) {
@@ -60,6 +60,11 @@ function createAuthMiddleware({ mastra, requiresAuth = true }) {
60
60
  }
61
61
  //#endregion
62
62
  //#region src/index.ts
63
+ var BodyLimitExceededError = class extends Error {
64
+ constructor(limit) {
65
+ super(`Request body size limit exceeded (max: ${limit} bytes)`);
66
+ }
67
+ };
63
68
  let _hasPermissionPromise;
64
69
  function loadHasPermission() {
65
70
  if (!_hasPermissionPromise) _hasPermissionPromise = import("@mastra/core/auth/ee").then((m) => m.hasPermission).catch(() => {
@@ -73,8 +78,10 @@ function loadHasPermission() {
73
78
  function toWebRequest(req) {
74
79
  const url = `${req.protocol || "http"}://${req.get("host") || "localhost"}${req.originalUrl || req.url}`;
75
80
  const headers = new Headers();
76
- for (const [key, value] of Object.entries(req.headers)) if (value) if (Array.isArray(value)) value.forEach((v) => headers.append(key, v));
77
- else headers.set(key, value);
81
+ for (const [key, value] of Object.entries(req.headers)) if (value) {
82
+ if (Array.isArray(value)) value.forEach((v) => headers.append(key, v));
83
+ else headers.set(key, value);
84
+ }
78
85
  return new globalThis.Request(url, {
79
86
  method: req.method,
80
87
  headers
@@ -171,18 +178,20 @@ var MastraServer = class extends MastraServer$1 {
171
178
  const queryParams = normalizeQueryParams(request.query);
172
179
  let body;
173
180
  let bodyParseError;
174
- if (route.method === "POST" || route.method === "PUT" || route.method === "PATCH" || route.method === "DELETE") if ((request.headers["content-type"] || "").includes("multipart/form-data")) try {
175
- const maxFileSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;
176
- body = await this.parseMultipartFormData(request, maxFileSize);
177
- } catch (error) {
178
- this.mastra.getLogger()?.error("Failed to parse multipart form data", { error: error instanceof Error ? {
179
- message: error.message,
180
- stack: error.stack
181
- } : error });
182
- if (error instanceof Error && error.message.toLowerCase().includes("size")) throw error;
183
- bodyParseError = { message: error instanceof Error ? error.message : "Failed to parse multipart form data" };
181
+ if (route.method === "POST" || route.method === "PUT" || route.method === "PATCH" || route.method === "DELETE") {
182
+ if ((request.headers["content-type"] || "").includes("multipart/form-data")) try {
183
+ const maxFileSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;
184
+ body = await this.parseMultipartFormData(request, maxFileSize);
185
+ } catch (error) {
186
+ if (error instanceof BodyLimitExceededError) throw error;
187
+ this.mastra.getLogger()?.error("Failed to parse multipart form data", { error: error instanceof Error ? {
188
+ message: error.message,
189
+ stack: error.stack
190
+ } : error });
191
+ bodyParseError = { message: error instanceof Error ? error.message : "Failed to parse multipart form data" };
192
+ }
193
+ else body = request.body;
184
194
  }
185
- else body = request.body;
186
195
  return {
187
196
  urlParams,
188
197
  queryParams,
@@ -202,8 +211,24 @@ var MastraServer = class extends MastraServer$1 {
202
211
  const result = {};
203
212
  const busboy = new Busboy({
204
213
  headers: { "content-type": request.headers["content-type"] },
205
- limits: maxFileSize ? { fileSize: maxFileSize } : void 0
214
+ limits: maxFileSize ? {
215
+ fileSize: maxFileSize,
216
+ fieldSize: maxFileSize
217
+ } : void 0
206
218
  });
219
+ if (maxFileSize !== void 0) {
220
+ let received = 0;
221
+ const onData = (chunk) => {
222
+ received += chunk.length;
223
+ if (received > maxFileSize) {
224
+ request.off("data", onData);
225
+ request.unpipe(busboy);
226
+ request.pause();
227
+ reject(new BodyLimitExceededError(maxFileSize));
228
+ }
229
+ };
230
+ request.on("data", onData);
231
+ }
207
232
  busboy.on("file", (fieldname, file) => {
208
233
  const chunks = [];
209
234
  let limitExceeded = false;
@@ -212,7 +237,7 @@ var MastraServer = class extends MastraServer$1 {
212
237
  });
213
238
  file.on("limit", () => {
214
239
  limitExceeded = true;
215
- reject(/* @__PURE__ */ new Error(`File size limit exceeded${maxFileSize ? ` (max: ${maxFileSize} bytes)` : ""}`));
240
+ reject(new BodyLimitExceededError(maxFileSize));
216
241
  });
217
242
  file.on("end", () => {
218
243
  if (!limitExceeded && isSafeObjectKey(fieldname)) result[fieldname] = Buffer.concat(chunks);
@@ -331,17 +356,19 @@ var MastraServer = class extends MastraServer$1 {
331
356
  "DELETE"
332
357
  ].includes(route.method.toUpperCase());
333
358
  const middlewares = [];
359
+ const sendBodyTooLarge = (res) => {
360
+ let errorResponse = { error: "Request body too large" };
361
+ if (route.maxBodySize === void 0 && this.bodyLimitOptions) try {
362
+ errorResponse = this.bodyLimitOptions.onError(errorResponse);
363
+ } catch {}
364
+ res.setHeader("Connection", "close");
365
+ return res.status(413).json(errorResponse);
366
+ };
334
367
  if (isBodyMethod && maxSize !== void 0) {
335
368
  const bodyLimitMiddleware = (req, res, next) => {
336
369
  const contentLength = req.headers["content-length"];
337
370
  const parsedLength = contentLength === void 0 && req.body !== void 0 ? Buffer.byteLength(JSON.stringify(req.body), "utf8") : 0;
338
- if (contentLength && parseInt(contentLength, 10) > maxSize || parsedLength > maxSize) {
339
- let errorResponse = { error: "Request body too large" };
340
- if (route.maxBodySize === void 0 && this.bodyLimitOptions) try {
341
- errorResponse = this.bodyLimitOptions.onError(errorResponse);
342
- } catch {}
343
- return res.status(413).json(errorResponse);
344
- }
371
+ if (contentLength && parseInt(contentLength, 10) > maxSize || parsedLength > maxSize) return sendBodyTooLarge(res);
345
372
  next();
346
373
  };
347
374
  middlewares.push(bodyLimitMiddleware);
@@ -361,7 +388,13 @@ var MastraServer = class extends MastraServer$1 {
361
388
  if (authResult.headers) for (const [key, value] of Object.entries(authResult.headers)) res.setHeader(key, value);
362
389
  if (authResult.error) return res.status(authResult.status).json({ error: authResult.error });
363
390
  }
364
- const params = await this.getParams(route, req);
391
+ let params;
392
+ try {
393
+ params = await this.getParams(route, req);
394
+ } catch (error) {
395
+ if (error instanceof BodyLimitExceededError) return sendBodyTooLarge(res);
396
+ throw error;
397
+ }
365
398
  if (params.bodyParseError) return res.status(400).json({
366
399
  error: "Invalid request body",
367
400
  issues: [{
@@ -438,11 +471,11 @@ var MastraServer = class extends MastraServer$1 {
438
471
  routePrefix: prefix,
439
472
  request: toWebRequest(req)
440
473
  };
441
- if (this.mastra.getServer()?.auth) {
474
+ if (this.mastra.getStudio?.()?.auth || this.mastra.getServer()?.auth) {
442
475
  const hasPermission = await loadHasPermission();
443
476
  if (hasPermission) {
444
477
  const userPermissions = res.locals.requestContext.get("mastra__userPermissions");
445
- const permissionError = this.checkRoutePermission(route, userPermissions, hasPermission);
478
+ const permissionError = this.checkRoutePermission(route, userPermissions, hasPermission, res.locals.requestContext);
446
479
  if (permissionError) return res.status(permissionError.status).json({
447
480
  error: permissionError.error,
448
481
  message: permissionError.message
@@ -480,12 +513,8 @@ var MastraServer = class extends MastraServer$1 {
480
513
  res.status(customResponse.status).end(Buffer.from(await customResponse.arrayBuffer()));
481
514
  return;
482
515
  }
483
- let status = 500;
484
- if (error && typeof error === "object") {
485
- if ("status" in error) status = error.status;
486
- else if ("details" in error && error.details && typeof error.details === "object" && "status" in error.details) status = error.details.status;
487
- }
488
- res.status(status).json({ error: error instanceof Error ? error.message : "Unknown error" });
516
+ const { status, body } = getHTTPErrorResponse(error);
517
+ res.status(status).json(body);
489
518
  }
490
519
  });
491
520
  }
@@ -523,11 +552,11 @@ var MastraServer = class extends MastraServer$1 {
523
552
  if (authResult.headers) for (const [key, value] of Object.entries(authResult.headers)) res.setHeader(key, value);
524
553
  if (authResult.error) return res.status(authResult.status).json({ error: authResult.error });
525
554
  }
526
- if (this.mastra.getServer()?.auth) {
555
+ if (this.mastra.getStudio?.()?.auth || this.mastra.getServer()?.auth) {
527
556
  const hasPermission = await loadHasPermission();
528
557
  if (hasPermission) {
529
558
  const userPermissions = res.locals.requestContext.get("mastra__userPermissions");
530
- const permissionError = this.checkRoutePermission(serverRoute, userPermissions, hasPermission);
559
+ const permissionError = this.checkRoutePermission(serverRoute, userPermissions, hasPermission, res.locals.requestContext);
531
560
  if (permissionError) return res.status(permissionError.status).json({
532
561
  error: permissionError.error,
533
562
  message: permissionError.message
@@ -536,9 +565,9 @@ var MastraServer = class extends MastraServer$1 {
536
565
  }
537
566
  }
538
567
  const fgaError = await checkRouteFGA(this.mastra, serverRoute, res.locals.requestContext, {
539
- ...matchedRoute?.params ?? {},
540
568
  ...req.query,
541
- ...typeof req.body === "object" && req.body !== null ? req.body : {}
569
+ ...typeof req.body === "object" && req.body !== null ? req.body : {},
570
+ ...matchedRoute?.params ?? {}
542
571
  });
543
572
  if (fgaError) return res.status(fgaError.status).json({
544
573
  error: fgaError.error,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["toWebRequest","MastraServerBase"],"sources":["../src/auth-middleware.ts","../src/index.ts"],"sourcesContent":["import type { Mastra } from '@mastra/core/mastra';\nimport { RequestContext } from '@mastra/core/request-context';\nimport { coreAuthMiddleware, isCustomRoutePublic } from '@mastra/server/auth';\nimport type { NextFunction, Request, Response } from 'express';\n\nexport interface ExpressAuthMiddlewareOptions {\n mastra: Mastra;\n requiresAuth?: boolean;\n}\n\nfunction toWebRequest(req: Request): globalThis.Request {\n const protocol = req.protocol || 'http';\n const host = req.get('host') || 'localhost';\n const url = `${protocol}://${host}${req.originalUrl || req.url}`;\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (!value) continue;\n if (Array.isArray(value)) {\n value.forEach(v => headers.append(key, v));\n } else {\n headers.set(key, value);\n }\n }\n\n return new globalThis.Request(url, {\n method: req.method,\n headers,\n });\n}\n\nexport function createAuthMiddleware({\n mastra,\n requiresAuth = true,\n}: ExpressAuthMiddlewareOptions): (req: Request, res: Response, next: NextFunction) => Promise<void> {\n return async (req: Request, res: Response, next: NextFunction) => {\n if (!requiresAuth) {\n next();\n return;\n }\n\n const authConfig = mastra.getServer()?.auth;\n if (!authConfig) {\n next();\n return;\n }\n\n const requestContext = res.locals.requestContext ?? new RequestContext();\n res.locals.requestContext = requestContext;\n res.locals.mastra = res.locals.mastra ?? mastra;\n\n const path = String(req.path || '/');\n const method = String(req.method || 'GET');\n const customRouteAuthConfig = new Map<string, boolean>(res.locals.customRouteAuthConfig ?? []);\n // Don't reclassify a custom route the app declared public (requiresAuth: false).\n if (!isCustomRoutePublic(path, method, customRouteAuthConfig)) {\n customRouteAuthConfig.set(`${method}:${path}`, true);\n }\n\n const authHeader = req.headers.authorization;\n let token: string | null = authHeader ? authHeader.replace('Bearer ', '') : null;\n if (!token && req.query.apiKey) {\n token = (req.query.apiKey as string) || null;\n }\n\n const result = await coreAuthMiddleware({\n path,\n method,\n getHeader: name => req.headers[name.toLowerCase()] as string | undefined,\n mastra,\n authConfig,\n customRouteAuthConfig,\n requestContext,\n rawRequest: toWebRequest(req),\n token,\n buildAuthorizeContext: () => toWebRequest(req),\n });\n\n for (const [key, value] of Object.entries(result.headers ?? {})) {\n if (key.toLowerCase() === 'set-cookie') {\n res.append(key, value);\n } else {\n res.setHeader(key, value);\n }\n }\n\n if (result.action === 'next') {\n next();\n return;\n }\n\n res.status(result.status).json(result.body);\n };\n}\n","import { Busboy } from '@fastify/busboy';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { InMemoryTaskStore } from '@mastra/server/a2a/store';\nimport { findMatchingCustomRoute, isProtectedCustomRoute } from '@mastra/server/auth';\nimport type { MCPHttpTransportResult, MCPSseTransportResult } from '@mastra/server/handlers/mcp';\nimport type { ParsedRequestParams, ServerRoute } from '@mastra/server/server-adapter';\nimport {\n MastraServer as MastraServerBase,\n checkRouteFGA,\n getCustomHTTPExceptionResponse,\n isSafeObjectKey,\n isZodError,\n normalizeQueryParams,\n redactStreamChunk,\n serializeStreamChunk,\n} from '@mastra/server/server-adapter';\nimport type { Application, NextFunction, Request, Response } from 'express';\nexport { createAuthMiddleware } from './auth-middleware';\nexport type { ExpressAuthMiddlewareOptions } from './auth-middleware';\n\ntype HasPermissionFn = (userPerms: string[], required: string) => boolean;\ntype AuthErrorWithHeaders = { status: number; error: string; headers?: Record<string, string> };\nlet _hasPermissionPromise: Promise<HasPermissionFn | undefined> | undefined;\nfunction loadHasPermission(): Promise<HasPermissionFn | undefined> {\n if (!_hasPermissionPromise) {\n _hasPermissionPromise = import('@mastra/core/auth/ee')\n .then(m => m.hasPermission)\n .catch(() => {\n console.error(\n '[@mastra/express] Auth features require @mastra/core >= 1.6.0. Please upgrade: npm install @mastra/core@latest',\n );\n return undefined;\n });\n }\n return _hasPermissionPromise;\n}\n\n/**\n * Convert Express request to Web API Request for cookie-based auth providers.\n */\nfunction toWebRequest(req: Request): globalThis.Request {\n const protocol = req.protocol || 'http';\n const host = req.get('host') || 'localhost';\n const url = `${protocol}://${host}${req.originalUrl || req.url}`;\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value) {\n if (Array.isArray(value)) {\n value.forEach(v => headers.append(key, v));\n } else {\n headers.set(key, value);\n }\n }\n }\n\n return new globalThis.Request(url, {\n method: req.method,\n headers,\n });\n}\n\n// Extend Express types to include Mastra context\ndeclare global {\n namespace Express {\n interface Locals {\n mastra: Mastra;\n requestContext: RequestContext;\n abortSignal: AbortSignal;\n registeredTools: ToolsInput;\n taskStore: InMemoryTaskStore;\n customRouteAuthConfig?: Map<string, boolean>;\n }\n }\n}\n\nexport class MastraServer extends MastraServerBase<Application, Request, Response> {\n createContextMiddleware(): (req: Request, res: Response, next: NextFunction) => Promise<void> {\n return async (req: Request, res: Response, next: NextFunction) => {\n // Parse request context from request body and add to context\n let bodyRequestContext: Record<string, any> | undefined;\n let paramsRequestContext: Record<string, any> | undefined;\n\n // Parse request context from request body (POST/PUT)\n if (req.method === 'POST' || req.method === 'PUT') {\n const contentType = req.headers['content-type'];\n if (contentType?.includes('application/json') && req.body) {\n if (req.body.requestContext) {\n bodyRequestContext = req.body.requestContext;\n }\n }\n }\n\n // Parse request context from query params.\n if (req.method === 'GET' || req.method === 'POST') {\n try {\n const encodedRequestContext = req.query.requestContext;\n if (typeof encodedRequestContext === 'string') {\n // Try JSON first\n try {\n paramsRequestContext = JSON.parse(encodedRequestContext);\n } catch {\n // Fallback to base64(JSON)\n try {\n const json = Buffer.from(encodedRequestContext, 'base64').toString('utf-8');\n paramsRequestContext = JSON.parse(json);\n } catch {\n // ignore if still invalid\n }\n }\n }\n } catch {\n // ignore query parsing errors\n }\n }\n\n const requestContext = this.mergeRequestContext({ paramsRequestContext, bodyRequestContext });\n this.applyRequestMetadataToContext({\n requestContext,\n getHeader: name => req.get(name),\n });\n\n // Set context in res.locals\n res.locals.requestContext = requestContext;\n res.locals.mastra = this.mastra;\n res.locals.registeredTools = this.tools || {};\n if (this.taskStore) {\n res.locals.taskStore = this.taskStore;\n }\n res.locals.customRouteAuthConfig = this.customRouteAuthConfig;\n const controller = new AbortController();\n // Use res.on('close') instead of req.on('close') because the request's 'close' event\n // fires when the request body is fully consumed (e.g., after express.json() parses it),\n // NOT when the client disconnects. The response's 'close' event fires when the underlying\n // connection is actually closed, which is the correct signal for stream cleanup.\n res.on('close', () => {\n // Only abort if the response wasn't successfully completed\n if (!res.writableFinished) {\n controller.abort();\n }\n });\n res.locals.abortSignal = controller.signal;\n next();\n };\n }\n async stream(route: ServerRoute, res: Response, result: { fullStream: ReadableStream }): Promise<void> {\n const streamFormat = route.streamFormat || 'stream';\n\n if (streamFormat === 'sse') {\n res.setHeader('Content-Type', 'text/event-stream');\n res.setHeader('Cache-Control', 'no-cache');\n res.setHeader('Connection', 'keep-alive');\n res.setHeader('X-Accel-Buffering', 'no');\n } else {\n res.setHeader('Content-Type', 'text/plain');\n }\n res.setHeader('Transfer-Encoding', 'chunked');\n res.flushHeaders();\n\n if (streamFormat === 'sse' && route.sseFlushOnConnect) {\n res.write(': connected\\n\\n');\n }\n\n const readableStream = result instanceof ReadableStream ? result : result.fullStream;\n const reader = readableStream.getReader();\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n if (value) {\n if (streamFormat === 'sse' && typeof value === 'string' && value.startsWith(':')) {\n res.write(value);\n continue;\n }\n\n // Optionally redact sensitive data (system prompts, tool definitions, API keys) before sending to the client\n const shouldRedact = this.streamOptions?.redact ?? true;\n const outputValue = shouldRedact ? redactStreamChunk(value) : value;\n // A chunk that can't be serialized must not kill the stream — skip it and keep streaming\n const serialized = serializeStreamChunk(outputValue);\n if (!serialized.ok) {\n this.mastra.getLogger()?.error('Failed to serialize stream chunk, skipping', {\n path: route.path,\n chunkType: (outputValue as { type?: string })?.type,\n error: serialized.error.message,\n });\n continue;\n }\n if (streamFormat === 'sse') {\n res.write(`data: ${serialized.json}\\n\\n`);\n } else {\n res.write(serialized.json + '\\x1E');\n }\n }\n }\n } catch (error) {\n this.mastra.getLogger()?.error('Error in stream processing', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n } finally {\n res.end();\n }\n }\n\n async getParams(route: ServerRoute, request: Request): Promise<ParsedRequestParams> {\n const urlParams = request.params as Record<string, string>;\n // Express's req.query can contain string | string[] | ParsedQs | ParsedQs[]\n const queryParams = normalizeQueryParams(request.query as Record<string, unknown>);\n let body: unknown;\n let bodyParseError: { message: string } | undefined;\n\n if (route.method === 'POST' || route.method === 'PUT' || route.method === 'PATCH' || route.method === 'DELETE') {\n const contentType = request.headers['content-type'] || '';\n\n if (contentType.includes('multipart/form-data')) {\n try {\n const maxFileSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;\n body = await this.parseMultipartFormData(request, maxFileSize);\n } catch (error) {\n this.mastra.getLogger()?.error('Failed to parse multipart form data', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n // Re-throw size limit errors, let others fall through to validation\n if (error instanceof Error && error.message.toLowerCase().includes('size')) {\n throw error;\n }\n bodyParseError = {\n message: error instanceof Error ? error.message : 'Failed to parse multipart form data',\n };\n }\n } else {\n body = request.body;\n }\n }\n\n return { urlParams, queryParams, body, bodyParseError };\n }\n\n /**\n * Parse multipart/form-data using @fastify/busboy.\n * Converts file uploads to Buffers and parses JSON field values.\n *\n * @param request - The Express request object\n * @param maxFileSize - Optional maximum file size in bytes\n */\n private parseMultipartFormData(request: Request, maxFileSize?: number): Promise<Record<string, unknown>> {\n return new Promise((resolve, reject) => {\n const result: Record<string, unknown> = {};\n\n const busboy = new Busboy({\n headers: {\n 'content-type': request.headers['content-type'] as string,\n },\n limits: maxFileSize ? { fileSize: maxFileSize } : undefined,\n });\n\n busboy.on('file', (fieldname: string, file: NodeJS.ReadableStream) => {\n const chunks: Buffer[] = [];\n let limitExceeded = false;\n\n file.on('data', (chunk: Buffer) => {\n chunks.push(chunk);\n });\n\n file.on('limit', () => {\n limitExceeded = true;\n reject(new Error(`File size limit exceeded${maxFileSize ? ` (max: ${maxFileSize} bytes)` : ''}`));\n });\n\n file.on('end', () => {\n if (!limitExceeded && isSafeObjectKey(fieldname)) {\n result[fieldname] = Buffer.concat(chunks);\n }\n });\n });\n\n busboy.on('field', (fieldname: string, value: string) => {\n if (!isSafeObjectKey(fieldname)) {\n return;\n }\n // Try to parse JSON strings (like 'options')\n try {\n result[fieldname] = JSON.parse(value);\n } catch {\n result[fieldname] = value;\n }\n });\n\n busboy.on('finish', () => {\n resolve(result);\n });\n\n busboy.on('error', (error: Error) => {\n reject(error);\n });\n\n request.pipe(busboy);\n });\n }\n\n async sendResponse(\n route: ServerRoute,\n response: Response,\n result: unknown,\n request?: Request,\n prefix?: string,\n ): Promise<void> {\n const resolvedPrefix = prefix ?? this.prefix ?? '';\n\n // Apply refresh headers from transparent session refresh (e.g. Set-Cookie after token refresh)\n if (result && typeof result === 'object' && '__refreshHeaders' in result) {\n const refreshHeaders = (result as any).__refreshHeaders as Record<string, string>;\n for (const [key, value] of Object.entries(refreshHeaders)) {\n response.setHeader(key, value);\n }\n delete (result as any).__refreshHeaders;\n }\n\n if (route.responseType === 'json') {\n response.json(result);\n } else if (route.responseType === 'stream') {\n await this.stream(route, response, result as { fullStream: ReadableStream });\n } else if (route.responseType === 'datastream-response') {\n // Handle AI SDK Response objects - pipe Response.body to Express response\n const fetchResponse = result as globalThis.Response;\n fetchResponse.headers.forEach((value, key) => response.setHeader(key, value));\n response.status(fetchResponse.status);\n if (fetchResponse.body) {\n const reader = fetchResponse.body.getReader();\n\n const onResError = (err: unknown) => {\n this.mastra.getLogger()?.error('Error writing datastream response', {\n error: err instanceof Error ? { message: err.message, stack: err.stack } : err,\n });\n void reader.cancel('response write error').catch(() => {});\n };\n response.once('error', onResError);\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n response.write(value);\n }\n } catch (error) {\n this.mastra.getLogger()?.error('Error in datastream processing', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n } finally {\n response.off('error', onResError);\n response.end();\n }\n } else {\n response.end();\n }\n } else if (route.responseType === 'mcp-http') {\n // MCP Streamable HTTP transport - request is required\n if (!request) {\n response.status(500).json({ error: 'Request object required for MCP transport' });\n return;\n }\n\n const { server, httpPath, mcpOptions: routeMcpOptions } = result as MCPHttpTransportResult;\n\n try {\n // Merge class-level mcpOptions with route-specific options (route takes precedence)\n const options = { ...this.mcpOptions, ...routeMcpOptions };\n\n await server.startHTTP({\n url: new URL(request.url, `http://${request.headers.host}`),\n httpPath: `${resolvedPrefix}${httpPath}`,\n req: request,\n res: response,\n options: Object.keys(options).length > 0 ? options : undefined,\n });\n // Response handled by startHTTP\n } catch {\n if (!response.headersSent) {\n response.status(500).json({\n jsonrpc: '2.0',\n error: { code: -32603, message: 'Internal server error' },\n id: null,\n });\n }\n }\n } else if (route.responseType === 'mcp-sse') {\n // MCP SSE transport - request is required\n if (!request) {\n response.status(500).json({ error: 'Request object required for MCP transport' });\n return;\n }\n\n const { server, ssePath, messagePath } = result as MCPSseTransportResult;\n\n try {\n await server.startSSE({\n url: new URL(request.url, `http://${request.headers.host}`),\n ssePath: `${resolvedPrefix}${ssePath}`,\n messagePath: `${resolvedPrefix}${messagePath}`,\n req: request,\n res: response,\n });\n // Response handled by startSSE\n } catch {\n if (!response.headersSent) {\n response.status(500).json({ error: 'Error handling MCP SSE request' });\n }\n }\n } else {\n response.sendStatus(500);\n }\n }\n\n async registerRoute(\n app: Application,\n route: ServerRoute,\n { prefix: prefixParam }: { prefix?: string } = {},\n ): Promise<void> {\n // Default prefix to this.prefix if not provided, or empty string\n const prefix = prefixParam ?? this.prefix ?? '';\n\n const maxSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;\n const isBodyMethod = ['POST', 'PUT', 'PATCH', 'DELETE'].includes(route.method.toUpperCase());\n\n // Create middleware array\n const middlewares: Array<(req: Request, res: Response, next: NextFunction) => void> = [];\n\n // Add body limit middleware if needed\n if (isBodyMethod && maxSize !== undefined) {\n const bodyLimitMiddleware = (req: Request, res: Response, next: NextFunction) => {\n const contentLength = req.headers['content-length'];\n // A host-level parser may run before this route middleware, so this is a\n // post-parse safeguard when Content-Length is unavailable.\n const parsedLength =\n contentLength === undefined && req.body !== undefined\n ? Buffer.byteLength(JSON.stringify(req.body), 'utf8')\n : 0;\n if ((contentLength && parseInt(contentLength, 10) > maxSize) || parsedLength > maxSize) {\n let errorResponse: unknown = { error: 'Request body too large' };\n if (route.maxBodySize === undefined && this.bodyLimitOptions) {\n try {\n errorResponse = this.bodyLimitOptions.onError(errorResponse);\n } catch {\n // Fall back to the default response.\n }\n }\n return res.status(413).json(errorResponse);\n }\n next();\n };\n middlewares.push(bodyLimitMiddleware);\n }\n\n app[route.method.toLowerCase() as keyof Application](\n `${prefix}${route.path}`,\n ...middlewares,\n async (req: Request, res: Response) => {\n // Check route-level authentication/authorization\n const authError = await this.checkRouteAuth(route, {\n path: String(req.path || '/'),\n method: String(req.method || 'GET'),\n getHeader: name => req.headers[name.toLowerCase()] as string | undefined,\n getQuery: name => req.query[name] as string | undefined,\n requestContext: res.locals.requestContext,\n request: toWebRequest(req),\n buildAuthorizeContext: () => toWebRequest(req),\n });\n\n if (authError) {\n const authResult = authError as AuthErrorWithHeaders;\n // Apply any refresh headers (e.g. Set-Cookie from transparent session refresh)\n if (authResult.headers) {\n for (const [key, value] of Object.entries(authResult.headers)) {\n res.setHeader(key, value);\n }\n }\n\n // If this is an auth error (not just a success-with-headers), return error response\n if (authResult.error) {\n return res.status(authResult.status).json({ error: authResult.error });\n }\n }\n\n const params = await this.getParams(route, req);\n\n // Return 400 Bad Request if body parsing failed (e.g., malformed multipart data)\n if (params.bodyParseError) {\n return res.status(400).json({\n error: 'Invalid request body',\n issues: [{ field: 'body', message: params.bodyParseError.message }],\n });\n }\n\n if (params.queryParams) {\n try {\n params.queryParams = await this.parseQueryParams(route, params.queryParams);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing query params', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (isZodError(error)) {\n const { status, body } = this.resolveValidationError(route, error, 'query');\n return res.status(status).json(body);\n }\n return res.status(400).json({\n error: 'Invalid query parameters',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n });\n }\n }\n\n if (params.body !== undefined || route.bodySchema) {\n try {\n params.body = await this.parseBody(route, params.body);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing body', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (isZodError(error)) {\n const { status, body } = this.resolveValidationError(route, error, 'body');\n return res.status(status).json(body);\n }\n return res.status(400).json({\n error: 'Invalid request body',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n });\n }\n }\n\n // Parse path params through pathParamSchema for type coercion (e.g., z.coerce.number())\n if (params.urlParams) {\n try {\n params.urlParams = await this.parsePathParams(route, params.urlParams);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing path params', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (isZodError(error)) {\n const { status, body } = this.resolveValidationError(route, error, 'path');\n return res.status(status).json(body);\n }\n return res.status(400).json({\n error: 'Invalid path parameters',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n });\n }\n }\n\n const handlerParams = {\n ...params.urlParams,\n ...params.queryParams,\n ...(typeof params.body === 'object' ? params.body : {}),\n requestContext: res.locals.requestContext,\n mastra: this.mastra,\n registeredTools: res.locals.registeredTools,\n taskStore: res.locals.taskStore,\n abortSignal: res.locals.abortSignal,\n routePrefix: prefix,\n request: toWebRequest(req),\n };\n\n // Check route permission requirement (EE feature)\n // Uses convention-based permission derivation: permissions are auto-derived\n // from route path/method unless explicitly set or route is public\n const authConfig = this.mastra.getServer()?.auth;\n if (authConfig) {\n const hasPermission = await loadHasPermission();\n if (hasPermission) {\n const userPermissions = res.locals.requestContext.get('mastra__userPermissions') as string[] | undefined;\n const permissionError = this.checkRoutePermission(route, userPermissions, hasPermission);\n\n if (permissionError) {\n return res.status(permissionError.status).json({\n error: permissionError.error,\n message: permissionError.message,\n });\n }\n }\n }\n\n // Check FGA authorization (EE feature)\n const fgaError = await checkRouteFGA(this.mastra, route, res.locals.requestContext, {\n ...params.urlParams,\n ...params.queryParams,\n ...(typeof params.body === 'object' ? params.body : {}),\n });\n if (fgaError) {\n return res.status(fgaError.status).json({ error: fgaError.error, message: fgaError.message });\n }\n\n try {\n const result = await route.handler(handlerParams);\n await this.sendResponse(route, res, result, req, prefix);\n } catch (error) {\n const httpStatus =\n error && typeof error === 'object' ? ((error as any).status ?? (error as any).details?.status) : undefined;\n const isClientError = typeof httpStatus === 'number' && httpStatus >= 400 && httpStatus < 500;\n if (!isClientError) {\n // 501 means an optional capability isn't provided by the configured storage or core: expected, not a server fault.\n const logLevel = httpStatus === 501 ? 'warn' : 'error';\n this.mastra.getLogger()?.[logLevel]('Error calling handler', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n path: route.path,\n method: route.method,\n });\n }\n const customResponse = getCustomHTTPExceptionResponse(error);\n if (customResponse) {\n customResponse.headers.forEach((value, name) => res.setHeader(name, value));\n res.status(customResponse.status).end(Buffer.from(await customResponse.arrayBuffer()));\n return;\n }\n\n // Check if it's an HTTPException or MastraError with a status code\n let status = 500;\n if (error && typeof error === 'object') {\n // Check for direct status property (HTTPException)\n if ('status' in error) {\n status = (error as any).status;\n }\n // Check for MastraError with status in details\n else if (\n 'details' in error &&\n error.details &&\n typeof error.details === 'object' &&\n 'status' in error.details\n ) {\n status = (error.details as any).status;\n }\n }\n res.status(status).json({ error: error instanceof Error ? error.message : 'Unknown error' });\n }\n },\n );\n }\n\n async registerCustomApiRoutes(): Promise<void> {\n const routes = await this.registerSchemaApiRoutes();\n if (!(await this.buildCustomRouteHandler(routes))) return;\n\n this.app.use(async (req: Request, res: Response, next: NextFunction) => {\n // Check if this request matches a protected custom route and run auth\n const path = String(req.path || '/');\n const method = String(req.method || 'GET');\n const matchedRoute = findMatchingCustomRoute(\n path,\n method,\n this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes,\n );\n const shouldRunCustomRouteAuth = isProtectedCustomRoute(path, method, this.customRouteAuthConfig);\n const shouldRunCustomRouteFGA = !!matchedRoute?.route.fga;\n\n if (shouldRunCustomRouteAuth || shouldRunCustomRouteFGA) {\n const serverRoute: ServerRoute = {\n method: (matchedRoute?.route.method ?? method) as any,\n path: matchedRoute?.route.path ?? path,\n responseType: 'json',\n handler: async () => {},\n requiresAuth: matchedRoute?.route.requiresAuth,\n requiresPermission: matchedRoute?.route.requiresPermission,\n fga: matchedRoute?.route.fga,\n };\n\n if (shouldRunCustomRouteAuth) {\n const authError = await this.checkRouteAuth(serverRoute, {\n path,\n method,\n getHeader: name => req.headers[name.toLowerCase()] as string | undefined,\n getQuery: name => req.query[name] as string | undefined,\n requestContext: res.locals.requestContext,\n request: toWebRequest(req),\n buildAuthorizeContext: () => toWebRequest(req),\n });\n\n if (authError) {\n const authResult = authError as AuthErrorWithHeaders;\n if (authResult.headers) {\n for (const [key, value] of Object.entries(authResult.headers)) {\n res.setHeader(key, value);\n }\n }\n if (authResult.error) {\n return res.status(authResult.status).json({ error: authResult.error });\n }\n }\n\n const authConfig = this.mastra.getServer()?.auth;\n if (authConfig) {\n const hasPermission = await loadHasPermission();\n if (hasPermission) {\n const userPermissions = res.locals.requestContext.get('mastra__userPermissions') as string[] | undefined;\n const permissionError = this.checkRoutePermission(serverRoute, userPermissions, hasPermission);\n if (permissionError) {\n return res.status(permissionError.status).json({\n error: permissionError.error,\n message: permissionError.message,\n });\n }\n }\n }\n }\n\n // Check FGA authorization (EE feature)\n const fgaError = await checkRouteFGA(this.mastra, serverRoute, res.locals.requestContext, {\n ...(matchedRoute?.params ?? {}),\n ...(req.query as Record<string, string>),\n ...(typeof req.body === 'object' && req.body !== null ? req.body : {}),\n });\n if (fgaError) {\n return res.status(fgaError.status).json({ error: fgaError.error, message: fgaError.message });\n }\n }\n\n const response = await this.handleCustomRouteRequest(\n `${req.protocol}://${req.get('host') || 'localhost'}${req.originalUrl}`,\n req.method,\n req.headers as Record<string, string | string[] | undefined>,\n req.body,\n res.locals.requestContext,\n res.locals.abortSignal,\n );\n if (!response) return next();\n await this.writeCustomRouteResponse(response, res, res.locals.abortSignal);\n });\n }\n\n registerContextMiddleware(): void {\n this.app.use(this.createContextMiddleware());\n this.app.use((req, res, next) => {\n const path = String(req.path || '/');\n const method = String(req.method || 'GET');\n res.on('finish', () => {\n this.warnIfUnregisteredChannelWebhook(path, method, res.statusCode);\n });\n next();\n });\n }\n\n registerAuthMiddleware(): void {\n // Auth is handled per-route in registerRoute() and registerCustomApiRoutes()\n // No global middleware needed\n }\n\n registerHttpLoggingMiddleware(): void {\n if (!this.httpLoggingConfig?.enabled) {\n return;\n }\n\n this.app.use((req, res, next) => {\n if (!this.shouldLogRequest(req.path)) {\n return next();\n }\n\n const start = Date.now();\n const method = req.method;\n const path = req.path;\n\n res.on('finish', () => {\n const duration = Date.now() - start;\n const status = res.statusCode;\n const level = this.httpLoggingConfig?.level || 'info';\n\n const logData: Record<string, any> = {\n method,\n path,\n status,\n duration: `${duration}ms`,\n };\n\n if (this.httpLoggingConfig?.includeQueryParams) {\n logData.query = req.query;\n }\n\n if (this.httpLoggingConfig?.includeHeaders) {\n const headers = { ...req.headers };\n const redactHeaders = this.httpLoggingConfig.redactHeaders || [];\n redactHeaders.forEach(h => {\n const key = h.toLowerCase();\n if (headers[key] !== undefined) {\n headers[key] = '[REDACTED]';\n }\n });\n logData.headers = headers;\n }\n\n this.logger[level](`${method} ${path} ${status} ${duration}ms`, logData);\n });\n\n next();\n });\n }\n}\n"],"mappings":";;;;;AAUA,SAASA,eAAa,KAAkC;CAGtD,MAAM,MAAM,GAFK,IAAI,YAAY,OAET,KADX,IAAI,IAAI,MAAM,KAAK,cACI,IAAI,eAAe,IAAI;CAE3D,MAAM,UAAU,IAAI,QAAQ;CAC5B,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,IAAI,OAAO,GAAG;EACtD,IAAI,CAAC,OAAO;EACZ,IAAI,MAAM,QAAQ,KAAK,GACrB,MAAM,SAAQ,MAAK,QAAQ,OAAO,KAAK,CAAC,CAAC;OAEzC,QAAQ,IAAI,KAAK,KAAK;CAE1B;CAEA,OAAO,IAAI,WAAW,QAAQ,KAAK;EACjC,QAAQ,IAAI;EACZ;CACF,CAAC;AACH;AAEA,SAAgB,qBAAqB,EACnC,QACA,eAAe,QACoF;CACnG,OAAO,OAAO,KAAc,KAAe,SAAuB;EAChE,IAAI,CAAC,cAAc;GACjB,KAAK;GACL;EACF;EAEA,MAAM,aAAa,OAAO,UAAU,CAAC,EAAE;EACvC,IAAI,CAAC,YAAY;GACf,KAAK;GACL;EACF;EAEA,MAAM,iBAAiB,IAAI,OAAO,kBAAkB,I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,SAAS,IAAI;IACnB,MAAM,QAAQ,KAAK,mBAAmB,SAAS;IAE/C,MAAM,UAA+B;KACnC;KACA;KACA;KACA,UAAU,GAAG,SAAS;IACxB;IAEA,IAAI,KAAK,mBAAmB,oBAC1B,QAAQ,QAAQ,IAAI;IAGtB,IAAI,KAAK,mBAAmB,gBAAgB;KAC1C,MAAM,UAAU,EAAE,GAAG,IAAI,QAAQ;KAEjC,CADsB,KAAK,kBAAkB,iBAAiB,CAAC,EAAA,CACjD,SAAQ,MAAK;MACzB,MAAM,MAAM,EAAE,YAAY;MAC1B,IAAI,QAAQ,SAAS,KAAA,GACnB,QAAQ,OAAO;KAEnB,CAAC;KACD,QAAQ,UAAU;IACpB;IAEA,KAAK,OAAO,MAAM,CAAC,GAAG,OAAO,GAAG,KAAK,GAAG,OAAO,GAAG,SAAS,KAAK,OAAO;GACzE,CAAC;GAED,KAAK;EACP,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"index.js","names":["toWebRequest","MastraServerBase"],"sources":["../src/auth-middleware.ts","../src/index.ts"],"sourcesContent":["import type { Mastra } from '@mastra/core/mastra';\nimport { RequestContext } from '@mastra/core/request-context';\nimport { coreAuthMiddleware, isCustomRoutePublic } from '@mastra/server/auth';\nimport type { NextFunction, Request, Response } from 'express';\n\nexport interface ExpressAuthMiddlewareOptions {\n mastra: Mastra;\n requiresAuth?: boolean;\n}\n\nfunction toWebRequest(req: Request): globalThis.Request {\n const protocol = req.protocol || 'http';\n const host = req.get('host') || 'localhost';\n const url = `${protocol}://${host}${req.originalUrl || req.url}`;\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (!value) continue;\n if (Array.isArray(value)) {\n value.forEach(v => headers.append(key, v));\n } else {\n headers.set(key, value);\n }\n }\n\n return new globalThis.Request(url, {\n method: req.method,\n headers,\n });\n}\n\nexport function createAuthMiddleware({\n mastra,\n requiresAuth = true,\n}: ExpressAuthMiddlewareOptions): (req: Request, res: Response, next: NextFunction) => Promise<void> {\n return async (req: Request, res: Response, next: NextFunction) => {\n if (!requiresAuth) {\n next();\n return;\n }\n\n const authConfig = mastra.getServer()?.auth;\n if (!authConfig) {\n next();\n return;\n }\n\n const requestContext = res.locals.requestContext ?? new RequestContext();\n res.locals.requestContext = requestContext;\n res.locals.mastra = res.locals.mastra ?? mastra;\n\n const path = String(req.path || '/');\n const method = String(req.method || 'GET');\n const customRouteAuthConfig = new Map<string, boolean>(res.locals.customRouteAuthConfig ?? []);\n // Don't reclassify a custom route the app declared public (requiresAuth: false).\n if (!isCustomRoutePublic(path, method, customRouteAuthConfig)) {\n customRouteAuthConfig.set(`${method}:${path}`, true);\n }\n\n const authHeader = req.headers.authorization;\n let token: string | null = authHeader ? authHeader.replace('Bearer ', '') : null;\n if (!token && req.query.apiKey) {\n token = (req.query.apiKey as string) || null;\n }\n\n const result = await coreAuthMiddleware({\n path,\n method,\n getHeader: name => req.headers[name.toLowerCase()] as string | undefined,\n mastra,\n authConfig,\n customRouteAuthConfig,\n requestContext,\n rawRequest: toWebRequest(req),\n token,\n buildAuthorizeContext: () => toWebRequest(req),\n });\n\n for (const [key, value] of Object.entries(result.headers ?? {})) {\n if (key.toLowerCase() === 'set-cookie') {\n res.append(key, value);\n } else {\n res.setHeader(key, value);\n }\n }\n\n if (result.action === 'next') {\n next();\n return;\n }\n\n res.status(result.status).json(result.body);\n };\n}\n","import { Busboy } from '@fastify/busboy';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { InMemoryTaskStore } from '@mastra/server/a2a/store';\nimport { findMatchingCustomRoute, isProtectedCustomRoute } from '@mastra/server/auth';\nimport type { MCPHttpTransportResult, MCPSseTransportResult } from '@mastra/server/handlers/mcp';\nimport type { ParsedRequestParams, ServerRoute } from '@mastra/server/server-adapter';\nimport {\n MastraServer as MastraServerBase,\n checkRouteFGA,\n getCustomHTTPExceptionResponse,\n getHTTPErrorResponse,\n isSafeObjectKey,\n isZodError,\n normalizeQueryParams,\n redactStreamChunk,\n serializeStreamChunk,\n} from '@mastra/server/server-adapter';\nimport type { Application, NextFunction, Request, Response } from 'express';\nexport { createAuthMiddleware } from './auth-middleware';\nexport type { ExpressAuthMiddlewareOptions } from './auth-middleware';\n\nclass BodyLimitExceededError extends Error {\n constructor(limit: number) {\n super(`Request body size limit exceeded (max: ${limit} bytes)`);\n }\n}\n\ntype HasPermissionFn = (userPerms: string[], required: string) => boolean;\ntype AuthErrorWithHeaders = { status: number; error: string; headers?: Record<string, string> };\nlet _hasPermissionPromise: Promise<HasPermissionFn | undefined> | undefined;\nfunction loadHasPermission(): Promise<HasPermissionFn | undefined> {\n if (!_hasPermissionPromise) {\n _hasPermissionPromise = import('@mastra/core/auth/ee')\n .then(m => m.hasPermission)\n .catch(() => {\n console.error(\n '[@mastra/express] Auth features require @mastra/core >= 1.6.0. Please upgrade: npm install @mastra/core@latest',\n );\n return undefined;\n });\n }\n return _hasPermissionPromise;\n}\n\n/**\n * Convert Express request to Web API Request for cookie-based auth providers.\n */\nfunction toWebRequest(req: Request): globalThis.Request {\n const protocol = req.protocol || 'http';\n const host = req.get('host') || 'localhost';\n const url = `${protocol}://${host}${req.originalUrl || req.url}`;\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value) {\n if (Array.isArray(value)) {\n value.forEach(v => headers.append(key, v));\n } else {\n headers.set(key, value);\n }\n }\n }\n\n return new globalThis.Request(url, {\n method: req.method,\n headers,\n });\n}\n\n// Extend Express types to include Mastra context\ndeclare global {\n namespace Express {\n interface Locals {\n mastra: Mastra;\n requestContext: RequestContext;\n abortSignal: AbortSignal;\n registeredTools: ToolsInput;\n taskStore: InMemoryTaskStore;\n customRouteAuthConfig?: Map<string, boolean>;\n }\n }\n}\n\nexport class MastraServer extends MastraServerBase<Application, Request, Response> {\n createContextMiddleware(): (req: Request, res: Response, next: NextFunction) => Promise<void> {\n return async (req: Request, res: Response, next: NextFunction) => {\n // Parse request context from request body and add to context\n let bodyRequestContext: Record<string, any> | undefined;\n let paramsRequestContext: Record<string, any> | undefined;\n\n // Parse request context from request body (POST/PUT)\n if (req.method === 'POST' || req.method === 'PUT') {\n const contentType = req.headers['content-type'];\n if (contentType?.includes('application/json') && req.body) {\n if (req.body.requestContext) {\n bodyRequestContext = req.body.requestContext;\n }\n }\n }\n\n // Parse request context from query params.\n if (req.method === 'GET' || req.method === 'POST') {\n try {\n const encodedRequestContext = req.query.requestContext;\n if (typeof encodedRequestContext === 'string') {\n // Try JSON first\n try {\n paramsRequestContext = JSON.parse(encodedRequestContext);\n } catch {\n // Fallback to base64(JSON)\n try {\n const json = Buffer.from(encodedRequestContext, 'base64').toString('utf-8');\n paramsRequestContext = JSON.parse(json);\n } catch {\n // ignore if still invalid\n }\n }\n }\n } catch {\n // ignore query parsing errors\n }\n }\n\n const requestContext = this.mergeRequestContext({ paramsRequestContext, bodyRequestContext });\n this.applyRequestMetadataToContext({\n requestContext,\n getHeader: name => req.get(name),\n });\n\n // Set context in res.locals\n res.locals.requestContext = requestContext;\n res.locals.mastra = this.mastra;\n res.locals.registeredTools = this.tools || {};\n if (this.taskStore) {\n res.locals.taskStore = this.taskStore;\n }\n res.locals.customRouteAuthConfig = this.customRouteAuthConfig;\n const controller = new AbortController();\n // Use res.on('close') instead of req.on('close') because the request's 'close' event\n // fires when the request body is fully consumed (e.g., after express.json() parses it),\n // NOT when the client disconnects. The response's 'close' event fires when the underlying\n // connection is actually closed, which is the correct signal for stream cleanup.\n res.on('close', () => {\n // Only abort if the response wasn't successfully completed\n if (!res.writableFinished) {\n controller.abort();\n }\n });\n res.locals.abortSignal = controller.signal;\n next();\n };\n }\n async stream(route: ServerRoute, res: Response, result: { fullStream: ReadableStream }): Promise<void> {\n const streamFormat = route.streamFormat || 'stream';\n\n if (streamFormat === 'sse') {\n res.setHeader('Content-Type', 'text/event-stream');\n res.setHeader('Cache-Control', 'no-cache');\n res.setHeader('Connection', 'keep-alive');\n res.setHeader('X-Accel-Buffering', 'no');\n } else {\n res.setHeader('Content-Type', 'text/plain');\n }\n res.setHeader('Transfer-Encoding', 'chunked');\n res.flushHeaders();\n\n if (streamFormat === 'sse' && route.sseFlushOnConnect) {\n res.write(': connected\\n\\n');\n }\n\n const readableStream = result instanceof ReadableStream ? result : result.fullStream;\n const reader = readableStream.getReader();\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n if (value) {\n if (streamFormat === 'sse' && typeof value === 'string' && value.startsWith(':')) {\n res.write(value);\n continue;\n }\n\n // Optionally redact sensitive data (system prompts, tool definitions, API keys) before sending to the client\n const shouldRedact = this.streamOptions?.redact ?? true;\n const outputValue = shouldRedact ? redactStreamChunk(value) : value;\n // A chunk that can't be serialized must not kill the stream — skip it and keep streaming\n const serialized = serializeStreamChunk(outputValue);\n if (!serialized.ok) {\n this.mastra.getLogger()?.error('Failed to serialize stream chunk, skipping', {\n path: route.path,\n chunkType: (outputValue as { type?: string })?.type,\n error: serialized.error.message,\n });\n continue;\n }\n if (streamFormat === 'sse') {\n res.write(`data: ${serialized.json}\\n\\n`);\n } else {\n res.write(serialized.json + '\\x1E');\n }\n }\n }\n } catch (error) {\n this.mastra.getLogger()?.error('Error in stream processing', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n } finally {\n res.end();\n }\n }\n\n async getParams(route: ServerRoute, request: Request): Promise<ParsedRequestParams> {\n const urlParams = request.params as Record<string, string>;\n // Express's req.query can contain string | string[] | ParsedQs | ParsedQs[]\n const queryParams = normalizeQueryParams(request.query as Record<string, unknown>);\n let body: unknown;\n let bodyParseError: { message: string } | undefined;\n\n if (route.method === 'POST' || route.method === 'PUT' || route.method === 'PATCH' || route.method === 'DELETE') {\n const contentType = request.headers['content-type'] || '';\n\n if (contentType.includes('multipart/form-data')) {\n try {\n const maxFileSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;\n body = await this.parseMultipartFormData(request, maxFileSize);\n } catch (error) {\n if (error instanceof BodyLimitExceededError) {\n throw error;\n }\n this.mastra.getLogger()?.error('Failed to parse multipart form data', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n bodyParseError = {\n message: error instanceof Error ? error.message : 'Failed to parse multipart form data',\n };\n }\n } else {\n body = request.body;\n }\n }\n\n return { urlParams, queryParams, body, bodyParseError };\n }\n\n /**\n * Parse multipart/form-data using @fastify/busboy.\n * Converts file uploads to Buffers and parses JSON field values.\n *\n * @param request - The Express request object\n * @param maxFileSize - Optional maximum file size in bytes\n */\n private parseMultipartFormData(request: Request, maxFileSize?: number): Promise<Record<string, unknown>> {\n return new Promise((resolve, reject) => {\n const result: Record<string, unknown> = {};\n\n const busboy = new Busboy({\n headers: {\n 'content-type': request.headers['content-type'] as string,\n },\n limits: maxFileSize ? { fileSize: maxFileSize, fieldSize: maxFileSize } : undefined,\n });\n\n // Content-Length is checked up front, but chunked bodies have none, so cap\n // the total bytes pulled from the request while streaming into busboy.\n if (maxFileSize !== undefined) {\n let received = 0;\n const onData = (chunk: Buffer) => {\n received += chunk.length;\n if (received > maxFileSize) {\n request.off('data', onData);\n request.unpipe(busboy);\n request.pause();\n reject(new BodyLimitExceededError(maxFileSize));\n }\n };\n request.on('data', onData);\n }\n\n busboy.on('file', (fieldname: string, file: NodeJS.ReadableStream) => {\n const chunks: Buffer[] = [];\n let limitExceeded = false;\n\n file.on('data', (chunk: Buffer) => {\n chunks.push(chunk);\n });\n\n file.on('limit', () => {\n limitExceeded = true;\n reject(new BodyLimitExceededError(maxFileSize!));\n });\n\n file.on('end', () => {\n if (!limitExceeded && isSafeObjectKey(fieldname)) {\n result[fieldname] = Buffer.concat(chunks);\n }\n });\n });\n\n busboy.on('field', (fieldname: string, value: string) => {\n if (!isSafeObjectKey(fieldname)) {\n return;\n }\n // Try to parse JSON strings (like 'options')\n try {\n result[fieldname] = JSON.parse(value);\n } catch {\n result[fieldname] = value;\n }\n });\n\n busboy.on('finish', () => {\n resolve(result);\n });\n\n busboy.on('error', (error: Error) => {\n reject(error);\n });\n\n request.pipe(busboy);\n });\n }\n\n async sendResponse(\n route: ServerRoute,\n response: Response,\n result: unknown,\n request?: Request,\n prefix?: string,\n ): Promise<void> {\n const resolvedPrefix = prefix ?? this.prefix ?? '';\n\n // Apply refresh headers from transparent session refresh (e.g. Set-Cookie after token refresh)\n if (result && typeof result === 'object' && '__refreshHeaders' in result) {\n const refreshHeaders = (result as any).__refreshHeaders as Record<string, string>;\n for (const [key, value] of Object.entries(refreshHeaders)) {\n response.setHeader(key, value);\n }\n delete (result as any).__refreshHeaders;\n }\n\n if (route.responseType === 'json') {\n response.json(result);\n } else if (route.responseType === 'stream') {\n await this.stream(route, response, result as { fullStream: ReadableStream });\n } else if (route.responseType === 'datastream-response') {\n // Handle AI SDK Response objects - pipe Response.body to Express response\n const fetchResponse = result as globalThis.Response;\n fetchResponse.headers.forEach((value, key) => response.setHeader(key, value));\n response.status(fetchResponse.status);\n if (fetchResponse.body) {\n const reader = fetchResponse.body.getReader();\n\n const onResError = (err: unknown) => {\n this.mastra.getLogger()?.error('Error writing datastream response', {\n error: err instanceof Error ? { message: err.message, stack: err.stack } : err,\n });\n void reader.cancel('response write error').catch(() => {});\n };\n response.once('error', onResError);\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n response.write(value);\n }\n } catch (error) {\n this.mastra.getLogger()?.error('Error in datastream processing', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n } finally {\n response.off('error', onResError);\n response.end();\n }\n } else {\n response.end();\n }\n } else if (route.responseType === 'mcp-http') {\n // MCP Streamable HTTP transport - request is required\n if (!request) {\n response.status(500).json({ error: 'Request object required for MCP transport' });\n return;\n }\n\n const { server, httpPath, mcpOptions: routeMcpOptions } = result as MCPHttpTransportResult;\n\n try {\n // Merge class-level mcpOptions with route-specific options (route takes precedence)\n const options = { ...this.mcpOptions, ...routeMcpOptions };\n\n await server.startHTTP({\n url: new URL(request.url, `http://${request.headers.host}`),\n httpPath: `${resolvedPrefix}${httpPath}`,\n req: request,\n res: response,\n options: Object.keys(options).length > 0 ? options : undefined,\n });\n // Response handled by startHTTP\n } catch {\n if (!response.headersSent) {\n response.status(500).json({\n jsonrpc: '2.0',\n error: { code: -32603, message: 'Internal server error' },\n id: null,\n });\n }\n }\n } else if (route.responseType === 'mcp-sse') {\n // MCP SSE transport - request is required\n if (!request) {\n response.status(500).json({ error: 'Request object required for MCP transport' });\n return;\n }\n\n const { server, ssePath, messagePath } = result as MCPSseTransportResult;\n\n try {\n await server.startSSE({\n url: new URL(request.url, `http://${request.headers.host}`),\n ssePath: `${resolvedPrefix}${ssePath}`,\n messagePath: `${resolvedPrefix}${messagePath}`,\n req: request,\n res: response,\n });\n // Response handled by startSSE\n } catch {\n if (!response.headersSent) {\n response.status(500).json({ error: 'Error handling MCP SSE request' });\n }\n }\n } else {\n response.sendStatus(500);\n }\n }\n\n async registerRoute(\n app: Application,\n route: ServerRoute,\n { prefix: prefixParam }: { prefix?: string } = {},\n ): Promise<void> {\n // Default prefix to this.prefix if not provided, or empty string\n const prefix = prefixParam ?? this.prefix ?? '';\n\n const maxSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;\n const isBodyMethod = ['POST', 'PUT', 'PATCH', 'DELETE'].includes(route.method.toUpperCase());\n\n // Create middleware array\n const middlewares: Array<(req: Request, res: Response, next: NextFunction) => void> = [];\n\n const sendBodyTooLarge = (res: Response) => {\n let errorResponse: unknown = { error: 'Request body too large' };\n if (route.maxBodySize === undefined && this.bodyLimitOptions) {\n try {\n errorResponse = this.bodyLimitOptions.onError(errorResponse);\n } catch {\n // Fall back to the default response.\n }\n }\n // Close the connection instead of draining the rest of the oversized body.\n res.setHeader('Connection', 'close');\n return res.status(413).json(errorResponse);\n };\n\n // Add body limit middleware if needed\n if (isBodyMethod && maxSize !== undefined) {\n const bodyLimitMiddleware = (req: Request, res: Response, next: NextFunction) => {\n const contentLength = req.headers['content-length'];\n // A host-level parser may run before this route middleware, so this is a\n // post-parse safeguard when Content-Length is unavailable.\n const parsedLength =\n contentLength === undefined && req.body !== undefined\n ? Buffer.byteLength(JSON.stringify(req.body), 'utf8')\n : 0;\n if ((contentLength && parseInt(contentLength, 10) > maxSize) || parsedLength > maxSize) {\n return sendBodyTooLarge(res);\n }\n next();\n };\n middlewares.push(bodyLimitMiddleware);\n }\n\n app[route.method.toLowerCase() as keyof Application](\n `${prefix}${route.path}`,\n ...middlewares,\n async (req: Request, res: Response) => {\n // Check route-level authentication/authorization\n const authError = await this.checkRouteAuth(route, {\n path: String(req.path || '/'),\n method: String(req.method || 'GET'),\n getHeader: name => req.headers[name.toLowerCase()] as string | undefined,\n getQuery: name => req.query[name] as string | undefined,\n requestContext: res.locals.requestContext,\n request: toWebRequest(req),\n buildAuthorizeContext: () => toWebRequest(req),\n });\n\n if (authError) {\n const authResult = authError as AuthErrorWithHeaders;\n // Apply any refresh headers (e.g. Set-Cookie from transparent session refresh)\n if (authResult.headers) {\n for (const [key, value] of Object.entries(authResult.headers)) {\n res.setHeader(key, value);\n }\n }\n\n // If this is an auth error (not just a success-with-headers), return error response\n if (authResult.error) {\n return res.status(authResult.status).json({ error: authResult.error });\n }\n }\n\n let params: ParsedRequestParams;\n try {\n params = await this.getParams(route, req);\n } catch (error) {\n if (error instanceof BodyLimitExceededError) {\n return sendBodyTooLarge(res);\n }\n throw error;\n }\n\n // Return 400 Bad Request if body parsing failed (e.g., malformed multipart data)\n if (params.bodyParseError) {\n return res.status(400).json({\n error: 'Invalid request body',\n issues: [{ field: 'body', message: params.bodyParseError.message }],\n });\n }\n\n if (params.queryParams) {\n try {\n params.queryParams = await this.parseQueryParams(route, params.queryParams);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing query params', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (isZodError(error)) {\n const { status, body } = this.resolveValidationError(route, error, 'query');\n return res.status(status).json(body);\n }\n return res.status(400).json({\n error: 'Invalid query parameters',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n });\n }\n }\n\n if (params.body !== undefined || route.bodySchema) {\n try {\n params.body = await this.parseBody(route, params.body);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing body', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (isZodError(error)) {\n const { status, body } = this.resolveValidationError(route, error, 'body');\n return res.status(status).json(body);\n }\n return res.status(400).json({\n error: 'Invalid request body',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n });\n }\n }\n\n // Parse path params through pathParamSchema for type coercion (e.g., z.coerce.number())\n if (params.urlParams) {\n try {\n params.urlParams = await this.parsePathParams(route, params.urlParams);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing path params', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (isZodError(error)) {\n const { status, body } = this.resolveValidationError(route, error, 'path');\n return res.status(status).json(body);\n }\n return res.status(400).json({\n error: 'Invalid path parameters',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n });\n }\n }\n\n const handlerParams = {\n ...params.urlParams,\n ...params.queryParams,\n ...(typeof params.body === 'object' ? params.body : {}),\n requestContext: res.locals.requestContext,\n mastra: this.mastra,\n registeredTools: res.locals.registeredTools,\n taskStore: res.locals.taskStore,\n abortSignal: res.locals.abortSignal,\n routePrefix: prefix,\n request: toWebRequest(req),\n };\n\n // Check route permission requirement (EE feature)\n // Uses convention-based permission derivation: permissions are auto-derived\n // from route path/method unless explicitly set or route is public\n // Check if any auth is configured (studio or server) for RBAC\n const hasAuth = this.mastra.getStudio?.()?.auth || this.mastra.getServer()?.auth;\n if (hasAuth) {\n const hasPermission = await loadHasPermission();\n if (hasPermission) {\n const userPermissions = res.locals.requestContext.get('mastra__userPermissions') as string[] | undefined;\n const permissionError = this.checkRoutePermission(\n route,\n userPermissions,\n hasPermission,\n res.locals.requestContext,\n );\n\n if (permissionError) {\n return res.status(permissionError.status).json({\n error: permissionError.error,\n message: permissionError.message,\n });\n }\n }\n }\n\n // Check FGA authorization (EE feature)\n const fgaError = await checkRouteFGA(this.mastra, route, res.locals.requestContext, {\n ...params.urlParams,\n ...params.queryParams,\n ...(typeof params.body === 'object' ? params.body : {}),\n });\n if (fgaError) {\n return res.status(fgaError.status).json({ error: fgaError.error, message: fgaError.message });\n }\n\n try {\n const result = await route.handler(handlerParams);\n await this.sendResponse(route, res, result, req, prefix);\n } catch (error) {\n const httpStatus =\n error && typeof error === 'object' ? ((error as any).status ?? (error as any).details?.status) : undefined;\n const isClientError = typeof httpStatus === 'number' && httpStatus >= 400 && httpStatus < 500;\n if (!isClientError) {\n // 501 means an optional capability isn't provided by the configured storage or core: expected, not a server fault.\n const logLevel = httpStatus === 501 ? 'warn' : 'error';\n this.mastra.getLogger()?.[logLevel]('Error calling handler', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n path: route.path,\n method: route.method,\n });\n }\n const customResponse = getCustomHTTPExceptionResponse(error);\n if (customResponse) {\n customResponse.headers.forEach((value, name) => res.setHeader(name, value));\n res.status(customResponse.status).end(Buffer.from(await customResponse.arrayBuffer()));\n return;\n }\n\n const { status, body } = getHTTPErrorResponse(error);\n res.status(status).json(body);\n }\n },\n );\n }\n\n async registerCustomApiRoutes(): Promise<void> {\n const routes = await this.registerSchemaApiRoutes();\n if (!(await this.buildCustomRouteHandler(routes))) return;\n\n this.app.use(async (req: Request, res: Response, next: NextFunction) => {\n // Check if this request matches a protected custom route and run auth\n const path = String(req.path || '/');\n const method = String(req.method || 'GET');\n const matchedRoute = findMatchingCustomRoute(\n path,\n method,\n this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes,\n );\n const shouldRunCustomRouteAuth = isProtectedCustomRoute(path, method, this.customRouteAuthConfig);\n const shouldRunCustomRouteFGA = !!matchedRoute?.route.fga;\n\n if (shouldRunCustomRouteAuth || shouldRunCustomRouteFGA) {\n const serverRoute: ServerRoute = {\n method: (matchedRoute?.route.method ?? method) as any,\n path: matchedRoute?.route.path ?? path,\n responseType: 'json',\n handler: async () => {},\n requiresAuth: matchedRoute?.route.requiresAuth,\n requiresPermission: matchedRoute?.route.requiresPermission,\n fga: matchedRoute?.route.fga,\n };\n\n if (shouldRunCustomRouteAuth) {\n const authError = await this.checkRouteAuth(serverRoute, {\n path,\n method,\n getHeader: name => req.headers[name.toLowerCase()] as string | undefined,\n getQuery: name => req.query[name] as string | undefined,\n requestContext: res.locals.requestContext,\n request: toWebRequest(req),\n buildAuthorizeContext: () => toWebRequest(req),\n });\n\n if (authError) {\n const authResult = authError as AuthErrorWithHeaders;\n if (authResult.headers) {\n for (const [key, value] of Object.entries(authResult.headers)) {\n res.setHeader(key, value);\n }\n }\n if (authResult.error) {\n return res.status(authResult.status).json({ error: authResult.error });\n }\n }\n\n // Check if any auth is configured (studio or server) for RBAC\n const hasAuth = this.mastra.getStudio?.()?.auth || this.mastra.getServer()?.auth;\n if (hasAuth) {\n const hasPermission = await loadHasPermission();\n if (hasPermission) {\n const userPermissions = res.locals.requestContext.get('mastra__userPermissions') as string[] | undefined;\n const permissionError = this.checkRoutePermission(\n serverRoute,\n userPermissions,\n hasPermission,\n res.locals.requestContext,\n );\n if (permissionError) {\n return res.status(permissionError.status).json({\n error: permissionError.error,\n message: permissionError.message,\n });\n }\n }\n }\n }\n\n // Check FGA authorization (EE feature)\n // Path params last: the custom handler reads them from the URL, so query/body\n // values must not be able to change which resource FGA checks.\n const fgaError = await checkRouteFGA(this.mastra, serverRoute, res.locals.requestContext, {\n ...(req.query as Record<string, string>),\n ...(typeof req.body === 'object' && req.body !== null ? req.body : {}),\n ...(matchedRoute?.params ?? {}),\n });\n if (fgaError) {\n return res.status(fgaError.status).json({ error: fgaError.error, message: fgaError.message });\n }\n }\n\n const response = await this.handleCustomRouteRequest(\n `${req.protocol}://${req.get('host') || 'localhost'}${req.originalUrl}`,\n req.method,\n req.headers as Record<string, string | string[] | undefined>,\n req.body,\n res.locals.requestContext,\n res.locals.abortSignal,\n );\n if (!response) return next();\n await this.writeCustomRouteResponse(response, res, res.locals.abortSignal);\n });\n }\n\n registerContextMiddleware(): void {\n this.app.use(this.createContextMiddleware());\n this.app.use((req, res, next) => {\n const path = String(req.path || '/');\n const method = String(req.method || 'GET');\n res.on('finish', () => {\n this.warnIfUnregisteredChannelWebhook(path, method, res.statusCode);\n });\n next();\n });\n }\n\n registerAuthMiddleware(): void {\n // Auth is handled per-route in registerRoute() and registerCustomApiRoutes()\n // No global middleware needed\n }\n\n registerHttpLoggingMiddleware(): void {\n if (!this.httpLoggingConfig?.enabled) {\n return;\n }\n\n this.app.use((req, res, next) => {\n if (!this.shouldLogRequest(req.path)) {\n return next();\n }\n\n const start = Date.now();\n const method = req.method;\n const path = req.path;\n\n res.on('finish', () => {\n const duration = Date.now() - start;\n const status = res.statusCode;\n const level = this.httpLoggingConfig?.level || 'info';\n\n const logData: Record<string, any> = {\n method,\n path,\n status,\n duration: `${duration}ms`,\n };\n\n if (this.httpLoggingConfig?.includeQueryParams) {\n logData.query = req.query;\n }\n\n if (this.httpLoggingConfig?.includeHeaders) {\n const headers = { ...req.headers };\n const redactHeaders = this.httpLoggingConfig.redactHeaders || [];\n redactHeaders.forEach(h => {\n const key = h.toLowerCase();\n if (headers[key] !== undefined) {\n headers[key] = '[REDACTED]';\n }\n });\n logData.headers = headers;\n }\n\n this.logger[level](`${method} ${path} ${status} ${duration}ms`, logData);\n });\n\n next();\n });\n }\n}\n"],"mappings":";;;;;AAUA,SAASA,eAAa,KAAkC;CAGtD,MAAM,MAAM,GAFK,IAAI,YAAY,OAET,KADX,IAAI,IAAI,MAAM,KAAK,cACI,IAAI,eAAe,IAAI;CAE3D,MAAM,UAAU,IAAI,QAAQ;CAC5B,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,IAAI,OAAO,GAAG;EACtD,IAAI,CAAC,OAAO;EACZ,IAAI,MAAM,QAAQ,KAAK,GACrB,MAAM,SAAQ,MAAK,QAAQ,OAAO,K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AAC;KACD,QAAQ,UAAU;IACpB;IAEA,KAAK,OAAO,MAAM,CAAC,GAAG,OAAO,GAAG,KAAK,GAAG,OAAO,GAAG,SAAS,KAAK,OAAO;GACzE,CAAC;GAED,KAAK;EACP,CAAC;CACH;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/express",
3
- "version": "1.5.23-alpha.9",
3
+ "version": "1.5.24-alpha.0",
4
4
  "description": "Mastra Express adapter for the server",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -21,31 +21,31 @@
21
21
  "license": "Apache-2.0",
22
22
  "dependencies": {
23
23
  "@fastify/busboy": "^3.2.2",
24
- "@mastra/server": "1.79.0-alpha.9"
24
+ "@mastra/server": "1.80.0-alpha.0"
25
25
  },
26
26
  "devDependencies": {
27
27
  "@ai-sdk/openai": "^2.0.135",
28
28
  "@types/cors": "^2.8.19",
29
29
  "@types/express": "^5.0.6",
30
- "@types/node": "22.20.1",
30
+ "@types/node": "22.20.5",
31
31
  "@types/swagger-ui-express": "^4.1.8",
32
32
  "cors": "^2.8.6",
33
33
  "express": "^5.2.1",
34
34
  "swagger-ui-express": "^5.0.1",
35
- "tsdown": "0.22.9",
35
+ "tsdown": "0.23.1",
36
36
  "typescript": "^7.0.2",
37
37
  "vitest": "4.1.11",
38
38
  "zod": "^4.6.7",
39
- "@internal/lint": "0.0.144",
40
- "@mastra/server-adapters-test-suite": "0.1.3-alpha.2",
41
- "@internal/storage-test-utils": "0.0.140",
42
- "@mastra/ai-sdk": "1.11.2-alpha.0",
43
- "@mastra/evals": "1.10.8-alpha.2",
44
- "@mastra/memory": "1.39.0-alpha.6",
45
- "@mastra/core": "1.79.0-alpha.9",
46
- "@internal/types-builder": "0.0.119",
47
- "@mastra/observability": "1.21.0-alpha.2",
48
- "@mastra/libsql": "1.27.0-alpha.3"
39
+ "@internal/lint": "0.0.145",
40
+ "@mastra/server-adapters-test-suite": "0.1.4-alpha.0",
41
+ "@internal/storage-test-utils": "0.0.141",
42
+ "@internal/types-builder": "0.0.120",
43
+ "@mastra/core": "1.80.0-alpha.0",
44
+ "@mastra/libsql": "1.27.0",
45
+ "@mastra/ai-sdk": "1.11.2",
46
+ "@mastra/evals": "1.10.8",
47
+ "@mastra/memory": "1.39.1-alpha.0",
48
+ "@mastra/observability": "1.21.1-alpha.0"
49
49
  },
50
50
  "peerDependencies": {
51
51
  "@mastra/core": ">=1.58.0-0 <2.0.0-0",