{"version":3,"file":"index.cjs","names":["toWebRequest","RequestContext","isCustomRoutePublic","coreAuthMiddleware","MastraServerBase","isZodError","checkRouteFGA","getCustomHTTPExceptionResponse","redactStreamChunk","serializeStreamChunk","normalizeQueryParams","Busboy","isSafeObjectKey","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 { Context, Middleware, Next } from 'koa';\n\nexport interface KoaAuthMiddlewareOptions {\n  mastra: Mastra;\n  requiresAuth?: boolean;\n}\n\nfunction toWebRequest(ctx: Context): globalThis.Request {\n  const protocol = ctx.protocol || 'http';\n  const host = ctx.host || 'localhost';\n  const url = `${protocol}://${host}${ctx.url}`;\n\n  const headers = new Headers();\n  for (const [key, value] of Object.entries(ctx.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: ctx.method,\n    headers,\n  });\n}\n\nexport function createAuthMiddleware({ mastra, requiresAuth = true }: KoaAuthMiddlewareOptions): Middleware {\n  return async (ctx: Context, next: Next) => {\n    if (!requiresAuth) {\n      await next();\n      return;\n    }\n\n    const authConfig = mastra.getServer()?.auth;\n    if (!authConfig) {\n      await next();\n      return;\n    }\n\n    ctx.state.requestContext ??= new RequestContext();\n    ctx.state.mastra ??= mastra;\n\n    const path = String(ctx.path || '/');\n    const method = String(ctx.method || 'GET');\n    const customRouteAuthConfig = new Map<string, boolean>(ctx.state.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 = ctx.headers.authorization;\n    let token: string | null = authHeader ? authHeader.replace('Bearer ', '') : null;\n    if (!token) {\n      token = (ctx.query.apiKey as string) || null;\n    }\n\n    const result = await coreAuthMiddleware({\n      path,\n      method,\n      getHeader: name => ctx.headers[name.toLowerCase()] as string | undefined,\n      mastra,\n      authConfig,\n      customRouteAuthConfig,\n      requestContext: ctx.state.requestContext,\n      rawRequest: toWebRequest(ctx),\n      token,\n      buildAuthorizeContext: () => toWebRequest(ctx),\n    });\n\n    for (const [key, value] of Object.entries(result.headers ?? {})) {\n      if (key.toLowerCase() === 'set-cookie') {\n        ctx.append(key, value);\n      } else {\n        ctx.set(key, value);\n      }\n    }\n\n    if (result.action === 'next') {\n      await next();\n      return;\n    }\n\n    ctx.status = result.status;\n    ctx.body = result.body;\n  };\n}\n","import { Busboy } from '@fastify/busboy';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { InMemoryTaskStore } from '@mastra/server/a2a/store';\nimport { findMatchingCustomRoute, isProtectedCustomRoute } from '@mastra/server/auth';\nimport type { MCPHttpTransportResult, MCPSseTransportResult } from '@mastra/server/handlers/mcp';\nimport type { ParsedRequestParams, ServerRoute } from '@mastra/server/server-adapter';\nimport {\n  MastraServer as MastraServerBase,\n  checkRouteFGA,\n  getCustomHTTPExceptionResponse,\n  isSafeObjectKey,\n  isZodError,\n  normalizeQueryParams,\n  redactStreamChunk,\n  serializeStreamChunk,\n} from '@mastra/server/server-adapter';\nimport type Koa from 'koa';\nimport type { Context, Middleware, Next } from 'koa';\nexport { createAuthMiddleware } from './auth-middleware';\nexport type { KoaAuthMiddlewareOptions } from './auth-middleware';\n\ntype HasPermissionFn = (userPerms: string[], required: string) => boolean;\ntype RegisteredKoaRoute = {\n  route: ServerRoute;\n  prefix: string;\n  koaPath: string;\n  pathRegex: RegExp;\n  paramNames: string[];\n};\ntype RouteDispatcherGroup = {\n  routes: RegisteredKoaRoute[];\n  stackLengthAfterRegistration: number;\n};\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/koa] 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 Koa context to Web API Request for cookie-based auth providers.\n */\nfunction toWebRequest(ctx: Context): globalThis.Request {\n  const protocol = ctx.protocol || 'http';\n  const host = ctx.host || 'localhost';\n  const url = `${protocol}://${host}${ctx.url}`;\n\n  const headers = new Headers();\n  for (const [key, value] of Object.entries(ctx.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: ctx.method,\n    headers,\n  });\n}\n\n// Extend Koa types to include Mastra context\ndeclare module 'koa' {\n  interface DefaultState {\n    mastra: Mastra;\n    requestContext: RequestContext;\n    tools: ToolsInput;\n    abortSignal: AbortSignal;\n    taskStore: InMemoryTaskStore;\n    customRouteAuthConfig?: Map<string, boolean>;\n  }\n  interface Request {\n    body?: unknown;\n  }\n}\n\nexport class MastraServer extends MastraServerBase<Koa, Context, Context> {\n  private readonly activeRouteDispatchers = new WeakMap<Koa, RouteDispatcherGroup>();\n\n  async init() {\n    this.registerErrorMiddleware();\n    await super.init();\n  }\n\n  /**\n   * Register a global error-handling middleware at the top of the middleware chain.\n   * This acts as a safety net for errors that propagate past route handlers\n   * (e.g., from auth middleware, context middleware, or when route handlers re-throw).\n   *\n   * When `server.onError` is configured, calls it and uses the response.\n   * Otherwise provides a default JSON error response.\n   *\n   * Errors are emitted on the app for logging (Koa convention) but NOT re-thrown,\n   * so this middleware is the final error boundary. Users who need custom error handling\n   * should use `server.onError` or register their own middleware between this and the routes.\n   */\n  private registerErrorMiddleware(): void {\n    const server = this;\n\n    this.app.use(async function mastraErrorBoundary(ctx: Context, next: Next) {\n      try {\n        await next();\n      } catch (err) {\n        // Try onError first (may have already been called in registerRoute,\n        // but this catches errors from other middleware too)\n        if (await server.handleOnError(err, ctx)) {\n          return;\n        }\n\n        // Default error handling\n        const error = err instanceof Error ? err : new Error(String(err));\n        let status = 500;\n        if (err && typeof err === 'object') {\n          if ('status' in err) {\n            status = (err as any).status;\n          } else if (\n            'details' in err &&\n            (err as any).details &&\n            typeof (err as any).details === 'object' &&\n            'status' in (err as any).details\n          ) {\n            status = (err as any).details.status;\n          }\n        }\n        ctx.status = status;\n        ctx.body = { error: error.message || 'Unknown error' };\n\n        // The route handler already logged this 501 at warn level. Skip the emit when only\n        // Koa's default listener would receive it, since that prints to console.error.\n        // Apps that register their own 'error' listeners still get the event.\n        const loggedAsWarning = status === 501 && (ctx as any)._mastraLoggedNotImplementedError === err;\n        const onlyDefaultListener = ctx.app.listeners('error').every(listener => listener === ctx.app.onerror);\n        if (loggedAsWarning && onlyDefaultListener) {\n          return;\n        }\n\n        // Emit the error for logging (standard Koa pattern) but don't re-throw\n        // since this middleware is the final error boundary.\n        ctx.app.emit('error', err, ctx);\n      }\n    });\n  }\n\n  /**\n   * Try to handle an error using the `server.onError` hook.\n   * Creates a minimal context shim compatible with the Hono-style onError signature.\n   *\n   * @returns true if the error was handled and the response was set on ctx\n   */\n  private async handleOnError(err: unknown, ctx: Context): Promise<boolean> {\n    // Guard against double invocation (route catch → re-throw → error middleware)\n    if ((ctx as any)._mastraOnErrorAttempted) return false;\n    (ctx as any)._mastraOnErrorAttempted = true;\n\n    const onError = this.mastra.getServer()?.onError;\n    if (!onError) return false;\n\n    const error = err instanceof Error ? err : new Error(String(err));\n\n    // Create a minimal context shim compatible with the onError signature\n    const shimContext = {\n      json: (data: unknown, status: number = 200) =>\n        new Response(JSON.stringify(data), {\n          status,\n          headers: { 'Content-Type': 'application/json' },\n        }),\n      req: {\n        path: ctx.path,\n        method: ctx.method,\n        header: (name: string) => {\n          const value = ctx.headers[name.toLowerCase()];\n          if (Array.isArray(value)) return value.join(', ');\n          return value;\n        },\n        url: ctx.url,\n      },\n    };\n\n    try {\n      const response = await onError(error, shimContext as any);\n      // Apply the Response from onError to the Koa context\n      ctx.status = response.status;\n      const contentType = response.headers.get('content-type') || '';\n      if (contentType.includes('application/json')) {\n        ctx.body = await response.json();\n      } else {\n        ctx.body = await response.text();\n      }\n      return true;\n    } catch (onErrorErr) {\n      this.mastra.getLogger()?.error('Error in custom onError handler', {\n        error: onErrorErr instanceof Error ? { message: onErrorErr.message, stack: onErrorErr.stack } : onErrorErr,\n      });\n      return false;\n    }\n  }\n\n  createContextMiddleware(): Middleware {\n    const server = this;\n\n    return async function mastraRequestContext(ctx: Context, next: Next) {\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 (ctx.method === 'POST' || ctx.method === 'PUT') {\n        const contentType = ctx.headers['content-type'];\n        if (contentType?.includes('application/json') && ctx.request.body) {\n          const body = ctx.request.body as { requestContext?: Record<string, any> };\n          if (body.requestContext) {\n            bodyRequestContext = body.requestContext;\n          }\n        }\n      }\n\n      // Parse request context from query params (GET)\n      if (ctx.method === 'GET') {\n        try {\n          const query = ctx.query;\n          const encodedRequestContext = 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 = server.mergeRequestContext({ paramsRequestContext, bodyRequestContext });\n      server.applyRequestMetadataToContext({\n        requestContext,\n        getHeader: name => ctx.get(name),\n      });\n\n      // Set context in state object\n      ctx.state.requestContext = requestContext;\n      ctx.state.mastra = server.mastra;\n      ctx.state.tools = server.tools || {};\n      if (server.taskStore) {\n        ctx.state.taskStore = server.taskStore;\n      }\n      ctx.state.customRouteAuthConfig = server.customRouteAuthConfig;\n\n      // Create abort controller for request cancellation\n      const controller = new AbortController();\n      ctx.req.on('close', () => {\n        // Only abort if the response wasn't successfully completed\n        if (!ctx.res.writableEnded) {\n          controller.abort();\n        }\n      });\n      ctx.state.abortSignal = controller.signal;\n\n      await next();\n    };\n  }\n\n  private getRouteDispatcherGroup(app: Koa): RouteDispatcherGroup {\n    // The dispatcher-reuse optimization needs to observe app.middleware.length\n    // to detect when other middleware was registered between our route\n    // registrations (in which case we must start a new dispatcher group to\n    // preserve middleware ordering). Subclasses may pass an app-like object\n    // (e.g., a koa-router or a mounted sub-app) that only exposes `use` and\n    // has no `middleware` array. In that case, skip reuse and register a fresh\n    // dispatcher per call — equivalent to the pre-1.5.0 per-route behavior.\n    const middlewareStack = (app as { middleware?: unknown }).middleware;\n    const supportsReuse = Array.isArray(middlewareStack);\n\n    if (supportsReuse) {\n      const activeGroup = this.activeRouteDispatchers.get(app);\n      if (activeGroup && middlewareStack.length === activeGroup.stackLengthAfterRegistration) {\n        return activeGroup;\n      }\n    }\n\n    const group: RouteDispatcherGroup = {\n      routes: [],\n      stackLengthAfterRegistration: 0,\n    };\n    app.use(this.createRouteDispatcherMiddleware(group));\n\n    if (supportsReuse) {\n      group.stackLengthAfterRegistration = (app as { middleware: unknown[] }).middleware.length;\n      this.activeRouteDispatchers.set(app, group);\n    }\n\n    return group;\n  }\n\n  private createRouteDispatcherMiddleware(group: RouteDispatcherGroup): Middleware {\n    const server = this;\n\n    return async function mastraRouteDispatcher(ctx: Context, next: Next) {\n      const matchedRoute = server.findRegisteredRoute(group.routes, ctx);\n\n      if (!matchedRoute) {\n        await next();\n        return;\n      }\n\n      await server.handleMatchedRoute(matchedRoute, ctx);\n    };\n  }\n\n  private findRegisteredRoute(routes: RegisteredKoaRoute[], ctx: Context): RegisteredKoaRoute | undefined {\n    const method = ctx.method.toUpperCase();\n\n    for (const registeredRoute of routes) {\n      if (\n        registeredRoute.route.method.toUpperCase() !== 'ALL' &&\n        method !== registeredRoute.route.method.toUpperCase()\n      ) {\n        continue;\n      }\n\n      const match = registeredRoute.pathRegex.exec(ctx.path);\n      if (!match) {\n        continue;\n      }\n\n      ctx.params = {};\n      registeredRoute.paramNames.forEach((name, index) => {\n        const value = match[index + 1];\n        ctx.params[name] = value === undefined ? value : decodeURIComponent(value);\n      });\n\n      return registeredRoute;\n    }\n\n    return undefined;\n  }\n\n  private async handleMatchedRoute(registeredRoute: RegisteredKoaRoute, ctx: Context): Promise<void> {\n    const { route, prefix } = registeredRoute;\n\n    const authError = await this.checkRouteAuth(route, {\n      path: String(ctx.path || '/'),\n      method: String(ctx.method || 'GET'),\n      getHeader: name => ctx.headers[name.toLowerCase()] as string | undefined,\n      getQuery: name => (ctx.query as Record<string, string>)[name],\n      requestContext: ctx.state.requestContext,\n      request: toWebRequest(ctx),\n      buildAuthorizeContext: () => toWebRequest(ctx),\n    });\n\n    if (authError) {\n      // Apply any refresh headers (e.g. Set-Cookie from transparent session refresh)\n      if (authError.headers) {\n        for (const [key, value] of Object.entries(authError.headers)) {\n          ctx.set(key, value);\n        }\n      }\n\n      // If this is an auth error (not just a success-with-headers), return error response\n      if (authError.error) {\n        ctx.status = authError.status;\n        ctx.body = { error: authError.error };\n        return;\n      }\n    }\n\n    const params = await this.getParams(route, ctx);\n\n    // Return 400 Bad Request if body parsing failed (e.g., malformed multipart data)\n    if (params.bodyParseError) {\n      ctx.status = 400;\n      ctx.body = {\n        error: 'Invalid request body',\n        issues: [{ field: 'body', message: params.bodyParseError.message }],\n      };\n      return;\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 resolved = this.resolveValidationError(route, error, 'query');\n          ctx.status = resolved.status;\n          ctx.body = resolved.body;\n          return;\n        }\n        ctx.status = 400;\n        ctx.body = {\n          error: 'Invalid query parameters',\n          issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n        };\n        return;\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 resolved = this.resolveValidationError(route, error, 'body');\n          ctx.status = resolved.status;\n          ctx.body = resolved.body;\n          return;\n        }\n        ctx.status = 400;\n        ctx.body = {\n          error: 'Invalid request body',\n          issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n        };\n        return;\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 resolved = this.resolveValidationError(route, error, 'path');\n          ctx.status = resolved.status;\n          ctx.body = resolved.body;\n          return;\n        }\n        ctx.status = 400;\n        ctx.body = {\n          error: 'Invalid path parameters',\n          issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n        };\n        return;\n      }\n    }\n\n    const handlerParams = {\n      ...params.urlParams,\n      ...params.queryParams,\n      ...(typeof params.body === 'object' ? params.body : {}),\n      requestContext: ctx.state.requestContext,\n      mastra: this.mastra,\n      tools: ctx.state.tools,\n      taskStore: ctx.state.taskStore,\n      abortSignal: ctx.state.abortSignal,\n      routePrefix: prefix,\n      request: toWebRequest(ctx),\n    };\n\n    // Check route permission requirement (EE feature)\n    // Uses convention-based permission derivation: permissions are auto-derived\n    // from route path/method unless explicitly set or route is public\n    const requestContext = ctx.state.requestContext;\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 = requestContext.get('mastra__userPermissions') as string[] | undefined;\n        const permissionError = this.checkRoutePermission(route, userPermissions, hasPermission, requestContext);\n\n        if (permissionError) {\n          ctx.status = permissionError.status;\n          ctx.body = {\n            error: permissionError.error,\n            message: permissionError.message,\n          };\n          return;\n        }\n      }\n    }\n\n    // Check FGA authorization (EE feature)\n    const fgaError = await checkRouteFGA(this.mastra, route, requestContext, {\n      ...params.urlParams,\n      ...params.queryParams,\n      ...(typeof params.body === 'object' ? params.body : {}),\n    });\n    if (fgaError) {\n      ctx.status = fgaError.status;\n      ctx.body = { error: fgaError.error, message: fgaError.message };\n      return;\n    }\n\n    try {\n      const result = await route.handler(handlerParams);\n      await this.sendResponse(route, ctx, result, 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        (ctx as any)._mastraLoggedNotImplementedError = httpStatus === 501 ? error : undefined;\n      }\n      const customResponse = getCustomHTTPExceptionResponse(error);\n      if (customResponse) {\n        ctx.status = customResponse.status;\n        customResponse.headers.forEach((value, name) => ctx.set(name, value));\n        ctx.body = Buffer.from(await customResponse.arrayBuffer());\n        return;\n      }\n\n      // Attach status code to the error for upstream middleware\n      if (error && typeof error === 'object') {\n        if (!('status' in error)) {\n          // Check for MastraError with status in details\n          if ('details' in error && error.details && typeof error.details === 'object' && 'status' in error.details) {\n            (error as any).status = (error.details as any).status;\n          }\n        }\n      }\n\n      // Try to call server.onError if configured\n      if (await this.handleOnError(error, ctx)) {\n        return;\n      }\n\n      // Re-throw so the error propagates up Koa's middleware chain\n      throw error;\n    }\n  }\n\n  async stream(route: ServerRoute, ctx: Context, result: { fullStream: ReadableStream }): Promise<void> {\n    // Tell Koa we're handling the response ourselves\n    ctx.respond = false;\n\n    const streamFormat = route.streamFormat || 'stream';\n\n    // Set status and headers via ctx.res directly since we're bypassing Koa's response\n    const sseHeaders =\n      streamFormat === 'sse'\n        ? {\n            'Content-Type': 'text/event-stream',\n            'Cache-Control': 'no-cache',\n            Connection: 'keep-alive',\n            'X-Accel-Buffering': 'no',\n          }\n        : {\n            'Content-Type': 'text/plain',\n          };\n\n    ctx.res.writeHead(200, {\n      ...sseHeaders,\n      'Transfer-Encoding': 'chunked',\n    });\n\n    if (streamFormat === 'sse' && route.sseFlushOnConnect) {\n      ctx.res.write(': connected\\n\\n');\n    }\n\n    const readableStream = result instanceof ReadableStream ? result : result.fullStream;\n    const reader = readableStream.getReader();\n\n    ctx.res.on('close', () => {\n      void reader.cancel('request aborted').catch(() => {});\n    });\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            ctx.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            ctx.res.write(`data: ${serialized.json}\\n\\n`);\n          } else {\n            ctx.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      ctx.res.end();\n    }\n  }\n\n  async getParams(route: ServerRoute, ctx: Context): Promise<ParsedRequestParams> {\n    const urlParams = (ctx.params || {}) as Record<string, string>;\n    // Koa's ctx.query is ParsedUrlQuery which is Record<string, string | string[]>\n    const queryParams = normalizeQueryParams((ctx.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 = ctx.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(ctx, maxFileSize);\n        } catch (error) {\n          this.mastra.getLogger()?.error('Failed to parse multipart form data', {\n            error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n          });\n          // Re-throw size limit errors, let others fall through to validation\n          if (error instanceof Error && error.message.toLowerCase().includes('size')) {\n            throw error;\n          }\n          bodyParseError = {\n            message: error instanceof Error ? error.message : 'Failed to parse multipart form data',\n          };\n        }\n      } else {\n        body = ctx.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 ctx - The Koa context object\n   * @param maxFileSize - Optional maximum file size in bytes\n   */\n  private parseMultipartFormData(ctx: Context, 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': ctx.headers['content-type'] as string,\n        },\n        limits: maxFileSize ? { fileSize: maxFileSize } : undefined,\n      });\n\n      busboy.on('file', (fieldname: string, file: NodeJS.ReadableStream) => {\n        const chunks: Buffer[] = [];\n        let limitExceeded = false;\n\n        file.on('data', (chunk: Buffer) => {\n          chunks.push(chunk);\n        });\n\n        file.on('limit', () => {\n          limitExceeded = true;\n          reject(new Error(`File size limit exceeded${maxFileSize ? ` (max: ${maxFileSize} bytes)` : ''}`));\n        });\n\n        file.on('end', () => {\n          if (!limitExceeded && isSafeObjectKey(fieldname)) {\n            result[fieldname] = Buffer.concat(chunks);\n          }\n        });\n      });\n\n      busboy.on('field', (fieldname: string, value: string) => {\n        if (!isSafeObjectKey(fieldname)) {\n          return;\n        }\n        // Try to parse JSON strings (like 'options')\n        try {\n          result[fieldname] = JSON.parse(value);\n        } catch {\n          result[fieldname] = value;\n        }\n      });\n\n      busboy.on('finish', () => {\n        resolve(result);\n      });\n\n      busboy.on('error', (error: Error) => {\n        reject(error);\n      });\n\n      // Pipe the raw request to busboy\n      ctx.req.pipe(busboy);\n    });\n  }\n\n  async sendResponse(route: ServerRoute, ctx: Context, result: unknown, prefix?: string): 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        ctx.set(key, value);\n      }\n      delete (result as any).__refreshHeaders;\n    }\n\n    if (route.responseType === 'json') {\n      // Explicitly set content-type and handle null/undefined to ensure proper JSON response\n      // Koa sets 204 No Content when body is null, but we want to return JSON null\n      ctx.type = 'application/json';\n      ctx.body = result === null || result === undefined ? JSON.stringify(null) : result;\n    } else if (route.responseType === 'stream') {\n      await this.stream(route, ctx, result as { fullStream: ReadableStream });\n    } else if (route.responseType === 'datastream-response') {\n      // Handle AI SDK Response objects - pipe Response.body to Koa response\n      // Tell Koa we're handling the response ourselves\n      ctx.respond = false;\n\n      const fetchResponse = result as globalThis.Response;\n      const headers: Record<string, string> = {};\n      fetchResponse.headers.forEach((value, key) => {\n        headers[key] = value;\n      });\n      ctx.res.writeHead(fetchResponse.status, headers);\n\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        ctx.res.once('error', onResError);\n\n        try {\n          while (true) {\n            const { done, value } = await reader.read();\n            if (done) break;\n            ctx.res.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          ctx.res.off('error', onResError);\n          ctx.res.end();\n        }\n      } else {\n        ctx.res.end();\n      }\n    } else if (route.responseType === 'mcp-http') {\n      // MCP Streamable HTTP transport\n      // Tell Koa we're handling the response ourselves\n      ctx.respond = false;\n\n      const { server, httpPath, mcpOptions: routeMcpOptions } = result as MCPHttpTransportResult;\n\n      try {\n        // Attach parsed body to raw request so MCP server's readJsonBody can use it\n        const rawReq = ctx.req as typeof ctx.req & { body?: unknown };\n        if (ctx.request.body !== undefined) {\n          rawReq.body = ctx.request.body;\n        }\n\n        // Merge class-level mcpOptions with route-specific options (route takes precedence)\n        const options = { ...this.mcpOptions, ...routeMcpOptions };\n\n        await server.startHTTP({\n          url: new URL(ctx.url, `http://${ctx.headers.host}`),\n          httpPath: `${resolvedPrefix}${httpPath}`,\n          req: rawReq,\n          res: ctx.res,\n          options: Object.keys(options).length > 0 ? options : undefined,\n        });\n        // Response handled by startHTTP\n      } catch {\n        if (!ctx.res.headersSent) {\n          ctx.res.writeHead(500, { 'Content-Type': 'application/json' });\n          ctx.res.end(\n            JSON.stringify({\n              jsonrpc: '2.0',\n              error: { code: -32603, message: 'Internal server error' },\n              id: null,\n            }),\n          );\n        }\n      }\n    } else if (route.responseType === 'mcp-sse') {\n      // MCP SSE transport\n      // Tell Koa we're handling the response ourselves\n      ctx.respond = false;\n\n      const { server, ssePath, messagePath } = result as MCPSseTransportResult;\n\n      try {\n        // Attach parsed body to raw request so MCP server's readJsonBody can use it\n        const rawReq = ctx.req as typeof ctx.req & { body?: unknown };\n        if (ctx.request.body !== undefined) {\n          rawReq.body = ctx.request.body;\n        }\n\n        await server.startSSE({\n          url: new URL(ctx.url, `http://${ctx.headers.host}`),\n          ssePath: `${resolvedPrefix}${ssePath}`,\n          messagePath: `${resolvedPrefix}${messagePath}`,\n          req: rawReq,\n          res: ctx.res,\n        });\n        // Response handled by startSSE\n      } catch {\n        if (!ctx.res.headersSent) {\n          ctx.res.writeHead(500, { 'Content-Type': 'application/json' });\n          ctx.res.end(JSON.stringify({ error: 'Error handling MCP SSE request' }));\n        }\n      }\n    } else {\n      ctx.status = 500;\n    }\n  }\n\n  async registerRoute(app: Koa, route: ServerRoute, { prefix: prefixParam }: { prefix?: string } = {}): Promise<void> {\n    // Default prefix to this.prefix if not provided, or empty string\n    const prefix = prefixParam ?? this.prefix ?? '';\n\n    const fullPath = `${prefix}${route.path}`;\n\n    // Convert Express-style :param to Koa-style :param (they're the same)\n    const koaPath = fullPath;\n\n    const group = this.getRouteDispatcherGroup(app);\n    group.routes.push({\n      route,\n      prefix,\n      koaPath,\n      pathRegex: this.pathToRegex(koaPath),\n      paramNames: this.extractParamNames(koaPath),\n    });\n  }\n\n  /**\n   * Convert Express-style path to regex for matching\n   */\n  private pathToRegex(path: string): RegExp {\n    // First replace :param with a placeholder that won't be affected by escaping\n    const PARAM_PLACEHOLDER = '\\x00PARAM\\x00';\n    const pathWithPlaceholders = path.replace(/:[^/]+/g, PARAM_PLACEHOLDER);\n\n    // Escape all regex meta-characters so the path is treated literally\n    const escapedPath = pathWithPlaceholders.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n    // Replace placeholders with capture groups and escape forward slashes\n    const regexPath = escapedPath.replace(new RegExp(PARAM_PLACEHOLDER, 'g'), '([^/]+)').replace(/\\//g, '\\\\/');\n\n    return new RegExp(`^${regexPath}$`);\n  }\n\n  /**\n   * Extract parameter names from path\n   */\n  private extractParamNames(path: string): string[] {\n    const matches = path.match(/:[^/]+/g) || [];\n    return matches.map(m => m.slice(1)); // Remove the leading ':'\n  }\n\n  async registerCustomApiRoutes(): Promise<void> {\n    const routes = await this.registerSchemaApiRoutes();\n    if (!(await this.buildCustomRouteHandler(routes))) return;\n\n    const server = this;\n    this.app.use(async function mastraCustomRouteDispatcher(ctx: Context, next: Next) {\n      // Check if this request matches a protected custom route and run auth\n      const path = String(ctx.path || '/');\n      const method = String(ctx.method || 'GET');\n      const matchedRoute = findMatchingCustomRoute(\n        path,\n        method,\n        server.customApiRoutes ?? server.mastra.getServer()?.apiRoutes,\n      );\n      const shouldRunCustomRouteAuth = isProtectedCustomRoute(path, method, server.customRouteAuthConfig);\n      const shouldRunCustomRouteFGA = !!matchedRoute?.route.fga;\n\n      const customRouteAbortController = new AbortController();\n      const abortCustomRoute = () => {\n        customRouteAbortController.abort();\n      };\n      const abortCustomRouteIfOpen = () => {\n        if (!ctx.res.writableEnded) {\n          abortCustomRoute();\n        }\n      };\n\n      ctx.res.once('close', abortCustomRouteIfOpen);\n      ctx.res.once('error', abortCustomRouteIfOpen);\n\n      try {\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 server.checkRouteAuth(serverRoute, {\n              path,\n              method,\n              getHeader: name => ctx.headers[name.toLowerCase()] as string | undefined,\n              getQuery: name => (ctx.query as Record<string, string>)[name],\n              requestContext: ctx.state.requestContext,\n              request: toWebRequest(ctx),\n              buildAuthorizeContext: () => toWebRequest(ctx),\n            });\n\n            if (authError) {\n              if (authError.headers) {\n                for (const [key, value] of Object.entries(authError.headers)) {\n                  ctx.set(key, value);\n                }\n              }\n\n              if (authError.error) {\n                ctx.status = authError.status;\n                ctx.body = { error: authError.error };\n                return;\n              }\n            }\n          }\n\n          const requestContext = ctx.state.requestContext;\n          // Check if any auth is configured (studio or server) for RBAC\n          const hasAuth = server.mastra.getStudio?.()?.auth || server.mastra.getServer()?.auth;\n          if (hasAuth) {\n            const hasPermission = await loadHasPermission();\n            if (hasPermission) {\n              const userPermissions = requestContext.get('mastra__userPermissions') as string[] | undefined;\n              const permissionError = server.checkRoutePermission(\n                serverRoute,\n                userPermissions,\n                hasPermission,\n                requestContext,\n              );\n              if (permissionError) {\n                ctx.status = permissionError.status;\n                ctx.body = {\n                  error: permissionError.error,\n                  message: permissionError.message,\n                };\n                return;\n              }\n            }\n          }\n\n          // Check FGA authorization (EE feature)\n          const fgaError = await checkRouteFGA(server.mastra, serverRoute, ctx.state.requestContext, {\n            ...(matchedRoute?.params ?? {}),\n            ...(ctx.query as Record<string, string>),\n            ...(typeof ctx.request.body === 'object' && ctx.request.body !== null\n              ? (ctx.request.body as Record<string, unknown>)\n              : {}),\n          });\n          if (fgaError) {\n            ctx.status = fgaError.status;\n            ctx.body = { error: fgaError.error, message: fgaError.message };\n            return;\n          }\n        }\n\n        const response = await server.handleCustomRouteRequest(\n          `${ctx.protocol}://${ctx.host}${ctx.originalUrl || ctx.url}`,\n          ctx.method,\n          ctx.headers as Record<string, string | string[] | undefined>,\n          ctx.request.body,\n          ctx.state.requestContext,\n          customRouteAbortController.signal,\n        );\n        if (!response) return next();\n        ctx.respond = false;\n        await server.writeCustomRouteResponse(response, ctx.res, customRouteAbortController.signal);\n      } finally {\n        ctx.res.off('close', abortCustomRouteIfOpen);\n        ctx.res.off('error', abortCustomRouteIfOpen);\n      }\n    });\n  }\n\n  registerContextMiddleware(): void {\n    this.app.use(this.createContextMiddleware());\n    this.app.use(async (ctx: Context, next: Next) => {\n      const path = String(ctx.path || '/');\n      const method = String(ctx.method || 'GET');\n      ctx.res.once('finish', () => {\n        this.warnIfUnregisteredChannelWebhook(path, method, ctx.res.statusCode);\n      });\n      await 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    const server = this;\n\n    this.app.use(async function mastraHttpLogger(ctx: Context, next: Next) {\n      if (!server.shouldLogRequest(ctx.path)) {\n        return next();\n      }\n\n      const start = Date.now();\n      const method = ctx.method;\n      const path = ctx.path;\n\n      await next();\n\n      const duration = Date.now() - start;\n      const status = ctx.status;\n      const level = server.httpLoggingConfig?.level || 'info';\n\n      const logData: Record<string, any> = {\n        method,\n        path,\n        status,\n        duration: `${duration}ms`,\n      };\n\n      if (server.httpLoggingConfig?.includeQueryParams) {\n        logData.query = ctx.query;\n      }\n\n      if (server.httpLoggingConfig?.includeHeaders) {\n        const headers = { ...ctx.headers };\n        const redactHeaders = server.httpLoggingConfig.redactHeaders || [];\n        redactHeaders.forEach((h: string) => {\n          const key = h.toLowerCase();\n          if (headers[key] !== undefined) {\n            headers[key] = '[REDACTED]';\n          }\n        });\n        logData.headers = headers;\n      }\n\n      server.logger[level](`${method} ${path} ${status} ${duration}ms`, logData);\n    });\n  }\n}\n"],"mappings":";;;;;;AAUA,SAASA,eAAa,KAAkC;CAGtD,MAAM,MAAM,GAFK,IAAI,YAAY,OAET,KADX,IAAI,QAAQ,cACW,IAAI;CAExC,MAAM,UAAU,IAAI,QAAQ;CAC5B,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,IAAI,OAAO,G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