@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/CHANGELOG.md +6 -0
- package/dist/_types/@internal_auth/dist/_types/@internal_core/dist/base/index.d.ts +27 -27
- package/dist/_types/@internal_auth/dist/_types/@internal_core/dist/index-S1lgaKO7.d.ts +218 -0
- package/dist/index.cjs +1357 -1099
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1356 -1097
- package/dist/index.js.map +1 -1
- package/package.json +7 -7
- package/dist/_types/@internal_auth/dist/_types/@internal_core/dist/logger/index.d.ts +0 -217
package/dist/index.cjs
CHANGED
|
@@ -1,1162 +1,1420 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
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
|
-
|
|
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
|
-
|
|
80
|
-
|
|
81
|
-
|
|
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
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
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
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
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
|
-
|
|
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
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
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
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
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
|
-
|
|
161
|
-
|
|
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
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
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
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
298
|
+
return (0, crypto$1.randomBytes)(16).toString("base64url");
|
|
206
299
|
}
|
|
207
|
-
|
|
208
|
-
|
|
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
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
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
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
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
|
-
|
|
287
|
-
|
|
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
|
-
|
|
290
|
-
|
|
291
|
-
|
|
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
|
-
|
|
298
|
-
|
|
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
|
-
|
|
444
|
+
return `${SESSION_COOKIE_NAME}=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0`;
|
|
305
445
|
}
|
|
306
|
-
|
|
307
|
-
|
|
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
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
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
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
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
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
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
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
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
|
-
|
|
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
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
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
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
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
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
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
|
-
|
|
824
|
+
//#endregion
|
|
825
|
+
//#region ../../packages/_internal-core/dist/base/index.js
|
|
582
826
|
var MastraBase = class {
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
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
|
-
|
|
859
|
+
//#endregion
|
|
860
|
+
//#region ../../packages/_internals/auth/dist/provider/index.js
|
|
621
861
|
var MastraAuthProvider = class extends MastraBase {
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
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
|
-
|
|
650
|
-
function
|
|
651
|
-
|
|
652
|
-
|
|
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
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
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
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
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
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
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
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
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
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
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
|
-
|
|
1419
|
+
|
|
1162
1420
|
//# sourceMappingURL=index.cjs.map
|