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