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

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,1420 @@
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/_internal-core/dist/logger/index.js
676
+ const RegisteredLogger = {
677
+ AGENT: "AGENT",
678
+ OBSERVABILITY: "OBSERVABILITY",
679
+ AUTH: "AUTH",
680
+ BROWSER: "BROWSER",
681
+ NETWORK: "NETWORK",
682
+ WORKFLOW: "WORKFLOW",
683
+ LLM: "LLM",
684
+ TTS: "TTS",
685
+ VOICE: "VOICE",
686
+ VECTOR: "VECTOR",
687
+ BUNDLER: "BUNDLER",
688
+ DEPLOYER: "DEPLOYER",
689
+ MEMORY: "MEMORY",
690
+ STORAGE: "STORAGE",
691
+ EMBEDDINGS: "EMBEDDINGS",
692
+ MCP_SERVER: "MCP_SERVER",
693
+ SERVER_CACHE: "SERVER_CACHE",
694
+ SERVER: "SERVER",
695
+ WORKSPACE: "WORKSPACE",
696
+ CHANNEL: "CHANNEL"
697
+ };
698
+ const LogLevel = {
699
+ DEBUG: "debug",
700
+ INFO: "info",
701
+ WARN: "warn",
702
+ ERROR: "error",
703
+ NONE: "silent"
466
704
  };
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
705
  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
- }
706
+ name;
707
+ level;
708
+ transports;
709
+ constructor(options = {}) {
710
+ this.name = options.name || "Mastra";
711
+ this.level = options.level || LogLevel.ERROR;
712
+ this.transports = new Map(Object.entries(options.transports || {}));
713
+ }
714
+ getTransports() {
715
+ return this.transports;
716
+ }
717
+ trackException(_error, _metadata) {}
718
+ async listLogs(transportId, params) {
719
+ if (!transportId || !this.transports.has(transportId)) return {
720
+ logs: [],
721
+ total: 0,
722
+ page: params?.page ?? 1,
723
+ perPage: params?.perPage ?? 100,
724
+ hasMore: false
725
+ };
726
+ return this.transports.get(transportId).listLogs?.(params) ?? {
727
+ logs: [],
728
+ total: 0,
729
+ page: params?.page ?? 1,
730
+ perPage: params?.perPage ?? 100,
731
+ hasMore: false
732
+ };
733
+ }
734
+ async listLogsByRunId({ transportId, runId, fromDate, toDate, logLevel, filters, page, perPage }) {
735
+ if (!transportId || !this.transports.has(transportId) || !runId) return {
736
+ logs: [],
737
+ total: 0,
738
+ page: page ?? 1,
739
+ perPage: perPage ?? 100,
740
+ hasMore: false
741
+ };
742
+ return this.transports.get(transportId).listLogsByRunId?.({
743
+ runId,
744
+ fromDate,
745
+ toDate,
746
+ logLevel,
747
+ filters,
748
+ page,
749
+ perPage
750
+ }) ?? {
751
+ logs: [],
752
+ total: 0,
753
+ page: page ?? 1,
754
+ perPage: perPage ?? 100,
755
+ hasMore: false
756
+ };
757
+ }
523
758
  };
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
- }
759
+ var ConsoleLogger = class ConsoleLogger extends MastraLogger {
760
+ component;
761
+ filter;
762
+ constructor(options = {}) {
763
+ super(options);
764
+ this.component = options.component;
765
+ this.filter = options.filter;
766
+ }
767
+ child(componentOrBindings) {
768
+ const component = typeof componentOrBindings === "string" ? componentOrBindings : componentOrBindings?.component ?? this.component;
769
+ return new ConsoleLogger({
770
+ name: this.name,
771
+ level: this.level,
772
+ component,
773
+ filter: this.filter
774
+ });
775
+ }
776
+ shouldLog(level, message, args) {
777
+ if (!this.filter) return true;
778
+ try {
779
+ return this.filter({
780
+ component: this.component,
781
+ level,
782
+ message,
783
+ args
784
+ });
785
+ } catch (e) {
786
+ console.error(`[Logger] Filter error for component=${this.component} level=${level}:`, e);
787
+ return true;
788
+ }
789
+ }
790
+ prefix() {
791
+ return this.component ? `[${this.component}] ` : "";
792
+ }
793
+ debug(message, ...args) {
794
+ if (this.level === LogLevel.DEBUG && this.shouldLog(LogLevel.DEBUG, message, args)) console.info(`${this.prefix()}${message}`, ...args);
795
+ }
796
+ info(message, ...args) {
797
+ if ((this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.INFO, message, args)) console.info(`${this.prefix()}${message}`, ...args);
798
+ }
799
+ warn(message, ...args) {
800
+ 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);
801
+ }
802
+ error(message, ...args) {
803
+ 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);
804
+ }
805
+ async listLogs(_transportId, _params) {
806
+ return {
807
+ logs: [],
808
+ total: 0,
809
+ page: _params?.page ?? 1,
810
+ perPage: _params?.perPage ?? 100,
811
+ hasMore: false
812
+ };
813
+ }
814
+ async listLogsByRunId(_args) {
815
+ return {
816
+ logs: [],
817
+ total: 0,
818
+ page: _args.page ?? 1,
819
+ perPage: _args.perPage ?? 100,
820
+ hasMore: false
821
+ };
822
+ }
579
823
  };
580
-
581
- // ../../packages/_internal-core/dist/base/index.js
824
+ //#endregion
825
+ //#region ../../packages/_internal-core/dist/base/index.js
582
826
  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
- }
827
+ component = RegisteredLogger.LLM;
828
+ logger;
829
+ name;
830
+ #rawConfig;
831
+ constructor({ component, name, rawConfig }) {
832
+ this.component = component || RegisteredLogger.LLM;
833
+ this.name = name;
834
+ this.#rawConfig = rawConfig;
835
+ this.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });
836
+ }
837
+ /**
838
+ * Returns the raw storage configuration this primitive was created from,
839
+ * or undefined if it was created from code.
840
+ */
841
+ toRawConfig() {
842
+ return this.#rawConfig;
843
+ }
844
+ /**
845
+ * Sets the raw storage configuration for this primitive.
846
+ * @internal
847
+ */
848
+ __setRawConfig(rawConfig) {
849
+ this.#rawConfig = rawConfig;
850
+ }
851
+ /**
852
+ * Set the logger for the agent
853
+ * @param logger
854
+ */
855
+ __setLogger(logger) {
856
+ this.logger = "child" in logger && typeof logger.child === "function" ? logger.child({ component: this.component }) : logger;
857
+ }
618
858
  };
619
-
620
- // ../../packages/_internals/auth/dist/chunk-NJOKT6V5.js
859
+ //#endregion
860
+ //#region ../../packages/_internals/auth/dist/provider/index.js
621
861
  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
- }
862
+ protected;
863
+ public;
864
+ constructor(options) {
865
+ super({
866
+ component: "AUTH",
867
+ name: options?.name
868
+ });
869
+ if (options?.authorizeUser) this.authorizeUser = options.authorizeUser.bind(this);
870
+ this.protected = options?.protected;
871
+ this.public = options?.public;
872
+ this.mapUserToResourceId = options?.mapUserToResourceId;
873
+ }
874
+ registerOptions(opts) {
875
+ if (opts?.authorizeUser) this.authorizeUser = opts.authorizeUser.bind(this);
876
+ if (opts?.mapUserToResourceId) this.mapUserToResourceId = opts.mapUserToResourceId;
877
+ if (opts?.protected) this.protected = opts.protected;
878
+ if (opts?.public) this.public = opts.public;
879
+ }
647
880
  };
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;
881
+ //#endregion
882
+ //#region src/auth-provider.ts
883
+ function getRequestHeader(request, name) {
884
+ if (request instanceof Request) return request.headers.get(name);
885
+ return request.raw?.headers.get(name) ?? request.headers?.get(name) ?? request.header(name) ?? null;
655
886
  }
887
+ /**
888
+ * Mastra Cloud authentication provider for server integration.
889
+ *
890
+ * Wraps the MastraCloudAuth client and implements the required interfaces
891
+ * for Mastra server middleware. Provides SSO login, session management,
892
+ * and user awareness.
893
+ *
894
+ * @example
895
+ * ```typescript
896
+ * import { MastraCloudAuthProvider } from '@mastra/auth-cloud';
897
+ *
898
+ * const auth = new MastraCloudAuthProvider({
899
+ * cloudBaseUrl: 'https://cloud.mastra.ai',
900
+ * callbackUrl: 'https://myapp.com/auth/callback',
901
+ * });
902
+ *
903
+ * const mastra = new Mastra({
904
+ * auth,
905
+ * // ...
906
+ * });
907
+ * ```
908
+ */
656
909
  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
- ]
910
+ client;
911
+ /** Marker for EE license exemption - MastraCloudAuth is exempt */
912
+ isMastraCloudAuth = true;
913
+ /**
914
+ * Cookie header for handleCallback PKCE validation.
915
+ * Set via setCallbackCookieHeader() before handleCallback() is called.
916
+ * @internal
917
+ */
918
+ _lastCallbackCookieHeader = null;
919
+ constructor(options) {
920
+ super({ name: options?.name ?? "cloud" });
921
+ this.client = new MastraCloudAuth({
922
+ projectId: options.projectId,
923
+ cloudBaseUrl: options.cloudBaseUrl,
924
+ callbackUrl: options.callbackUrl,
925
+ isProduction: options.isProduction
926
+ });
927
+ this.registerOptions(options);
928
+ }
929
+ /**
930
+ * Set cookie header for handleCallback PKCE validation.
931
+ * Must be called before handleCallback() to pass cookie header.
932
+ *
933
+ * @param cookieHeader - Cookie header from original request
934
+ */
935
+ setCallbackCookieHeader(cookieHeader) {
936
+ this._lastCallbackCookieHeader = cookieHeader;
937
+ }
938
+ /**
939
+ * Authenticate a bearer token or session cookie.
940
+ *
941
+ * Checks session cookie first, falls back to bearer token for API clients.
942
+ *
943
+ * @param token - Bearer token (from Authorization header)
944
+ * @param request - Request used for cookie access
945
+ * @returns Authenticated user with role, or null if invalid
946
+ */
947
+ async authenticateToken(token, request) {
948
+ try {
949
+ const sessionToken = parseSessionCookie(getRequestHeader(request, "cookie"));
950
+ if (sessionToken) {
951
+ const { user, role } = await this.client.verifyToken(sessionToken);
952
+ return {
953
+ ...user,
954
+ role
955
+ };
956
+ }
957
+ if (token) {
958
+ const { user, role } = await this.client.verifyToken(token);
959
+ return {
960
+ ...user,
961
+ role
962
+ };
963
+ }
964
+ return null;
965
+ } catch {
966
+ return null;
967
+ }
968
+ }
969
+ /**
970
+ * Authorize a user for access.
971
+ *
972
+ * Simple validation - detailed permission checking happens in server
973
+ * middleware via checkRoutePermission(), not authorizeUser().
974
+ *
975
+ * @param user - Authenticated user
976
+ * @returns True if user has valid id
977
+ */
978
+ authorizeUser(user) {
979
+ return !!user?.id;
980
+ }
981
+ /**
982
+ * Cached login results for getLoginCookies() to retrieve cookies.
983
+ * Keyed by the OAuth state parameter to prevent race conditions.
984
+ * @internal
985
+ */
986
+ _loginResults = /* @__PURE__ */ new Map();
987
+ /**
988
+ * Get URL to redirect user to for SSO login.
989
+ *
990
+ * @param redirectUri - Callback URL after authentication
991
+ * @param state - State parameter (format: uuid|encodedPostLoginRedirect)
992
+ * @returns Full authorization URL
993
+ */
994
+ getLoginUrl(redirectUri, state) {
995
+ let postLoginRedirect = "/";
996
+ if (state && state.includes("|")) {
997
+ const encodedRedirect = state.split("|", 2)[1];
998
+ if (encodedRedirect) try {
999
+ postLoginRedirect = decodeURIComponent(encodedRedirect);
1000
+ } catch {
1001
+ postLoginRedirect = "/";
1002
+ }
1003
+ }
1004
+ const origin = new URL(redirectUri).origin;
1005
+ const result = this.client.getLoginUrl({
1006
+ returnTo: postLoginRedirect,
1007
+ requestOrigin: origin
1008
+ });
1009
+ if (this._loginResults.size > 100) {
1010
+ const firstKey = this._loginResults.keys().next().value;
1011
+ if (firstKey) this._loginResults.delete(firstKey);
1012
+ }
1013
+ this._loginResults.set(state, result);
1014
+ return result.url;
1015
+ }
1016
+ /**
1017
+ * Get cookies to set during login redirect (PKCE verifier).
1018
+ * Must be called after getLoginUrl() in same request.
1019
+ *
1020
+ * @param _redirectUri - OAuth callback URL
1021
+ * @param state - State parameter
1022
+ * @returns Array of Set-Cookie header values
1023
+ */
1024
+ getLoginCookies(_redirectUri, state) {
1025
+ const result = this._loginResults.get(state);
1026
+ if (result) {
1027
+ this._loginResults.delete(state);
1028
+ return result.cookies;
1029
+ }
1030
+ }
1031
+ /**
1032
+ * Handle OAuth callback, exchange code for tokens and user.
1033
+ *
1034
+ * @param code - Authorization code from callback
1035
+ * @param state - State parameter for CSRF validation
1036
+ * @returns User, tokens, and session cookies
1037
+ */
1038
+ async handleCallback(code, state) {
1039
+ const cookieHeader = this._lastCallbackCookieHeader;
1040
+ this._lastCallbackCookieHeader = null;
1041
+ const result = await this.client.handleCallback({
1042
+ code,
1043
+ state,
1044
+ cookieHeader
1045
+ });
1046
+ const sessionCookie = this.client.setSessionCookie(result.accessToken);
1047
+ return {
1048
+ user: result.user,
1049
+ tokens: { accessToken: result.accessToken },
1050
+ cookies: [...result.cookies, sessionCookie]
1051
+ };
1052
+ }
1053
+ /**
1054
+ * Get configuration for rendering login button in UI.
1055
+ *
1056
+ * @returns Login button configuration
1057
+ */
1058
+ getLoginButtonConfig() {
1059
+ return {
1060
+ provider: "mastra",
1061
+ text: "Sign in with Mastra Cloud"
1062
+ };
1063
+ }
1064
+ /**
1065
+ * Get logout URL for client-side redirect.
1066
+ * Requires the request to extract the session token for id_token_hint.
1067
+ *
1068
+ * @param redirectUri - URL to redirect to after logout
1069
+ * @param request - Request to extract session token from
1070
+ * @returns Logout URL with redirect and token parameters, or null if no session
1071
+ */
1072
+ getLogoutUrl(redirectUri, request) {
1073
+ const sessionToken = request ? this.getSessionIdFromRequest(request) : null;
1074
+ if (!sessionToken) return null;
1075
+ return this.client.getLogoutUrl(redirectUri, sessionToken);
1076
+ }
1077
+ /**
1078
+ * Create a new session for a user.
1079
+ *
1080
+ * For Cloud auth, sessions are created via handleCallback.
1081
+ * This method builds a Session object for interface compatibility.
1082
+ *
1083
+ * @param userId - User to create session for
1084
+ * @param metadata - Optional metadata (accessToken can be passed here)
1085
+ * @returns Session object
1086
+ */
1087
+ async createSession(userId, metadata) {
1088
+ const now = /* @__PURE__ */ new Date();
1089
+ const expiresAt = new Date(now.getTime() + 1440 * 60 * 1e3);
1090
+ return {
1091
+ id: metadata?.accessToken ?? crypto.randomUUID(),
1092
+ userId,
1093
+ createdAt: now,
1094
+ expiresAt,
1095
+ metadata
1096
+ };
1097
+ }
1098
+ /**
1099
+ * Validate a session and return it if valid.
1100
+ *
1101
+ * @param sessionId - Session token to validate
1102
+ * @returns Session object or null if invalid/expired
1103
+ */
1104
+ async validateSession(sessionId) {
1105
+ const session = await this.client.validateSession(sessionId);
1106
+ if (!session) return null;
1107
+ return {
1108
+ id: sessionId,
1109
+ userId: session.userId,
1110
+ createdAt: new Date(session.createdAt),
1111
+ expiresAt: new Date(session.expiresAt)
1112
+ };
1113
+ }
1114
+ /**
1115
+ * Destroy a session (logout).
1116
+ *
1117
+ * @param sessionId - Session token to destroy
1118
+ */
1119
+ async destroySession(sessionId) {
1120
+ await this.client.destroySession(sessionId);
1121
+ }
1122
+ /**
1123
+ * Refresh a session, extending its expiry.
1124
+ * Cloud handles refresh internally, so just validate.
1125
+ *
1126
+ * @param sessionId - Session token to refresh
1127
+ * @returns Session object or null if invalid
1128
+ */
1129
+ async refreshSession(sessionId) {
1130
+ return this.validateSession(sessionId);
1131
+ }
1132
+ /**
1133
+ * Extract session ID from an incoming request.
1134
+ *
1135
+ * @param request - Incoming HTTP request
1136
+ * @returns Session token or null if not present
1137
+ */
1138
+ getSessionIdFromRequest(request) {
1139
+ return parseSessionCookie(request.headers.get("cookie"));
1140
+ }
1141
+ /**
1142
+ * Create response headers to set session cookie.
1143
+ *
1144
+ * @param session - Session to encode (id is the access token)
1145
+ * @returns Headers object with Set-Cookie
1146
+ */
1147
+ getSessionHeaders(session) {
1148
+ return { "Set-Cookie": this.client.setSessionCookie(session.id) };
1149
+ }
1150
+ /**
1151
+ * Create response headers to clear session (for logout).
1152
+ *
1153
+ * @returns Headers object to clear session cookie
1154
+ */
1155
+ getClearSessionHeaders() {
1156
+ return { "Set-Cookie": this.client.clearSessionCookie() };
1157
+ }
1158
+ /**
1159
+ * Get current user from request (session cookie).
1160
+ *
1161
+ * @param request - Incoming HTTP request
1162
+ * @returns User with role or null if not authenticated
1163
+ */
1164
+ async getCurrentUser(request) {
1165
+ const sessionToken = this.getSessionIdFromRequest(request);
1166
+ if (!sessionToken) return null;
1167
+ try {
1168
+ const { user, role } = await this.client.verifyToken(sessionToken);
1169
+ return {
1170
+ ...user,
1171
+ role
1172
+ };
1173
+ } catch {
1174
+ return null;
1175
+ }
1176
+ }
1177
+ /**
1178
+ * Get user by ID.
1179
+ * Cloud API doesn't have a /users/:id endpoint.
1180
+ *
1181
+ * @returns Always null (not supported)
1182
+ */
1183
+ async getUser(_userId) {
1184
+ return null;
1185
+ }
959
1186
  };
1187
+ //#endregion
1188
+ //#region ../../packages/_internals/auth/dist/ee-C8o0LZ3r.js
1189
+ /**
1190
+ * FGA enforcement utility for checking fine-grained authorization.
1191
+ *
1192
+ * @license Mastra Enterprise License - see ee/LICENSE
1193
+ */
1194
+ /**
1195
+ * Compound resource keys that expand to a set of per-family resources.
1196
+ * A granted `stored:<action>` is treated as matching any `stored-<family>:<action>`
1197
+ * (and `stored:*` matches any `stored-<family>:*`).
1198
+ */
1199
+ const RESOURCE_EXPANSIONS = { stored: [
1200
+ "stored-agents",
1201
+ "stored-mcp-clients",
1202
+ "stored-prompt-blocks",
1203
+ "stored-scorers",
1204
+ "stored-skills",
1205
+ "stored-workspaces"
1206
+ ] };
1207
+ /**
1208
+ * Check if a permission matches (including wildcard support).
1209
+ *
1210
+ * Permission format: `{resource}:{action}[:{resource-id}]`
1211
+ *
1212
+ * Examples:
1213
+ * - `*` matches everything
1214
+ * - `agents:*` matches `agents:read`, `agents:read:my-agent`
1215
+ * - `*:read` matches `agents:read`, `workflows:read` (action across all resources)
1216
+ * - `agents:read` matches `agents:read`, `agents:read:my-agent`
1217
+ * - `agents:read:my-agent` matches only `agents:read:my-agent`
1218
+ * - `agents:*:my-agent` matches `agents:read:my-agent`, `agents:write:my-agent`
1219
+ *
1220
+ * @param userPermission - Permission the user has
1221
+ * @param requiredPermission - Permission being checked
1222
+ * @returns True if permission matches
1223
+ */
960
1224
  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;
1225
+ if (userPermission === "*") return true;
1226
+ const grantedParts = userPermission.split(":");
1227
+ const requiredParts = requiredPermission.split(":");
1228
+ const expandedFamilies = RESOURCE_EXPANSIONS[grantedParts[0] ?? ""];
1229
+ if (expandedFamilies && expandedFamilies.includes(requiredParts[0] ?? "")) return matchesPermission([requiredParts[0], ...grantedParts.slice(1)].join(":"), requiredPermission);
1230
+ if (grantedParts.length < 2 || requiredParts.length < 2) return userPermission === requiredPermission;
1231
+ const [grantedResource, grantedAction, grantedId] = grantedParts;
1232
+ const [requiredResource, requiredAction, requiredId] = requiredParts;
1233
+ if (grantedResource === "*") {
1234
+ if (grantedAction === "*") {
1235
+ if (grantedId === void 0) return true;
1236
+ return grantedId === requiredId;
1237
+ }
1238
+ if (grantedAction !== requiredAction) return false;
1239
+ if (grantedId === void 0) return true;
1240
+ return grantedId === requiredId;
1241
+ }
1242
+ if (grantedResource !== requiredResource) return false;
1243
+ if (grantedAction === "*") {
1244
+ if (grantedId === void 0) return true;
1245
+ return grantedId === requiredId;
1246
+ }
1247
+ if (grantedAction !== requiredAction) return false;
1248
+ if (grantedId === void 0) return true;
1249
+ return grantedId === requiredId;
1007
1250
  }
1251
+ /**
1252
+ * Resolve permissions from user roles using a role mapping.
1253
+ *
1254
+ * This function translates provider-defined roles (from WorkOS, Okta, etc.)
1255
+ * to Mastra permissions using a configurable mapping.
1256
+ *
1257
+ * @example
1258
+ * ```typescript
1259
+ * const roleMapping = {
1260
+ * "Engineering": ["agents:*", "workflows:*"],
1261
+ * "Product": ["agents:read"],
1262
+ * "_default": [],
1263
+ * };
1264
+ *
1265
+ * // User has "Engineering" and "QA" roles
1266
+ * const permissions = resolvePermissionsFromMapping(
1267
+ * ["Engineering", "QA"],
1268
+ * roleMapping
1269
+ * );
1270
+ * // Result: ["agents:*", "workflows:*"] (QA is unmapped, gets _default)
1271
+ * ```
1272
+ *
1273
+ * @param roles - User's roles from the identity provider
1274
+ * @param mapping - Role to permission mapping
1275
+ * @returns Array of resolved permissions
1276
+ */
1008
1277
  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);
1278
+ const permissions = /* @__PURE__ */ new Set();
1279
+ const defaultPerms = mapping["_default"] ?? [];
1280
+ for (const role of roles) {
1281
+ const rolePerms = mapping[role];
1282
+ if (rolePerms) for (const perm of rolePerms) permissions.add(perm);
1283
+ else for (const perm of defaultPerms) permissions.add(perm);
1284
+ }
1285
+ return Array.from(permissions);
1024
1286
  }
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
- /**
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
- */
1132
- /**
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
1287
  /**
1143
- * Default implementations for EE authentication.
1144
- *
1145
- * @license Mastra Enterprise License - see ee/LICENSE
1146
- */
1288
+ * @mastra/core/auth/ee
1289
+ *
1290
+ * Enterprise authentication capabilities for Mastra.
1291
+ * This code is licensed under the Mastra Enterprise License - see ee/LICENSE.
1292
+ *
1293
+ * @license Mastra Enterprise License - see ee/LICENSE
1294
+ * @packageDocumentation
1295
+ */
1296
+ //#endregion
1297
+ //#region src/rbac/rbac-provider.ts
1147
1298
  /**
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
-
1299
+ * RBAC provider for Mastra Cloud authentication.
1300
+ *
1301
+ * Maps user roles (from /verify endpoint) to Mastra permissions
1302
+ * using a configurable role mapping. This is a simpler implementation
1303
+ * than WorkOS RBAC since Cloud uses a single-role model.
1304
+ *
1305
+ * @example Basic usage
1306
+ * ```typescript
1307
+ * import { MastraRBACCloud } from '@mastra/auth-cloud';
1308
+ *
1309
+ * const rbac = new MastraRBACCloud({
1310
+ * roleMapping: {
1311
+ * admin: ['*'],
1312
+ * member: ['agents:read', 'workflows:*'],
1313
+ * viewer: ['agents:read', 'workflows:read'],
1314
+ * _default: [],
1315
+ * },
1316
+ * });
1317
+ *
1318
+ * const hasAccess = await rbac.hasPermission(user, 'agents:read');
1319
+ * ```
1320
+ */
1321
+ var MastraRBACCloud = class {
1322
+ options;
1323
+ /**
1324
+ * Expose roleMapping for middleware access.
1325
+ * This allows the authorization middleware to resolve permissions
1326
+ * without needing to call the async methods.
1327
+ */
1328
+ get roleMapping() {
1329
+ return this.options.roleMapping;
1330
+ }
1331
+ /**
1332
+ * Create a new Mastra Cloud RBAC provider.
1333
+ *
1334
+ * @param options - RBAC configuration options
1335
+ */
1336
+ constructor(options) {
1337
+ this.options = options;
1338
+ }
1339
+ /**
1340
+ * Get all roles for a user.
1341
+ *
1342
+ * Returns the user's role as a single-element array, or empty array if no role.
1343
+ * Cloud uses a single-role model (role is attached via verifyToken()).
1344
+ *
1345
+ * @param user - Cloud user to get roles for
1346
+ * @returns Array containing user's role, or empty array
1347
+ */
1348
+ async getRoles(user) {
1349
+ return user.role ? [user.role] : [];
1350
+ }
1351
+ /**
1352
+ * Check if a user has a specific role.
1353
+ *
1354
+ * @param user - Cloud user to check
1355
+ * @param role - Role name to check for
1356
+ * @returns True if user has the role
1357
+ */
1358
+ async hasRole(user, role) {
1359
+ return (await this.getRoles(user)).includes(role);
1360
+ }
1361
+ /**
1362
+ * Get all permissions for a user by mapping their role.
1363
+ *
1364
+ * Uses the configured roleMapping to translate the user's role
1365
+ * into Mastra permission strings.
1366
+ *
1367
+ * If the user has no role, the _default permissions from the
1368
+ * role mapping are applied.
1369
+ *
1370
+ * @param user - Cloud user to get permissions for
1371
+ * @returns Array of permission strings
1372
+ */
1373
+ async getPermissions(user) {
1374
+ const roles = await this.getRoles(user);
1375
+ if (roles.length === 0) return this.options.roleMapping["_default"] ?? [];
1376
+ return resolvePermissionsFromMapping(roles, this.options.roleMapping);
1377
+ }
1378
+ /**
1379
+ * Check if a user has a specific permission.
1380
+ *
1381
+ * Uses wildcard matching to check if the user's permissions
1382
+ * grant access to the required permission.
1383
+ *
1384
+ * @param user - Cloud user to check
1385
+ * @param permission - Permission to check for (e.g., 'agents:read')
1386
+ * @returns True if user has the permission
1387
+ */
1388
+ async hasPermission(user, permission) {
1389
+ return (await this.getPermissions(user)).some((p) => matchesPermission(p, permission));
1390
+ }
1391
+ /**
1392
+ * Check if a user has ALL of the specified permissions.
1393
+ *
1394
+ * @param user - Cloud user to check
1395
+ * @param permissions - Array of permissions to check for
1396
+ * @returns True if user has all permissions
1397
+ */
1398
+ async hasAllPermissions(user, permissions) {
1399
+ const userPermissions = await this.getPermissions(user);
1400
+ return permissions.every((required) => userPermissions.some((p) => matchesPermission(p, required)));
1401
+ }
1402
+ /**
1403
+ * Check if a user has ANY of the specified permissions.
1404
+ *
1405
+ * @param user - Cloud user to check
1406
+ * @param permissions - Array of permissions to check for
1407
+ * @returns True if user has at least one permission
1408
+ */
1409
+ async hasAnyPermission(user, permissions) {
1410
+ const userPermissions = await this.getPermissions(user);
1411
+ return permissions.some((required) => userPermissions.some((p) => matchesPermission(p, required)));
1412
+ }
1413
+ };
1414
+ //#endregion
1157
1415
  exports.AuthError = AuthError;
1158
1416
  exports.MastraCloudAuth = MastraCloudAuth;
1159
1417
  exports.MastraCloudAuthProvider = MastraCloudAuthProvider;
1160
1418
  exports.MastraRBACCloud = MastraRBACCloud;
1161
- //# sourceMappingURL=index.cjs.map
1419
+
1162
1420
  //# sourceMappingURL=index.cjs.map