@mastra/auth-studio 1.3.3 → 1.3.4-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/dist/_types/@internal_auth/dist/ee/interfaces/permissions.generated.d.ts +12 -2
- package/dist/_types/@internal_auth/dist/types/index.d.ts +6 -2
- package/dist/index.cjs +125 -108
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +1 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +125 -108
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["#rawConfig"],"sources":["../../../packages/_internals/auth/dist/ee-C8o0LZ3r.js","../../../packages/_internal-core/dist/logger/index.js","../../../packages/_internal-core/dist/base/index.js","../../../packages/_internals/auth/dist/provider/index.js","../src/index.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-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 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/** 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-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/** 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-C8o0LZ3r.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","import { createHash } from 'node:crypto';\n\nimport type {\n IOrganizationsProvider,\n ISSOProvider,\n ISessionProvider,\n IUserProvider,\n Session,\n SSOCallbackResult,\n SSOLoginConfig,\n} from '@internal/auth';\nimport type { EEUser, IRBACProvider, RoleMapping } from '@internal/auth/ee';\nimport { resolvePermissionsFromMapping, matchesPermission } from '@internal/auth/ee';\nimport { MastraAuthProvider } from '@internal/auth/provider';\nimport type { MastraAuthProviderOptions } from '@internal/auth/provider';\n\ntype HonoRequestLike = {\n raw?: Request;\n headers?: Headers;\n header(name: string): string | undefined;\n};\n\ntype MastraAuthRequest = Request | HonoRequestLike;\n\nfunction getRequestHeader(request: MastraAuthRequest, name: string): string | null {\n if (request instanceof Request) {\n return request.headers.get(name);\n }\n\n return request.raw?.headers.get(name) ?? request.headers?.get(name) ?? request.header(name) ?? null;\n}\n\nexport interface StudioUser extends EEUser {\n id: string;\n email?: string;\n name?: string;\n avatarUrl?: string;\n organizationId?: string;\n role?: string;\n permissions?: string[];\n /** All organization IDs the user is a member of (for cross-org access checks) */\n memberOrgIds?: string[];\n}\n\nexport interface MastraAuthStudioOptions extends MastraAuthProviderOptions<StudioUser> {\n /** Base URL of the Mastra shared API (e.g., https://api.mastra.ai/v1) */\n sharedApiUrl?: string;\n /** Organization ID that owns this deployed instance. Users not in this org are rejected. */\n organizationId?: string;\n /**\n * Cookie domain for session cookies (e.g., '.example.com').\n * When set, cookies will include Secure and Domain attributes.\n * Defaults to auto-detecting from sharedApiUrl (uses '.mastra.ai' when sharedApiUrl contains '.mastra.ai').\n * Can also be set via MASTRA_COOKIE_DOMAIN environment variable.\n */\n cookieDomain?: string;\n}\n\nconst COOKIE_NAME = 'wos-session';\n\n/**\n * Upper bound for shared-API verification fetches. Matches the platform API\n * client's request budget: a slow shared API must fail a single request in\n * bounded time instead of hanging every authenticated endpoint behind it.\n */\nconst VERIFY_FETCH_TIMEOUT_MS = 15_000;\n\n/**\n * How long a successful credential verification may be reused without\n * re-contacting the shared API. Bounds revocation lag: a signed-out or\n * revoked session can be honored for at most this long.\n */\nconst VERIFY_CACHE_TTL_MS = 30_000;\n\n/**\n * Auth provider for Mastra Studio deployed instances.\n *\n * Proxies all authentication through the shared API, keeping the\n * WorkOS API key safely in the shared API. Deployed instances only\n * need the shared API URL — no secrets required.\n *\n * The shared API's sealed session cookie (`wos-session`) is set with\n * `Domain=.mastra.ai` in production, so it's included in requests\n * to deployed instances and can be forwarded for validation.\n */\nexport class MastraAuthStudio\n extends MastraAuthProvider<StudioUser>\n implements ISSOProvider<StudioUser>, ISessionProvider<Session>, IUserProvider<StudioUser>, IOrganizationsProvider\n{\n readonly isMastraCloudAuth = true;\n\n private sharedApiUrl: string;\n private organizationId: string | undefined;\n private useProductionCookies: boolean;\n private cookieDomain: string | undefined;\n /**\n * `userId → sealed session cookie` cache. The `IOrganizationsProvider`\n * interface only hands us a `userId`, but the shared API's org endpoints are\n * cookie-authenticated — so we remember the cookie last seen for a user\n * inside `verifySessionCookie` and reuse it here. Kept small: bounded to\n * the last 1000 users, LRU-evicted on insert.\n */\n private userSessionCookies = new Map<string, string>();\n private readonly maxCachedSessions = 1000;\n\n /**\n * Short-TTL cache of SUCCESSFUL credential verifications, keyed by a\n * sha256 of the credential (never the raw cookie/token). Every protected\n * request re-verifies against the shared API otherwise — one network\n * round trip per request. Failures are never cached, so a rejected\n * credential is always re-checked. Bounded + insert-order evicted.\n */\n private verifiedCredentials = new Map<string, { user: StudioUser; expiresAt: number }>();\n private readonly maxCachedVerifications = 1000;\n\n /**\n * In-flight `ensureOrganization` promises keyed by userId. Concurrent calls\n * for the same brand-new user (multiple tabs, parallel requests) would\n * otherwise all see \"no org\" from `GET /auth/me` and each fire\n * `POST /auth/orgs`, creating duplicate personal organizations. The first\n * caller's promise is reused by every follower until it settles.\n */\n private organizationBootstrapInFlight = new Map<string, Promise<string | undefined>>();\n\n constructor(options?: MastraAuthStudioOptions) {\n super({ name: 'mastra-studio', ...options });\n const explicitSharedApiUrl = options?.sharedApiUrl || process.env.MASTRA_SHARED_API_URL;\n this.sharedApiUrl = explicitSharedApiUrl || 'https://platform.mastra.ai/v1';\n this.organizationId = options?.organizationId || process.env.MASTRA_ORGANIZATION_ID;\n\n // Strip trailing slash\n if (this.sharedApiUrl.endsWith('/')) {\n this.sharedApiUrl = this.sharedApiUrl.slice(0, -1);\n }\n\n // Cookie domain can be explicitly configured, read from env, or auto-detected from sharedApiUrl\n this.cookieDomain = options?.cookieDomain || process.env.MASTRA_COOKIE_DOMAIN;\n\n // Use production cookie settings (Secure + Domain) when:\n // 1. An explicit cookieDomain is configured, OR\n // 2. The shared API is *explicitly* configured on .mastra.ai (auto-detect\n // default domain). The built-in platform.mastra.ai fallback doesn't\n // count — a localhost studio using the default would otherwise mint\n // Domain=.mastra.ai cookies the browser rejects.\n // Use hostname-based detection to avoid false positives (e.g., api.mastra.ai.evil.com)\n let autoDetectMastraAi = false;\n if (explicitSharedApiUrl) {\n try {\n const hostname = new URL(this.sharedApiUrl).hostname.toLowerCase();\n autoDetectMastraAi = hostname === 'mastra.ai' || hostname.endsWith('.mastra.ai');\n } catch {\n autoDetectMastraAi = false;\n }\n }\n this.useProductionCookies = !!this.cookieDomain || autoDetectMastraAi;\n\n // If no explicit domain but we're on .mastra.ai, use the default domain\n if (!this.cookieDomain && autoDetectMastraAi) {\n this.cookieDomain = '.mastra.ai';\n }\n\n if (options) {\n this.registerOptions(options);\n }\n }\n\n // ---------------------------------------------------------------------------\n // MastraAuthProvider abstract methods\n // ---------------------------------------------------------------------------\n\n /**\n * Authenticate an incoming request by forwarding the sealed session cookie\n * to the shared API's /auth/me endpoint, or a Bearer token to /auth/verify.\n */\n async authenticateToken(token: string, request: MastraAuthRequest): Promise<StudioUser | null> {\n let user: StudioUser | null = null;\n\n // Try sealed session cookie first (browser flow)\n const cookieHeader = getRequestHeader(request, 'Cookie');\n const sessionCookie = parseCookie(cookieHeader, COOKIE_NAME);\n\n if (sessionCookie) {\n user = await this.verifySessionCookie(sessionCookie);\n }\n\n // Fall back to Bearer token (CLI / API token flow)\n if (!user && token) {\n user = await this.verifyBearerToken(token);\n }\n\n if (!user) return null;\n\n // Org-scoping: if this instance belongs to a specific org, reject users not a member of that org\n // Check memberOrgIds (all orgs user belongs to) rather than organizationId (current org)\n if (this.organizationId && !user.memberOrgIds?.includes(this.organizationId)) {\n return null;\n }\n\n return user;\n }\n\n authorizeUser(user: StudioUser): boolean {\n return !!user?.id;\n }\n\n // ---------------------------------------------------------------------------\n // ISSOProvider\n // ---------------------------------------------------------------------------\n\n getLoginUrl(redirectUri: string, state: string): string {\n // Extract the post-login redirect from state (format: uuid|encodedPostLoginRedirect)\n let postLoginRedirect = '/';\n if (state) {\n const pipeIndex = state.indexOf('|');\n if (pipeIndex !== -1) {\n try {\n postLoginRedirect = decodeURIComponent(state.slice(pipeIndex + 1));\n } catch {\n // ignore decode errors\n }\n }\n }\n\n const params = new URLSearchParams({\n product: 'deploy',\n redirect_uri: redirectUri,\n post_login_redirect: postLoginRedirect,\n // Force re-authentication so AuthKit always shows the account picker\n prompt: 'login',\n ...(this.organizationId ? { organization_id: this.organizationId } : {}),\n });\n\n return `${this.sharedApiUrl}/auth/login?${params.toString()}`;\n }\n\n async handleCallback(code: string, _state: string): Promise<SSOCallbackResult<StudioUser>> {\n // The shared API already consumed the OAuth code and passes the sealed\n // session directly as the `code` parameter in the redirect to this callback.\n // Validate it to get user info.\n this.logger.debug('SSO callback: validating sealed session via shared API', {\n sharedApiUrl: this.sharedApiUrl,\n codeLength: code?.length,\n });\n const user = await this.verifySessionCookie(code);\n if (!user) {\n this.logger.error('SSO callback: session validation failed — verifySessionCookie returned null', {\n sharedApiUrl: this.sharedApiUrl,\n codeLength: code?.length,\n });\n throw new Error('Session validation failed');\n }\n\n // Omit `cookies` so the Mastra server fallback path calls\n // createSession() + getSessionHeaders() to build a cookie scoped to\n // the deployed instance's domain.\n return {\n user,\n tokens: {\n accessToken: code,\n },\n };\n }\n\n setCallbackCookieHeader(_cookieHeader: string | null): void {\n // No-op: we don't use PKCE cookies — the shared API handles the full OAuth flow\n }\n\n getLoginCookies(): string[] | undefined {\n // No PKCE cookies needed — shared API manages the OAuth state\n return undefined;\n }\n\n getLoginButtonConfig(): SSOLoginConfig {\n return {\n provider: 'mastra-studio',\n text: 'Sign in with Mastra',\n description:\n 'Your deployed Studio is secured by your Mastra account. Sign in with the same email you used to sign up on mastra.ai.',\n };\n }\n\n async getLogoutUrl(_redirectUri: string, request?: Request): Promise<string | null> {\n const cookieHeader = request?.headers.get('Cookie');\n const sessionCookie = parseCookie(cookieHeader, COOKIE_NAME);\n\n if (!sessionCookie) return null;\n\n try {\n const res = await fetch(`${this.sharedApiUrl}/auth/logout`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Cookie: `${COOKIE_NAME}=${sessionCookie}`,\n },\n });\n\n if (res.ok) {\n const data = (await res.json()) as { ok: boolean; logoutUrl?: string };\n return data.logoutUrl ?? null;\n }\n } catch {\n // Failed to get logout URL — return null\n }\n\n return null;\n }\n\n // ---------------------------------------------------------------------------\n // ISessionProvider\n // ---------------------------------------------------------------------------\n\n async createSession(userId: string, metadata?: Record<string, unknown>): Promise<Session> {\n const now = new Date();\n return {\n id: (metadata?.accessToken as string) || crypto.randomUUID(),\n userId,\n expiresAt: new Date(now.getTime() + 24 * 60 * 60 * 1000), // 24 hours\n createdAt: now,\n metadata,\n };\n }\n\n async validateSession(sessionId: string): Promise<Session | null> {\n const user = await this.verifySessionCookie(sessionId);\n if (!user) return null;\n\n const now = new Date();\n return {\n id: sessionId,\n userId: user.id,\n expiresAt: new Date(now.getTime() + 24 * 60 * 60 * 1000),\n createdAt: now,\n };\n }\n\n async destroySession(sessionId: string): Promise<void> {\n try {\n await fetch(`${this.sharedApiUrl}/auth/logout`, {\n method: 'POST',\n headers: {\n Cookie: `${COOKIE_NAME}=${sessionId}`,\n },\n });\n } catch {\n // Best effort\n }\n }\n\n async refreshSession(sessionId: string): Promise<Session | null> {\n try {\n // Call the shared API's /auth/refresh endpoint to get a fresh access token\n const res = await fetch(`${this.sharedApiUrl}/auth/refresh`, {\n method: 'GET',\n headers: {\n Cookie: `${COOKIE_NAME}=${sessionId}`,\n },\n });\n\n if (!res.ok) {\n this.logger.warn('refreshSession: shared API refresh returned non-OK status', {\n status: res.status,\n url: `${this.sharedApiUrl}/auth/refresh`,\n });\n // Refresh failed, fall back to validation (will likely also fail)\n return this.validateSession(sessionId);\n }\n\n // Parse the new sealed session from Set-Cookie header\n const setCookie = res.headers.get('Set-Cookie');\n const newSessionId = setCookie ? parseCookieFromHeader(setCookie, COOKIE_NAME) : null;\n\n if (!newSessionId) {\n this.logger.warn('refreshSession: no Set-Cookie header in refresh response');\n // No new cookie returned, fall back to validation with original\n return this.validateSession(sessionId);\n }\n\n // Verify the new session works and return it\n const user = await this.verifySessionCookie(newSessionId);\n if (!user) return null;\n\n const now = new Date();\n return {\n id: newSessionId,\n userId: user.id,\n expiresAt: new Date(now.getTime() + 24 * 60 * 60 * 1000),\n createdAt: now,\n };\n } catch (error) {\n this.logger.error('refreshSession: fetch to shared API failed', {\n url: `${this.sharedApiUrl}/auth/refresh`,\n error: error instanceof Error ? { message: error.message, stack: error.stack } : String(error),\n });\n // On error, fall back to validation\n return this.validateSession(sessionId);\n }\n }\n\n getSessionIdFromRequest(request: Request): string | null {\n const cookieHeader = request.headers.get('Cookie');\n return parseCookie(cookieHeader, COOKIE_NAME);\n }\n\n getSessionHeaders(session: Session): Record<string, string> {\n const parts = [`${COOKIE_NAME}=${session.id}`, 'HttpOnly', 'SameSite=Lax', 'Path=/', 'Max-Age=86400'];\n if (this.useProductionCookies && this.cookieDomain) {\n parts.push('Secure');\n parts.push(`Domain=${this.cookieDomain}`);\n }\n return { 'Set-Cookie': parts.join('; ') };\n }\n\n getClearSessionHeaders(): Record<string, string> {\n const parts = [`${COOKIE_NAME}=`, 'HttpOnly', 'SameSite=Lax', 'Path=/', 'Max-Age=0'];\n if (this.useProductionCookies && this.cookieDomain) {\n parts.push('Secure');\n parts.push(`Domain=${this.cookieDomain}`);\n }\n return { 'Set-Cookie': parts.join('; ') };\n }\n\n // ---------------------------------------------------------------------------\n // IUserProvider\n // ---------------------------------------------------------------------------\n\n async getCurrentUser(request: Request): Promise<StudioUser | null> {\n const cookieHeader = request.headers.get('Cookie');\n const sessionCookie = parseCookie(cookieHeader, COOKIE_NAME);\n\n if (sessionCookie) {\n return this.verifySessionCookie(sessionCookie);\n }\n\n // Try bearer token\n const authHeader = request.headers.get('Authorization');\n if (authHeader?.startsWith('Bearer ')) {\n return this.verifyBearerToken(authHeader.slice(7));\n }\n\n return null;\n }\n\n async getUser(_userId: string): Promise<StudioUser | null> {\n // Cannot look up users by ID — only validate sessions\n return null;\n }\n\n // ---------------------------------------------------------------------------\n // IOrganizationsProvider\n // ---------------------------------------------------------------------------\n\n /**\n * Ensure the user belongs to an organization, bootstrapping a personal org\n * on first use when they have none.\n *\n * Because the shared API's org endpoints are cookie-authenticated but this\n * method only receives a userId, we look up the user's sealed session cookie\n * from the {@link userSessionCookies} cache populated by\n * {@link verifySessionCookie}. If we have never seen a cookie for this user\n * (e.g. bearer-token flow, or the cache was evicted), we skip bootstrap and\n * return `undefined` — the caller keeps the user in their current no-org\n * state and the next authenticated request retries.\n *\n * Best-effort: any shared-API failure returns `undefined` rather than\n * throwing, mirroring `MastraAuthWorkos.ensureOrganization`.\n */\n async ensureOrganization(userId: string): Promise<string | undefined> {\n // Dedupe concurrent bootstraps for the same user — otherwise parallel tabs\n // for a brand-new user each POST /auth/orgs and create duplicate personal\n // organizations.\n const inFlight = this.organizationBootstrapInFlight.get(userId);\n if (inFlight) return inFlight;\n\n const bootstrap = this.doEnsureOrganization(userId).finally(() => {\n this.organizationBootstrapInFlight.delete(userId);\n });\n this.organizationBootstrapInFlight.set(userId, bootstrap);\n return bootstrap;\n }\n\n private async doEnsureOrganization(userId: string): Promise<string | undefined> {\n const sessionCookie = this.userSessionCookies.get(userId);\n if (!sessionCookie) {\n this.logger.debug('ensureOrganization: no cached session cookie for user; skipping bootstrap', { userId });\n return undefined;\n }\n\n try {\n // Check /auth/me first — the session may already carry an organizationId\n // (existing user) or memberOrgIds we can pick from (multi-org user with\n // no active selection).\n const me = await this.fetchMe(sessionCookie);\n if (me?.organizationId) return me.organizationId;\n if (me?.memberOrgIds && me.memberOrgIds.length > 0) return me.memberOrgIds[0];\n\n // No org anywhere → create a personal org. The shared API auto-switches\n // the session cookie to the new org, but the browser holds the sealed\n // cookie, not us, so we can't update it in-place. Next validated request\n // will observe the new org via /auth/me.\n const orgName = me?.user?.email ? `${me.user.email}'s org` : `Personal (${userId})`;\n const res = await fetch(`${this.sharedApiUrl}/auth/orgs`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Cookie: `${COOKIE_NAME}=${sessionCookie}`,\n },\n body: JSON.stringify({ name: orgName }),\n });\n\n if (!res.ok) {\n this.logger.warn('ensureOrganization: shared API POST /auth/orgs returned non-OK', {\n status: res.status,\n userId,\n });\n return undefined;\n }\n\n const data = (await res.json()) as { organization?: { id?: string } };\n return data.organization?.id;\n } catch (error) {\n this.logger.error('ensureOrganization: fetch to shared API failed', {\n userId,\n error: error instanceof Error ? { message: error.message, stack: error.stack } : String(error),\n });\n return undefined;\n }\n }\n\n /**\n * Whether the user holds an admin-equivalent role in the organization.\n *\n * Fast path: if the org matches the user's currently-active session org, we\n * read the role directly from `/auth/me`. Cross-org path: we call\n * `/auth/orgs` (which returns per-membership roles) and look up the target\n * org. Any shared-API failure resolves to `false`.\n */\n async isOrganizationAdmin(organizationId: string, userId: string): Promise<boolean> {\n const sessionCookie = this.userSessionCookies.get(userId);\n if (!sessionCookie) return false;\n\n try {\n const me = await this.fetchMe(sessionCookie);\n if (me?.organizationId === organizationId) {\n return isAdminRole(me.role);\n }\n\n // Not the active org — fall back to /auth/orgs for the per-org role.\n const res = await fetch(`${this.sharedApiUrl}/auth/orgs`, {\n headers: { Cookie: `${COOKIE_NAME}=${sessionCookie}` },\n });\n if (!res.ok) return false;\n\n const data = (await res.json()) as {\n organizations?: Array<{ id: string; role?: string | null }>;\n };\n const membership = data.organizations?.find(o => o.id === organizationId);\n return isAdminRole(membership?.role ?? undefined);\n } catch {\n return false;\n }\n }\n\n // ---------------------------------------------------------------------------\n // Internal helpers\n // ---------------------------------------------------------------------------\n\n /**\n * Record the sealed session cookie last seen for a user so\n * {@link ensureOrganization} / {@link isOrganizationAdmin} can act on their\n * behalf. LRU-evicted at {@link maxCachedSessions} entries.\n */\n private rememberUserSession(userId: string, sessionCookie: string): void {\n // Refresh recency by re-inserting.\n this.userSessionCookies.delete(userId);\n this.userSessionCookies.set(userId, sessionCookie);\n if (this.userSessionCookies.size > this.maxCachedSessions) {\n const oldest = this.userSessionCookies.keys().next().value;\n if (oldest !== undefined) this.userSessionCookies.delete(oldest);\n }\n }\n\n /** Cache key for a verified credential — hash, never the raw secret. */\n private verificationKey(kind: 'cookie' | 'bearer', credential: string): string {\n return createHash('sha256').update(`${kind}:${credential}`).digest('hex');\n }\n\n private getCachedVerification(key: string): StudioUser | null {\n const entry = this.verifiedCredentials.get(key);\n if (!entry) return null;\n if (entry.expiresAt <= Date.now()) {\n this.verifiedCredentials.delete(key);\n return null;\n }\n return entry.user;\n }\n\n private cacheVerification(key: string, user: StudioUser): void {\n this.verifiedCredentials.delete(key);\n this.verifiedCredentials.set(key, { user, expiresAt: Date.now() + VERIFY_CACHE_TTL_MS });\n if (this.verifiedCredentials.size > this.maxCachedVerifications) {\n const oldest = this.verifiedCredentials.keys().next().value;\n if (oldest !== undefined) this.verifiedCredentials.delete(oldest);\n }\n }\n\n /**\n * Fetch the shared API's `/auth/me` and return the raw response body, or\n * `null` on any non-OK / network error. Split out so `ensureOrganization`\n * and `isOrganizationAdmin` can reuse it without duplicating the shape.\n */\n private async fetchMe(sessionCookie: string): Promise<{\n user?: { id?: string; email?: string };\n organizationId?: string;\n role?: string;\n memberOrgIds?: string[];\n } | null> {\n try {\n const res = await fetch(`${this.sharedApiUrl}/auth/me`, {\n headers: { Cookie: `${COOKIE_NAME}=${sessionCookie}` },\n signal: AbortSignal.timeout(VERIFY_FETCH_TIMEOUT_MS),\n });\n if (!res.ok) return null;\n return (await res.json()) as {\n user?: { id?: string; email?: string };\n organizationId?: string;\n role?: string;\n memberOrgIds?: string[];\n };\n } catch {\n return null;\n }\n }\n\n /**\n * Forward a sealed session cookie to the shared API's /auth/me endpoint\n * to validate it and get user info.\n */\n private async verifySessionCookie(sessionCookie: string): Promise<StudioUser | null> {\n const cacheKey = this.verificationKey('cookie', sessionCookie);\n const cached = this.getCachedVerification(cacheKey);\n if (cached) {\n // Keep the userId → cookie mapping warm for IOrganizationsProvider.\n this.rememberUserSession(cached.id, sessionCookie);\n return cached;\n }\n\n try {\n const res = await fetch(`${this.sharedApiUrl}/auth/me`, {\n headers: {\n Cookie: `${COOKIE_NAME}=${sessionCookie}`,\n },\n signal: AbortSignal.timeout(VERIFY_FETCH_TIMEOUT_MS),\n });\n\n if (!res.ok) {\n this.logger.warn('verifySessionCookie: shared API returned non-OK status', {\n status: res.status,\n statusText: res.statusText,\n url: `${this.sharedApiUrl}/auth/me`,\n });\n return null;\n }\n\n const data = (await res.json()) as {\n user: {\n id: string;\n email: string;\n firstName: string;\n lastName: string;\n profilePictureUrl?: string;\n };\n organizationId: string;\n role?: string;\n permissions?: string[];\n memberOrgIds?: string[];\n };\n\n // Remember the sealed cookie for this user so IOrganizationsProvider\n // methods (invoked with only a userId) can act on the user's behalf.\n this.rememberUserSession(data.user.id, sessionCookie);\n\n const user: StudioUser = {\n id: data.user.id,\n email: data.user.email,\n name: [data.user.firstName, data.user.lastName].filter(Boolean).join(' ') || undefined,\n avatarUrl: data.user.profilePictureUrl,\n organizationId: data.organizationId,\n role: data.role,\n permissions: data.permissions,\n memberOrgIds: data.memberOrgIds,\n };\n // Don't pin brand-new users in the no-org state: org bootstrap runs on\n // the next request, which must re-read /auth/me to see the new org.\n if (user.organizationId) this.cacheVerification(cacheKey, user);\n return user;\n } catch (error) {\n this.logger.error('verifySessionCookie: fetch to shared API failed', {\n url: `${this.sharedApiUrl}/auth/me`,\n error: error instanceof Error ? { message: error.message, stack: error.stack } : String(error),\n });\n return null;\n }\n }\n\n /**\n * Forward a Bearer token to the shared API's /auth/verify endpoint\n * to validate it and get user info (used for CLI tokens).\n */\n private async verifyBearerToken(token: string): Promise<StudioUser | null> {\n const cacheKey = this.verificationKey('bearer', token);\n const cached = this.getCachedVerification(cacheKey);\n if (cached) return cached;\n\n try {\n const res = await fetch(`${this.sharedApiUrl}/auth/verify`, {\n headers: {\n Authorization: `Bearer ${token}`,\n },\n signal: AbortSignal.timeout(VERIFY_FETCH_TIMEOUT_MS),\n });\n\n if (!res.ok) {\n this.logger.warn('verifyBearerToken: shared API returned non-OK status', {\n status: res.status,\n url: `${this.sharedApiUrl}/auth/verify`,\n });\n return null;\n }\n\n const data = (await res.json()) as {\n user: {\n id: string;\n email: string;\n firstName: string;\n lastName: string;\n };\n organizationId: string;\n role?: string;\n memberOrgIds?: string[];\n };\n\n const user: StudioUser = {\n id: data.user.id,\n email: data.user.email,\n name: [data.user.firstName, data.user.lastName].filter(Boolean).join(' ') || undefined,\n organizationId: data.organizationId,\n role: data.role,\n memberOrgIds: data.memberOrgIds,\n };\n // Same no-org guard as verifySessionCookie: cache only after the user's\n // organization bootstrap has completed.\n if (user.organizationId) this.cacheVerification(cacheKey, user);\n return user;\n } catch (error) {\n this.logger.error('verifyBearerToken: fetch to shared API failed', {\n url: `${this.sharedApiUrl}/auth/verify`,\n error: error instanceof Error ? { message: error.message, stack: error.stack } : String(error),\n });\n return null;\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Cookie helpers\n// ---------------------------------------------------------------------------\n\nfunction parseCookie(cookieHeader: string | null | undefined, name: string): string | null {\n if (!cookieHeader) return null;\n const match = cookieHeader.match(new RegExp(`${name}=([^;]+)`));\n return match?.[1] ?? null;\n}\n\n/**\n * WorkOS AuthKit conventionally uses `admin` / `owner` for admin-equivalent\n * roles; the shared API surfaces the WorkOS role slug directly on\n * `/auth/me` and `/auth/orgs`.\n */\nfunction isAdminRole(role: string | undefined): boolean {\n return role === 'admin' || role === 'owner';\n}\n\n/**\n * Parse a cookie value from a Set-Cookie header.\n * Set-Cookie format: \"name=value; HttpOnly; SameSite=Lax; Path=/; Max-Age=86400\"\n */\nfunction parseCookieFromHeader(setCookieHeader: string, name: string): string | null {\n // Set-Cookie header starts with \"name=value\" followed by optional attributes\n const parts = setCookieHeader.split(';');\n if (parts.length === 0) return null;\n\n const [cookieName, ...valueParts] = parts[0]!.split('=');\n if (cookieName?.trim() !== name) return null;\n\n // Value could contain = characters, so rejoin\n return valueParts.join('=') || null;\n}\n\n// ---------------------------------------------------------------------------\n// MastraRBACStudio — role-based permission provider for Studio auth\n// ---------------------------------------------------------------------------\n\nexport interface MastraRBACStudioOptions {\n /**\n * Mapping from role names to permission arrays.\n *\n * @example\n * ```typescript\n * {\n * admin: ['*'],\n * member: ['agents:read', 'workflows:*'],\n * viewer: ['agents:read', 'workflows:read'],\n * _default: [],\n * }\n * ```\n */\n roleMapping: RoleMapping;\n}\n\n/**\n * RBAC provider for Mastra Studio authentication.\n *\n * Maps user roles (from the shared API's /auth/me endpoint) to Mastra permissions\n * using a configurable role mapping.\n */\nexport class MastraRBACStudio implements IRBACProvider<StudioUser> {\n private options: MastraRBACStudioOptions;\n\n get roleMapping(): RoleMapping {\n return this.options.roleMapping;\n }\n\n constructor(options: MastraRBACStudioOptions) {\n this.options = options;\n }\n\n async getRoles(user: StudioUser): Promise<string[]> {\n return user.role ? [user.role] : [];\n }\n\n async hasRole(user: StudioUser, role: string): Promise<boolean> {\n const roles = await this.getRoles(user);\n return roles.includes(role);\n }\n\n async getPermissions(user: StudioUser): Promise<string[]> {\n const roles = await this.getRoles(user);\n if (roles.length === 0) {\n return this.options.roleMapping['_default'] ?? [];\n }\n return resolvePermissionsFromMapping(roles, this.options.roleMapping);\n }\n\n async hasPermission(user: StudioUser, permission: string): Promise<boolean> {\n const permissions = await this.getPermissions(user);\n return permissions.some(p => matchesPermission(p, permission));\n }\n\n async hasAllPermissions(user: StudioUser, permissions: string[]): Promise<boolean> {\n const userPermissions = await this.getPermissions(user);\n return permissions.every(required => userPermissions.some(p => matchesPermission(p, required)));\n }\n\n async hasAnyPermission(user: StudioUser, permissions: string[]): Promise<boolean> {\n const userPermissions = await this.getPermissions(user);\n return permissions.some(required => userPermissions.some(p => matchesPermission(p, required)));\n }\n}\n"],"mappings":";;;;;;;;;;;;AAszBA,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;CACtB;CACA,IAAI,oBAAoB,kBAAkB,OAAO;CACjD,IAAI,kBAAkB,KAAK;EAC1B,IAAI,cAAc,KAAK,GAAG,OAAO;EACjC,OAAO,cAAc;CACtB;CACA,IAAI,kBAAkB,gBAAgB,OAAO;CAC7C,IAAI,cAAc,KAAK,GAAG,OAAO;CACjC,OAAO,cAAc;AACtB;;;;;;;;;;;;;;;;;;;;;;;;;;;AA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cAAc,MAAkB,YAAsC;EAE1E,QAAO,MADmB,KAAK,eAAe,IAAI,EAAA,CAC/B,MAAK,MAAK,kBAAkB,GAAG,UAAU,CAAC;CAC/D;CAEA,MAAM,kBAAkB,MAAkB,aAAyC;EACjF,MAAM,kBAAkB,MAAM,KAAK,eAAe,IAAI;EACtD,OAAO,YAAY,OAAM,aAAY,gBAAgB,MAAK,MAAK,kBAAkB,GAAG,QAAQ,CAAC,CAAC;CAChG;CAEA,MAAM,iBAAiB,MAAkB,aAAyC;EAChF,MAAM,kBAAkB,MAAM,KAAK,eAAe,IAAI;EACtD,OAAO,YAAY,MAAK,aAAY,gBAAgB,MAAK,MAAK,kBAAkB,GAAG,QAAQ,CAAC,CAAC;CAC/F;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["#rawConfig"],"sources":["../../../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","../../../packages/_internals/auth/dist/ee-DXvSoTl7.js","../src/index.ts"],"sourcesContent":["//#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","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","import { createHash } from 'node:crypto';\n\nimport type {\n IOrganizationsProvider,\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 { EEUser, IRBACProvider, RoleMapping } from '@internal/auth/ee';\nimport { resolvePermissionsFromMapping, matchesPermission } from '@internal/auth/ee';\nimport { MastraAuthProvider } from '@internal/auth/provider';\nimport type { MastraAuthProviderOptions } from '@internal/auth/provider';\n\nexport interface StudioUser extends EEUser {\n id: string;\n email?: string;\n name?: string;\n avatarUrl?: string;\n organizationId?: string;\n role?: string;\n permissions?: string[];\n /** All organization IDs the user is a member of (for cross-org access checks) */\n memberOrgIds?: string[];\n}\n\nexport interface MastraAuthStudioOptions extends MastraAuthProviderOptions<StudioUser> {\n /** Base URL of the Mastra shared API (e.g., https://api.mastra.ai/v1) */\n sharedApiUrl?: string;\n /** Organization ID that owns this deployed instance. Users not in this org are rejected. */\n organizationId?: string;\n /**\n * Cookie domain for session cookies (e.g., '.example.com').\n * When set, cookies will include Secure and Domain attributes.\n * Defaults to auto-detecting from sharedApiUrl (uses '.mastra.ai' when sharedApiUrl contains '.mastra.ai').\n * Can also be set via MASTRA_COOKIE_DOMAIN environment variable.\n */\n cookieDomain?: string;\n}\n\nconst COOKIE_NAME = 'wos-session';\n\n/**\n * Upper bound for shared-API verification fetches. Matches the platform API\n * client's request budget: a slow shared API must fail a single request in\n * bounded time instead of hanging every authenticated endpoint behind it.\n */\nconst VERIFY_FETCH_TIMEOUT_MS = 15_000;\n\n/**\n * How long a successful credential verification may be reused without\n * re-contacting the shared API. Bounds revocation lag: a signed-out or\n * revoked session can be honored for at most this long.\n */\nconst VERIFY_CACHE_TTL_MS = 30_000;\n\n/**\n * Auth provider for Mastra Studio deployed instances.\n *\n * Proxies all authentication through the shared API, keeping the\n * WorkOS API key safely in the shared API. Deployed instances only\n * need the shared API URL — no secrets required.\n *\n * The shared API's sealed session cookie (`wos-session`) is set with\n * `Domain=.mastra.ai` in production, so it's included in requests\n * to deployed instances and can be forwarded for validation.\n */\nexport class MastraAuthStudio\n extends MastraAuthProvider<StudioUser>\n implements ISSOProvider<StudioUser>, ISessionProvider<Session>, IUserProvider<StudioUser>, IOrganizationsProvider\n{\n readonly isMastraCloudAuth = true;\n\n private sharedApiUrl: string;\n private organizationId: string | undefined;\n private useProductionCookies: boolean;\n private cookieDomain: string | undefined;\n /**\n * `userId → sealed session cookie` cache. The `IOrganizationsProvider`\n * interface only hands us a `userId`, but the shared API's org endpoints are\n * cookie-authenticated — so we remember the cookie last seen for a user\n * inside `verifySessionCookie` and reuse it here. Kept small: bounded to\n * the last 1000 users, LRU-evicted on insert.\n */\n private userSessionCookies = new Map<string, string>();\n private readonly maxCachedSessions = 1000;\n\n /**\n * Short-TTL cache of SUCCESSFUL credential verifications, keyed by a\n * sha256 of the credential (never the raw cookie/token). Every protected\n * request re-verifies against the shared API otherwise — one network\n * round trip per request. Failures are never cached, so a rejected\n * credential is always re-checked. Bounded + insert-order evicted.\n */\n private verifiedCredentials = new Map<string, { user: StudioUser; expiresAt: number }>();\n private readonly maxCachedVerifications = 1000;\n\n /**\n * In-flight `ensureOrganization` promises keyed by userId. Concurrent calls\n * for the same brand-new user (multiple tabs, parallel requests) would\n * otherwise all see \"no org\" from `GET /auth/me` and each fire\n * `POST /auth/orgs`, creating duplicate personal organizations. The first\n * caller's promise is reused by every follower until it settles.\n */\n private organizationBootstrapInFlight = new Map<string, Promise<string | undefined>>();\n\n constructor(options?: MastraAuthStudioOptions) {\n super({ name: 'mastra-studio', ...options });\n const explicitSharedApiUrl = options?.sharedApiUrl || process.env.MASTRA_SHARED_API_URL;\n this.sharedApiUrl = explicitSharedApiUrl || 'https://platform.mastra.ai/v1';\n this.organizationId = options?.organizationId || process.env.MASTRA_ORGANIZATION_ID;\n\n // Strip trailing slash\n if (this.sharedApiUrl.endsWith('/')) {\n this.sharedApiUrl = this.sharedApiUrl.slice(0, -1);\n }\n\n // Cookie domain can be explicitly configured, read from env, or auto-detected from sharedApiUrl\n this.cookieDomain = options?.cookieDomain || process.env.MASTRA_COOKIE_DOMAIN;\n\n // Use production cookie settings (Secure + Domain) when:\n // 1. An explicit cookieDomain is configured, OR\n // 2. The shared API is *explicitly* configured on .mastra.ai (auto-detect\n // default domain). The built-in platform.mastra.ai fallback doesn't\n // count — a localhost studio using the default would otherwise mint\n // Domain=.mastra.ai cookies the browser rejects.\n // Use hostname-based detection to avoid false positives (e.g., api.mastra.ai.evil.com)\n let autoDetectMastraAi = false;\n if (explicitSharedApiUrl) {\n try {\n const hostname = new URL(this.sharedApiUrl).hostname.toLowerCase();\n autoDetectMastraAi = hostname === 'mastra.ai' || hostname.endsWith('.mastra.ai');\n } catch {\n autoDetectMastraAi = false;\n }\n }\n this.useProductionCookies = !!this.cookieDomain || autoDetectMastraAi;\n\n // If no explicit domain but we're on .mastra.ai, use the default domain\n if (!this.cookieDomain && autoDetectMastraAi) {\n this.cookieDomain = '.mastra.ai';\n }\n\n if (options) {\n this.registerOptions(options);\n }\n }\n\n // ---------------------------------------------------------------------------\n // MastraAuthProvider abstract methods\n // ---------------------------------------------------------------------------\n\n /**\n * Authenticate an incoming request by forwarding the sealed session cookie\n * to the shared API's /auth/me endpoint, or a Bearer token to /auth/verify.\n */\n async authenticateToken(token: string, request: MastraAuthRequest): Promise<StudioUser | null> {\n let user: StudioUser | null = null;\n\n // Try sealed session cookie first (browser flow)\n const cookieHeader = getRequestHeader(request, 'Cookie');\n const sessionCookie = parseCookie(cookieHeader, COOKIE_NAME);\n\n if (sessionCookie) {\n user = await this.verifySessionCookie(sessionCookie);\n }\n\n // Fall back to Bearer token (CLI / API token flow)\n if (!user && token) {\n user = await this.verifyBearerToken(token);\n }\n\n if (!user) return null;\n\n // Org-scoping: if this instance belongs to a specific org, reject users not a member of that org\n // Check memberOrgIds (all orgs user belongs to) rather than organizationId (current org)\n if (this.organizationId && !user.memberOrgIds?.includes(this.organizationId)) {\n return null;\n }\n\n return user;\n }\n\n authorizeUser(user: StudioUser): boolean {\n return !!user?.id;\n }\n\n // ---------------------------------------------------------------------------\n // ISSOProvider\n // ---------------------------------------------------------------------------\n\n getLoginUrl(redirectUri: string, state: string): string {\n // Extract the post-login redirect from state (format: uuid|encodedPostLoginRedirect)\n let postLoginRedirect = '/';\n if (state) {\n const pipeIndex = state.indexOf('|');\n if (pipeIndex !== -1) {\n try {\n postLoginRedirect = decodeURIComponent(state.slice(pipeIndex + 1));\n } catch {\n // ignore decode errors\n }\n }\n }\n\n const params = new URLSearchParams({\n product: 'deploy',\n redirect_uri: redirectUri,\n post_login_redirect: postLoginRedirect,\n // Force re-authentication so AuthKit always shows the account picker\n prompt: 'login',\n ...(this.organizationId ? { organization_id: this.organizationId } : {}),\n });\n\n return `${this.sharedApiUrl}/auth/login?${params.toString()}`;\n }\n\n async handleCallback(code: string, _state: string): Promise<SSOCallbackResult<StudioUser>> {\n // The shared API already consumed the OAuth code and passes the sealed\n // session directly as the `code` parameter in the redirect to this callback.\n // Validate it to get user info.\n this.logger.debug('SSO callback: validating sealed session via shared API', {\n sharedApiUrl: this.sharedApiUrl,\n codeLength: code?.length,\n });\n const user = await this.verifySessionCookie(code);\n if (!user) {\n this.logger.error('SSO callback: session validation failed — verifySessionCookie returned null', {\n sharedApiUrl: this.sharedApiUrl,\n codeLength: code?.length,\n });\n throw new Error('Session validation failed');\n }\n\n // Omit `cookies` so the Mastra server fallback path calls\n // createSession() + getSessionHeaders() to build a cookie scoped to\n // the deployed instance's domain.\n return {\n user,\n tokens: {\n accessToken: code,\n },\n };\n }\n\n setCallbackCookieHeader(_cookieHeader: string | null): void {\n // No-op: we don't use PKCE cookies — the shared API handles the full OAuth flow\n }\n\n getLoginCookies(): string[] | undefined {\n // No PKCE cookies needed — shared API manages the OAuth state\n return undefined;\n }\n\n getLoginButtonConfig(): SSOLoginConfig {\n return {\n provider: 'mastra-studio',\n text: 'Sign in with Mastra',\n description:\n 'Your deployed Studio is secured by your Mastra account. Sign in with the same email you used to sign up on mastra.ai.',\n };\n }\n\n async getLogoutUrl(_redirectUri: string, request?: Request): Promise<string | null> {\n const cookieHeader = request?.headers.get('Cookie');\n const sessionCookie = parseCookie(cookieHeader, COOKIE_NAME);\n\n if (!sessionCookie) return null;\n\n try {\n const res = await fetch(`${this.sharedApiUrl}/auth/logout`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Cookie: `${COOKIE_NAME}=${sessionCookie}`,\n },\n });\n\n if (res.ok) {\n const data = (await res.json()) as { ok: boolean; logoutUrl?: string };\n return data.logoutUrl ?? null;\n }\n } catch {\n // Failed to get logout URL — return null\n }\n\n return null;\n }\n\n // ---------------------------------------------------------------------------\n // ISessionProvider\n // ---------------------------------------------------------------------------\n\n async createSession(userId: string, metadata?: Record<string, unknown>): Promise<Session> {\n const now = new Date();\n return {\n id: (metadata?.accessToken as string) || crypto.randomUUID(),\n userId,\n expiresAt: new Date(now.getTime() + 24 * 60 * 60 * 1000), // 24 hours\n createdAt: now,\n metadata,\n };\n }\n\n async validateSession(sessionId: string): Promise<Session | null> {\n const user = await this.verifySessionCookie(sessionId);\n if (!user) return null;\n\n const now = new Date();\n return {\n id: sessionId,\n userId: user.id,\n expiresAt: new Date(now.getTime() + 24 * 60 * 60 * 1000),\n createdAt: now,\n };\n }\n\n async destroySession(sessionId: string): Promise<void> {\n try {\n await fetch(`${this.sharedApiUrl}/auth/logout`, {\n method: 'POST',\n headers: {\n Cookie: `${COOKIE_NAME}=${sessionId}`,\n },\n });\n } catch {\n // Best effort\n }\n }\n\n async refreshSession(sessionId: string): Promise<Session | null> {\n try {\n // Call the shared API's /auth/refresh endpoint to get a fresh access token\n const res = await fetch(`${this.sharedApiUrl}/auth/refresh`, {\n method: 'GET',\n headers: {\n Cookie: `${COOKIE_NAME}=${sessionId}`,\n },\n });\n\n if (!res.ok) {\n this.logger.warn('refreshSession: shared API refresh returned non-OK status', {\n status: res.status,\n url: `${this.sharedApiUrl}/auth/refresh`,\n });\n // Refresh failed, fall back to validation (will likely also fail)\n return this.validateSession(sessionId);\n }\n\n // Parse the new sealed session from Set-Cookie header\n const setCookie = res.headers.get('Set-Cookie');\n const newSessionId = setCookie ? parseCookieFromHeader(setCookie, COOKIE_NAME) : null;\n\n if (!newSessionId) {\n this.logger.warn('refreshSession: no Set-Cookie header in refresh response');\n // No new cookie returned, fall back to validation with original\n return this.validateSession(sessionId);\n }\n\n // Verify the new session works and return it\n const user = await this.verifySessionCookie(newSessionId);\n if (!user) return null;\n\n const now = new Date();\n return {\n id: newSessionId,\n userId: user.id,\n expiresAt: new Date(now.getTime() + 24 * 60 * 60 * 1000),\n createdAt: now,\n };\n } catch (error) {\n this.logger.error('refreshSession: fetch to shared API failed', {\n url: `${this.sharedApiUrl}/auth/refresh`,\n error: error instanceof Error ? { message: error.message, stack: error.stack } : String(error),\n });\n // On error, fall back to validation\n return this.validateSession(sessionId);\n }\n }\n\n getSessionIdFromRequest(request: Request): string | null {\n const cookieHeader = request.headers.get('Cookie');\n return parseCookie(cookieHeader, COOKIE_NAME);\n }\n\n getSessionHeaders(session: Session): Record<string, string> {\n const parts = [`${COOKIE_NAME}=${session.id}`, 'HttpOnly', 'SameSite=Lax', 'Path=/', 'Max-Age=86400'];\n if (this.useProductionCookies && this.cookieDomain) {\n parts.push('Secure');\n parts.push(`Domain=${this.cookieDomain}`);\n }\n return { 'Set-Cookie': parts.join('; ') };\n }\n\n getClearSessionHeaders(): Record<string, string> {\n const parts = [`${COOKIE_NAME}=`, 'HttpOnly', 'SameSite=Lax', 'Path=/', 'Max-Age=0'];\n if (this.useProductionCookies && this.cookieDomain) {\n parts.push('Secure');\n parts.push(`Domain=${this.cookieDomain}`);\n }\n return { 'Set-Cookie': parts.join('; ') };\n }\n\n // ---------------------------------------------------------------------------\n // IUserProvider\n // ---------------------------------------------------------------------------\n\n async getCurrentUser(request: Request): Promise<StudioUser | null> {\n const cookieHeader = request.headers.get('Cookie');\n const sessionCookie = parseCookie(cookieHeader, COOKIE_NAME);\n\n if (sessionCookie) {\n return this.verifySessionCookie(sessionCookie);\n }\n\n // Try bearer token\n const authHeader = request.headers.get('Authorization');\n if (authHeader?.startsWith('Bearer ')) {\n return this.verifyBearerToken(authHeader.slice(7));\n }\n\n return null;\n }\n\n async getUser(_userId: string): Promise<StudioUser | null> {\n // Cannot look up users by ID — only validate sessions\n return null;\n }\n\n // ---------------------------------------------------------------------------\n // IOrganizationsProvider\n // ---------------------------------------------------------------------------\n\n /**\n * Ensure the user belongs to an organization, bootstrapping a personal org\n * on first use when they have none.\n *\n * Because the shared API's org endpoints are cookie-authenticated but this\n * method only receives a userId, we look up the user's sealed session cookie\n * from the {@link userSessionCookies} cache populated by\n * {@link verifySessionCookie}. If we have never seen a cookie for this user\n * (e.g. bearer-token flow, or the cache was evicted), we skip bootstrap and\n * return `undefined` — the caller keeps the user in their current no-org\n * state and the next authenticated request retries.\n *\n * Best-effort: any shared-API failure returns `undefined` rather than\n * throwing, mirroring `MastraAuthWorkos.ensureOrganization`.\n */\n async ensureOrganization(userId: string): Promise<string | undefined> {\n // Dedupe concurrent bootstraps for the same user — otherwise parallel tabs\n // for a brand-new user each POST /auth/orgs and create duplicate personal\n // organizations.\n const inFlight = this.organizationBootstrapInFlight.get(userId);\n if (inFlight) return inFlight;\n\n const bootstrap = this.doEnsureOrganization(userId).finally(() => {\n this.organizationBootstrapInFlight.delete(userId);\n });\n this.organizationBootstrapInFlight.set(userId, bootstrap);\n return bootstrap;\n }\n\n private async doEnsureOrganization(userId: string): Promise<string | undefined> {\n const sessionCookie = this.userSessionCookies.get(userId);\n if (!sessionCookie) {\n this.logger.debug('ensureOrganization: no cached session cookie for user; skipping bootstrap', { userId });\n return undefined;\n }\n\n try {\n // Check /auth/me first — the session may already carry an organizationId\n // (existing user) or memberOrgIds we can pick from (multi-org user with\n // no active selection).\n const me = await this.fetchMe(sessionCookie);\n if (me?.organizationId) return me.organizationId;\n if (me?.memberOrgIds && me.memberOrgIds.length > 0) return me.memberOrgIds[0];\n\n // No org anywhere → create a personal org. The shared API auto-switches\n // the session cookie to the new org, but the browser holds the sealed\n // cookie, not us, so we can't update it in-place. Next validated request\n // will observe the new org via /auth/me.\n const orgName = me?.user?.email ? `${me.user.email}'s org` : `Personal (${userId})`;\n const res = await fetch(`${this.sharedApiUrl}/auth/orgs`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Cookie: `${COOKIE_NAME}=${sessionCookie}`,\n },\n body: JSON.stringify({ name: orgName }),\n });\n\n if (!res.ok) {\n this.logger.warn('ensureOrganization: shared API POST /auth/orgs returned non-OK', {\n status: res.status,\n userId,\n });\n return undefined;\n }\n\n const data = (await res.json()) as { organization?: { id?: string } };\n return data.organization?.id;\n } catch (error) {\n this.logger.error('ensureOrganization: fetch to shared API failed', {\n userId,\n error: error instanceof Error ? { message: error.message, stack: error.stack } : String(error),\n });\n return undefined;\n }\n }\n\n /**\n * Whether the user holds an admin-equivalent role in the organization.\n *\n * Fast path: if the org matches the user's currently-active session org, we\n * read the role directly from `/auth/me`. Cross-org path: we call\n * `/auth/orgs` (which returns per-membership roles) and look up the target\n * org. Any shared-API failure resolves to `false`.\n */\n async isOrganizationAdmin(organizationId: string, userId: string): Promise<boolean> {\n const sessionCookie = this.userSessionCookies.get(userId);\n if (!sessionCookie) return false;\n\n try {\n const me = await this.fetchMe(sessionCookie);\n if (me?.organizationId === organizationId) {\n return isAdminRole(me.role);\n }\n\n // Not the active org — fall back to /auth/orgs for the per-org role.\n const res = await fetch(`${this.sharedApiUrl}/auth/orgs`, {\n headers: { Cookie: `${COOKIE_NAME}=${sessionCookie}` },\n });\n if (!res.ok) return false;\n\n const data = (await res.json()) as {\n organizations?: Array<{ id: string; role?: string | null }>;\n };\n const membership = data.organizations?.find(o => o.id === organizationId);\n return isAdminRole(membership?.role ?? undefined);\n } catch {\n return false;\n }\n }\n\n // ---------------------------------------------------------------------------\n // Internal helpers\n // ---------------------------------------------------------------------------\n\n /**\n * Record the sealed session cookie last seen for a user so\n * {@link ensureOrganization} / {@link isOrganizationAdmin} can act on their\n * behalf. LRU-evicted at {@link maxCachedSessions} entries.\n */\n private rememberUserSession(userId: string, sessionCookie: string): void {\n // Refresh recency by re-inserting.\n this.userSessionCookies.delete(userId);\n this.userSessionCookies.set(userId, sessionCookie);\n if (this.userSessionCookies.size > this.maxCachedSessions) {\n const oldest = this.userSessionCookies.keys().next().value;\n if (oldest !== undefined) this.userSessionCookies.delete(oldest);\n }\n }\n\n /** Cache key for a verified credential — hash, never the raw secret. */\n private verificationKey(kind: 'cookie' | 'bearer', credential: string): string {\n return createHash('sha256').update(`${kind}:${credential}`).digest('hex');\n }\n\n private getCachedVerification(key: string): StudioUser | null {\n const entry = this.verifiedCredentials.get(key);\n if (!entry) return null;\n if (entry.expiresAt <= Date.now()) {\n this.verifiedCredentials.delete(key);\n return null;\n }\n return entry.user;\n }\n\n private cacheVerification(key: string, user: StudioUser): void {\n this.verifiedCredentials.delete(key);\n this.verifiedCredentials.set(key, { user, expiresAt: Date.now() + VERIFY_CACHE_TTL_MS });\n if (this.verifiedCredentials.size > this.maxCachedVerifications) {\n const oldest = this.verifiedCredentials.keys().next().value;\n if (oldest !== undefined) this.verifiedCredentials.delete(oldest);\n }\n }\n\n /**\n * Fetch the shared API's `/auth/me` and return the raw response body, or\n * `null` on any non-OK / network error. Split out so `ensureOrganization`\n * and `isOrganizationAdmin` can reuse it without duplicating the shape.\n */\n private async fetchMe(sessionCookie: string): Promise<{\n user?: { id?: string; email?: string };\n organizationId?: string;\n role?: string;\n memberOrgIds?: string[];\n } | null> {\n try {\n const res = await fetch(`${this.sharedApiUrl}/auth/me`, {\n headers: { Cookie: `${COOKIE_NAME}=${sessionCookie}` },\n signal: AbortSignal.timeout(VERIFY_FETCH_TIMEOUT_MS),\n });\n if (!res.ok) return null;\n return (await res.json()) as {\n user?: { id?: string; email?: string };\n organizationId?: string;\n role?: string;\n memberOrgIds?: string[];\n };\n } catch {\n return null;\n }\n }\n\n /**\n * Forward a sealed session cookie to the shared API's /auth/me endpoint\n * to validate it and get user info.\n */\n private async verifySessionCookie(sessionCookie: string): Promise<StudioUser | null> {\n const cacheKey = this.verificationKey('cookie', sessionCookie);\n const cached = this.getCachedVerification(cacheKey);\n if (cached) {\n // Keep the userId → cookie mapping warm for IOrganizationsProvider.\n this.rememberUserSession(cached.id, sessionCookie);\n return cached;\n }\n\n try {\n const res = await fetch(`${this.sharedApiUrl}/auth/me`, {\n headers: {\n Cookie: `${COOKIE_NAME}=${sessionCookie}`,\n },\n signal: AbortSignal.timeout(VERIFY_FETCH_TIMEOUT_MS),\n });\n\n if (!res.ok) {\n this.logger.warn('verifySessionCookie: shared API returned non-OK status', {\n status: res.status,\n statusText: res.statusText,\n url: `${this.sharedApiUrl}/auth/me`,\n });\n return null;\n }\n\n const data = (await res.json()) as {\n user: {\n id: string;\n email: string;\n firstName: string;\n lastName: string;\n profilePictureUrl?: string;\n };\n organizationId: string;\n role?: string;\n permissions?: string[];\n memberOrgIds?: string[];\n };\n\n // Remember the sealed cookie for this user so IOrganizationsProvider\n // methods (invoked with only a userId) can act on the user's behalf.\n this.rememberUserSession(data.user.id, sessionCookie);\n\n const user: StudioUser = {\n id: data.user.id,\n email: data.user.email,\n name: [data.user.firstName, data.user.lastName].filter(Boolean).join(' ') || undefined,\n avatarUrl: data.user.profilePictureUrl,\n organizationId: data.organizationId,\n role: data.role,\n permissions: data.permissions,\n memberOrgIds: data.memberOrgIds,\n };\n // Don't pin brand-new users in the no-org state: org bootstrap runs on\n // the next request, which must re-read /auth/me to see the new org.\n if (user.organizationId) this.cacheVerification(cacheKey, user);\n return user;\n } catch (error) {\n this.logger.error('verifySessionCookie: fetch to shared API failed', {\n url: `${this.sharedApiUrl}/auth/me`,\n error: error instanceof Error ? { message: error.message, stack: error.stack } : String(error),\n });\n return null;\n }\n }\n\n /**\n * Forward a Bearer token to the shared API's /auth/verify endpoint\n * to validate it and get user info (used for CLI tokens).\n */\n private async verifyBearerToken(token: string): Promise<StudioUser | null> {\n const cacheKey = this.verificationKey('bearer', token);\n const cached = this.getCachedVerification(cacheKey);\n if (cached) return cached;\n\n try {\n const res = await fetch(`${this.sharedApiUrl}/auth/verify`, {\n headers: {\n Authorization: `Bearer ${token}`,\n },\n signal: AbortSignal.timeout(VERIFY_FETCH_TIMEOUT_MS),\n });\n\n if (!res.ok) {\n this.logger.warn('verifyBearerToken: shared API returned non-OK status', {\n status: res.status,\n url: `${this.sharedApiUrl}/auth/verify`,\n });\n return null;\n }\n\n const data = (await res.json()) as {\n user: {\n id: string;\n email: string;\n firstName: string;\n lastName: string;\n };\n organizationId: string;\n role?: string;\n memberOrgIds?: string[];\n };\n\n const user: StudioUser = {\n id: data.user.id,\n email: data.user.email,\n name: [data.user.firstName, data.user.lastName].filter(Boolean).join(' ') || undefined,\n organizationId: data.organizationId,\n role: data.role,\n memberOrgIds: data.memberOrgIds,\n };\n // Same no-org guard as verifySessionCookie: cache only after the user's\n // organization bootstrap has completed.\n if (user.organizationId) this.cacheVerification(cacheKey, user);\n return user;\n } catch (error) {\n this.logger.error('verifyBearerToken: fetch to shared API failed', {\n url: `${this.sharedApiUrl}/auth/verify`,\n error: error instanceof Error ? { message: error.message, stack: error.stack } : String(error),\n });\n return null;\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Cookie helpers\n// ---------------------------------------------------------------------------\n\nfunction parseCookie(cookieHeader: string | null | undefined, name: string): string | null {\n if (!cookieHeader) return null;\n const match = cookieHeader.match(new RegExp(`${name}=([^;]+)`));\n return match?.[1] ?? null;\n}\n\n/**\n * WorkOS AuthKit conventionally uses `admin` / `owner` for admin-equivalent\n * roles; the shared API surfaces the WorkOS role slug directly on\n * `/auth/me` and `/auth/orgs`.\n */\nfunction isAdminRole(role: string | undefined): boolean {\n return role === 'admin' || role === 'owner';\n}\n\n/**\n * Parse a cookie value from a Set-Cookie header.\n * Set-Cookie format: \"name=value; HttpOnly; SameSite=Lax; Path=/; Max-Age=86400\"\n */\nfunction parseCookieFromHeader(setCookieHeader: string, name: string): string | null {\n // Set-Cookie header starts with \"name=value\" followed by optional attributes\n const parts = setCookieHeader.split(';');\n if (parts.length === 0) return null;\n\n const [cookieName, ...valueParts] = parts[0]!.split('=');\n if (cookieName?.trim() !== name) return null;\n\n // Value could contain = characters, so rejoin\n return valueParts.join('=') || null;\n}\n\n// ---------------------------------------------------------------------------\n// MastraRBACStudio — role-based permission provider for Studio auth\n// ---------------------------------------------------------------------------\n\nexport interface MastraRBACStudioOptions {\n /**\n * Mapping from role names to permission arrays.\n *\n * @example\n * ```typescript\n * {\n * admin: ['*'],\n * member: ['agents:read', 'workflows:*'],\n * viewer: ['agents:read', 'workflows:read'],\n * _default: [],\n * }\n * ```\n */\n roleMapping: RoleMapping;\n}\n\n/**\n * RBAC provider for Mastra Studio authentication.\n *\n * Maps user roles (from the shared API's /auth/me endpoint) to Mastra permissions\n * using a configurable role mapping.\n */\nexport class MastraRBACStudio implements IRBACProvider<StudioUser> {\n private options: MastraRBACStudioOptions;\n\n get roleMapping(): RoleMapping {\n return this.options.roleMapping;\n }\n\n constructor(options: MastraRBACStudioOptions) {\n this.options = options;\n }\n\n async getRoles(user: StudioUser): Promise<string[]> {\n return user.role ? [user.role] : [];\n }\n\n async hasRole(user: StudioUser, role: string): Promise<boolean> {\n const roles = await this.getRoles(user);\n return roles.includes(role);\n }\n\n async getPermissions(user: StudioUser): Promise<string[]> {\n const roles = await this.getRoles(user);\n if (roles.length === 0) {\n return this.options.roleMapping['_default'] ?? [];\n }\n return resolvePermissionsFromMapping(roles, this.options.roleMapping);\n }\n\n async hasPermission(user: StudioUser, permission: string): Promise<boolean> {\n const permissions = await this.getPermissions(user);\n return permissions.some(p => matchesPermission(p, permission));\n }\n\n async hasAllPermissions(user: StudioUser, permissions: string[]): Promise<boolean> {\n const userPermissions = await this.getPermissions(user);\n return permissions.every(required => userPermissions.some(p => matchesPermission(p, required)));\n }\n\n async hasAnyPermission(user: StudioUser, permissions: string[]): Promise<boolean> {\n const userPermissions = await this.getPermissions(user);\n return permissions.some(required => userPermissions.some(p => matchesPermission(p, required)));\n }\n}\n"],"mappings":";;AACA,SAAS,sBAAsB,SAAS,MAAM;CAC7C,MAAM,iBAAiB,KAAK,YAAY;CACxC,MAAM,cAAc,OAAO,KAAK,OAAO,CAAC,CAAC,MAAM,QAAQ,IAAI,YAAY,MAAM,cAAc;CAC3F,MAAM,QAAQ,gBAAgB,KAAK,IAAI,KAAK,IAAI,QAAQ;C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AQ,YAAY,eAAe,CAAC;EAElD,OAAO,8BAA8B,OAAO,KAAK,QAAQ,WAAW;CACtE;CAEA,MAAM,cAAc,MAAkB,YAAsC;EAE1E,QAAO,MADmB,KAAK,eAAe,IAAI,EAAA,CAC/B,MAAK,MAAK,kBAAkB,GAAG,UAAU,CAAC;CAC/D;CAEA,MAAM,kBAAkB,MAAkB,aAAyC;EACjF,MAAM,kBAAkB,MAAM,KAAK,eAAe,IAAI;EACtD,OAAO,YAAY,OAAM,aAAY,gBAAgB,MAAK,MAAK,kBAAkB,GAAG,QAAQ,CAAC,CAAC;CAChG;CAEA,MAAM,iBAAiB,MAAkB,aAAyC;EAChF,MAAM,kBAAkB,MAAM,KAAK,eAAe,IAAI;EACtD,OAAO,YAAY,MAAK,aAAY,gBAAgB,MAAK,MAAK,kBAAkB,GAAG,QAAQ,CAAC,CAAC;CAC/F;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mastra/auth-studio",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.4-alpha.0",
|
|
4
4
|
"description": "Mastra Studio Auth integration — proxies authentication through Mastra shared API",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -27,9 +27,9 @@
|
|
|
27
27
|
"tsdown": "0.22.9",
|
|
28
28
|
"typescript": "^6.0.3",
|
|
29
29
|
"vitest": "4.1.10",
|
|
30
|
-
"@internal/auth": "0.0.
|
|
31
|
-
"@internal/
|
|
32
|
-
"@internal/
|
|
30
|
+
"@internal/auth": "0.0.13",
|
|
31
|
+
"@internal/lint": "0.0.123",
|
|
32
|
+
"@internal/types-builder": "0.0.98"
|
|
33
33
|
},
|
|
34
34
|
"files": [
|
|
35
35
|
"dist",
|