@mastra/express 1.5.27-alpha.0 → 1.5.27-alpha.10

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
@@ -1,8 +1,8 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let _fastify_busboy = require("@fastify/busboy");
3
- let _mastra_server_auth = require("@mastra/server/auth");
4
3
  let _mastra_server_server_adapter = require("@mastra/server/server-adapter");
5
4
  let _mastra_core_request_context = require("@mastra/core/request-context");
5
+ let _mastra_server_auth = require("@mastra/server/auth");
6
6
  // src/auth-middleware.ts
7
7
  function toWebRequest$1(req) {
8
8
  const url = `${req.protocol || "http"}://${req.get("host") || "localhost"}${req.originalUrl || req.url}`;
@@ -125,6 +125,7 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
125
125
  res.on("close", () => {
126
126
  if (!res.writableFinished) controller.abort();
127
127
  });
128
+ if (res.destroyed) controller.abort();
128
129
  res.locals.abortSignal = controller.signal;
129
130
  next();
130
131
  };
@@ -141,13 +142,14 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
141
142
  res.flushHeaders();
142
143
  if (streamFormat === "sse" && route.sseFlushOnConnect) res.write(": connected\n\n");
143
144
  const reader = (result instanceof ReadableStream ? result : result.fullStream).getReader();
145
+ const readerCancel = (0, _mastra_server_server_adapter.cancelReaderOnResponseClose)(reader, res);
144
146
  try {
145
147
  while (true) {
146
148
  const { done, value } = await reader.read();
147
149
  if (done) break;
148
150
  if (value) {
149
151
  if (streamFormat === "sse" && typeof value === "string" && value.startsWith(":")) {
150
- res.write(value);
152
+ await (0, _mastra_server_server_adapter.writeWithBackpressure)(res, value);
151
153
  continue;
152
154
  }
153
155
  const outputValue = this.streamOptions?.redact ?? true ? (0, _mastra_server_server_adapter.redactStreamChunk)(value) : value;
@@ -160,8 +162,8 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
160
162
  });
161
163
  continue;
162
164
  }
163
- if (streamFormat === "sse") res.write(`data: ${serialized.json}\n\n`);
164
- else res.write(serialized.json + "");
165
+ if (streamFormat === "sse") await (0, _mastra_server_server_adapter.writeWithBackpressure)(res, `data: ${serialized.json}\n\n`);
166
+ else await (0, _mastra_server_server_adapter.writeWithBackpressure)(res, serialized.json + "");
165
167
  }
166
168
  }
167
169
  } catch (error) {
@@ -170,6 +172,7 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
170
172
  stack: error.stack
171
173
  } : error });
172
174
  } finally {
175
+ readerCancel.dispose();
173
176
  res.end();
174
177
  }
175
178
  }
@@ -275,19 +278,20 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
275
278
  response.status(fetchResponse.status);
276
279
  if (fetchResponse.body) {
277
280
  const reader = fetchResponse.body.getReader();
281
+ const readerCancel = (0, _mastra_server_server_adapter.cancelReaderOnResponseClose)(reader, response);
278
282
  const onResError = (err) => {
279
283
  this.mastra.getLogger()?.error("Error writing datastream response", { error: err instanceof Error ? {
280
284
  message: err.message,
281
285
  stack: err.stack
282
286
  } : err });
283
- reader.cancel("response write error").catch(() => {});
287
+ readerCancel.cancel("response write error");
284
288
  };
285
289
  response.once("error", onResError);
286
290
  try {
287
291
  while (true) {
288
292
  const { done, value } = await reader.read();
289
293
  if (done) break;
290
- response.write(value);
294
+ await (0, _mastra_server_server_adapter.writeWithBackpressure)(response, value);
291
295
  }
292
296
  } catch (error) {
293
297
  this.mastra.getLogger()?.error("Error in datastream processing", { error: error instanceof Error ? {
@@ -296,6 +300,7 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
296
300
  } : error });
297
301
  } finally {
298
302
  response.off("error", onResError);
303
+ readerCancel.dispose();
299
304
  response.end();
300
305
  }
301
306
  } else response.end();
@@ -534,19 +539,10 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
534
539
  this.app.use(async (req, res, next) => {
535
540
  const path = String(req.path || "/");
536
541
  const method = String(req.method || "GET");
537
- const matchedRoute = (0, _mastra_server_auth.findMatchingCustomRoute)(path, method, this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes);
538
- const shouldRunCustomRouteAuth = (0, _mastra_server_auth.isProtectedCustomRoute)(path, method, this.customRouteAuthConfig);
542
+ const dispatchUrl = `${req.protocol}://${req.get("host") || "localhost"}${req.originalUrl}`;
543
+ const { match: matchedRoute, requiresAuth: shouldRunCustomRouteAuth, serverRoute, customRouteAuthConfig } = this.resolveCustomRouteAuth(dispatchUrl, method, path);
539
544
  const shouldRunCustomRouteFGA = !!matchedRoute?.route.fga;
540
545
  if (shouldRunCustomRouteAuth || shouldRunCustomRouteFGA) {
541
- const serverRoute = {
542
- method: matchedRoute?.route.method ?? method,
543
- path: matchedRoute?.route.path ?? path,
544
- responseType: "json",
545
- handler: async () => {},
546
- requiresAuth: matchedRoute?.route.requiresAuth,
547
- requiresPermission: matchedRoute?.route.requiresPermission,
548
- fga: matchedRoute?.route.fga
549
- };
550
546
  if (shouldRunCustomRouteAuth) {
551
547
  const authError = await this.checkRouteAuth(serverRoute, {
552
548
  path,
@@ -555,7 +551,8 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
555
551
  getQuery: (name) => req.query[name],
556
552
  requestContext: res.locals.requestContext,
557
553
  request: toWebRequest(req),
558
- buildAuthorizeContext: () => toWebRequest(req)
554
+ buildAuthorizeContext: () => toWebRequest(req),
555
+ customRouteAuthConfig
559
556
  });
560
557
  if (authError) {
561
558
  const authResult = authError;
@@ -584,7 +581,7 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
584
581
  message: fgaError.message
585
582
  });
586
583
  }
587
- const response = await this.handleCustomRouteRequest(`${req.protocol}://${req.get("host") || "localhost"}${req.originalUrl}`, req.method, req.headers, req.body, res.locals.requestContext, res.locals.abortSignal);
584
+ const response = await this.handleCustomRouteRequest(dispatchUrl, req.method, req.headers, req.body, res.locals.requestContext, res.locals.abortSignal);
588
585
  if (!response) return next();
589
586
  await this.writeCustomRouteResponse(response, res, res.locals.abortSignal);
590
587
  });
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["toWebRequest","RequestContext","isCustomRoutePublic","coreAuthMiddleware","MastraServerBase","redactStreamChunk","serializeStreamChunk","normalizeQueryParams","Busboy","isSafeObjectKey","applyMcpRequestAuth","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 applyMcpRequestAuth,\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 { setRequestAuth, ...options } = { ...this.mcpOptions, ...routeMcpOptions };\n\n await applyMcpRequestAuth({ req: request, requestContext: response.locals.requestContext, setRequestAuth });\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 applyMcpRequestAuth({\n req: request,\n requestContext: response.locals.requestContext,\n setRequestAuth: this.mcpOptions?.setRequestAuth,\n });\n\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,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,eAA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;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","cancelReaderOnResponseClose","writeWithBackpressure","redactStreamChunk","serializeStreamChunk","normalizeQueryParams","Busboy","isSafeObjectKey","applyMcpRequestAuth","isZodError","checkRouteFGA","getCustomHTTPExceptionResponse","getHTTPErrorResponse"],"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 type { MCPHttpTransportResult, MCPSseTransportResult } from '@mastra/server/handlers/mcp';\nimport type { ParsedRequestParams, ServerRoute } from '@mastra/server/server-adapter';\nimport {\n MastraServer as MastraServerBase,\n applyMcpRequestAuth,\n cancelReaderOnResponseClose,\n checkRouteFGA,\n getCustomHTTPExceptionResponse,\n getHTTPErrorResponse,\n isSafeObjectKey,\n isZodError,\n normalizeQueryParams,\n redactStreamChunk,\n serializeStreamChunk,\n writeWithBackpressure,\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 // A client that dropped while earlier middleware ran (async auth, body parsing) fired 'close' before this\n // listener existed.\n if (res.destroyed) {\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 const readerCancel = cancelReaderOnResponseClose(reader, res);\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 await writeWithBackpressure(res, 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 await writeWithBackpressure(res, `data: ${serialized.json}\\n\\n`);\n } else {\n await writeWithBackpressure(res, 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 readerCancel.dispose();\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 const readerCancel = cancelReaderOnResponseClose(reader, response);\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 readerCancel.cancel('response write error');\n };\n response.once('error', onResError);\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n await writeWithBackpressure(response, 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 readerCancel.dispose();\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 { setRequestAuth, ...options } = { ...this.mcpOptions, ...routeMcpOptions };\n\n await applyMcpRequestAuth({ req: request, requestContext: response.locals.requestContext, setRequestAuth });\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 applyMcpRequestAuth({\n req: request,\n requestContext: response.locals.requestContext,\n setRequestAuth: this.mcpOptions?.setRequestAuth,\n });\n\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 auth against the custom route the custom-route app will actually run for\n // the URL it's forwarded, which can differ from what Express matched.\n const path = String(req.path || '/');\n const method = String(req.method || 'GET');\n const dispatchUrl = `${req.protocol}://${req.get('host') || 'localhost'}${req.originalUrl}`;\n const {\n match: matchedRoute,\n requiresAuth: shouldRunCustomRouteAuth,\n serverRoute,\n customRouteAuthConfig,\n } = this.resolveCustomRouteAuth(dispatchUrl, method, path);\n const shouldRunCustomRouteFGA = !!matchedRoute?.route.fga;\n\n if (shouldRunCustomRouteAuth || shouldRunCustomRouteFGA) {\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 customRouteAuthConfig,\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 dispatchUrl,\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,OAAO,OAAO,IAAI,QAAQ,GAAG;EACnC,MAAM,SAAS,OAAO,IAAI,UAAU,KAAK;EACzC,MAAM,wBAAwB,IAAI,IAAqB,IAAI,OAAO,yBAAyB,CAAC,CAAC;EAE7F,IAAI,EAAA,GAACC,oBAAAA,oBAAAA,CAAoB,MAAM,QAAQ,qBAAqB,GAC1D,sBAAsB,IAAI,GAAG,OAAO,GAAG,QAAQ,IAAI;EAGrD,MAAM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AW,EAChB,KAAK,EAAE,WAAW,EAClB,EAAE,MAAM,EAAE,WAAW,EAAE,GAAE;QAAE,MAAM,CAAC,EAAE,MAAM,CAAA;KAAO,GAChD,OAAO,CAAC,IAAI,CAAC,CA6Nf;IAEK,uBAAuB,IAAI,OAAO,CAAC,IAAI,CAAC,CAyF7C;IAED,yBAAyB,IAAI,IAAI,CAUhC;IAED,sBAAsB,IAAI,IAAI,CAG7B;IAED,6BAA6B,IAAI,IAAI,CA+CpC;CACF"}
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Busboy } from "@fastify/busboy";
2
- import { coreAuthMiddleware, findMatchingCustomRoute, isCustomRoutePublic, isProtectedCustomRoute } from "@mastra/server/auth";
3
- import { MastraServer as MastraServer$1, applyMcpRequestAuth, checkRouteFGA, getCustomHTTPExceptionResponse, getHTTPErrorResponse, isSafeObjectKey, isZodError, normalizeQueryParams, redactStreamChunk, serializeStreamChunk } from "@mastra/server/server-adapter";
2
+ import { MastraServer as MastraServer$1, applyMcpRequestAuth, cancelReaderOnResponseClose, checkRouteFGA, getCustomHTTPExceptionResponse, getHTTPErrorResponse, isSafeObjectKey, isZodError, normalizeQueryParams, redactStreamChunk, serializeStreamChunk, writeWithBackpressure } from "@mastra/server/server-adapter";
4
3
  import { RequestContext } from "@mastra/core/request-context";
4
+ import { coreAuthMiddleware, isCustomRoutePublic } from "@mastra/server/auth";
5
5
  // src/auth-middleware.ts
6
6
  function toWebRequest$1(req) {
7
7
  const url = `${req.protocol || "http"}://${req.get("host") || "localhost"}${req.originalUrl || req.url}`;
@@ -124,6 +124,7 @@ var MastraServer = class extends MastraServer$1 {
124
124
  res.on("close", () => {
125
125
  if (!res.writableFinished) controller.abort();
126
126
  });
127
+ if (res.destroyed) controller.abort();
127
128
  res.locals.abortSignal = controller.signal;
128
129
  next();
129
130
  };
@@ -140,13 +141,14 @@ var MastraServer = class extends MastraServer$1 {
140
141
  res.flushHeaders();
141
142
  if (streamFormat === "sse" && route.sseFlushOnConnect) res.write(": connected\n\n");
142
143
  const reader = (result instanceof ReadableStream ? result : result.fullStream).getReader();
144
+ const readerCancel = cancelReaderOnResponseClose(reader, res);
143
145
  try {
144
146
  while (true) {
145
147
  const { done, value } = await reader.read();
146
148
  if (done) break;
147
149
  if (value) {
148
150
  if (streamFormat === "sse" && typeof value === "string" && value.startsWith(":")) {
149
- res.write(value);
151
+ await writeWithBackpressure(res, value);
150
152
  continue;
151
153
  }
152
154
  const outputValue = this.streamOptions?.redact ?? true ? redactStreamChunk(value) : value;
@@ -159,8 +161,8 @@ var MastraServer = class extends MastraServer$1 {
159
161
  });
160
162
  continue;
161
163
  }
162
- if (streamFormat === "sse") res.write(`data: ${serialized.json}\n\n`);
163
- else res.write(serialized.json + "");
164
+ if (streamFormat === "sse") await writeWithBackpressure(res, `data: ${serialized.json}\n\n`);
165
+ else await writeWithBackpressure(res, serialized.json + "");
164
166
  }
165
167
  }
166
168
  } catch (error) {
@@ -169,6 +171,7 @@ var MastraServer = class extends MastraServer$1 {
169
171
  stack: error.stack
170
172
  } : error });
171
173
  } finally {
174
+ readerCancel.dispose();
172
175
  res.end();
173
176
  }
174
177
  }
@@ -274,19 +277,20 @@ var MastraServer = class extends MastraServer$1 {
274
277
  response.status(fetchResponse.status);
275
278
  if (fetchResponse.body) {
276
279
  const reader = fetchResponse.body.getReader();
280
+ const readerCancel = cancelReaderOnResponseClose(reader, response);
277
281
  const onResError = (err) => {
278
282
  this.mastra.getLogger()?.error("Error writing datastream response", { error: err instanceof Error ? {
279
283
  message: err.message,
280
284
  stack: err.stack
281
285
  } : err });
282
- reader.cancel("response write error").catch(() => {});
286
+ readerCancel.cancel("response write error");
283
287
  };
284
288
  response.once("error", onResError);
285
289
  try {
286
290
  while (true) {
287
291
  const { done, value } = await reader.read();
288
292
  if (done) break;
289
- response.write(value);
293
+ await writeWithBackpressure(response, value);
290
294
  }
291
295
  } catch (error) {
292
296
  this.mastra.getLogger()?.error("Error in datastream processing", { error: error instanceof Error ? {
@@ -295,6 +299,7 @@ var MastraServer = class extends MastraServer$1 {
295
299
  } : error });
296
300
  } finally {
297
301
  response.off("error", onResError);
302
+ readerCancel.dispose();
298
303
  response.end();
299
304
  }
300
305
  } else response.end();
@@ -533,19 +538,10 @@ var MastraServer = class extends MastraServer$1 {
533
538
  this.app.use(async (req, res, next) => {
534
539
  const path = String(req.path || "/");
535
540
  const method = String(req.method || "GET");
536
- const matchedRoute = findMatchingCustomRoute(path, method, this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes);
537
- const shouldRunCustomRouteAuth = isProtectedCustomRoute(path, method, this.customRouteAuthConfig);
541
+ const dispatchUrl = `${req.protocol}://${req.get("host") || "localhost"}${req.originalUrl}`;
542
+ const { match: matchedRoute, requiresAuth: shouldRunCustomRouteAuth, serverRoute, customRouteAuthConfig } = this.resolveCustomRouteAuth(dispatchUrl, method, path);
538
543
  const shouldRunCustomRouteFGA = !!matchedRoute?.route.fga;
539
544
  if (shouldRunCustomRouteAuth || shouldRunCustomRouteFGA) {
540
- const serverRoute = {
541
- method: matchedRoute?.route.method ?? method,
542
- path: matchedRoute?.route.path ?? path,
543
- responseType: "json",
544
- handler: async () => {},
545
- requiresAuth: matchedRoute?.route.requiresAuth,
546
- requiresPermission: matchedRoute?.route.requiresPermission,
547
- fga: matchedRoute?.route.fga
548
- };
549
545
  if (shouldRunCustomRouteAuth) {
550
546
  const authError = await this.checkRouteAuth(serverRoute, {
551
547
  path,
@@ -554,7 +550,8 @@ var MastraServer = class extends MastraServer$1 {
554
550
  getQuery: (name) => req.query[name],
555
551
  requestContext: res.locals.requestContext,
556
552
  request: toWebRequest(req),
557
- buildAuthorizeContext: () => toWebRequest(req)
553
+ buildAuthorizeContext: () => toWebRequest(req),
554
+ customRouteAuthConfig
558
555
  });
559
556
  if (authError) {
560
557
  const authResult = authError;
@@ -583,7 +580,7 @@ var MastraServer = class extends MastraServer$1 {
583
580
  message: fgaError.message
584
581
  });
585
582
  }
586
- const response = await this.handleCustomRouteRequest(`${req.protocol}://${req.get("host") || "localhost"}${req.originalUrl}`, req.method, req.headers, req.body, res.locals.requestContext, res.locals.abortSignal);
583
+ const response = await this.handleCustomRouteRequest(dispatchUrl, req.method, req.headers, req.body, res.locals.requestContext, res.locals.abortSignal);
587
584
  if (!response) return next();
588
585
  await this.writeCustomRouteResponse(response, res, res.locals.abortSignal);
589
586
  });
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 applyMcpRequestAuth,\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 { setRequestAuth, ...options } = { ...this.mcpOptions, ...routeMcpOptions };\n\n await applyMcpRequestAuth({ req: request, requestContext: response.locals.requestContext, setRequestAuth });\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 applyMcpRequestAuth({\n req: request,\n requestContext: response.locals.requestContext,\n setRequestAuth: this.mcpOptions?.setRequestAuth,\n });\n\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,KAAK,CAAC,CAAC;OAEzC,QAAQ,IAAI,KAAK,KAAK;CAE1B;CAEA,OAAO,IAAI,WAAW,QAAQ,KAAK;EACjC,QAAQ,IAAI;EACZ;CACF,CAAC;AACH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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 type { MCPHttpTransportResult, MCPSseTransportResult } from '@mastra/server/handlers/mcp';\nimport type { ParsedRequestParams, ServerRoute } from '@mastra/server/server-adapter';\nimport {\n MastraServer as MastraServerBase,\n applyMcpRequestAuth,\n cancelReaderOnResponseClose,\n checkRouteFGA,\n getCustomHTTPExceptionResponse,\n getHTTPErrorResponse,\n isSafeObjectKey,\n isZodError,\n normalizeQueryParams,\n redactStreamChunk,\n serializeStreamChunk,\n writeWithBackpressure,\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 // A client that dropped while earlier middleware ran (async auth, body parsing) fired 'close' before this\n // listener existed.\n if (res.destroyed) {\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 const readerCancel = cancelReaderOnResponseClose(reader, res);\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 await writeWithBackpressure(res, 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 await writeWithBackpressure(res, `data: ${serialized.json}\\n\\n`);\n } else {\n await writeWithBackpressure(res, 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 readerCancel.dispose();\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 const readerCancel = cancelReaderOnResponseClose(reader, response);\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 readerCancel.cancel('response write error');\n };\n response.once('error', onResError);\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n await writeWithBackpressure(response, 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 readerCancel.dispose();\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 { setRequestAuth, ...options } = { ...this.mcpOptions, ...routeMcpOptions };\n\n await applyMcpRequestAuth({ req: request, requestContext: response.locals.requestContext, setRequestAuth });\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 applyMcpRequestAuth({\n req: request,\n requestContext: response.locals.requestContext,\n setRequestAuth: this.mcpOptions?.setRequestAuth,\n });\n\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 auth against the custom route the custom-route app will actually run for\n // the URL it's forwarded, which can differ from what Express matched.\n const path = String(req.path || '/');\n const method = String(req.method || 'GET');\n const dispatchUrl = `${req.protocol}://${req.get('host') || 'localhost'}${req.originalUrl}`;\n const {\n match: matchedRoute,\n requiresAuth: shouldRunCustomRouteAuth,\n serverRoute,\n customRouteAuthConfig,\n } = this.resolveCustomRouteAuth(dispatchUrl, method, path);\n const shouldRunCustomRouteFGA = !!matchedRoute?.route.fga;\n\n if (shouldRunCustomRouteAuth || shouldRunCustomRouteFGA) {\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 customRouteAuthConfig,\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 dispatchUrl,\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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nB,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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/express",
3
- "version": "1.5.27-alpha.0",
3
+ "version": "1.5.27-alpha.10",
4
4
  "description": "Mastra Express adapter for the server",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -21,14 +21,17 @@
21
21
  "license": "Apache-2.0",
22
22
  "dependencies": {
23
23
  "@fastify/busboy": "^3.2.4",
24
- "@mastra/server": "1.83.0-alpha.0"
24
+ "@mastra/server": "1.83.0-alpha.10"
25
25
  },
26
26
  "devDependencies": {
27
27
  "@ai-sdk/openai": "^2.0.139",
28
+ "@copilotkit/aimock": "^1.46.0",
29
+ "@types/compression": "^1.8.1",
28
30
  "@types/cors": "^2.8.19",
29
31
  "@types/express": "^5.0.6",
30
32
  "@types/node": "22.19.15",
31
33
  "@types/swagger-ui-express": "^4.1.8",
34
+ "compression": "^1.8.2",
32
35
  "cors": "^2.8.6",
33
36
  "express": "^5.3.0",
34
37
  "swagger-ui-express": "^5.0.1",
@@ -39,13 +42,14 @@
39
42
  "@internal/lint": "0.0.148",
40
43
  "@internal/storage-test-utils": "0.0.144",
41
44
  "@internal/types-builder": "0.0.123",
42
- "@mastra/ai-sdk": "1.11.3",
43
- "@mastra/core": "1.83.0-alpha.0",
45
+ "@mastra/ai-sdk": "1.12.0-alpha.1",
46
+ "@mastra/client-js": "1.60.0-alpha.10",
47
+ "@mastra/core": "1.83.0-alpha.10",
44
48
  "@mastra/evals": "1.10.11",
45
- "@mastra/libsql": "1.30.0-alpha.0",
46
- "@mastra/memory": "1.41.1-alpha.0",
47
- "@mastra/observability": "1.23.2-alpha.0",
48
- "@mastra/server-adapters-test-suite": "0.2.1"
49
+ "@mastra/libsql": "1.30.0-alpha.3",
50
+ "@mastra/memory": "1.41.1-alpha.4",
51
+ "@mastra/observability": "1.24.0-alpha.6",
52
+ "@mastra/server-adapters-test-suite": "0.3.0-alpha.4"
49
53
  },
50
54
  "peerDependencies": {
51
55
  "@mastra/core": ">=1.80.0-0 <2.0.0-0",