@mastra/express 1.5.30-alpha.5 → 1.5.30-alpha.7

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
@@ -612,5 +612,3 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
612
612
  };
613
613
  exports.MastraServer = MastraServer;
614
614
  exports.createAuthMiddleware = createAuthMiddleware;
615
-
616
- //# sourceMappingURL=index.cjs.map
package/dist/index.js CHANGED
@@ -610,5 +610,3 @@ var MastraServer = class extends MastraServer$1 {
610
610
  }
611
611
  };
612
612
  export { MastraServer, createAuthMiddleware };
613
-
614
- //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/express",
3
- "version": "1.5.30-alpha.5",
3
+ "version": "1.5.30-alpha.7",
4
4
  "description": "Mastra Express adapter for the server",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -21,7 +21,7 @@
21
21
  "license": "Apache-2.0",
22
22
  "dependencies": {
23
23
  "@fastify/busboy": "^3.2.4",
24
- "@mastra/server": "1.86.0-alpha.5"
24
+ "@mastra/server": "1.86.0-alpha.7"
25
25
  },
26
26
  "devDependencies": {
27
27
  "@ai-sdk/openai": "^2.0.139",
@@ -42,14 +42,14 @@
42
42
  "@internal/lint": "0.0.151",
43
43
  "@internal/storage-test-utils": "0.0.147",
44
44
  "@internal/types-builder": "0.0.126",
45
- "@mastra/ai-sdk": "1.12.0",
46
- "@mastra/client-js": "1.61.2-alpha.5",
47
- "@mastra/core": "1.86.0-alpha.5",
48
- "@mastra/evals": "1.10.12-alpha.0",
49
- "@mastra/libsql": "1.31.1",
50
- "@mastra/memory": "1.41.3-alpha.1",
51
- "@mastra/observability": "1.24.3-alpha.0",
52
- "@mastra/server-adapters-test-suite": "0.3.0"
45
+ "@mastra/ai-sdk": "1.12.1-alpha.0",
46
+ "@mastra/client-js": "1.61.2-alpha.7",
47
+ "@mastra/core": "1.86.0-alpha.7",
48
+ "@mastra/evals": "1.10.12-alpha.2",
49
+ "@mastra/libsql": "1.32.0-alpha.1",
50
+ "@mastra/memory": "1.41.3-alpha.3",
51
+ "@mastra/observability": "1.24.3-alpha.1",
52
+ "@mastra/server-adapters-test-suite": "0.3.1-alpha.0"
53
53
  },
54
54
  "peerDependencies": {
55
55
  "@mastra/core": ">=1.85.1-0 <2.0.0-0",
@@ -60,7 +60,8 @@
60
60
  "node": ">=22.13.0"
61
61
  },
62
62
  "files": [
63
- "dist"
63
+ "dist",
64
+ "!dist/**/*.d.*ts.map"
64
65
  ],
65
66
  "homepage": "https://mastra.ai",
66
67
  "repository": {
@@ -1 +0,0 @@
1
- {"version":3,"file":"auth-middleware.d.ts","sourceRoot":"","sources":["../src/auth-middleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAGlD,OAAO,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAE/D,MAAM,WAAW,4BAA4B;IAC3C,MAAM,EAAE,MAAM,CAAC;IACf,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB;AAuBD,wBAAgB,oBAAoB,CAAC,EACnC,MAAM,EACN,YAAmB,GACpB,EAAE,4BAA4B,GAAG,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE,YAAY,KAAK,OAAO,CAAC,IAAI,CAAC,CA2DnG"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.cjs","names":["toWebRequest","RequestContext","isCustomRoutePublic","coreAuthMiddleware","MastraServerBase","cancelReaderOnResponseClose","writeWithBackpressure","redactStreamChunk","serializeStreamChunk","normalizeQueryParams","Busboy","isSafeObjectKey","applyMcpRequestAuth","isZodError","getCustomHTTPExceptionResponse","getHTTPErrorResponse","checkRouteFGA"],"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 AuthErrorWithHeaders = { status: number; error: string; headers?: Record<string, string> };\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 /** Adapter `mcpOptions` win; otherwise use `server.mcpOptions` from the Mastra config. */\n private resolveMcpOptions() {\n return this.mcpOptions ?? this.mastra.getServer()?.mcpOptions;\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.resolveMcpOptions(), ...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.resolveMcpOptions()?.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 (RBAC) and FGA authorization (EE features)\n const authzError = await this.authorizeRoute(\n route,\n {\n ...params.urlParams,\n ...params.queryParams,\n ...(typeof params.body === 'object' ? params.body : {}),\n },\n res.locals.requestContext,\n );\n if (authzError) {\n return res.status(authzError.status).json({ error: authzError.error, message: authzError.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 const permissionError = this.checkRouteRBAC(serverRoute, res.locals.requestContext);\n if (permissionError) {\n return res.status(permissionError.status).json({\n error: permissionError.error,\n message: permissionError.message,\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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I,EAAE,YAAY,KAAK,OAAO,CAAC,IAAI,CAAC,CAyE5F;IACK,MAAM,CAAC,KAAK,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE;QAAE,UAAU,EAAE,cAAc,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CA6DrG;IAEK,SAAS,CAAC,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,mBAAmB,CAAC,CA+BlF;IAED;;;;;;OAMG;IACH,OAAO,CAAC,sBAAsB;IAuE9B,0FAA0F;IAC1F,OAAO,CAAC,iBAAiB;IAInB,YAAY,CAChB,KAAK,EAAE,WAAW,EAClB,QAAQ,EAAE,QAAQ,EAClB,MAAM,EAAE,OAAO,EACf,OAAO,CAAC,EAAE,OAAO,EACjB,MAAM,CAAC,EAAE,MAAM,GACd,OAAO,CAAC,IAAI,CAAC,CAmHf;IAEK,aAAa,CACjB,GAAG,EAAE,WAAW,EAChB,KAAK,EAAE,WAAW,EAClB,EAAE,MAAM,EAAE,WAAW,EAAE,GAAE;QAAE,MAAM,CAAC,EAAE,MAAM,CAAA;KAAO,GAChD,OAAO,CAAC,IAAI,CAAC,CAwMf;IAEK,uBAAuB,IAAI,OAAO,CAAC,IAAI,CAAC,CA4E7C;IAED,yBAAyB,IAAI,IAAI,CAUhC;IAED,sBAAsB,IAAI,IAAI,CAG7B;IAED,6BAA6B,IAAI,IAAI,CA+CpC;CACF"}
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
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 AuthErrorWithHeaders = { status: number; error: string; headers?: Record<string, string> };\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 /** Adapter `mcpOptions` win; otherwise use `server.mcpOptions` from the Mastra config. */\n private resolveMcpOptions() {\n return this.mcpOptions ?? this.mastra.getServer()?.mcpOptions;\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.resolveMcpOptions(), ...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.resolveMcpOptions()?.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 (RBAC) and FGA authorization (EE features)\n const authzError = await this.authorizeRoute(\n route,\n {\n ...params.urlParams,\n ...params.queryParams,\n ...(typeof params.body === 'object' ? params.body : {}),\n },\n res.locals.requestContext,\n );\n if (authzError) {\n return res.status(authzError.status).json({ error: authzError.error, message: authzError.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 const permissionError = this.checkRouteRBAC(serverRoute, res.locals.requestContext);\n if (permissionError) {\n return res.status(permissionError.status).json({\n error: permissionError.error,\n message: permissionError.message,\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,QAC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