@mastra/auth-better-auth 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/README.md +107 -0
- package/dist/index.cjs +205 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +83 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +203 -0
- package/dist/index.js.map +1 -0
- package/package.json +60 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# @mastra/auth-better-auth
|
|
2
|
+
|
|
3
|
+
## 1.0.0-beta.1
|
|
4
|
+
|
|
5
|
+
### Major Changes
|
|
6
|
+
|
|
7
|
+
- Initial release of Better Auth integration for Mastra
|
|
8
|
+
- Self-hosted authentication provider using Better Auth
|
|
9
|
+
- Support for session-based authentication
|
|
10
|
+
- Custom authorization logic support
|
|
11
|
+
- Route configuration for public/protected paths
|
package/README.md
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# @mastra/auth-better-auth
|
|
2
|
+
|
|
3
|
+
Better Auth integration for Mastra - a self-hosted, open-source authentication solution.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @mastra/auth-better-auth better-auth
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
```typescript
|
|
14
|
+
import { betterAuth } from 'better-auth';
|
|
15
|
+
import { MastraAuthBetterAuth } from '@mastra/auth-better-auth';
|
|
16
|
+
import { Mastra } from '@mastra/core';
|
|
17
|
+
|
|
18
|
+
// Create your Better Auth instance
|
|
19
|
+
const auth = betterAuth({
|
|
20
|
+
database: {
|
|
21
|
+
provider: 'postgresql',
|
|
22
|
+
url: process.env.DATABASE_URL!,
|
|
23
|
+
},
|
|
24
|
+
emailAndPassword: {
|
|
25
|
+
enabled: true,
|
|
26
|
+
},
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
// Create the Mastra auth provider
|
|
30
|
+
const mastraAuth = new MastraAuthBetterAuth({
|
|
31
|
+
auth,
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
// Use with Mastra
|
|
35
|
+
const mastra = new Mastra({
|
|
36
|
+
server: {
|
|
37
|
+
auth: mastraAuth,
|
|
38
|
+
},
|
|
39
|
+
});
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Configuration Options
|
|
43
|
+
|
|
44
|
+
| Option | Type | Required | Description |
|
|
45
|
+
| --------------- | ------------------------------------- | -------- | ------------------------------------------------------------ |
|
|
46
|
+
| `auth` | `Auth` | Yes | Your Better Auth instance created via `betterAuth({ ... })` |
|
|
47
|
+
| `name` | `string` | No | Custom name for the auth provider (default: `'better-auth'`) |
|
|
48
|
+
| `authorizeUser` | `(user, request) => Promise<boolean>` | No | Custom authorization logic |
|
|
49
|
+
| `public` | `string[]` | No | Public routes that don't require authentication |
|
|
50
|
+
| `protected` | `string[]` | No | Protected routes that require authentication |
|
|
51
|
+
|
|
52
|
+
## Custom Authorization
|
|
53
|
+
|
|
54
|
+
You can provide custom authorization logic:
|
|
55
|
+
|
|
56
|
+
```typescript
|
|
57
|
+
const mastraAuth = new MastraAuthBetterAuth({
|
|
58
|
+
auth,
|
|
59
|
+
async authorizeUser(user) {
|
|
60
|
+
// Only allow verified emails
|
|
61
|
+
return user?.user?.emailVerified === true;
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## Role-Based Access Control
|
|
67
|
+
|
|
68
|
+
```typescript
|
|
69
|
+
const mastraAuth = new MastraAuthBetterAuth({
|
|
70
|
+
auth,
|
|
71
|
+
async authorizeUser(user) {
|
|
72
|
+
// Check for admin role (assuming you have a role field)
|
|
73
|
+
const userWithRole = user?.user as any;
|
|
74
|
+
return userWithRole?.role === 'admin';
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Route Configuration
|
|
80
|
+
|
|
81
|
+
```typescript
|
|
82
|
+
const mastraAuth = new MastraAuthBetterAuth({
|
|
83
|
+
auth,
|
|
84
|
+
public: ['/health', '/api/status'],
|
|
85
|
+
protected: ['/api/*', '/admin/*'],
|
|
86
|
+
});
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## Why Better Auth?
|
|
90
|
+
|
|
91
|
+
Better Auth is a self-hosted, open-source authentication framework that gives you:
|
|
92
|
+
|
|
93
|
+
- **Full control** over your authentication system
|
|
94
|
+
- **No vendor lock-in** - host it yourself
|
|
95
|
+
- **Flexible** - works with various databases and providers
|
|
96
|
+
- **TypeScript-first** - full type safety
|
|
97
|
+
- **Plugin system** - extend with OAuth, 2FA, organizations, etc.
|
|
98
|
+
|
|
99
|
+
## Resources
|
|
100
|
+
|
|
101
|
+
- [Better Auth Documentation](https://better-auth.com)
|
|
102
|
+
- [Mastra Documentation](https://mastra.ai/docs)
|
|
103
|
+
- [GitHub Repository](https://github.com/mastra-ai/mastra)
|
|
104
|
+
|
|
105
|
+
## License
|
|
106
|
+
|
|
107
|
+
Apache-2.0
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// ../../packages/core/dist/chunk-KJ2SW6VA.js
|
|
4
|
+
var RegisteredLogger = {
|
|
5
|
+
LLM: "LLM"};
|
|
6
|
+
var LogLevel = {
|
|
7
|
+
DEBUG: "debug",
|
|
8
|
+
INFO: "info",
|
|
9
|
+
WARN: "warn",
|
|
10
|
+
ERROR: "error"};
|
|
11
|
+
var MastraLogger = class {
|
|
12
|
+
name;
|
|
13
|
+
level;
|
|
14
|
+
transports;
|
|
15
|
+
constructor(options = {}) {
|
|
16
|
+
this.name = options.name || "Mastra";
|
|
17
|
+
this.level = options.level || LogLevel.ERROR;
|
|
18
|
+
this.transports = new Map(Object.entries(options.transports || {}));
|
|
19
|
+
}
|
|
20
|
+
getTransports() {
|
|
21
|
+
return this.transports;
|
|
22
|
+
}
|
|
23
|
+
trackException(_error) {
|
|
24
|
+
}
|
|
25
|
+
async listLogs(transportId, params) {
|
|
26
|
+
if (!transportId || !this.transports.has(transportId)) {
|
|
27
|
+
return { logs: [], total: 0, page: params?.page ?? 1, perPage: params?.perPage ?? 100, hasMore: false };
|
|
28
|
+
}
|
|
29
|
+
return this.transports.get(transportId).listLogs(params) ?? {
|
|
30
|
+
logs: [],
|
|
31
|
+
total: 0,
|
|
32
|
+
page: params?.page ?? 1,
|
|
33
|
+
perPage: params?.perPage ?? 100,
|
|
34
|
+
hasMore: false
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
async listLogsByRunId({
|
|
38
|
+
transportId,
|
|
39
|
+
runId,
|
|
40
|
+
fromDate,
|
|
41
|
+
toDate,
|
|
42
|
+
logLevel,
|
|
43
|
+
filters,
|
|
44
|
+
page,
|
|
45
|
+
perPage
|
|
46
|
+
}) {
|
|
47
|
+
if (!transportId || !this.transports.has(transportId) || !runId) {
|
|
48
|
+
return { logs: [], total: 0, page: page ?? 1, perPage: perPage ?? 100, hasMore: false };
|
|
49
|
+
}
|
|
50
|
+
return this.transports.get(transportId).listLogsByRunId({ runId, fromDate, toDate, logLevel, filters, page, perPage }) ?? {
|
|
51
|
+
logs: [],
|
|
52
|
+
total: 0,
|
|
53
|
+
page: page ?? 1,
|
|
54
|
+
perPage: perPage ?? 100,
|
|
55
|
+
hasMore: false
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
var ConsoleLogger = class extends MastraLogger {
|
|
60
|
+
constructor(options = {}) {
|
|
61
|
+
super(options);
|
|
62
|
+
}
|
|
63
|
+
debug(message, ...args) {
|
|
64
|
+
if (this.level === LogLevel.DEBUG) {
|
|
65
|
+
console.info(message, ...args);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
info(message, ...args) {
|
|
69
|
+
if (this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) {
|
|
70
|
+
console.info(message, ...args);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
warn(message, ...args) {
|
|
74
|
+
if (this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) {
|
|
75
|
+
console.info(message, ...args);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
error(message, ...args) {
|
|
79
|
+
if (this.level === LogLevel.ERROR || this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) {
|
|
80
|
+
console.error(message, ...args);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
async listLogs(_transportId, _params) {
|
|
84
|
+
return { logs: [], total: 0, page: _params?.page ?? 1, perPage: _params?.perPage ?? 100, hasMore: false };
|
|
85
|
+
}
|
|
86
|
+
async listLogsByRunId(_args) {
|
|
87
|
+
return { logs: [], total: 0, page: _args.page ?? 1, perPage: _args.perPage ?? 100, hasMore: false };
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
// ../../packages/core/dist/chunk-S6URFGCZ.js
|
|
92
|
+
var MastraBase = class {
|
|
93
|
+
component = RegisteredLogger.LLM;
|
|
94
|
+
logger;
|
|
95
|
+
name;
|
|
96
|
+
constructor({ component, name }) {
|
|
97
|
+
this.component = component || RegisteredLogger.LLM;
|
|
98
|
+
this.name = name;
|
|
99
|
+
this.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Set the logger for the agent
|
|
103
|
+
* @param logger
|
|
104
|
+
*/
|
|
105
|
+
__setLogger(logger) {
|
|
106
|
+
this.logger = logger;
|
|
107
|
+
if (this.component !== RegisteredLogger.LLM) {
|
|
108
|
+
this.logger.debug(`Logger updated [component=${this.component}] [name=${this.name}]`);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
// ../../packages/core/dist/server/index.js
|
|
114
|
+
var MastraAuthProvider = class extends MastraBase {
|
|
115
|
+
protected;
|
|
116
|
+
public;
|
|
117
|
+
constructor(options) {
|
|
118
|
+
super({ component: "AUTH", name: options?.name });
|
|
119
|
+
if (options?.authorizeUser) {
|
|
120
|
+
this.authorizeUser = options.authorizeUser.bind(this);
|
|
121
|
+
}
|
|
122
|
+
this.protected = options?.protected;
|
|
123
|
+
this.public = options?.public;
|
|
124
|
+
}
|
|
125
|
+
registerOptions(opts) {
|
|
126
|
+
if (opts?.authorizeUser) {
|
|
127
|
+
this.authorizeUser = opts.authorizeUser.bind(this);
|
|
128
|
+
}
|
|
129
|
+
if (opts?.protected) {
|
|
130
|
+
this.protected = opts.protected;
|
|
131
|
+
}
|
|
132
|
+
if (opts?.public) {
|
|
133
|
+
this.public = opts.public;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
// src/index.ts
|
|
139
|
+
var MastraAuthBetterAuth = class extends MastraAuthProvider {
|
|
140
|
+
auth;
|
|
141
|
+
constructor(options) {
|
|
142
|
+
super({ name: options?.name ?? "better-auth" });
|
|
143
|
+
if (!options.auth) {
|
|
144
|
+
throw new Error(
|
|
145
|
+
"Better Auth instance is required. Please provide the auth option with your Better Auth instance created via betterAuth({ ... })"
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
this.auth = options.auth;
|
|
149
|
+
this.registerOptions(options);
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Authenticate a bearer token by verifying the session with Better Auth.
|
|
153
|
+
*
|
|
154
|
+
* This method extracts the session from the request headers using
|
|
155
|
+
* Better Auth's `api.getSession()` endpoint.
|
|
156
|
+
*
|
|
157
|
+
* @param token - The bearer token (session token) to authenticate
|
|
158
|
+
* @param request - The Hono request object containing headers
|
|
159
|
+
* @returns The authenticated user and session, or null if authentication fails
|
|
160
|
+
*/
|
|
161
|
+
async authenticateToken(token, request) {
|
|
162
|
+
try {
|
|
163
|
+
const headers = new Headers();
|
|
164
|
+
const authHeader = request.header("Authorization");
|
|
165
|
+
if (authHeader) {
|
|
166
|
+
headers.set("Authorization", authHeader);
|
|
167
|
+
} else if (token) {
|
|
168
|
+
headers.set("Authorization", `Bearer ${token}`);
|
|
169
|
+
}
|
|
170
|
+
const cookieHeader = request.header("Cookie");
|
|
171
|
+
if (cookieHeader) {
|
|
172
|
+
headers.set("Cookie", cookieHeader);
|
|
173
|
+
}
|
|
174
|
+
const result = await this.auth.api.getSession({
|
|
175
|
+
headers
|
|
176
|
+
});
|
|
177
|
+
if (!result || !result.session || !result.user) {
|
|
178
|
+
return null;
|
|
179
|
+
}
|
|
180
|
+
return {
|
|
181
|
+
session: result.session,
|
|
182
|
+
user: result.user
|
|
183
|
+
};
|
|
184
|
+
} catch {
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Authorize a user for access.
|
|
190
|
+
*
|
|
191
|
+
* By default, any authenticated user with a valid session is authorized.
|
|
192
|
+
* You can override this behavior by providing a custom `authorizeUser` function
|
|
193
|
+
* in the constructor options.
|
|
194
|
+
*
|
|
195
|
+
* @param user - The authenticated user and session
|
|
196
|
+
* @returns True if the user is authorized, false otherwise
|
|
197
|
+
*/
|
|
198
|
+
async authorizeUser(user) {
|
|
199
|
+
return !!user?.session?.id && !!user?.user?.id;
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
exports.MastraAuthBetterAuth = MastraAuthBetterAuth;
|
|
204
|
+
//# sourceMappingURL=index.cjs.map
|
|
205
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../packages/core/src/logger/constants.ts","../../../packages/core/src/logger/logger.ts","../../../packages/core/src/logger/default-logger.ts","../../../packages/core/src/base.ts","../../../packages/core/src/server/auth.ts","../src/index.ts"],"names":[],"mappings":";;;AACO,IAAM,gBAAA,GAAmB;EAM9B,GAAA,E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B,CAAA,OAAA,EAAU,KAAK,CAAA,CAAE,CAAA;AAAA,MAChD;AAGA,MAAA,MAAM,YAAA,GAAe,OAAA,CAAQ,MAAA,CAAO,QAAQ,CAAA;AAC5C,MAAA,IAAI,YAAA,EAAc;AAChB,QAAA,OAAA,CAAQ,GAAA,CAAI,UAAU,YAAY,CAAA;AAAA,MACpC;AAGA,MAAA,MAAM,MAAA,GAAS,MAAM,IAAA,CAAK,IAAA,CAAK,IAAI,UAAA,CAAW;AAAA,QAC5C;AAAA,OACD,CAAA;AAED,MAAA,IAAI,CAAC,MAAA,IAAU,CAAC,OAAO,OAAA,IAAW,CAAC,OAAO,IAAA,EAAM;AAC9C,QAAA,OAAO,IAAA;AAAA,MACT;AAEA,MAAA,OAAO;AAAA,QACL,SAAS,MAAA,CAAO,OAAA;AAAA,QAChB,MAAM,MAAA,CAAO;AAAA,OACf;AAAA,IACF,CAAA,CAAA,MAAQ;AAEN,MAAA,OAAO,IAAA;AAAA,IACT;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,MAAM,cAAc,IAAA,EAAwC;AAE1D,IAAA,OAAO,CAAC,CAAC,IAAA,EAAM,OAAA,EAAS,MAAM,CAAC,CAAC,MAAM,IAAA,EAAM,EAAA;AAAA,EAC9C;AACF","file":"index.cjs","sourcesContent":["// 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} 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 type { MastraAuthProviderOptions } from '@mastra/core/server';\nimport { MastraAuthProvider } from '@mastra/core/server';\n\nimport type { Auth, Session, User } from 'better-auth';\nimport type { HonoRequest } from 'hono';\n\n/**\n * User type returned by Better Auth session verification\n */\nexport interface BetterAuthUser {\n session: Session;\n user: User;\n}\n\ninterface MastraAuthBetterAuthOptions extends MastraAuthProviderOptions<BetterAuthUser> {\n /**\n * The Better Auth instance to use for authentication.\n * This should be the result of calling `betterAuth({ ... })`.\n */\n auth: Auth;\n}\n\n/**\n * Mastra authentication provider for Better Auth.\n *\n * Better Auth is a self-hosted, open-source authentication framework\n * that gives you full control over your authentication system.\n *\n * @example\n * ```typescript\n * import { betterAuth } from 'better-auth';\n * import { MastraAuthBetterAuth } from '@mastra/auth-better-auth';\n *\n * // Create your Better Auth instance\n * const auth = betterAuth({\n * database: {\n * provider: 'postgresql',\n * url: process.env.DATABASE_URL!,\n * },\n * emailAndPassword: {\n * enabled: true,\n * },\n * });\n *\n * // Create the Mastra auth provider\n * const mastraAuth = new MastraAuthBetterAuth({\n * auth,\n * });\n *\n * // Use with Mastra\n * const mastra = new Mastra({\n * server: {\n * auth: mastraAuth,\n * },\n * });\n * ```\n *\n * @see https://better-auth.com for Better Auth documentation\n */\nexport class MastraAuthBetterAuth extends MastraAuthProvider<BetterAuthUser> {\n protected auth: Auth;\n\n constructor(options: MastraAuthBetterAuthOptions) {\n super({ name: options?.name ?? 'better-auth' });\n\n if (!options.auth) {\n throw new Error(\n 'Better Auth instance is required. Please provide the auth option with your Better Auth instance created via betterAuth({ ... })',\n );\n }\n\n this.auth = options.auth;\n\n this.registerOptions(options);\n }\n\n /**\n * Authenticate a bearer token by verifying the session with Better Auth.\n *\n * This method extracts the session from the request headers using\n * Better Auth's `api.getSession()` endpoint.\n *\n * @param token - The bearer token (session token) to authenticate\n * @param request - The Hono request object containing headers\n * @returns The authenticated user and session, or null if authentication fails\n */\n async authenticateToken(token: string, request: HonoRequest): Promise<BetterAuthUser | null> {\n try {\n // Better Auth expects the token to be passed via headers\n // We need to construct headers with the Authorization bearer token\n const headers = new Headers();\n\n // Copy relevant headers from the request\n const authHeader = request.header('Authorization');\n if (authHeader) {\n headers.set('Authorization', authHeader);\n } else if (token) {\n // If no auth header but token is provided, set it\n headers.set('Authorization', `Bearer ${token}`);\n }\n\n // Copy cookie header if present (Better Auth can use cookies for sessions)\n const cookieHeader = request.header('Cookie');\n if (cookieHeader) {\n headers.set('Cookie', cookieHeader);\n }\n\n // Use Better Auth's API to get the session\n const result = await this.auth.api.getSession({\n headers,\n });\n\n if (!result || !result.session || !result.user) {\n return null;\n }\n\n return {\n session: result.session,\n user: result.user,\n };\n } catch {\n // Session verification failed\n return null;\n }\n }\n\n /**\n * Authorize a user for access.\n *\n * By default, any authenticated user with a valid session is authorized.\n * You can override this behavior by providing a custom `authorizeUser` function\n * in the constructor options.\n *\n * @param user - The authenticated user and session\n * @returns True if the user is authorized, false otherwise\n */\n async authorizeUser(user: BetterAuthUser): Promise<boolean> {\n // By default, any authenticated user with a valid session is authorized\n return !!user?.session?.id && !!user?.user?.id;\n }\n}\n"]}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import type { MastraAuthProviderOptions } from '@mastra/core/server';
|
|
2
|
+
import { MastraAuthProvider } from '@mastra/core/server';
|
|
3
|
+
import type { Auth, Session, User } from 'better-auth';
|
|
4
|
+
import type { HonoRequest } from 'hono';
|
|
5
|
+
/**
|
|
6
|
+
* User type returned by Better Auth session verification
|
|
7
|
+
*/
|
|
8
|
+
export interface BetterAuthUser {
|
|
9
|
+
session: Session;
|
|
10
|
+
user: User;
|
|
11
|
+
}
|
|
12
|
+
interface MastraAuthBetterAuthOptions extends MastraAuthProviderOptions<BetterAuthUser> {
|
|
13
|
+
/**
|
|
14
|
+
* The Better Auth instance to use for authentication.
|
|
15
|
+
* This should be the result of calling `betterAuth({ ... })`.
|
|
16
|
+
*/
|
|
17
|
+
auth: Auth;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Mastra authentication provider for Better Auth.
|
|
21
|
+
*
|
|
22
|
+
* Better Auth is a self-hosted, open-source authentication framework
|
|
23
|
+
* that gives you full control over your authentication system.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```typescript
|
|
27
|
+
* import { betterAuth } from 'better-auth';
|
|
28
|
+
* import { MastraAuthBetterAuth } from '@mastra/auth-better-auth';
|
|
29
|
+
*
|
|
30
|
+
* // Create your Better Auth instance
|
|
31
|
+
* const auth = betterAuth({
|
|
32
|
+
* database: {
|
|
33
|
+
* provider: 'postgresql',
|
|
34
|
+
* url: process.env.DATABASE_URL!,
|
|
35
|
+
* },
|
|
36
|
+
* emailAndPassword: {
|
|
37
|
+
* enabled: true,
|
|
38
|
+
* },
|
|
39
|
+
* });
|
|
40
|
+
*
|
|
41
|
+
* // Create the Mastra auth provider
|
|
42
|
+
* const mastraAuth = new MastraAuthBetterAuth({
|
|
43
|
+
* auth,
|
|
44
|
+
* });
|
|
45
|
+
*
|
|
46
|
+
* // Use with Mastra
|
|
47
|
+
* const mastra = new Mastra({
|
|
48
|
+
* server: {
|
|
49
|
+
* auth: mastraAuth,
|
|
50
|
+
* },
|
|
51
|
+
* });
|
|
52
|
+
* ```
|
|
53
|
+
*
|
|
54
|
+
* @see https://better-auth.com for Better Auth documentation
|
|
55
|
+
*/
|
|
56
|
+
export declare class MastraAuthBetterAuth extends MastraAuthProvider<BetterAuthUser> {
|
|
57
|
+
protected auth: Auth;
|
|
58
|
+
constructor(options: MastraAuthBetterAuthOptions);
|
|
59
|
+
/**
|
|
60
|
+
* Authenticate a bearer token by verifying the session with Better Auth.
|
|
61
|
+
*
|
|
62
|
+
* This method extracts the session from the request headers using
|
|
63
|
+
* Better Auth's `api.getSession()` endpoint.
|
|
64
|
+
*
|
|
65
|
+
* @param token - The bearer token (session token) to authenticate
|
|
66
|
+
* @param request - The Hono request object containing headers
|
|
67
|
+
* @returns The authenticated user and session, or null if authentication fails
|
|
68
|
+
*/
|
|
69
|
+
authenticateToken(token: string, request: HonoRequest): Promise<BetterAuthUser | null>;
|
|
70
|
+
/**
|
|
71
|
+
* Authorize a user for access.
|
|
72
|
+
*
|
|
73
|
+
* By default, any authenticated user with a valid session is authorized.
|
|
74
|
+
* You can override this behavior by providing a custom `authorizeUser` function
|
|
75
|
+
* in the constructor options.
|
|
76
|
+
*
|
|
77
|
+
* @param user - The authenticated user and session
|
|
78
|
+
* @returns True if the user is authorized, false otherwise
|
|
79
|
+
*/
|
|
80
|
+
authorizeUser(user: BetterAuthUser): Promise<boolean>;
|
|
81
|
+
}
|
|
82
|
+
export {};
|
|
83
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,qBAAqB,CAAC;AACrE,OAAO,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAEzD,OAAO,KAAK,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AACvD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,MAAM,CAAC;AAExC;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,OAAO,EAAE,OAAO,CAAC;IACjB,IAAI,EAAE,IAAI,CAAC;CACZ;AAED,UAAU,2BAA4B,SAAQ,yBAAyB,CAAC,cAAc,CAAC;IACrF;;;OAGG;IACH,IAAI,EAAE,IAAI,CAAC;CACZ;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,qBAAa,oBAAqB,SAAQ,kBAAkB,CAAC,cAAc,CAAC;IAC1E,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC;gBAET,OAAO,EAAE,2BAA2B;IAchD;;;;;;;;;OASG;IACG,iBAAiB,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,GAAG,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC;IAwC5F;;;;;;;;;OASG;IACG,aAAa,CAAC,IAAI,EAAE,cAAc,GAAG,OAAO,CAAC,OAAO,CAAC;CAI5D"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
// ../../packages/core/dist/chunk-KJ2SW6VA.js
|
|
2
|
+
var RegisteredLogger = {
|
|
3
|
+
LLM: "LLM"};
|
|
4
|
+
var LogLevel = {
|
|
5
|
+
DEBUG: "debug",
|
|
6
|
+
INFO: "info",
|
|
7
|
+
WARN: "warn",
|
|
8
|
+
ERROR: "error"};
|
|
9
|
+
var MastraLogger = class {
|
|
10
|
+
name;
|
|
11
|
+
level;
|
|
12
|
+
transports;
|
|
13
|
+
constructor(options = {}) {
|
|
14
|
+
this.name = options.name || "Mastra";
|
|
15
|
+
this.level = options.level || LogLevel.ERROR;
|
|
16
|
+
this.transports = new Map(Object.entries(options.transports || {}));
|
|
17
|
+
}
|
|
18
|
+
getTransports() {
|
|
19
|
+
return this.transports;
|
|
20
|
+
}
|
|
21
|
+
trackException(_error) {
|
|
22
|
+
}
|
|
23
|
+
async listLogs(transportId, params) {
|
|
24
|
+
if (!transportId || !this.transports.has(transportId)) {
|
|
25
|
+
return { logs: [], total: 0, page: params?.page ?? 1, perPage: params?.perPage ?? 100, hasMore: false };
|
|
26
|
+
}
|
|
27
|
+
return this.transports.get(transportId).listLogs(params) ?? {
|
|
28
|
+
logs: [],
|
|
29
|
+
total: 0,
|
|
30
|
+
page: params?.page ?? 1,
|
|
31
|
+
perPage: params?.perPage ?? 100,
|
|
32
|
+
hasMore: false
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
async listLogsByRunId({
|
|
36
|
+
transportId,
|
|
37
|
+
runId,
|
|
38
|
+
fromDate,
|
|
39
|
+
toDate,
|
|
40
|
+
logLevel,
|
|
41
|
+
filters,
|
|
42
|
+
page,
|
|
43
|
+
perPage
|
|
44
|
+
}) {
|
|
45
|
+
if (!transportId || !this.transports.has(transportId) || !runId) {
|
|
46
|
+
return { logs: [], total: 0, page: page ?? 1, perPage: perPage ?? 100, hasMore: false };
|
|
47
|
+
}
|
|
48
|
+
return this.transports.get(transportId).listLogsByRunId({ runId, fromDate, toDate, logLevel, filters, page, perPage }) ?? {
|
|
49
|
+
logs: [],
|
|
50
|
+
total: 0,
|
|
51
|
+
page: page ?? 1,
|
|
52
|
+
perPage: perPage ?? 100,
|
|
53
|
+
hasMore: false
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
var ConsoleLogger = class extends MastraLogger {
|
|
58
|
+
constructor(options = {}) {
|
|
59
|
+
super(options);
|
|
60
|
+
}
|
|
61
|
+
debug(message, ...args) {
|
|
62
|
+
if (this.level === LogLevel.DEBUG) {
|
|
63
|
+
console.info(message, ...args);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
info(message, ...args) {
|
|
67
|
+
if (this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) {
|
|
68
|
+
console.info(message, ...args);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
warn(message, ...args) {
|
|
72
|
+
if (this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) {
|
|
73
|
+
console.info(message, ...args);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
error(message, ...args) {
|
|
77
|
+
if (this.level === LogLevel.ERROR || this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) {
|
|
78
|
+
console.error(message, ...args);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
async listLogs(_transportId, _params) {
|
|
82
|
+
return { logs: [], total: 0, page: _params?.page ?? 1, perPage: _params?.perPage ?? 100, hasMore: false };
|
|
83
|
+
}
|
|
84
|
+
async listLogsByRunId(_args) {
|
|
85
|
+
return { logs: [], total: 0, page: _args.page ?? 1, perPage: _args.perPage ?? 100, hasMore: false };
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
// ../../packages/core/dist/chunk-S6URFGCZ.js
|
|
90
|
+
var MastraBase = class {
|
|
91
|
+
component = RegisteredLogger.LLM;
|
|
92
|
+
logger;
|
|
93
|
+
name;
|
|
94
|
+
constructor({ component, name }) {
|
|
95
|
+
this.component = component || RegisteredLogger.LLM;
|
|
96
|
+
this.name = name;
|
|
97
|
+
this.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Set the logger for the agent
|
|
101
|
+
* @param logger
|
|
102
|
+
*/
|
|
103
|
+
__setLogger(logger) {
|
|
104
|
+
this.logger = logger;
|
|
105
|
+
if (this.component !== RegisteredLogger.LLM) {
|
|
106
|
+
this.logger.debug(`Logger updated [component=${this.component}] [name=${this.name}]`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
// ../../packages/core/dist/server/index.js
|
|
112
|
+
var MastraAuthProvider = class extends MastraBase {
|
|
113
|
+
protected;
|
|
114
|
+
public;
|
|
115
|
+
constructor(options) {
|
|
116
|
+
super({ component: "AUTH", name: options?.name });
|
|
117
|
+
if (options?.authorizeUser) {
|
|
118
|
+
this.authorizeUser = options.authorizeUser.bind(this);
|
|
119
|
+
}
|
|
120
|
+
this.protected = options?.protected;
|
|
121
|
+
this.public = options?.public;
|
|
122
|
+
}
|
|
123
|
+
registerOptions(opts) {
|
|
124
|
+
if (opts?.authorizeUser) {
|
|
125
|
+
this.authorizeUser = opts.authorizeUser.bind(this);
|
|
126
|
+
}
|
|
127
|
+
if (opts?.protected) {
|
|
128
|
+
this.protected = opts.protected;
|
|
129
|
+
}
|
|
130
|
+
if (opts?.public) {
|
|
131
|
+
this.public = opts.public;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
// src/index.ts
|
|
137
|
+
var MastraAuthBetterAuth = class extends MastraAuthProvider {
|
|
138
|
+
auth;
|
|
139
|
+
constructor(options) {
|
|
140
|
+
super({ name: options?.name ?? "better-auth" });
|
|
141
|
+
if (!options.auth) {
|
|
142
|
+
throw new Error(
|
|
143
|
+
"Better Auth instance is required. Please provide the auth option with your Better Auth instance created via betterAuth({ ... })"
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
this.auth = options.auth;
|
|
147
|
+
this.registerOptions(options);
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Authenticate a bearer token by verifying the session with Better Auth.
|
|
151
|
+
*
|
|
152
|
+
* This method extracts the session from the request headers using
|
|
153
|
+
* Better Auth's `api.getSession()` endpoint.
|
|
154
|
+
*
|
|
155
|
+
* @param token - The bearer token (session token) to authenticate
|
|
156
|
+
* @param request - The Hono request object containing headers
|
|
157
|
+
* @returns The authenticated user and session, or null if authentication fails
|
|
158
|
+
*/
|
|
159
|
+
async authenticateToken(token, request) {
|
|
160
|
+
try {
|
|
161
|
+
const headers = new Headers();
|
|
162
|
+
const authHeader = request.header("Authorization");
|
|
163
|
+
if (authHeader) {
|
|
164
|
+
headers.set("Authorization", authHeader);
|
|
165
|
+
} else if (token) {
|
|
166
|
+
headers.set("Authorization", `Bearer ${token}`);
|
|
167
|
+
}
|
|
168
|
+
const cookieHeader = request.header("Cookie");
|
|
169
|
+
if (cookieHeader) {
|
|
170
|
+
headers.set("Cookie", cookieHeader);
|
|
171
|
+
}
|
|
172
|
+
const result = await this.auth.api.getSession({
|
|
173
|
+
headers
|
|
174
|
+
});
|
|
175
|
+
if (!result || !result.session || !result.user) {
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
return {
|
|
179
|
+
session: result.session,
|
|
180
|
+
user: result.user
|
|
181
|
+
};
|
|
182
|
+
} catch {
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Authorize a user for access.
|
|
188
|
+
*
|
|
189
|
+
* By default, any authenticated user with a valid session is authorized.
|
|
190
|
+
* You can override this behavior by providing a custom `authorizeUser` function
|
|
191
|
+
* in the constructor options.
|
|
192
|
+
*
|
|
193
|
+
* @param user - The authenticated user and session
|
|
194
|
+
* @returns True if the user is authorized, false otherwise
|
|
195
|
+
*/
|
|
196
|
+
async authorizeUser(user) {
|
|
197
|
+
return !!user?.session?.id && !!user?.user?.id;
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
export { MastraAuthBetterAuth };
|
|
202
|
+
//# sourceMappingURL=index.js.map
|
|
203
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../packages/core/src/logger/constants.ts","../../../packages/core/src/logger/logger.ts","../../../packages/core/src/logger/default-logger.ts","../../../packages/core/src/base.ts","../../../packages/core/src/server/auth.ts","../src/index.ts"],"names":[],"mappings":";A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A,OAAA,CAAQ,GAAA,CAAI,eAAA,EAAiB,CAAA,OAAA,EAAU,KAAK,CAAA,CAAE,CAAA;AAAA,MAChD;AAGA,MAAA,MAAM,YAAA,GAAe,OAAA,CAAQ,MAAA,CAAO,QAAQ,CAAA;AAC5C,MAAA,IAAI,YAAA,EAAc;AAChB,QAAA,OAAA,CAAQ,GAAA,CAAI,UAAU,YAAY,CAAA;AAAA,MACpC;AAGA,MAAA,MAAM,MAAA,GAAS,MAAM,IAAA,CAAK,IAAA,CAAK,IAAI,UAAA,CAAW;AAAA,QAC5C;AAAA,OACD,CAAA;AAED,MAAA,IAAI,CAAC,MAAA,IAAU,CAAC,OAAO,OAAA,IAAW,CAAC,OAAO,IAAA,EAAM;AAC9C,QAAA,OAAO,IAAA;AAAA,MACT;AAEA,MAAA,OAAO;AAAA,QACL,SAAS,MAAA,CAAO,OAAA;AAAA,QAChB,MAAM,MAAA,CAAO;AAAA,OACf;AAAA,IACF,CAAA,CAAA,MAAQ;AAEN,MAAA,OAAO,IAAA;AAAA,IACT;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,MAAM,cAAc,IAAA,EAAwC;AAE1D,IAAA,OAAO,CAAC,CAAC,IAAA,EAAM,OAAA,EAAS,MAAM,CAAC,CAAC,MAAM,IAAA,EAAM,EAAA;AAAA,EAC9C;AACF","file":"index.js","sourcesContent":["// 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} 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 type { MastraAuthProviderOptions } from '@mastra/core/server';\nimport { MastraAuthProvider } from '@mastra/core/server';\n\nimport type { Auth, Session, User } from 'better-auth';\nimport type { HonoRequest } from 'hono';\n\n/**\n * User type returned by Better Auth session verification\n */\nexport interface BetterAuthUser {\n session: Session;\n user: User;\n}\n\ninterface MastraAuthBetterAuthOptions extends MastraAuthProviderOptions<BetterAuthUser> {\n /**\n * The Better Auth instance to use for authentication.\n * This should be the result of calling `betterAuth({ ... })`.\n */\n auth: Auth;\n}\n\n/**\n * Mastra authentication provider for Better Auth.\n *\n * Better Auth is a self-hosted, open-source authentication framework\n * that gives you full control over your authentication system.\n *\n * @example\n * ```typescript\n * import { betterAuth } from 'better-auth';\n * import { MastraAuthBetterAuth } from '@mastra/auth-better-auth';\n *\n * // Create your Better Auth instance\n * const auth = betterAuth({\n * database: {\n * provider: 'postgresql',\n * url: process.env.DATABASE_URL!,\n * },\n * emailAndPassword: {\n * enabled: true,\n * },\n * });\n *\n * // Create the Mastra auth provider\n * const mastraAuth = new MastraAuthBetterAuth({\n * auth,\n * });\n *\n * // Use with Mastra\n * const mastra = new Mastra({\n * server: {\n * auth: mastraAuth,\n * },\n * });\n * ```\n *\n * @see https://better-auth.com for Better Auth documentation\n */\nexport class MastraAuthBetterAuth extends MastraAuthProvider<BetterAuthUser> {\n protected auth: Auth;\n\n constructor(options: MastraAuthBetterAuthOptions) {\n super({ name: options?.name ?? 'better-auth' });\n\n if (!options.auth) {\n throw new Error(\n 'Better Auth instance is required. Please provide the auth option with your Better Auth instance created via betterAuth({ ... })',\n );\n }\n\n this.auth = options.auth;\n\n this.registerOptions(options);\n }\n\n /**\n * Authenticate a bearer token by verifying the session with Better Auth.\n *\n * This method extracts the session from the request headers using\n * Better Auth's `api.getSession()` endpoint.\n *\n * @param token - The bearer token (session token) to authenticate\n * @param request - The Hono request object containing headers\n * @returns The authenticated user and session, or null if authentication fails\n */\n async authenticateToken(token: string, request: HonoRequest): Promise<BetterAuthUser | null> {\n try {\n // Better Auth expects the token to be passed via headers\n // We need to construct headers with the Authorization bearer token\n const headers = new Headers();\n\n // Copy relevant headers from the request\n const authHeader = request.header('Authorization');\n if (authHeader) {\n headers.set('Authorization', authHeader);\n } else if (token) {\n // If no auth header but token is provided, set it\n headers.set('Authorization', `Bearer ${token}`);\n }\n\n // Copy cookie header if present (Better Auth can use cookies for sessions)\n const cookieHeader = request.header('Cookie');\n if (cookieHeader) {\n headers.set('Cookie', cookieHeader);\n }\n\n // Use Better Auth's API to get the session\n const result = await this.auth.api.getSession({\n headers,\n });\n\n if (!result || !result.session || !result.user) {\n return null;\n }\n\n return {\n session: result.session,\n user: result.user,\n };\n } catch {\n // Session verification failed\n return null;\n }\n }\n\n /**\n * Authorize a user for access.\n *\n * By default, any authenticated user with a valid session is authorized.\n * You can override this behavior by providing a custom `authorizeUser` function\n * in the constructor options.\n *\n * @param user - The authenticated user and session\n * @returns True if the user is authorized, false otherwise\n */\n async authorizeUser(user: BetterAuthUser): Promise<boolean> {\n // By default, any authenticated user with a valid session is authorized\n return !!user?.session?.id && !!user?.user?.id;\n }\n}\n"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@mastra/auth-better-auth",
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"description": "Mastra Better Auth integration - self-hosted authentication",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"import": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"default": "./dist/index.js"
|
|
13
|
+
},
|
|
14
|
+
"require": {
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"default": "./dist/index.cjs"
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"./package.json": "./package.json"
|
|
20
|
+
},
|
|
21
|
+
"scripts": {
|
|
22
|
+
"build": "tsup --silent --config tsup.config.ts",
|
|
23
|
+
"build:watch": "tsup --watch --silent --config tsup.config.ts",
|
|
24
|
+
"test": "vitest run",
|
|
25
|
+
"lint": "eslint ."
|
|
26
|
+
},
|
|
27
|
+
"license": "Apache-2.0",
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"better-auth": "^1.2.0"
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"@internal/lint": "workspace:*",
|
|
33
|
+
"@internal/types-builder": "workspace:*",
|
|
34
|
+
"@mastra/core": "workspace:*",
|
|
35
|
+
"@types/node": "22.13.17",
|
|
36
|
+
"hono": "^4.7.10",
|
|
37
|
+
"@vitest/coverage-v8": "catalog:",
|
|
38
|
+
"@vitest/ui": "catalog:",
|
|
39
|
+
"eslint": "^9.37.0",
|
|
40
|
+
"tsup": "^8.5.0",
|
|
41
|
+
"typescript": "^5.8.3",
|
|
42
|
+
"vitest": "catalog:"
|
|
43
|
+
},
|
|
44
|
+
"files": [
|
|
45
|
+
"dist",
|
|
46
|
+
"CHANGELOG.md"
|
|
47
|
+
],
|
|
48
|
+
"homepage": "https://mastra.ai",
|
|
49
|
+
"repository": {
|
|
50
|
+
"type": "git",
|
|
51
|
+
"url": "git+https://github.com/mastra-ai/mastra.git",
|
|
52
|
+
"directory": "auth/better-auth"
|
|
53
|
+
},
|
|
54
|
+
"bugs": {
|
|
55
|
+
"url": "https://github.com/mastra-ai/mastra/issues"
|
|
56
|
+
},
|
|
57
|
+
"engines": {
|
|
58
|
+
"node": ">=22.13.0"
|
|
59
|
+
}
|
|
60
|
+
}
|