@mastra/auth-okta 0.1.2-alpha.0 → 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/CHANGELOG.md +35 -0
- package/README.md +2 -0
- package/dist/_types/@internal_auth/dist/_types/@internal_core/dist/base/index.d.ts +27 -27
- package/dist/_types/@internal_auth/dist/_types/@internal_core/dist/index-S1lgaKO7.d.ts +218 -0
- package/dist/_types/@internal_auth/dist/ee/fga-check.d.ts +2 -5
- package/dist/_types/@internal_auth/dist/ee/interfaces/fga.d.ts +47 -0
- package/dist/_types/@internal_auth/dist/ee/interfaces/permissions.generated.d.ts +16 -20
- package/dist/_types/@internal_auth/dist/index.d.ts +66 -0
- package/dist/_types/@internal_auth/dist/provider/index.d.ts +8 -1
- package/dist/auth-provider.d.ts +1 -0
- package/dist/auth-provider.d.ts.map +1 -1
- package/dist/index.cjs +919 -861
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +896 -856
- package/dist/index.js.map +1 -1
- package/dist/types.d.ts +12 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +14 -13
- package/dist/_types/@internal_auth/dist/_types/@internal_core/dist/logger/index.d.ts +0 -217
package/dist/index.js
CHANGED
|
@@ -1,884 +1,924 @@
|
|
|
1
|
-
import pkg from
|
|
2
|
-
import { LRUCache } from
|
|
3
|
-
import { createRemoteJWKSet, jwtVerify } from
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
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
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
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
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
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
|
-
|
|
82
|
-
|
|
83
|
-
|
|
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
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
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
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
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
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
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
|
-
|
|
443
|
+
//#endregion
|
|
444
|
+
//#region ../../packages/_internal-core/dist/base/index.js
|
|
352
445
|
var MastraBase = class {
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
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
|
-
|
|
478
|
+
//#endregion
|
|
479
|
+
//#region ../../packages/_internals/auth/dist/provider/index.js
|
|
391
480
|
var MastraAuthProvider = class extends MastraBase {
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
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
|
-
|
|
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
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
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
|
-
|
|
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
|
-
|
|
439
|
-
|
|
440
|
-
|
|
530
|
+
let end = value.length;
|
|
531
|
+
while (end > 0 && value[end - 1] === "/") end--;
|
|
532
|
+
return value.slice(0, end);
|
|
441
533
|
}
|
|
442
|
-
function
|
|
443
|
-
|
|
444
|
-
|
|
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
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
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
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
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
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
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
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
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
|
-
|
|
851
|
-
|
|
852
|
-
|
|
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
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
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
|
-
|
|
923
|
+
|
|
884
924
|
//# sourceMappingURL=index.js.map
|