@mastra/auth-okta 0.1.2 → 0.2.0-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/dist/index.cjs CHANGED
@@ -1,892 +1,950 @@
1
- 'use strict';
2
-
3
- var pkg = require('@okta/okta-sdk-nodejs');
4
- var lruCache = require('lru-cache');
5
- var jose = require('jose');
6
-
7
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
8
-
9
- var pkg__default = /*#__PURE__*/_interopDefault(pkg);
10
-
11
- // ../../packages/_internals/auth/dist/chunk-H3EJ4GVJ.js
12
- var RESOURCE_EXPANSIONS = {
13
- stored: [
14
- "stored-agents",
15
- "stored-mcp-clients",
16
- "stored-prompt-blocks",
17
- "stored-scorers",
18
- "stored-skills",
19
- "stored-workspaces"
20
- ]
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region \0rolldown/runtime.js
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
21
18
  };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
23
+ //#endregion
24
+ let _okta_okta_sdk_nodejs = require("@okta/okta-sdk-nodejs");
25
+ _okta_okta_sdk_nodejs = __toESM(_okta_okta_sdk_nodejs, 1);
26
+ let lru_cache = require("lru-cache");
27
+ let jose = require("jose");
28
+ //#region ../../packages/_internals/auth/dist/ee-DXvSoTl7.js
29
+ /**
30
+ * FGA enforcement utility for checking fine-grained authorization.
31
+ *
32
+ * @license Mastra Enterprise License - see ee/LICENSE
33
+ */
34
+ /**
35
+ * Compound resource keys that expand to a set of per-family resources.
36
+ * A granted `stored:<action>` is treated as matching any `stored-<family>:<action>`
37
+ * (and `stored:*` matches any `stored-<family>:*`).
38
+ */
39
+ const RESOURCE_EXPANSIONS = { stored: [
40
+ "stored-agents",
41
+ "stored-mcp-clients",
42
+ "stored-prompt-blocks",
43
+ "stored-scorers",
44
+ "stored-skills",
45
+ "stored-workspaces"
46
+ ] };
47
+ /**
48
+ * Check if a permission matches (including wildcard support).
49
+ *
50
+ * Permission format: `{resource}:{action}[:{resource-id}]`
51
+ *
52
+ * Examples:
53
+ * - `*` matches everything
54
+ * - `agents:*` matches `agents:read`, `agents:read:my-agent`
55
+ * - `*:read` matches `agents:read`, `workflows:read` (action across all resources)
56
+ * - `agents:read` matches `agents:read`, `agents:read:my-agent`
57
+ * - `agents:read:my-agent` matches only `agents:read:my-agent`
58
+ * - `agents:*:my-agent` matches `agents:read:my-agent`, `agents:write:my-agent`
59
+ *
60
+ * @param userPermission - Permission the user has
61
+ * @param requiredPermission - Permission being checked
62
+ * @returns True if permission matches
63
+ */
22
64
  function matchesPermission(userPermission, requiredPermission) {
23
- if (userPermission === "*") {
24
- return true;
25
- }
26
- const grantedParts = userPermission.split(":");
27
- const requiredParts = requiredPermission.split(":");
28
- const expandedFamilies = RESOURCE_EXPANSIONS[grantedParts[0] ?? ""];
29
- if (expandedFamilies && expandedFamilies.includes(requiredParts[0] ?? "")) {
30
- const aliased = [requiredParts[0], ...grantedParts.slice(1)].join(":");
31
- return matchesPermission(aliased, requiredPermission);
32
- }
33
- if (grantedParts.length < 2 || requiredParts.length < 2) {
34
- return userPermission === requiredPermission;
35
- }
36
- const [grantedResource, grantedAction, grantedId] = grantedParts;
37
- const [requiredResource, requiredAction, requiredId] = requiredParts;
38
- if (grantedResource === "*") {
39
- if (grantedAction === "*") {
40
- if (grantedId === void 0) {
41
- return true;
42
- }
43
- return grantedId === requiredId;
44
- }
45
- if (grantedAction !== requiredAction) {
46
- return false;
47
- }
48
- if (grantedId === void 0) {
49
- return true;
50
- }
51
- return grantedId === requiredId;
52
- }
53
- if (grantedResource !== requiredResource) {
54
- return false;
55
- }
56
- if (grantedAction === "*") {
57
- if (grantedId === void 0) {
58
- return true;
59
- }
60
- return grantedId === requiredId;
61
- }
62
- if (grantedAction !== requiredAction) {
63
- return false;
64
- }
65
- if (grantedId === void 0) {
66
- return true;
67
- }
68
- return grantedId === requiredId;
65
+ if (userPermission === "*") return true;
66
+ const grantedParts = userPermission.split(":");
67
+ const requiredParts = requiredPermission.split(":");
68
+ const expandedFamilies = RESOURCE_EXPANSIONS[grantedParts[0] ?? ""];
69
+ if (expandedFamilies && expandedFamilies.includes(requiredParts[0] ?? "")) return matchesPermission([requiredParts[0], ...grantedParts.slice(1)].join(":"), requiredPermission);
70
+ if (grantedParts.length < 2 || requiredParts.length < 2) return userPermission === requiredPermission;
71
+ const [grantedResource, grantedAction, grantedId] = grantedParts;
72
+ const [requiredResource, requiredAction, requiredId] = requiredParts;
73
+ if (grantedResource === "*") {
74
+ if (grantedAction === "*") {
75
+ if (grantedId === void 0) return true;
76
+ return grantedId === requiredId;
77
+ }
78
+ if (grantedAction !== requiredAction) return false;
79
+ if (grantedId === void 0) return true;
80
+ return grantedId === requiredId;
81
+ }
82
+ if (grantedResource !== requiredResource) return false;
83
+ if (grantedAction === "*") {
84
+ if (grantedId === void 0) return true;
85
+ return grantedId === requiredId;
86
+ }
87
+ if (grantedAction !== requiredAction) return false;
88
+ if (grantedId === void 0) return true;
89
+ return grantedId === requiredId;
69
90
  }
91
+ /**
92
+ * Resolve permissions from user roles using a role mapping.
93
+ *
94
+ * This function translates provider-defined roles (from WorkOS, Okta, etc.)
95
+ * to Mastra permissions using a configurable mapping.
96
+ *
97
+ * @example
98
+ * ```typescript
99
+ * const roleMapping = {
100
+ * "Engineering": ["agents:*", "workflows:*"],
101
+ * "Product": ["agents:read"],
102
+ * "_default": [],
103
+ * };
104
+ *
105
+ * // User has "Engineering" and "QA" roles
106
+ * const permissions = resolvePermissionsFromMapping(
107
+ * ["Engineering", "QA"],
108
+ * roleMapping
109
+ * );
110
+ * // Result: ["agents:*", "workflows:*"] (QA is unmapped, gets _default)
111
+ * ```
112
+ *
113
+ * @param roles - User's roles from the identity provider
114
+ * @param mapping - Role to permission mapping
115
+ * @returns Array of resolved permissions
116
+ */
70
117
  function resolvePermissionsFromMapping(roles, mapping) {
71
- const permissions = /* @__PURE__ */ new Set();
72
- const defaultPerms = mapping["_default"] ?? [];
73
- for (const role of roles) {
74
- const rolePerms = mapping[role];
75
- if (rolePerms) {
76
- for (const perm of rolePerms) {
77
- permissions.add(perm);
78
- }
79
- } else {
80
- for (const perm of defaultPerms) {
81
- permissions.add(perm);
82
- }
83
- }
84
- }
85
- return Array.from(permissions);
118
+ const permissions = /* @__PURE__ */ new Set();
119
+ const defaultPerms = mapping["_default"] ?? [];
120
+ for (const role of roles) {
121
+ const rolePerms = mapping[role];
122
+ if (rolePerms) for (const perm of rolePerms) permissions.add(perm);
123
+ else for (const perm of defaultPerms) permissions.add(perm);
124
+ }
125
+ return Array.from(permissions);
86
126
  }
87
- var { Client } = pkg__default.default;
88
- var DEFAULT_CACHE_TTL_MS = 60 * 1e3;
89
- var DEFAULT_CACHE_MAX_SIZE = 1e3;
127
+ /**
128
+ * @mastra/core/auth/ee
129
+ *
130
+ * Enterprise authentication capabilities for Mastra.
131
+ * This code is licensed under the Mastra Enterprise License - see ee/LICENSE.
132
+ *
133
+ * @license Mastra Enterprise License - see ee/LICENSE
134
+ * @packageDocumentation
135
+ */
136
+ //#endregion
137
+ //#region src/rbac-provider.ts
138
+ const { Client } = _okta_okta_sdk_nodejs.default;
139
+ /** Default cache TTL in milliseconds (60 seconds) */
140
+ const DEFAULT_CACHE_TTL_MS = 60 * 1e3;
141
+ /** Default max cache size (number of users) */
142
+ const DEFAULT_CACHE_MAX_SIZE = 1e3;
143
+ /**
144
+ * Okta RBAC provider that maps Okta groups to Mastra permissions.
145
+ *
146
+ * This provider fetches user groups from Okta and translates them into
147
+ * Mastra permissions using a configurable role mapping.
148
+ *
149
+ * @example Basic usage with Okta auth
150
+ * ```typescript
151
+ * import { MastraAuthOkta, MastraRBACOkta } from '@mastra/auth-okta';
152
+ *
153
+ * const mastra = new Mastra({
154
+ * server: {
155
+ * auth: new MastraAuthOkta(),
156
+ * rbac: new MastraRBACOkta({
157
+ * roleMapping: {
158
+ * 'Engineering': ['agents:*', 'workflows:*'],
159
+ * 'Admin': ['*'],
160
+ * '_default': [],
161
+ * },
162
+ * }),
163
+ * },
164
+ * });
165
+ * ```
166
+ *
167
+ * @example Cross-provider usage (Auth0 + Okta RBAC)
168
+ * ```typescript
169
+ * import { MastraAuthAuth0 } from '@mastra/auth-auth0';
170
+ * import { MastraRBACOkta } from '@mastra/auth-okta';
171
+ *
172
+ * const mastra = new Mastra({
173
+ * server: {
174
+ * auth: new MastraAuthAuth0(),
175
+ * rbac: new MastraRBACOkta({
176
+ * getUserId: (user) => user.metadata?.oktaUserId || user.email,
177
+ * roleMapping: {
178
+ * 'Engineering': ['agents:*', 'workflows:*'],
179
+ * 'Admin': ['*'],
180
+ * '_default': [],
181
+ * },
182
+ * }),
183
+ * },
184
+ * });
185
+ * ```
186
+ */
90
187
  var MastraRBACOkta = class {
91
- oktaClient;
92
- options;
93
- /**
94
- * Single cache for roles (the expensive Okta API call).
95
- * Permissions are derived from roles on-the-fly (cheap, synchronous).
96
- * Storing promises handles concurrent request deduplication.
97
- */
98
- rolesCache;
99
- /**
100
- * Expose roleMapping for middleware access.
101
- * This allows the authorization middleware to resolve permissions
102
- * without needing to call the async methods.
103
- */
104
- get roleMapping() {
105
- return this.options.roleMapping;
106
- }
107
- /**
108
- * Create a new Okta RBAC provider.
109
- *
110
- * @param options - RBAC configuration options
111
- */
112
- constructor(options) {
113
- const domain = options.domain ?? process.env.OKTA_DOMAIN;
114
- const apiToken = options.apiToken ?? process.env.OKTA_API_TOKEN;
115
- if (!domain) {
116
- throw new Error(
117
- "Okta domain is required. Provide it in the options or set OKTA_DOMAIN environment variable."
118
- );
119
- }
120
- if (!apiToken) {
121
- throw new Error(
122
- "Okta API token is required for RBAC. Provide it in the options or set OKTA_API_TOKEN environment variable."
123
- );
124
- }
125
- this.oktaClient = new Client({
126
- orgUrl: `https://${domain}`,
127
- token: apiToken
128
- });
129
- this.options = options;
130
- this.rolesCache = new lruCache.LRUCache({
131
- max: options.cache?.maxSize ?? DEFAULT_CACHE_MAX_SIZE,
132
- ttl: options.cache?.ttlMs ?? DEFAULT_CACHE_TTL_MS
133
- });
134
- }
135
- /**
136
- * Get all roles (groups) for a user from Okta.
137
- *
138
- * If the user object already has groups attached, uses those.
139
- * Otherwise, fetches groups from Okta API and caches the result.
140
- *
141
- * @param user - User to get roles for
142
- * @returns Array of group names
143
- */
144
- async getRoles(user) {
145
- if (user.groups && user.groups.length > 0) {
146
- return user.groups;
147
- }
148
- const userId = this.resolveUserId(user);
149
- if (!userId) {
150
- return [];
151
- }
152
- const cached = this.rolesCache.get(userId);
153
- if (cached) {
154
- return cached;
155
- }
156
- const groupsPromise = this.fetchGroupsFromOkta(userId).catch((err) => {
157
- console.error(`[MastraRBACOkta] Failed to fetch groups for user ${userId}:`, err);
158
- this.rolesCache.delete(userId);
159
- return [];
160
- });
161
- this.rolesCache.set(userId, groupsPromise);
162
- return groupsPromise;
163
- }
164
- /**
165
- * Resolve the Okta user ID from the user object.
166
- * Uses custom getUserId function if provided, otherwise falls back to oktaId or id.
167
- */
168
- resolveUserId(user) {
169
- if (this.options.getUserId) {
170
- return this.options.getUserId(user);
171
- }
172
- return user.oktaId ?? user.id;
173
- }
174
- /**
175
- * Fetch groups from Okta API.
176
- * Errors propagate to the caller so the cache eviction in getRoles() works.
177
- */
178
- async fetchGroupsFromOkta(userId) {
179
- const groups = await this.oktaClient.userApi.listUserGroups({ userId });
180
- const groupNames = [];
181
- for await (const group of groups) {
182
- if (group && group.profile?.name) {
183
- groupNames.push(group.profile.name);
184
- }
185
- }
186
- return groupNames;
187
- }
188
- /**
189
- * Check if a user has a specific role (group).
190
- *
191
- * @param user - User to check
192
- * @param role - Group name to check for
193
- * @returns True if user has the group
194
- */
195
- async hasRole(user, role) {
196
- const roles = await this.getRoles(user);
197
- return roles.includes(role);
198
- }
199
- /**
200
- * Get all permissions for a user by mapping their Okta groups.
201
- *
202
- * @param user - User to get permissions for
203
- * @returns Array of permission strings
204
- */
205
- async getPermissions(user) {
206
- const roles = await this.getRoles(user);
207
- return resolvePermissionsFromMapping(roles, this.options.roleMapping);
208
- }
209
- /**
210
- * Check if a user has a specific permission.
211
- *
212
- * @param user - User to check
213
- * @param permission - Permission to check for (supports wildcards)
214
- * @returns True if user has the permission
215
- */
216
- async hasPermission(user, permission) {
217
- const permissions = await this.getPermissions(user);
218
- return permissions.some((granted) => matchesPermission(granted, permission));
219
- }
220
- /**
221
- * Check if a user has ALL of the specified permissions.
222
- *
223
- * @param user - User to check
224
- * @param permissions - Permissions to check for
225
- * @returns True if user has all permissions
226
- */
227
- async hasAllPermissions(user, permissions) {
228
- const userPermissions = await this.getPermissions(user);
229
- return permissions.every((required) => userPermissions.some((granted) => matchesPermission(granted, required)));
230
- }
231
- /**
232
- * Check if a user has ANY of the specified permissions.
233
- *
234
- * @param user - User to check
235
- * @param permissions - Permissions to check for
236
- * @returns True if user has at least one permission
237
- */
238
- async hasAnyPermission(user, permissions) {
239
- const userPermissions = await this.getPermissions(user);
240
- return permissions.some((required) => userPermissions.some((granted) => matchesPermission(granted, required)));
241
- }
188
+ oktaClient;
189
+ options;
190
+ /**
191
+ * Single cache for roles (the expensive Okta API call).
192
+ * Permissions are derived from roles on-the-fly (cheap, synchronous).
193
+ * Storing promises handles concurrent request deduplication.
194
+ */
195
+ rolesCache;
196
+ /**
197
+ * Expose roleMapping for middleware access.
198
+ * This allows the authorization middleware to resolve permissions
199
+ * without needing to call the async methods.
200
+ */
201
+ get roleMapping() {
202
+ return this.options.roleMapping;
203
+ }
204
+ /**
205
+ * Create a new Okta RBAC provider.
206
+ *
207
+ * @param options - RBAC configuration options
208
+ */
209
+ constructor(options) {
210
+ const domain = options.domain ?? process.env.OKTA_DOMAIN;
211
+ const apiToken = options.apiToken ?? process.env.OKTA_API_TOKEN;
212
+ if (!domain) throw new Error("Okta domain is required. Provide it in the options or set OKTA_DOMAIN environment variable.");
213
+ if (!apiToken) throw new Error("Okta API token is required for RBAC. Provide it in the options or set OKTA_API_TOKEN environment variable.");
214
+ this.oktaClient = new Client({
215
+ orgUrl: `https://${domain}`,
216
+ token: apiToken
217
+ });
218
+ this.options = options;
219
+ this.rolesCache = new lru_cache.LRUCache({
220
+ max: options.cache?.maxSize ?? DEFAULT_CACHE_MAX_SIZE,
221
+ ttl: options.cache?.ttlMs ?? DEFAULT_CACHE_TTL_MS
222
+ });
223
+ }
224
+ /**
225
+ * Get all roles (groups) for a user from Okta.
226
+ *
227
+ * If the user object already has groups attached, uses those.
228
+ * Otherwise, fetches groups from Okta API and caches the result.
229
+ *
230
+ * @param user - User to get roles for
231
+ * @returns Array of group names
232
+ */
233
+ async getRoles(user) {
234
+ if (user.groups && user.groups.length > 0) return user.groups;
235
+ const userId = this.resolveUserId(user);
236
+ if (!userId) return [];
237
+ const cached = this.rolesCache.get(userId);
238
+ if (cached) return cached;
239
+ const groupsPromise = this.fetchGroupsFromOkta(userId).catch((err) => {
240
+ console.error(`[MastraRBACOkta] Failed to fetch groups for user ${userId}:`, err);
241
+ this.rolesCache.delete(userId);
242
+ return [];
243
+ });
244
+ this.rolesCache.set(userId, groupsPromise);
245
+ return groupsPromise;
246
+ }
247
+ /**
248
+ * Resolve the Okta user ID from the user object.
249
+ * Uses custom getUserId function if provided, otherwise falls back to oktaId or id.
250
+ */
251
+ resolveUserId(user) {
252
+ if (this.options.getUserId) return this.options.getUserId(user);
253
+ return user.oktaId ?? user.id;
254
+ }
255
+ /**
256
+ * Fetch groups from Okta API.
257
+ * Errors propagate to the caller so the cache eviction in getRoles() works.
258
+ */
259
+ async fetchGroupsFromOkta(userId) {
260
+ const groups = await this.oktaClient.userApi.listUserGroups({ userId });
261
+ const groupNames = [];
262
+ for await (const group of groups) if (group && group.profile?.name) groupNames.push(group.profile.name);
263
+ return groupNames;
264
+ }
265
+ /**
266
+ * Check if a user has a specific role (group).
267
+ *
268
+ * @param user - User to check
269
+ * @param role - Group name to check for
270
+ * @returns True if user has the group
271
+ */
272
+ async hasRole(user, role) {
273
+ return (await this.getRoles(user)).includes(role);
274
+ }
275
+ /**
276
+ * Get all permissions for a user by mapping their Okta groups.
277
+ *
278
+ * @param user - User to get permissions for
279
+ * @returns Array of permission strings
280
+ */
281
+ async getPermissions(user) {
282
+ return resolvePermissionsFromMapping(await this.getRoles(user), this.options.roleMapping);
283
+ }
284
+ /**
285
+ * Check if a user has a specific permission.
286
+ *
287
+ * @param user - User to check
288
+ * @param permission - Permission to check for (supports wildcards)
289
+ * @returns True if user has the permission
290
+ */
291
+ async hasPermission(user, permission) {
292
+ return (await this.getPermissions(user)).some((granted) => matchesPermission(granted, permission));
293
+ }
294
+ /**
295
+ * Check if a user has ALL of the specified permissions.
296
+ *
297
+ * @param user - User to check
298
+ * @param permissions - Permissions to check for
299
+ * @returns True if user has all permissions
300
+ */
301
+ async hasAllPermissions(user, permissions) {
302
+ const userPermissions = await this.getPermissions(user);
303
+ return permissions.every((required) => userPermissions.some((granted) => matchesPermission(granted, required)));
304
+ }
305
+ /**
306
+ * Check if a user has ANY of the specified permissions.
307
+ *
308
+ * @param user - User to check
309
+ * @param permissions - Permissions to check for
310
+ * @returns True if user has at least one permission
311
+ */
312
+ async hasAnyPermission(user, permissions) {
313
+ const userPermissions = await this.getPermissions(user);
314
+ return permissions.some((required) => userPermissions.some((granted) => matchesPermission(granted, required)));
315
+ }
316
+ };
317
+ //#endregion
318
+ //#region ../../packages/_internal-core/dist/logger/index.js
319
+ const RegisteredLogger = {
320
+ AGENT: "AGENT",
321
+ OBSERVABILITY: "OBSERVABILITY",
322
+ AUTH: "AUTH",
323
+ BROWSER: "BROWSER",
324
+ NETWORK: "NETWORK",
325
+ WORKFLOW: "WORKFLOW",
326
+ LLM: "LLM",
327
+ TTS: "TTS",
328
+ VOICE: "VOICE",
329
+ VECTOR: "VECTOR",
330
+ BUNDLER: "BUNDLER",
331
+ DEPLOYER: "DEPLOYER",
332
+ MEMORY: "MEMORY",
333
+ STORAGE: "STORAGE",
334
+ EMBEDDINGS: "EMBEDDINGS",
335
+ MCP_SERVER: "MCP_SERVER",
336
+ SERVER_CACHE: "SERVER_CACHE",
337
+ SERVER: "SERVER",
338
+ WORKSPACE: "WORKSPACE",
339
+ CHANNEL: "CHANNEL"
340
+ };
341
+ const LogLevel = {
342
+ DEBUG: "debug",
343
+ INFO: "info",
344
+ WARN: "warn",
345
+ ERROR: "error",
346
+ NONE: "silent"
242
347
  };
243
-
244
- // ../../packages/_internal-core/dist/chunk-3M4SEWMI.js
245
- var RegisteredLogger = {
246
- LLM: "LLM"};
247
- var LogLevel = {
248
- DEBUG: "debug",
249
- INFO: "info",
250
- WARN: "warn",
251
- ERROR: "error"};
252
348
  var MastraLogger = class {
253
- name;
254
- level;
255
- transports;
256
- constructor(options = {}) {
257
- this.name = options.name || "Mastra";
258
- this.level = options.level || LogLevel.ERROR;
259
- this.transports = new Map(Object.entries(options.transports || {}));
260
- }
261
- getTransports() {
262
- return this.transports;
263
- }
264
- trackException(_error, _metadata) {
265
- }
266
- async listLogs(transportId, params) {
267
- if (!transportId || !this.transports.has(transportId)) {
268
- return { logs: [], total: 0, page: params?.page ?? 1, perPage: params?.perPage ?? 100, hasMore: false };
269
- }
270
- return this.transports.get(transportId).listLogs?.(params) ?? {
271
- logs: [],
272
- total: 0,
273
- page: params?.page ?? 1,
274
- perPage: params?.perPage ?? 100,
275
- hasMore: false
276
- };
277
- }
278
- async listLogsByRunId({
279
- transportId,
280
- runId,
281
- fromDate,
282
- toDate,
283
- logLevel,
284
- filters,
285
- page,
286
- perPage
287
- }) {
288
- if (!transportId || !this.transports.has(transportId) || !runId) {
289
- return { logs: [], total: 0, page: page ?? 1, perPage: perPage ?? 100, hasMore: false };
290
- }
291
- return this.transports.get(transportId).listLogsByRunId?.({ runId, fromDate, toDate, logLevel, filters, page, perPage }) ?? {
292
- logs: [],
293
- total: 0,
294
- page: page ?? 1,
295
- perPage: perPage ?? 100,
296
- hasMore: false
297
- };
298
- }
349
+ name;
350
+ level;
351
+ transports;
352
+ constructor(options = {}) {
353
+ this.name = options.name || "Mastra";
354
+ this.level = options.level || LogLevel.ERROR;
355
+ this.transports = new Map(Object.entries(options.transports || {}));
356
+ }
357
+ getTransports() {
358
+ return this.transports;
359
+ }
360
+ trackException(_error, _metadata) {}
361
+ async listLogs(transportId, params) {
362
+ if (!transportId || !this.transports.has(transportId)) return {
363
+ logs: [],
364
+ total: 0,
365
+ page: params?.page ?? 1,
366
+ perPage: params?.perPage ?? 100,
367
+ hasMore: false
368
+ };
369
+ return this.transports.get(transportId).listLogs?.(params) ?? {
370
+ logs: [],
371
+ total: 0,
372
+ page: params?.page ?? 1,
373
+ perPage: params?.perPage ?? 100,
374
+ hasMore: false
375
+ };
376
+ }
377
+ async listLogsByRunId({ transportId, runId, fromDate, toDate, logLevel, filters, page, perPage }) {
378
+ if (!transportId || !this.transports.has(transportId) || !runId) return {
379
+ logs: [],
380
+ total: 0,
381
+ page: page ?? 1,
382
+ perPage: perPage ?? 100,
383
+ hasMore: false
384
+ };
385
+ return this.transports.get(transportId).listLogsByRunId?.({
386
+ runId,
387
+ fromDate,
388
+ toDate,
389
+ logLevel,
390
+ filters,
391
+ page,
392
+ perPage
393
+ }) ?? {
394
+ logs: [],
395
+ total: 0,
396
+ page: page ?? 1,
397
+ perPage: perPage ?? 100,
398
+ hasMore: false
399
+ };
400
+ }
299
401
  };
300
- var ConsoleLogger = class _ConsoleLogger extends MastraLogger {
301
- component;
302
- filter;
303
- constructor(options = {}) {
304
- super(options);
305
- this.component = options.component;
306
- this.filter = options.filter;
307
- }
308
- child(componentOrBindings) {
309
- const component = typeof componentOrBindings === "string" ? componentOrBindings : componentOrBindings?.component ?? this.component;
310
- return new _ConsoleLogger({
311
- name: this.name,
312
- level: this.level,
313
- component,
314
- filter: this.filter
315
- });
316
- }
317
- shouldLog(level, message, args) {
318
- if (!this.filter) return true;
319
- try {
320
- return this.filter({ component: this.component, level, message, args });
321
- } catch (e) {
322
- console.error(`[Logger] Filter error for component=${this.component} level=${level}:`, e);
323
- return true;
324
- }
325
- }
326
- prefix() {
327
- return this.component ? `[${this.component}] ` : "";
328
- }
329
- debug(message, ...args) {
330
- if (this.level === LogLevel.DEBUG && this.shouldLog(LogLevel.DEBUG, message, args)) {
331
- console.info(`${this.prefix()}${message}`, ...args);
332
- }
333
- }
334
- info(message, ...args) {
335
- if ((this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.INFO, message, args)) {
336
- console.info(`${this.prefix()}${message}`, ...args);
337
- }
338
- }
339
- warn(message, ...args) {
340
- if ((this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.WARN, message, args)) {
341
- console.warn(`${this.prefix()}${message}`, ...args);
342
- }
343
- }
344
- error(message, ...args) {
345
- if ((this.level === LogLevel.ERROR || this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.ERROR, message, args)) {
346
- console.error(`${this.prefix()}${message}`, ...args);
347
- }
348
- }
349
- async listLogs(_transportId, _params) {
350
- return { logs: [], total: 0, page: _params?.page ?? 1, perPage: _params?.perPage ?? 100, hasMore: false };
351
- }
352
- async listLogsByRunId(_args) {
353
- return { logs: [], total: 0, page: _args.page ?? 1, perPage: _args.perPage ?? 100, hasMore: false };
354
- }
402
+ var ConsoleLogger = class ConsoleLogger extends MastraLogger {
403
+ component;
404
+ filter;
405
+ constructor(options = {}) {
406
+ super(options);
407
+ this.component = options.component;
408
+ this.filter = options.filter;
409
+ }
410
+ child(componentOrBindings) {
411
+ const component = typeof componentOrBindings === "string" ? componentOrBindings : componentOrBindings?.component ?? this.component;
412
+ return new ConsoleLogger({
413
+ name: this.name,
414
+ level: this.level,
415
+ component,
416
+ filter: this.filter
417
+ });
418
+ }
419
+ shouldLog(level, message, args) {
420
+ if (!this.filter) return true;
421
+ try {
422
+ return this.filter({
423
+ component: this.component,
424
+ level,
425
+ message,
426
+ args
427
+ });
428
+ } catch (e) {
429
+ console.error(`[Logger] Filter error for component=${this.component} level=${level}:`, e);
430
+ return true;
431
+ }
432
+ }
433
+ prefix() {
434
+ return this.component ? `[${this.component}] ` : "";
435
+ }
436
+ debug(message, ...args) {
437
+ if (this.level === LogLevel.DEBUG && this.shouldLog(LogLevel.DEBUG, message, args)) console.info(`${this.prefix()}${message}`, ...args);
438
+ }
439
+ info(message, ...args) {
440
+ if ((this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.INFO, message, args)) console.info(`${this.prefix()}${message}`, ...args);
441
+ }
442
+ warn(message, ...args) {
443
+ if ((this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.WARN, message, args)) console.warn(`${this.prefix()}${message}`, ...args);
444
+ }
445
+ error(message, ...args) {
446
+ if ((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);
447
+ }
448
+ async listLogs(_transportId, _params) {
449
+ return {
450
+ logs: [],
451
+ total: 0,
452
+ page: _params?.page ?? 1,
453
+ perPage: _params?.perPage ?? 100,
454
+ hasMore: false
455
+ };
456
+ }
457
+ async listLogsByRunId(_args) {
458
+ return {
459
+ logs: [],
460
+ total: 0,
461
+ page: _args.page ?? 1,
462
+ perPage: _args.perPage ?? 100,
463
+ hasMore: false
464
+ };
465
+ }
355
466
  };
356
-
357
- // ../../packages/_internal-core/dist/base/index.js
467
+ //#endregion
468
+ //#region ../../packages/_internal-core/dist/base/index.js
358
469
  var MastraBase = class {
359
- component = RegisteredLogger.LLM;
360
- logger;
361
- name;
362
- #rawConfig;
363
- constructor({
364
- component,
365
- name,
366
- rawConfig
367
- }) {
368
- this.component = component || RegisteredLogger.LLM;
369
- this.name = name;
370
- this.#rawConfig = rawConfig;
371
- this.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });
372
- }
373
- /**
374
- * Returns the raw storage configuration this primitive was created from,
375
- * or undefined if it was created from code.
376
- */
377
- toRawConfig() {
378
- return this.#rawConfig;
379
- }
380
- /**
381
- * Sets the raw storage configuration for this primitive.
382
- * @internal
383
- */
384
- __setRawConfig(rawConfig) {
385
- this.#rawConfig = rawConfig;
386
- }
387
- /**
388
- * Set the logger for the agent
389
- * @param logger
390
- */
391
- __setLogger(logger) {
392
- this.logger = "child" in logger && typeof logger.child === "function" ? logger.child({ component: this.component }) : logger;
393
- }
470
+ component = RegisteredLogger.LLM;
471
+ logger;
472
+ name;
473
+ #rawConfig;
474
+ constructor({ component, name, rawConfig }) {
475
+ this.component = component || RegisteredLogger.LLM;
476
+ this.name = name;
477
+ this.#rawConfig = rawConfig;
478
+ this.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });
479
+ }
480
+ /**
481
+ * Returns the raw storage configuration this primitive was created from,
482
+ * or undefined if it was created from code.
483
+ */
484
+ toRawConfig() {
485
+ return this.#rawConfig;
486
+ }
487
+ /**
488
+ * Sets the raw storage configuration for this primitive.
489
+ * @internal
490
+ */
491
+ __setRawConfig(rawConfig) {
492
+ this.#rawConfig = rawConfig;
493
+ }
494
+ /**
495
+ * Set the logger for the agent
496
+ * @param logger
497
+ */
498
+ __setLogger(logger) {
499
+ this.logger = "child" in logger && typeof logger.child === "function" ? logger.child({ component: this.component }) : logger;
500
+ }
394
501
  };
395
-
396
- // ../../packages/_internals/auth/dist/chunk-7GLKLOU3.js
502
+ //#endregion
503
+ //#region ../../packages/_internals/auth/dist/provider/index.js
397
504
  var MastraAuthProvider = class extends MastraBase {
398
- protected;
399
- public;
400
- constructor(options) {
401
- super({ component: "AUTH", name: options?.name });
402
- if (options?.authorizeUser) {
403
- this.authorizeUser = options.authorizeUser.bind(this);
404
- }
405
- this.protected = options?.protected;
406
- this.public = options?.public;
407
- this.mapUserToResourceId = options?.mapUserToResourceId;
408
- }
409
- registerOptions(opts) {
410
- if (opts?.authorizeUser) {
411
- this.authorizeUser = opts.authorizeUser.bind(this);
412
- }
413
- if (opts?.mapUserToResourceId) {
414
- this.mapUserToResourceId = opts.mapUserToResourceId;
415
- }
416
- if (opts?.protected) {
417
- this.protected = opts.protected;
418
- }
419
- if (opts?.public) {
420
- this.public = opts.public;
421
- }
422
- }
505
+ protected;
506
+ public;
507
+ constructor(options) {
508
+ super({
509
+ component: "AUTH",
510
+ name: options?.name
511
+ });
512
+ if (options?.authorizeUser) this.authorizeUser = options.authorizeUser.bind(this);
513
+ this.protected = options?.protected;
514
+ this.public = options?.public;
515
+ this.mapUserToResourceId = options?.mapUserToResourceId;
516
+ }
517
+ registerOptions(opts) {
518
+ if (opts?.authorizeUser) this.authorizeUser = opts.authorizeUser.bind(this);
519
+ if (opts?.mapUserToResourceId) this.mapUserToResourceId = opts.mapUserToResourceId;
520
+ if (opts?.protected) this.protected = opts.protected;
521
+ if (opts?.public) this.public = opts.public;
522
+ }
423
523
  };
424
-
425
- // src/types.ts
524
+ //#endregion
525
+ //#region src/types.ts
526
+ /**
527
+ * Maps Okta JWT claims to OktaUser format.
528
+ *
529
+ * @param payload - JWT payload from Okta token
530
+ * @returns OktaUser object
531
+ */
426
532
  function mapOktaClaimsToUser(payload) {
427
- return {
428
- id: payload.sub || payload.uid || "",
429
- oktaId: payload.sub || payload.uid || "",
430
- email: payload.email,
431
- name: payload.name || [payload.given_name, payload.family_name].filter(Boolean).join(" ") || payload.email || void 0,
432
- avatarUrl: payload.picture,
433
- groups: payload.groups,
434
- metadata: {
435
- oktaId: payload.sub,
436
- emailVerified: payload.email_verified,
437
- updatedAt: payload.updated_at
438
- }
439
- };
533
+ return {
534
+ id: payload.sub || payload.uid || "",
535
+ oktaId: payload.sub || payload.uid || "",
536
+ email: payload.email,
537
+ name: payload.name || [payload.given_name, payload.family_name].filter(Boolean).join(" ") || payload.email || void 0,
538
+ avatarUrl: payload.picture,
539
+ groups: payload.groups,
540
+ metadata: {
541
+ oktaId: payload.sub,
542
+ emailVerified: payload.email_verified,
543
+ updatedAt: payload.updated_at
544
+ }
545
+ };
440
546
  }
441
-
442
- // src/auth-provider.ts
547
+ //#endregion
548
+ //#region src/auth-provider.ts
549
+ /**
550
+ * Trim trailing slashes. Index scan instead of regex to avoid backtracking
551
+ * (CodeQL js/polynomial-redos).
552
+ */
443
553
  function trimTrailingSlashes(value) {
444
- let end = value.length;
445
- while (end > 0 && value[end - 1] === "/") end--;
446
- return value.slice(0, end);
554
+ let end = value.length;
555
+ while (end > 0 && value[end - 1] === "/") end--;
556
+ return value.slice(0, end);
447
557
  }
448
- function getRequestHeader2(request, name) {
449
- if (request instanceof Request) {
450
- return request.headers.get(name);
451
- }
452
- return request.raw?.headers.get(name) ?? request.headers?.get(name) ?? request.header(name) ?? null;
558
+ function getRequestHeader(request, name) {
559
+ if (request instanceof Request) return request.headers.get(name);
560
+ return request.raw?.headers.get(name) ?? request.headers?.get(name) ?? request.header(name) ?? null;
453
561
  }
454
- var DEFAULT_COOKIE_NAME = "okta_session";
455
- var DEFAULT_COOKIE_MAX_AGE = 86400;
456
- var DEFAULT_SCOPES = ["openid", "profile", "email", "groups"];
457
- var SALT_LENGTH = 16;
458
- var IV_LENGTH = 12;
562
+ /** Default cookie name for Okta sessions */
563
+ const DEFAULT_COOKIE_NAME = "okta_session";
564
+ /** Default cookie max age (24 hours) */
565
+ const DEFAULT_COOKIE_MAX_AGE = 86400;
566
+ /** Default OAuth scopes */
567
+ const DEFAULT_SCOPES = [
568
+ "openid",
569
+ "profile",
570
+ "email",
571
+ "groups"
572
+ ];
573
+ /** PBKDF2 salt length in bytes */
574
+ const SALT_LENGTH = 16;
575
+ /** AES-GCM IV length in bytes */
576
+ const IV_LENGTH = 12;
577
+ /**
578
+ * Derive an AES-GCM key from password + salt using PBKDF2.
579
+ */
459
580
  async function deriveKey(password, salt, usage) {
460
- const encoder = new TextEncoder();
461
- const keyMaterial = await crypto.subtle.importKey("raw", encoder.encode(password), "PBKDF2", false, [
462
- "deriveBits",
463
- "deriveKey"
464
- ]);
465
- return crypto.subtle.deriveKey(
466
- { name: "PBKDF2", salt, iterations: 1e5, hash: "SHA-256" },
467
- keyMaterial,
468
- { name: "AES-GCM", length: 256 },
469
- false,
470
- [usage]
471
- );
581
+ const encoder = new TextEncoder();
582
+ const keyMaterial = await crypto.subtle.importKey("raw", encoder.encode(password), "PBKDF2", false, ["deriveBits", "deriveKey"]);
583
+ return crypto.subtle.deriveKey({
584
+ name: "PBKDF2",
585
+ salt,
586
+ iterations: 1e5,
587
+ hash: "SHA-256"
588
+ }, keyMaterial, {
589
+ name: "AES-GCM",
590
+ length: 256
591
+ }, false, [usage]);
472
592
  }
593
+ /**
594
+ * Encrypt session data for cookie storage.
595
+ * Format: base64(salt || iv || ciphertext)
596
+ * Salt is random per-encryption to ensure unique derived keys.
597
+ */
473
598
  async function encryptSession(data, password) {
474
- const encoder = new TextEncoder();
475
- const salt = crypto.getRandomValues(new Uint8Array(SALT_LENGTH));
476
- const key = await deriveKey(password, salt, "encrypt");
477
- const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH));
478
- const encrypted = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, encoder.encode(JSON.stringify(data)));
479
- const combined = new Uint8Array(salt.length + iv.length + new Uint8Array(encrypted).length);
480
- combined.set(salt);
481
- combined.set(iv, salt.length);
482
- combined.set(new Uint8Array(encrypted), salt.length + iv.length);
483
- return btoa(String.fromCharCode(...combined));
599
+ const encoder = new TextEncoder();
600
+ const salt = crypto.getRandomValues(new Uint8Array(SALT_LENGTH));
601
+ const key = await deriveKey(password, salt, "encrypt");
602
+ const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH));
603
+ const encrypted = await crypto.subtle.encrypt({
604
+ name: "AES-GCM",
605
+ iv
606
+ }, key, encoder.encode(JSON.stringify(data)));
607
+ const combined = new Uint8Array(salt.length + iv.length + new Uint8Array(encrypted).length);
608
+ combined.set(salt);
609
+ combined.set(iv, salt.length);
610
+ combined.set(new Uint8Array(encrypted), salt.length + iv.length);
611
+ return btoa(String.fromCharCode(...combined));
484
612
  }
613
+ /**
614
+ * Decrypt session data from cookie.
615
+ * Reads the random salt from the ciphertext prefix to derive the same key.
616
+ */
485
617
  async function decryptSession(encrypted, password) {
486
- const combined = Uint8Array.from(atob(encrypted), (c) => c.charCodeAt(0));
487
- const salt = combined.slice(0, SALT_LENGTH);
488
- const iv = combined.slice(SALT_LENGTH, SALT_LENGTH + IV_LENGTH);
489
- const data = combined.slice(SALT_LENGTH + IV_LENGTH);
490
- const key = await deriveKey(password, salt, "decrypt");
491
- const decrypted = await crypto.subtle.decrypt({ name: "AES-GCM", iv }, key, data);
492
- return JSON.parse(new TextDecoder().decode(decrypted));
618
+ const combined = Uint8Array.from(atob(encrypted), (c) => c.charCodeAt(0));
619
+ const salt = combined.slice(0, SALT_LENGTH);
620
+ const iv = combined.slice(SALT_LENGTH, 28);
621
+ const data = combined.slice(28);
622
+ const key = await deriveKey(password, salt, "decrypt");
623
+ const decrypted = await crypto.subtle.decrypt({
624
+ name: "AES-GCM",
625
+ iv
626
+ }, key, data);
627
+ return JSON.parse(new TextDecoder().decode(decrypted));
493
628
  }
494
- var stateStore = /* @__PURE__ */ new Map();
495
- var MastraAuthOkta = class extends MastraAuthProvider {
496
- domain;
497
- clientId;
498
- clientSecret;
499
- issuer;
500
- endpointBase;
501
- redirectUri;
502
- scopes;
503
- cookieName;
504
- cookieMaxAge;
505
- cookiePassword;
506
- secureCookies;
507
- apiToken;
508
- jwks;
509
- constructor(options) {
510
- super({ name: options?.name ?? "okta" });
511
- const domain = options?.domain ?? process.env.OKTA_DOMAIN;
512
- const clientId = options?.clientId ?? process.env.OKTA_CLIENT_ID;
513
- const clientSecret = options?.clientSecret ?? process.env.OKTA_CLIENT_SECRET;
514
- const issuer = options?.issuer ?? process.env.OKTA_ISSUER;
515
- const redirectUri = options?.redirectUri ?? process.env.OKTA_REDIRECT_URI;
516
- const cookiePassword = options?.session?.cookiePassword ?? process.env.OKTA_COOKIE_PASSWORD ?? crypto.randomUUID() + crypto.randomUUID();
517
- if (!domain) {
518
- throw new Error("Okta domain is required. Provide it in the options or set OKTA_DOMAIN environment variable.");
519
- }
520
- if (!clientId) {
521
- throw new Error(
522
- "Okta client ID is required. Provide it in the options or set OKTA_CLIENT_ID environment variable."
523
- );
524
- }
525
- if (!clientSecret) {
526
- throw new Error(
527
- "Okta client secret is required for SSO. Provide it in the options or set OKTA_CLIENT_SECRET environment variable."
528
- );
529
- }
530
- if (!redirectUri) {
531
- throw new Error(
532
- "Okta redirect URI is required for SSO. Provide it in the options or set OKTA_REDIRECT_URI environment variable."
533
- );
534
- }
535
- if (cookiePassword.length < 32) {
536
- throw new Error("Cookie password must be at least 32 characters. Set OKTA_COOKIE_PASSWORD environment variable.");
537
- }
538
- this.domain = domain;
539
- this.clientId = clientId;
540
- this.clientSecret = clientSecret;
541
- this.issuer = trimTrailingSlashes(issuer ?? `https://${domain}/oauth2/default`);
542
- this.endpointBase = this.issuer.includes("/oauth2/") || this.issuer.endsWith("/oauth2") ? this.issuer : `${this.issuer}/oauth2`;
543
- this.redirectUri = redirectUri;
544
- this.scopes = options?.scopes ?? DEFAULT_SCOPES;
545
- this.cookieName = options?.session?.cookieName ?? DEFAULT_COOKIE_NAME;
546
- this.cookieMaxAge = options?.session?.cookieMaxAge ?? DEFAULT_COOKIE_MAX_AGE;
547
- this.cookiePassword = cookiePassword;
548
- this.secureCookies = options?.session?.secureCookies ?? process.env.NODE_ENV === "production";
549
- this.apiToken = options?.apiToken ?? process.env.OKTA_API_TOKEN;
550
- this.jwks = jose.createRemoteJWKSet(new URL(`${this.endpointBase}/v1/keys`));
551
- if (!options?.session?.cookiePassword && !process.env.OKTA_COOKIE_PASSWORD) {
552
- console.warn(
553
- "[MastraAuthOkta] No cookie password set \u2014 using auto-generated value. Sessions will not survive restarts and will break in multi-instance deployments. Set OKTA_COOKIE_PASSWORD for production use."
554
- );
555
- }
556
- if (process.env.NODE_ENV === "production") {
557
- console.warn(
558
- "[MastraAuthOkta] Using in-memory OAuth state store. This will not work in serverless or multi-instance deployments. Consider implementing a custom state store for production."
559
- );
560
- }
561
- this.registerOptions(options);
562
- }
563
- // ============================================================================
564
- // MastraAuthProvider Implementation
565
- // ============================================================================
566
- /**
567
- * Authenticate a token from the request.
568
- * First tries to read from session cookie, then falls back to Authorization header.
569
- */
570
- async authenticateToken(token, request) {
571
- const sessionUser = await this.getUserFromSession(request);
572
- if (sessionUser) {
573
- return sessionUser;
574
- }
575
- if (!token || typeof token !== "string") {
576
- return null;
577
- }
578
- try {
579
- const { payload } = await jose.jwtVerify(token, this.jwks, {
580
- issuer: this.issuer,
581
- audience: this.clientId
582
- });
583
- return mapOktaClaimsToUser(payload);
584
- } catch (err) {
585
- console.error("Okta token verification failed:", err);
586
- return null;
587
- }
588
- }
589
- /**
590
- * Authorize a user.
591
- */
592
- authorizeUser(user, _request) {
593
- if (!user || !user.oktaId) return false;
594
- return true;
595
- }
596
- // ============================================================================
597
- // IUserProvider Implementation
598
- // ============================================================================
599
- /**
600
- * Get the current user from the request session.
601
- */
602
- async getCurrentUser(request) {
603
- return this.getUserFromSession(request);
604
- }
605
- /**
606
- * Get a user by ID via the Okta Users API.
607
- * Requires an API token (set OKTA_API_TOKEN or pass apiToken in options).
608
- * Returns null if no API token is configured or user is not found.
609
- */
610
- async getUser(userId) {
611
- if (!this.apiToken) {
612
- return null;
613
- }
614
- try {
615
- const response = await fetch(`https://${this.domain}/api/v1/users/${userId}`, {
616
- headers: {
617
- Authorization: `SSWS ${this.apiToken}`,
618
- Accept: "application/json"
619
- }
620
- });
621
- if (!response.ok) {
622
- return null;
623
- }
624
- const oktaProfile = await response.json();
625
- return {
626
- id: oktaProfile.id,
627
- oktaId: oktaProfile.id,
628
- email: oktaProfile.profile.email,
629
- name: [oktaProfile.profile.firstName, oktaProfile.profile.lastName].filter(Boolean).join(" ") || void 0
630
- };
631
- } catch {
632
- return null;
633
- }
634
- }
635
- /**
636
- * Get user from session cookie.
637
- */
638
- async getUserFromSession(request) {
639
- try {
640
- const cookieHeader = getRequestHeader2(request, "cookie");
641
- if (!cookieHeader) return null;
642
- const cookies = cookieHeader.split(";").map((c) => c.trim());
643
- const sessionCookie = cookies.find((c) => c.startsWith(`${this.cookieName}=`));
644
- if (!sessionCookie) return null;
645
- const sessionValue = sessionCookie.split("=")[1];
646
- if (!sessionValue) return null;
647
- const session = await decryptSession(decodeURIComponent(sessionValue), this.cookiePassword);
648
- if (session.expiresAt && session.expiresAt < Date.now()) {
649
- return null;
650
- }
651
- return session.user;
652
- } catch {
653
- return null;
654
- }
655
- }
656
- /**
657
- * Extract the raw ID token from the encrypted session cookie.
658
- * Used to provide id_token_hint for Okta logout.
659
- */
660
- async getIdTokenFromSession(request) {
661
- try {
662
- const cookieHeader = getRequestHeader2(request, "cookie");
663
- if (!cookieHeader) return null;
664
- const cookies = cookieHeader.split(";").map((c) => c.trim());
665
- const sessionCookie = cookies.find((c) => c.startsWith(`${this.cookieName}=`));
666
- if (!sessionCookie) return null;
667
- const sessionValue = sessionCookie.split("=")[1];
668
- if (!sessionValue) return null;
669
- const session = await decryptSession(decodeURIComponent(sessionValue), this.cookiePassword);
670
- return session.idToken ?? null;
671
- } catch {
672
- return null;
673
- }
674
- }
675
- // ============================================================================
676
- // ISSOProvider Implementation
677
- // ============================================================================
678
- /**
679
- * Get the URL to redirect users to for Okta login.
680
- * Uses client_secret authentication (no PKCE) since this is a confidential client.
681
- */
682
- getLoginUrl(redirectUri, state) {
683
- const stateId = state.includes("|") ? state.split("|")[0] : state;
684
- const actualRedirectUri = redirectUri ?? this.redirectUri;
685
- stateStore.set(stateId, {
686
- expiresAt: Date.now() + 10 * 60 * 1e3,
687
- redirectUri: actualRedirectUri
688
- });
689
- for (const [key, value] of stateStore.entries()) {
690
- if (value.expiresAt < Date.now()) {
691
- stateStore.delete(key);
692
- }
693
- }
694
- const params = new URLSearchParams({
695
- client_id: this.clientId,
696
- response_type: "code",
697
- scope: this.scopes.join(" "),
698
- redirect_uri: actualRedirectUri,
699
- state
700
- });
701
- return `${this.endpointBase}/v1/authorize?${params.toString()}`;
702
- }
703
- /**
704
- * Handle the OAuth callback from Okta.
705
- * Note: The server passes only the stateId (UUID part), not the full state.
706
- */
707
- async handleCallback(code, stateId) {
708
- const stored = stateStore.get(stateId);
709
- if (!stored) {
710
- throw new Error("Invalid or expired state parameter");
711
- }
712
- stateStore.delete(stateId);
713
- if (stored.expiresAt < Date.now()) {
714
- throw new Error("State parameter has expired");
715
- }
716
- const tokenResponse = await fetch(`${this.endpointBase}/v1/token`, {
717
- method: "POST",
718
- headers: {
719
- "Content-Type": "application/x-www-form-urlencoded",
720
- Authorization: `Basic ${btoa(`${this.clientId}:${this.clientSecret}`)}`
721
- },
722
- body: new URLSearchParams({
723
- grant_type: "authorization_code",
724
- code,
725
- redirect_uri: stored.redirectUri
726
- })
727
- });
728
- if (!tokenResponse.ok) {
729
- const error = await tokenResponse.text();
730
- throw new Error(`Token exchange failed: ${error}`);
731
- }
732
- const tokens = await tokenResponse.json();
733
- const { payload: idTokenPayload } = await jose.jwtVerify(tokens.id_token, this.jwks, {
734
- issuer: this.issuer,
735
- audience: this.clientId
736
- });
737
- const user = mapOktaClaimsToUser(idTokenPayload);
738
- const sessionData = {
739
- user,
740
- idToken: tokens.id_token,
741
- expiresAt: Date.now() + tokens.expires_in * 1e3
742
- };
743
- const encryptedSession = await encryptSession(sessionData, this.cookiePassword);
744
- const cookieValue = `${this.cookieName}=${encodeURIComponent(encryptedSession)}; ${this.cookieFlags(this.cookieMaxAge)}`;
745
- return {
746
- user,
747
- tokens: {
748
- accessToken: tokens.access_token,
749
- refreshToken: tokens.refresh_token,
750
- idToken: tokens.id_token,
751
- expiresAt: new Date(Date.now() + tokens.expires_in * 1e3)
752
- },
753
- cookies: [cookieValue]
754
- };
755
- }
756
- /**
757
- * Get the URL to redirect users to for logout.
758
- * Includes id_token_hint from session when available (required by Okta).
759
- */
760
- async getLogoutUrl(redirectUri, request) {
761
- const params = new URLSearchParams({
762
- post_logout_redirect_uri: redirectUri,
763
- client_id: this.clientId
764
- });
765
- if (request) {
766
- const idToken = await this.getIdTokenFromSession(request);
767
- if (idToken) {
768
- params.set("id_token_hint", idToken);
769
- }
770
- }
771
- return `${this.endpointBase}/v1/logout?${params.toString()}`;
772
- }
773
- /**
774
- * Get cookies to set during login.
775
- */
776
- getLoginCookies(_state) {
777
- return [];
778
- }
779
- /**
780
- * Get the configuration for rendering the login button.
781
- */
782
- getLoginButtonConfig() {
783
- return {
784
- provider: "okta",
785
- text: "Sign in with Okta"
786
- };
787
- }
788
- // ============================================================================
789
- // ISessionProvider Implementation
790
- // ============================================================================
791
- async createSession(userId, metadata) {
792
- const now = /* @__PURE__ */ new Date();
793
- return {
794
- id: crypto.randomUUID(),
795
- userId,
796
- createdAt: now,
797
- expiresAt: new Date(now.getTime() + this.cookieMaxAge * 1e3),
798
- metadata
799
- };
800
- }
801
- async validateSession(_sessionId) {
802
- return null;
803
- }
804
- async destroySession(_sessionId) {
805
- }
806
- async refreshSession(_sessionId) {
807
- return null;
808
- }
809
- getSessionIdFromRequest(_request) {
810
- return null;
811
- }
812
- getSessionHeaders(_session) {
813
- return {};
814
- }
815
- getClearSessionHeaders() {
816
- return {
817
- "Set-Cookie": `${this.cookieName}=; ${this.cookieFlags(0)}`
818
- };
819
- }
820
- /**
821
- * Build consistent cookie attribute string for set/clear operations.
822
- */
823
- cookieFlags(maxAge) {
824
- const flags = `Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}`;
825
- return this.secureCookies ? `${flags}; Secure` : flags;
826
- }
827
- // ============================================================================
828
- // Helper Methods
829
- // ============================================================================
830
- /**
831
- * Get the Okta domain.
832
- */
833
- getDomain() {
834
- return this.domain;
835
- }
836
- /**
837
- * Get the configured client ID.
838
- */
839
- getClientId() {
840
- return this.clientId;
841
- }
842
- /**
843
- * Get the configured redirect URI.
844
- */
845
- getRedirectUri() {
846
- return this.redirectUri;
847
- }
848
- /**
849
- * Get the issuer URL.
850
- */
851
- getIssuer() {
852
- return this.issuer;
853
- }
854
- };
855
629
  /**
856
- * EE Authentication Interfaces
857
- *
858
- * Enterprise interfaces for RBAC, ACL, and advanced authorization.
859
- *
860
- * @license Mastra Enterprise License - see ee/LICENSE
861
- * @packageDocumentation
862
- */
630
+ * In-memory store for state validation (keyed by state).
631
+ * Used to validate that callback state matches the login request.
632
+ */
633
+ const stateStore = /* @__PURE__ */ new Map();
863
634
  /**
864
- * FGA enforcement utility for checking fine-grained authorization.
865
- *
866
- * @license Mastra Enterprise License - see ee/LICENSE
867
- */
868
- /**
869
- * RBAC provider implementations.
870
- *
871
- * @license Mastra Enterprise License - see ee/LICENSE
872
- */
873
- /**
874
- * Default implementations for EE authentication.
875
- *
876
- * @license Mastra Enterprise License - see ee/LICENSE
877
- */
878
- /**
879
- * @mastra/core/auth/ee
880
- *
881
- * Enterprise authentication capabilities for Mastra.
882
- * This code is licensed under the Mastra Enterprise License - see ee/LICENSE.
883
- *
884
- * @license Mastra Enterprise License - see ee/LICENSE
885
- * @packageDocumentation
886
- */
887
-
635
+ * Mastra authentication provider for Okta with SSO support.
636
+ *
637
+ * Implements OAuth 2.0 / OIDC login flow with encrypted session cookies.
638
+ *
639
+ * @example Basic usage with SSO
640
+ * ```typescript
641
+ * import { MastraAuthOkta } from '@mastra/auth-okta';
642
+ *
643
+ * const auth = new MastraAuthOkta({
644
+ * domain: 'dev-123456.okta.com',
645
+ * clientId: 'your-client-id',
646
+ * clientSecret: 'your-client-secret',
647
+ * redirectUri: 'http://localhost:4111/api/auth/callback',
648
+ * });
649
+ * ```
650
+ */
651
+ var MastraAuthOkta = class extends MastraAuthProvider {
652
+ domain;
653
+ clientId;
654
+ clientSecret;
655
+ issuer;
656
+ endpointBase;
657
+ redirectUri;
658
+ audience;
659
+ scopes;
660
+ cookieName;
661
+ cookieMaxAge;
662
+ cookiePassword;
663
+ secureCookies;
664
+ apiToken;
665
+ jwks;
666
+ constructor(options) {
667
+ super({ name: options?.name ?? "okta" });
668
+ const domain = options?.domain ?? process.env.OKTA_DOMAIN;
669
+ const clientId = options?.clientId ?? process.env.OKTA_CLIENT_ID;
670
+ const clientSecret = options?.clientSecret ?? process.env.OKTA_CLIENT_SECRET;
671
+ const issuer = options?.issuer ?? process.env.OKTA_ISSUER;
672
+ const redirectUri = options?.redirectUri ?? process.env.OKTA_REDIRECT_URI;
673
+ const cookiePassword = options?.session?.cookiePassword ?? process.env.OKTA_COOKIE_PASSWORD ?? crypto.randomUUID() + crypto.randomUUID();
674
+ if (!domain) throw new Error("Okta domain is required. Provide it in the options or set OKTA_DOMAIN environment variable.");
675
+ if (!clientId) throw new Error("Okta client ID is required. Provide it in the options or set OKTA_CLIENT_ID environment variable.");
676
+ if (!clientSecret) throw new Error("Okta client secret is required for SSO. Provide it in the options or set OKTA_CLIENT_SECRET environment variable.");
677
+ if (!redirectUri) throw new Error("Okta redirect URI is required for SSO. Provide it in the options or set OKTA_REDIRECT_URI environment variable.");
678
+ if (cookiePassword.length < 32) throw new Error("Cookie password must be at least 32 characters. Set OKTA_COOKIE_PASSWORD environment variable.");
679
+ this.domain = domain;
680
+ this.clientId = clientId;
681
+ this.clientSecret = clientSecret;
682
+ this.issuer = trimTrailingSlashes(issuer ?? `https://${domain}/oauth2/default`);
683
+ this.endpointBase = this.issuer.includes("/oauth2/") || this.issuer.endsWith("/oauth2") ? this.issuer : `${this.issuer}/oauth2`;
684
+ this.redirectUri = redirectUri;
685
+ this.audience = options?.audience ?? process.env.OKTA_AUDIENCE ?? clientId;
686
+ this.scopes = options?.scopes ?? DEFAULT_SCOPES;
687
+ this.cookieName = options?.session?.cookieName ?? DEFAULT_COOKIE_NAME;
688
+ this.cookieMaxAge = options?.session?.cookieMaxAge ?? DEFAULT_COOKIE_MAX_AGE;
689
+ this.cookiePassword = cookiePassword;
690
+ this.secureCookies = options?.session?.secureCookies ?? process.env.NODE_ENV === "production";
691
+ this.apiToken = options?.apiToken ?? process.env.OKTA_API_TOKEN;
692
+ this.jwks = (0, jose.createRemoteJWKSet)(new URL(`${this.endpointBase}/v1/keys`));
693
+ if (!options?.session?.cookiePassword && !process.env.OKTA_COOKIE_PASSWORD) console.warn("[MastraAuthOkta] No cookie password set — using auto-generated value. Sessions will not survive restarts and will break in multi-instance deployments. Set OKTA_COOKIE_PASSWORD for production use.");
694
+ if (process.env.NODE_ENV === "production") console.warn("[MastraAuthOkta] Using in-memory OAuth state store. This will not work in serverless or multi-instance deployments. Consider implementing a custom state store for production.");
695
+ this.registerOptions(options);
696
+ }
697
+ /**
698
+ * Authenticate a token from the request.
699
+ * First tries to read from session cookie, then falls back to Authorization header.
700
+ */
701
+ async authenticateToken(token, request) {
702
+ const sessionUser = await this.getUserFromSession(request);
703
+ if (sessionUser) return sessionUser;
704
+ if (!token || typeof token !== "string") return null;
705
+ try {
706
+ const { payload } = await (0, jose.jwtVerify)(token, this.jwks, {
707
+ issuer: this.issuer,
708
+ audience: this.audience
709
+ });
710
+ return mapOktaClaimsToUser(payload);
711
+ } catch (err) {
712
+ console.error("Okta token verification failed:", err);
713
+ return null;
714
+ }
715
+ }
716
+ /**
717
+ * Authorize a user.
718
+ */
719
+ authorizeUser(user, _request) {
720
+ if (!user || !user.oktaId) return false;
721
+ return true;
722
+ }
723
+ /**
724
+ * Get the current user from the request session.
725
+ */
726
+ async getCurrentUser(request) {
727
+ return this.getUserFromSession(request);
728
+ }
729
+ /**
730
+ * Get a user by ID via the Okta Users API.
731
+ * Requires an API token (set OKTA_API_TOKEN or pass apiToken in options).
732
+ * Returns null if no API token is configured or user is not found.
733
+ */
734
+ async getUser(userId) {
735
+ if (!this.apiToken) return null;
736
+ try {
737
+ const response = await fetch(`https://${this.domain}/api/v1/users/${userId}`, { headers: {
738
+ Authorization: `SSWS ${this.apiToken}`,
739
+ Accept: "application/json"
740
+ } });
741
+ if (!response.ok) return null;
742
+ const oktaProfile = await response.json();
743
+ return {
744
+ id: oktaProfile.id,
745
+ oktaId: oktaProfile.id,
746
+ email: oktaProfile.profile.email,
747
+ name: [oktaProfile.profile.firstName, oktaProfile.profile.lastName].filter(Boolean).join(" ") || void 0
748
+ };
749
+ } catch {
750
+ return null;
751
+ }
752
+ }
753
+ /**
754
+ * Get user from session cookie.
755
+ */
756
+ async getUserFromSession(request) {
757
+ try {
758
+ const cookieHeader = getRequestHeader(request, "cookie");
759
+ if (!cookieHeader) return null;
760
+ const sessionCookie = cookieHeader.split(";").map((c) => c.trim()).find((c) => c.startsWith(`${this.cookieName}=`));
761
+ if (!sessionCookie) return null;
762
+ const sessionValue = sessionCookie.split("=")[1];
763
+ if (!sessionValue) return null;
764
+ const session = await decryptSession(decodeURIComponent(sessionValue), this.cookiePassword);
765
+ if (session.expiresAt && session.expiresAt < Date.now()) return null;
766
+ return session.user;
767
+ } catch {
768
+ return null;
769
+ }
770
+ }
771
+ /**
772
+ * Extract the raw ID token from the encrypted session cookie.
773
+ * Used to provide id_token_hint for Okta logout.
774
+ */
775
+ async getIdTokenFromSession(request) {
776
+ try {
777
+ const cookieHeader = getRequestHeader(request, "cookie");
778
+ if (!cookieHeader) return null;
779
+ const sessionCookie = cookieHeader.split(";").map((c) => c.trim()).find((c) => c.startsWith(`${this.cookieName}=`));
780
+ if (!sessionCookie) return null;
781
+ const sessionValue = sessionCookie.split("=")[1];
782
+ if (!sessionValue) return null;
783
+ return (await decryptSession(decodeURIComponent(sessionValue), this.cookiePassword)).idToken ?? null;
784
+ } catch {
785
+ return null;
786
+ }
787
+ }
788
+ /**
789
+ * Get the URL to redirect users to for Okta login.
790
+ * Uses client_secret authentication (no PKCE) since this is a confidential client.
791
+ */
792
+ getLoginUrl(redirectUri, state) {
793
+ const stateId = state.includes("|") ? state.split("|")[0] : state;
794
+ const actualRedirectUri = redirectUri ?? this.redirectUri;
795
+ stateStore.set(stateId, {
796
+ expiresAt: Date.now() + 600 * 1e3,
797
+ redirectUri: actualRedirectUri
798
+ });
799
+ for (const [key, value] of stateStore.entries()) if (value.expiresAt < Date.now()) stateStore.delete(key);
800
+ const params = new URLSearchParams({
801
+ client_id: this.clientId,
802
+ response_type: "code",
803
+ scope: this.scopes.join(" "),
804
+ redirect_uri: actualRedirectUri,
805
+ state
806
+ });
807
+ return `${this.endpointBase}/v1/authorize?${params.toString()}`;
808
+ }
809
+ /**
810
+ * Handle the OAuth callback from Okta.
811
+ * Note: The server passes only the stateId (UUID part), not the full state.
812
+ */
813
+ async handleCallback(code, stateId) {
814
+ const stored = stateStore.get(stateId);
815
+ if (!stored) throw new Error("Invalid or expired state parameter");
816
+ stateStore.delete(stateId);
817
+ if (stored.expiresAt < Date.now()) throw new Error("State parameter has expired");
818
+ const tokenResponse = await fetch(`${this.endpointBase}/v1/token`, {
819
+ method: "POST",
820
+ headers: {
821
+ "Content-Type": "application/x-www-form-urlencoded",
822
+ Authorization: `Basic ${btoa(`${this.clientId}:${this.clientSecret}`)}`
823
+ },
824
+ body: new URLSearchParams({
825
+ grant_type: "authorization_code",
826
+ code,
827
+ redirect_uri: stored.redirectUri
828
+ })
829
+ });
830
+ if (!tokenResponse.ok) {
831
+ const error = await tokenResponse.text();
832
+ throw new Error(`Token exchange failed: ${error}`);
833
+ }
834
+ const tokens = await tokenResponse.json();
835
+ const { payload: idTokenPayload } = await (0, jose.jwtVerify)(tokens.id_token, this.jwks, {
836
+ issuer: this.issuer,
837
+ audience: this.clientId
838
+ });
839
+ const user = mapOktaClaimsToUser(idTokenPayload);
840
+ const encryptedSession = await encryptSession({
841
+ user,
842
+ idToken: tokens.id_token,
843
+ expiresAt: Date.now() + tokens.expires_in * 1e3
844
+ }, this.cookiePassword);
845
+ const cookieValue = `${this.cookieName}=${encodeURIComponent(encryptedSession)}; ${this.cookieFlags(this.cookieMaxAge)}`;
846
+ return {
847
+ user,
848
+ tokens: {
849
+ accessToken: tokens.access_token,
850
+ refreshToken: tokens.refresh_token,
851
+ idToken: tokens.id_token,
852
+ expiresAt: new Date(Date.now() + tokens.expires_in * 1e3)
853
+ },
854
+ cookies: [cookieValue]
855
+ };
856
+ }
857
+ /**
858
+ * Get the URL to redirect users to for logout.
859
+ * Includes id_token_hint from session when available (required by Okta).
860
+ */
861
+ async getLogoutUrl(redirectUri, request) {
862
+ const params = new URLSearchParams({
863
+ post_logout_redirect_uri: redirectUri,
864
+ client_id: this.clientId
865
+ });
866
+ if (request) {
867
+ const idToken = await this.getIdTokenFromSession(request);
868
+ if (idToken) params.set("id_token_hint", idToken);
869
+ }
870
+ return `${this.endpointBase}/v1/logout?${params.toString()}`;
871
+ }
872
+ /**
873
+ * Get cookies to set during login.
874
+ */
875
+ getLoginCookies(_state) {
876
+ return [];
877
+ }
878
+ /**
879
+ * Get the configuration for rendering the login button.
880
+ */
881
+ getLoginButtonConfig() {
882
+ return {
883
+ provider: "okta",
884
+ text: "Sign in with Okta"
885
+ };
886
+ }
887
+ async createSession(userId, metadata) {
888
+ const now = /* @__PURE__ */ new Date();
889
+ return {
890
+ id: crypto.randomUUID(),
891
+ userId,
892
+ createdAt: now,
893
+ expiresAt: new Date(now.getTime() + this.cookieMaxAge * 1e3),
894
+ metadata
895
+ };
896
+ }
897
+ async validateSession(_sessionId) {
898
+ return null;
899
+ }
900
+ async destroySession(_sessionId) {}
901
+ async refreshSession(_sessionId) {
902
+ return null;
903
+ }
904
+ getSessionIdFromRequest(_request) {
905
+ return null;
906
+ }
907
+ getSessionHeaders(_session) {
908
+ return {};
909
+ }
910
+ getClearSessionHeaders() {
911
+ return { "Set-Cookie": `${this.cookieName}=; ${this.cookieFlags(0)}` };
912
+ }
913
+ /**
914
+ * Build consistent cookie attribute string for set/clear operations.
915
+ */
916
+ cookieFlags(maxAge) {
917
+ const flags = `Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}`;
918
+ return this.secureCookies ? `${flags}; Secure` : flags;
919
+ }
920
+ /**
921
+ * Get the Okta domain.
922
+ */
923
+ getDomain() {
924
+ return this.domain;
925
+ }
926
+ /**
927
+ * Get the configured client ID.
928
+ */
929
+ getClientId() {
930
+ return this.clientId;
931
+ }
932
+ /**
933
+ * Get the configured redirect URI.
934
+ */
935
+ getRedirectUri() {
936
+ return this.redirectUri;
937
+ }
938
+ /**
939
+ * Get the issuer URL.
940
+ */
941
+ getIssuer() {
942
+ return this.issuer;
943
+ }
944
+ };
945
+ //#endregion
888
946
  exports.MastraAuthOkta = MastraAuthOkta;
889
947
  exports.MastraRBACOkta = MastraRBACOkta;
890
948
  exports.mapOktaClaimsToUser = mapOktaClaimsToUser;
891
- //# sourceMappingURL=index.cjs.map
949
+
892
950
  //# sourceMappingURL=index.cjs.map