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