@mastra/auth 1.0.0 → 1.0.1
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 +20 -0
- package/LICENSE.md +15 -0
- package/dist/docs/SKILL.md +16 -21
- package/dist/docs/{SOURCE_MAP.json → assets/SOURCE_MAP.json} +1 -1
- package/dist/docs/references/docs-server-auth-custom-auth-provider.md +513 -0
- package/dist/docs/{server/02-jwt.md → references/docs-server-auth-jwt.md} +52 -41
- package/dist/docs/references/docs-server-auth.md +38 -0
- package/dist/docs/references/reference-auth-jwt.md +26 -0
- package/dist/index.cjs +23 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +23 -3
- package/dist/index.js.map +1 -1
- package/package.json +11 -12
- package/dist/docs/README.md +0 -32
- package/dist/docs/auth/01-reference.md +0 -33
- package/dist/docs/server/01-index.md +0 -16
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,25 @@
|
|
|
1
1
|
# @mastra/auth
|
|
2
2
|
|
|
3
|
+
## 1.0.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- dependencies updates: ([#13134](https://github.com/mastra-ai/mastra/pull/13134))
|
|
8
|
+
- Updated dependency [`jsonwebtoken@^9.0.3` ↗︎](https://www.npmjs.com/package/jsonwebtoken/v/9.0.3) (from `^9.0.2`, in `dependencies`)
|
|
9
|
+
|
|
10
|
+
- dependencies updates: ([#13135](https://github.com/mastra-ai/mastra/pull/13135))
|
|
11
|
+
- Updated dependency [`jwks-rsa@^3.2.2` ↗︎](https://www.npmjs.com/package/jwks-rsa/v/3.2.2) (from `^3.2.0`, in `dependencies`)
|
|
12
|
+
|
|
13
|
+
## 1.0.1-alpha.0
|
|
14
|
+
|
|
15
|
+
### Patch Changes
|
|
16
|
+
|
|
17
|
+
- dependencies updates: ([#13134](https://github.com/mastra-ai/mastra/pull/13134))
|
|
18
|
+
- Updated dependency [`jsonwebtoken@^9.0.3` ↗︎](https://www.npmjs.com/package/jsonwebtoken/v/9.0.3) (from `^9.0.2`, in `dependencies`)
|
|
19
|
+
|
|
20
|
+
- dependencies updates: ([#13135](https://github.com/mastra-ai/mastra/pull/13135))
|
|
21
|
+
- Updated dependency [`jwks-rsa@^3.2.2` ↗︎](https://www.npmjs.com/package/jwks-rsa/v/3.2.2) (from `^3.2.0`, in `dependencies`)
|
|
22
|
+
|
|
3
23
|
## 1.0.0
|
|
4
24
|
|
|
5
25
|
### Major Changes
|
package/LICENSE.md
CHANGED
|
@@ -1,3 +1,18 @@
|
|
|
1
|
+
Portions of this software are licensed as follows:
|
|
2
|
+
|
|
3
|
+
- All content that resides under any directory named "ee/" within this
|
|
4
|
+
repository, including but not limited to:
|
|
5
|
+
- `packages/core/src/auth/ee/`
|
|
6
|
+
- `packages/server/src/server/auth/ee/`
|
|
7
|
+
is licensed under the license defined in `ee/LICENSE`.
|
|
8
|
+
|
|
9
|
+
- All third-party components incorporated into the Mastra Software are
|
|
10
|
+
licensed under the original license provided by the owner of the
|
|
11
|
+
applicable component.
|
|
12
|
+
|
|
13
|
+
- Content outside of the above-mentioned directories or restrictions is
|
|
14
|
+
available under the "Apache License 2.0" as defined below.
|
|
15
|
+
|
|
1
16
|
# Apache License 2.0
|
|
2
17
|
|
|
3
18
|
Copyright (c) 2025 Kepler Software, Inc.
|
package/dist/docs/SKILL.md
CHANGED
|
@@ -1,33 +1,28 @@
|
|
|
1
1
|
---
|
|
2
|
-
name: mastra-auth
|
|
3
|
-
description: Documentation for @mastra/auth.
|
|
2
|
+
name: mastra-auth
|
|
3
|
+
description: Documentation for @mastra/auth. Use when working with @mastra/auth APIs, configuration, or implementation.
|
|
4
|
+
metadata:
|
|
5
|
+
package: "@mastra/auth"
|
|
6
|
+
version: "1.0.1"
|
|
4
7
|
---
|
|
5
8
|
|
|
6
|
-
|
|
9
|
+
## When to use
|
|
7
10
|
|
|
8
|
-
|
|
9
|
-
> **Package**: @mastra/auth
|
|
11
|
+
Use this skill whenever you are working with @mastra/auth to obtain the domain-specific knowledge.
|
|
10
12
|
|
|
11
|
-
##
|
|
13
|
+
## How to use
|
|
12
14
|
|
|
13
|
-
|
|
15
|
+
Read the individual reference documents for detailed explanations and code examples.
|
|
14
16
|
|
|
15
|
-
|
|
16
|
-
cat docs/SOURCE_MAP.json
|
|
17
|
-
```
|
|
17
|
+
### Docs
|
|
18
18
|
|
|
19
|
-
|
|
20
|
-
-
|
|
21
|
-
-
|
|
22
|
-
- **docs**: Conceptual documentation in `docs/`
|
|
19
|
+
- [Auth Overview](references/docs-server-auth.md) - Learn about different Auth options for your Mastra applications
|
|
20
|
+
- [Custom Auth Provider](references/docs-server-auth-custom-auth-provider.md) - Create custom authentication providers for specialized identity systems
|
|
21
|
+
- [MastraJwtAuth Class](references/docs-server-auth-jwt.md) - Documentation for the MastraJwtAuth class, which authenticates Mastra applications using JSON Web Tokens.
|
|
23
22
|
|
|
24
|
-
|
|
23
|
+
### Reference
|
|
25
24
|
|
|
25
|
+
- [Reference: MastraJwtAuth Class](references/reference-auth-jwt.md) - API reference for the MastraJwtAuth class, which authenticates Mastra applications using JSON Web Tokens.
|
|
26
26
|
|
|
27
27
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
## Available Topics
|
|
31
|
-
|
|
32
|
-
- [Auth](auth/) - 1 file(s)
|
|
33
|
-
- [Server](server/) - 2 file(s)
|
|
28
|
+
Read [assets/SOURCE_MAP.json](assets/SOURCE_MAP.json) for source code references.
|
|
@@ -0,0 +1,513 @@
|
|
|
1
|
+
# Custom Auth Providers
|
|
2
|
+
|
|
3
|
+
Custom auth providers allow you to implement authentication for identity systems that aren't covered by the built-in providers. Extend the `MastraAuthProvider` base class to integrate with any authentication system.
|
|
4
|
+
|
|
5
|
+
## Overview
|
|
6
|
+
|
|
7
|
+
Auth providers handle authentication and authorization for incoming requests:
|
|
8
|
+
|
|
9
|
+
- Token verification and user extraction
|
|
10
|
+
- User authorization logic
|
|
11
|
+
- Path-based access control (public/protected routes)
|
|
12
|
+
|
|
13
|
+
Create custom auth providers to support:
|
|
14
|
+
|
|
15
|
+
- Self-hosted identity systems
|
|
16
|
+
- Custom token formats or verification logic
|
|
17
|
+
- Specialized authorization rules
|
|
18
|
+
- Enterprise SSO integrations
|
|
19
|
+
|
|
20
|
+
## Creating a Custom Auth Provider
|
|
21
|
+
|
|
22
|
+
Extend the `MastraAuthProvider` class and implement the required methods:
|
|
23
|
+
|
|
24
|
+
```typescript
|
|
25
|
+
import { MastraAuthProvider } from '@mastra/core/server'
|
|
26
|
+
import type { MastraAuthProviderOptions } from '@mastra/core/server'
|
|
27
|
+
import type { HonoRequest } from 'hono'
|
|
28
|
+
|
|
29
|
+
// Define your user type
|
|
30
|
+
type MyUser = {
|
|
31
|
+
id: string
|
|
32
|
+
email: string
|
|
33
|
+
roles: string[]
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Define options for your provider
|
|
37
|
+
interface MyAuthOptions extends MastraAuthProviderOptions<MyUser> {
|
|
38
|
+
apiUrl?: string
|
|
39
|
+
apiKey?: string
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export class MyAuthProvider extends MastraAuthProvider<MyUser> {
|
|
43
|
+
protected apiUrl: string
|
|
44
|
+
protected apiKey: string
|
|
45
|
+
|
|
46
|
+
constructor(options?: MyAuthOptions) {
|
|
47
|
+
// Call super with a name for logging/debugging
|
|
48
|
+
super({ name: options?.name ?? 'my-auth' })
|
|
49
|
+
|
|
50
|
+
const apiUrl = options?.apiUrl ?? process.env.MY_AUTH_API_URL
|
|
51
|
+
const apiKey = options?.apiKey ?? process.env.MY_AUTH_API_KEY
|
|
52
|
+
|
|
53
|
+
if (!apiUrl || !apiKey) {
|
|
54
|
+
throw new Error(
|
|
55
|
+
'Auth API URL and API key are required. Provide them in options or set MY_AUTH_API_URL and MY_AUTH_API_KEY environment variables.',
|
|
56
|
+
)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
this.apiUrl = apiUrl
|
|
60
|
+
this.apiKey = apiKey
|
|
61
|
+
|
|
62
|
+
// Register any custom options (authorizeUser override, public/protected paths)
|
|
63
|
+
this.registerOptions(options)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Verify the token and return the user
|
|
68
|
+
* Return null if authentication fails
|
|
69
|
+
*/
|
|
70
|
+
async authenticateToken(token: string, request: HonoRequest): Promise<MyUser | null> {
|
|
71
|
+
try {
|
|
72
|
+
const response = await fetch(`${this.apiUrl}/verify`, {
|
|
73
|
+
method: 'POST',
|
|
74
|
+
headers: {
|
|
75
|
+
'Content-Type': 'application/json',
|
|
76
|
+
'X-API-Key': this.apiKey,
|
|
77
|
+
},
|
|
78
|
+
body: JSON.stringify({ token }),
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
if (!response.ok) {
|
|
82
|
+
return null
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const user = await response.json()
|
|
86
|
+
return user
|
|
87
|
+
} catch (error) {
|
|
88
|
+
console.error('Token verification failed:', error)
|
|
89
|
+
return null
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Check if the authenticated user is authorized
|
|
95
|
+
* Return true to allow access, false to deny
|
|
96
|
+
*/
|
|
97
|
+
async authorizeUser(user: MyUser, request: HonoRequest): Promise<boolean> {
|
|
98
|
+
// Basic authorization: user must exist and have an ID
|
|
99
|
+
return !!user?.id
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## Required Methods
|
|
105
|
+
|
|
106
|
+
### authenticateToken()
|
|
107
|
+
|
|
108
|
+
Verify the incoming token and return the user object if valid, or `null` if authentication fails.
|
|
109
|
+
|
|
110
|
+
```typescript
|
|
111
|
+
async authenticateToken(token: string, request: HonoRequest): Promise<TUser | null>
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
| Parameter | Type | Description |
|
|
115
|
+
| --------- | ------------- | ----------------------------------------------------------- |
|
|
116
|
+
| `token` | `string` | The bearer token extracted from the `Authorization` header |
|
|
117
|
+
| `request` | `HonoRequest` | The incoming request object (access headers, cookies, etc.) |
|
|
118
|
+
|
|
119
|
+
**Returns**: The user object if authentication succeeds, or `null` if it fails.
|
|
120
|
+
|
|
121
|
+
The token is automatically extracted from the `Authorization: Bearer <token>` header. If you need to access other headers or cookies, use the `request` parameter.
|
|
122
|
+
|
|
123
|
+
### authorizeUser()
|
|
124
|
+
|
|
125
|
+
Determine if the authenticated user is allowed to access the resource.
|
|
126
|
+
|
|
127
|
+
```typescript
|
|
128
|
+
async authorizeUser(user: TUser, request: HonoRequest): Promise<boolean> | boolean
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
| Parameter | Type | Description |
|
|
132
|
+
| --------- | ------------- | ----------------------------------------------- |
|
|
133
|
+
| `user` | `TUser` | The user object returned by `authenticateToken` |
|
|
134
|
+
| `request` | `HonoRequest` | The incoming request object |
|
|
135
|
+
|
|
136
|
+
**Returns**: `true` to allow access, `false` to deny (returns 403 Forbidden).
|
|
137
|
+
|
|
138
|
+
## Configuration Options
|
|
139
|
+
|
|
140
|
+
The `MastraAuthProviderOptions` interface supports these options:
|
|
141
|
+
|
|
142
|
+
| Option | Type | Description |
|
|
143
|
+
| --------------- | -------------------------------------------------------- | ----------------------------------- |
|
|
144
|
+
| `name` | `string` | Provider name for logging/debugging |
|
|
145
|
+
| `authorizeUser` | `(user, request) => Promise<boolean> \| boolean` | Custom authorization function |
|
|
146
|
+
| `protected` | `(RegExp \| string \| [string, Methods \| Methods[]])[]` | Paths that require authentication |
|
|
147
|
+
| `public` | `(RegExp \| string \| [string, Methods \| Methods[]])[]` | Paths that bypass authentication |
|
|
148
|
+
|
|
149
|
+
### Path Patterns
|
|
150
|
+
|
|
151
|
+
Configure which paths require authentication using pattern matching:
|
|
152
|
+
|
|
153
|
+
```typescript
|
|
154
|
+
const auth = new MyAuthProvider({
|
|
155
|
+
// Paths that require authentication
|
|
156
|
+
protected: [
|
|
157
|
+
'/api/*', // Wildcard: all /api routes
|
|
158
|
+
'/admin/*', // Wildcard: all /admin routes
|
|
159
|
+
/^\/secure\/.*/, // Regex pattern
|
|
160
|
+
],
|
|
161
|
+
|
|
162
|
+
// Paths that bypass authentication
|
|
163
|
+
public: [
|
|
164
|
+
'/health', // Exact match
|
|
165
|
+
'/api/status', // Exact match
|
|
166
|
+
['/api/webhook', 'POST'], // Only POST requests to /api/webhook
|
|
167
|
+
],
|
|
168
|
+
})
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
## Using Your Auth Provider
|
|
172
|
+
|
|
173
|
+
Register your custom auth provider with the Mastra instance:
|
|
174
|
+
|
|
175
|
+
```typescript
|
|
176
|
+
import { Mastra } from '@mastra/core'
|
|
177
|
+
import { MyAuthProvider } from './my-auth-provider'
|
|
178
|
+
|
|
179
|
+
export const mastra = new Mastra({
|
|
180
|
+
server: {
|
|
181
|
+
auth: new MyAuthProvider({
|
|
182
|
+
apiUrl: process.env.MY_AUTH_API_URL,
|
|
183
|
+
apiKey: process.env.MY_AUTH_API_KEY,
|
|
184
|
+
}),
|
|
185
|
+
},
|
|
186
|
+
})
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
## Helper Utilities
|
|
190
|
+
|
|
191
|
+
The `@mastra/auth` package provides utilities for common token verification patterns:
|
|
192
|
+
|
|
193
|
+
### JWT Verification
|
|
194
|
+
|
|
195
|
+
```typescript
|
|
196
|
+
import { verifyHmac, verifyJwks, decodeToken, getTokenIssuer } from '@mastra/auth'
|
|
197
|
+
|
|
198
|
+
// Verify HMAC-signed JWT
|
|
199
|
+
const payload = await verifyHmac(token, 'your-secret-key')
|
|
200
|
+
|
|
201
|
+
// Verify with JWKS (for OAuth providers)
|
|
202
|
+
const payload = await verifyJwks(token, 'https://provider.com/.well-known/jwks.json')
|
|
203
|
+
|
|
204
|
+
// Decode without verification (for inspection)
|
|
205
|
+
const decoded = await decodeToken(token)
|
|
206
|
+
|
|
207
|
+
// Get the issuer from a decoded token
|
|
208
|
+
const issuer = getTokenIssuer(decoded)
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
### Example: JWKS-based Provider
|
|
212
|
+
|
|
213
|
+
```typescript
|
|
214
|
+
import { MastraAuthProvider } from '@mastra/core/server'
|
|
215
|
+
import type { MastraAuthProviderOptions } from '@mastra/core/server'
|
|
216
|
+
import { verifyJwks } from '@mastra/auth'
|
|
217
|
+
import type { JwtPayload } from '@mastra/auth'
|
|
218
|
+
|
|
219
|
+
type MyUser = JwtPayload
|
|
220
|
+
|
|
221
|
+
interface MyJwksAuthOptions extends MastraAuthProviderOptions<MyUser> {
|
|
222
|
+
jwksUri?: string
|
|
223
|
+
issuer?: string
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export class MyJwksAuth extends MastraAuthProvider<MyUser> {
|
|
227
|
+
protected jwksUri: string
|
|
228
|
+
protected issuer: string
|
|
229
|
+
|
|
230
|
+
constructor(options?: MyJwksAuthOptions) {
|
|
231
|
+
super({ name: options?.name ?? 'my-jwks-auth' })
|
|
232
|
+
|
|
233
|
+
const jwksUri = options?.jwksUri ?? process.env.MY_JWKS_URI
|
|
234
|
+
const issuer = options?.issuer ?? process.env.MY_AUTH_ISSUER
|
|
235
|
+
|
|
236
|
+
if (!jwksUri) {
|
|
237
|
+
throw new Error('JWKS URI is required')
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
this.jwksUri = jwksUri
|
|
241
|
+
this.issuer = issuer ?? ''
|
|
242
|
+
|
|
243
|
+
this.registerOptions(options)
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
async authenticateToken(token: string): Promise<MyUser | null> {
|
|
247
|
+
try {
|
|
248
|
+
const payload = await verifyJwks(token, this.jwksUri)
|
|
249
|
+
|
|
250
|
+
// Optionally validate issuer
|
|
251
|
+
if (this.issuer && payload.iss !== this.issuer) {
|
|
252
|
+
return null
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
return payload
|
|
256
|
+
} catch {
|
|
257
|
+
return null
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
async authorizeUser(user: MyUser): Promise<boolean> {
|
|
262
|
+
// Check token hasn't expired
|
|
263
|
+
if (user.exp && user.exp * 1000 < Date.now()) {
|
|
264
|
+
return false
|
|
265
|
+
}
|
|
266
|
+
return !!user.sub
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
## Custom Authorization Logic
|
|
272
|
+
|
|
273
|
+
Override the default authorization by providing a custom `authorizeUser` function:
|
|
274
|
+
|
|
275
|
+
```typescript
|
|
276
|
+
const auth = new MyAuthProvider({
|
|
277
|
+
apiUrl: process.env.MY_AUTH_API_URL,
|
|
278
|
+
apiKey: process.env.MY_AUTH_API_KEY,
|
|
279
|
+
|
|
280
|
+
// Custom authorization: require admin role for all requests
|
|
281
|
+
async authorizeUser(user, request) {
|
|
282
|
+
return user.roles.includes('admin')
|
|
283
|
+
},
|
|
284
|
+
})
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
### Role-based Authorization
|
|
288
|
+
|
|
289
|
+
```typescript
|
|
290
|
+
const auth = new MyAuthProvider({
|
|
291
|
+
async authorizeUser(user, request) {
|
|
292
|
+
const path = request.url
|
|
293
|
+
const method = request.method
|
|
294
|
+
|
|
295
|
+
// Admin routes require admin role
|
|
296
|
+
if (path.startsWith('/admin/')) {
|
|
297
|
+
return user.roles.includes('admin')
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// Write operations require write role
|
|
301
|
+
if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) {
|
|
302
|
+
return user.roles.includes('write') || user.roles.includes('admin')
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// Read operations allowed for all authenticated users
|
|
306
|
+
return true
|
|
307
|
+
},
|
|
308
|
+
})
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
## Testing Custom Auth Providers
|
|
312
|
+
|
|
313
|
+
Example test structure using Vitest:
|
|
314
|
+
|
|
315
|
+
```typescript
|
|
316
|
+
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|
317
|
+
import { MyAuthProvider } from './my-auth-provider'
|
|
318
|
+
|
|
319
|
+
// Mock fetch for API calls
|
|
320
|
+
global.fetch = vi.fn()
|
|
321
|
+
|
|
322
|
+
describe('MyAuthProvider', () => {
|
|
323
|
+
const mockOptions = {
|
|
324
|
+
apiUrl: 'https://auth.example.com',
|
|
325
|
+
apiKey: 'test-api-key',
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
beforeEach(() => {
|
|
329
|
+
vi.clearAllMocks()
|
|
330
|
+
})
|
|
331
|
+
|
|
332
|
+
describe('initialization', () => {
|
|
333
|
+
it('should initialize with provided options', () => {
|
|
334
|
+
const auth = new MyAuthProvider(mockOptions)
|
|
335
|
+
expect(auth).toBeInstanceOf(MyAuthProvider)
|
|
336
|
+
})
|
|
337
|
+
|
|
338
|
+
it('should throw error when required options are missing', () => {
|
|
339
|
+
expect(() => new MyAuthProvider({})).toThrow('Auth API URL and API key are required')
|
|
340
|
+
})
|
|
341
|
+
})
|
|
342
|
+
|
|
343
|
+
describe('authenticateToken', () => {
|
|
344
|
+
it('should return user when token is valid', async () => {
|
|
345
|
+
const mockUser = { id: 'user123', email: 'test@example.com', roles: ['read'] }
|
|
346
|
+
;(fetch as any).mockResolvedValue({
|
|
347
|
+
ok: true,
|
|
348
|
+
json: () => Promise.resolve(mockUser),
|
|
349
|
+
})
|
|
350
|
+
|
|
351
|
+
const auth = new MyAuthProvider(mockOptions)
|
|
352
|
+
const result = await auth.authenticateToken('valid-token', {} as any)
|
|
353
|
+
|
|
354
|
+
expect(fetch).toHaveBeenCalledWith(
|
|
355
|
+
'https://auth.example.com/verify',
|
|
356
|
+
expect.objectContaining({
|
|
357
|
+
method: 'POST',
|
|
358
|
+
body: JSON.stringify({ token: 'valid-token' }),
|
|
359
|
+
}),
|
|
360
|
+
)
|
|
361
|
+
expect(result).toEqual(mockUser)
|
|
362
|
+
})
|
|
363
|
+
|
|
364
|
+
it('should return null when token is invalid', async () => {
|
|
365
|
+
;(fetch as any).mockResolvedValue({ ok: false })
|
|
366
|
+
|
|
367
|
+
const auth = new MyAuthProvider(mockOptions)
|
|
368
|
+
const result = await auth.authenticateToken('invalid-token', {} as any)
|
|
369
|
+
|
|
370
|
+
expect(result).toBeNull()
|
|
371
|
+
})
|
|
372
|
+
})
|
|
373
|
+
|
|
374
|
+
describe('authorizeUser', () => {
|
|
375
|
+
it('should return true when user has valid id', async () => {
|
|
376
|
+
const auth = new MyAuthProvider(mockOptions)
|
|
377
|
+
const result = await auth.authorizeUser(
|
|
378
|
+
{ id: 'user123', email: 'test@example.com', roles: [] },
|
|
379
|
+
{} as any,
|
|
380
|
+
)
|
|
381
|
+
|
|
382
|
+
expect(result).toBe(true)
|
|
383
|
+
})
|
|
384
|
+
|
|
385
|
+
it('should return false when user has no id', async () => {
|
|
386
|
+
const auth = new MyAuthProvider(mockOptions)
|
|
387
|
+
const result = await auth.authorizeUser(
|
|
388
|
+
{ id: '', email: 'test@example.com', roles: [] },
|
|
389
|
+
{} as any,
|
|
390
|
+
)
|
|
391
|
+
|
|
392
|
+
expect(result).toBe(false)
|
|
393
|
+
})
|
|
394
|
+
})
|
|
395
|
+
|
|
396
|
+
describe('custom authorization', () => {
|
|
397
|
+
it('should use custom authorizeUser when provided', async () => {
|
|
398
|
+
const auth = new MyAuthProvider({
|
|
399
|
+
...mockOptions,
|
|
400
|
+
authorizeUser: user => user.roles.includes('admin'),
|
|
401
|
+
})
|
|
402
|
+
|
|
403
|
+
const adminUser = { id: 'user123', email: 'admin@example.com', roles: ['admin'] }
|
|
404
|
+
const regularUser = { id: 'user456', email: 'user@example.com', roles: ['read'] }
|
|
405
|
+
|
|
406
|
+
expect(await auth.authorizeUser(adminUser, {} as any)).toBe(true)
|
|
407
|
+
expect(await auth.authorizeUser(regularUser, {} as any)).toBe(false)
|
|
408
|
+
})
|
|
409
|
+
})
|
|
410
|
+
|
|
411
|
+
describe('route configuration', () => {
|
|
412
|
+
it('should store public routes configuration', () => {
|
|
413
|
+
const publicRoutes = ['/health', '/api/status']
|
|
414
|
+
const auth = new MyAuthProvider({
|
|
415
|
+
...mockOptions,
|
|
416
|
+
public: publicRoutes,
|
|
417
|
+
})
|
|
418
|
+
|
|
419
|
+
expect(auth.public).toEqual(publicRoutes)
|
|
420
|
+
})
|
|
421
|
+
|
|
422
|
+
it('should store protected routes configuration', () => {
|
|
423
|
+
const protectedRoutes = ['/api/*', '/admin/*']
|
|
424
|
+
const auth = new MyAuthProvider({
|
|
425
|
+
...mockOptions,
|
|
426
|
+
protected: protectedRoutes,
|
|
427
|
+
})
|
|
428
|
+
|
|
429
|
+
expect(auth.protected).toEqual(protectedRoutes)
|
|
430
|
+
})
|
|
431
|
+
})
|
|
432
|
+
})
|
|
433
|
+
```
|
|
434
|
+
|
|
435
|
+
## Error Handling
|
|
436
|
+
|
|
437
|
+
Provide descriptive errors for common failure scenarios:
|
|
438
|
+
|
|
439
|
+
```typescript
|
|
440
|
+
export class MyAuthProvider extends MastraAuthProvider<MyUser> {
|
|
441
|
+
constructor(options?: MyAuthOptions) {
|
|
442
|
+
super({ name: options?.name ?? 'my-auth' })
|
|
443
|
+
|
|
444
|
+
const apiUrl = options?.apiUrl ?? process.env.MY_AUTH_API_URL
|
|
445
|
+
const apiKey = options?.apiKey ?? process.env.MY_AUTH_API_KEY
|
|
446
|
+
|
|
447
|
+
if (!apiUrl) {
|
|
448
|
+
throw new Error(
|
|
449
|
+
'Missing MY_AUTH_API_URL. Set the environment variable or pass apiUrl in options.',
|
|
450
|
+
)
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
if (!apiKey) {
|
|
454
|
+
throw new Error(
|
|
455
|
+
'Missing MY_AUTH_API_KEY. Set the environment variable or pass apiKey in options.',
|
|
456
|
+
)
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
this.apiUrl = apiUrl
|
|
460
|
+
this.apiKey = apiKey
|
|
461
|
+
this.registerOptions(options)
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
async authenticateToken(token: string): Promise<MyUser | null> {
|
|
465
|
+
if (!token || typeof token !== 'string') {
|
|
466
|
+
return null // Immediate safe fail
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
try {
|
|
470
|
+
const response = await fetch(`${this.apiUrl}/verify`, {
|
|
471
|
+
method: 'POST',
|
|
472
|
+
headers: {
|
|
473
|
+
'Content-Type': 'application/json',
|
|
474
|
+
'X-API-Key': this.apiKey,
|
|
475
|
+
},
|
|
476
|
+
body: JSON.stringify({ token }),
|
|
477
|
+
})
|
|
478
|
+
|
|
479
|
+
if (!response.ok) {
|
|
480
|
+
return null
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
return await response.json()
|
|
484
|
+
} catch (error) {
|
|
485
|
+
// Log error for debugging, but don't expose details to client
|
|
486
|
+
console.error('Auth verification error:', error)
|
|
487
|
+
return null
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
```
|
|
492
|
+
|
|
493
|
+
## Built-in Providers
|
|
494
|
+
|
|
495
|
+
Mastra includes these auth providers as reference implementations:
|
|
496
|
+
|
|
497
|
+
- **MastraJwtAuth**: Simple JWT verification with HMAC secrets (`@mastra/auth`)
|
|
498
|
+
- **MastraAuthClerk**: Clerk authentication (`@mastra/auth-clerk`)
|
|
499
|
+
- **MastraAuthAuth0**: Auth0 authentication (`@mastra/auth-auth0`)
|
|
500
|
+
- **MastraAuthSupabase**: Supabase authentication (`@mastra/auth-supabase`)
|
|
501
|
+
- **MastraAuthFirebase**: Firebase authentication (`@mastra/auth-firebase`)
|
|
502
|
+
- **MastraAuthWorkOS**: WorkOS authentication (`@mastra/auth-workos`)
|
|
503
|
+
- **MastraAuthBetterAuth**: Better Auth integration (`@mastra/auth-better-auth`)
|
|
504
|
+
- **SimpleAuth**: Token-to-user mapping for development (`@mastra/core/server`)
|
|
505
|
+
|
|
506
|
+
See the [source code](https://github.com/mastra-ai/mastra/tree/main/auth) for implementation details.
|
|
507
|
+
|
|
508
|
+
## Related
|
|
509
|
+
|
|
510
|
+
- [Auth Overview](https://mastra.ai/docs/server/auth) - Authentication concepts and configuration
|
|
511
|
+
- [JWT Auth](https://mastra.ai/docs/server/auth/jwt) - Simple JWT authentication
|
|
512
|
+
- [Clerk Auth](https://mastra.ai/docs/server/auth/clerk) - Clerk integration
|
|
513
|
+
- [Custom API Routes](https://mastra.ai/docs/server/custom-api-routes) - Controlling authentication on custom endpoints
|
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
> Documentation for the MastraJwtAuth class, which authenticates Mastra applications using JSON Web Tokens.
|
|
2
|
-
|
|
3
1
|
# MastraJwtAuth Class
|
|
4
2
|
|
|
5
3
|
The `MastraJwtAuth` class provides a lightweight authentication mechanism for Mastra using JSON Web Tokens (JWTs). It verifies incoming requests based on a shared secret and integrates with the Mastra server using the `auth` option.
|
|
@@ -8,15 +6,35 @@ The `MastraJwtAuth` class provides a lightweight authentication mechanism for Ma
|
|
|
8
6
|
|
|
9
7
|
Before you can use the `MastraJwtAuth` class you have to install the `@mastra/auth` package.
|
|
10
8
|
|
|
9
|
+
**npm**:
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install @mastra/auth@latest
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
**pnpm**:
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
pnpm add @mastra/auth@latest
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
**Yarn**:
|
|
22
|
+
|
|
11
23
|
```bash
|
|
12
|
-
|
|
24
|
+
yarn add @mastra/auth@latest
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
**Bun**:
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
bun add @mastra/auth@latest
|
|
13
31
|
```
|
|
14
32
|
|
|
15
33
|
## Usage example
|
|
16
34
|
|
|
17
|
-
```typescript
|
|
18
|
-
import { Mastra } from
|
|
19
|
-
import { MastraJwtAuth } from
|
|
35
|
+
```typescript
|
|
36
|
+
import { Mastra } from '@mastra/core'
|
|
37
|
+
import { MastraJwtAuth } from '@mastra/auth'
|
|
20
38
|
|
|
21
39
|
export const mastra = new Mastra({
|
|
22
40
|
server: {
|
|
@@ -24,67 +42,60 @@ export const mastra = new Mastra({
|
|
|
24
42
|
secret: process.env.MASTRA_JWT_SECRET,
|
|
25
43
|
}),
|
|
26
44
|
},
|
|
27
|
-
})
|
|
45
|
+
})
|
|
28
46
|
```
|
|
29
47
|
|
|
30
|
-
> **
|
|
31
|
-
|
|
32
|
-
Visit [MastraJwtAuth](https://mastra.ai/reference/v1/auth/jwt) for all available configuration options.
|
|
48
|
+
> **Info:** Visit [MastraJwtAuth](https://mastra.ai/reference/auth/jwt) for all available configuration options.
|
|
33
49
|
|
|
34
50
|
## Configuring `MastraClient`
|
|
35
51
|
|
|
36
52
|
When `auth` is enabled, all requests made with `MastraClient` must include a valid JWT in the `Authorization` header:
|
|
37
53
|
|
|
38
|
-
```typescript
|
|
39
|
-
import { MastraClient } from
|
|
54
|
+
```typescript
|
|
55
|
+
import { MastraClient } from '@mastra/client-js'
|
|
40
56
|
|
|
41
57
|
export const mastraClient = new MastraClient({
|
|
42
|
-
baseUrl:
|
|
58
|
+
baseUrl: 'https://<mastra-api-url>',
|
|
43
59
|
headers: {
|
|
44
60
|
Authorization: `Bearer ${process.env.MASTRA_JWT_TOKEN}`,
|
|
45
61
|
},
|
|
46
|
-
})
|
|
62
|
+
})
|
|
47
63
|
```
|
|
48
64
|
|
|
49
|
-
> **
|
|
50
|
-
|
|
51
|
-
Visit [Mastra Client SDK](https://mastra.ai/docs/v1/server/mastra-client) for more configuration options.
|
|
65
|
+
> **Info:** Visit [Mastra Client SDK](https://mastra.ai/docs/server/mastra-client) for more configuration options.
|
|
52
66
|
|
|
53
67
|
### Making authenticated requests
|
|
54
68
|
|
|
55
69
|
Once `MastraClient` is configured, you can send authenticated requests from your frontend application, or use `curl` for quick local testing:
|
|
56
70
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
```tsx title="src/components/test-agent.tsx" copy
|
|
60
|
-
import { mastraClient } from "../../lib/mastra-client";
|
|
71
|
+
**React**:
|
|
61
72
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
const agent = mastraClient.getAgent("weatherAgent");
|
|
73
|
+
```tsx
|
|
74
|
+
import { mastraClient } from '../../lib/mastra-client'
|
|
65
75
|
|
|
66
|
-
|
|
76
|
+
export const TestAgent = () => {
|
|
77
|
+
async function handleClick() {
|
|
78
|
+
const agent = mastraClient.getAgent('weatherAgent')
|
|
67
79
|
|
|
68
|
-
|
|
69
|
-
}
|
|
80
|
+
const response = await agent.generate('Weather in London')
|
|
70
81
|
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
```
|
|
82
|
+
console.log(response)
|
|
83
|
+
}
|
|
74
84
|
|
|
75
|
-
|
|
76
|
-
|
|
85
|
+
return <button onClick={handleClick}>Test Agent</button>
|
|
86
|
+
}
|
|
87
|
+
```
|
|
77
88
|
|
|
78
|
-
|
|
79
|
-
curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \
|
|
80
|
-
-H "Content-Type: application/json" \
|
|
81
|
-
-H "Authorization: Bearer <your-jwt>" \
|
|
82
|
-
-d '{
|
|
83
|
-
"messages": "Weather in London"
|
|
84
|
-
}'
|
|
85
|
-
```
|
|
89
|
+
**cURL**:
|
|
86
90
|
|
|
87
|
-
|
|
91
|
+
```bash
|
|
92
|
+
curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \
|
|
93
|
+
-H "Content-Type: application/json" \
|
|
94
|
+
-H "Authorization: Bearer <your-jwt>" \
|
|
95
|
+
-d '{
|
|
96
|
+
"messages": "Weather in London"
|
|
97
|
+
}'
|
|
98
|
+
```
|
|
88
99
|
|
|
89
100
|
## Creating a JWT
|
|
90
101
|
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# Auth Overview
|
|
2
|
+
|
|
3
|
+
Mastra lets you choose how you handle authentication, so you can secure access to your application's endpoints using the identity system that fits your stack.
|
|
4
|
+
|
|
5
|
+
You can start with simple shared secret JWT authentication and switch to providers like Supabase, Firebase Auth, Auth0, Clerk, or WorkOS when you need more advanced identity features.
|
|
6
|
+
|
|
7
|
+
## Default behavior
|
|
8
|
+
|
|
9
|
+
Authentication is optional in Mastra. When you configure authentication:
|
|
10
|
+
|
|
11
|
+
- **All built-in API routes** (`/api/agents/*`, `/api/workflows/*`, etc.) require authentication by default
|
|
12
|
+
- **Custom API routes** also require authentication by default
|
|
13
|
+
- **Public access** can be enabled on custom routes using `requiresAuth: false`
|
|
14
|
+
|
|
15
|
+
If no authentication is configured, all routes are publicly accessible.
|
|
16
|
+
|
|
17
|
+
See [Custom API Routes](https://mastra.ai/docs/server/custom-api-routes) for controlling authentication on custom endpoints.
|
|
18
|
+
|
|
19
|
+
## Available providers
|
|
20
|
+
|
|
21
|
+
### Built-in
|
|
22
|
+
|
|
23
|
+
- [Simple Auth](https://mastra.ai/docs/server/auth/simple-auth) - Token-to-user mapping for development and API keys
|
|
24
|
+
- [JSON Web Token (JWT)](https://mastra.ai/docs/server/auth/jwt) - HMAC-signed JWT verification
|
|
25
|
+
|
|
26
|
+
### Third-party integrations
|
|
27
|
+
|
|
28
|
+
- [Auth0](https://mastra.ai/docs/server/auth/auth0)
|
|
29
|
+
- [Better Auth](https://mastra.ai/docs/server/auth/better-auth)
|
|
30
|
+
- [Clerk](https://mastra.ai/docs/server/auth/clerk)
|
|
31
|
+
- [Firebase](https://mastra.ai/docs/server/auth/firebase)
|
|
32
|
+
- [Supabase](https://mastra.ai/docs/server/auth/supabase)
|
|
33
|
+
- [WorkOS](https://mastra.ai/docs/server/auth/workos)
|
|
34
|
+
|
|
35
|
+
### Advanced
|
|
36
|
+
|
|
37
|
+
- [Composite Auth](https://mastra.ai/docs/server/auth/composite-auth) - Combine multiple auth providers
|
|
38
|
+
- [Custom Auth Provider](https://mastra.ai/docs/server/auth/custom-auth-provider) - Build your own provider
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# MastraJwtAuth Class
|
|
2
|
+
|
|
3
|
+
The `MastraJwtAuth` class provides a lightweight authentication mechanism for Mastra using JSON Web Tokens (JWTs). It verifies incoming requests based on a shared secret and integrates with the Mastra server using the `auth` option.
|
|
4
|
+
|
|
5
|
+
## Usage example
|
|
6
|
+
|
|
7
|
+
```typescript
|
|
8
|
+
import { Mastra } from '@mastra/core'
|
|
9
|
+
import { MastraJwtAuth } from '@mastra/auth'
|
|
10
|
+
|
|
11
|
+
export const mastra = new Mastra({
|
|
12
|
+
server: {
|
|
13
|
+
auth: new MastraJwtAuth({
|
|
14
|
+
secret: '<your-secret>',
|
|
15
|
+
}),
|
|
16
|
+
},
|
|
17
|
+
})
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Constructor parameters
|
|
21
|
+
|
|
22
|
+
**secret** (`string`): A unique string used to sign and verify JSON Web Tokens (JWTs) for authenticating incoming requests.
|
|
23
|
+
|
|
24
|
+
## Related
|
|
25
|
+
|
|
26
|
+
[MastraJwtAuth](https://mastra.ai/docs/server/auth/jwt)
|
package/dist/index.cjs
CHANGED
|
@@ -33,7 +33,7 @@ async function verifyJwks(accessToken, jwksUri) {
|
|
|
33
33
|
return jwt__default.default.verify(accessToken, signingKey);
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
-
// ../core/dist/chunk-
|
|
36
|
+
// ../core/dist/chunk-X2WMFSPB.js
|
|
37
37
|
var RegisteredLogger = {
|
|
38
38
|
LLM: "LLM"};
|
|
39
39
|
var LogLevel = {
|
|
@@ -121,16 +121,36 @@ var ConsoleLogger = class extends MastraLogger {
|
|
|
121
121
|
}
|
|
122
122
|
};
|
|
123
123
|
|
|
124
|
-
// ../core/dist/chunk-
|
|
124
|
+
// ../core/dist/chunk-WCAFTXGK.js
|
|
125
125
|
var MastraBase = class {
|
|
126
126
|
component = RegisteredLogger.LLM;
|
|
127
127
|
logger;
|
|
128
128
|
name;
|
|
129
|
-
|
|
129
|
+
#rawConfig;
|
|
130
|
+
constructor({
|
|
131
|
+
component,
|
|
132
|
+
name,
|
|
133
|
+
rawConfig
|
|
134
|
+
}) {
|
|
130
135
|
this.component = component || RegisteredLogger.LLM;
|
|
131
136
|
this.name = name;
|
|
137
|
+
this.#rawConfig = rawConfig;
|
|
132
138
|
this.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });
|
|
133
139
|
}
|
|
140
|
+
/**
|
|
141
|
+
* Returns the raw storage configuration this primitive was created from,
|
|
142
|
+
* or undefined if it was created from code.
|
|
143
|
+
*/
|
|
144
|
+
toRawConfig() {
|
|
145
|
+
return this.#rawConfig;
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Sets the raw storage configuration for this primitive.
|
|
149
|
+
* @internal
|
|
150
|
+
*/
|
|
151
|
+
__setRawConfig(rawConfig) {
|
|
152
|
+
this.#rawConfig = rawConfig;
|
|
153
|
+
}
|
|
134
154
|
/**
|
|
135
155
|
* Set the logger for the agent
|
|
136
156
|
* @param logger
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils.ts","../../core/src/logger/constants.ts","../../core/src/logger/logger.ts","../../core/src/logger/default-logger.ts","../../core/src/base.ts","../../core/src/server/auth.ts","../src/jwt.ts"],"names":["jwt","jwksClient"],"mappings":";;;;;;;;;;;AAKA,eAAsB,YAAY,WAAA,EAAqB;AACrD,EAAA,MAAM,UAAUA,oBAAA,CAAI,MAAA,CAAO,aAAa,EAAE,QAAA,EAAU,MAAM,CAAA;AAC1D,EAAA,OAAO,OAAA;AACT;AAEO,SAAS,eAAe,OAAA,EAAgC;AAC7D,EAAA,IAAI,CAAC,OAAA,EAAS,MAAM,IAAI,MAAM,eAAe,CAAA;AAC7C,EAAA,IAAI,CAAC,OAAA,CAAQ,OAAA,IA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IAAI,MAAM,SAAA,EAAW;AACnB,MAAA,IAAA,CAAK,YAAY,IAAA,CAAK,SAAA;AACxB,IAAA;AACA,IAAA,IAAI,MAAM,MAAA,EAAQ;AAChB,MAAA,IAAA,CAAK,SAAS,IAAA,CAAK,MAAA;AACrB,IAAA;AACF,EAAA;AACF,CAAA;AChDO,IAAM,aAAA,GAAN,cAA4B,kBAAA,CAA4B;AAAA,EACnD,MAAA;AAAA,EAEV,YAAY,OAAA,EAAgC;AAC1C,IAAA,KAAA,CAAM,EAAE,IAAA,EAAM,OAAA,EAAS,IAAA,IAAQ,OAAO,CAAA;AAEtC,IAAA,IAAA,CAAK,MAAA,GAAS,OAAA,EAAS,MAAA,IAAU,OAAA,CAAQ,IAAI,eAAA,IAAmB,EAAA;AAEhE,IAAA,IAAI,CAAC,KAAK,MAAA,EAAQ;AAChB,MAAA,MAAM,IAAI,MAAM,6BAA6B,CAAA;AAAA,IAC/C;AAEA,IAAA,IAAA,CAAK,gBAAgB,OAAO,CAAA;AAAA,EAC9B;AAAA,EAEA,MAAM,kBAAkB,KAAA,EAAiC;AACvD,IAAA,OAAOA,oBAAAA,CAAI,MAAA,CAAO,KAAA,EAAO,IAAA,CAAK,MAAM,CAAA;AAAA,EACtC;AAAA,EAEA,MAAM,cAAc,IAAA,EAAe;AACjC,IAAA,OAAO,CAAC,CAAC,IAAA;AAAA,EACX;AACF","file":"index.cjs","sourcesContent":["import jwt from 'jsonwebtoken';\nimport jwksClient from 'jwks-rsa';\n\nexport type JwtPayload = jwt.JwtPayload;\n\nexport async function decodeToken(accessToken: string) {\n const decoded = jwt.decode(accessToken, { complete: true });\n return decoded;\n}\n\nexport function getTokenIssuer(decoded: jwt.JwtPayload | null) {\n if (!decoded) throw new Error('Invalid token');\n if (!decoded.payload || typeof decoded.payload !== 'object') throw new Error('Invalid token payload');\n if (!decoded.payload.iss) throw new Error('Invalid token header');\n return decoded.payload.iss;\n}\n\nexport async function verifyHmac(accessToken: string, secret: string) {\n const decoded = jwt.decode(accessToken, { complete: true });\n\n if (!decoded) throw new Error('Invalid token');\n\n return jwt.verify(accessToken, secret) as jwt.JwtPayload;\n}\n\nexport async function verifyJwks(accessToken: string, jwksUri: string) {\n const decoded = jwt.decode(accessToken, { complete: true });\n\n if (!decoded) throw new Error('Invalid token');\n\n const client = jwksClient({ jwksUri });\n const key = await client.getSigningKey(decoded.header.kid);\n const signingKey = key.getPublicKey();\n return jwt.verify(accessToken, signingKey) as jwt.JwtPayload;\n}\n","// Constants and Types (keeping from original implementation)\nexport const RegisteredLogger = {\n AGENT: 'AGENT',\n OBSERVABILITY: 'OBSERVABILITY',\n AUTH: 'AUTH',\n NETWORK: 'NETWORK',\n WORKFLOW: 'WORKFLOW',\n LLM: 'LLM',\n TTS: 'TTS',\n VOICE: 'VOICE',\n VECTOR: 'VECTOR',\n BUNDLER: 'BUNDLER',\n DEPLOYER: 'DEPLOYER',\n MEMORY: 'MEMORY',\n STORAGE: 'STORAGE',\n EMBEDDINGS: 'EMBEDDINGS',\n MCP_SERVER: 'MCP_SERVER',\n SERVER_CACHE: 'SERVER_CACHE',\n SERVER: 'SERVER',\n} as const;\n\nexport type RegisteredLogger = (typeof RegisteredLogger)[keyof typeof RegisteredLogger];\n\nexport const LogLevel = {\n DEBUG: 'debug',\n INFO: 'info',\n WARN: 'warn',\n ERROR: 'error',\n NONE: 'silent',\n} as const;\n\nexport type LogLevel = (typeof LogLevel)[keyof typeof LogLevel];\n","import type { MastraError } from '../error';\nimport { LogLevel } from './constants';\nimport type { BaseLogMessage, LoggerTransport } from './transport';\n\nexport interface IMastraLogger {\n debug(message: string, ...args: any[]): void;\n info(message: string, ...args: any[]): void;\n warn(message: string, ...args: any[]): void;\n error(message: string, ...args: any[]): void;\n trackException(error: MastraError): void;\n\n getTransports(): Map<string, LoggerTransport>;\n listLogs(\n _transportId: string,\n _params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n },\n ): Promise<{ logs: BaseLogMessage[]; total: number; page: number; perPage: number; hasMore: boolean }>;\n listLogsByRunId(_args: {\n transportId: string;\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }): Promise<{ logs: BaseLogMessage[]; total: number; page: number; perPage: number; hasMore: boolean }>;\n}\n\nexport abstract class MastraLogger implements IMastraLogger {\n protected name: string;\n protected level: LogLevel;\n protected transports: Map<string, LoggerTransport>;\n\n constructor(\n options: {\n name?: string;\n level?: LogLevel;\n transports?: Record<string, LoggerTransport>;\n } = {},\n ) {\n this.name = options.name || 'Mastra';\n this.level = options.level || LogLevel.ERROR;\n this.transports = new Map(Object.entries(options.transports || {}));\n }\n\n abstract debug(message: string, ...args: any[]): void;\n abstract info(message: string, ...args: any[]): void;\n abstract warn(message: string, ...args: any[]): void;\n abstract error(message: string, ...args: any[]): void;\n\n getTransports() {\n return this.transports;\n }\n\n trackException(_error: MastraError) {}\n\n async listLogs(\n transportId: string,\n params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n },\n ) {\n if (!transportId || !this.transports.has(transportId)) {\n return { logs: [], total: 0, page: params?.page ?? 1, perPage: params?.perPage ?? 100, hasMore: false };\n }\n\n return (\n this.transports.get(transportId)!.listLogs(params) ?? {\n logs: [],\n total: 0,\n page: params?.page ?? 1,\n perPage: params?.perPage ?? 100,\n hasMore: false,\n }\n );\n }\n\n async listLogsByRunId({\n transportId,\n runId,\n fromDate,\n toDate,\n logLevel,\n filters,\n page,\n perPage,\n }: {\n transportId: string;\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }) {\n if (!transportId || !this.transports.has(transportId) || !runId) {\n return { logs: [], total: 0, page: page ?? 1, perPage: perPage ?? 100, hasMore: false };\n }\n\n return (\n this.transports\n .get(transportId)!\n .listLogsByRunId({ runId, fromDate, toDate, logLevel, filters, page, perPage }) ?? {\n logs: [],\n total: 0,\n page: page ?? 1,\n perPage: perPage ?? 100,\n hasMore: false,\n }\n );\n }\n}\n","import { LogLevel } from './constants';\nimport { MastraLogger } from './logger';\nimport type { LoggerTransport } from './transport';\n\nexport const createLogger = (options: {\n name?: string;\n level?: LogLevel;\n transports?: Record<string, LoggerTransport>;\n}) => {\n const logger = new ConsoleLogger(options);\n\n logger.warn(`createLogger is deprecated. Please use \"new ConsoleLogger()\" from \"@mastra/core/logger\" instead.`);\n\n return logger;\n};\n\nexport class ConsoleLogger extends MastraLogger {\n constructor(\n options: {\n name?: string;\n level?: LogLevel;\n } = {},\n ) {\n super(options);\n }\n\n debug(message: string, ...args: any[]): void {\n if (this.level === LogLevel.DEBUG) {\n console.info(message, ...args);\n }\n }\n\n info(message: string, ...args: any[]): void {\n if (this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) {\n console.info(message, ...args);\n }\n }\n\n warn(message: string, ...args: any[]): void {\n if (this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) {\n console.info(message, ...args);\n }\n }\n\n error(message: string, ...args: any[]): void {\n if (\n this.level === LogLevel.ERROR ||\n this.level === LogLevel.WARN ||\n this.level === LogLevel.INFO ||\n this.level === LogLevel.DEBUG\n ) {\n console.error(message, ...args);\n }\n }\n\n async listLogs(\n _transportId: string,\n _params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n },\n ) {\n return { logs: [], total: 0, page: _params?.page ?? 1, perPage: _params?.perPage ?? 100, hasMore: false };\n }\n\n async listLogsByRunId(_args: {\n transportId: string;\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }) {\n return { logs: [], total: 0, page: _args.page ?? 1, perPage: _args.perPage ?? 100, hasMore: false };\n }\n}\n","import type { IMastraLogger } from './logger';\nimport { RegisteredLogger } from './logger/constants';\nimport { ConsoleLogger } from './logger/default-logger';\n\nexport class MastraBase {\n component: RegisteredLogger = RegisteredLogger.LLM;\n protected logger: IMastraLogger;\n name?: string;\n\n constructor({ component, name }: { component?: RegisteredLogger; name?: string }) {\n this.component = component || RegisteredLogger.LLM;\n this.name = name;\n this.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });\n }\n\n /**\n * Set the logger for the agent\n * @param logger\n */\n __setLogger(logger: IMastraLogger) {\n this.logger = logger;\n\n if (this.component !== RegisteredLogger.LLM) {\n this.logger.debug(`Logger updated [component=${this.component}] [name=${this.name}]`);\n }\n }\n}\n\nexport * from './types';\n","import type { HonoRequest } from 'hono';\nimport { MastraBase } from '../base';\nimport type { MastraAuthConfig } from './types';\n\nexport interface MastraAuthProviderOptions<TUser = unknown> {\n name?: string;\n authorizeUser?: (user: TUser, request: HonoRequest) => Promise<boolean> | boolean;\n /**\n * Protected paths for the auth provider\n */\n protected?: MastraAuthConfig['protected'];\n /**\n * Public paths for the auth provider\n */\n public?: MastraAuthConfig['public'];\n}\n\nexport abstract class MastraAuthProvider<TUser = unknown> extends MastraBase {\n public protected?: MastraAuthConfig['protected'];\n public public?: MastraAuthConfig['public'];\n\n constructor(options?: MastraAuthProviderOptions<TUser>) {\n super({ component: 'AUTH', name: options?.name });\n\n if (options?.authorizeUser) {\n this.authorizeUser = options.authorizeUser.bind(this);\n }\n\n this.protected = options?.protected;\n this.public = options?.public;\n }\n\n /**\n * Authenticate a token and return the payload\n * @param token - The token to authenticate\n * @param request - The request\n * @returns The payload\n */\n abstract authenticateToken(token: string, request: HonoRequest): Promise<TUser | null>;\n\n /**\n * Authorize a user for a path and method\n * @param user - The user to authorize\n * @param request - The request\n * @returns The authorization result\n */\n abstract authorizeUser(user: TUser, request: HonoRequest): Promise<boolean> | boolean;\n\n protected registerOptions(opts?: MastraAuthProviderOptions<TUser>) {\n if (opts?.authorizeUser) {\n this.authorizeUser = opts.authorizeUser.bind(this);\n }\n if (opts?.protected) {\n this.protected = opts.protected;\n }\n if (opts?.public) {\n this.public = opts.public;\n }\n }\n}\n","import { MastraAuthProvider } from '@mastra/core/server';\nimport type { MastraAuthProviderOptions } from '@mastra/core/server';\n\nimport jwt from 'jsonwebtoken';\n\ntype JwtUser = jwt.JwtPayload;\n\ninterface MastraJwtAuthOptions extends MastraAuthProviderOptions<JwtUser> {\n secret?: string;\n}\n\nexport class MastraJwtAuth extends MastraAuthProvider<JwtUser> {\n protected secret: string;\n\n constructor(options?: MastraJwtAuthOptions) {\n super({ name: options?.name ?? 'jwt' });\n\n this.secret = options?.secret ?? process.env.JWT_AUTH_SECRET ?? '';\n\n if (!this.secret) {\n throw new Error('JWT auth secret is required');\n }\n\n this.registerOptions(options);\n }\n\n async authenticateToken(token: string): Promise<JwtUser> {\n return jwt.verify(token, this.secret) as JwtUser;\n }\n\n async authorizeUser(user: JwtUser) {\n return !!user;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/utils.ts","../../core/src/logger/constants.ts","../../core/src/logger/logger.ts","../../core/src/logger/default-logger.ts","../../core/src/base.ts","../../core/src/server/auth.ts","../src/jwt.ts"],"names":["jwt","jwksClient"],"mappings":";;;;;;;;;;;AAKA,eAAsB,YAAY,WAAA,EAAqB;AACrD,EAAA,MAAM,UAAUA,oBAAA,CAAI,MAAA,CAAO,aAAa,EAAE,QAAA,EAAU,MAAM,CAAA;AAC1D,EAAA,OAAO,OAAA;AACT;AAEO,SAAS,eAAe,OAAA,EAAgC;AAC7D,EAAA,IAAI,CAAC,OAAA,EAAS,MAAM,IAAI,MAAM,eAAe,CAAA;AAC7C,EAAA,IAAI,CAAC,OAAA,CAAQ,OAAA,IAAW,OAAO,OAAA,CAAQ,YAAY,QAAA,EAAU,MAAM,IAAI,KAAA,CAAM,uBAAuB,CAAA;AACpG,EAAA,IAAI,CAAC,OAAA,CAAQ,OAAA,CAAQ,KAAK,MAAM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B,MAAA,IAAA,CAAK,aAAA,GAAgB,IAAA,CAAK,aAAA,CAAc,IAAA,CAAK,IAAI,CAAA;AACnD,IAAA;AACA,IAAA,IAAI,MAAM,SAAA,EAAW;AACnB,MAAA,IAAA,CAAK,YAAY,IAAA,CAAK,SAAA;AACxB,IAAA;AACA,IAAA,IAAI,MAAM,MAAA,EAAQ;AAChB,MAAA,IAAA,CAAK,SAAS,IAAA,CAAK,MAAA;AACrB,IAAA;AACF,EAAA;AACF,CAAA;AChDO,IAAM,aAAA,GAAN,cAA4B,kBAAA,CAA4B;AAAA,EACnD,MAAA;AAAA,EAEV,YAAY,OAAA,EAAgC;AAC1C,IAAA,KAAA,CAAM,EAAE,IAAA,EAAM,OAAA,EAAS,IAAA,IAAQ,OAAO,CAAA;AAEtC,IAAA,IAAA,CAAK,MAAA,GAAS,OAAA,EAAS,MAAA,IAAU,OAAA,CAAQ,IAAI,eAAA,IAAmB,EAAA;AAEhE,IAAA,IAAI,CAAC,KAAK,MAAA,EAAQ;AAChB,MAAA,MAAM,IAAI,MAAM,6BAA6B,CAAA;AAAA,IAC/C;AAEA,IAAA,IAAA,CAAK,gBAAgB,OAAO,CAAA;AAAA,EAC9B;AAAA,EAEA,MAAM,kBAAkB,KAAA,EAAiC;AACvD,IAAA,OAAOA,oBAAAA,CAAI,MAAA,CAAO,KAAA,EAAO,IAAA,CAAK,MAAM,CAAA;AAAA,EACtC;AAAA,EAEA,MAAM,cAAc,IAAA,EAAe;AACjC,IAAA,OAAO,CAAC,CAAC,IAAA;AAAA,EACX;AACF","file":"index.cjs","sourcesContent":["import jwt from 'jsonwebtoken';\nimport jwksClient from 'jwks-rsa';\n\nexport type JwtPayload = jwt.JwtPayload;\n\nexport async function decodeToken(accessToken: string) {\n const decoded = jwt.decode(accessToken, { complete: true });\n return decoded;\n}\n\nexport function getTokenIssuer(decoded: jwt.JwtPayload | null) {\n if (!decoded) throw new Error('Invalid token');\n if (!decoded.payload || typeof decoded.payload !== 'object') throw new Error('Invalid token payload');\n if (!decoded.payload.iss) throw new Error('Invalid token header');\n return decoded.payload.iss;\n}\n\nexport async function verifyHmac(accessToken: string, secret: string) {\n const decoded = jwt.decode(accessToken, { complete: true });\n\n if (!decoded) throw new Error('Invalid token');\n\n return jwt.verify(accessToken, secret) as jwt.JwtPayload;\n}\n\nexport async function verifyJwks(accessToken: string, jwksUri: string) {\n const decoded = jwt.decode(accessToken, { complete: true });\n\n if (!decoded) throw new Error('Invalid token');\n\n const client = jwksClient({ jwksUri });\n const key = await client.getSigningKey(decoded.header.kid);\n const signingKey = key.getPublicKey();\n return jwt.verify(accessToken, signingKey) as jwt.JwtPayload;\n}\n","// Constants and Types (keeping from original implementation)\nexport const RegisteredLogger = {\n AGENT: 'AGENT',\n OBSERVABILITY: 'OBSERVABILITY',\n AUTH: 'AUTH',\n NETWORK: 'NETWORK',\n WORKFLOW: 'WORKFLOW',\n LLM: 'LLM',\n TTS: 'TTS',\n VOICE: 'VOICE',\n VECTOR: 'VECTOR',\n BUNDLER: 'BUNDLER',\n DEPLOYER: 'DEPLOYER',\n MEMORY: 'MEMORY',\n STORAGE: 'STORAGE',\n EMBEDDINGS: 'EMBEDDINGS',\n MCP_SERVER: 'MCP_SERVER',\n SERVER_CACHE: 'SERVER_CACHE',\n SERVER: 'SERVER',\n WORKSPACE: 'WORKSPACE',\n} as const;\n\nexport type RegisteredLogger = (typeof RegisteredLogger)[keyof typeof RegisteredLogger];\n\nexport const LogLevel = {\n DEBUG: 'debug',\n INFO: 'info',\n WARN: 'warn',\n ERROR: 'error',\n NONE: 'silent',\n} as const;\n\nexport type LogLevel = (typeof LogLevel)[keyof typeof LogLevel];\n","import type { MastraError } from '../error';\nimport { LogLevel } from './constants';\nimport type { BaseLogMessage, LoggerTransport } from './transport';\n\nexport interface IMastraLogger {\n debug(message: string, ...args: any[]): void;\n info(message: string, ...args: any[]): void;\n warn(message: string, ...args: any[]): void;\n error(message: string, ...args: any[]): void;\n trackException(error: MastraError): void;\n\n getTransports(): Map<string, LoggerTransport>;\n listLogs(\n _transportId: string,\n _params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n },\n ): Promise<{ logs: BaseLogMessage[]; total: number; page: number; perPage: number; hasMore: boolean }>;\n listLogsByRunId(_args: {\n transportId: string;\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }): Promise<{ logs: BaseLogMessage[]; total: number; page: number; perPage: number; hasMore: boolean }>;\n}\n\nexport abstract class MastraLogger implements IMastraLogger {\n protected name: string;\n protected level: LogLevel;\n protected transports: Map<string, LoggerTransport>;\n\n constructor(\n options: {\n name?: string;\n level?: LogLevel;\n transports?: Record<string, LoggerTransport>;\n } = {},\n ) {\n this.name = options.name || 'Mastra';\n this.level = options.level || LogLevel.ERROR;\n this.transports = new Map(Object.entries(options.transports || {}));\n }\n\n abstract debug(message: string, ...args: any[]): void;\n abstract info(message: string, ...args: any[]): void;\n abstract warn(message: string, ...args: any[]): void;\n abstract error(message: string, ...args: any[]): void;\n\n getTransports() {\n return this.transports;\n }\n\n trackException(_error: MastraError) {}\n\n async listLogs(\n transportId: string,\n params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n },\n ) {\n if (!transportId || !this.transports.has(transportId)) {\n return { logs: [], total: 0, page: params?.page ?? 1, perPage: params?.perPage ?? 100, hasMore: false };\n }\n\n return (\n this.transports.get(transportId)!.listLogs(params) ?? {\n logs: [],\n total: 0,\n page: params?.page ?? 1,\n perPage: params?.perPage ?? 100,\n hasMore: false,\n }\n );\n }\n\n async listLogsByRunId({\n transportId,\n runId,\n fromDate,\n toDate,\n logLevel,\n filters,\n page,\n perPage,\n }: {\n transportId: string;\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }) {\n if (!transportId || !this.transports.has(transportId) || !runId) {\n return { logs: [], total: 0, page: page ?? 1, perPage: perPage ?? 100, hasMore: false };\n }\n\n return (\n this.transports\n .get(transportId)!\n .listLogsByRunId({ runId, fromDate, toDate, logLevel, filters, page, perPage }) ?? {\n logs: [],\n total: 0,\n page: page ?? 1,\n perPage: perPage ?? 100,\n hasMore: false,\n }\n );\n }\n}\n","import { LogLevel } from './constants';\nimport { MastraLogger } from './logger';\nimport type { LoggerTransport } from './transport';\n\nexport const createLogger = (options: {\n name?: string;\n level?: LogLevel;\n transports?: Record<string, LoggerTransport>;\n}) => {\n const logger = new ConsoleLogger(options);\n\n logger.warn(`createLogger is deprecated. Please use \"new ConsoleLogger()\" from \"@mastra/core/logger\" instead.`);\n\n return logger;\n};\n\nexport class ConsoleLogger extends MastraLogger {\n constructor(\n options: {\n name?: string;\n level?: LogLevel;\n } = {},\n ) {\n super(options);\n }\n\n debug(message: string, ...args: any[]): void {\n if (this.level === LogLevel.DEBUG) {\n console.info(message, ...args);\n }\n }\n\n info(message: string, ...args: any[]): void {\n if (this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) {\n console.info(message, ...args);\n }\n }\n\n warn(message: string, ...args: any[]): void {\n if (this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) {\n console.info(message, ...args);\n }\n }\n\n error(message: string, ...args: any[]): void {\n if (\n this.level === LogLevel.ERROR ||\n this.level === LogLevel.WARN ||\n this.level === LogLevel.INFO ||\n this.level === LogLevel.DEBUG\n ) {\n console.error(message, ...args);\n }\n }\n\n async listLogs(\n _transportId: string,\n _params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n },\n ) {\n return { logs: [], total: 0, page: _params?.page ?? 1, perPage: _params?.perPage ?? 100, hasMore: false };\n }\n\n async listLogsByRunId(_args: {\n transportId: string;\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }) {\n return { logs: [], total: 0, page: _args.page ?? 1, perPage: _args.perPage ?? 100, hasMore: false };\n }\n}\n","import type { IMastraLogger } from './logger';\nimport { RegisteredLogger } from './logger/constants';\nimport { ConsoleLogger } from './logger/default-logger';\n\nexport class MastraBase {\n component: RegisteredLogger = RegisteredLogger.LLM;\n protected logger: IMastraLogger;\n name?: string;\n #rawConfig?: Record<string, unknown>;\n\n constructor({\n component,\n name,\n rawConfig,\n }: {\n component?: RegisteredLogger;\n name?: string;\n rawConfig?: Record<string, unknown>;\n }) {\n this.component = component || RegisteredLogger.LLM;\n this.name = name;\n this.#rawConfig = rawConfig;\n this.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });\n }\n\n /**\n * Returns the raw storage configuration this primitive was created from,\n * or undefined if it was created from code.\n */\n toRawConfig(): Record<string, unknown> | undefined {\n return this.#rawConfig;\n }\n\n /**\n * Sets the raw storage configuration for this primitive.\n * @internal\n */\n __setRawConfig(rawConfig: Record<string, unknown>): void {\n this.#rawConfig = rawConfig;\n }\n\n /**\n * Set the logger for the agent\n * @param logger\n */\n __setLogger(logger: IMastraLogger) {\n this.logger = logger;\n\n if (this.component !== RegisteredLogger.LLM) {\n this.logger.debug(`Logger updated [component=${this.component}] [name=${this.name}]`);\n }\n }\n}\n\nexport * from './types';\n","import type { HonoRequest } from 'hono';\nimport { MastraBase } from '../base';\nimport type { MastraAuthConfig } from './types';\n\nexport interface MastraAuthProviderOptions<TUser = unknown> {\n name?: string;\n authorizeUser?: (user: TUser, request: HonoRequest) => Promise<boolean> | boolean;\n /**\n * Protected paths for the auth provider\n */\n protected?: MastraAuthConfig['protected'];\n /**\n * Public paths for the auth provider\n */\n public?: MastraAuthConfig['public'];\n}\n\nexport abstract class MastraAuthProvider<TUser = unknown> extends MastraBase {\n public protected?: MastraAuthConfig['protected'];\n public public?: MastraAuthConfig['public'];\n\n constructor(options?: MastraAuthProviderOptions<TUser>) {\n super({ component: 'AUTH', name: options?.name });\n\n if (options?.authorizeUser) {\n this.authorizeUser = options.authorizeUser.bind(this);\n }\n\n this.protected = options?.protected;\n this.public = options?.public;\n }\n\n /**\n * Authenticate a token and return the payload\n * @param token - The token to authenticate\n * @param request - The request\n * @returns The payload\n */\n abstract authenticateToken(token: string, request: HonoRequest): Promise<TUser | null>;\n\n /**\n * Authorize a user for a path and method\n * @param user - The user to authorize\n * @param request - The request\n * @returns The authorization result\n */\n abstract authorizeUser(user: TUser, request: HonoRequest): Promise<boolean> | boolean;\n\n protected registerOptions(opts?: MastraAuthProviderOptions<TUser>) {\n if (opts?.authorizeUser) {\n this.authorizeUser = opts.authorizeUser.bind(this);\n }\n if (opts?.protected) {\n this.protected = opts.protected;\n }\n if (opts?.public) {\n this.public = opts.public;\n }\n }\n}\n","import { MastraAuthProvider } from '@mastra/core/server';\nimport type { MastraAuthProviderOptions } from '@mastra/core/server';\n\nimport jwt from 'jsonwebtoken';\n\ntype JwtUser = jwt.JwtPayload;\n\ninterface MastraJwtAuthOptions extends MastraAuthProviderOptions<JwtUser> {\n secret?: string;\n}\n\nexport class MastraJwtAuth extends MastraAuthProvider<JwtUser> {\n protected secret: string;\n\n constructor(options?: MastraJwtAuthOptions) {\n super({ name: options?.name ?? 'jwt' });\n\n this.secret = options?.secret ?? process.env.JWT_AUTH_SECRET ?? '';\n\n if (!this.secret) {\n throw new Error('JWT auth secret is required');\n }\n\n this.registerOptions(options);\n }\n\n async authenticateToken(token: string): Promise<JwtUser> {\n return jwt.verify(token, this.secret) as JwtUser;\n }\n\n async authorizeUser(user: JwtUser) {\n return !!user;\n }\n}\n"]}
|
package/dist/index.js
CHANGED
|
@@ -26,7 +26,7 @@ async function verifyJwks(accessToken, jwksUri) {
|
|
|
26
26
|
return jwt.verify(accessToken, signingKey);
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
-
// ../core/dist/chunk-
|
|
29
|
+
// ../core/dist/chunk-X2WMFSPB.js
|
|
30
30
|
var RegisteredLogger = {
|
|
31
31
|
LLM: "LLM"};
|
|
32
32
|
var LogLevel = {
|
|
@@ -114,16 +114,36 @@ var ConsoleLogger = class extends MastraLogger {
|
|
|
114
114
|
}
|
|
115
115
|
};
|
|
116
116
|
|
|
117
|
-
// ../core/dist/chunk-
|
|
117
|
+
// ../core/dist/chunk-WCAFTXGK.js
|
|
118
118
|
var MastraBase = class {
|
|
119
119
|
component = RegisteredLogger.LLM;
|
|
120
120
|
logger;
|
|
121
121
|
name;
|
|
122
|
-
|
|
122
|
+
#rawConfig;
|
|
123
|
+
constructor({
|
|
124
|
+
component,
|
|
125
|
+
name,
|
|
126
|
+
rawConfig
|
|
127
|
+
}) {
|
|
123
128
|
this.component = component || RegisteredLogger.LLM;
|
|
124
129
|
this.name = name;
|
|
130
|
+
this.#rawConfig = rawConfig;
|
|
125
131
|
this.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });
|
|
126
132
|
}
|
|
133
|
+
/**
|
|
134
|
+
* Returns the raw storage configuration this primitive was created from,
|
|
135
|
+
* or undefined if it was created from code.
|
|
136
|
+
*/
|
|
137
|
+
toRawConfig() {
|
|
138
|
+
return this.#rawConfig;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Sets the raw storage configuration for this primitive.
|
|
142
|
+
* @internal
|
|
143
|
+
*/
|
|
144
|
+
__setRawConfig(rawConfig) {
|
|
145
|
+
this.#rawConfig = rawConfig;
|
|
146
|
+
}
|
|
127
147
|
/**
|
|
128
148
|
* Set the logger for the agent
|
|
129
149
|
* @param logger
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils.ts","../../core/src/logger/constants.ts","../../core/src/logger/logger.ts","../../core/src/logger/default-logger.ts","../../core/src/base.ts","../../core/src/server/auth.ts","../src/jwt.ts"],"names":["jwt"],"mappings":";;;;AAKA,eAAsB,YAAY,WAAA,EAAqB;AACrD,EAA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,IAAA,IAAA,CAAK,SAAS,OAAA,EAAS,MAAA;AACzB,EAAA;AAkBU,EAAA,eAAA,CAAgB,IAAA,EAAyC;AACjE,IAAA,IAAI,MAAM,aAAA,EAAe;AACvB,MAAA,IAAA,CAAK,aAAA,GAAgB,IAAA,CAAK,aAAA,CAAc,IAAA,CAAK,IAAI,CAAA;AACnD,IAAA;AACA,IAAA,IAAI,MAAM,SAAA,EAAW;AACnB,MAAA,IAAA,CAAK,YAAY,IAAA,CAAK,SAAA;AACxB,IAAA;AACA,IAAA,IAAI,MAAM,MAAA,EAAQ;AAChB,MAAA,IAAA,CAAK,SAAS,IAAA,CAAK,MAAA;AACrB,IAAA;AACF,EAAA;AACF,CAAA;AChDO,IAAM,aAAA,GAAN,cAA4B,kBAAA,CAA4B;AAAA,EACnD,MAAA;AAAA,EAEV,YAAY,OAAA,EAAgC;AAC1C,IAAA,KAAA,CAAM,EAAE,IAAA,EAAM,OAAA,EAAS,IAAA,IAAQ,OAAO,CAAA;AAEtC,IAAA,IAAA,CAAK,MAAA,GAAS,OAAA,EAAS,MAAA,IAAU,OAAA,CAAQ,IAAI,eAAA,IAAmB,EAAA;AAEhE,IAAA,IAAI,CAAC,KAAK,MAAA,EAAQ;AAChB,MAAA,MAAM,IAAI,MAAM,6BAA6B,CAAA;AAAA,IAC/C;AAEA,IAAA,IAAA,CAAK,gBAAgB,OAAO,CAAA;AAAA,EAC9B;AAAA,EAEA,MAAM,kBAAkB,KAAA,EAAiC;AACvD,IAAA,OAAOA,GAAAA,CAAI,MAAA,CAAO,KAAA,EAAO,IAAA,CAAK,MAAM,CAAA;AAAA,EACtC;AAAA,EAEA,MAAM,cAAc,IAAA,EAAe;AACjC,IAAA,OAAO,CAAC,CAAC,IAAA;AAAA,EACX;AACF","file":"index.js","sourcesContent":["import jwt from 'jsonwebtoken';\nimport jwksClient from 'jwks-rsa';\n\nexport type JwtPayload = jwt.JwtPayload;\n\nexport async function decodeToken(accessToken: string) {\n const decoded = jwt.decode(accessToken, { complete: true });\n return decoded;\n}\n\nexport function getTokenIssuer(decoded: jwt.JwtPayload | null) {\n if (!decoded) throw new Error('Invalid token');\n if (!decoded.payload || typeof decoded.payload !== 'object') throw new Error('Invalid token payload');\n if (!decoded.payload.iss) throw new Error('Invalid token header');\n return decoded.payload.iss;\n}\n\nexport async function verifyHmac(accessToken: string, secret: string) {\n const decoded = jwt.decode(accessToken, { complete: true });\n\n if (!decoded) throw new Error('Invalid token');\n\n return jwt.verify(accessToken, secret) as jwt.JwtPayload;\n}\n\nexport async function verifyJwks(accessToken: string, jwksUri: string) {\n const decoded = jwt.decode(accessToken, { complete: true });\n\n if (!decoded) throw new Error('Invalid token');\n\n const client = jwksClient({ jwksUri });\n const key = await client.getSigningKey(decoded.header.kid);\n const signingKey = key.getPublicKey();\n return jwt.verify(accessToken, signingKey) as jwt.JwtPayload;\n}\n","// Constants and Types (keeping from original implementation)\nexport const RegisteredLogger = {\n AGENT: 'AGENT',\n OBSERVABILITY: 'OBSERVABILITY',\n AUTH: 'AUTH',\n NETWORK: 'NETWORK',\n WORKFLOW: 'WORKFLOW',\n LLM: 'LLM',\n TTS: 'TTS',\n VOICE: 'VOICE',\n VECTOR: 'VECTOR',\n BUNDLER: 'BUNDLER',\n DEPLOYER: 'DEPLOYER',\n MEMORY: 'MEMORY',\n STORAGE: 'STORAGE',\n EMBEDDINGS: 'EMBEDDINGS',\n MCP_SERVER: 'MCP_SERVER',\n SERVER_CACHE: 'SERVER_CACHE',\n SERVER: 'SERVER',\n} as const;\n\nexport type RegisteredLogger = (typeof RegisteredLogger)[keyof typeof RegisteredLogger];\n\nexport const LogLevel = {\n DEBUG: 'debug',\n INFO: 'info',\n WARN: 'warn',\n ERROR: 'error',\n NONE: 'silent',\n} as const;\n\nexport type LogLevel = (typeof LogLevel)[keyof typeof LogLevel];\n","import type { MastraError } from '../error';\nimport { LogLevel } from './constants';\nimport type { BaseLogMessage, LoggerTransport } from './transport';\n\nexport interface IMastraLogger {\n debug(message: string, ...args: any[]): void;\n info(message: string, ...args: any[]): void;\n warn(message: string, ...args: any[]): void;\n error(message: string, ...args: any[]): void;\n trackException(error: MastraError): void;\n\n getTransports(): Map<string, LoggerTransport>;\n listLogs(\n _transportId: string,\n _params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n },\n ): Promise<{ logs: BaseLogMessage[]; total: number; page: number; perPage: number; hasMore: boolean }>;\n listLogsByRunId(_args: {\n transportId: string;\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }): Promise<{ logs: BaseLogMessage[]; total: number; page: number; perPage: number; hasMore: boolean }>;\n}\n\nexport abstract class MastraLogger implements IMastraLogger {\n protected name: string;\n protected level: LogLevel;\n protected transports: Map<string, LoggerTransport>;\n\n constructor(\n options: {\n name?: string;\n level?: LogLevel;\n transports?: Record<string, LoggerTransport>;\n } = {},\n ) {\n this.name = options.name || 'Mastra';\n this.level = options.level || LogLevel.ERROR;\n this.transports = new Map(Object.entries(options.transports || {}));\n }\n\n abstract debug(message: string, ...args: any[]): void;\n abstract info(message: string, ...args: any[]): void;\n abstract warn(message: string, ...args: any[]): void;\n abstract error(message: string, ...args: any[]): void;\n\n getTransports() {\n return this.transports;\n }\n\n trackException(_error: MastraError) {}\n\n async listLogs(\n transportId: string,\n params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n },\n ) {\n if (!transportId || !this.transports.has(transportId)) {\n return { logs: [], total: 0, page: params?.page ?? 1, perPage: params?.perPage ?? 100, hasMore: false };\n }\n\n return (\n this.transports.get(transportId)!.listLogs(params) ?? {\n logs: [],\n total: 0,\n page: params?.page ?? 1,\n perPage: params?.perPage ?? 100,\n hasMore: false,\n }\n );\n }\n\n async listLogsByRunId({\n transportId,\n runId,\n fromDate,\n toDate,\n logLevel,\n filters,\n page,\n perPage,\n }: {\n transportId: string;\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }) {\n if (!transportId || !this.transports.has(transportId) || !runId) {\n return { logs: [], total: 0, page: page ?? 1, perPage: perPage ?? 100, hasMore: false };\n }\n\n return (\n this.transports\n .get(transportId)!\n .listLogsByRunId({ runId, fromDate, toDate, logLevel, filters, page, perPage }) ?? {\n logs: [],\n total: 0,\n page: page ?? 1,\n perPage: perPage ?? 100,\n hasMore: false,\n }\n );\n }\n}\n","import { LogLevel } from './constants';\nimport { MastraLogger } from './logger';\nimport type { LoggerTransport } from './transport';\n\nexport const createLogger = (options: {\n name?: string;\n level?: LogLevel;\n transports?: Record<string, LoggerTransport>;\n}) => {\n const logger = new ConsoleLogger(options);\n\n logger.warn(`createLogger is deprecated. Please use \"new ConsoleLogger()\" from \"@mastra/core/logger\" instead.`);\n\n return logger;\n};\n\nexport class ConsoleLogger extends MastraLogger {\n constructor(\n options: {\n name?: string;\n level?: LogLevel;\n } = {},\n ) {\n super(options);\n }\n\n debug(message: string, ...args: any[]): void {\n if (this.level === LogLevel.DEBUG) {\n console.info(message, ...args);\n }\n }\n\n info(message: string, ...args: any[]): void {\n if (this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) {\n console.info(message, ...args);\n }\n }\n\n warn(message: string, ...args: any[]): void {\n if (this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) {\n console.info(message, ...args);\n }\n }\n\n error(message: string, ...args: any[]): void {\n if (\n this.level === LogLevel.ERROR ||\n this.level === LogLevel.WARN ||\n this.level === LogLevel.INFO ||\n this.level === LogLevel.DEBUG\n ) {\n console.error(message, ...args);\n }\n }\n\n async listLogs(\n _transportId: string,\n _params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n },\n ) {\n return { logs: [], total: 0, page: _params?.page ?? 1, perPage: _params?.perPage ?? 100, hasMore: false };\n }\n\n async listLogsByRunId(_args: {\n transportId: string;\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }) {\n return { logs: [], total: 0, page: _args.page ?? 1, perPage: _args.perPage ?? 100, hasMore: false };\n }\n}\n","import type { IMastraLogger } from './logger';\nimport { RegisteredLogger } from './logger/constants';\nimport { ConsoleLogger } from './logger/default-logger';\n\nexport class MastraBase {\n component: RegisteredLogger = RegisteredLogger.LLM;\n protected logger: IMastraLogger;\n name?: string;\n\n constructor({ component, name }: { component?: RegisteredLogger; name?: string }) {\n this.component = component || RegisteredLogger.LLM;\n this.name = name;\n this.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });\n }\n\n /**\n * Set the logger for the agent\n * @param logger\n */\n __setLogger(logger: IMastraLogger) {\n this.logger = logger;\n\n if (this.component !== RegisteredLogger.LLM) {\n this.logger.debug(`Logger updated [component=${this.component}] [name=${this.name}]`);\n }\n }\n}\n\nexport * from './types';\n","import type { HonoRequest } from 'hono';\nimport { MastraBase } from '../base';\nimport type { MastraAuthConfig } from './types';\n\nexport interface MastraAuthProviderOptions<TUser = unknown> {\n name?: string;\n authorizeUser?: (user: TUser, request: HonoRequest) => Promise<boolean> | boolean;\n /**\n * Protected paths for the auth provider\n */\n protected?: MastraAuthConfig['protected'];\n /**\n * Public paths for the auth provider\n */\n public?: MastraAuthConfig['public'];\n}\n\nexport abstract class MastraAuthProvider<TUser = unknown> extends MastraBase {\n public protected?: MastraAuthConfig['protected'];\n public public?: MastraAuthConfig['public'];\n\n constructor(options?: MastraAuthProviderOptions<TUser>) {\n super({ component: 'AUTH', name: options?.name });\n\n if (options?.authorizeUser) {\n this.authorizeUser = options.authorizeUser.bind(this);\n }\n\n this.protected = options?.protected;\n this.public = options?.public;\n }\n\n /**\n * Authenticate a token and return the payload\n * @param token - The token to authenticate\n * @param request - The request\n * @returns The payload\n */\n abstract authenticateToken(token: string, request: HonoRequest): Promise<TUser | null>;\n\n /**\n * Authorize a user for a path and method\n * @param user - The user to authorize\n * @param request - The request\n * @returns The authorization result\n */\n abstract authorizeUser(user: TUser, request: HonoRequest): Promise<boolean> | boolean;\n\n protected registerOptions(opts?: MastraAuthProviderOptions<TUser>) {\n if (opts?.authorizeUser) {\n this.authorizeUser = opts.authorizeUser.bind(this);\n }\n if (opts?.protected) {\n this.protected = opts.protected;\n }\n if (opts?.public) {\n this.public = opts.public;\n }\n }\n}\n","import { MastraAuthProvider } from '@mastra/core/server';\nimport type { MastraAuthProviderOptions } from '@mastra/core/server';\n\nimport jwt from 'jsonwebtoken';\n\ntype JwtUser = jwt.JwtPayload;\n\ninterface MastraJwtAuthOptions extends MastraAuthProviderOptions<JwtUser> {\n secret?: string;\n}\n\nexport class MastraJwtAuth extends MastraAuthProvider<JwtUser> {\n protected secret: string;\n\n constructor(options?: MastraJwtAuthOptions) {\n super({ name: options?.name ?? 'jwt' });\n\n this.secret = options?.secret ?? process.env.JWT_AUTH_SECRET ?? '';\n\n if (!this.secret) {\n throw new Error('JWT auth secret is required');\n }\n\n this.registerOptions(options);\n }\n\n async authenticateToken(token: string): Promise<JwtUser> {\n return jwt.verify(token, this.secret) as JwtUser;\n }\n\n async authorizeUser(user: JwtUser) {\n return !!user;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/utils.ts","../../core/src/logger/constants.ts","../../core/src/logger/logger.ts","../../core/src/logger/default-logger.ts","../../core/src/base.ts","../../core/src/server/auth.ts","../src/jwt.ts"],"names":["jwt"],"mappings":";;;;AAKA,eAAsB,YAAY,WAAA,EAAqB;AACrD,EAAA,MAAM,UAAU,GAAA,CAAI,MAAA,CAAO,aAAa,EAAE,QAAA,EAAU,MAAM,CAAA;AAC1D,EAAA,OAAO,OAAA;AACT;AAEO,SAAS,eAAe,OAAA,EAAgC;AAC7D,EAAA,IAAI,CAAC,OAAA,EAAS,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n\nexport type JwtPayload = jwt.JwtPayload;\n\nexport async function decodeToken(accessToken: string) {\n const decoded = jwt.decode(accessToken, { complete: true });\n return decoded;\n}\n\nexport function getTokenIssuer(decoded: jwt.JwtPayload | null) {\n if (!decoded) throw new Error('Invalid token');\n if (!decoded.payload || typeof decoded.payload !== 'object') throw new Error('Invalid token payload');\n if (!decoded.payload.iss) throw new Error('Invalid token header');\n return decoded.payload.iss;\n}\n\nexport async function verifyHmac(accessToken: string, secret: string) {\n const decoded = jwt.decode(accessToken, { complete: true });\n\n if (!decoded) throw new Error('Invalid token');\n\n return jwt.verify(accessToken, secret) as jwt.JwtPayload;\n}\n\nexport async function verifyJwks(accessToken: string, jwksUri: string) {\n const decoded = jwt.decode(accessToken, { complete: true });\n\n if (!decoded) throw new Error('Invalid token');\n\n const client = jwksClient({ jwksUri });\n const key = await client.getSigningKey(decoded.header.kid);\n const signingKey = key.getPublicKey();\n return jwt.verify(accessToken, signingKey) as jwt.JwtPayload;\n}\n","// Constants and Types (keeping from original implementation)\nexport const RegisteredLogger = {\n AGENT: 'AGENT',\n OBSERVABILITY: 'OBSERVABILITY',\n AUTH: 'AUTH',\n NETWORK: 'NETWORK',\n WORKFLOW: 'WORKFLOW',\n LLM: 'LLM',\n TTS: 'TTS',\n VOICE: 'VOICE',\n VECTOR: 'VECTOR',\n BUNDLER: 'BUNDLER',\n DEPLOYER: 'DEPLOYER',\n MEMORY: 'MEMORY',\n STORAGE: 'STORAGE',\n EMBEDDINGS: 'EMBEDDINGS',\n MCP_SERVER: 'MCP_SERVER',\n SERVER_CACHE: 'SERVER_CACHE',\n SERVER: 'SERVER',\n WORKSPACE: 'WORKSPACE',\n} as const;\n\nexport type RegisteredLogger = (typeof RegisteredLogger)[keyof typeof RegisteredLogger];\n\nexport const LogLevel = {\n DEBUG: 'debug',\n INFO: 'info',\n WARN: 'warn',\n ERROR: 'error',\n NONE: 'silent',\n} as const;\n\nexport type LogLevel = (typeof LogLevel)[keyof typeof LogLevel];\n","import type { MastraError } from '../error';\nimport { LogLevel } from './constants';\nimport type { BaseLogMessage, LoggerTransport } from './transport';\n\nexport interface IMastraLogger {\n debug(message: string, ...args: any[]): void;\n info(message: string, ...args: any[]): void;\n warn(message: string, ...args: any[]): void;\n error(message: string, ...args: any[]): void;\n trackException(error: MastraError): void;\n\n getTransports(): Map<string, LoggerTransport>;\n listLogs(\n _transportId: string,\n _params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n },\n ): Promise<{ logs: BaseLogMessage[]; total: number; page: number; perPage: number; hasMore: boolean }>;\n listLogsByRunId(_args: {\n transportId: string;\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }): Promise<{ logs: BaseLogMessage[]; total: number; page: number; perPage: number; hasMore: boolean }>;\n}\n\nexport abstract class MastraLogger implements IMastraLogger {\n protected name: string;\n protected level: LogLevel;\n protected transports: Map<string, LoggerTransport>;\n\n constructor(\n options: {\n name?: string;\n level?: LogLevel;\n transports?: Record<string, LoggerTransport>;\n } = {},\n ) {\n this.name = options.name || 'Mastra';\n this.level = options.level || LogLevel.ERROR;\n this.transports = new Map(Object.entries(options.transports || {}));\n }\n\n abstract debug(message: string, ...args: any[]): void;\n abstract info(message: string, ...args: any[]): void;\n abstract warn(message: string, ...args: any[]): void;\n abstract error(message: string, ...args: any[]): void;\n\n getTransports() {\n return this.transports;\n }\n\n trackException(_error: MastraError) {}\n\n async listLogs(\n transportId: string,\n params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n },\n ) {\n if (!transportId || !this.transports.has(transportId)) {\n return { logs: [], total: 0, page: params?.page ?? 1, perPage: params?.perPage ?? 100, hasMore: false };\n }\n\n return (\n this.transports.get(transportId)!.listLogs(params) ?? {\n logs: [],\n total: 0,\n page: params?.page ?? 1,\n perPage: params?.perPage ?? 100,\n hasMore: false,\n }\n );\n }\n\n async listLogsByRunId({\n transportId,\n runId,\n fromDate,\n toDate,\n logLevel,\n filters,\n page,\n perPage,\n }: {\n transportId: string;\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }) {\n if (!transportId || !this.transports.has(transportId) || !runId) {\n return { logs: [], total: 0, page: page ?? 1, perPage: perPage ?? 100, hasMore: false };\n }\n\n return (\n this.transports\n .get(transportId)!\n .listLogsByRunId({ runId, fromDate, toDate, logLevel, filters, page, perPage }) ?? {\n logs: [],\n total: 0,\n page: page ?? 1,\n perPage: perPage ?? 100,\n hasMore: false,\n }\n );\n }\n}\n","import { LogLevel } from './constants';\nimport { MastraLogger } from './logger';\nimport type { LoggerTransport } from './transport';\n\nexport const createLogger = (options: {\n name?: string;\n level?: LogLevel;\n transports?: Record<string, LoggerTransport>;\n}) => {\n const logger = new ConsoleLogger(options);\n\n logger.warn(`createLogger is deprecated. Please use \"new ConsoleLogger()\" from \"@mastra/core/logger\" instead.`);\n\n return logger;\n};\n\nexport class ConsoleLogger extends MastraLogger {\n constructor(\n options: {\n name?: string;\n level?: LogLevel;\n } = {},\n ) {\n super(options);\n }\n\n debug(message: string, ...args: any[]): void {\n if (this.level === LogLevel.DEBUG) {\n console.info(message, ...args);\n }\n }\n\n info(message: string, ...args: any[]): void {\n if (this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) {\n console.info(message, ...args);\n }\n }\n\n warn(message: string, ...args: any[]): void {\n if (this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) {\n console.info(message, ...args);\n }\n }\n\n error(message: string, ...args: any[]): void {\n if (\n this.level === LogLevel.ERROR ||\n this.level === LogLevel.WARN ||\n this.level === LogLevel.INFO ||\n this.level === LogLevel.DEBUG\n ) {\n console.error(message, ...args);\n }\n }\n\n async listLogs(\n _transportId: string,\n _params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n },\n ) {\n return { logs: [], total: 0, page: _params?.page ?? 1, perPage: _params?.perPage ?? 100, hasMore: false };\n }\n\n async listLogsByRunId(_args: {\n transportId: string;\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }) {\n return { logs: [], total: 0, page: _args.page ?? 1, perPage: _args.perPage ?? 100, hasMore: false };\n }\n}\n","import type { IMastraLogger } from './logger';\nimport { RegisteredLogger } from './logger/constants';\nimport { ConsoleLogger } from './logger/default-logger';\n\nexport class MastraBase {\n component: RegisteredLogger = RegisteredLogger.LLM;\n protected logger: IMastraLogger;\n name?: string;\n #rawConfig?: Record<string, unknown>;\n\n constructor({\n component,\n name,\n rawConfig,\n }: {\n component?: RegisteredLogger;\n name?: string;\n rawConfig?: Record<string, unknown>;\n }) {\n this.component = component || RegisteredLogger.LLM;\n this.name = name;\n this.#rawConfig = rawConfig;\n this.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });\n }\n\n /**\n * Returns the raw storage configuration this primitive was created from,\n * or undefined if it was created from code.\n */\n toRawConfig(): Record<string, unknown> | undefined {\n return this.#rawConfig;\n }\n\n /**\n * Sets the raw storage configuration for this primitive.\n * @internal\n */\n __setRawConfig(rawConfig: Record<string, unknown>): void {\n this.#rawConfig = rawConfig;\n }\n\n /**\n * Set the logger for the agent\n * @param logger\n */\n __setLogger(logger: IMastraLogger) {\n this.logger = logger;\n\n if (this.component !== RegisteredLogger.LLM) {\n this.logger.debug(`Logger updated [component=${this.component}] [name=${this.name}]`);\n }\n }\n}\n\nexport * from './types';\n","import type { HonoRequest } from 'hono';\nimport { MastraBase } from '../base';\nimport type { MastraAuthConfig } from './types';\n\nexport interface MastraAuthProviderOptions<TUser = unknown> {\n name?: string;\n authorizeUser?: (user: TUser, request: HonoRequest) => Promise<boolean> | boolean;\n /**\n * Protected paths for the auth provider\n */\n protected?: MastraAuthConfig['protected'];\n /**\n * Public paths for the auth provider\n */\n public?: MastraAuthConfig['public'];\n}\n\nexport abstract class MastraAuthProvider<TUser = unknown> extends MastraBase {\n public protected?: MastraAuthConfig['protected'];\n public public?: MastraAuthConfig['public'];\n\n constructor(options?: MastraAuthProviderOptions<TUser>) {\n super({ component: 'AUTH', name: options?.name });\n\n if (options?.authorizeUser) {\n this.authorizeUser = options.authorizeUser.bind(this);\n }\n\n this.protected = options?.protected;\n this.public = options?.public;\n }\n\n /**\n * Authenticate a token and return the payload\n * @param token - The token to authenticate\n * @param request - The request\n * @returns The payload\n */\n abstract authenticateToken(token: string, request: HonoRequest): Promise<TUser | null>;\n\n /**\n * Authorize a user for a path and method\n * @param user - The user to authorize\n * @param request - The request\n * @returns The authorization result\n */\n abstract authorizeUser(user: TUser, request: HonoRequest): Promise<boolean> | boolean;\n\n protected registerOptions(opts?: MastraAuthProviderOptions<TUser>) {\n if (opts?.authorizeUser) {\n this.authorizeUser = opts.authorizeUser.bind(this);\n }\n if (opts?.protected) {\n this.protected = opts.protected;\n }\n if (opts?.public) {\n this.public = opts.public;\n }\n }\n}\n","import { MastraAuthProvider } from '@mastra/core/server';\nimport type { MastraAuthProviderOptions } from '@mastra/core/server';\n\nimport jwt from 'jsonwebtoken';\n\ntype JwtUser = jwt.JwtPayload;\n\ninterface MastraJwtAuthOptions extends MastraAuthProviderOptions<JwtUser> {\n secret?: string;\n}\n\nexport class MastraJwtAuth extends MastraAuthProvider<JwtUser> {\n protected secret: string;\n\n constructor(options?: MastraJwtAuthOptions) {\n super({ name: options?.name ?? 'jwt' });\n\n this.secret = options?.secret ?? process.env.JWT_AUTH_SECRET ?? '';\n\n if (!this.secret) {\n throw new Error('JWT auth secret is required');\n }\n\n this.registerOptions(options);\n }\n\n async authenticateToken(token: string): Promise<JwtUser> {\n return jwt.verify(token, this.secret) as JwtUser;\n }\n\n async authorizeUser(user: JwtUser) {\n return !!user;\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mastra/auth",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.1",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"files": [
|
|
@@ -25,21 +25,21 @@
|
|
|
25
25
|
"author": "",
|
|
26
26
|
"license": "Apache-2.0",
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"jsonwebtoken": "^9.0.
|
|
29
|
-
"jwks-rsa": "^3.2.
|
|
28
|
+
"jsonwebtoken": "^9.0.3",
|
|
29
|
+
"jwks-rsa": "^3.2.2"
|
|
30
30
|
},
|
|
31
31
|
"devDependencies": {
|
|
32
32
|
"@types/jsonwebtoken": "^9.0.10",
|
|
33
|
-
"@types/node": "22.
|
|
34
|
-
"@vitest/coverage-v8": "4.0.
|
|
35
|
-
"@vitest/ui": "4.0.
|
|
33
|
+
"@types/node": "22.19.7",
|
|
34
|
+
"@vitest/coverage-v8": "4.0.18",
|
|
35
|
+
"@vitest/ui": "4.0.18",
|
|
36
36
|
"eslint": "^9.37.0",
|
|
37
|
-
"tsup": "^8.5.
|
|
37
|
+
"tsup": "^8.5.1",
|
|
38
38
|
"typescript": "^5.9.3",
|
|
39
|
-
"vitest": "4.0.
|
|
40
|
-
"@
|
|
41
|
-
"@internal/
|
|
42
|
-
"@
|
|
39
|
+
"vitest": "4.0.18",
|
|
40
|
+
"@mastra/core": "1.10.0",
|
|
41
|
+
"@internal/lint": "0.0.66",
|
|
42
|
+
"@internal/types-builder": "0.0.41"
|
|
43
43
|
},
|
|
44
44
|
"homepage": "https://mastra.ai",
|
|
45
45
|
"repository": {
|
|
@@ -55,7 +55,6 @@
|
|
|
55
55
|
},
|
|
56
56
|
"scripts": {
|
|
57
57
|
"build:lib": "tsup --silent --config tsup.config.ts",
|
|
58
|
-
"build:docs": "pnpx tsx ../../scripts/generate-package-docs.ts packages/auth",
|
|
59
58
|
"build:watch": "tsup --watch --silent --config tsup.config.ts",
|
|
60
59
|
"test": "vitest run",
|
|
61
60
|
"lint": "eslint ."
|
package/dist/docs/README.md
DELETED
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
# @mastra/auth Documentation
|
|
2
|
-
|
|
3
|
-
> Embedded documentation for coding agents
|
|
4
|
-
|
|
5
|
-
## Quick Start
|
|
6
|
-
|
|
7
|
-
```bash
|
|
8
|
-
# Read the skill overview
|
|
9
|
-
cat docs/SKILL.md
|
|
10
|
-
|
|
11
|
-
# Get the source map
|
|
12
|
-
cat docs/SOURCE_MAP.json
|
|
13
|
-
|
|
14
|
-
# Read topic documentation
|
|
15
|
-
cat docs/<topic>/01-overview.md
|
|
16
|
-
```
|
|
17
|
-
|
|
18
|
-
## Structure
|
|
19
|
-
|
|
20
|
-
```
|
|
21
|
-
docs/
|
|
22
|
-
├── SKILL.md # Entry point
|
|
23
|
-
├── README.md # This file
|
|
24
|
-
├── SOURCE_MAP.json # Export index
|
|
25
|
-
├── auth/ (1 files)
|
|
26
|
-
├── server/ (2 files)
|
|
27
|
-
```
|
|
28
|
-
|
|
29
|
-
## Version
|
|
30
|
-
|
|
31
|
-
Package: @mastra/auth
|
|
32
|
-
Version: 1.0.0
|
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
# Auth API Reference
|
|
2
|
-
|
|
3
|
-
> API reference for auth - 1 entries
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
---
|
|
7
|
-
|
|
8
|
-
## Reference: MastraJwtAuth Class
|
|
9
|
-
|
|
10
|
-
> API reference for the MastraJwtAuth class, which authenticates Mastra applications using JSON Web Tokens.
|
|
11
|
-
|
|
12
|
-
The `MastraJwtAuth` class provides a lightweight authentication mechanism for Mastra using JSON Web Tokens (JWTs). It verifies incoming requests based on a shared secret and integrates with the Mastra server using the `auth` option.
|
|
13
|
-
|
|
14
|
-
## Usage example
|
|
15
|
-
|
|
16
|
-
```typescript title="src/mastra/index.ts"
|
|
17
|
-
import { Mastra } from "@mastra/core";
|
|
18
|
-
import { MastraJwtAuth } from "@mastra/auth";
|
|
19
|
-
|
|
20
|
-
export const mastra = new Mastra({
|
|
21
|
-
server: {
|
|
22
|
-
auth: new MastraJwtAuth({
|
|
23
|
-
secret: "<your-secret>",
|
|
24
|
-
}),
|
|
25
|
-
},
|
|
26
|
-
});
|
|
27
|
-
```
|
|
28
|
-
|
|
29
|
-
## Constructor parameters
|
|
30
|
-
|
|
31
|
-
## Related
|
|
32
|
-
|
|
33
|
-
[MastraJwtAuth](https://mastra.ai/docs/v1/server/auth/jwt)
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
> Learn about different Auth options for your Mastra applications
|
|
2
|
-
|
|
3
|
-
# Auth Overview
|
|
4
|
-
|
|
5
|
-
Mastra lets you choose how you handle authentication, so you can secure access to your application's endpoints using the identity system that fits your stack.
|
|
6
|
-
|
|
7
|
-
You can start with simple shared secret JWT authentication and switch to providers like Supabase, Firebase Auth, Auth0, Clerk, or WorkOS when you need more advanced identity features.
|
|
8
|
-
|
|
9
|
-
## Available providers
|
|
10
|
-
|
|
11
|
-
- [JSON Web Token (JWT)](https://mastra.ai/docs/v1/server/auth/jwt)
|
|
12
|
-
- [Clerk](https://mastra.ai/docs/v1/server/auth/clerk)
|
|
13
|
-
- [Supabase](https://mastra.ai/docs/v1/server/auth/supabase)
|
|
14
|
-
- [Firebase](https://mastra.ai/docs/v1/server/auth/firebase)
|
|
15
|
-
- [WorkOS](https://mastra.ai/docs/v1/server/auth/workos)
|
|
16
|
-
- [Auth0](https://mastra.ai/docs/v1/server/auth/auth0)
|