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