-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathauth.ts
More file actions
318 lines (294 loc) · 9 KB
/
Copy pathauth.ts
File metadata and controls
318 lines (294 loc) · 9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
import { MastraAuthBetterAuth } from '@mastra/auth-better-auth'
import { LibsqlDialect } from '@libsql/kysely-libsql'
import { betterAuth, type Auth, type BetterAuthOptions } from 'better-auth'
import { admin, multiSession, oAuthProxy, oneTap, username } from 'better-auth/plugins'
import { apiKey } from '@better-auth/api-key'
import { Kysely, type ColumnType } from 'kysely'
import { log } from './config/logger'
import { mcp } from "better-auth/plugins";
import { agentAuth } from "@better-auth/agent-auth";
import {
fromOpenAPI,
createOpenAPIHandler,
} from "@better-auth/agent-auth/openapi";
//const capabilities = fromOpenAPI(spec);
//const onExecute = createOpenAPIHandler(spec, {
// baseUrl: 'http://localhost:3000/api',
//});
type AuthDateColumn = ColumnType<Date, Date | string, Date | string>;
type AuthNullableDateColumn = ColumnType<
Date | null,
Date | string | null | undefined,
Date | string | null | undefined
>;
type AuthNullableTextColumn = ColumnType<
string | null,
string | null | undefined,
string | null | undefined
>;
type AuthNullableBooleanColumn = ColumnType<
boolean | null,
boolean | null | undefined,
boolean | null | undefined
>;
type AuthNullableNumberColumn = ColumnType<
number | null,
number | null | undefined,
number | null | undefined
>;
/**
* Better Auth tables backed by LibSQL.
*
* The shape mirrors the current Better Auth core tables plus the user/session
* columns added by the username/admin plugins and the API key plugin.
*/
interface BetterAuthDatabase {
user: {
id: string;
name: string;
email: string;
emailVerified: boolean;
image: AuthNullableTextColumn;
createdAt: AuthDateColumn;
updatedAt: AuthDateColumn;
username: AuthNullableTextColumn;
displayUsername: AuthNullableTextColumn;
role: AuthNullableTextColumn;
banned: AuthNullableBooleanColumn;
banReason: AuthNullableTextColumn;
banExpires: AuthNullableDateColumn;
};
session: {
id: string;
userId: string;
expiresAt: AuthDateColumn;
token: string;
ipAddress: AuthNullableTextColumn;
userAgent: AuthNullableTextColumn;
createdAt: AuthDateColumn;
updatedAt: AuthDateColumn;
impersonatedBy: AuthNullableTextColumn;
};
account: {
id: string;
userId: string;
providerId: string;
accountId: string;
accessToken: AuthNullableTextColumn;
refreshToken: AuthNullableTextColumn;
idToken: AuthNullableTextColumn;
accessTokenExpiresAt: AuthNullableDateColumn;
refreshTokenExpiresAt: AuthNullableDateColumn;
scope: AuthNullableTextColumn;
password: AuthNullableTextColumn;
createdAt: AuthDateColumn;
updatedAt: AuthDateColumn;
};
verification: {
id: string;
identifier: string;
value: string;
expiresAt: AuthDateColumn;
createdAt: AuthDateColumn;
updatedAt: AuthDateColumn;
};
apikey: {
id: string;
configId: string;
name: AuthNullableTextColumn;
start: AuthNullableTextColumn;
referenceId: string;
prefix: AuthNullableTextColumn;
key: string;
refillInterval: AuthNullableNumberColumn;
refillAmount: AuthNullableNumberColumn;
lastRefillAt: AuthNullableDateColumn;
enabled: boolean;
rateLimitEnabled: boolean;
rateLimitTimeWindow: AuthNullableNumberColumn;
rateLimitMax: AuthNullableNumberColumn;
requestCount: AuthNullableNumberColumn;
remaining: AuthNullableNumberColumn;
lastRequest: AuthNullableDateColumn;
expiresAt: AuthNullableDateColumn;
createdAt: AuthDateColumn;
updatedAt: AuthDateColumn;
permissions: AuthNullableTextColumn;
metadata: AuthNullableTextColumn;
};
}
const isDevelopment = process.env.NODE_ENV !== 'production'
function trimTrailingSlash(url: string): string {
return url.replace(/\/+$/, '')
}
/**
* Normalizes legacy OAuth callback env values onto Better Auth's default
* Next.js callback route so older local env files do not break Google sign-in.
*/
function resolveGoogleRedirectUri(baseUrl: string): string {
const configuredRedirectUri = process.env.GOOGLE_CLIENT_CALLBACK_URL?.trim()
const defaultRedirectUri = `${trimTrailingSlash(baseUrl)}/api/auth/callback/google`
if (!configuredRedirectUri) {
return defaultRedirectUri
}
if (/\/api\/callback\/?$/.test(configuredRedirectUri)) {
log.warn('Normalizing legacy Google callback URL', {
configuredRedirectUri,
normalizedRedirectUri: defaultRedirectUri,
})
return defaultRedirectUri
}
return configuredRedirectUri
}
const baseURL =
process.env.BETTER_AUTH_URL?.trim() ??
process.env.NEXT_PUBLIC_BETTER_AUTH_URL?.trim() ??
(isDevelopment ? 'http://localhost:3000' : undefined)
const trustedOrigins = [
process.env.BETTER_AUTH_TRUSTED_ORIGIN?.trim(),
process.env.NEXT_PUBLIC_BETTER_AUTH_URL?.trim(),
baseURL,
isDevelopment ? 'http://localhost:3000' : undefined,
isDevelopment ? 'http://127.0.0.1:3000' : undefined,
].filter((origin, index, values): origin is string => Boolean(origin) && values.indexOf(origin) === index)
const socialProviders: BetterAuthOptions['socialProviders'] = {}
const githubClientId = process.env.GITHUB_CLIENT_ID?.trim()
const githubClientSecret = process.env.GITHUB_CLIENT_SECRET?.trim()
const googleClientId = process.env.GOOGLE_CLIENT_ID?.trim()
const googleClientSecret = process.env.GOOGLE_CLIENT_SECRET?.trim()
if (githubClientId && githubClientSecret) {
socialProviders.github = {
clientId: githubClientId,
clientSecret: githubClientSecret,
}
}
if (googleClientId && googleClientSecret && baseURL) {
socialProviders.google = {
clientId: googleClientId,
clientSecret: googleClientSecret,
redirectURI: resolveGoogleRedirectUri(baseURL),
}
}
const authDatabase = new Kysely<BetterAuthDatabase>({
dialect: new LibsqlDialect({
url: process.env.TURSO_DATABASE_URL ?? process.env.TURSO_URL ?? 'file:./database.db',
authToken: process.env.TURSO_AUTH_TOKEN,
}),
});
export const authOptions: BetterAuthOptions = {
appName: 'AgentStack',
emailAndPassword: {
enabled: true,
},
databaseHooks: {
user: {
create: {
before: async (user) => {
const adminEmails = [process.env.USER_EMAIL]
.filter((value): value is string => Boolean(value))
.map((value) => value.trim().toLowerCase());
if (adminEmails.includes(user.email.trim().toLowerCase())) {
return {
data: {
...user,
role: 'admin',
},
};
}
return {
data: {
...user,
role: 'user',
},
};
},
},
},
},
trustedOrigins,
database: {
db: authDatabase,
type: 'sqlite',
},
socialProviders,
baseURL: process.env.BETTER_AUTH_URL ?? 'http://localhost:3000',
secret: process.env.BETTER_AUTH_SECRET ?? 'supersecret',
plugins: [
username(),
admin(),
multiSession(),
apiKey({
enableSessionForAPIKeys: true,
}),
oneTap(),
mcp({
loginPage: "/login" // path to your login page
}),
oAuthProxy({
productionURL: process.env.BETTER_AUTH_PRODUCTION_URL ?? baseURL,
}),
agentAuth({
providerName: "AgentStack",
providerDescription: "AgentStack project information, details about the user, and session context. Plus agents, including their tools, resources, and permissions.",
modes: ["delegated", "autonomous"],
capabilities: [
{
name: "create_issue",
description: "Create an issue in the current workspace.",
input: {
type: "object",
properties: {
title: { type: "string" },
body: { type: "string" },
},
required: ["title"],
},
},
{
name: "deploy_project",
description: "Deploy a project to production.",
input: {
type: "object",
properties: {
projectId: { type: "string" },
},
required: ["projectId"],
},
},
{
name: "list_projects",
description: "List projects the current user can access.",
},
],
async onExecute({ capability, arguments: args, agentSession }) {
switch (capability) {
case "list_projects":
return [{ id: "proj_123", name: "marketing-site" }];
case "deploy_project":
return {
ok: true,
projectId: args?.projectId,
requestedBy: agentSession.user.id,
};
default:
throw new Error(`Unsupported capability: ${capability}`);
}
},
}),
],
session: {
cookieCache: {
enabled: true,
maxAge: 5 * 60, // Cache duration in seconds
},
},
};
const authBetter = betterAuth(authOptions);
export const auth = authBetter as Auth;
/**
* Mastra auth bridge wired to the Better Auth instance.
*/
export const mastraAuth = new MastraAuthBetterAuth({
auth,
signUpEnabled: true,
})