@mastra/auth-cloud 1.2.3-alpha.0 → 1.2.4-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,1157 +1,1433 @@
1
- import { randomBytes, createHash } from 'crypto';
2
-
3
- // src/error.ts
4
- var AuthError = class _AuthError extends Error {
5
- code;
6
- cause;
7
- cloudCode;
8
- cloudMessage;
9
- constructor(code, message, options) {
10
- super(message);
11
- this.name = "AuthError";
12
- this.code = code;
13
- this.cause = options?.cause;
14
- this.cloudCode = options?.cloudCode;
15
- this.cloudMessage = options?.cloudMessage;
16
- Object.setPrototypeOf(this, new.target.prototype);
17
- }
18
- /**
19
- * Factory: OAuth state parameter is invalid or malformed.
20
- */
21
- static invalidState() {
22
- return new _AuthError("invalid_state", "OAuth state parameter is invalid or malformed.");
23
- }
24
- /**
25
- * Factory: OAuth state parameter does not match expected value.
26
- */
27
- static stateMismatch() {
28
- return new _AuthError("state_mismatch", "OAuth state parameter does not match. Possible CSRF attack.");
29
- }
30
- /**
31
- * Factory: Authorization code is missing from callback.
32
- */
33
- static missingCode() {
34
- return new _AuthError("missing_code", "Authorization code is missing from OAuth callback.");
35
- }
36
- /**
37
- * Factory: Token exchange with Cloud API failed.
38
- */
39
- static tokenExchangeFailed(options) {
40
- return new _AuthError("token_exchange_failed", "Failed to exchange authorization code for tokens.", options);
41
- }
42
- /**
43
- * Factory: Token verification failed.
44
- */
45
- static verificationFailed() {
46
- return new _AuthError("verification_failed", "Token verification failed.");
47
- }
48
- /**
49
- * Factory: Session is invalid.
50
- */
51
- static sessionInvalid() {
52
- return new _AuthError("session_invalid", "Session is invalid or has been revoked.");
53
- }
54
- /**
55
- * Factory: Session has expired.
56
- */
57
- static sessionExpired() {
58
- return new _AuthError("session_expired", "Session has expired. Please log in again.");
59
- }
60
- /**
61
- * Factory: Network error during API call.
62
- */
63
- static networkError(cause) {
64
- return new _AuthError("network_error", "Network error occurred while communicating with Cloud API.", { cause });
65
- }
66
- /**
67
- * Factory: Cloud API returned an error.
68
- */
69
- static cloudApiError(options) {
70
- const message = options?.cloudMessage ?? "Cloud API returned an error.";
71
- return new _AuthError("cloud_api_error", message, options);
72
- }
1
+ import { createHash, randomBytes } from "crypto";
2
+ //#region src/error.ts
3
+ /**
4
+ * Error class for authentication-related failures.
5
+ * Uses a code discriminator for programmatic error handling.
6
+ */
7
+ var AuthError = class AuthError extends Error {
8
+ code;
9
+ cause;
10
+ cloudCode;
11
+ cloudMessage;
12
+ constructor(code, message, options) {
13
+ super(message);
14
+ this.name = "AuthError";
15
+ this.code = code;
16
+ this.cause = options?.cause;
17
+ this.cloudCode = options?.cloudCode;
18
+ this.cloudMessage = options?.cloudMessage;
19
+ Object.setPrototypeOf(this, new.target.prototype);
20
+ }
21
+ /**
22
+ * Factory: OAuth state parameter is invalid or malformed.
23
+ */
24
+ static invalidState() {
25
+ return new AuthError("invalid_state", "OAuth state parameter is invalid or malformed.");
26
+ }
27
+ /**
28
+ * Factory: OAuth state parameter does not match expected value.
29
+ */
30
+ static stateMismatch() {
31
+ return new AuthError("state_mismatch", "OAuth state parameter does not match. Possible CSRF attack.");
32
+ }
33
+ /**
34
+ * Factory: Authorization code is missing from callback.
35
+ */
36
+ static missingCode() {
37
+ return new AuthError("missing_code", "Authorization code is missing from OAuth callback.");
38
+ }
39
+ /**
40
+ * Factory: Token exchange with Cloud API failed.
41
+ */
42
+ static tokenExchangeFailed(options) {
43
+ return new AuthError("token_exchange_failed", "Failed to exchange authorization code for tokens.", options);
44
+ }
45
+ /**
46
+ * Factory: Token verification failed.
47
+ */
48
+ static verificationFailed() {
49
+ return new AuthError("verification_failed", "Token verification failed.");
50
+ }
51
+ /**
52
+ * Factory: Session is invalid.
53
+ */
54
+ static sessionInvalid() {
55
+ return new AuthError("session_invalid", "Session is invalid or has been revoked.");
56
+ }
57
+ /**
58
+ * Factory: Session has expired.
59
+ */
60
+ static sessionExpired() {
61
+ return new AuthError("session_expired", "Session has expired. Please log in again.");
62
+ }
63
+ /**
64
+ * Factory: Network error during API call.
65
+ */
66
+ static networkError(cause) {
67
+ return new AuthError("network_error", "Network error occurred while communicating with Cloud API.", { cause });
68
+ }
69
+ /**
70
+ * Factory: Cloud API returned an error.
71
+ */
72
+ static cloudApiError(options) {
73
+ const message = options?.cloudMessage ?? "Cloud API returned an error.";
74
+ return new AuthError("cloud_api_error", message, options);
75
+ }
73
76
  };
74
-
75
- // src/oauth/state.ts
77
+ //#endregion
78
+ //#region src/oauth/state.ts
79
+ /**
80
+ * OAuth state parameter encoding/decoding.
81
+ *
82
+ * The state parameter carries:
83
+ * - csrf: CSRF token for validation
84
+ * - returnTo: URL to redirect after successful login
85
+ *
86
+ * @internal This module is not exported from the main package.
87
+ */
88
+ /**
89
+ * Encode state data into a base64url string for OAuth state parameter.
90
+ *
91
+ * @param csrf - CSRF token to include
92
+ * @param returnTo - URL to redirect to after login
93
+ * @returns Base64url encoded state string
94
+ */
76
95
  function encodeState(csrf, returnTo) {
77
- const data = { csrf, returnTo };
78
- const json = JSON.stringify(data);
79
- return Buffer.from(json).toString("base64url");
96
+ const json = JSON.stringify({
97
+ csrf,
98
+ returnTo
99
+ });
100
+ return Buffer.from(json).toString("base64url");
80
101
  }
102
+ /**
103
+ * Decode state parameter back to StateData.
104
+ *
105
+ * @param state - Base64url encoded state string
106
+ * @returns Decoded state data
107
+ * @throws AuthError with code 'invalid_state' if decoding fails
108
+ */
81
109
  function decodeState(state) {
82
- try {
83
- const json = Buffer.from(state, "base64url").toString();
84
- const data = JSON.parse(json);
85
- if (typeof data.csrf !== "string" || typeof data.returnTo !== "string") {
86
- throw new Error("Missing required fields");
87
- }
88
- return data;
89
- } catch {
90
- throw AuthError.invalidState();
91
- }
110
+ try {
111
+ const json = Buffer.from(state, "base64url").toString();
112
+ const data = JSON.parse(json);
113
+ if (typeof data.csrf !== "string" || typeof data.returnTo !== "string") throw new Error("Missing required fields");
114
+ return data;
115
+ } catch {
116
+ throw AuthError.invalidState();
117
+ }
92
118
  }
119
+ /**
120
+ * Validate and sanitize returnTo URL to prevent open redirect attacks.
121
+ *
122
+ * Safe values:
123
+ * - Relative paths starting with '/' (but not '//')
124
+ * - Absolute URLs with same origin as request
125
+ *
126
+ * @param returnTo - URL from user input (may be undefined)
127
+ * @param requestOrigin - Origin of the current request (e.g., 'https://example.com')
128
+ * @returns Safe redirect URL, defaults to '/' if invalid
129
+ */
93
130
  function validateReturnTo(returnTo, requestOrigin) {
94
- if (!returnTo) {
95
- return "/";
96
- }
97
- if (returnTo.startsWith("/") && !returnTo.startsWith("//")) {
98
- return returnTo;
99
- }
100
- try {
101
- const parsed = new URL(returnTo);
102
- const origin = new URL(requestOrigin);
103
- if (parsed.origin === origin.origin) {
104
- return returnTo;
105
- }
106
- } catch {
107
- }
108
- return "/";
131
+ if (!returnTo) return "/";
132
+ if (returnTo.startsWith("/") && !returnTo.startsWith("//")) return returnTo;
133
+ try {
134
+ const parsed = new URL(returnTo);
135
+ const origin = new URL(requestOrigin);
136
+ if (parsed.origin === origin.origin) return returnTo;
137
+ } catch {}
138
+ return "/";
109
139
  }
110
-
111
- // src/oauth/network.ts
140
+ //#endregion
141
+ //#region src/oauth/network.ts
142
+ /**
143
+ * Network utilities for OAuth flow.
144
+ *
145
+ * Provides fetch wrapper with single retry for transient network errors.
146
+ *
147
+ * @internal This module is not exported from the main package.
148
+ */
149
+ /**
150
+ * Fetch with single retry on network errors.
151
+ *
152
+ * Retries ONLY on network failures (fetch throws), not HTTP error responses.
153
+ * Caller is responsible for handling HTTP status codes.
154
+ *
155
+ * @param url - URL to fetch
156
+ * @param options - Fetch options
157
+ * @returns Response (may have error status code)
158
+ * @throws AuthError with code 'network_error' if both attempts fail
159
+ */
112
160
  async function fetchWithRetry(url, options) {
113
- try {
114
- return await fetch(url, options);
115
- } catch {
116
- try {
117
- return await fetch(url, options);
118
- } catch (retryError) {
119
- throw AuthError.networkError(retryError instanceof Error ? retryError : void 0);
120
- }
121
- }
161
+ try {
162
+ return await fetch(url, options);
163
+ } catch {
164
+ try {
165
+ return await fetch(url, options);
166
+ } catch (retryError) {
167
+ throw AuthError.networkError(retryError instanceof Error ? retryError : void 0);
168
+ }
169
+ }
122
170
  }
123
-
124
- // src/pkce/error.ts
125
- var PKCEError = class _PKCEError extends Error {
126
- code;
127
- cause;
128
- constructor(code, message, cause) {
129
- super(message);
130
- this.name = "PKCEError";
131
- this.code = code;
132
- this.cause = cause;
133
- Object.setPrototypeOf(this, new.target.prototype);
134
- }
135
- /**
136
- * Factory: PKCE verifier cookie not found.
137
- */
138
- static missingVerifier() {
139
- return new _PKCEError(
140
- "MISSING_VERIFIER",
141
- "PKCE verifier cookie not found. Authorization flow may have expired or was not initiated properly."
142
- );
143
- }
144
- /**
145
- * Factory: PKCE verifier has expired.
146
- */
147
- static expired() {
148
- return new _PKCEError("EXPIRED", "PKCE verifier has expired. Please restart the authorization flow.");
149
- }
150
- /**
151
- * Factory: PKCE verifier cookie is malformed.
152
- */
153
- static invalid(cause) {
154
- return new _PKCEError("INVALID", "PKCE verifier cookie is malformed or invalid.", cause);
155
- }
171
+ //#endregion
172
+ //#region src/pkce/error.ts
173
+ /**
174
+ * Error class for PKCE-related failures.
175
+ * Uses a code discriminator for programmatic error handling.
176
+ */
177
+ var PKCEError = class PKCEError extends Error {
178
+ code;
179
+ cause;
180
+ constructor(code, message, cause) {
181
+ super(message);
182
+ this.name = "PKCEError";
183
+ this.code = code;
184
+ this.cause = cause;
185
+ Object.setPrototypeOf(this, new.target.prototype);
186
+ }
187
+ /**
188
+ * Factory: PKCE verifier cookie not found.
189
+ */
190
+ static missingVerifier() {
191
+ return new PKCEError("MISSING_VERIFIER", "PKCE verifier cookie not found. Authorization flow may have expired or was not initiated properly.");
192
+ }
193
+ /**
194
+ * Factory: PKCE verifier has expired.
195
+ */
196
+ static expired() {
197
+ return new PKCEError("EXPIRED", "PKCE verifier has expired. Please restart the authorization flow.");
198
+ }
199
+ /**
200
+ * Factory: PKCE verifier cookie is malformed.
201
+ */
202
+ static invalid(cause) {
203
+ return new PKCEError("INVALID", "PKCE verifier cookie is malformed or invalid.", cause);
204
+ }
156
205
  };
157
-
158
- // src/pkce/cookie.ts
159
- var PKCE_COOKIE_NAME = "mastra_pkce_verifier";
206
+ //#endregion
207
+ //#region src/pkce/cookie.ts
208
+ /**
209
+ * PKCE cookie storage utilities.
210
+ * Handles serialization, parsing, and clearing of PKCE verifier cookies.
211
+ *
212
+ * @internal This module is not exported from the main package.
213
+ */
214
+ /**
215
+ * Cookie name for PKCE verifier storage.
216
+ */
217
+ const PKCE_COOKIE_NAME = "mastra_pkce_verifier";
218
+ /**
219
+ * Create a Set-Cookie header value for storing PKCE verifier and state.
220
+ *
221
+ * @param verifier - The code verifier for PKCE
222
+ * @param state - The state parameter for CSRF protection
223
+ * @param isProduction - Whether to add Secure flag (required for HTTPS)
224
+ * @returns Set-Cookie header value
225
+ */
160
226
  function setPKCECookie(verifier, state, isProduction) {
161
- const ttlSeconds = 5 * 60;
162
- const data = {
163
- verifier,
164
- state,
165
- expiresAt: Date.now() + ttlSeconds * 1e3
166
- };
167
- const encoded = encodeURIComponent(JSON.stringify(data));
168
- let cookie = `${PKCE_COOKIE_NAME}=${encoded}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${ttlSeconds}`;
169
- if (isProduction) {
170
- cookie += "; Secure";
171
- }
172
- return cookie;
227
+ const ttlSeconds = 300;
228
+ const data = {
229
+ verifier,
230
+ state,
231
+ expiresAt: Date.now() + ttlSeconds * 1e3
232
+ };
233
+ const encoded = encodeURIComponent(JSON.stringify(data));
234
+ let cookie = `${PKCE_COOKIE_NAME}=${encoded}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${ttlSeconds}`;
235
+ if (isProduction) cookie += "; Secure";
236
+ return cookie;
173
237
  }
238
+ /**
239
+ * Parse the PKCE cookie from a Cookie header.
240
+ *
241
+ * @param cookieHeader - The Cookie header value (may be null)
242
+ * @returns Parsed cookie data
243
+ * @throws PKCEError if cookie is missing, expired, or malformed
244
+ */
174
245
  function parsePKCECookie(cookieHeader) {
175
- if (!cookieHeader) {
176
- throw PKCEError.missingVerifier();
177
- }
178
- const match = cookieHeader.match(new RegExp(`${PKCE_COOKIE_NAME}=([^;]+)`));
179
- if (!match?.[1]) {
180
- throw PKCEError.missingVerifier();
181
- }
182
- let data;
183
- try {
184
- data = JSON.parse(decodeURIComponent(match[1]));
185
- } catch (e) {
186
- throw PKCEError.invalid(e instanceof Error ? e : void 0);
187
- }
188
- if (data.expiresAt < Date.now()) {
189
- throw PKCEError.expired();
190
- }
191
- return data;
246
+ if (!cookieHeader) throw PKCEError.missingVerifier();
247
+ const match = cookieHeader.match(new RegExp(`${PKCE_COOKIE_NAME}=([^;]+)`));
248
+ if (!match?.[1]) throw PKCEError.missingVerifier();
249
+ let data;
250
+ try {
251
+ data = JSON.parse(decodeURIComponent(match[1]));
252
+ } catch (e) {
253
+ throw PKCEError.invalid(e instanceof Error ? e : void 0);
254
+ }
255
+ if (data.expiresAt < Date.now()) throw PKCEError.expired();
256
+ return data;
192
257
  }
258
+ /**
259
+ * Create a Set-Cookie header value to clear the PKCE cookie.
260
+ *
261
+ * @returns Set-Cookie header value that expires the cookie
262
+ */
193
263
  function clearPKCECookie() {
194
- return `${PKCE_COOKIE_NAME}=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0`;
264
+ return `${PKCE_COOKIE_NAME}=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0`;
195
265
  }
266
+ //#endregion
267
+ //#region src/pkce/pkce.ts
268
+ /**
269
+ * PKCE (Proof Key for Code Exchange) cryptographic utilities.
270
+ * Implements RFC 7636 S256 challenge method.
271
+ *
272
+ * @internal This module is not exported from the main package.
273
+ */
274
+ /**
275
+ * Generate a code verifier for PKCE.
276
+ * Uses 32 random bytes encoded as base64url (43 characters).
277
+ *
278
+ * Per RFC 7636: code_verifier must be 43-128 characters using unreserved characters.
279
+ */
196
280
  function generateCodeVerifier() {
197
- return randomBytes(32).toString("base64url");
281
+ return randomBytes(32).toString("base64url");
198
282
  }
283
+ /**
284
+ * Compute the S256 code challenge from a verifier.
285
+ * challenge = BASE64URL(SHA256(verifier))
286
+ *
287
+ * Per RFC 7636: S256 method uses SHA-256 hash of the verifier.
288
+ */
199
289
  function computeCodeChallenge(verifier) {
200
- return createHash("sha256").update(verifier).digest("base64url");
290
+ return createHash("sha256").update(verifier).digest("base64url");
201
291
  }
292
+ /**
293
+ * Generate a state parameter for CSRF protection.
294
+ * Uses 16 random bytes encoded as base64url (22 characters).
295
+ */
202
296
  function generateState() {
203
- return randomBytes(16).toString("base64url");
297
+ return randomBytes(16).toString("base64url");
204
298
  }
205
-
206
- // src/oauth/oauth.ts
299
+ //#endregion
300
+ //#region src/oauth/oauth.ts
301
+ /**
302
+ * OAuth authorization flow functions.
303
+ *
304
+ * Implements login URL generation and callback handling for
305
+ * Mastra Cloud authentication with PKCE.
306
+ *
307
+ * @internal This module is not exported from the main package.
308
+ */
309
+ /**
310
+ * Generate a login URL for Mastra Cloud OAuth flow.
311
+ *
312
+ * Creates a URL with PKCE challenge and state parameter for CSRF protection.
313
+ * Returns a PKCE cookie that must be set on the response.
314
+ *
315
+ * @param options - Login URL options
316
+ * @returns URL to redirect to and cookies to set
317
+ */
207
318
  function getLoginUrl(options) {
208
- const { projectId, cloudBaseUrl, callbackUrl, returnTo, requestOrigin, isProduction } = options;
209
- const verifier = generateCodeVerifier();
210
- const challenge = computeCodeChallenge(verifier);
211
- const csrf = generateState();
212
- const validatedReturnTo = validateReturnTo(returnTo, requestOrigin);
213
- const state = encodeState(csrf, validatedReturnTo);
214
- const url = new URL("/auth/oss", cloudBaseUrl);
215
- url.searchParams.set("project_id", projectId);
216
- url.searchParams.set("code_challenge", challenge);
217
- url.searchParams.set("code_challenge_method", "S256");
218
- url.searchParams.set("redirect_uri", callbackUrl);
219
- url.searchParams.set("state", state);
220
- const isProductionEnv = isProduction ?? process.env.NODE_ENV === "production";
221
- const pkceCookie = setPKCECookie(verifier, csrf, isProductionEnv);
222
- return {
223
- url: url.toString(),
224
- cookies: [pkceCookie]
225
- };
319
+ const { projectId, cloudBaseUrl, callbackUrl, returnTo, requestOrigin, isProduction } = options;
320
+ const verifier = generateCodeVerifier();
321
+ const challenge = computeCodeChallenge(verifier);
322
+ const csrf = generateState();
323
+ const state = encodeState(csrf, validateReturnTo(returnTo, requestOrigin));
324
+ const url = new URL("/auth/oss", cloudBaseUrl);
325
+ url.searchParams.set("project_id", projectId);
326
+ url.searchParams.set("code_challenge", challenge);
327
+ url.searchParams.set("code_challenge_method", "S256");
328
+ url.searchParams.set("redirect_uri", callbackUrl);
329
+ url.searchParams.set("state", state);
330
+ const pkceCookie = setPKCECookie(verifier, csrf, isProduction ?? process.env.NODE_ENV === "production");
331
+ return {
332
+ url: url.toString(),
333
+ cookies: [pkceCookie]
334
+ };
226
335
  }
336
+ /**
337
+ * Handle OAuth callback from Mastra Cloud.
338
+ *
339
+ * Validates state for CSRF, exchanges code for tokens, and returns user info.
340
+ * Returns a cookie to clear the PKCE state.
341
+ *
342
+ * Note: Session cookie is NOT set here - caller (session module) handles that.
343
+ *
344
+ * @param options - Callback options
345
+ * @returns User info, access token, and redirect URL
346
+ * @throws PKCEError if PKCE cookie is missing or expired
347
+ * @throws AuthError if state validation fails or token exchange fails
348
+ */
227
349
  async function handleCallback(options) {
228
- const { projectId, cloudBaseUrl, redirectUri, code, state, cookieHeader } = options;
229
- const pkceData = parsePKCECookie(cookieHeader);
230
- const stateData = decodeState(state);
231
- if (stateData.csrf !== pkceData.state) {
232
- throw AuthError.stateMismatch();
233
- }
234
- const response = await fetchWithRetry(`${cloudBaseUrl}/auth/callback`, {
235
- method: "POST",
236
- headers: {
237
- "Content-Type": "application/json",
238
- "X-Project-ID": projectId
239
- },
240
- body: JSON.stringify({
241
- code,
242
- redirect_uri: redirectUri,
243
- code_verifier: pkceData.verifier
244
- })
245
- });
246
- if (!response.ok) {
247
- let cloudCode;
248
- let cloudMessage;
249
- try {
250
- const errorBody = await response.json();
251
- cloudCode = errorBody.code;
252
- cloudMessage = errorBody.message;
253
- } catch {
254
- }
255
- throw AuthError.tokenExchangeFailed({ cloudCode, cloudMessage });
256
- }
257
- const body = await response.json();
258
- const verifyResponse = await fetchWithRetry(`${cloudBaseUrl}/auth/verify`, {
259
- method: "POST",
260
- headers: {
261
- Authorization: `Bearer ${body.access_token}`,
262
- "X-Project-ID": projectId
263
- }
264
- });
265
- if (!verifyResponse.ok) {
266
- throw AuthError.verificationFailed();
267
- }
268
- const verifyBody = await verifyResponse.json();
269
- const clearCookie = clearPKCECookie();
270
- return {
271
- user: {
272
- id: verifyBody.sub,
273
- email: verifyBody.email,
274
- name: verifyBody.name,
275
- avatar: verifyBody.avatar_url,
276
- role: verifyBody.role
277
- },
278
- accessToken: body.access_token,
279
- returnTo: stateData.returnTo,
280
- cookies: [clearCookie]
281
- };
350
+ const { projectId, cloudBaseUrl, redirectUri, code, state, cookieHeader } = options;
351
+ const pkceData = parsePKCECookie(cookieHeader);
352
+ const stateData = decodeState(state);
353
+ if (stateData.csrf !== pkceData.state) throw AuthError.stateMismatch();
354
+ const response = await fetchWithRetry(`${cloudBaseUrl}/auth/callback`, {
355
+ method: "POST",
356
+ headers: {
357
+ "Content-Type": "application/json",
358
+ "X-Project-ID": projectId
359
+ },
360
+ body: JSON.stringify({
361
+ code,
362
+ redirect_uri: redirectUri,
363
+ code_verifier: pkceData.verifier
364
+ })
365
+ });
366
+ if (!response.ok) {
367
+ let cloudCode;
368
+ let cloudMessage;
369
+ try {
370
+ const errorBody = await response.json();
371
+ cloudCode = errorBody.code;
372
+ cloudMessage = errorBody.message;
373
+ } catch {}
374
+ throw AuthError.tokenExchangeFailed({
375
+ cloudCode,
376
+ cloudMessage
377
+ });
378
+ }
379
+ const body = await response.json();
380
+ const verifyResponse = await fetchWithRetry(`${cloudBaseUrl}/auth/verify`, {
381
+ method: "POST",
382
+ headers: {
383
+ Authorization: `Bearer ${body.access_token}`,
384
+ "X-Project-ID": projectId
385
+ }
386
+ });
387
+ if (!verifyResponse.ok) throw AuthError.verificationFailed();
388
+ const verifyBody = await verifyResponse.json();
389
+ const clearCookie = clearPKCECookie();
390
+ return {
391
+ user: {
392
+ id: verifyBody.sub,
393
+ email: verifyBody.email,
394
+ name: verifyBody.name,
395
+ avatar: verifyBody.avatar_url,
396
+ role: verifyBody.role
397
+ },
398
+ accessToken: body.access_token,
399
+ returnTo: stateData.returnTo,
400
+ cookies: [clearCookie]
401
+ };
282
402
  }
283
-
284
- // src/session/cookie.ts
285
- var SESSION_COOKIE_NAME = "mastra_cloud_session";
403
+ //#endregion
404
+ //#region src/session/cookie.ts
405
+ /**
406
+ * Session cookie utilities.
407
+ * Handles setting, parsing, and clearing of session cookies.
408
+ *
409
+ * @internal This module is not exported from the main package.
410
+ */
411
+ /**
412
+ * Cookie name for session token storage.
413
+ */
414
+ const SESSION_COOKIE_NAME = "mastra_cloud_session";
415
+ /**
416
+ * Create a Set-Cookie header value for storing session token.
417
+ *
418
+ * @param token - The session token
419
+ * @param isProduction - Whether to add Secure flag (required for HTTPS)
420
+ * @returns Set-Cookie header value
421
+ */
286
422
  function setSessionCookie(token, isProduction) {
287
- const ttlSeconds = 24 * 60 * 60;
288
- let cookie = `${SESSION_COOKIE_NAME}=${token}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${ttlSeconds}`;
289
- if (isProduction) {
290
- cookie += "; Secure";
291
- }
292
- return cookie;
423
+ let cookie = `${SESSION_COOKIE_NAME}=${token}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${1440 * 60}`;
424
+ if (isProduction) cookie += "; Secure";
425
+ return cookie;
293
426
  }
427
+ /**
428
+ * Parse the session token from a Cookie header.
429
+ *
430
+ * @param cookieHeader - The Cookie header value (may be null)
431
+ * @returns Session token or null if not present
432
+ */
294
433
  function parseSessionCookie(cookieHeader) {
295
- if (!cookieHeader) {
296
- return null;
297
- }
298
- const match = cookieHeader.match(new RegExp(`${SESSION_COOKIE_NAME}=([^;]+)`));
299
- return match?.[1] ?? null;
434
+ if (!cookieHeader) return null;
435
+ return cookieHeader.match(new RegExp(`mastra_cloud_session=([^;]+)`))?.[1] ?? null;
300
436
  }
437
+ /**
438
+ * Create a Set-Cookie header value to clear the session cookie.
439
+ *
440
+ * @returns Set-Cookie header value that expires the cookie
441
+ */
301
442
  function clearSessionCookie() {
302
- return `${SESSION_COOKIE_NAME}=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0`;
443
+ return `${SESSION_COOKIE_NAME}=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0`;
303
444
  }
304
-
305
- // src/session/session.ts
445
+ //#endregion
446
+ //#region src/session/session.ts
447
+ /**
448
+ * Session lifecycle functions.
449
+ * Handles token verification, session validation, and logout.
450
+ *
451
+ * @internal This module is not exported from the main package.
452
+ */
453
+ /**
454
+ * Verify an access token with Cloud API.
455
+ *
456
+ * @param options - Verification options
457
+ * @returns User and role information
458
+ * @throws AuthError with code 'verification_failed' if verification fails
459
+ * @throws AuthError with code 'network_error' if network request fails
460
+ */
306
461
  async function verifyToken(options) {
307
- const { projectId, cloudBaseUrl, token } = options;
308
- const response = await fetchWithRetry(`${cloudBaseUrl}/auth/verify`, {
309
- method: "POST",
310
- headers: {
311
- Authorization: `Bearer ${token}`,
312
- "X-Project-ID": projectId
313
- }
314
- });
315
- if (!response.ok) {
316
- throw AuthError.verificationFailed();
317
- }
318
- const body = await response.json();
319
- if (body.token_type === "project_api_token") {
320
- return {
321
- user: {
322
- id: "api-token",
323
- email: void 0,
324
- name: void 0,
325
- avatar: void 0
326
- },
327
- role: body.role
328
- };
329
- }
330
- return {
331
- user: {
332
- id: body.sub,
333
- email: body.email,
334
- name: body.name,
335
- avatar: body.avatar_url
336
- },
337
- role: body.role
338
- };
462
+ const { projectId, cloudBaseUrl, token } = options;
463
+ const response = await fetchWithRetry(`${cloudBaseUrl}/auth/verify`, {
464
+ method: "POST",
465
+ headers: {
466
+ Authorization: `Bearer ${token}`,
467
+ "X-Project-ID": projectId
468
+ }
469
+ });
470
+ if (!response.ok) throw AuthError.verificationFailed();
471
+ const body = await response.json();
472
+ if (body.token_type === "project_api_token") return {
473
+ user: {
474
+ id: "api-token",
475
+ email: void 0,
476
+ name: void 0,
477
+ avatar: void 0
478
+ },
479
+ role: body.role
480
+ };
481
+ return {
482
+ user: {
483
+ id: body.sub,
484
+ email: body.email,
485
+ name: body.name,
486
+ avatar: body.avatar_url
487
+ },
488
+ role: body.role
489
+ };
339
490
  }
491
+ /**
492
+ * Validate an existing session with Cloud API.
493
+ *
494
+ * @param options - Session options
495
+ * @returns Session data if valid, null otherwise
496
+ */
340
497
  async function validateSession(options) {
341
- const { projectId, cloudBaseUrl, sessionToken } = options;
342
- try {
343
- const response = await fetchWithRetry(`${cloudBaseUrl}/auth/session/validate`, {
344
- method: "POST",
345
- headers: {
346
- "Content-Type": "application/json",
347
- Authorization: `Bearer ${sessionToken}`,
348
- "X-Project-ID": projectId
349
- }
350
- });
351
- if (!response.ok) {
352
- return null;
353
- }
354
- return await response.json();
355
- } catch {
356
- return null;
357
- }
498
+ const { projectId, cloudBaseUrl, sessionToken } = options;
499
+ try {
500
+ const response = await fetchWithRetry(`${cloudBaseUrl}/auth/session/validate`, {
501
+ method: "POST",
502
+ headers: {
503
+ "Content-Type": "application/json",
504
+ Authorization: `Bearer ${sessionToken}`,
505
+ "X-Project-ID": projectId
506
+ }
507
+ });
508
+ if (!response.ok) return null;
509
+ return await response.json();
510
+ } catch {
511
+ return null;
512
+ }
358
513
  }
514
+ /**
515
+ * Destroy a session with Cloud API.
516
+ * Note: X-Project-ID not required for this endpoint.
517
+ *
518
+ * @param options - Session options
519
+ */
359
520
  async function destroySession(options) {
360
- const { cloudBaseUrl, sessionToken } = options;
361
- await fetchWithRetry(`${cloudBaseUrl}/auth/session/destroy`, {
362
- method: "POST",
363
- headers: {
364
- Authorization: `Bearer ${sessionToken}`
365
- }
366
- });
521
+ const { cloudBaseUrl, sessionToken } = options;
522
+ await fetchWithRetry(`${cloudBaseUrl}/auth/session/destroy`, {
523
+ method: "POST",
524
+ headers: { Authorization: `Bearer ${sessionToken}` }
525
+ });
367
526
  }
527
+ /**
528
+ * Get the logout URL for redirecting users.
529
+ *
530
+ * @param cloudBaseUrl - Cloud API base URL
531
+ * @param postLogoutRedirectUri - URL to redirect to after logout (required)
532
+ * @param idTokenHint - The access token (required by Cloud)
533
+ * @returns Full logout URL with redirect and token parameters
534
+ */
368
535
  function getLogoutUrl(cloudBaseUrl, postLogoutRedirectUri, idTokenHint) {
369
- const url = new URL("/auth/logout", cloudBaseUrl);
370
- url.searchParams.set("post_logout_redirect_uri", postLogoutRedirectUri);
371
- url.searchParams.set("id_token_hint", idTokenHint);
372
- return url.toString();
536
+ const url = new URL("/auth/logout", cloudBaseUrl);
537
+ url.searchParams.set("post_logout_redirect_uri", postLogoutRedirectUri);
538
+ url.searchParams.set("id_token_hint", idTokenHint);
539
+ return url.toString();
373
540
  }
374
-
375
- // src/client.ts
541
+ //#endregion
542
+ //#region src/client.ts
543
+ /**
544
+ * MastraCloudAuth client class.
545
+ * Facade composing OAuth and session modules into unified API.
546
+ */
547
+ /**
548
+ * Mastra Cloud authentication client.
549
+ *
550
+ * Provides unified API for OAuth flow and session management.
551
+ *
552
+ * @example
553
+ * ```typescript
554
+ * const auth = new MastraCloudAuth({
555
+ * cloudBaseUrl: 'https://cloud.mastra.ai',
556
+ * callbackUrl: 'https://myapp.com/auth/callback',
557
+ * });
558
+ *
559
+ * // Start login flow
560
+ * const { url, cookies } = auth.getLoginUrl({
561
+ * requestOrigin: 'https://myapp.com',
562
+ * });
563
+ *
564
+ * // After callback
565
+ * const result = await auth.handleCallback({
566
+ * code: 'auth_code',
567
+ * state: 'state_param',
568
+ * cookieHeader: request.headers.get('cookie'),
569
+ * });
570
+ * ```
571
+ */
376
572
  var MastraCloudAuth = class {
377
- config;
378
- constructor(config) {
379
- this.config = config;
380
- }
381
- /**
382
- * Generate login URL for OAuth authorization.
383
- *
384
- * @param options - Login options
385
- * @returns URL to redirect to and cookies to set
386
- */
387
- getLoginUrl(options) {
388
- return getLoginUrl({
389
- projectId: this.config.projectId,
390
- cloudBaseUrl: this.config.cloudBaseUrl,
391
- callbackUrl: this.config.callbackUrl,
392
- returnTo: options.returnTo,
393
- requestOrigin: options.requestOrigin,
394
- isProduction: this.config.isProduction
395
- });
396
- }
397
- /**
398
- * Handle OAuth callback after authorization.
399
- *
400
- * @param options - Callback parameters
401
- * @returns User info, tokens, and redirect URL
402
- */
403
- handleCallback(options) {
404
- return handleCallback({
405
- projectId: this.config.projectId,
406
- cloudBaseUrl: this.config.cloudBaseUrl,
407
- redirectUri: this.config.callbackUrl,
408
- ...options
409
- });
410
- }
411
- /**
412
- * Verify an access token.
413
- *
414
- * @param token - Access token to verify
415
- * @returns User and role information
416
- */
417
- verifyToken(token) {
418
- return verifyToken({ projectId: this.config.projectId, cloudBaseUrl: this.config.cloudBaseUrl, token });
419
- }
420
- /**
421
- * Validate an existing session.
422
- *
423
- * @param sessionToken - Session token to validate
424
- * @returns Session data if valid, null otherwise
425
- */
426
- validateSession(sessionToken) {
427
- return validateSession({ projectId: this.config.projectId, cloudBaseUrl: this.config.cloudBaseUrl, sessionToken });
428
- }
429
- /**
430
- * Destroy a session (server-side logout).
431
- *
432
- * @param sessionToken - Session token to destroy
433
- */
434
- destroySession(sessionToken) {
435
- return destroySession({ cloudBaseUrl: this.config.cloudBaseUrl, sessionToken });
436
- }
437
- /**
438
- * Get the logout URL for client-side redirect.
439
- *
440
- * @param postLogoutRedirectUri - URL to redirect to after logout
441
- * @param idTokenHint - The access token
442
- * @returns Full logout URL with redirect and token parameters
443
- */
444
- getLogoutUrl(postLogoutRedirectUri, idTokenHint) {
445
- return getLogoutUrl(this.config.cloudBaseUrl, postLogoutRedirectUri, idTokenHint);
446
- }
447
- /**
448
- * Create Set-Cookie header value for session token.
449
- *
450
- * @param token - Session token to store
451
- * @returns Set-Cookie header value
452
- */
453
- setSessionCookie(token) {
454
- return setSessionCookie(token, this.config.isProduction ?? process.env.NODE_ENV === "production");
455
- }
456
- /**
457
- * Create Set-Cookie header value to clear session cookie.
458
- *
459
- * @returns Set-Cookie header value
460
- */
461
- clearSessionCookie() {
462
- return clearSessionCookie();
463
- }
573
+ config;
574
+ constructor(config) {
575
+ this.config = config;
576
+ }
577
+ /**
578
+ * Generate login URL for OAuth authorization.
579
+ *
580
+ * @param options - Login options
581
+ * @returns URL to redirect to and cookies to set
582
+ */
583
+ getLoginUrl(options) {
584
+ return getLoginUrl({
585
+ projectId: this.config.projectId,
586
+ cloudBaseUrl: this.config.cloudBaseUrl,
587
+ callbackUrl: this.config.callbackUrl,
588
+ returnTo: options.returnTo,
589
+ requestOrigin: options.requestOrigin,
590
+ isProduction: this.config.isProduction
591
+ });
592
+ }
593
+ /**
594
+ * Handle OAuth callback after authorization.
595
+ *
596
+ * @param options - Callback parameters
597
+ * @returns User info, tokens, and redirect URL
598
+ */
599
+ handleCallback(options) {
600
+ return handleCallback({
601
+ projectId: this.config.projectId,
602
+ cloudBaseUrl: this.config.cloudBaseUrl,
603
+ redirectUri: this.config.callbackUrl,
604
+ ...options
605
+ });
606
+ }
607
+ /**
608
+ * Verify an access token.
609
+ *
610
+ * @param token - Access token to verify
611
+ * @returns User and role information
612
+ */
613
+ verifyToken(token) {
614
+ return verifyToken({
615
+ projectId: this.config.projectId,
616
+ cloudBaseUrl: this.config.cloudBaseUrl,
617
+ token
618
+ });
619
+ }
620
+ /**
621
+ * Validate an existing session.
622
+ *
623
+ * @param sessionToken - Session token to validate
624
+ * @returns Session data if valid, null otherwise
625
+ */
626
+ validateSession(sessionToken) {
627
+ return validateSession({
628
+ projectId: this.config.projectId,
629
+ cloudBaseUrl: this.config.cloudBaseUrl,
630
+ sessionToken
631
+ });
632
+ }
633
+ /**
634
+ * Destroy a session (server-side logout).
635
+ *
636
+ * @param sessionToken - Session token to destroy
637
+ */
638
+ destroySession(sessionToken) {
639
+ return destroySession({
640
+ projectId: this.config.projectId,
641
+ cloudBaseUrl: this.config.cloudBaseUrl,
642
+ sessionToken
643
+ });
644
+ }
645
+ /**
646
+ * Get the logout URL for client-side redirect.
647
+ *
648
+ * @param postLogoutRedirectUri - URL to redirect to after logout
649
+ * @param idTokenHint - The access token
650
+ * @returns Full logout URL with redirect and token parameters
651
+ */
652
+ getLogoutUrl(postLogoutRedirectUri, idTokenHint) {
653
+ return getLogoutUrl(this.config.cloudBaseUrl, postLogoutRedirectUri, idTokenHint);
654
+ }
655
+ /**
656
+ * Create Set-Cookie header value for session token.
657
+ *
658
+ * @param token - Session token to store
659
+ * @returns Set-Cookie header value
660
+ */
661
+ setSessionCookie(token) {
662
+ return setSessionCookie(token, this.config.isProduction ?? process.env.NODE_ENV === "production");
663
+ }
664
+ /**
665
+ * Create Set-Cookie header value to clear session cookie.
666
+ *
667
+ * @returns Set-Cookie header value
668
+ */
669
+ clearSessionCookie() {
670
+ return clearSessionCookie();
671
+ }
672
+ };
673
+ //#endregion
674
+ //#region ../../packages/_internals/auth/dist/types/index.js
675
+ function headerFromPlainObject(headers, name) {
676
+ const normalizedName = name.toLowerCase();
677
+ const matchingKey = Object.keys(headers).find((key) => key.toLowerCase() === normalizedName);
678
+ const value = matchingKey === void 0 ? void 0 : headers[matchingKey];
679
+ return Array.isArray(value) ? value[0] ?? null : value ?? null;
680
+ }
681
+ /**
682
+ * Read a request header across fetch, Hono, and Express-style request shapes.
683
+ * Must not throw when `headers` is a plain object (Express `IncomingHttpHeaders`).
684
+ */
685
+ function getRequestHeader(request, name) {
686
+ if (request instanceof Request) return request.headers.get(name);
687
+ if (request.raw instanceof Request) return request.raw.headers.get(name);
688
+ const headers = request.headers;
689
+ if (headers instanceof Headers) return headers.get(name);
690
+ if (typeof request.header === "function") return request.header(name) ?? null;
691
+ if (headers && typeof headers === "object") return headerFromPlainObject(headers, name);
692
+ return null;
693
+ }
694
+ //#endregion
695
+ //#region ../../packages/_internal-core/dist/logger/index.js
696
+ const RegisteredLogger = {
697
+ AGENT: "AGENT",
698
+ OBSERVABILITY: "OBSERVABILITY",
699
+ AUTH: "AUTH",
700
+ BROWSER: "BROWSER",
701
+ NETWORK: "NETWORK",
702
+ WORKFLOW: "WORKFLOW",
703
+ LLM: "LLM",
704
+ TTS: "TTS",
705
+ VOICE: "VOICE",
706
+ VECTOR: "VECTOR",
707
+ BUNDLER: "BUNDLER",
708
+ DEPLOYER: "DEPLOYER",
709
+ MEMORY: "MEMORY",
710
+ STORAGE: "STORAGE",
711
+ EMBEDDINGS: "EMBEDDINGS",
712
+ MCP_SERVER: "MCP_SERVER",
713
+ SERVER_CACHE: "SERVER_CACHE",
714
+ SERVER: "SERVER",
715
+ WORKSPACE: "WORKSPACE",
716
+ CHANNEL: "CHANNEL"
717
+ };
718
+ const LogLevel = {
719
+ DEBUG: "debug",
720
+ INFO: "info",
721
+ WARN: "warn",
722
+ ERROR: "error",
723
+ NONE: "silent"
464
724
  };
465
-
466
- // ../../packages/_internal-core/dist/chunk-3M4SEWMI.js
467
- var RegisteredLogger = {
468
- LLM: "LLM"};
469
- var LogLevel = {
470
- DEBUG: "debug",
471
- INFO: "info",
472
- WARN: "warn",
473
- ERROR: "error"};
474
725
  var MastraLogger = class {
475
- name;
476
- level;
477
- transports;
478
- constructor(options = {}) {
479
- this.name = options.name || "Mastra";
480
- this.level = options.level || LogLevel.ERROR;
481
- this.transports = new Map(Object.entries(options.transports || {}));
482
- }
483
- getTransports() {
484
- return this.transports;
485
- }
486
- trackException(_error, _metadata) {
487
- }
488
- async listLogs(transportId, params) {
489
- if (!transportId || !this.transports.has(transportId)) {
490
- return { logs: [], total: 0, page: params?.page ?? 1, perPage: params?.perPage ?? 100, hasMore: false };
491
- }
492
- return this.transports.get(transportId).listLogs?.(params) ?? {
493
- logs: [],
494
- total: 0,
495
- page: params?.page ?? 1,
496
- perPage: params?.perPage ?? 100,
497
- hasMore: false
498
- };
499
- }
500
- async listLogsByRunId({
501
- transportId,
502
- runId,
503
- fromDate,
504
- toDate,
505
- logLevel,
506
- filters,
507
- page,
508
- perPage
509
- }) {
510
- if (!transportId || !this.transports.has(transportId) || !runId) {
511
- return { logs: [], total: 0, page: page ?? 1, perPage: perPage ?? 100, hasMore: false };
512
- }
513
- return this.transports.get(transportId).listLogsByRunId?.({ runId, fromDate, toDate, logLevel, filters, page, perPage }) ?? {
514
- logs: [],
515
- total: 0,
516
- page: page ?? 1,
517
- perPage: perPage ?? 100,
518
- hasMore: false
519
- };
520
- }
726
+ name;
727
+ level;
728
+ transports;
729
+ constructor(options = {}) {
730
+ this.name = options.name || "Mastra";
731
+ this.level = options.level || LogLevel.ERROR;
732
+ this.transports = new Map(Object.entries(options.transports || {}));
733
+ }
734
+ getTransports() {
735
+ return this.transports;
736
+ }
737
+ trackException(_error, _metadata) {}
738
+ async listLogs(transportId, params) {
739
+ if (!transportId || !this.transports.has(transportId)) return {
740
+ logs: [],
741
+ total: 0,
742
+ page: params?.page ?? 1,
743
+ perPage: params?.perPage ?? 100,
744
+ hasMore: false
745
+ };
746
+ return this.transports.get(transportId).listLogs?.(params) ?? {
747
+ logs: [],
748
+ total: 0,
749
+ page: params?.page ?? 1,
750
+ perPage: params?.perPage ?? 100,
751
+ hasMore: false
752
+ };
753
+ }
754
+ async listLogsByRunId({ transportId, runId, fromDate, toDate, logLevel, filters, page, perPage }) {
755
+ if (!transportId || !this.transports.has(transportId) || !runId) return {
756
+ logs: [],
757
+ total: 0,
758
+ page: page ?? 1,
759
+ perPage: perPage ?? 100,
760
+ hasMore: false
761
+ };
762
+ return this.transports.get(transportId).listLogsByRunId?.({
763
+ runId,
764
+ fromDate,
765
+ toDate,
766
+ logLevel,
767
+ filters,
768
+ page,
769
+ perPage
770
+ }) ?? {
771
+ logs: [],
772
+ total: 0,
773
+ page: page ?? 1,
774
+ perPage: perPage ?? 100,
775
+ hasMore: false
776
+ };
777
+ }
521
778
  };
522
- var ConsoleLogger = class _ConsoleLogger extends MastraLogger {
523
- component;
524
- filter;
525
- constructor(options = {}) {
526
- super(options);
527
- this.component = options.component;
528
- this.filter = options.filter;
529
- }
530
- child(componentOrBindings) {
531
- const component = typeof componentOrBindings === "string" ? componentOrBindings : componentOrBindings?.component ?? this.component;
532
- return new _ConsoleLogger({
533
- name: this.name,
534
- level: this.level,
535
- component,
536
- filter: this.filter
537
- });
538
- }
539
- shouldLog(level, message, args) {
540
- if (!this.filter) return true;
541
- try {
542
- return this.filter({ component: this.component, level, message, args });
543
- } catch (e) {
544
- console.error(`[Logger] Filter error for component=${this.component} level=${level}:`, e);
545
- return true;
546
- }
547
- }
548
- prefix() {
549
- return this.component ? `[${this.component}] ` : "";
550
- }
551
- debug(message, ...args) {
552
- if (this.level === LogLevel.DEBUG && this.shouldLog(LogLevel.DEBUG, message, args)) {
553
- console.info(`${this.prefix()}${message}`, ...args);
554
- }
555
- }
556
- info(message, ...args) {
557
- if ((this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.INFO, message, args)) {
558
- console.info(`${this.prefix()}${message}`, ...args);
559
- }
560
- }
561
- warn(message, ...args) {
562
- if ((this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.WARN, message, args)) {
563
- console.warn(`${this.prefix()}${message}`, ...args);
564
- }
565
- }
566
- error(message, ...args) {
567
- if ((this.level === LogLevel.ERROR || this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.ERROR, message, args)) {
568
- console.error(`${this.prefix()}${message}`, ...args);
569
- }
570
- }
571
- async listLogs(_transportId, _params) {
572
- return { logs: [], total: 0, page: _params?.page ?? 1, perPage: _params?.perPage ?? 100, hasMore: false };
573
- }
574
- async listLogsByRunId(_args) {
575
- return { logs: [], total: 0, page: _args.page ?? 1, perPage: _args.perPage ?? 100, hasMore: false };
576
- }
779
+ var ConsoleLogger = class ConsoleLogger extends MastraLogger {
780
+ component;
781
+ filter;
782
+ constructor(options = {}) {
783
+ super(options);
784
+ this.component = options.component;
785
+ this.filter = options.filter;
786
+ }
787
+ child(componentOrBindings) {
788
+ const component = typeof componentOrBindings === "string" ? componentOrBindings : componentOrBindings?.component ?? this.component;
789
+ return new ConsoleLogger({
790
+ name: this.name,
791
+ level: this.level,
792
+ component,
793
+ filter: this.filter
794
+ });
795
+ }
796
+ shouldLog(level, message, args) {
797
+ if (!this.filter) return true;
798
+ try {
799
+ return this.filter({
800
+ component: this.component,
801
+ level,
802
+ message,
803
+ args
804
+ });
805
+ } catch (e) {
806
+ console.error(`[Logger] Filter error for component=${this.component} level=${level}:`, e);
807
+ return true;
808
+ }
809
+ }
810
+ prefix() {
811
+ return this.component ? `[${this.component}] ` : "";
812
+ }
813
+ debug(message, ...args) {
814
+ if (this.level === LogLevel.DEBUG && this.shouldLog(LogLevel.DEBUG, message, args)) console.info(`${this.prefix()}${message}`, ...args);
815
+ }
816
+ info(message, ...args) {
817
+ if ((this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.INFO, message, args)) console.info(`${this.prefix()}${message}`, ...args);
818
+ }
819
+ warn(message, ...args) {
820
+ 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);
821
+ }
822
+ error(message, ...args) {
823
+ 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);
824
+ }
825
+ async listLogs(_transportId, _params) {
826
+ return {
827
+ logs: [],
828
+ total: 0,
829
+ page: _params?.page ?? 1,
830
+ perPage: _params?.perPage ?? 100,
831
+ hasMore: false
832
+ };
833
+ }
834
+ async listLogsByRunId(_args) {
835
+ return {
836
+ logs: [],
837
+ total: 0,
838
+ page: _args.page ?? 1,
839
+ perPage: _args.perPage ?? 100,
840
+ hasMore: false
841
+ };
842
+ }
577
843
  };
578
-
579
- // ../../packages/_internal-core/dist/base/index.js
844
+ //#endregion
845
+ //#region ../../packages/_internal-core/dist/base/index.js
580
846
  var MastraBase = class {
581
- component = RegisteredLogger.LLM;
582
- logger;
583
- name;
584
- #rawConfig;
585
- constructor({
586
- component,
587
- name,
588
- rawConfig
589
- }) {
590
- this.component = component || RegisteredLogger.LLM;
591
- this.name = name;
592
- this.#rawConfig = rawConfig;
593
- this.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });
594
- }
595
- /**
596
- * Returns the raw storage configuration this primitive was created from,
597
- * or undefined if it was created from code.
598
- */
599
- toRawConfig() {
600
- return this.#rawConfig;
601
- }
602
- /**
603
- * Sets the raw storage configuration for this primitive.
604
- * @internal
605
- */
606
- __setRawConfig(rawConfig) {
607
- this.#rawConfig = rawConfig;
608
- }
609
- /**
610
- * Set the logger for the agent
611
- * @param logger
612
- */
613
- __setLogger(logger) {
614
- this.logger = "child" in logger && typeof logger.child === "function" ? logger.child({ component: this.component }) : logger;
615
- }
847
+ component = RegisteredLogger.LLM;
848
+ logger;
849
+ name;
850
+ #rawConfig;
851
+ constructor({ component, name, rawConfig }) {
852
+ this.component = component || RegisteredLogger.LLM;
853
+ this.name = name;
854
+ this.#rawConfig = rawConfig;
855
+ this.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });
856
+ }
857
+ /**
858
+ * Returns the raw storage configuration this primitive was created from,
859
+ * or undefined if it was created from code.
860
+ */
861
+ toRawConfig() {
862
+ return this.#rawConfig;
863
+ }
864
+ /**
865
+ * Sets the raw storage configuration for this primitive.
866
+ * @internal
867
+ */
868
+ __setRawConfig(rawConfig) {
869
+ this.#rawConfig = rawConfig;
870
+ }
871
+ /**
872
+ * Set the logger for the agent
873
+ * @param logger
874
+ */
875
+ __setLogger(logger) {
876
+ this.logger = "child" in logger && typeof logger.child === "function" ? logger.child({ component: this.component }) : logger;
877
+ }
616
878
  };
617
-
618
- // ../../packages/_internals/auth/dist/chunk-NJOKT6V5.js
879
+ //#endregion
880
+ //#region ../../packages/_internals/auth/dist/provider/index.js
619
881
  var MastraAuthProvider = class extends MastraBase {
620
- protected;
621
- public;
622
- constructor(options) {
623
- super({ component: "AUTH", name: options?.name });
624
- if (options?.authorizeUser) {
625
- this.authorizeUser = options.authorizeUser.bind(this);
626
- }
627
- this.protected = options?.protected;
628
- this.public = options?.public;
629
- this.mapUserToResourceId = options?.mapUserToResourceId;
630
- }
631
- registerOptions(opts) {
632
- if (opts?.authorizeUser) {
633
- this.authorizeUser = opts.authorizeUser.bind(this);
634
- }
635
- if (opts?.mapUserToResourceId) {
636
- this.mapUserToResourceId = opts.mapUserToResourceId;
637
- }
638
- if (opts?.protected) {
639
- this.protected = opts.protected;
640
- }
641
- if (opts?.public) {
642
- this.public = opts.public;
643
- }
644
- }
645
- };
646
-
647
- // src/auth-provider.ts
648
- function getRequestHeader2(request, name) {
649
- if (request instanceof Request) {
650
- return request.headers.get(name);
651
- }
652
- return request.raw?.headers.get(name) ?? request.headers?.get(name) ?? request.header(name) ?? null;
653
- }
654
- var MastraCloudAuthProvider = class extends MastraAuthProvider {
655
- client;
656
- /** Marker for EE license exemption - MastraCloudAuth is exempt */
657
- isMastraCloudAuth = true;
658
- /**
659
- * Cookie header for handleCallback PKCE validation.
660
- * Set via setCallbackCookieHeader() before handleCallback() is called.
661
- * @internal
662
- */
663
- _lastCallbackCookieHeader = null;
664
- constructor(options) {
665
- super({ name: options?.name ?? "cloud" });
666
- this.client = new MastraCloudAuth({
667
- projectId: options.projectId,
668
- cloudBaseUrl: options.cloudBaseUrl,
669
- callbackUrl: options.callbackUrl,
670
- isProduction: options.isProduction
671
- });
672
- this.registerOptions(options);
673
- }
674
- /**
675
- * Set cookie header for handleCallback PKCE validation.
676
- * Must be called before handleCallback() to pass cookie header.
677
- *
678
- * @param cookieHeader - Cookie header from original request
679
- */
680
- setCallbackCookieHeader(cookieHeader) {
681
- this._lastCallbackCookieHeader = cookieHeader;
682
- }
683
- // ============================================================================
684
- // MastraAuthProvider Implementation
685
- // ============================================================================
686
- /**
687
- * Authenticate a bearer token or session cookie.
688
- *
689
- * Checks session cookie first, falls back to bearer token for API clients.
690
- *
691
- * @param token - Bearer token (from Authorization header)
692
- * @param request - Request used for cookie access
693
- * @returns Authenticated user with role, or null if invalid
694
- */
695
- async authenticateToken(token, request) {
696
- try {
697
- const cookieHeader = getRequestHeader2(request, "cookie");
698
- const sessionToken = parseSessionCookie(cookieHeader);
699
- if (sessionToken) {
700
- const { user, role } = await this.client.verifyToken(sessionToken);
701
- return { ...user, role };
702
- }
703
- if (token) {
704
- const { user, role } = await this.client.verifyToken(token);
705
- return { ...user, role };
706
- }
707
- return null;
708
- } catch {
709
- return null;
710
- }
711
- }
712
- /**
713
- * Authorize a user for access.
714
- *
715
- * Simple validation - detailed permission checking happens in server
716
- * middleware via checkRoutePermission(), not authorizeUser().
717
- *
718
- * @param user - Authenticated user
719
- * @returns True if user has valid id
720
- */
721
- authorizeUser(user) {
722
- return !!user?.id;
723
- }
724
- // ============================================================================
725
- // ISSOProvider Implementation
726
- // ============================================================================
727
- /**
728
- * Cached login results for getLoginCookies() to retrieve cookies.
729
- * Keyed by the OAuth state parameter to prevent race conditions.
730
- * @internal
731
- */
732
- _loginResults = /* @__PURE__ */ new Map();
733
- /**
734
- * Get URL to redirect user to for SSO login.
735
- *
736
- * @param redirectUri - Callback URL after authentication
737
- * @param state - State parameter (format: uuid|encodedPostLoginRedirect)
738
- * @returns Full authorization URL
739
- */
740
- getLoginUrl(redirectUri, state) {
741
- let postLoginRedirect = "/";
742
- if (state && state.includes("|")) {
743
- const parts = state.split("|", 2);
744
- const encodedRedirect = parts[1];
745
- if (encodedRedirect) {
746
- try {
747
- postLoginRedirect = decodeURIComponent(encodedRedirect);
748
- } catch {
749
- postLoginRedirect = "/";
750
- }
751
- }
752
- }
753
- const redirectUrl = new URL(redirectUri);
754
- const origin = redirectUrl.origin;
755
- const result = this.client.getLoginUrl({
756
- returnTo: postLoginRedirect,
757
- requestOrigin: origin
758
- });
759
- if (this._loginResults.size > 100) {
760
- const firstKey = this._loginResults.keys().next().value;
761
- if (firstKey) this._loginResults.delete(firstKey);
762
- }
763
- this._loginResults.set(state, result);
764
- return result.url;
765
- }
766
- /**
767
- * Get cookies to set during login redirect (PKCE verifier).
768
- * Must be called after getLoginUrl() in same request.
769
- *
770
- * @param _redirectUri - OAuth callback URL
771
- * @param state - State parameter
772
- * @returns Array of Set-Cookie header values
773
- */
774
- getLoginCookies(_redirectUri, state) {
775
- const result = this._loginResults.get(state);
776
- if (result) {
777
- this._loginResults.delete(state);
778
- return result.cookies;
779
- }
780
- return void 0;
781
- }
782
- /**
783
- * Handle OAuth callback, exchange code for tokens and user.
784
- *
785
- * @param code - Authorization code from callback
786
- * @param state - State parameter for CSRF validation
787
- * @returns User, tokens, and session cookies
788
- */
789
- async handleCallback(code, state) {
790
- const cookieHeader = this._lastCallbackCookieHeader;
791
- this._lastCallbackCookieHeader = null;
792
- const result = await this.client.handleCallback({
793
- code,
794
- state,
795
- cookieHeader
796
- });
797
- const sessionCookie = this.client.setSessionCookie(result.accessToken);
798
- return {
799
- user: result.user,
800
- // Already has role from handleCallback
801
- tokens: {
802
- accessToken: result.accessToken
803
- },
804
- cookies: [...result.cookies, sessionCookie]
805
- };
806
- }
807
- /**
808
- * Get configuration for rendering login button in UI.
809
- *
810
- * @returns Login button configuration
811
- */
812
- getLoginButtonConfig() {
813
- return {
814
- provider: "mastra",
815
- text: "Sign in with Mastra Cloud"
816
- };
817
- }
818
- /**
819
- * Get logout URL for client-side redirect.
820
- * Requires the request to extract the session token for id_token_hint.
821
- *
822
- * @param redirectUri - URL to redirect to after logout
823
- * @param request - Request to extract session token from
824
- * @returns Logout URL with redirect and token parameters, or null if no session
825
- */
826
- getLogoutUrl(redirectUri, request) {
827
- const sessionToken = request ? this.getSessionIdFromRequest(request) : null;
828
- if (!sessionToken) {
829
- return null;
830
- }
831
- return this.client.getLogoutUrl(redirectUri, sessionToken);
832
- }
833
- // ============================================================================
834
- // ISessionProvider Implementation
835
- // ============================================================================
836
- /**
837
- * Create a new session for a user.
838
- *
839
- * For Cloud auth, sessions are created via handleCallback.
840
- * This method builds a Session object for interface compatibility.
841
- *
842
- * @param userId - User to create session for
843
- * @param metadata - Optional metadata (accessToken can be passed here)
844
- * @returns Session object
845
- */
846
- async createSession(userId, metadata) {
847
- const now = /* @__PURE__ */ new Date();
848
- const expiresAt = new Date(now.getTime() + 24 * 60 * 60 * 1e3);
849
- return {
850
- id: metadata?.accessToken ?? crypto.randomUUID(),
851
- userId,
852
- createdAt: now,
853
- expiresAt,
854
- metadata
855
- };
856
- }
857
- /**
858
- * Validate a session and return it if valid.
859
- *
860
- * @param sessionId - Session token to validate
861
- * @returns Session object or null if invalid/expired
862
- */
863
- async validateSession(sessionId) {
864
- const session = await this.client.validateSession(sessionId);
865
- if (!session) return null;
866
- return {
867
- id: sessionId,
868
- userId: session.userId,
869
- createdAt: new Date(session.createdAt),
870
- expiresAt: new Date(session.expiresAt)
871
- };
872
- }
873
- /**
874
- * Destroy a session (logout).
875
- *
876
- * @param sessionId - Session token to destroy
877
- */
878
- async destroySession(sessionId) {
879
- await this.client.destroySession(sessionId);
880
- }
881
- /**
882
- * Refresh a session, extending its expiry.
883
- * Cloud handles refresh internally, so just validate.
884
- *
885
- * @param sessionId - Session token to refresh
886
- * @returns Session object or null if invalid
887
- */
888
- async refreshSession(sessionId) {
889
- return this.validateSession(sessionId);
890
- }
891
- /**
892
- * Extract session ID from an incoming request.
893
- *
894
- * @param request - Incoming HTTP request
895
- * @returns Session token or null if not present
896
- */
897
- getSessionIdFromRequest(request) {
898
- return parseSessionCookie(request.headers.get("cookie"));
899
- }
900
- /**
901
- * Create response headers to set session cookie.
902
- *
903
- * @param session - Session to encode (id is the access token)
904
- * @returns Headers object with Set-Cookie
905
- */
906
- getSessionHeaders(session) {
907
- return { "Set-Cookie": this.client.setSessionCookie(session.id) };
908
- }
909
- /**
910
- * Create response headers to clear session (for logout).
911
- *
912
- * @returns Headers object to clear session cookie
913
- */
914
- getClearSessionHeaders() {
915
- return { "Set-Cookie": this.client.clearSessionCookie() };
916
- }
917
- // ============================================================================
918
- // IUserProvider Implementation
919
- // ============================================================================
920
- /**
921
- * Get current user from request (session cookie).
922
- *
923
- * @param request - Incoming HTTP request
924
- * @returns User with role or null if not authenticated
925
- */
926
- async getCurrentUser(request) {
927
- const sessionToken = this.getSessionIdFromRequest(request);
928
- if (!sessionToken) return null;
929
- try {
930
- const { user, role } = await this.client.verifyToken(sessionToken);
931
- return { ...user, role };
932
- } catch {
933
- return null;
934
- }
935
- }
936
- /**
937
- * Get user by ID.
938
- * Cloud API doesn't have a /users/:id endpoint.
939
- *
940
- * @returns Always null (not supported)
941
- */
942
- async getUser(_userId) {
943
- return null;
944
- }
945
- };
946
-
947
- // ../../packages/_internals/auth/dist/chunk-LZCWL5CT.js
948
- var RESOURCE_EXPANSIONS = {
949
- stored: [
950
- "stored-agents",
951
- "stored-mcp-clients",
952
- "stored-prompt-blocks",
953
- "stored-scorers",
954
- "stored-skills",
955
- "stored-workspaces"
956
- ]
882
+ protected;
883
+ public;
884
+ constructor(options) {
885
+ super({
886
+ component: "AUTH",
887
+ name: options?.name
888
+ });
889
+ if (options?.authorizeUser) this.authorizeUser = options.authorizeUser.bind(this);
890
+ this.protected = options?.protected;
891
+ this.public = options?.public;
892
+ this.mapUserToResourceId = options?.mapUserToResourceId;
893
+ }
894
+ registerOptions(opts) {
895
+ if (opts?.authorizeUser) this.authorizeUser = opts.authorizeUser.bind(this);
896
+ if (opts?.mapUserToResourceId) this.mapUserToResourceId = opts.mapUserToResourceId;
897
+ if (opts?.protected) this.protected = opts.protected;
898
+ if (opts?.public) this.public = opts.public;
899
+ }
957
900
  };
901
+ //#endregion
902
+ //#region ../../packages/_internals/auth/dist/ee-DXvSoTl7.js
903
+ /**
904
+ * FGA enforcement utility for checking fine-grained authorization.
905
+ *
906
+ * @license Mastra Enterprise License - see ee/LICENSE
907
+ */
908
+ /**
909
+ * Compound resource keys that expand to a set of per-family resources.
910
+ * A granted `stored:<action>` is treated as matching any `stored-<family>:<action>`
911
+ * (and `stored:*` matches any `stored-<family>:*`).
912
+ */
913
+ const RESOURCE_EXPANSIONS = { stored: [
914
+ "stored-agents",
915
+ "stored-mcp-clients",
916
+ "stored-prompt-blocks",
917
+ "stored-scorers",
918
+ "stored-skills",
919
+ "stored-workspaces"
920
+ ] };
921
+ /**
922
+ * Check if a permission matches (including wildcard support).
923
+ *
924
+ * Permission format: `{resource}:{action}[:{resource-id}]`
925
+ *
926
+ * Examples:
927
+ * - `*` matches everything
928
+ * - `agents:*` matches `agents:read`, `agents:read:my-agent`
929
+ * - `*:read` matches `agents:read`, `workflows:read` (action across all resources)
930
+ * - `agents:read` matches `agents:read`, `agents:read:my-agent`
931
+ * - `agents:read:my-agent` matches only `agents:read:my-agent`
932
+ * - `agents:*:my-agent` matches `agents:read:my-agent`, `agents:write:my-agent`
933
+ *
934
+ * @param userPermission - Permission the user has
935
+ * @param requiredPermission - Permission being checked
936
+ * @returns True if permission matches
937
+ */
958
938
  function matchesPermission(userPermission, requiredPermission) {
959
- if (userPermission === "*") {
960
- return true;
961
- }
962
- const grantedParts = userPermission.split(":");
963
- const requiredParts = requiredPermission.split(":");
964
- const expandedFamilies = RESOURCE_EXPANSIONS[grantedParts[0] ?? ""];
965
- if (expandedFamilies && expandedFamilies.includes(requiredParts[0] ?? "")) {
966
- const aliased = [requiredParts[0], ...grantedParts.slice(1)].join(":");
967
- return matchesPermission(aliased, requiredPermission);
968
- }
969
- if (grantedParts.length < 2 || requiredParts.length < 2) {
970
- return userPermission === requiredPermission;
971
- }
972
- const [grantedResource, grantedAction, grantedId] = grantedParts;
973
- const [requiredResource, requiredAction, requiredId] = requiredParts;
974
- if (grantedResource === "*") {
975
- if (grantedAction === "*") {
976
- if (grantedId === void 0) {
977
- return true;
978
- }
979
- return grantedId === requiredId;
980
- }
981
- if (grantedAction !== requiredAction) {
982
- return false;
983
- }
984
- if (grantedId === void 0) {
985
- return true;
986
- }
987
- return grantedId === requiredId;
988
- }
989
- if (grantedResource !== requiredResource) {
990
- return false;
991
- }
992
- if (grantedAction === "*") {
993
- if (grantedId === void 0) {
994
- return true;
995
- }
996
- return grantedId === requiredId;
997
- }
998
- if (grantedAction !== requiredAction) {
999
- return false;
1000
- }
1001
- if (grantedId === void 0) {
1002
- return true;
1003
- }
1004
- return grantedId === requiredId;
939
+ if (userPermission === "*") return true;
940
+ const grantedParts = userPermission.split(":");
941
+ const requiredParts = requiredPermission.split(":");
942
+ const expandedFamilies = RESOURCE_EXPANSIONS[grantedParts[0] ?? ""];
943
+ if (expandedFamilies && expandedFamilies.includes(requiredParts[0] ?? "")) return matchesPermission([requiredParts[0], ...grantedParts.slice(1)].join(":"), requiredPermission);
944
+ if (grantedParts.length < 2 || requiredParts.length < 2) return userPermission === requiredPermission;
945
+ const [grantedResource, grantedAction, grantedId] = grantedParts;
946
+ const [requiredResource, requiredAction, requiredId] = requiredParts;
947
+ if (grantedResource === "*") {
948
+ if (grantedAction === "*") {
949
+ if (grantedId === void 0) return true;
950
+ return grantedId === requiredId;
951
+ }
952
+ if (grantedAction !== requiredAction) return false;
953
+ if (grantedId === void 0) return true;
954
+ return grantedId === requiredId;
955
+ }
956
+ if (grantedResource !== requiredResource) return false;
957
+ if (grantedAction === "*") {
958
+ if (grantedId === void 0) return true;
959
+ return grantedId === requiredId;
960
+ }
961
+ if (grantedAction !== requiredAction) return false;
962
+ if (grantedId === void 0) return true;
963
+ return grantedId === requiredId;
1005
964
  }
965
+ /**
966
+ * Resolve permissions from user roles using a role mapping.
967
+ *
968
+ * This function translates provider-defined roles (from WorkOS, Okta, etc.)
969
+ * to Mastra permissions using a configurable mapping.
970
+ *
971
+ * @example
972
+ * ```typescript
973
+ * const roleMapping = {
974
+ * "Engineering": ["agents:*", "workflows:*"],
975
+ * "Product": ["agents:read"],
976
+ * "_default": [],
977
+ * };
978
+ *
979
+ * // User has "Engineering" and "QA" roles
980
+ * const permissions = resolvePermissionsFromMapping(
981
+ * ["Engineering", "QA"],
982
+ * roleMapping
983
+ * );
984
+ * // Result: ["agents:*", "workflows:*"] (QA is unmapped, gets _default)
985
+ * ```
986
+ *
987
+ * @param roles - User's roles from the identity provider
988
+ * @param mapping - Role to permission mapping
989
+ * @returns Array of resolved permissions
990
+ */
1006
991
  function resolvePermissionsFromMapping(roles, mapping) {
1007
- const permissions = /* @__PURE__ */ new Set();
1008
- const defaultPerms = mapping["_default"] ?? [];
1009
- for (const role of roles) {
1010
- const rolePerms = mapping[role];
1011
- if (rolePerms) {
1012
- for (const perm of rolePerms) {
1013
- permissions.add(perm);
1014
- }
1015
- } else {
1016
- for (const perm of defaultPerms) {
1017
- permissions.add(perm);
1018
- }
1019
- }
1020
- }
1021
- return Array.from(permissions);
992
+ const permissions = /* @__PURE__ */ new Set();
993
+ const defaultPerms = mapping["_default"] ?? [];
994
+ for (const role of roles) {
995
+ const rolePerms = mapping[role];
996
+ if (rolePerms) for (const perm of rolePerms) permissions.add(perm);
997
+ else for (const perm of defaultPerms) permissions.add(perm);
998
+ }
999
+ return Array.from(permissions);
1022
1000
  }
1023
-
1024
- // src/rbac/rbac-provider.ts
1025
- var MastraRBACCloud = class {
1026
- options;
1027
- /**
1028
- * Expose roleMapping for middleware access.
1029
- * This allows the authorization middleware to resolve permissions
1030
- * without needing to call the async methods.
1031
- */
1032
- get roleMapping() {
1033
- return this.options.roleMapping;
1034
- }
1035
- /**
1036
- * Create a new Mastra Cloud RBAC provider.
1037
- *
1038
- * @param options - RBAC configuration options
1039
- */
1040
- constructor(options) {
1041
- this.options = options;
1042
- }
1043
- /**
1044
- * Get all roles for a user.
1045
- *
1046
- * Returns the user's role as a single-element array, or empty array if no role.
1047
- * Cloud uses a single-role model (role is attached via verifyToken()).
1048
- *
1049
- * @param user - Cloud user to get roles for
1050
- * @returns Array containing user's role, or empty array
1051
- */
1052
- async getRoles(user) {
1053
- return user.role ? [user.role] : [];
1054
- }
1055
- /**
1056
- * Check if a user has a specific role.
1057
- *
1058
- * @param user - Cloud user to check
1059
- * @param role - Role name to check for
1060
- * @returns True if user has the role
1061
- */
1062
- async hasRole(user, role) {
1063
- const roles = await this.getRoles(user);
1064
- return roles.includes(role);
1065
- }
1066
- /**
1067
- * Get all permissions for a user by mapping their role.
1068
- *
1069
- * Uses the configured roleMapping to translate the user's role
1070
- * into Mastra permission strings.
1071
- *
1072
- * If the user has no role, the _default permissions from the
1073
- * role mapping are applied.
1074
- *
1075
- * @param user - Cloud user to get permissions for
1076
- * @returns Array of permission strings
1077
- */
1078
- async getPermissions(user) {
1079
- const roles = await this.getRoles(user);
1080
- if (roles.length === 0) {
1081
- return this.options.roleMapping["_default"] ?? [];
1082
- }
1083
- return resolvePermissionsFromMapping(roles, this.options.roleMapping);
1084
- }
1085
- /**
1086
- * Check if a user has a specific permission.
1087
- *
1088
- * Uses wildcard matching to check if the user's permissions
1089
- * grant access to the required permission.
1090
- *
1091
- * @param user - Cloud user to check
1092
- * @param permission - Permission to check for (e.g., 'agents:read')
1093
- * @returns True if user has the permission
1094
- */
1095
- async hasPermission(user, permission) {
1096
- const permissions = await this.getPermissions(user);
1097
- return permissions.some((p) => matchesPermission(p, permission));
1098
- }
1099
- /**
1100
- * Check if a user has ALL of the specified permissions.
1101
- *
1102
- * @param user - Cloud user to check
1103
- * @param permissions - Array of permissions to check for
1104
- * @returns True if user has all permissions
1105
- */
1106
- async hasAllPermissions(user, permissions) {
1107
- const userPermissions = await this.getPermissions(user);
1108
- return permissions.every((required) => userPermissions.some((p) => matchesPermission(p, required)));
1109
- }
1110
- /**
1111
- * Check if a user has ANY of the specified permissions.
1112
- *
1113
- * @param user - Cloud user to check
1114
- * @param permissions - Array of permissions to check for
1115
- * @returns True if user has at least one permission
1116
- */
1117
- async hasAnyPermission(user, permissions) {
1118
- const userPermissions = await this.getPermissions(user);
1119
- return permissions.some((required) => userPermissions.some((p) => matchesPermission(p, required)));
1120
- }
1121
- };
1122
1001
  /**
1123
- * EE Authentication Interfaces
1124
- *
1125
- * Enterprise interfaces for RBAC, ACL, and advanced authorization.
1126
- *
1127
- * @license Mastra Enterprise License - see ee/LICENSE
1128
- * @packageDocumentation
1129
- */
1002
+ * @mastra/core/auth/ee
1003
+ *
1004
+ * Enterprise authentication capabilities for Mastra.
1005
+ * This code is licensed under the Mastra Enterprise License - see ee/LICENSE.
1006
+ *
1007
+ * @license Mastra Enterprise License - see ee/LICENSE
1008
+ * @packageDocumentation
1009
+ */
1010
+ //#endregion
1011
+ //#region src/auth-provider.ts
1130
1012
  /**
1131
- * FGA enforcement utility for checking fine-grained authorization.
1132
- *
1133
- * @license Mastra Enterprise License - see ee/LICENSE
1134
- */
1135
- /**
1136
- * RBAC provider implementations.
1137
- *
1138
- * @license Mastra Enterprise License - see ee/LICENSE
1139
- */
1140
- /**
1141
- * Default implementations for EE authentication.
1142
- *
1143
- * @license Mastra Enterprise License - see ee/LICENSE
1144
- */
1013
+ * Mastra Cloud authentication provider for server integration.
1014
+ *
1015
+ * Wraps the MastraCloudAuth client and implements the required interfaces
1016
+ * for Mastra server middleware. Provides SSO login, session management,
1017
+ * and user awareness.
1018
+ *
1019
+ * @example
1020
+ * ```typescript
1021
+ * import { MastraCloudAuthProvider } from '@mastra/auth-cloud';
1022
+ *
1023
+ * const auth = new MastraCloudAuthProvider({
1024
+ * cloudBaseUrl: 'https://cloud.mastra.ai',
1025
+ * callbackUrl: 'https://myapp.com/auth/callback',
1026
+ * });
1027
+ *
1028
+ * const mastra = new Mastra({
1029
+ * auth,
1030
+ * // ...
1031
+ * });
1032
+ * ```
1033
+ */
1034
+ var MastraCloudAuthProvider = class extends MastraAuthProvider {
1035
+ client;
1036
+ /** Marker for EE license exemption - MastraCloudAuth is exempt */
1037
+ isMastraCloudAuth = true;
1038
+ /**
1039
+ * Cookie header for handleCallback PKCE validation.
1040
+ * Set via setCallbackCookieHeader() before handleCallback() is called.
1041
+ * @internal
1042
+ */
1043
+ _lastCallbackCookieHeader = null;
1044
+ constructor(options) {
1045
+ super({ name: options?.name ?? "cloud" });
1046
+ this.client = new MastraCloudAuth({
1047
+ projectId: options.projectId,
1048
+ cloudBaseUrl: options.cloudBaseUrl,
1049
+ callbackUrl: options.callbackUrl,
1050
+ isProduction: options.isProduction
1051
+ });
1052
+ this.registerOptions(options);
1053
+ }
1054
+ /**
1055
+ * Set cookie header for handleCallback PKCE validation.
1056
+ * Must be called before handleCallback() to pass cookie header.
1057
+ *
1058
+ * @param cookieHeader - Cookie header from original request
1059
+ */
1060
+ setCallbackCookieHeader(cookieHeader) {
1061
+ this._lastCallbackCookieHeader = cookieHeader;
1062
+ }
1063
+ /**
1064
+ * Authenticate a bearer token or session cookie.
1065
+ *
1066
+ * Checks session cookie first, falls back to bearer token for API clients.
1067
+ *
1068
+ * @param token - Bearer token (from Authorization header)
1069
+ * @param request - Request used for cookie access
1070
+ * @returns Authenticated user with role, or null if invalid
1071
+ */
1072
+ async authenticateToken(token, request) {
1073
+ try {
1074
+ const sessionToken = parseSessionCookie(getRequestHeader(request, "cookie"));
1075
+ if (sessionToken) {
1076
+ const { user, role } = await this.client.verifyToken(sessionToken);
1077
+ return {
1078
+ ...user,
1079
+ role
1080
+ };
1081
+ }
1082
+ if (token) {
1083
+ const { user, role } = await this.client.verifyToken(token);
1084
+ return {
1085
+ ...user,
1086
+ role
1087
+ };
1088
+ }
1089
+ return null;
1090
+ } catch {
1091
+ return null;
1092
+ }
1093
+ }
1094
+ /**
1095
+ * Authorize a user for access.
1096
+ *
1097
+ * Simple validation - detailed permission checking happens in server
1098
+ * middleware via checkRoutePermission(), not authorizeUser().
1099
+ *
1100
+ * @param user - Authenticated user
1101
+ * @returns True if user has valid id
1102
+ */
1103
+ authorizeUser(user) {
1104
+ return !!user?.id;
1105
+ }
1106
+ /**
1107
+ * Cached login results for getLoginCookies() to retrieve cookies.
1108
+ * Keyed by the OAuth state parameter to prevent race conditions.
1109
+ * @internal
1110
+ */
1111
+ _loginResults = /* @__PURE__ */ new Map();
1112
+ /**
1113
+ * Get URL to redirect user to for SSO login.
1114
+ *
1115
+ * @param redirectUri - Callback URL after authentication
1116
+ * @param state - State parameter (format: uuid|encodedPostLoginRedirect)
1117
+ * @returns Full authorization URL
1118
+ */
1119
+ getLoginUrl(redirectUri, state) {
1120
+ let postLoginRedirect = "/";
1121
+ if (state && state.includes("|")) {
1122
+ const encodedRedirect = state.split("|", 2)[1];
1123
+ if (encodedRedirect) try {
1124
+ postLoginRedirect = decodeURIComponent(encodedRedirect);
1125
+ } catch {
1126
+ postLoginRedirect = "/";
1127
+ }
1128
+ }
1129
+ const origin = new URL(redirectUri).origin;
1130
+ const result = this.client.getLoginUrl({
1131
+ returnTo: postLoginRedirect,
1132
+ requestOrigin: origin
1133
+ });
1134
+ if (this._loginResults.size > 100) {
1135
+ const firstKey = this._loginResults.keys().next().value;
1136
+ if (firstKey) this._loginResults.delete(firstKey);
1137
+ }
1138
+ this._loginResults.set(state, result);
1139
+ return result.url;
1140
+ }
1141
+ /**
1142
+ * Get cookies to set during login redirect (PKCE verifier).
1143
+ * Must be called after getLoginUrl() in same request.
1144
+ *
1145
+ * @param _redirectUri - OAuth callback URL
1146
+ * @param state - State parameter
1147
+ * @returns Array of Set-Cookie header values
1148
+ */
1149
+ getLoginCookies(_redirectUri, state) {
1150
+ const result = this._loginResults.get(state);
1151
+ if (result) {
1152
+ this._loginResults.delete(state);
1153
+ return result.cookies;
1154
+ }
1155
+ }
1156
+ /**
1157
+ * Handle OAuth callback, exchange code for tokens and user.
1158
+ *
1159
+ * @param code - Authorization code from callback
1160
+ * @param state - State parameter for CSRF validation
1161
+ * @returns User, tokens, and session cookies
1162
+ */
1163
+ async handleCallback(code, state) {
1164
+ const cookieHeader = this._lastCallbackCookieHeader;
1165
+ this._lastCallbackCookieHeader = null;
1166
+ const result = await this.client.handleCallback({
1167
+ code,
1168
+ state,
1169
+ cookieHeader
1170
+ });
1171
+ const sessionCookie = this.client.setSessionCookie(result.accessToken);
1172
+ return {
1173
+ user: result.user,
1174
+ tokens: { accessToken: result.accessToken },
1175
+ cookies: [...result.cookies, sessionCookie]
1176
+ };
1177
+ }
1178
+ /**
1179
+ * Get configuration for rendering login button in UI.
1180
+ *
1181
+ * @returns Login button configuration
1182
+ */
1183
+ getLoginButtonConfig() {
1184
+ return {
1185
+ provider: "mastra",
1186
+ text: "Sign in with Mastra Cloud"
1187
+ };
1188
+ }
1189
+ /**
1190
+ * Get logout URL for client-side redirect.
1191
+ * Requires the request to extract the session token for id_token_hint.
1192
+ *
1193
+ * @param redirectUri - URL to redirect to after logout
1194
+ * @param request - Request to extract session token from
1195
+ * @returns Logout URL with redirect and token parameters, or null if no session
1196
+ */
1197
+ getLogoutUrl(redirectUri, request) {
1198
+ const sessionToken = request ? this.getSessionIdFromRequest(request) : null;
1199
+ if (!sessionToken) return null;
1200
+ return this.client.getLogoutUrl(redirectUri, sessionToken);
1201
+ }
1202
+ /**
1203
+ * Create a new session for a user.
1204
+ *
1205
+ * For Cloud auth, sessions are created via handleCallback.
1206
+ * This method builds a Session object for interface compatibility.
1207
+ *
1208
+ * @param userId - User to create session for
1209
+ * @param metadata - Optional metadata (accessToken can be passed here)
1210
+ * @returns Session object
1211
+ */
1212
+ async createSession(userId, metadata) {
1213
+ const now = /* @__PURE__ */ new Date();
1214
+ const expiresAt = new Date(now.getTime() + 1440 * 60 * 1e3);
1215
+ return {
1216
+ id: metadata?.accessToken ?? crypto.randomUUID(),
1217
+ userId,
1218
+ createdAt: now,
1219
+ expiresAt,
1220
+ metadata
1221
+ };
1222
+ }
1223
+ /**
1224
+ * Validate a session and return it if valid.
1225
+ *
1226
+ * @param sessionId - Session token to validate
1227
+ * @returns Session object or null if invalid/expired
1228
+ */
1229
+ async validateSession(sessionId) {
1230
+ const session = await this.client.validateSession(sessionId);
1231
+ if (!session) return null;
1232
+ return {
1233
+ id: sessionId,
1234
+ userId: session.userId,
1235
+ createdAt: new Date(session.createdAt),
1236
+ expiresAt: new Date(session.expiresAt)
1237
+ };
1238
+ }
1239
+ /**
1240
+ * Destroy a session (logout).
1241
+ *
1242
+ * @param sessionId - Session token to destroy
1243
+ */
1244
+ async destroySession(sessionId) {
1245
+ await this.client.destroySession(sessionId);
1246
+ }
1247
+ /**
1248
+ * Refresh a session, extending its expiry.
1249
+ * Cloud handles refresh internally, so just validate.
1250
+ *
1251
+ * @param sessionId - Session token to refresh
1252
+ * @returns Session object or null if invalid
1253
+ */
1254
+ async refreshSession(sessionId) {
1255
+ return this.validateSession(sessionId);
1256
+ }
1257
+ /**
1258
+ * Extract session ID from an incoming request.
1259
+ *
1260
+ * @param request - Incoming HTTP request
1261
+ * @returns Session token or null if not present
1262
+ */
1263
+ getSessionIdFromRequest(request) {
1264
+ return parseSessionCookie(request.headers.get("cookie"));
1265
+ }
1266
+ /**
1267
+ * Create response headers to set session cookie.
1268
+ *
1269
+ * @param session - Session to encode (id is the access token)
1270
+ * @returns Headers object with Set-Cookie
1271
+ */
1272
+ getSessionHeaders(session) {
1273
+ return { "Set-Cookie": this.client.setSessionCookie(session.id) };
1274
+ }
1275
+ /**
1276
+ * Create response headers to clear session (for logout).
1277
+ *
1278
+ * @returns Headers object to clear session cookie
1279
+ */
1280
+ getClearSessionHeaders() {
1281
+ return { "Set-Cookie": this.client.clearSessionCookie() };
1282
+ }
1283
+ /**
1284
+ * Get current user from request (session cookie).
1285
+ *
1286
+ * @param request - Incoming HTTP request
1287
+ * @returns User with role or null if not authenticated
1288
+ */
1289
+ async getCurrentUser(request) {
1290
+ const sessionToken = this.getSessionIdFromRequest(request);
1291
+ if (!sessionToken) return null;
1292
+ try {
1293
+ const { user, role } = await this.client.verifyToken(sessionToken);
1294
+ return {
1295
+ ...user,
1296
+ role
1297
+ };
1298
+ } catch {
1299
+ return null;
1300
+ }
1301
+ }
1302
+ /**
1303
+ * Get user by ID.
1304
+ * Cloud API doesn't have a /users/:id endpoint.
1305
+ *
1306
+ * @returns Always null (not supported)
1307
+ */
1308
+ async getUser(_userId) {
1309
+ return null;
1310
+ }
1311
+ };
1312
+ //#endregion
1313
+ //#region src/rbac/rbac-provider.ts
1145
1314
  /**
1146
- * @mastra/core/auth/ee
1147
- *
1148
- * Enterprise authentication capabilities for Mastra.
1149
- * This code is licensed under the Mastra Enterprise License - see ee/LICENSE.
1150
- *
1151
- * @license Mastra Enterprise License - see ee/LICENSE
1152
- * @packageDocumentation
1153
- */
1154
-
1315
+ * RBAC provider for Mastra Cloud authentication.
1316
+ *
1317
+ * Maps user roles (from /verify endpoint) to Mastra permissions
1318
+ * using a configurable role mapping. This is a simpler implementation
1319
+ * than WorkOS RBAC since Cloud uses a single-role model.
1320
+ *
1321
+ * @example Basic usage
1322
+ * ```typescript
1323
+ * import { MastraRBACCloud } from '@mastra/auth-cloud';
1324
+ *
1325
+ * const rbac = new MastraRBACCloud({
1326
+ * roleMapping: {
1327
+ * admin: ['*'],
1328
+ * member: ['agents:read', 'workflows:*'],
1329
+ * viewer: ['agents:read', 'workflows:read'],
1330
+ * _default: [],
1331
+ * },
1332
+ * });
1333
+ *
1334
+ * const hasAccess = await rbac.hasPermission(user, 'agents:read');
1335
+ * ```
1336
+ */
1337
+ var MastraRBACCloud = class {
1338
+ options;
1339
+ /**
1340
+ * Expose roleMapping for middleware access.
1341
+ * This allows the authorization middleware to resolve permissions
1342
+ * without needing to call the async methods.
1343
+ */
1344
+ get roleMapping() {
1345
+ return this.options.roleMapping;
1346
+ }
1347
+ /**
1348
+ * Create a new Mastra Cloud RBAC provider.
1349
+ *
1350
+ * @param options - RBAC configuration options
1351
+ */
1352
+ constructor(options) {
1353
+ this.options = options;
1354
+ }
1355
+ /**
1356
+ * Get all roles for a user.
1357
+ *
1358
+ * Returns the user's role as a single-element array, or empty array if no role.
1359
+ * Cloud uses a single-role model (role is attached via verifyToken()).
1360
+ *
1361
+ * @param user - Cloud user to get roles for
1362
+ * @returns Array containing user's role, or empty array
1363
+ */
1364
+ async getRoles(user) {
1365
+ return user.role ? [user.role] : [];
1366
+ }
1367
+ /**
1368
+ * Check if a user has a specific role.
1369
+ *
1370
+ * @param user - Cloud user to check
1371
+ * @param role - Role name to check for
1372
+ * @returns True if user has the role
1373
+ */
1374
+ async hasRole(user, role) {
1375
+ return (await this.getRoles(user)).includes(role);
1376
+ }
1377
+ /**
1378
+ * Get all permissions for a user by mapping their role.
1379
+ *
1380
+ * Uses the configured roleMapping to translate the user's role
1381
+ * into Mastra permission strings.
1382
+ *
1383
+ * If the user has no role, the _default permissions from the
1384
+ * role mapping are applied.
1385
+ *
1386
+ * @param user - Cloud user to get permissions for
1387
+ * @returns Array of permission strings
1388
+ */
1389
+ async getPermissions(user) {
1390
+ const roles = await this.getRoles(user);
1391
+ if (roles.length === 0) return this.options.roleMapping["_default"] ?? [];
1392
+ return resolvePermissionsFromMapping(roles, this.options.roleMapping);
1393
+ }
1394
+ /**
1395
+ * Check if a user has a specific permission.
1396
+ *
1397
+ * Uses wildcard matching to check if the user's permissions
1398
+ * grant access to the required permission.
1399
+ *
1400
+ * @param user - Cloud user to check
1401
+ * @param permission - Permission to check for (e.g., 'agents:read')
1402
+ * @returns True if user has the permission
1403
+ */
1404
+ async hasPermission(user, permission) {
1405
+ return (await this.getPermissions(user)).some((p) => matchesPermission(p, permission));
1406
+ }
1407
+ /**
1408
+ * Check if a user has ALL of the specified permissions.
1409
+ *
1410
+ * @param user - Cloud user to check
1411
+ * @param permissions - Array of permissions to check for
1412
+ * @returns True if user has all permissions
1413
+ */
1414
+ async hasAllPermissions(user, permissions) {
1415
+ const userPermissions = await this.getPermissions(user);
1416
+ return permissions.every((required) => userPermissions.some((p) => matchesPermission(p, required)));
1417
+ }
1418
+ /**
1419
+ * Check if a user has ANY of the specified permissions.
1420
+ *
1421
+ * @param user - Cloud user to check
1422
+ * @param permissions - Array of permissions to check for
1423
+ * @returns True if user has at least one permission
1424
+ */
1425
+ async hasAnyPermission(user, permissions) {
1426
+ const userPermissions = await this.getPermissions(user);
1427
+ return permissions.some((required) => userPermissions.some((p) => matchesPermission(p, required)));
1428
+ }
1429
+ };
1430
+ //#endregion
1155
1431
  export { AuthError, MastraCloudAuth, MastraCloudAuthProvider, MastraRBACCloud };
1156
- //# sourceMappingURL=index.js.map
1432
+
1157
1433
  //# sourceMappingURL=index.js.map