{"version":3,"file":"index.cjs","names":["pkg","LRUCache","#rawConfig"],"sources":["../../../packages/_internals/auth/dist/ee-DXvSoTl7.js","../src/rbac-provider.ts","../../../packages/_internals/auth/dist/types/index.js","../../../packages/_internal-core/dist/logger/index.js","../../../packages/_internal-core/dist/base/index.js","../../../packages/_internals/auth/dist/provider/index.js","../src/types.ts","../src/auth-provider.ts"],"sourcesContent":["import { i as getSafeLicenseSummary, m as getEETelemetryFallbackDistinctId, p as captureEEEvent } from \"./capabilities-ZXD8uYsD.js\";\n//#region src/ee/interfaces/permissions.generated.ts\n/**\n* AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY\n*\n* This file is generated by packages/server/scripts/generate-permissions.ts\n* Run `pnpm generate:permissions` from packages/server to regenerate.\n*\n* Source of truth: SERVER_ROUTES in @mastra/server\n*/\n/**\n* All known API resources.\n* Derived from SERVER_ROUTES paths in @mastra/server.\n*/\nconst RESOURCES = [\n\t\"a2a\",\n\t\"agent-builder\",\n\t\"agent-controller\",\n\t\"agents\",\n\t\"auth\",\n\t\"background-tasks\",\n\t\"channels\",\n\t\"datasets\",\n\t\"embedders\",\n\t\"experiments\",\n\t\"infrastructure\",\n\t\"logs\",\n\t\"mcp\",\n\t\"memory\",\n\t\"observability\",\n\t\"processor-providers\",\n\t\"processors\",\n\t\"schedules\",\n\t\"scores\",\n\t\"stored-agents\",\n\t\"stored-mcp-clients\",\n\t\"stored-prompt-blocks\",\n\t\"stored-scorers\",\n\t\"stored-skills\",\n\t\"stored-workflows\",\n\t\"stored-workspaces\",\n\t\"system\",\n\t\"tool-providers\",\n\t\"tools\",\n\t\"vector\",\n\t\"vectors\",\n\t\"workflows\",\n\t\"workspaces\"\n];\n/**\n* All permission actions.\n* Derived from HTTP methods and route overrides:\n* - GET → read\n* - POST → write or execute (context-dependent)\n* - PUT/PATCH → write\n* - DELETE → delete\n* - Additional actions from explicit requiresPermission overrides\n*/\nconst ACTIONS = [\n\t\"create\",\n\t\"delete\",\n\t\"execute\",\n\t\"publish\",\n\t\"read\",\n\t\"share\",\n\t\"write\"\n];\n/**\n* All valid permission patterns.\n* Use `keyof typeof PERMISSION_PATTERNS` or the `PermissionPattern` type.\n*/\nconst PERMISSION_PATTERNS = {\n\t/** Full access to all resources and actions */\n\t\"*\": \"*\",\n\t/** Create all resources */\n\t\"*:create\": \"*:create\",\n\t/** Delete all resources */\n\t\"*:delete\": \"*:delete\",\n\t/** Execute all resources */\n\t\"*:execute\": \"*:execute\",\n\t/** Publish, activate, or restore all resources */\n\t\"*:publish\": \"*:publish\",\n\t/** View all resources */\n\t\"*:read\": \"*:read\",\n\t/** Change visibility/audience all resources */\n\t\"*:share\": \"*:share\",\n\t/** Create and modify all resources */\n\t\"*:write\": \"*:write\",\n\t/** Full access to agent-to-agent communication */\n\t\"a2a:*\": \"a2a:*\",\n\t/** Full access to agent builder */\n\t\"agent-builder:*\": \"agent-builder:*\",\n\t/** Full access to agent controller sessions */\n\t\"agent-controller:*\": \"agent-controller:*\",\n\t/** Full access to agents */\n\t\"agents:*\": \"agents:*\",\n\t/** Full access to auth */\n\t\"auth:*\": \"auth:*\",\n\t/** Full access to background tasks */\n\t\"background-tasks:*\": \"background-tasks:*\",\n\t/** Full access to channels */\n\t\"channels:*\": \"channels:*\",\n\t/** Full access to datasets */\n\t\"datasets:*\": \"datasets:*\",\n\t/** Full access to embedders */\n\t\"embedders:*\": \"embedders:*\",\n\t/** Full access to experiments */\n\t\"experiments:*\": \"experiments:*\",\n\t/** Full access to infrastructure */\n\t\"infrastructure:*\": \"infrastructure:*\",\n\t/** Full access to logs */\n\t\"logs:*\": \"logs:*\",\n\t/** Full access to MCP servers */\n\t\"mcp:*\": \"mcp:*\",\n\t/** Full access to memory and threads */\n\t\"memory:*\": \"memory:*\",\n\t/** Full access to traces and spans */\n\t\"observability:*\": \"observability:*\",\n\t/** Full access to processor-providers */\n\t\"processor-providers:*\": \"processor-providers:*\",\n\t/** Full access to processors */\n\t\"processors:*\": \"processors:*\",\n\t/** Full access to schedules */\n\t\"schedules:*\": \"schedules:*\",\n\t/** Full access to evaluation scores */\n\t\"scores:*\": \"scores:*\",\n\t/** Full access to stored agents */\n\t\"stored-agents:*\": \"stored-agents:*\",\n\t/** Full access to stored MCP clients */\n\t\"stored-mcp-clients:*\": \"stored-mcp-clients:*\",\n\t/** Full access to stored prompt blocks */\n\t\"stored-prompt-blocks:*\": \"stored-prompt-blocks:*\",\n\t/** Full access to stored scorers */\n\t\"stored-scorers:*\": \"stored-scorers:*\",\n\t/** Full access to stored skills */\n\t\"stored-skills:*\": \"stored-skills:*\",\n\t/** Full access to stored workflows */\n\t\"stored-workflows:*\": \"stored-workflows:*\",\n\t/** Full access to stored workspaces */\n\t\"stored-workspaces:*\": \"stored-workspaces:*\",\n\t/** Full access to system info */\n\t\"system:*\": \"system:*\",\n\t/** Full access to tool-providers */\n\t\"tool-providers:*\": \"tool-providers:*\",\n\t/** Full access to tools */\n\t\"tools:*\": \"tools:*\",\n\t/** Full access to vector stores */\n\t\"vector:*\": \"vector:*\",\n\t/** Full access to vectors */\n\t\"vectors:*\": \"vectors:*\",\n\t/** Full access to workflows */\n\t\"workflows:*\": \"workflows:*\",\n\t/** Full access to workspaces */\n\t\"workspaces:*\": \"workspaces:*\",\n\t/** View agent-to-agent communication */\n\t\"a2a:read\": \"a2a:read\",\n\t/** Create and modify agent-to-agent communication */\n\t\"a2a:write\": \"a2a:write\",\n\t/** Execute agent builder */\n\t\"agent-builder:execute\": \"agent-builder:execute\",\n\t/** View agent builder */\n\t\"agent-builder:read\": \"agent-builder:read\",\n\t/** Create and modify agent builder */\n\t\"agent-builder:write\": \"agent-builder:write\",\n\t/** Execute agent controller sessions */\n\t\"agent-controller:execute\": \"agent-controller:execute\",\n\t/** View agent controller sessions */\n\t\"agent-controller:read\": \"agent-controller:read\",\n\t/** Create agents */\n\t\"agents:create\": \"agents:create\",\n\t/** Delete agents */\n\t\"agents:delete\": \"agents:delete\",\n\t/** Execute agents */\n\t\"agents:execute\": \"agents:execute\",\n\t/** View agents */\n\t\"agents:read\": \"agents:read\",\n\t/** Create and modify agents */\n\t\"agents:write\": \"agents:write\",\n\t/** View auth */\n\t\"auth:read\": \"auth:read\",\n\t/** View background tasks */\n\t\"background-tasks:read\": \"background-tasks:read\",\n\t/** View channels */\n\t\"channels:read\": \"channels:read\",\n\t/** Create and modify channels */\n\t\"channels:write\": \"channels:write\",\n\t/** Delete datasets */\n\t\"datasets:delete\": \"datasets:delete\",\n\t/** Execute datasets */\n\t\"datasets:execute\": \"datasets:execute\",\n\t/** View datasets */\n\t\"datasets:read\": \"datasets:read\",\n\t/** Create and modify datasets */\n\t\"datasets:write\": \"datasets:write\",\n\t/** View embedders */\n\t\"embedders:read\": \"embedders:read\",\n\t/** View experiments */\n\t\"experiments:read\": \"experiments:read\",\n\t/** View infrastructure */\n\t\"infrastructure:read\": \"infrastructure:read\",\n\t/** View logs */\n\t\"logs:read\": \"logs:read\",\n\t/** Execute MCP servers */\n\t\"mcp:execute\": \"mcp:execute\",\n\t/** View MCP servers */\n\t\"mcp:read\": \"mcp:read\",\n\t/** Create and modify MCP servers */\n\t\"mcp:write\": \"mcp:write\",\n\t/** Delete memory and threads */\n\t\"memory:delete\": \"memory:delete\",\n\t/** Execute memory and threads */\n\t\"memory:execute\": \"memory:execute\",\n\t/** View memory and threads */\n\t\"memory:read\": \"memory:read\",\n\t/** Create and modify memory and threads */\n\t\"memory:write\": \"memory:write\",\n\t/** View traces and spans */\n\t\"observability:read\": \"observability:read\",\n\t/** Create and modify traces and spans */\n\t\"observability:write\": \"observability:write\",\n\t/** View processor-providers */\n\t\"processor-providers:read\": \"processor-providers:read\",\n\t/** Execute processors */\n\t\"processors:execute\": \"processors:execute\",\n\t/** View processors */\n\t\"processors:read\": \"processors:read\",\n\t/** Delete schedules */\n\t\"schedules:delete\": \"schedules:delete\",\n\t/** Execute schedules */\n\t\"schedules:execute\": \"schedules:execute\",\n\t/** View schedules */\n\t\"schedules:read\": \"schedules:read\",\n\t/** Create and modify schedules */\n\t\"schedules:write\": \"schedules:write\",\n\t/** View evaluation scores */\n\t\"scores:read\": \"scores:read\",\n\t/** Create and modify evaluation scores */\n\t\"scores:write\": \"scores:write\",\n\t/** Delete stored agents */\n\t\"stored-agents:delete\": \"stored-agents:delete\",\n\t/** Publish, activate, or restore stored agents */\n\t\"stored-agents:publish\": \"stored-agents:publish\",\n\t/** View stored agents */\n\t\"stored-agents:read\": \"stored-agents:read\",\n\t/** Create and modify stored agents */\n\t\"stored-agents:write\": \"stored-agents:write\",\n\t/** Delete stored MCP clients */\n\t\"stored-mcp-clients:delete\": \"stored-mcp-clients:delete\",\n\t/** Publish, activate, or restore stored MCP clients */\n\t\"stored-mcp-clients:publish\": \"stored-mcp-clients:publish\",\n\t/** View stored MCP clients */\n\t\"stored-mcp-clients:read\": \"stored-mcp-clients:read\",\n\t/** Create and modify stored MCP clients */\n\t\"stored-mcp-clients:write\": \"stored-mcp-clients:write\",\n\t/** Delete stored prompt blocks */\n\t\"stored-prompt-blocks:delete\": \"stored-prompt-blocks:delete\",\n\t/** Publish, activate, or restore stored prompt blocks */\n\t\"stored-prompt-blocks:publish\": \"stored-prompt-blocks:publish\",\n\t/** View stored prompt blocks */\n\t\"stored-prompt-blocks:read\": \"stored-prompt-blocks:read\",\n\t/** Create and modify stored prompt blocks */\n\t\"stored-prompt-blocks:write\": \"stored-prompt-blocks:write\",\n\t/** Delete stored scorers */\n\t\"stored-scorers:delete\": \"stored-scorers:delete\",\n\t/** Publish, activate, or restore stored scorers */\n\t\"stored-scorers:publish\": \"stored-scorers:publish\",\n\t/** View stored scorers */\n\t\"stored-scorers:read\": \"stored-scorers:read\",\n\t/** Create and modify stored scorers */\n\t\"stored-scorers:write\": \"stored-scorers:write\",\n\t/** Delete stored skills */\n\t\"stored-skills:delete\": \"stored-skills:delete\",\n\t/** Publish, activate, or restore stored skills */\n\t\"stored-skills:publish\": \"stored-skills:publish\",\n\t/** View stored skills */\n\t\"stored-skills:read\": \"stored-skills:read\",\n\t/** Create and modify stored skills */\n\t\"stored-skills:write\": \"stored-skills:write\",\n\t/** View stored workflows */\n\t\"stored-workflows:read\": \"stored-workflows:read\",\n\t/** Create and modify stored workflows */\n\t\"stored-workflows:write\": \"stored-workflows:write\",\n\t/** Delete stored workspaces */\n\t\"stored-workspaces:delete\": \"stored-workspaces:delete\",\n\t/** View stored workspaces */\n\t\"stored-workspaces:read\": \"stored-workspaces:read\",\n\t/** Create and modify stored workspaces */\n\t\"stored-workspaces:write\": \"stored-workspaces:write\",\n\t/** View system info */\n\t\"system:read\": \"system:read\",\n\t/** Delete tool-providers */\n\t\"tool-providers:delete\": \"tool-providers:delete\",\n\t/** View tool-providers */\n\t\"tool-providers:read\": \"tool-providers:read\",\n\t/** Create and modify tool-providers */\n\t\"tool-providers:write\": \"tool-providers:write\",\n\t/** Execute tools */\n\t\"tools:execute\": \"tools:execute\",\n\t/** View tools */\n\t\"tools:read\": \"tools:read\",\n\t/** Delete vector stores */\n\t\"vector:delete\": \"vector:delete\",\n\t/** Execute vector stores */\n\t\"vector:execute\": \"vector:execute\",\n\t/** View vector stores */\n\t\"vector:read\": \"vector:read\",\n\t/** Create and modify vector stores */\n\t\"vector:write\": \"vector:write\",\n\t/** View vectors */\n\t\"vectors:read\": \"vectors:read\",\n\t/** Delete workflows */\n\t\"workflows:delete\": \"workflows:delete\",\n\t/** Execute workflows */\n\t\"workflows:execute\": \"workflows:execute\",\n\t/** View workflows */\n\t\"workflows:read\": \"workflows:read\",\n\t/** Create and modify workflows */\n\t\"workflows:write\": \"workflows:write\",\n\t/** Delete workspaces */\n\t\"workspaces:delete\": \"workspaces:delete\",\n\t/** View workspaces */\n\t\"workspaces:read\": \"workspaces:read\",\n\t/** Create and modify workspaces */\n\t\"workspaces:write\": \"workspaces:write\",\n\t/** Full access to all stored resource families */\n\t\"stored:*\": \"stored:*\",\n\t/** View all stored resource families */\n\t\"stored:read\": \"stored:read\",\n\t/** Create and modify all stored resource families */\n\t\"stored:write\": \"stored:write\",\n\t/** Delete all stored resource families */\n\t\"stored:delete\": \"stored:delete\",\n\t/** Change visibility/audience stored agents */\n\t\"stored-agents:share\": \"stored-agents:share\",\n\t/** Change visibility/audience stored skills */\n\t\"stored-skills:share\": \"stored-skills:share\"\n};\n/**\n* All valid resource:action permission combinations (excludes wildcards).\n*/\nconst PERMISSIONS = [\n\t\"a2a:read\",\n\t\"a2a:write\",\n\t\"agent-builder:execute\",\n\t\"agent-builder:read\",\n\t\"agent-builder:write\",\n\t\"agent-controller:execute\",\n\t\"agent-controller:read\",\n\t\"agents:create\",\n\t\"agents:delete\",\n\t\"agents:execute\",\n\t\"agents:read\",\n\t\"agents:write\",\n\t\"auth:read\",\n\t\"background-tasks:read\",\n\t\"channels:read\",\n\t\"channels:write\",\n\t\"datasets:delete\",\n\t\"datasets:execute\",\n\t\"datasets:read\",\n\t\"datasets:write\",\n\t\"embedders:read\",\n\t\"experiments:read\",\n\t\"infrastructure:read\",\n\t\"logs:read\",\n\t\"mcp:execute\",\n\t\"mcp:read\",\n\t\"mcp:write\",\n\t\"memory:delete\",\n\t\"memory:execute\",\n\t\"memory:read\",\n\t\"memory:write\",\n\t\"observability:read\",\n\t\"observability:write\",\n\t\"processor-providers:read\",\n\t\"processors:execute\",\n\t\"processors:read\",\n\t\"schedules:delete\",\n\t\"schedules:execute\",\n\t\"schedules:read\",\n\t\"schedules:write\",\n\t\"scores:read\",\n\t\"scores:write\",\n\t\"stored-agents:delete\",\n\t\"stored-agents:publish\",\n\t\"stored-agents:read\",\n\t\"stored-agents:write\",\n\t\"stored-mcp-clients:delete\",\n\t\"stored-mcp-clients:publish\",\n\t\"stored-mcp-clients:read\",\n\t\"stored-mcp-clients:write\",\n\t\"stored-prompt-blocks:delete\",\n\t\"stored-prompt-blocks:publish\",\n\t\"stored-prompt-blocks:read\",\n\t\"stored-prompt-blocks:write\",\n\t\"stored-scorers:delete\",\n\t\"stored-scorers:publish\",\n\t\"stored-scorers:read\",\n\t\"stored-scorers:write\",\n\t\"stored-skills:delete\",\n\t\"stored-skills:publish\",\n\t\"stored-skills:read\",\n\t\"stored-skills:write\",\n\t\"stored-workflows:read\",\n\t\"stored-workflows:write\",\n\t\"stored-workspaces:delete\",\n\t\"stored-workspaces:read\",\n\t\"stored-workspaces:write\",\n\t\"system:read\",\n\t\"tool-providers:delete\",\n\t\"tool-providers:read\",\n\t\"tool-providers:write\",\n\t\"tools:execute\",\n\t\"tools:read\",\n\t\"vector:delete\",\n\t\"vector:execute\",\n\t\"vector:read\",\n\t\"vector:write\",\n\t\"vectors:read\",\n\t\"workflows:delete\",\n\t\"workflows:execute\",\n\t\"workflows:read\",\n\t\"workflows:write\",\n\t\"workspaces:delete\",\n\t\"workspaces:read\",\n\t\"workspaces:write\"\n];\n/**\n* Type-safe constants for Mastra-owned FGA permissions.\n*\n* These values are generated from server routes and can be used wherever\n* Mastra checks or maps FGA permissions.\n*/\nconst MastraFGAPermissions = {\n\t/** View agent-to-agent communication */\n\tA2A_READ: \"a2a:read\",\n\t/** Create and modify agent-to-agent communication */\n\tA2A_WRITE: \"a2a:write\",\n\t/** Execute agent builder */\n\tAGENT_BUILDER_EXECUTE: \"agent-builder:execute\",\n\t/** View agent builder */\n\tAGENT_BUILDER_READ: \"agent-builder:read\",\n\t/** Create and modify agent builder */\n\tAGENT_BUILDER_WRITE: \"agent-builder:write\",\n\t/** Execute agent controller sessions */\n\tAGENT_CONTROLLER_EXECUTE: \"agent-controller:execute\",\n\t/** View agent controller sessions */\n\tAGENT_CONTROLLER_READ: \"agent-controller:read\",\n\t/** Create agents */\n\tAGENTS_CREATE: \"agents:create\",\n\t/** Delete agents */\n\tAGENTS_DELETE: \"agents:delete\",\n\t/** Execute agents */\n\tAGENTS_EXECUTE: \"agents:execute\",\n\t/** View agents */\n\tAGENTS_READ: \"agents:read\",\n\t/** Create and modify agents */\n\tAGENTS_WRITE: \"agents:write\",\n\t/** View auth */\n\tAUTH_READ: \"auth:read\",\n\t/** View background tasks */\n\tBACKGROUND_TASKS_READ: \"background-tasks:read\",\n\t/** View channels */\n\tCHANNELS_READ: \"channels:read\",\n\t/** Create and modify channels */\n\tCHANNELS_WRITE: \"channels:write\",\n\t/** Delete datasets */\n\tDATASETS_DELETE: \"datasets:delete\",\n\t/** Execute datasets */\n\tDATASETS_EXECUTE: \"datasets:execute\",\n\t/** View datasets */\n\tDATASETS_READ: \"datasets:read\",\n\t/** Create and modify datasets */\n\tDATASETS_WRITE: \"datasets:write\",\n\t/** View embedders */\n\tEMBEDDERS_READ: \"embedders:read\",\n\t/** View experiments */\n\tEXPERIMENTS_READ: \"experiments:read\",\n\t/** View infrastructure */\n\tINFRASTRUCTURE_READ: \"infrastructure:read\",\n\t/** View logs */\n\tLOGS_READ: \"logs:read\",\n\t/** Execute MCP servers */\n\tMCP_EXECUTE: \"mcp:execute\",\n\t/** View MCP servers */\n\tMCP_READ: \"mcp:read\",\n\t/** Create and modify MCP servers */\n\tMCP_WRITE: \"mcp:write\",\n\t/** Delete memory and threads */\n\tMEMORY_DELETE: \"memory:delete\",\n\t/** Execute memory and threads */\n\tMEMORY_EXECUTE: \"memory:execute\",\n\t/** View memory and threads */\n\tMEMORY_READ: \"memory:read\",\n\t/** Create and modify memory and threads */\n\tMEMORY_WRITE: \"memory:write\",\n\t/** View traces and spans */\n\tOBSERVABILITY_READ: \"observability:read\",\n\t/** Create and modify traces and spans */\n\tOBSERVABILITY_WRITE: \"observability:write\",\n\t/** View processor-providers */\n\tPROCESSOR_PROVIDERS_READ: \"processor-providers:read\",\n\t/** Execute processors */\n\tPROCESSORS_EXECUTE: \"processors:execute\",\n\t/** View processors */\n\tPROCESSORS_READ: \"processors:read\",\n\t/** Delete schedules */\n\tSCHEDULES_DELETE: \"schedules:delete\",\n\t/** Execute schedules */\n\tSCHEDULES_EXECUTE: \"schedules:execute\",\n\t/** View schedules */\n\tSCHEDULES_READ: \"schedules:read\",\n\t/** Create and modify schedules */\n\tSCHEDULES_WRITE: \"schedules:write\",\n\t/** View evaluation scores */\n\tSCORES_READ: \"scores:read\",\n\t/** Create and modify evaluation scores */\n\tSCORES_WRITE: \"scores:write\",\n\t/** Delete stored agents */\n\tSTORED_AGENTS_DELETE: \"stored-agents:delete\",\n\t/** Publish, activate, or restore stored agents */\n\tSTORED_AGENTS_PUBLISH: \"stored-agents:publish\",\n\t/** View stored agents */\n\tSTORED_AGENTS_READ: \"stored-agents:read\",\n\t/** Create and modify stored agents */\n\tSTORED_AGENTS_WRITE: \"stored-agents:write\",\n\t/** Delete stored MCP clients */\n\tSTORED_MCP_CLIENTS_DELETE: \"stored-mcp-clients:delete\",\n\t/** Publish, activate, or restore stored MCP clients */\n\tSTORED_MCP_CLIENTS_PUBLISH: \"stored-mcp-clients:publish\",\n\t/** View stored MCP clients */\n\tSTORED_MCP_CLIENTS_READ: \"stored-mcp-clients:read\",\n\t/** Create and modify stored MCP clients */\n\tSTORED_MCP_CLIENTS_WRITE: \"stored-mcp-clients:write\",\n\t/** Delete stored prompt blocks */\n\tSTORED_PROMPT_BLOCKS_DELETE: \"stored-prompt-blocks:delete\",\n\t/** Publish, activate, or restore stored prompt blocks */\n\tSTORED_PROMPT_BLOCKS_PUBLISH: \"stored-prompt-blocks:publish\",\n\t/** View stored prompt blocks */\n\tSTORED_PROMPT_BLOCKS_READ: \"stored-prompt-blocks:read\",\n\t/** Create and modify stored prompt blocks */\n\tSTORED_PROMPT_BLOCKS_WRITE: \"stored-prompt-blocks:write\",\n\t/** Delete stored scorers */\n\tSTORED_SCORERS_DELETE: \"stored-scorers:delete\",\n\t/** Publish, activate, or restore stored scorers */\n\tSTORED_SCORERS_PUBLISH: \"stored-scorers:publish\",\n\t/** View stored scorers */\n\tSTORED_SCORERS_READ: \"stored-scorers:read\",\n\t/** Create and modify stored scorers */\n\tSTORED_SCORERS_WRITE: \"stored-scorers:write\",\n\t/** Delete stored skills */\n\tSTORED_SKILLS_DELETE: \"stored-skills:delete\",\n\t/** Publish, activate, or restore stored skills */\n\tSTORED_SKILLS_PUBLISH: \"stored-skills:publish\",\n\t/** View stored skills */\n\tSTORED_SKILLS_READ: \"stored-skills:read\",\n\t/** Create and modify stored skills */\n\tSTORED_SKILLS_WRITE: \"stored-skills:write\",\n\t/** View stored workflows */\n\tSTORED_WORKFLOWS_READ: \"stored-workflows:read\",\n\t/** Create and modify stored workflows */\n\tSTORED_WORKFLOWS_WRITE: \"stored-workflows:write\",\n\t/** Delete stored workspaces */\n\tSTORED_WORKSPACES_DELETE: \"stored-workspaces:delete\",\n\t/** View stored workspaces */\n\tSTORED_WORKSPACES_READ: \"stored-workspaces:read\",\n\t/** Create and modify stored workspaces */\n\tSTORED_WORKSPACES_WRITE: \"stored-workspaces:write\",\n\t/** View system info */\n\tSYSTEM_READ: \"system:read\",\n\t/** Delete tool-providers */\n\tTOOL_PROVIDERS_DELETE: \"tool-providers:delete\",\n\t/** View tool-providers */\n\tTOOL_PROVIDERS_READ: \"tool-providers:read\",\n\t/** Create and modify tool-providers */\n\tTOOL_PROVIDERS_WRITE: \"tool-providers:write\",\n\t/** Execute tools */\n\tTOOLS_EXECUTE: \"tools:execute\",\n\t/** View tools */\n\tTOOLS_READ: \"tools:read\",\n\t/** Delete vector stores */\n\tVECTOR_DELETE: \"vector:delete\",\n\t/** Execute vector stores */\n\tVECTOR_EXECUTE: \"vector:execute\",\n\t/** View vector stores */\n\tVECTOR_READ: \"vector:read\",\n\t/** Create and modify vector stores */\n\tVECTOR_WRITE: \"vector:write\",\n\t/** View vectors */\n\tVECTORS_READ: \"vectors:read\",\n\t/** Delete workflows */\n\tWORKFLOWS_DELETE: \"workflows:delete\",\n\t/** Execute workflows */\n\tWORKFLOWS_EXECUTE: \"workflows:execute\",\n\t/** View workflows */\n\tWORKFLOWS_READ: \"workflows:read\",\n\t/** Create and modify workflows */\n\tWORKFLOWS_WRITE: \"workflows:write\",\n\t/** Delete workspaces */\n\tWORKSPACES_DELETE: \"workspaces:delete\",\n\t/** View workspaces */\n\tWORKSPACES_READ: \"workspaces:read\",\n\t/** Create and modify workspaces */\n\tWORKSPACES_WRITE: \"workspaces:write\"\n};\n/**\n* Validates that a string is a valid permission pattern.\n* Useful for runtime validation of permission strings.\n*/\nfunction isValidPermissionPattern(pattern) {\n\treturn pattern in PERMISSION_PATTERNS;\n}\n/**\n* Validates that all permissions in an array are valid patterns.\n*/\nfunction validatePermissions(permissions) {\n\treturn permissions.every(isValidPermissionPattern);\n}\n//#endregion\n//#region src/ee/fga-check.ts\n/**\n* FGA enforcement utility for checking fine-grained authorization.\n*\n* @license Mastra Enterprise License - see ee/LICENSE\n*/\nfunction mergeFGAContext({ context, requestContext, metadata }) {\n\tconst mergedContext = { ...context };\n\tif (requestContext) mergedContext.requestContext = requestContext;\n\tif (metadata || context?.metadata) mergedContext.metadata = {\n\t\t...context?.metadata ?? {},\n\t\t...metadata ?? {}\n\t};\n\treturn Object.keys(mergedContext).length > 0 ? mergedContext : void 0;\n}\nfunction isActorSignal(actor) {\n\tif (actor === true) return true;\n\tif (typeof actor !== \"object\" || actor === null) return false;\n\tconst candidate = actor;\n\treturn candidate.actorKind === \"system\" && (candidate.sourceWorkflow === void 0 || typeof candidate.sourceWorkflow === \"string\");\n}\nfunction getAgentFGAResourceId(agentId) {\n\treturn agentId;\n}\nfunction getWorkflowFGAResourceId(workflowId) {\n\treturn workflowId;\n}\nfunction getStandaloneToolFGAResourceId(toolName) {\n\treturn toolName;\n}\nfunction getAgentToolFGAResourceId(agentId, toolName) {\n\treturn `${agentId}:${toolName}`;\n}\nfunction getMCPToolFGAResourceId(serverName, toolName) {\n\treturn JSON.stringify([serverName, toolName]);\n}\n/**\n* Check fine-grained authorization for a resource.\n*\n* No-op if no FGA provider is configured (backward compatibility).\n* Delegates to fgaProvider.require() which throws FGADeniedError if denied.\n*/\nasync function checkFGA(options) {\n\tawait requireFGA(options);\n}\n/**\n* Require fine-grained authorization for a resource.\n*\n* No-op if no FGA provider is configured. When FGA is configured, a missing\n* user fails closed.\n*/\nasync function requireFGA(options) {\n\tconst { fgaProvider, user, resource, permission, context, requestContext, metadata, actor } = options;\n\tif (!fgaProvider) return;\n\tconst fgaContext = mergeFGAContext({\n\t\tcontext,\n\t\trequestContext,\n\t\tmetadata\n\t});\n\tconst license = getSafeLicenseSummary();\n\tif (isActorSignal(actor)) {\n\t\tconst tenantOrganizationId = fgaContext?.requestContext?.get(\"organizationId\");\n\t\tif (typeof tenantOrganizationId !== \"string\" || tenantOrganizationId.length === 0) throw new FGADeniedError(user, resource, permission, \"trusted actor requires organizationId / tenant scope\");\n\t\tconst sourceWorkflow = (actor === true ? void 0 : actor.sourceWorkflow) ?? (typeof fgaContext?.metadata?.[\"sourceWorkflow\"] === \"string\" ? fgaContext.metadata[\"sourceWorkflow\"] : void 0);\n\t\tconst providerEnforced = typeof fgaProvider.requireActor === \"function\";\n\t\tif (providerEnforced) await fgaProvider.requireActor(actor, {\n\t\t\tresource,\n\t\t\tpermission,\n\t\t\t...fgaContext ? { context: fgaContext } : {}\n\t\t});\n\t\ttry {\n\t\t\tcaptureEEEvent(\"ee_feature_used\", license.anonymousId || getEETelemetryFallbackDistinctId(), {\n\t\t\t\tfeature: \"fga\",\n\t\t\t\tactor_kind: \"system\",\n\t\t\t\tactor_authorized_by: providerEnforced ? \"provider\" : \"bypass\",\n\t\t\t\tresource_type: resource.type,\n\t\t\t\tresource_id: resource.id,\n\t\t\t\tpermission,\n\t\t\t\tuser_id: null,\n\t\t\t\torganization_membership_id: null,\n\t\t\t\tsource_workflow: sourceWorkflow,\n\t\t\t\tlicense_valid: license.valid,\n\t\t\t\tlicense_hash: license.licenseHash,\n\t\t\t\tis_dev_environment: license.isDevEnvironment\n\t\t\t});\n\t\t} catch {}\n\t\treturn;\n\t}\n\tif (!user) throw new FGADeniedError(user, resource, permission, \"authenticated user is required\");\n\tawait fgaProvider.require(user, fgaContext ? {\n\t\tresource,\n\t\tpermission,\n\t\tcontext: fgaContext\n\t} : {\n\t\tresource,\n\t\tpermission\n\t});\n\ttry {\n\t\tcaptureEEEvent(\"ee_feature_used\", user?.id || license.anonymousId || getEETelemetryFallbackDistinctId(), {\n\t\t\tfeature: \"fga\",\n\t\t\tactor_kind: \"user\",\n\t\t\tresource_type: resource.type,\n\t\t\tresource_id: resource.id,\n\t\t\tpermission,\n\t\t\tuser_id: user?.id ?? null,\n\t\t\torganization_membership_id: user?.organizationMembershipId ?? null,\n\t\t\tlicense_valid: license.valid,\n\t\t\tlicense_hash: license.licenseHash,\n\t\t\tis_dev_environment: license.isDevEnvironment\n\t\t});\n\t} catch {}\n}\n/**\n* Error thrown when an FGA authorization check is denied.\n*/\nvar FGADeniedError = class extends Error {\n\tuser;\n\tresource;\n\tpermission;\n\tstatus;\n\tconstructor(user, resource, permission, reason) {\n\t\tconst userId = user?.id || user?.workosId || \"unknown\";\n\t\tconst permissionLabel = Array.isArray(permission) ? `any of [${permission.join(\", \")}]` : permission;\n\t\tsuper(reason ? `FGA authorization denied: ${reason}` : `FGA authorization denied: user ${userId} cannot ${permissionLabel} on ${resource.type}:${resource.id}`);\n\t\tthis.name = \"FGADeniedError\";\n\t\tthis.user = user;\n\t\tthis.resource = resource;\n\t\tthis.permission = permission;\n\t\tthis.status = 403;\n\t}\n};\n//#endregion\n//#region src/ee/defaults/roles.ts\n/**\n* Default role definitions for Studio.\n*\n* These roles provide a sensible starting point for most applications:\n* - **owner**: Full access to everything\n* - **admin**: Manage agents, workflows, and users\n* - **member**: Execute agents and workflows, read-only settings\n* - **viewer**: Read-only access\n*\n* Permission patterns:\n* - `*` - Full access to everything\n* - `resource:*` - All actions on a specific resource\n* - `*:action` - An action across all resources (e.g., `*:read` for read-only)\n*/\nconst DEFAULT_ROLES = [\n\t{\n\t\tid: \"owner\",\n\t\tname: \"Owner\",\n\t\tdescription: \"Full access to all features and settings\",\n\t\tpermissions: [\"*\"]\n\t},\n\t{\n\t\tid: \"admin\",\n\t\tname: \"Admin\",\n\t\tdescription: \"Manage agents, workflows, and team members\",\n\t\tpermissions: [\n\t\t\t\"*:read\",\n\t\t\t\"*:write\",\n\t\t\t\"*:execute\",\n\t\t\t\"*:publish\",\n\t\t\t\"*:share\"\n\t\t]\n\t},\n\t{\n\t\tid: \"member\",\n\t\tname: \"Member\",\n\t\tdescription: \"Execute agents and workflows\",\n\t\tpermissions: [\"*:read\", \"*:execute\"]\n\t},\n\t{\n\t\tid: \"viewer\",\n\t\tname: \"Viewer\",\n\t\tdescription: \"Read-only access\",\n\t\tpermissions: [\"*:read\"]\n\t}\n];\n/**\n* Get role by ID from default roles.\n*\n* @param roleId - Role ID to find\n* @returns Role definition or undefined\n*/\nfunction getDefaultRole(roleId) {\n\treturn DEFAULT_ROLES.find((role) => role.id === roleId);\n}\n/**\n* Resolve all permissions for a set of role IDs.\n*\n* Handles role inheritance and deduplication.\n*\n* @param roleIds - Role IDs to resolve\n* @param roles - Role definitions (defaults to DEFAULT_ROLES)\n* @returns Array of resolved permissions\n*/\nfunction resolvePermissions(roleIds, roles = DEFAULT_ROLES) {\n\tconst permissions = /* @__PURE__ */ new Set();\n\tconst visited = /* @__PURE__ */ new Set();\n\tfunction resolveRole(roleId) {\n\t\tif (visited.has(roleId)) return;\n\t\tvisited.add(roleId);\n\t\tconst role = roles.find((r) => r.id === roleId);\n\t\tif (!role) return;\n\t\tfor (const permission of role.permissions) permissions.add(permission);\n\t\tif (role.inherits) for (const inheritedRoleId of role.inherits) resolveRole(inheritedRoleId);\n\t}\n\tfor (const roleId of roleIds) resolveRole(roleId);\n\treturn Array.from(permissions);\n}\n/**\n* Compound resource keys that expand to a set of per-family resources.\n* A granted `stored:<action>` is treated as matching any `stored-<family>:<action>`\n* (and `stored:*` matches any `stored-<family>:*`).\n*/\nconst RESOURCE_EXPANSIONS = { stored: [\n\t\"stored-agents\",\n\t\"stored-mcp-clients\",\n\t\"stored-prompt-blocks\",\n\t\"stored-scorers\",\n\t\"stored-skills\",\n\t\"stored-workspaces\"\n] };\n/**\n* Check if a permission matches (including wildcard support).\n*\n* Permission format: `{resource}:{action}[:{resource-id}]`\n*\n* Examples:\n* - `*` matches everything\n* - `agents:*` matches `agents:read`, `agents:read:my-agent`\n* - `*:read` matches `agents:read`, `workflows:read` (action across all resources)\n* - `agents:read` matches `agents:read`, `agents:read:my-agent`\n* - `agents:read:my-agent` matches only `agents:read:my-agent`\n* - `agents:*:my-agent` matches `agents:read:my-agent`, `agents:write:my-agent`\n*\n* @param userPermission - Permission the user has\n* @param requiredPermission - Permission being checked\n* @returns True if permission matches\n*/\nfunction matchesPermission(userPermission, requiredPermission) {\n\tif (userPermission === \"*\") return true;\n\tconst grantedParts = userPermission.split(\":\");\n\tconst requiredParts = requiredPermission.split(\":\");\n\tconst expandedFamilies = RESOURCE_EXPANSIONS[grantedParts[0] ?? \"\"];\n\tif (expandedFamilies && expandedFamilies.includes(requiredParts[0] ?? \"\")) return matchesPermission([requiredParts[0], ...grantedParts.slice(1)].join(\":\"), requiredPermission);\n\tif (grantedParts.length < 2 || requiredParts.length < 2) return userPermission === requiredPermission;\n\tconst [grantedResource, grantedAction, grantedId] = grantedParts;\n\tconst [requiredResource, requiredAction, requiredId] = requiredParts;\n\tif (grantedResource === \"*\") {\n\t\tif (grantedAction === \"*\") {\n\t\t\tif (grantedId === void 0) return true;\n\t\t\treturn grantedId === requiredId;\n\t\t}\n\t\tif (grantedAction !== requiredAction) return false;\n\t\tif (grantedId === void 0) return true;\n\t\treturn grantedId === requiredId;\n\t}\n\tif (grantedResource !== requiredResource) return false;\n\tif (grantedAction === \"*\") {\n\t\tif (grantedId === void 0) return true;\n\t\treturn grantedId === requiredId;\n\t}\n\tif (grantedAction !== requiredAction) return false;\n\tif (grantedId === void 0) return true;\n\treturn grantedId === requiredId;\n}\n/**\n* Check if a user has a specific permission.\n*\n* @param userPermissions - Permissions the user has\n* @param requiredPermission - Permission being checked\n* @returns True if user has the permission\n*/\nfunction hasPermission(userPermissions, requiredPermission) {\n\treturn userPermissions.some((p) => matchesPermission(p, requiredPermission));\n}\n/**\n* Resolve permissions from user roles using a role mapping.\n*\n* This function translates provider-defined roles (from WorkOS, Okta, etc.)\n* to Mastra permissions using a configurable mapping.\n*\n* @example\n* ```typescript\n* const roleMapping = {\n*   \"Engineering\": [\"agents:*\", \"workflows:*\"],\n*   \"Product\": [\"agents:read\"],\n*   \"_default\": [],\n* };\n*\n* // User has \"Engineering\" and \"QA\" roles\n* const permissions = resolvePermissionsFromMapping(\n*   [\"Engineering\", \"QA\"],\n*   roleMapping\n* );\n* // Result: [\"agents:*\", \"workflows:*\"] (QA is unmapped, gets _default)\n* ```\n*\n* @param roles - User's roles from the identity provider\n* @param mapping - Role to permission mapping\n* @returns Array of resolved permissions\n*/\nfunction resolvePermissionsFromMapping(roles, mapping) {\n\tconst permissions = /* @__PURE__ */ new Set();\n\tconst defaultPerms = mapping[\"_default\"] ?? [];\n\tfor (const role of roles) {\n\t\tconst rolePerms = mapping[role];\n\t\tif (rolePerms) for (const perm of rolePerms) permissions.add(perm);\n\t\telse for (const perm of defaultPerms) permissions.add(perm);\n\t}\n\treturn Array.from(permissions);\n}\n//#endregion\n//#region src/ee/defaults/rbac/static.ts\n/**\n* Static RBAC provider.\n*\n* Supports two modes:\n* 1. **Role definitions**: Use Mastra's native role system with structured roles\n* 2. **Role mapping**: Directly map provider roles to permissions\n*\n* @example Using role definitions (Mastra's native system)\n* ```typescript\n* const rbac = new StaticRBACProvider({\n*   roles: DEFAULT_ROLES,\n*   getUserRoles: (user) => [user.role],\n* });\n* ```\n*\n* @example Using role mapping (for external providers)\n* ```typescript\n* const rbac = new StaticRBACProvider({\n*   roleMapping: {\n*     \"Engineering\": [\"agents:*\", \"workflows:*\"],\n*     \"Product\": [\"agents:read\", \"workflows:read\"],\n*     \"_default\": [],\n*   },\n*   getUserRoles: (user) => user.providerRoles,\n* });\n* ```\n*\n* @example Async role lookup\n* ```typescript\n* const rbac = new StaticRBACProvider({\n*   roles: DEFAULT_ROLES,\n*   getUserRoles: async (user) => {\n*     return db.getUserRoles(user.id);\n*   },\n* });\n* ```\n*/\nvar StaticRBACProvider = class {\n\troles;\n\t_roleMapping;\n\tgetUserRolesFn;\n\tpermissionCache = /* @__PURE__ */ new Map();\n\t/** Expose roleMapping for middleware access */\n\tget roleMapping() {\n\t\treturn this._roleMapping;\n\t}\n\tconstructor(options) {\n\t\tif (\"roles\" in options && options.roles) this.roles = options.roles;\n\t\tif (\"roleMapping\" in options && options.roleMapping) this._roleMapping = options.roleMapping;\n\t\tthis.getUserRolesFn = options.getUserRoles;\n\t}\n\tasync getRoles(user) {\n\t\treturn await this.getUserRolesFn(user);\n\t}\n\tasync hasRole(user, role) {\n\t\treturn (await this.getRoles(user)).includes(role);\n\t}\n\tasync getPermissions(user) {\n\t\tconst roleIds = await this.getRoles(user);\n\t\tconst cacheKey = roleIds.sort().join(\",\");\n\t\tconst cached = this.permissionCache.get(cacheKey);\n\t\tif (cached) return cached;\n\t\tlet permissions;\n\t\tif (this._roleMapping) permissions = resolvePermissionsFromMapping(roleIds, this._roleMapping);\n\t\telse if (this.roles) permissions = resolvePermissions(roleIds, this.roles);\n\t\telse permissions = [];\n\t\tthis.permissionCache.set(cacheKey, permissions);\n\t\treturn permissions;\n\t}\n\tasync hasPermission(user, permission) {\n\t\treturn (await this.getPermissions(user)).some((p) => matchesPermission(p, permission));\n\t}\n\tasync hasAllPermissions(user, permissions) {\n\t\tconst userPermissions = await this.getPermissions(user);\n\t\treturn permissions.every((required) => userPermissions.some((p) => matchesPermission(p, required)));\n\t}\n\tasync hasAnyPermission(user, permissions) {\n\t\tconst userPermissions = await this.getPermissions(user);\n\t\treturn permissions.some((required) => userPermissions.some((p) => matchesPermission(p, required)));\n\t}\n\t/**\n\t* Clear the permission cache.\n\t*/\n\tclearCache() {\n\t\tthis.permissionCache.clear();\n\t}\n\t/**\n\t* Get all role definitions.\n\t* Only available when using role definitions mode (not role mapping).\n\t*/\n\tgetRoleDefinitions() {\n\t\treturn this.roles ?? [];\n\t}\n\t/**\n\t* Get a specific role definition.\n\t* Only available when using role definitions mode (not role mapping).\n\t*/\n\tgetRoleDefinition(roleId) {\n\t\treturn this.roles?.find((r) => r.id === roleId);\n\t}\n\t/**\n\t* Get all available roles in the system.\n\t*/\n\tasync getAvailableRoles() {\n\t\tif (this.roles) return this.roles.map((r) => ({\n\t\t\tid: r.id,\n\t\t\tname: r.name\n\t\t}));\n\t\tif (this._roleMapping) return Object.keys(this._roleMapping).filter((k) => k !== \"_default\").map((k) => ({\n\t\t\tid: k,\n\t\t\tname: k\n\t\t}));\n\t\treturn [];\n\t}\n\t/**\n\t* Get the resolved permissions for a specific role.\n\t*/\n\tasync getPermissionsForRole(roleId) {\n\t\tif (this._roleMapping) return resolvePermissionsFromMapping([roleId], this._roleMapping);\n\t\tif (this.roles) return resolvePermissions([roleId], this.roles);\n\t\treturn [];\n\t}\n};\n//#endregion\n//#region src/ee/index.ts\n/**\n* @mastra/core/auth/ee\n*\n* Enterprise authentication capabilities for Mastra.\n* This code is licensed under the Mastra Enterprise License - see ee/LICENSE.\n*\n* @license Mastra Enterprise License - see ee/LICENSE\n* @packageDocumentation\n*/\n//#endregion\nexport { validatePermissions as S, MastraFGAPermissions as _, matchesPermission as a, RESOURCES as b, FGADeniedError as c, getAgentToolFGAResourceId as d, getMCPToolFGAResourceId as f, ACTIONS as g, requireFGA as h, hasPermission as i, checkFGA as l, getWorkflowFGAResourceId as m, DEFAULT_ROLES as n, resolvePermissions as o, getStandaloneToolFGAResourceId as p, getDefaultRole as r, resolvePermissionsFromMapping as s, StaticRBACProvider as t, getAgentFGAResourceId as u, PERMISSIONS as v, isValidPermissionPattern as x, PERMISSION_PATTERNS as y };\n\n//# sourceMappingURL=ee-DXvSoTl7.js.map","/**\n * Okta RBAC provider for Mastra.\n *\n * Maps Okta groups to Mastra permissions using a configurable role mapping.\n * Can be used with any auth provider (Auth0, Clerk, etc.) or with MastraAuthOkta.\n */\n\nimport type { IRBACProvider, RoleMapping } from '@internal/auth/ee';\nimport { resolvePermissionsFromMapping, matchesPermission } from '@internal/auth/ee';\nimport pkg from '@okta/okta-sdk-nodejs';\nconst { Client } = pkg;\nimport { LRUCache } from 'lru-cache';\n\nimport type { OktaUser, MastraRBACOktaOptions } from './types.js';\n\n/** Default cache TTL in milliseconds (60 seconds) */\nconst DEFAULT_CACHE_TTL_MS = 60 * 1000;\n\n/** Default max cache size (number of users) */\nconst DEFAULT_CACHE_MAX_SIZE = 1000;\n\n/**\n * Okta RBAC provider that maps Okta groups to Mastra permissions.\n *\n * This provider fetches user groups from Okta and translates them into\n * Mastra permissions using a configurable role mapping.\n *\n * @example Basic usage with Okta auth\n * ```typescript\n * import { MastraAuthOkta, MastraRBACOkta } from '@mastra/auth-okta';\n *\n * const mastra = new Mastra({\n *   server: {\n *     auth: new MastraAuthOkta(),\n *     rbac: new MastraRBACOkta({\n *       roleMapping: {\n *         'Engineering': ['agents:*', 'workflows:*'],\n *         'Admin': ['*'],\n *         '_default': [],\n *       },\n *     }),\n *   },\n * });\n * ```\n *\n * @example Cross-provider usage (Auth0 + Okta RBAC)\n * ```typescript\n * import { MastraAuthAuth0 } from '@mastra/auth-auth0';\n * import { MastraRBACOkta } from '@mastra/auth-okta';\n *\n * const mastra = new Mastra({\n *   server: {\n *     auth: new MastraAuthAuth0(),\n *     rbac: new MastraRBACOkta({\n *       getUserId: (user) => user.metadata?.oktaUserId || user.email,\n *       roleMapping: {\n *         'Engineering': ['agents:*', 'workflows:*'],\n *         'Admin': ['*'],\n *         '_default': [],\n *       },\n *     }),\n *   },\n * });\n * ```\n */\nexport class MastraRBACOkta implements IRBACProvider<OktaUser> {\n  private oktaClient: InstanceType<typeof Client>;\n  private options: MastraRBACOktaOptions;\n  /**\n   * Single cache for roles (the expensive Okta API call).\n   * Permissions are derived from roles on-the-fly (cheap, synchronous).\n   * Storing promises handles concurrent request deduplication.\n   */\n  private rolesCache: LRUCache<string, Promise<string[]>>;\n\n  /**\n   * Expose roleMapping for middleware access.\n   * This allows the authorization middleware to resolve permissions\n   * without needing to call the async methods.\n   */\n  get roleMapping(): RoleMapping {\n    return this.options.roleMapping;\n  }\n\n  /**\n   * Create a new Okta RBAC provider.\n   *\n   * @param options - RBAC configuration options\n   */\n  constructor(options: MastraRBACOktaOptions) {\n    const domain = options.domain ?? process.env.OKTA_DOMAIN;\n    const apiToken = options.apiToken ?? process.env.OKTA_API_TOKEN;\n\n    if (!domain) {\n      throw new Error(\n        'Okta domain is required. ' + 'Provide it in the options or set OKTA_DOMAIN environment variable.',\n      );\n    }\n\n    if (!apiToken) {\n      throw new Error(\n        'Okta API token is required for RBAC. ' +\n          'Provide it in the options or set OKTA_API_TOKEN environment variable.',\n      );\n    }\n\n    this.oktaClient = new Client({\n      orgUrl: `https://${domain}`,\n      token: apiToken,\n    });\n\n    this.options = options;\n\n    // Initialize LRU cache with configurable size and TTL\n    this.rolesCache = new LRUCache<string, Promise<string[]>>({\n      max: options.cache?.maxSize ?? DEFAULT_CACHE_MAX_SIZE,\n      ttl: options.cache?.ttlMs ?? DEFAULT_CACHE_TTL_MS,\n    });\n  }\n\n  /**\n   * Get all roles (groups) for a user from Okta.\n   *\n   * If the user object already has groups attached, uses those.\n   * Otherwise, fetches groups from Okta API and caches the result.\n   *\n   * @param user - User to get roles for\n   * @returns Array of group names\n   */\n  async getRoles(user: OktaUser): Promise<string[]> {\n    // If groups are already present on the user object, use them\n    if (user.groups && user.groups.length > 0) {\n      return user.groups;\n    }\n\n    // Determine the user ID to use for Okta API lookup\n    const userId = this.resolveUserId(user);\n    if (!userId) {\n      return [];\n    }\n\n    // Check cache - returns existing promise (resolved or in-flight)\n    const cached = this.rolesCache.get(userId);\n    if (cached) {\n      return cached;\n    }\n\n    // Create and cache the group fetch promise.\n    // On failure, evict from cache so the next request retries,\n    // then fall back to empty groups (which applies _default permissions).\n    const groupsPromise = this.fetchGroupsFromOkta(userId).catch(err => {\n      console.error(`[MastraRBACOkta] Failed to fetch groups for user ${userId}:`, err);\n      this.rolesCache.delete(userId);\n      return [];\n    });\n    this.rolesCache.set(userId, groupsPromise);\n\n    return groupsPromise;\n  }\n\n  /**\n   * Resolve the Okta user ID from the user object.\n   * Uses custom getUserId function if provided, otherwise falls back to oktaId or id.\n   */\n  private resolveUserId(user: OktaUser): string | undefined {\n    if (this.options.getUserId) {\n      return this.options.getUserId(user);\n    }\n    return user.oktaId ?? user.id;\n  }\n\n  /**\n   * Fetch groups from Okta API.\n   * Errors propagate to the caller so the cache eviction in getRoles() works.\n   */\n  private async fetchGroupsFromOkta(userId: string): Promise<string[]> {\n    const groups = await this.oktaClient.userApi.listUserGroups({ userId });\n    const groupNames: string[] = [];\n\n    for await (const group of groups) {\n      if (group && group.profile?.name) {\n        groupNames.push(group.profile.name);\n      }\n    }\n\n    return groupNames;\n  }\n\n  /**\n   * Check if a user has a specific role (group).\n   *\n   * @param user - User to check\n   * @param role - Group name to check for\n   * @returns True if user has the group\n   */\n  async hasRole(user: OktaUser, role: string): Promise<boolean> {\n    const roles = await this.getRoles(user);\n    return roles.includes(role);\n  }\n\n  /**\n   * Get all permissions for a user by mapping their Okta groups.\n   *\n   * @param user - User to get permissions for\n   * @returns Array of permission strings\n   */\n  async getPermissions(user: OktaUser): Promise<string[]> {\n    const roles = await this.getRoles(user);\n    return resolvePermissionsFromMapping(roles, this.options.roleMapping);\n  }\n\n  /**\n   * Check if a user has a specific permission.\n   *\n   * @param user - User to check\n   * @param permission - Permission to check for (supports wildcards)\n   * @returns True if user has the permission\n   */\n  async hasPermission(user: OktaUser, permission: string): Promise<boolean> {\n    const permissions = await this.getPermissions(user);\n\n    // Check if any granted permission matches the required permission\n    return permissions.some(granted => matchesPermission(granted, permission));\n  }\n\n  /**\n   * Check if a user has ALL of the specified permissions.\n   *\n   * @param user - User to check\n   * @param permissions - Permissions to check for\n   * @returns True if user has all permissions\n   */\n  async hasAllPermissions(user: OktaUser, permissions: string[]): Promise<boolean> {\n    const userPermissions = await this.getPermissions(user);\n\n    return permissions.every(required => userPermissions.some(granted => matchesPermission(granted, required)));\n  }\n\n  /**\n   * Check if a user has ANY of the specified permissions.\n   *\n   * @param user - User to check\n   * @param permissions - Permissions to check for\n   * @returns True if user has at least one permission\n   */\n  async hasAnyPermission(user: OktaUser, permissions: string[]): Promise<boolean> {\n    const userPermissions = await this.getPermissions(user);\n\n    return permissions.some(required => userPermissions.some(granted => matchesPermission(granted, required)));\n  }\n}\n","//#region src/types/index.ts\nfunction headerFromPlainObject(headers, name) {\n\tconst normalizedName = name.toLowerCase();\n\tconst matchingKey = Object.keys(headers).find((key) => key.toLowerCase() === normalizedName);\n\tconst value = matchingKey === void 0 ? void 0 : headers[matchingKey];\n\treturn Array.isArray(value) ? value[0] ?? null : value ?? null;\n}\n/**\n* Read a request header across fetch, Hono, and Express-style request shapes.\n* Must not throw when `headers` is a plain object (Express `IncomingHttpHeaders`).\n*/\nfunction getRequestHeader(request, name) {\n\tif (request instanceof Request) return request.headers.get(name);\n\tif (request.raw instanceof Request) return request.raw.headers.get(name);\n\tconst headers = request.headers;\n\tif (headers instanceof Headers) return headers.get(name);\n\tif (typeof request.header === \"function\") return request.header(name) ?? null;\n\tif (headers && typeof headers === \"object\") return headerFromPlainObject(headers, name);\n\treturn null;\n}\nfunction getWebRequest(request) {\n\tif (request instanceof Request) return request;\n\treturn request.raw instanceof Request ? request.raw : void 0;\n}\n//#endregion\nexport { getRequestHeader, getWebRequest };\n\n//# sourceMappingURL=index.js.map","import { Transform } from \"stream\";\n//#region src/logger/index.ts\nconst RegisteredLogger = {\n\tAGENT: \"AGENT\",\n\tOBSERVABILITY: \"OBSERVABILITY\",\n\tAUTH: \"AUTH\",\n\tBROWSER: \"BROWSER\",\n\tNETWORK: \"NETWORK\",\n\tWORKFLOW: \"WORKFLOW\",\n\tLLM: \"LLM\",\n\tTTS: \"TTS\",\n\tVOICE: \"VOICE\",\n\tVECTOR: \"VECTOR\",\n\tBUNDLER: \"BUNDLER\",\n\tDEPLOYER: \"DEPLOYER\",\n\tMEMORY: \"MEMORY\",\n\tSTORAGE: \"STORAGE\",\n\tEMBEDDINGS: \"EMBEDDINGS\",\n\tMCP_SERVER: \"MCP_SERVER\",\n\tSERVER_CACHE: \"SERVER_CACHE\",\n\tSERVER: \"SERVER\",\n\tWORKSPACE: \"WORKSPACE\",\n\tCHANNEL: \"CHANNEL\"\n};\nconst LogLevel = {\n\tDEBUG: \"debug\",\n\tINFO: \"info\",\n\tWARN: \"warn\",\n\tERROR: \"error\",\n\tNONE: \"silent\"\n};\nvar LoggerTransport = class extends Transform {\n\tconstructor(opts = {}) {\n\t\tsuper({\n\t\t\t...opts,\n\t\t\tobjectMode: true\n\t\t});\n\t}\n\tasync listLogsByRunId(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args?.page ?? 1,\n\t\t\tperPage: _args?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogs(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args?.page ?? 1,\n\t\t\tperPage: _args?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\nconst createCustomTransport = (stream, listLogs, listLogsByRunId) => {\n\tlet transport = stream;\n\tif (listLogs) transport.listLogs = listLogs;\n\tif (listLogsByRunId) transport.listLogsByRunId = listLogsByRunId;\n\treturn transport;\n};\nvar MastraLogger = class {\n\tname;\n\tlevel;\n\ttransports;\n\tconstructor(options = {}) {\n\t\tthis.name = options.name || \"Mastra\";\n\t\tthis.level = options.level || LogLevel.ERROR;\n\t\tthis.transports = new Map(Object.entries(options.transports || {}));\n\t}\n\tgetTransports() {\n\t\treturn this.transports;\n\t}\n\ttrackException(_error, _metadata) {}\n\tasync listLogs(transportId, params) {\n\t\tif (!transportId || !this.transports.has(transportId)) return {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: params?.page ?? 1,\n\t\t\tperPage: params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t\treturn this.transports.get(transportId).listLogs?.(params) ?? {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: params?.page ?? 1,\n\t\t\tperPage: params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogsByRunId({ transportId, runId, fromDate, toDate, logLevel, filters, page, perPage }) {\n\t\tif (!transportId || !this.transports.has(transportId) || !runId) return {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: page ?? 1,\n\t\t\tperPage: perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t\treturn this.transports.get(transportId).listLogsByRunId?.({\n\t\t\trunId,\n\t\t\tfromDate,\n\t\t\ttoDate,\n\t\t\tlogLevel,\n\t\t\tfilters,\n\t\t\tpage,\n\t\t\tperPage\n\t\t}) ?? {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: page ?? 1,\n\t\t\tperPage: perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\nvar ConsoleLogger = class ConsoleLogger extends MastraLogger {\n\tcomponent;\n\tfilter;\n\tconstructor(options = {}) {\n\t\tsuper(options);\n\t\tthis.component = options.component;\n\t\tthis.filter = options.filter;\n\t}\n\tchild(componentOrBindings) {\n\t\tconst component = typeof componentOrBindings === \"string\" ? componentOrBindings : componentOrBindings?.component ?? this.component;\n\t\treturn new ConsoleLogger({\n\t\t\tname: this.name,\n\t\t\tlevel: this.level,\n\t\t\tcomponent,\n\t\t\tfilter: this.filter\n\t\t});\n\t}\n\tshouldLog(level, message, args) {\n\t\tif (!this.filter) return true;\n\t\ttry {\n\t\t\treturn this.filter({\n\t\t\t\tcomponent: this.component,\n\t\t\t\tlevel,\n\t\t\t\tmessage,\n\t\t\t\targs\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tconsole.error(`[Logger] Filter error for component=${this.component} level=${level}:`, e);\n\t\t\treturn true;\n\t\t}\n\t}\n\tprefix() {\n\t\treturn this.component ? `[${this.component}] ` : \"\";\n\t}\n\tdebug(message, ...args) {\n\t\tif (this.level === LogLevel.DEBUG && this.shouldLog(LogLevel.DEBUG, message, args)) console.info(`${this.prefix()}${message}`, ...args);\n\t}\n\tinfo(message, ...args) {\n\t\tif ((this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.INFO, message, args)) console.info(`${this.prefix()}${message}`, ...args);\n\t}\n\twarn(message, ...args) {\n\t\tif ((this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.WARN, message, args)) console.warn(`${this.prefix()}${message}`, ...args);\n\t}\n\terror(message, ...args) {\n\t\tif ((this.level === LogLevel.ERROR || this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.ERROR, message, args)) console.error(`${this.prefix()}${message}`, ...args);\n\t}\n\tasync listLogs(_transportId, _params) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _params?.page ?? 1,\n\t\t\tperPage: _params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogsByRunId(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args.page ?? 1,\n\t\t\tperPage: _args.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\n//#endregion\nexport { ConsoleLogger, LogLevel, LoggerTransport, MastraLogger, RegisteredLogger, createCustomTransport };\n\n//# sourceMappingURL=index.js.map","import { ConsoleLogger, RegisteredLogger } from \"../logger/index.js\";\n//#region src/base/MastraBase.ts\nvar MastraBase = class {\n\tcomponent = RegisteredLogger.LLM;\n\tlogger;\n\tname;\n\t#rawConfig;\n\tconstructor({ component, name, rawConfig }) {\n\t\tthis.component = component || RegisteredLogger.LLM;\n\t\tthis.name = name;\n\t\tthis.#rawConfig = rawConfig;\n\t\tthis.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });\n\t}\n\t/**\n\t* Returns the raw storage configuration this primitive was created from,\n\t* or undefined if it was created from code.\n\t*/\n\ttoRawConfig() {\n\t\treturn this.#rawConfig;\n\t}\n\t/**\n\t* Sets the raw storage configuration for this primitive.\n\t* @internal\n\t*/\n\t__setRawConfig(rawConfig) {\n\t\tthis.#rawConfig = rawConfig;\n\t}\n\t/**\n\t* Set the logger for the agent\n\t* @param logger\n\t*/\n\t__setLogger(logger) {\n\t\tthis.logger = \"child\" in logger && typeof logger.child === \"function\" ? logger.child({ component: this.component }) : logger;\n\t}\n};\n//#endregion\nexport { MastraBase };\n\n//# sourceMappingURL=index.js.map","import { getRequestHeader } from \"../types/index.js\";\nimport { MastraBase } from \"@internal/core/base\";\n//#region src/provider/index.ts\nvar MastraAuthProvider = class extends MastraBase {\n\tprotected;\n\tpublic;\n\tconstructor(options) {\n\t\tsuper({\n\t\t\tcomponent: \"AUTH\",\n\t\t\tname: options?.name\n\t\t});\n\t\tif (options?.authorizeUser) this.authorizeUser = options.authorizeUser.bind(this);\n\t\tthis.protected = options?.protected;\n\t\tthis.public = options?.public;\n\t\tthis.mapUserToResourceId = options?.mapUserToResourceId;\n\t}\n\tregisterOptions(opts) {\n\t\tif (opts?.authorizeUser) this.authorizeUser = opts.authorizeUser.bind(this);\n\t\tif (opts?.mapUserToResourceId) this.mapUserToResourceId = opts.mapUserToResourceId;\n\t\tif (opts?.protected) this.protected = opts.protected;\n\t\tif (opts?.public) this.public = opts.public;\n\t}\n};\nfunction isSSOProvider(p) {\n\treturn p !== null && typeof p === \"object\" && typeof p.getLoginUrl === \"function\" && typeof p.handleCallback === \"function\";\n}\nfunction isSessionProvider(p) {\n\treturn p !== null && typeof p === \"object\" && typeof p.validateSession === \"function\" && typeof p.createSession === \"function\";\n}\nfunction isUserProvider(p) {\n\treturn p !== null && typeof p === \"object\" && typeof p.getCurrentUser === \"function\";\n}\nfunction isCredentialsProvider(p) {\n\treturn p !== null && typeof p === \"object\" && typeof p.signIn === \"function\";\n}\nfunction isOrganizationsProvider(p) {\n\treturn p !== null && typeof p === \"object\" && typeof p.ensureOrganization === \"function\" && typeof p.isOrganizationAdmin === \"function\";\n}\nfunction isAuthHttpHandler(p) {\n\treturn p !== null && typeof p === \"object\" && typeof p.handleAuthRequest === \"function\";\n}\nfunction hasAuthInit(p) {\n\treturn p !== null && typeof p === \"object\" && typeof p.init === \"function\";\n}\nfunction isObjectLike(value) {\n\treturn typeof value === \"object\" && value !== null || typeof value === \"function\";\n}\nvar CompositeAuth = class extends MastraAuthProvider {\n\tproviders;\n\tauthenticatedProviderByObject = /* @__PURE__ */ new WeakMap();\n\tauthenticatedProviderByPrimitive = /* @__PURE__ */ new Map();\n\tconstructor(providers) {\n\t\tconst combinedPublic = providers.flatMap((provider) => provider.public ?? []);\n\t\tconst combinedProtected = providers.flatMap((provider) => provider.protected ?? []);\n\t\tsuper({\n\t\t\tpublic: combinedPublic,\n\t\t\tprotected: combinedProtected\n\t\t});\n\t\tthis.providers = providers;\n\t\tif (providers.some((provider) => typeof provider.mapUserToResourceId === \"function\")) this.mapUserToResourceId = (user) => this.mapAuthenticatedUserToResourceId(user);\n\t\tif (!providers.some(isSSOProvider)) {\n\t\t\tthis.getLoginUrl = void 0;\n\t\t\tthis.handleCallback = void 0;\n\t\t\tthis.getLoginButtonConfig = void 0;\n\t\t}\n\t\tif (!providers.some(isSessionProvider)) {\n\t\t\tthis.createSession = void 0;\n\t\t\tthis.validateSession = void 0;\n\t\t\tthis.getSessionIdFromRequest = void 0;\n\t\t}\n\t\tif (!providers.some(isUserProvider)) {\n\t\t\tthis.getCurrentUser = void 0;\n\t\t\tthis.getUser = void 0;\n\t\t\tthis.getUsers = void 0;\n\t\t}\n\t\tconst credProvider = providers.find(isCredentialsProvider);\n\t\tif (credProvider) {\n\t\t\tthis.signIn = credProvider.signIn.bind(credProvider);\n\t\t\tif (typeof credProvider.signUp === \"function\") this.signUp = credProvider.signUp.bind(credProvider);\n\t\t\tif (typeof credProvider.requestPasswordReset === \"function\") this.requestPasswordReset = credProvider.requestPasswordReset.bind(credProvider);\n\t\t\tif (typeof credProvider.resetPassword === \"function\") this.resetPassword = credProvider.resetPassword.bind(credProvider);\n\t\t\tthis.isSignUpEnabled = typeof credProvider.isSignUpEnabled === \"function\" ? credProvider.isSignUpEnabled.bind(credProvider) : () => true;\n\t\t} else {\n\t\t\tthis.signIn = void 0;\n\t\t\tthis.signUp = void 0;\n\t\t\tthis.requestPasswordReset = void 0;\n\t\t\tthis.resetPassword = void 0;\n\t\t\tthis.isSignUpEnabled = void 0;\n\t\t}\n\t}\n\tfindProvider(check) {\n\t\treturn this.providers.find(check);\n\t}\n\trememberAuthenticatedProvider(user, provider) {\n\t\tif (isObjectLike(user)) {\n\t\t\tthis.authenticatedProviderByObject.set(user, provider);\n\t\t\treturn;\n\t\t}\n\t\tthis.authenticatedProviderByPrimitive.set(user, provider);\n\t}\n\ttakeAuthenticatedProvider(user) {\n\t\tif (isObjectLike(user)) {\n\t\t\tconst provider = this.authenticatedProviderByObject.get(user);\n\t\t\tthis.authenticatedProviderByObject.delete(user);\n\t\t\treturn provider;\n\t\t}\n\t\tconst primitiveUser = user;\n\t\tconst provider = this.authenticatedProviderByPrimitive.get(primitiveUser);\n\t\tthis.authenticatedProviderByPrimitive.delete(primitiveUser);\n\t\treturn provider;\n\t}\n\tmapAuthenticatedUserToResourceId(user) {\n\t\treturn this.takeAuthenticatedProvider(user)?.mapUserToResourceId?.(user);\n\t}\n\t/**\n\t* True if any provider is MastraCloudAuth (exempt from license requirement).\n\t*/\n\tget isMastraCloudAuth() {\n\t\treturn this.providers.some((p) => \"isMastraCloudAuth\" in p && p.isMastraCloudAuth === true);\n\t}\n\t/**\n\t* True if any provider is SimpleAuth (exempt from license requirement).\n\t*/\n\tget isSimpleAuth() {\n\t\treturn this.providers.some((p) => \"isSimpleAuth\" in p && p.isSimpleAuth === true);\n\t}\n\tasync authenticateToken(token, request) {\n\t\tfor (const provider of this.providers) try {\n\t\t\tconst user = await provider.authenticateToken(token, request);\n\t\t\tif (user) {\n\t\t\t\tthis.rememberAuthenticatedProvider(user, provider);\n\t\t\t\treturn user;\n\t\t\t}\n\t\t} catch {}\n\t\treturn null;\n\t}\n\tasync authorizeUser(user, request) {\n\t\tfor (const provider of this.providers) if (await provider.authorizeUser(user, request)) return true;\n\t\treturn false;\n\t}\n\t/**\n\t* Forward cookie header to SSO provider for PKCE validation.\n\t* Called by auth handler before handleCallback().\n\t*/\n\tsetCallbackCookieHeader(cookieHeader) {\n\t\tconst sso = this.findProvider(isSSOProvider);\n\t\tif (sso && typeof sso.setCallbackCookieHeader === \"function\") sso.setCallbackCookieHeader(cookieHeader);\n\t}\n\tgetLoginUrl(redirectUri, state) {\n\t\tconst sso = this.findProvider(isSSOProvider);\n\t\tif (!sso) throw new Error(\"No SSO provider configured in CompositeAuth\");\n\t\treturn sso.getLoginUrl(redirectUri, state);\n\t}\n\tgetLoginCookies(redirectUri, state) {\n\t\treturn this.findProvider(isSSOProvider)?.getLoginCookies?.(redirectUri, state);\n\t}\n\tasync handleCallback(code, state) {\n\t\tconst sso = this.findProvider(isSSOProvider);\n\t\tif (!sso) throw new Error(\"No SSO provider configured in CompositeAuth\");\n\t\treturn sso.handleCallback(code, state);\n\t}\n\tgetLoginButtonConfig() {\n\t\tconst sso = this.findProvider(isSSOProvider);\n\t\tif (!sso) return {\n\t\t\tprovider: \"unknown\",\n\t\t\ttext: \"Sign in\"\n\t\t};\n\t\treturn sso.getLoginButtonConfig();\n\t}\n\tasync getLogoutUrl(redirectUri, request) {\n\t\tfor (const provider of this.providers) if (isSSOProvider(provider) && provider.getLogoutUrl) try {\n\t\t\tconst url = await provider.getLogoutUrl(redirectUri, request);\n\t\t\tif (url) return url;\n\t\t} catch {}\n\t\treturn null;\n\t}\n\tasync createSession(userId, metadata) {\n\t\tconst session = this.findProvider(isSessionProvider);\n\t\tif (!session) throw new Error(\"No session provider configured in CompositeAuth\");\n\t\treturn session.createSession(userId, metadata);\n\t}\n\tasync validateSession(sessionId) {\n\t\tfor (const provider of this.providers) if (isSessionProvider(provider)) try {\n\t\t\tconst session = await provider.validateSession(sessionId);\n\t\t\tif (session) return session;\n\t\t} catch {}\n\t\treturn null;\n\t}\n\tasync destroySession(sessionId) {\n\t\tconst destroyPromises = [];\n\t\tfor (const provider of this.providers) if (isSessionProvider(provider)) destroyPromises.push(provider.destroySession(sessionId).catch(() => {}));\n\t\tawait Promise.all(destroyPromises);\n\t}\n\tasync refreshSession(sessionId) {\n\t\tfor (const provider of this.providers) if (isSessionProvider(provider)) try {\n\t\t\tconst session = await provider.refreshSession(sessionId);\n\t\t\tif (session) return session;\n\t\t} catch {}\n\t\treturn null;\n\t}\n\tgetSessionIdFromRequest(request) {\n\t\tfor (const provider of this.providers) if (isSessionProvider(provider)) try {\n\t\t\tconst sessionId = provider.getSessionIdFromRequest(request);\n\t\t\tif (sessionId) return sessionId;\n\t\t} catch {}\n\t\treturn null;\n\t}\n\tgetSessionHeaders(session) {\n\t\treturn this.findProvider(isSessionProvider)?.getSessionHeaders(session) ?? {};\n\t}\n\tgetClearSessionHeaders() {\n\t\tconst headers = {};\n\t\tfor (const provider of this.providers) if (isSessionProvider(provider)) try {\n\t\t\tconst providerHeaders = provider.getClearSessionHeaders();\n\t\t\tObject.assign(headers, providerHeaders);\n\t\t} catch {}\n\t\treturn headers;\n\t}\n\tasync getCurrentUser(request) {\n\t\tfor (const provider of this.providers) if (isUserProvider(provider)) try {\n\t\t\tconst user = await provider.getCurrentUser(request);\n\t\t\tif (user) return user;\n\t\t} catch {}\n\t\treturn null;\n\t}\n\tasync getUser(userId) {\n\t\tfor (const provider of this.providers) if (isUserProvider(provider)) try {\n\t\t\tconst user = await provider.getUser(userId);\n\t\t\tif (user) return user;\n\t\t} catch {}\n\t\treturn null;\n\t}\n\tasync getUsers(userIds) {\n\t\treturn Promise.all(userIds.map((userId) => this.getUser(userId)));\n\t}\n};\nconst DEFAULT_HEADERS = [\"Authorization\", \"X-Playground-Access\"];\nvar SimpleAuth = class extends MastraAuthProvider {\n\t/**\n\t* Marker to exempt SimpleAuth from EE license requirement.\n\t* SimpleAuth is for development/testing and should work without a license.\n\t*/\n\tisSimpleAuth = true;\n\ttokens;\n\theaders;\n\tusers;\n\tuserById;\n\tconstructor(options) {\n\t\tsuper(options);\n\t\tthis.tokens = options.tokens;\n\t\tthis.users = Object.values(this.tokens);\n\t\tthis.headers = [...DEFAULT_HEADERS].concat(options.headers || []);\n\t\tthis.userById = new Map(this.users.map((u) => [String(u?.id), u]));\n\t}\n\tasync authenticateToken(token, request) {\n\t\tconst requestTokens = this.getTokensFromHeaders(token, request);\n\t\tfor (const requestToken of requestTokens) {\n\t\t\tconst tokenToUser = this.tokens[requestToken];\n\t\t\tif (tokenToUser) return tokenToUser;\n\t\t}\n\t\treturn this.getUserFromCookie(getRequestHeader(request, \"Cookie\"));\n\t}\n\tasync authorizeUser(user, _request) {\n\t\treturn this.users.includes(user);\n\t}\n\t/** Get current user from request headers or cookie. */\n\tasync getCurrentUser(request) {\n\t\tfor (const headerName of this.headers) {\n\t\t\tconst headerValue = request.headers.get(headerName);\n\t\t\tif (headerValue) {\n\t\t\t\tconst token = this.stripBearerPrefix(headerValue);\n\t\t\t\tconst user = this.tokens[token];\n\t\t\t\tif (user) return user;\n\t\t\t}\n\t\t}\n\t\treturn this.getUserFromCookie(request.headers.get(\"Cookie\"));\n\t}\n\tgetUserFromCookie(cookieHeader) {\n\t\tif (!cookieHeader) return null;\n\t\tconst cookies = cookieHeader.split(\";\").map((c) => c.trim());\n\t\tfor (const cookie of cookies) if (cookie.startsWith(\"mastra-token=\")) {\n\t\t\tconst token = cookie.slice(13);\n\t\t\tconst user = this.tokens[token];\n\t\t\tif (user) return user;\n\t\t}\n\t\treturn null;\n\t}\n\t/** Get user by ID. */\n\tasync getUser(userId) {\n\t\treturn this.userById.get(userId) ?? null;\n\t}\n\tasync getUsers(userIds) {\n\t\treturn userIds.map((userId) => this.userById.get(userId) ?? null);\n\t}\n\t/**\n\t* Sign in with token (passed as password field).\n\t* The email field is ignored - only the token matters.\n\t*/\n\tasync signIn(_email, password, _request) {\n\t\tconst token = password;\n\t\tconst user = this.tokens[token];\n\t\tif (!user) throw new Error(\"Invalid token\");\n\t\treturn {\n\t\t\tuser,\n\t\t\ttoken,\n\t\t\tcookies: [`mastra-token=${token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=86400`]\n\t\t};\n\t}\n\tasync signUp() {\n\t\tthrow new Error(\"Sign up is not supported with SimpleAuth. Use pre-configured tokens.\");\n\t}\n\tisSignUpEnabled() {\n\t\treturn false;\n\t}\n\t/**\n\t* Get headers to clear the session cookie on logout.\n\t* Partial ISessionProvider implementation for logout support.\n\t*/\n\tgetClearSessionHeaders() {\n\t\treturn { \"Set-Cookie\": \"mastra-token=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0\" };\n\t}\n\tstripBearerPrefix(token) {\n\t\treturn token.startsWith(\"Bearer \") ? token.slice(7) : token;\n\t}\n\tgetTokensFromHeaders(token, request) {\n\t\tconst tokens = [token];\n\t\tfor (const headerName of this.headers) {\n\t\t\tconst headerValue = getRequestHeader(request, headerName);\n\t\t\tif (headerValue) tokens.push(this.stripBearerPrefix(headerValue));\n\t\t}\n\t\treturn tokens;\n\t}\n};\n//#endregion\nexport { CompositeAuth, MastraAuthProvider, SimpleAuth, hasAuthInit, isAuthHttpHandler, isCredentialsProvider, isOrganizationsProvider, isSSOProvider, isSessionProvider, isUserProvider };\n\n//# sourceMappingURL=index.js.map","/**\n * Shared types for Okta integration.\n */\n\nimport type { EEUser, RoleMapping } from '@internal/auth/ee';\nimport type { JWTPayload } from 'jose';\n\n// ============================================================================\n// User Types\n// ============================================================================\n\n/**\n * Extended EEUser with Okta-specific fields.\n */\nexport interface OktaUser extends EEUser {\n  /** Okta user ID */\n  oktaId: string;\n  /** User's Okta groups (if fetched) */\n  groups?: string[];\n}\n\n/**\n * Maps Okta JWT claims to OktaUser format.\n *\n * @param payload - JWT payload from Okta token\n * @returns OktaUser object\n */\nexport function mapOktaClaimsToUser(payload: JWTPayload): OktaUser {\n  return {\n    id: (payload.sub as string) || (payload.uid as string) || '',\n    oktaId: (payload.sub as string) || (payload.uid as string) || '',\n    email: payload.email as string | undefined,\n    name:\n      (payload.name as string) ||\n      [payload.given_name, payload.family_name].filter(Boolean).join(' ') ||\n      (payload.email as string) ||\n      undefined,\n    avatarUrl: payload.picture as string | undefined,\n    groups: payload.groups as string[] | undefined,\n    metadata: {\n      oktaId: payload.sub,\n      emailVerified: payload.email_verified,\n      updatedAt: payload.updated_at,\n    },\n  };\n}\n\n// ============================================================================\n// Auth Provider Options\n// ============================================================================\n\n/**\n * Session configuration options for MastraAuthOkta.\n */\nexport interface OktaSessionOptions {\n  /** Cookie name (default: 'okta_session') */\n  cookieName?: string;\n  /** Cookie max age in seconds (default: 86400 = 24 hours) */\n  cookieMaxAge?: number;\n  /**\n   * Password for encrypting session cookies.\n   * Must be at least 32 characters.\n   * Defaults to OKTA_COOKIE_PASSWORD env var.\n   */\n  cookiePassword?: string;\n  /**\n   * Set the Secure flag on session cookies.\n   * Defaults to true when NODE_ENV=production, false otherwise.\n   */\n  secureCookies?: boolean;\n}\n\n/**\n * Options for MastraAuthOkta.\n */\nexport interface MastraAuthOktaOptions {\n  /** Okta domain (e.g., 'dev-123456.okta.com'). Defaults to OKTA_DOMAIN env var. */\n  domain?: string;\n  /** Okta OAuth client ID. Defaults to OKTA_CLIENT_ID env var. */\n  clientId?: string;\n  /** Okta OAuth client secret. Defaults to OKTA_CLIENT_SECRET env var. Required for SSO. */\n  clientSecret?: string;\n  /**\n   * Token issuer URL.\n   * Defaults to OKTA_ISSUER env var or `https://{domain}/oauth2/default`.\n   */\n  issuer?: string;\n  /**\n   * OAuth redirect URI for SSO callback.\n   * Defaults to OKTA_REDIRECT_URI env var.\n   */\n  redirectUri?: string;\n  /**\n   * Expected `aud` claim when verifying bearer tokens.\n   * Defaults to OKTA_AUDIENCE env var, then to the client ID (the ID-token audience).\n   *\n   * Set this to accept Okta access tokens:\n   * - org authorization server: `https://{domain}`\n   * - custom authorization server: the configured audience, e.g. `api://default`\n   *\n   * Pass an array to accept more than one, e.g. ID tokens from the browser and\n   * access tokens from service callers against the same provider.\n   */\n  audience?: string | string[];\n  /**\n   * OAuth scopes to request.\n   * Default: ['openid', 'profile', 'email', 'groups']\n   */\n  scopes?: string[];\n  /**\n   * Okta API token for user lookups via the Users API.\n   * Required for getUser() to return user data by ID.\n   * Defaults to OKTA_API_TOKEN env var.\n   */\n  apiToken?: string;\n  /** Session configuration */\n  session?: OktaSessionOptions;\n  /** Custom provider name (default: 'okta') */\n  name?: string;\n}\n\n// ============================================================================\n// RBAC Provider Options\n// ============================================================================\n\n/**\n * Cache configuration options for RBAC permission caching.\n */\nexport interface PermissionCacheOptions {\n  /** Maximum number of users to cache (default: 1000) */\n  maxSize?: number;\n  /** Time-to-live in milliseconds (default: 60000) */\n  ttlMs?: number;\n}\n\n/**\n * Options for MastraRBACOkta.\n */\nexport interface MastraRBACOktaOptions {\n  /** Okta domain (e.g., 'dev-123456.okta.com'). Defaults to OKTA_DOMAIN env var. */\n  domain?: string;\n\n  /** Okta API token for management SDK. Defaults to OKTA_API_TOKEN env var. */\n  apiToken?: string;\n\n  /**\n   * Map Okta groups to Mastra permissions.\n   *\n   * @example\n   * ```typescript\n   * roleMapping: {\n   *   'Engineering': ['agents:*', 'workflows:*'],\n   *   'Admin': ['*'],\n   *   'Viewer': ['agents:read', 'workflows:read'],\n   *   '_default': [],\n   * }\n   * ```\n   */\n  roleMapping: RoleMapping;\n\n  /**\n   * Function to extract Okta user ID from any user object.\n   * Use this when using a different auth provider (e.g., Auth0) with Okta RBAC.\n   *\n   * @example\n   * ```typescript\n   * getUserId: (user) => user.metadata?.oktaUserId || user.email\n   * ```\n   */\n  getUserId?: (user: unknown) => string | undefined;\n\n  /** Permission cache configuration */\n  cache?: PermissionCacheOptions;\n}\n","/**\n * MastraAuthOkta - Okta authentication provider for Mastra with SSO support.\n *\n * Supports OAuth 2.0 / OIDC login flow with client_secret and session management.\n */\n\nimport type {\n  ISSOProvider,\n  ISessionProvider,\n  IUserProvider,\n  MastraAuthRequest,\n  Session,\n  SSOCallbackResult,\n  SSOLoginConfig,\n} from '@internal/auth';\nimport { getRequestHeader } from '@internal/auth';\nimport type { MastraAuthProviderOptions } from '@internal/auth/provider';\nimport { MastraAuthProvider } from '@internal/auth/provider';\nimport { createRemoteJWKSet, jwtVerify } from 'jose';\n\nimport type { OktaUser, MastraAuthOktaOptions } from './types.js';\nimport { mapOktaClaimsToUser } from './types.js';\n\n/**\n * Trim trailing slashes. Index scan instead of regex to avoid backtracking\n * (CodeQL js/polynomial-redos).\n */\nfunction trimTrailingSlashes(value: string): string {\n  let end = value.length;\n  while (end > 0 && value[end - 1] === '/') end--;\n  return value.slice(0, end);\n}\n\n/** Default cookie name for Okta sessions */\nconst DEFAULT_COOKIE_NAME = 'okta_session';\n\n/** Default cookie max age (24 hours) */\nconst DEFAULT_COOKIE_MAX_AGE = 86400;\n\n/** Default OAuth scopes */\nconst DEFAULT_SCOPES = ['openid', 'profile', 'email', 'groups'];\n\n/** PBKDF2 salt length in bytes */\nconst SALT_LENGTH = 16;\n\n/** AES-GCM IV length in bytes */\nconst IV_LENGTH = 12;\n\n/**\n * Derive an AES-GCM key from password + salt using PBKDF2.\n */\nasync function deriveKey(password: string, salt: Uint8Array, usage: 'encrypt' | 'decrypt') {\n  const encoder = new TextEncoder();\n  const keyMaterial = await crypto.subtle.importKey('raw', encoder.encode(password), 'PBKDF2', false, [\n    'deriveBits',\n    'deriveKey',\n  ]);\n  return crypto.subtle.deriveKey(\n    { name: 'PBKDF2', salt, iterations: 100000, hash: 'SHA-256' },\n    keyMaterial,\n    { name: 'AES-GCM', length: 256 },\n    false,\n    [usage],\n  );\n}\n\n/**\n * Encrypt session data for cookie storage.\n * Format: base64(salt || iv || ciphertext)\n * Salt is random per-encryption to ensure unique derived keys.\n */\nasync function encryptSession(data: unknown, password: string): Promise<string> {\n  const encoder = new TextEncoder();\n  const salt = crypto.getRandomValues(new Uint8Array(SALT_LENGTH));\n  const key = await deriveKey(password, salt, 'encrypt');\n  const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH));\n  const encrypted = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, encoder.encode(JSON.stringify(data)));\n  const combined = new Uint8Array(salt.length + iv.length + new Uint8Array(encrypted).length);\n  combined.set(salt);\n  combined.set(iv, salt.length);\n  combined.set(new Uint8Array(encrypted), salt.length + iv.length);\n  return btoa(String.fromCharCode(...combined));\n}\n\n/**\n * Decrypt session data from cookie.\n * Reads the random salt from the ciphertext prefix to derive the same key.\n */\nasync function decryptSession(encrypted: string, password: string): Promise<unknown> {\n  const combined = Uint8Array.from(atob(encrypted), c => c.charCodeAt(0));\n  const salt = combined.slice(0, SALT_LENGTH);\n  const iv = combined.slice(SALT_LENGTH, SALT_LENGTH + IV_LENGTH);\n  const data = combined.slice(SALT_LENGTH + IV_LENGTH);\n  const key = await deriveKey(password, salt, 'decrypt');\n  const decrypted = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, data);\n  return JSON.parse(new TextDecoder().decode(decrypted));\n}\n\n/**\n * In-memory store for state validation (keyed by state).\n * Used to validate that callback state matches the login request.\n */\nconst stateStore = new Map<string, { expiresAt: number; redirectUri: string }>();\n\n/**\n * Mastra authentication provider for Okta with SSO support.\n *\n * Implements OAuth 2.0 / OIDC login flow with encrypted session cookies.\n *\n * @example Basic usage with SSO\n * ```typescript\n * import { MastraAuthOkta } from '@mastra/auth-okta';\n *\n * const auth = new MastraAuthOkta({\n *   domain: 'dev-123456.okta.com',\n *   clientId: 'your-client-id',\n *   clientSecret: 'your-client-secret',\n *   redirectUri: 'http://localhost:4111/api/auth/callback',\n * });\n * ```\n */\nexport class MastraAuthOkta\n  extends MastraAuthProvider<OktaUser>\n  implements ISSOProvider<OktaUser>, ISessionProvider<Session>, IUserProvider<OktaUser>\n{\n  protected domain: string;\n  protected clientId: string;\n  protected clientSecret: string;\n  protected issuer: string;\n  protected endpointBase: string;\n  protected redirectUri: string;\n  protected audience: string | string[];\n  protected scopes: string[];\n  protected cookieName: string;\n  protected cookieMaxAge: number;\n  protected cookiePassword: string;\n  protected secureCookies: boolean;\n  protected apiToken?: string;\n  private jwks: ReturnType<typeof createRemoteJWKSet>;\n\n  constructor(options?: MastraAuthOktaOptions) {\n    super({ name: options?.name ?? 'okta' });\n\n    const domain = options?.domain ?? process.env.OKTA_DOMAIN;\n    const clientId = options?.clientId ?? process.env.OKTA_CLIENT_ID;\n    const clientSecret = options?.clientSecret ?? process.env.OKTA_CLIENT_SECRET;\n    const issuer = options?.issuer ?? process.env.OKTA_ISSUER;\n    const redirectUri = options?.redirectUri ?? process.env.OKTA_REDIRECT_URI;\n    const cookiePassword =\n      options?.session?.cookiePassword ?? process.env.OKTA_COOKIE_PASSWORD ?? crypto.randomUUID() + crypto.randomUUID();\n\n    if (!domain) {\n      throw new Error('Okta domain is required. Provide it in the options or set OKTA_DOMAIN environment variable.');\n    }\n\n    if (!clientId) {\n      throw new Error(\n        'Okta client ID is required. Provide it in the options or set OKTA_CLIENT_ID environment variable.',\n      );\n    }\n\n    if (!clientSecret) {\n      throw new Error(\n        'Okta client secret is required for SSO. Provide it in the options or set OKTA_CLIENT_SECRET environment variable.',\n      );\n    }\n\n    if (!redirectUri) {\n      throw new Error(\n        'Okta redirect URI is required for SSO. Provide it in the options or set OKTA_REDIRECT_URI environment variable.',\n      );\n    }\n\n    if (cookiePassword.length < 32) {\n      throw new Error('Cookie password must be at least 32 characters. Set OKTA_COOKIE_PASSWORD environment variable.');\n    }\n\n    this.domain = domain;\n    this.clientId = clientId;\n    this.clientSecret = clientSecret;\n    // Normalize trailing slashes so a stray `OKTA_ISSUER=https://domain/` doesn't produce `.../oauth2//v1/...`\n    this.issuer = trimTrailingSlashes(issuer ?? `https://${domain}/oauth2/default`);\n    // Org authorization servers use issuer `https://{domain}` but serve endpoints under `/oauth2/v1/*`.\n    // Custom authorization servers use issuer `https://{domain}/oauth2/<name>` and serve endpoints under `<issuer>/v1/*`.\n    // `issuer` is still used verbatim for JWT `iss`-claim validation on both server types.\n    this.endpointBase =\n      this.issuer.includes('/oauth2/') || this.issuer.endsWith('/oauth2') ? this.issuer : `${this.issuer}/oauth2`;\n    this.redirectUri = redirectUri;\n    // Defaults to the client ID, which is the `aud` of an Okta ID token. Deployments that\n    // send access tokens need the authorization server's audience instead.\n    this.audience = options?.audience ?? process.env.OKTA_AUDIENCE ?? clientId;\n    this.scopes = options?.scopes ?? DEFAULT_SCOPES;\n    this.cookieName = options?.session?.cookieName ?? DEFAULT_COOKIE_NAME;\n    this.cookieMaxAge = options?.session?.cookieMaxAge ?? DEFAULT_COOKIE_MAX_AGE;\n    this.cookiePassword = cookiePassword;\n    this.secureCookies = options?.session?.secureCookies ?? process.env.NODE_ENV === 'production';\n    this.apiToken = options?.apiToken ?? process.env.OKTA_API_TOKEN;\n    this.jwks = createRemoteJWKSet(new URL(`${this.endpointBase}/v1/keys`));\n\n    // Warn about insecure defaults in production\n    if (!options?.session?.cookiePassword && !process.env.OKTA_COOKIE_PASSWORD) {\n      console.warn(\n        '[MastraAuthOkta] No cookie password set — using auto-generated value. Sessions will not survive restarts and will break in multi-instance deployments. Set OKTA_COOKIE_PASSWORD for production use.',\n      );\n    }\n\n    if (process.env.NODE_ENV === 'production') {\n      console.warn(\n        '[MastraAuthOkta] Using in-memory OAuth state store. This will not work in serverless or multi-instance deployments. Consider implementing a custom state store for production.',\n      );\n    }\n\n    this.registerOptions(options as MastraAuthProviderOptions<OktaUser>);\n  }\n\n  // ============================================================================\n  // MastraAuthProvider Implementation\n  // ============================================================================\n\n  /**\n   * Authenticate a token from the request.\n   * First tries to read from session cookie, then falls back to Authorization header.\n   */\n  async authenticateToken(token: string, request: MastraAuthRequest): Promise<OktaUser | null> {\n    // Try session cookie first\n    const sessionUser = await this.getUserFromSession(request);\n    if (sessionUser) {\n      return sessionUser;\n    }\n\n    // Fall back to JWT verification from Authorization header\n    if (!token || typeof token !== 'string') {\n      return null;\n    }\n\n    try {\n      const { payload } = await jwtVerify(token, this.jwks, {\n        issuer: this.issuer,\n        audience: this.audience,\n      });\n\n      return mapOktaClaimsToUser(payload);\n    } catch (err) {\n      console.error('Okta token verification failed:', err);\n      return null;\n    }\n  }\n\n  /**\n   * Authorize a user.\n   */\n  authorizeUser(user: OktaUser, _request: MastraAuthRequest): boolean {\n    if (!user || !user.oktaId) return false;\n    return true;\n  }\n\n  // ============================================================================\n  // IUserProvider Implementation\n  // ============================================================================\n\n  /**\n   * Get the current user from the request session.\n   */\n  async getCurrentUser(request: Request): Promise<OktaUser | null> {\n    return this.getUserFromSession(request);\n  }\n\n  /**\n   * Get a user by ID via the Okta Users API.\n   * Requires an API token (set OKTA_API_TOKEN or pass apiToken in options).\n   * Returns null if no API token is configured or user is not found.\n   */\n  async getUser(userId: string): Promise<OktaUser | null> {\n    if (!this.apiToken) {\n      return null;\n    }\n\n    try {\n      const response = await fetch(`https://${this.domain}/api/v1/users/${userId}`, {\n        headers: {\n          Authorization: `SSWS ${this.apiToken}`,\n          Accept: 'application/json',\n        },\n      });\n\n      if (!response.ok) {\n        return null;\n      }\n\n      const oktaProfile = (await response.json()) as {\n        id: string;\n        profile: {\n          login: string;\n          email: string;\n          firstName?: string;\n          lastName?: string;\n        };\n      };\n\n      return {\n        id: oktaProfile.id,\n        oktaId: oktaProfile.id,\n        email: oktaProfile.profile.email,\n        name: [oktaProfile.profile.firstName, oktaProfile.profile.lastName].filter(Boolean).join(' ') || undefined,\n      };\n    } catch {\n      return null;\n    }\n  }\n\n  /**\n   * Get user from session cookie.\n   */\n  private async getUserFromSession(request: MastraAuthRequest): Promise<OktaUser | null> {\n    try {\n      const cookieHeader = getRequestHeader(request, 'cookie');\n      if (!cookieHeader) return null;\n\n      const cookies = cookieHeader.split(';').map((c: string) => c.trim());\n      const sessionCookie = cookies.find((c: string) => c.startsWith(`${this.cookieName}=`));\n      if (!sessionCookie) return null;\n\n      const sessionValue = sessionCookie.split('=')[1];\n      if (!sessionValue) return null;\n\n      const session = (await decryptSession(decodeURIComponent(sessionValue), this.cookiePassword)) as {\n        user: OktaUser;\n        idToken?: string;\n        expiresAt: number;\n      };\n\n      // Check if session is expired\n      if (session.expiresAt && session.expiresAt < Date.now()) {\n        return null;\n      }\n\n      return session.user;\n    } catch {\n      return null;\n    }\n  }\n\n  /**\n   * Extract the raw ID token from the encrypted session cookie.\n   * Used to provide id_token_hint for Okta logout.\n   */\n  private async getIdTokenFromSession(request: MastraAuthRequest): Promise<string | null> {\n    try {\n      const cookieHeader = getRequestHeader(request, 'cookie');\n      if (!cookieHeader) return null;\n\n      const cookies = cookieHeader.split(';').map((c: string) => c.trim());\n      const sessionCookie = cookies.find((c: string) => c.startsWith(`${this.cookieName}=`));\n      if (!sessionCookie) return null;\n\n      const sessionValue = sessionCookie.split('=')[1];\n      if (!sessionValue) return null;\n\n      const session = (await decryptSession(decodeURIComponent(sessionValue), this.cookiePassword)) as {\n        idToken?: string;\n      };\n      return session.idToken ?? null;\n    } catch {\n      return null;\n    }\n  }\n\n  // ============================================================================\n  // ISSOProvider Implementation\n  // ============================================================================\n\n  /**\n   * Get the URL to redirect users to for Okta login.\n   * Uses client_secret authentication (no PKCE) since this is a confidential client.\n   */\n  getLoginUrl(redirectUri: string, state: string): string {\n    // State format from server: \"uuid|encodedRedirect\"\n    // Extract just the UUID for storage (callback receives only UUID)\n    const stateId = state.includes('|') ? state.split('|')[0]! : state;\n\n    // Store state ID with redirect_uri for validation (expires in 10 minutes)\n    const actualRedirectUri = redirectUri ?? this.redirectUri;\n    stateStore.set(stateId, {\n      expiresAt: Date.now() + 10 * 60 * 1000,\n      redirectUri: actualRedirectUri,\n    });\n\n    // Clean up expired states\n    for (const [key, value] of stateStore.entries()) {\n      if (value.expiresAt < Date.now()) {\n        stateStore.delete(key);\n      }\n    }\n\n    const params = new URLSearchParams({\n      client_id: this.clientId,\n      response_type: 'code',\n      scope: this.scopes.join(' '),\n      redirect_uri: actualRedirectUri,\n      state,\n    });\n\n    return `${this.endpointBase}/v1/authorize?${params.toString()}`;\n  }\n\n  /**\n   * Handle the OAuth callback from Okta.\n   * Note: The server passes only the stateId (UUID part), not the full state.\n   */\n  async handleCallback(code: string, stateId: string): Promise<SSOCallbackResult<OktaUser>> {\n    // Validate state parameter (server passes only the UUID part)\n    const stored = stateStore.get(stateId);\n    if (!stored) {\n      throw new Error('Invalid or expired state parameter');\n    }\n    stateStore.delete(stateId);\n\n    if (stored.expiresAt < Date.now()) {\n      throw new Error('State parameter has expired');\n    }\n\n    // Exchange code for tokens using client_secret (confidential client)\n    const tokenResponse = await fetch(`${this.endpointBase}/v1/token`, {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/x-www-form-urlencoded',\n        Authorization: `Basic ${btoa(`${this.clientId}:${this.clientSecret}`)}`,\n      },\n      body: new URLSearchParams({\n        grant_type: 'authorization_code',\n        code,\n        redirect_uri: stored.redirectUri,\n      }),\n    });\n\n    if (!tokenResponse.ok) {\n      const error = await tokenResponse.text();\n      throw new Error(`Token exchange failed: ${error}`);\n    }\n\n    const tokens = (await tokenResponse.json()) as {\n      access_token: string;\n      id_token: string;\n      refresh_token?: string;\n      expires_in: number;\n      token_type: string;\n    };\n\n    // Verify and decode ID token\n    const { payload: idTokenPayload } = await jwtVerify(tokens.id_token, this.jwks, {\n      issuer: this.issuer,\n      audience: this.clientId,\n    });\n    const user = mapOktaClaimsToUser(idTokenPayload);\n\n    // Create encrypted session cookie.\n    // Only store user claims, id_token (for logout hint), and expiry.\n    // Access/refresh tokens are NOT stored to keep cookie under 4KB browser limit.\n    const sessionData = {\n      user,\n      idToken: tokens.id_token,\n      expiresAt: Date.now() + tokens.expires_in * 1000,\n    };\n\n    const encryptedSession = await encryptSession(sessionData, this.cookiePassword);\n    const cookieValue = `${this.cookieName}=${encodeURIComponent(encryptedSession)}; ${this.cookieFlags(this.cookieMaxAge)}`;\n\n    return {\n      user,\n      tokens: {\n        accessToken: tokens.access_token,\n        refreshToken: tokens.refresh_token,\n        idToken: tokens.id_token,\n        expiresAt: new Date(Date.now() + tokens.expires_in * 1000),\n      },\n      cookies: [cookieValue],\n    };\n  }\n\n  /**\n   * Get the URL to redirect users to for logout.\n   * Includes id_token_hint from session when available (required by Okta).\n   */\n  async getLogoutUrl(redirectUri: string, request?: Request): Promise<string | null> {\n    const params = new URLSearchParams({\n      post_logout_redirect_uri: redirectUri,\n      client_id: this.clientId,\n    });\n\n    // Try to extract id_token from session for id_token_hint (Okta requires this)\n    if (request) {\n      const idToken = await this.getIdTokenFromSession(request);\n      if (idToken) {\n        params.set('id_token_hint', idToken);\n      }\n    }\n\n    return `${this.endpointBase}/v1/logout?${params.toString()}`;\n  }\n\n  /**\n   * Get cookies to set during login.\n   */\n  getLoginCookies(_state: string): string[] {\n    return [];\n  }\n\n  /**\n   * Get the configuration for rendering the login button.\n   */\n  getLoginButtonConfig(): SSOLoginConfig {\n    return {\n      provider: 'okta',\n      text: 'Sign in with Okta',\n    };\n  }\n\n  // ============================================================================\n  // ISessionProvider Implementation\n  // ============================================================================\n\n  async createSession(userId: string, metadata?: Record<string, unknown>): Promise<Session> {\n    const now = new Date();\n    return {\n      id: crypto.randomUUID(),\n      userId,\n      createdAt: now,\n      expiresAt: new Date(now.getTime() + this.cookieMaxAge * 1000),\n      metadata,\n    };\n  }\n\n  async validateSession(_sessionId: string): Promise<Session | null> {\n    return null;\n  }\n\n  async destroySession(_sessionId: string): Promise<void> {\n    // Session is cleared via cookie\n  }\n\n  async refreshSession(_sessionId: string): Promise<Session | null> {\n    return null;\n  }\n\n  getSessionIdFromRequest(_request: Request): string | null {\n    return null;\n  }\n\n  getSessionHeaders(_session: Session): Record<string, string> {\n    return {};\n  }\n\n  getClearSessionHeaders(): Record<string, string> {\n    return {\n      'Set-Cookie': `${this.cookieName}=; ${this.cookieFlags(0)}`,\n    };\n  }\n\n  /**\n   * Build consistent cookie attribute string for set/clear operations.\n   */\n  private cookieFlags(maxAge: number): string {\n    const flags = `Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}`;\n    return this.secureCookies ? `${flags}; Secure` : flags;\n  }\n\n  // ============================================================================\n  // Helper Methods\n  // ============================================================================\n\n  /**\n   * Get the Okta domain.\n   */\n  getDomain(): string {\n    return this.domain;\n  }\n\n  /**\n   * Get the configured client ID.\n   */\n  getClientId(): string {\n    return this.clientId;\n  }\n\n  /**\n   * Get the configured redirect URI.\n   */\n  getRedirectUri(): string {\n    return this.redirectUri;\n  }\n\n  /**\n   * Get the issuer URL.\n   */\n  getIssuer(): string {\n    return this.issuer;\n  }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAm0BA,MAAM,sBAAsB,EAAE,QAAQ;CACrC;CACA;CACA;CACA;CACA;CACA;AACD,EAAE;;;;;;;;;;;;;;;;;;AAkBF,SAAS,kBAAkB,gBAAgB,oBAAoB;CAC9D,IAAI,mBAAmB,KAAK,OAAO;CACnC,MAAM,eAAe,eAAe,MAAM,GAAG;CAC7C,MAAM,gBAAgB,mBAAmB,MAAM,GAAG;CAClD,MAAM,mBAAmB,oBAAoB,aAAa,MAAM;CAChE,IAAI,oBAAoB,iBAAiB,SAAS,cAAc,MAAM,EAAE,GAAG,OAAO,kBAAkB,CAAC,cAAc,IAAI,GAAG,aAAa,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,GAAG,kBAAkB;CAC9K,IAAI,aAAa,SAAS,KAAK,cAAc,SAAS,GAAG,OAAO,mBAAmB;CACnF,MAAM,CAAC,iBAAiB,eAAe,aAAa;CACpD,MAAM,CAAC,kBAAkB,gBAAgB,cAAc;CACvD,IAAI,oBAAoB,KAAK;EAC5B,IAAI,kBAAkB,KAAK;GAC1B,IAAI,cAAc,KAAK,GAAG,OAAO;GACjC,OAAO,cAAc;EACtB;EACA,IAAI,kBAAkB,gBAAgB,OAAO;EAC7C,IAAI,cAAc,KAAK,GAAG,OAAO;EACjC,OAAO,cAAc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