@terreno/api 57.16.2 → 57.17.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/dist/actions.d.ts +26 -3
- package/dist/actions.js +102 -16
- package/dist/api.d.ts +7 -0
- package/dist/api.js +59 -3
- package/dist/auth.d.ts +28 -4
- package/dist/auth.js +140 -15
- package/dist/authRecovery.d.ts +31 -0
- package/dist/authRecovery.js +86 -6
- package/dist/betterAuth.d.ts +86 -0
- package/dist/betterAuthApp.d.ts +17 -0
- package/dist/betterAuthApp.js +12 -1
- package/dist/betterAuthOAuthHandoff.d.ts +24 -0
- package/dist/betterAuthOAuthHandoff.js +305 -0
- package/dist/betterAuthSetup.d.ts +37 -2
- package/dist/betterAuthSetup.js +304 -24
- package/dist/expressServer.d.ts +16 -0
- package/dist/expressServer.js +61 -14
- package/dist/githubAuth.d.ts +9 -0
- package/dist/githubAuth.js +230 -31
- package/dist/index.d.ts +9 -1
- package/dist/index.js +27 -3
- package/dist/mcp/actionTools.d.ts +4 -0
- package/dist/mcp/actionTools.js +158 -0
- package/dist/mcp/auth.d.ts +30 -0
- package/dist/mcp/auth.js +83 -28
- package/dist/mcp/createMCPRequest.d.ts +5 -1
- package/dist/mcp/createMCPRequest.js +3 -3
- package/dist/mcp/handlers.d.ts +3 -0
- package/dist/mcp/handlers.js +43 -27
- package/dist/mcp/oauth.d.ts +14 -0
- package/dist/mcp/oauth.js +618 -0
- package/dist/mcp/oauthMetadata.d.ts +89 -0
- package/dist/mcp/oauthMetadata.js +137 -0
- package/dist/mcp/registry.d.ts +5 -0
- package/dist/mcp/registry.js +9 -1
- package/dist/mcp/server.d.ts +6 -0
- package/dist/mcp/server.js +44 -7
- package/dist/mcp/serviceTokens.js +12 -2
- package/dist/mcp/toolExecution.d.ts +12 -0
- package/dist/mcp/toolExecution.js +60 -0
- package/dist/mcp/toolGenerator.d.ts +4 -1
- package/dist/mcp/toolGenerator.js +26 -60
- package/dist/mcp/types.d.ts +4 -4
- package/dist/models/mcpOAuthAuthorization.d.ts +2 -0
- package/dist/models/mcpOAuthAuthorization.js +86 -0
- package/dist/models/mcpOAuthClient.d.ts +2 -0
- package/dist/models/mcpOAuthClient.js +42 -0
- package/dist/models/mcpOAuthRevokedFamily.d.ts +2 -0
- package/dist/models/mcpOAuthRevokedFamily.js +36 -0
- package/dist/models/mcpOAuthToken.d.ts +12 -0
- package/dist/models/mcpOAuthToken.js +159 -0
- package/dist/models/mcpServiceToken.d.ts +1 -0
- package/dist/models/mcpServiceToken.js +21 -4
- package/dist/permissions.d.ts +7 -0
- package/dist/permissions.js +18 -1
- package/dist/rateLimit/policies.d.ts +4 -0
- package/dist/rateLimit/policies.js +46 -7
- package/dist/rbac/access.js +1 -0
- package/dist/rbac/membershipOrgAdminSource.d.ts +4 -0
- package/dist/rbac/membershipOrgAdminSource.js +5 -0
- package/dist/rbac/modelRouterAccess.d.ts +7 -1
- package/dist/rbac/modelRouterAccess.js +37 -24
- package/dist/rbac/realtimeAccess.js +17 -3
- package/dist/rbac/resolve.js +66 -9
- package/dist/rbac/roleManager.js +60 -5
- package/dist/rbac/roleModel.js +1 -1
- package/dist/rbac/statements.d.ts +1 -1
- package/dist/rbac/statements.js +13 -1
- package/dist/rbac/types.d.ts +12 -0
- package/dist/rbac/userWriteGuards.d.ts +50 -0
- package/dist/rbac/userWriteGuards.js +156 -0
- package/dist/realtime/changeStreamWatcher.d.ts +4 -1
- package/dist/realtime/changeStreamWatcher.js +157 -73
- package/dist/realtime/queryMatcher.d.ts +3 -0
- package/dist/realtime/queryMatcher.js +25 -10
- package/dist/realtime/realtimeApp.d.ts +16 -1
- package/dist/realtime/realtimeApp.js +76 -8
- package/dist/realtime/socketAuth.d.ts +17 -6
- package/dist/realtime/socketAuth.js +77 -16
- package/dist/realtime/types.d.ts +8 -5
- package/dist/requestContext.d.ts +22 -0
- package/dist/requestContext.js +22 -1
- package/dist/seedRunner.js +3 -1
- package/dist/sortFields.d.ts +33 -0
- package/dist/sortFields.js +55 -0
- package/dist/sync/executors.js +140 -2
- package/dist/sync/models.d.ts +2 -0
- package/dist/sync/models.js +5 -0
- package/dist/sync/mutationHandler.js +70 -7
- package/dist/sync/routes.js +4 -2
- package/dist/sync/syncSeqPlugin.js +6 -5
- package/dist/terrenoApp.d.ts +14 -0
- package/dist/terrenoApp.js +21 -6
- package/dist/types/mcpOAuth.d.ts +101 -0
- package/dist/types/mcpOAuth.js +2 -0
- package/dist/types/mcpServiceToken.d.ts +8 -0
- package/package.json +3 -3
- package/src/actions.test.ts +118 -0
- package/src/actions.ts +139 -17
- package/src/api.arrayOperations.test.ts +78 -0
- package/src/api.test.ts +36 -0
- package/src/api.ts +76 -4
- package/src/auth.test.ts +521 -3
- package/src/auth.ts +171 -17
- package/src/authRecovery.test.ts +99 -0
- package/src/authRecovery.ts +117 -5
- package/src/authVerification.test.ts +3 -3
- package/src/betterAuth.ts +104 -1
- package/src/betterAuthApp.test.ts +634 -1
- package/src/betterAuthApp.ts +28 -0
- package/src/betterAuthOAuthHandoff.test.ts +946 -0
- package/src/betterAuthOAuthHandoff.ts +375 -0
- package/src/betterAuthSetup.test.ts +393 -4
- package/src/betterAuthSetup.ts +402 -29
- package/src/expressServer.test.ts +93 -0
- package/src/expressServer.ts +81 -14
- package/src/githubAuth.test.ts +448 -6
- package/src/githubAuth.ts +276 -34
- package/src/index.ts +35 -1
- package/src/mcp/actionTools.test.ts +498 -0
- package/src/mcp/actionTools.ts +220 -0
- package/src/mcp/auth.test.ts +114 -1
- package/src/mcp/auth.ts +122 -35
- package/src/mcp/createMCPRequest.ts +8 -2
- package/src/mcp/handlers.test.ts +27 -0
- package/src/mcp/handlers.ts +21 -6
- package/src/mcp/oauth.test.ts +1026 -0
- package/src/mcp/oauth.ts +798 -0
- package/src/mcp/oauthMetadata.ts +234 -0
- package/src/mcp/registry.ts +11 -0
- package/src/mcp/server.ts +54 -14
- package/src/mcp/serviceTokens.ts +16 -3
- package/src/mcp/toolExecution.ts +67 -0
- package/src/mcp/toolGenerator.ts +27 -83
- package/src/mcp/types.ts +4 -4
- package/src/models/mcpOAuthAuthorization.ts +97 -0
- package/src/models/mcpOAuthClient.ts +49 -0
- package/src/models/mcpOAuthRevokedFamily.ts +47 -0
- package/src/models/mcpOAuthToken.test.ts +82 -0
- package/src/models/mcpOAuthToken.ts +195 -0
- package/src/models/mcpServiceToken.ts +26 -2
- package/src/permissions.ts +17 -0
- package/src/rateLimit/policies.ts +54 -10
- package/src/rateLimit/rateLimit.test.ts +41 -0
- package/src/rbac/access.ts +1 -0
- package/src/rbac/membershipOrgAdminSource.ts +5 -0
- package/src/rbac/modelRouterAccess.ts +40 -23
- package/src/rbac/realtimeAccess.test.ts +43 -0
- package/src/rbac/realtimeAccess.ts +23 -3
- package/src/rbac/resolve.test.ts +179 -1
- package/src/rbac/resolve.ts +78 -9
- package/src/rbac/roleManager.test.ts +132 -0
- package/src/rbac/roleManager.ts +69 -5
- package/src/rbac/roleModel.ts +1 -1
- package/src/rbac/statements.ts +14 -1
- package/src/rbac/types.ts +12 -0
- package/src/rbac/userWriteGuards.test.ts +407 -0
- package/src/rbac/userWriteGuards.ts +185 -0
- package/src/realtime/changeStreamWatcher.ts +203 -75
- package/src/realtime/queryMatcher.ts +30 -13
- package/src/realtime/realtime.test.ts +132 -0
- package/src/realtime/realtimeApp.ts +94 -10
- package/src/realtime/realtimeAppSetup.test.ts +282 -1
- package/src/realtime/socketAuth.test.ts +140 -8
- package/src/realtime/socketAuth.ts +90 -19
- package/src/realtime/types.ts +8 -5
- package/src/requestContext.ts +52 -1
- package/src/requestCredential.test.ts +89 -0
- package/src/seedRunner.test.ts +21 -0
- package/src/seedRunner.ts +3 -1
- package/src/sortFields.ts +69 -0
- package/src/sync/executors.test.ts +382 -3
- package/src/sync/executors.ts +179 -4
- package/src/sync/models.ts +8 -0
- package/src/sync/mutationHandler.test.ts +166 -2
- package/src/sync/mutationHandler.ts +97 -5
- package/src/sync/routes.ts +4 -2
- package/src/sync/syncFrontier.test.ts +11 -0
- package/src/sync/syncPhaseC.test.ts +18 -0
- package/src/sync/syncSeqPlugin.ts +6 -5
- package/src/sync/syncSocket.test.ts +92 -0
- package/src/terrenoApp.ts +36 -21
- package/src/types/mcpOAuth.ts +129 -0
- package/src/types/mcpServiceToken.ts +6 -1
|
@@ -1,10 +1,19 @@
|
|
|
1
|
-
import {afterAll, afterEach, describe, expect, it} from "bun:test";
|
|
1
|
+
import {afterAll, afterEach, beforeEach, describe, expect, it} from "bun:test";
|
|
2
|
+
import type {BetterAuthPlugin} from "better-auth";
|
|
3
|
+
import {createAuthEndpoint} from "better-auth/api";
|
|
2
4
|
import express from "express";
|
|
5
|
+
import {DateTime} from "luxon";
|
|
3
6
|
import {MongoMemoryServer} from "mongodb-memory-server";
|
|
4
7
|
import mongoose, {Schema} from "mongoose";
|
|
8
|
+
import passportLocalMongoose from "passport-local-mongoose";
|
|
9
|
+
import supertest from "supertest";
|
|
10
|
+
import {modelRouter} from "./api";
|
|
5
11
|
import type {UserModel} from "./auth";
|
|
6
12
|
import type {BetterAuthConfig} from "./betterAuth";
|
|
7
13
|
import {BetterAuthApp} from "./betterAuthApp";
|
|
14
|
+
import {clearMCPRegistry} from "./mcp/registry";
|
|
15
|
+
import {Permissions} from "./permissions";
|
|
16
|
+
import {TerrenoApp} from "./terrenoApp";
|
|
8
17
|
|
|
9
18
|
let conn: mongoose.Connection;
|
|
10
19
|
let mongod: MongoMemoryServer;
|
|
@@ -113,4 +122,628 @@ describe("BetterAuthApp", () => {
|
|
|
113
122
|
expect(() => plugin.register(app)).not.toThrow();
|
|
114
123
|
expect(plugin.getAuth()).toBeDefined();
|
|
115
124
|
});
|
|
125
|
+
|
|
126
|
+
it("mounts endpoints of a plugin passed in config.plugins under the base path", async () => {
|
|
127
|
+
await setup;
|
|
128
|
+
const pingPlugin = {
|
|
129
|
+
endpoints: {
|
|
130
|
+
terrenoPing: createAuthEndpoint("/terreno-test/ping", {method: "GET"}, async (ctx) =>
|
|
131
|
+
ctx.json({ok: true})
|
|
132
|
+
),
|
|
133
|
+
},
|
|
134
|
+
id: "terreno-test",
|
|
135
|
+
} satisfies BetterAuthPlugin;
|
|
136
|
+
const app = express();
|
|
137
|
+
new BetterAuthApp({
|
|
138
|
+
config: makeConfig({basePath: "/custom/auth", plugins: [pingPlugin]}),
|
|
139
|
+
}).register(app);
|
|
140
|
+
|
|
141
|
+
const res = await supertest(app).get("/custom/auth/terreno-test/ping");
|
|
142
|
+
|
|
143
|
+
expect(res.status).toBe(200);
|
|
144
|
+
expect(res.body).toEqual({ok: true});
|
|
145
|
+
});
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
describe("BetterAuthApp on TerrenoApp with a cookie-less bearer from another site", () => {
|
|
149
|
+
const API_ORIGIN = "http://localhost:3000";
|
|
150
|
+
const WEB_ORIGIN = "https://web.example.com";
|
|
151
|
+
const PASSWORD = "password-123456";
|
|
152
|
+
|
|
153
|
+
interface CrossSiteNoteFields {
|
|
154
|
+
title?: string;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
interface CorsCase {
|
|
158
|
+
allowOrigin: string;
|
|
159
|
+
corsOrigin?: string[];
|
|
160
|
+
name: string;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
interface CrossSiteUserFields {
|
|
164
|
+
admin?: boolean;
|
|
165
|
+
betterAuthId?: string;
|
|
166
|
+
email: string;
|
|
167
|
+
name?: string;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// TerrenoApp's JWT setup needs passport-local-mongoose's createStrategy on the user model.
|
|
171
|
+
const getCrossSiteUserModel = (): mongoose.Model<CrossSiteUserFields> => {
|
|
172
|
+
if (mongoose.models.BetterAuthCrossSiteUser) {
|
|
173
|
+
return mongoose.models.BetterAuthCrossSiteUser as mongoose.Model<CrossSiteUserFields>;
|
|
174
|
+
}
|
|
175
|
+
const schema = new Schema<CrossSiteUserFields>({
|
|
176
|
+
admin: {default: false, description: "Whether the user is an admin", type: Boolean},
|
|
177
|
+
betterAuthId: {description: "Linked Better Auth user id", index: true, type: String},
|
|
178
|
+
email: {description: "Email address", required: true, type: String},
|
|
179
|
+
name: {description: "Display name", type: String},
|
|
180
|
+
});
|
|
181
|
+
schema.plugin(
|
|
182
|
+
passportLocalMongoose as unknown as (
|
|
183
|
+
target: Schema,
|
|
184
|
+
options?: Record<string, unknown>
|
|
185
|
+
) => void,
|
|
186
|
+
{usernameField: "email"}
|
|
187
|
+
);
|
|
188
|
+
return mongoose.model<CrossSiteUserFields>("BetterAuthCrossSiteUser", schema);
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
const getCrossSiteNoteModel = (): mongoose.Model<CrossSiteNoteFields> => {
|
|
192
|
+
if (mongoose.models.BetterAuthCrossSiteNote) {
|
|
193
|
+
return mongoose.models.BetterAuthCrossSiteNote as mongoose.Model<CrossSiteNoteFields>;
|
|
194
|
+
}
|
|
195
|
+
const schema = new Schema<CrossSiteNoteFields>({
|
|
196
|
+
title: {description: "Note title", type: String},
|
|
197
|
+
});
|
|
198
|
+
return mongoose.model<CrossSiteNoteFields>("BetterAuthCrossSiteNote", schema);
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
const CrossSiteUser = getCrossSiteUserModel();
|
|
202
|
+
const CrossSiteNote = getCrossSiteNoteModel();
|
|
203
|
+
const crossSiteUserModel = CrossSiteUser as unknown as UserModel;
|
|
204
|
+
|
|
205
|
+
const mcpRequest = (
|
|
206
|
+
method: string,
|
|
207
|
+
params: Record<string, unknown>
|
|
208
|
+
): Record<string, unknown> => ({
|
|
209
|
+
id: 1,
|
|
210
|
+
jsonrpc: "2.0",
|
|
211
|
+
method,
|
|
212
|
+
params,
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
interface CrossSiteApp {
|
|
216
|
+
app: express.Application;
|
|
217
|
+
betterAuthApp: BetterAuthApp;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// The API is served from API_ORIGIN; the web app on WEB_ORIGIN is a different site.
|
|
221
|
+
const buildCrossSiteApp = (corsOrigin?: string[]): CrossSiteApp => {
|
|
222
|
+
const betterAuthApp = new BetterAuthApp({
|
|
223
|
+
config: {
|
|
224
|
+
baseURL: API_ORIGIN,
|
|
225
|
+
enabled: true,
|
|
226
|
+
// Better Auth skips origin checks when NODE_ENV is "test"; turn them back on so these
|
|
227
|
+
// cases run against production's trustedOrigins enforcement.
|
|
228
|
+
options: {advanced: {disableOriginCheck: false}},
|
|
229
|
+
secret: "test-secret-at-least-32-characters-long",
|
|
230
|
+
trustedOrigins: [WEB_ORIGIN],
|
|
231
|
+
},
|
|
232
|
+
userModel: crossSiteUserModel,
|
|
233
|
+
});
|
|
234
|
+
const noteRouter = modelRouter("/crossSiteNotes", CrossSiteNote, {
|
|
235
|
+
mcp: {methods: ["list"], toolPrefix: "crosssitenotes"},
|
|
236
|
+
permissions: {
|
|
237
|
+
create: [],
|
|
238
|
+
delete: [],
|
|
239
|
+
list: [Permissions.IsAuthenticated],
|
|
240
|
+
read: [Permissions.IsAuthenticated],
|
|
241
|
+
update: [],
|
|
242
|
+
},
|
|
243
|
+
});
|
|
244
|
+
const app = new TerrenoApp({
|
|
245
|
+
...(corsOrigin ? {corsOrigin} : {}),
|
|
246
|
+
skipListen: true,
|
|
247
|
+
userModel: crossSiteUserModel,
|
|
248
|
+
})
|
|
249
|
+
.register(betterAuthApp)
|
|
250
|
+
.register(noteRouter)
|
|
251
|
+
.build();
|
|
252
|
+
return {app, betterAuthApp};
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
const signUp = async (betterAuthApp: BetterAuthApp): Promise<string> => {
|
|
256
|
+
const email = `cross-site-${DateTime.now().toMillis()}-${Math.random()}@example.com`;
|
|
257
|
+
await betterAuthApp.ensureAuth().api.signUpEmail({
|
|
258
|
+
body: {email, name: "Cross Site User", password: PASSWORD},
|
|
259
|
+
});
|
|
260
|
+
return email;
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
// What a browser's fetch with credentials: "omit" sends: Origin and Fetch Metadata, no cookie.
|
|
264
|
+
const signInFrom = (app: express.Application, email: string, origin: string): supertest.Test =>
|
|
265
|
+
supertest(app)
|
|
266
|
+
.post("/api/auth/sign-in/email")
|
|
267
|
+
.set("origin", origin)
|
|
268
|
+
.set("sec-fetch-site", "cross-site")
|
|
269
|
+
.set("sec-fetch-mode", "cors")
|
|
270
|
+
.set("content-type", "application/json")
|
|
271
|
+
.send({email, password: PASSWORD});
|
|
272
|
+
|
|
273
|
+
beforeEach(async () => {
|
|
274
|
+
clearMCPRegistry();
|
|
275
|
+
await CrossSiteUser.deleteMany({});
|
|
276
|
+
await CrossSiteNote.deleteMany({});
|
|
277
|
+
// Better Auth's own collections on the default connection.
|
|
278
|
+
for (const collection of ["user", "session", "account"]) {
|
|
279
|
+
await mongoose.connection.db?.collection(collection).deleteMany({});
|
|
280
|
+
}
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
afterAll(() => {
|
|
284
|
+
clearMCPRegistry();
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
const corsCases: CorsCase[] = [
|
|
288
|
+
{allowOrigin: "*", name: "the default corsOrigin"},
|
|
289
|
+
{allowOrigin: WEB_ORIGIN, corsOrigin: [WEB_ORIGIN], name: "an explicit corsOrigin"},
|
|
290
|
+
];
|
|
291
|
+
|
|
292
|
+
for (const {name, corsOrigin, allowOrigin} of corsCases) {
|
|
293
|
+
describe(`with ${name}`, () => {
|
|
294
|
+
it("allows the preflight for an authorization header from the web origin", async () => {
|
|
295
|
+
const {app} = buildCrossSiteApp(corsOrigin);
|
|
296
|
+
|
|
297
|
+
for (const [method, path] of [
|
|
298
|
+
["POST", "/api/auth/sign-in/email"],
|
|
299
|
+
["GET", "/auth/me"],
|
|
300
|
+
["GET", "/crossSiteNotes"],
|
|
301
|
+
["POST", "/mcp"],
|
|
302
|
+
]) {
|
|
303
|
+
const res = await supertest(app)
|
|
304
|
+
.options(path)
|
|
305
|
+
.set("origin", WEB_ORIGIN)
|
|
306
|
+
.set("access-control-request-method", method)
|
|
307
|
+
.set("access-control-request-headers", "authorization,content-type");
|
|
308
|
+
|
|
309
|
+
expect(res.status).toBe(204);
|
|
310
|
+
expect(res.headers["access-control-allow-origin"]).toBe(allowOrigin);
|
|
311
|
+
expect(res.headers["access-control-allow-headers"]).toContain("authorization");
|
|
312
|
+
expect(res.headers["access-control-allow-headers"]).toContain("content-type");
|
|
313
|
+
expect(res.headers["access-control-allow-methods"]).toContain(method);
|
|
314
|
+
}
|
|
315
|
+
});
|
|
316
|
+
|
|
317
|
+
it("returns set-auth-token from a cookie-less sign-in and exposes it to the page", async () => {
|
|
318
|
+
const {app, betterAuthApp} = buildCrossSiteApp(corsOrigin);
|
|
319
|
+
const email = await signUp(betterAuthApp);
|
|
320
|
+
|
|
321
|
+
const res = await signInFrom(app, email, WEB_ORIGIN);
|
|
322
|
+
|
|
323
|
+
expect(res.status).toBe(200);
|
|
324
|
+
expect(res.headers["access-control-allow-origin"]).toBe(allowOrigin);
|
|
325
|
+
expect(res.headers["set-auth-token"]).toBeTruthy();
|
|
326
|
+
const exposed = String(res.headers["access-control-expose-headers"] ?? "")
|
|
327
|
+
.split(",")
|
|
328
|
+
.map((header) => header.trim().toLowerCase());
|
|
329
|
+
expect(exposed).toContain("set-auth-token");
|
|
330
|
+
});
|
|
331
|
+
|
|
332
|
+
it("authenticates /auth/me, a model route, and /mcp with only the bearer", async () => {
|
|
333
|
+
const {app, betterAuthApp} = buildCrossSiteApp(corsOrigin);
|
|
334
|
+
const email = await signUp(betterAuthApp);
|
|
335
|
+
const signIn = await signInFrom(app, email, WEB_ORIGIN);
|
|
336
|
+
const token = signIn.headers["set-auth-token"] as string;
|
|
337
|
+
expect(signIn.status).toBe(200);
|
|
338
|
+
expect(token).toBeTruthy();
|
|
339
|
+
await CrossSiteNote.create({title: "Cross-site note"});
|
|
340
|
+
|
|
341
|
+
const me = await supertest(app)
|
|
342
|
+
.get("/auth/me")
|
|
343
|
+
.set("origin", WEB_ORIGIN)
|
|
344
|
+
.set("authorization", `Bearer ${token}`);
|
|
345
|
+
expect(me.status).toBe(200);
|
|
346
|
+
expect(me.body.data.email).toBe(email);
|
|
347
|
+
expect(me.headers["access-control-allow-origin"]).toBe(allowOrigin);
|
|
348
|
+
|
|
349
|
+
const notes = await supertest(app)
|
|
350
|
+
.get("/crossSiteNotes")
|
|
351
|
+
.set("origin", WEB_ORIGIN)
|
|
352
|
+
.set("authorization", `Bearer ${token}`);
|
|
353
|
+
expect(notes.status).toBe(200);
|
|
354
|
+
expect(notes.body.data.map((note: CrossSiteNoteFields) => note.title)).toEqual([
|
|
355
|
+
"Cross-site note",
|
|
356
|
+
]);
|
|
357
|
+
|
|
358
|
+
const initialize = await supertest(app)
|
|
359
|
+
.post("/mcp")
|
|
360
|
+
.set("origin", WEB_ORIGIN)
|
|
361
|
+
.set("accept", "application/json, text/event-stream")
|
|
362
|
+
.set("authorization", `Bearer ${token}`)
|
|
363
|
+
.send(
|
|
364
|
+
mcpRequest("initialize", {
|
|
365
|
+
capabilities: {},
|
|
366
|
+
clientInfo: {name: "cross-site-test", version: "1.0.0"},
|
|
367
|
+
protocolVersion: "2024-11-05",
|
|
368
|
+
})
|
|
369
|
+
);
|
|
370
|
+
expect(initialize.status).toBe(200);
|
|
371
|
+
expect(initialize.text).toContain("terreno-api-mcp");
|
|
372
|
+
|
|
373
|
+
// The list tool needs an authenticated caller, so its rows prove /mcp saw the user.
|
|
374
|
+
const listCall = await supertest(app)
|
|
375
|
+
.post("/mcp")
|
|
376
|
+
.set("origin", WEB_ORIGIN)
|
|
377
|
+
.set("accept", "application/json, text/event-stream")
|
|
378
|
+
.set("authorization", `Bearer ${token}`)
|
|
379
|
+
.send(mcpRequest("tools/call", {arguments: {}, name: "crosssitenotes_list"}));
|
|
380
|
+
expect(listCall.status).toBe(200);
|
|
381
|
+
expect(listCall.text).not.toContain("Permission denied");
|
|
382
|
+
expect(listCall.text).toContain("Cross-site note");
|
|
383
|
+
});
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
it("refuses an anonymous request to the model route and the list tool", async () => {
|
|
388
|
+
const {app} = buildCrossSiteApp();
|
|
389
|
+
await CrossSiteNote.create({title: "Cross-site note"});
|
|
390
|
+
|
|
391
|
+
const notes = await supertest(app).get("/crossSiteNotes").set("origin", WEB_ORIGIN);
|
|
392
|
+
const listCall = await supertest(app)
|
|
393
|
+
.post("/mcp")
|
|
394
|
+
.set("origin", WEB_ORIGIN)
|
|
395
|
+
.set("accept", "application/json, text/event-stream")
|
|
396
|
+
.send(mcpRequest("tools/call", {arguments: {}, name: "crosssitenotes_list"}));
|
|
397
|
+
|
|
398
|
+
expect(notes.status).toBe(401);
|
|
399
|
+
expect(listCall.text).toContain("Permission denied: authentication required");
|
|
400
|
+
});
|
|
401
|
+
|
|
402
|
+
it("rejects a cookie-less sign-in from an origin missing from trustedOrigins", async () => {
|
|
403
|
+
const {app, betterAuthApp} = buildCrossSiteApp();
|
|
404
|
+
const email = await signUp(betterAuthApp);
|
|
405
|
+
|
|
406
|
+
const res = await signInFrom(app, email, "https://untrusted.example.com");
|
|
407
|
+
|
|
408
|
+
expect(res.status).toBe(403);
|
|
409
|
+
expect(res.body.code).toBe("INVALID_ORIGIN");
|
|
410
|
+
expect(res.headers["set-auth-token"]).toBeUndefined();
|
|
411
|
+
});
|
|
412
|
+
});
|
|
413
|
+
|
|
414
|
+
describe("BetterAuthApp credential changes on a dual-enrolled account", () => {
|
|
415
|
+
const OLD_PASSWORD = "old-password-123";
|
|
416
|
+
const NEW_PASSWORD = "new-password-456";
|
|
417
|
+
|
|
418
|
+
interface DualUserFields {
|
|
419
|
+
betterAuthId?: string;
|
|
420
|
+
email: string;
|
|
421
|
+
name?: string;
|
|
422
|
+
tokenEpoch?: number;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
const getDualUserModel = (): mongoose.Model<DualUserFields> => {
|
|
426
|
+
if (mongoose.models.BetterAuthAppDualUser) {
|
|
427
|
+
return mongoose.models.BetterAuthAppDualUser as mongoose.Model<DualUserFields>;
|
|
428
|
+
}
|
|
429
|
+
const schema = new Schema<DualUserFields>({
|
|
430
|
+
betterAuthId: {description: "Linked Better Auth user id", index: true, type: String},
|
|
431
|
+
email: {description: "Email address", required: true, type: String},
|
|
432
|
+
name: {description: "Display name", type: String},
|
|
433
|
+
tokenEpoch: {default: 0, description: "Refresh token epoch", type: Number},
|
|
434
|
+
});
|
|
435
|
+
schema.plugin(
|
|
436
|
+
passportLocalMongoose as unknown as (
|
|
437
|
+
target: Schema,
|
|
438
|
+
options?: Record<string, unknown>
|
|
439
|
+
) => void,
|
|
440
|
+
{usernameCaseInsensitive: true, usernameField: "email"}
|
|
441
|
+
);
|
|
442
|
+
return mongoose.model<DualUserFields>("BetterAuthAppDualUser", schema);
|
|
443
|
+
};
|
|
444
|
+
|
|
445
|
+
const DualUser = getDualUserModel();
|
|
446
|
+
const mails: {text: string; to: string}[] = [];
|
|
447
|
+
|
|
448
|
+
const buildApp = (): {app: express.Application; betterAuthApp: BetterAuthApp} => {
|
|
449
|
+
const betterAuthApp = new BetterAuthApp({
|
|
450
|
+
config: {
|
|
451
|
+
baseURL: "http://localhost:3000",
|
|
452
|
+
enabled: true,
|
|
453
|
+
publicAppUrl: "http://localhost:8082",
|
|
454
|
+
secret: "test-secret-at-least-32-characters-long",
|
|
455
|
+
sendMail: async (message): Promise<void> => {
|
|
456
|
+
mails.push({text: message.text, to: message.to});
|
|
457
|
+
},
|
|
458
|
+
},
|
|
459
|
+
userModel: DualUser as unknown as UserModel,
|
|
460
|
+
});
|
|
461
|
+
const app = new TerrenoApp({
|
|
462
|
+
skipListen: true,
|
|
463
|
+
userModel: DualUser as unknown as UserModel,
|
|
464
|
+
})
|
|
465
|
+
.register(betterAuthApp)
|
|
466
|
+
.build();
|
|
467
|
+
return {app, betterAuthApp};
|
|
468
|
+
};
|
|
469
|
+
|
|
470
|
+
// Signs up through Better Auth, creates the app user, and gives it the same legacy password,
|
|
471
|
+
// as the JWT reset bridge does. Returns the Better Auth bearer and a legacy refresh token.
|
|
472
|
+
const enrollDualUser = async (
|
|
473
|
+
app: express.Application,
|
|
474
|
+
betterAuthApp: BetterAuthApp,
|
|
475
|
+
email: string
|
|
476
|
+
): Promise<{bearer: string; refreshToken: string}> => {
|
|
477
|
+
const signUp = await betterAuthApp.ensureAuth().api.signUpEmail({
|
|
478
|
+
body: {email, name: "Dual User", password: OLD_PASSWORD},
|
|
479
|
+
});
|
|
480
|
+
const bearer = signUp.token as string;
|
|
481
|
+
await supertest(app).get("/auth/me").set("authorization", `Bearer ${bearer}`).expect(200);
|
|
482
|
+
const appUser = await DualUser.findOne({email});
|
|
483
|
+
await (appUser as unknown as {setPassword: (password: string) => Promise<void>}).setPassword(
|
|
484
|
+
OLD_PASSWORD
|
|
485
|
+
);
|
|
486
|
+
await appUser?.save();
|
|
487
|
+
const login = await supertest(app)
|
|
488
|
+
.post("/auth/login")
|
|
489
|
+
.send({email, password: OLD_PASSWORD})
|
|
490
|
+
.expect(200);
|
|
491
|
+
return {bearer, refreshToken: login.body.data.refreshToken as string};
|
|
492
|
+
};
|
|
493
|
+
|
|
494
|
+
beforeEach(async () => {
|
|
495
|
+
mails.length = 0;
|
|
496
|
+
await DualUser.deleteMany({});
|
|
497
|
+
for (const collection of ["user", "session", "account", "verification"]) {
|
|
498
|
+
await mongoose.connection.db?.collection(collection).deleteMany({});
|
|
499
|
+
}
|
|
500
|
+
});
|
|
501
|
+
|
|
502
|
+
it("retires the legacy password and refresh tokens after a Better Auth change-password", async () => {
|
|
503
|
+
const {app, betterAuthApp} = buildApp();
|
|
504
|
+
const email = "dual-change@example.com";
|
|
505
|
+
const {bearer, refreshToken} = await enrollDualUser(app, betterAuthApp, email);
|
|
506
|
+
|
|
507
|
+
await supertest(app)
|
|
508
|
+
.post("/api/auth/change-password")
|
|
509
|
+
.set("authorization", `Bearer ${bearer}`)
|
|
510
|
+
.send({currentPassword: OLD_PASSWORD, newPassword: NEW_PASSWORD, revokeOtherSessions: true})
|
|
511
|
+
.expect(200);
|
|
512
|
+
|
|
513
|
+
await supertest(app).post("/auth/login").send({email, password: OLD_PASSWORD}).expect(401);
|
|
514
|
+
await supertest(app).post("/auth/login").send({email, password: NEW_PASSWORD}).expect(200);
|
|
515
|
+
await supertest(app).post("/auth/refresh_token").send({refreshToken}).expect(401);
|
|
516
|
+
});
|
|
517
|
+
|
|
518
|
+
it("does not touch the legacy credential when change-password fails", async () => {
|
|
519
|
+
const {app, betterAuthApp} = buildApp();
|
|
520
|
+
const email = "dual-change-fail@example.com";
|
|
521
|
+
const {bearer, refreshToken} = await enrollDualUser(app, betterAuthApp, email);
|
|
522
|
+
|
|
523
|
+
const res = await supertest(app)
|
|
524
|
+
.post("/api/auth/change-password")
|
|
525
|
+
.set("authorization", `Bearer ${bearer}`)
|
|
526
|
+
.send({currentPassword: "wrong-password-1", newPassword: NEW_PASSWORD});
|
|
527
|
+
expect(res.status).toBe(400);
|
|
528
|
+
|
|
529
|
+
await supertest(app).post("/auth/login").send({email, password: OLD_PASSWORD}).expect(200);
|
|
530
|
+
await supertest(app).post("/auth/refresh_token").send({refreshToken}).expect(200);
|
|
531
|
+
});
|
|
532
|
+
|
|
533
|
+
it("does not create a legacy password for a Better Auth only account", async () => {
|
|
534
|
+
const {app, betterAuthApp} = buildApp();
|
|
535
|
+
const email = "ba-only-change@example.com";
|
|
536
|
+
const signUp = await betterAuthApp.ensureAuth().api.signUpEmail({
|
|
537
|
+
body: {email, name: "Better Auth Only", password: OLD_PASSWORD},
|
|
538
|
+
});
|
|
539
|
+
const bearer = signUp.token as string;
|
|
540
|
+
await supertest(app).get("/auth/me").set("authorization", `Bearer ${bearer}`).expect(200);
|
|
541
|
+
|
|
542
|
+
await supertest(app)
|
|
543
|
+
.post("/api/auth/change-password")
|
|
544
|
+
.set("authorization", `Bearer ${bearer}`)
|
|
545
|
+
.send({currentPassword: OLD_PASSWORD, newPassword: NEW_PASSWORD})
|
|
546
|
+
.expect(200);
|
|
547
|
+
|
|
548
|
+
await supertest(app).post("/auth/login").send({email, password: NEW_PASSWORD}).expect(401);
|
|
549
|
+
const appUser = await DualUser.findOne({email}).lean();
|
|
550
|
+
expect(appUser?.tokenEpoch).toBe(1);
|
|
551
|
+
});
|
|
552
|
+
|
|
553
|
+
it("revokes legacy refresh tokens when Better Auth revokes all sessions", async () => {
|
|
554
|
+
const {app, betterAuthApp} = buildApp();
|
|
555
|
+
const email = "dual-revoke@example.com";
|
|
556
|
+
const {bearer, refreshToken} = await enrollDualUser(app, betterAuthApp, email);
|
|
557
|
+
|
|
558
|
+
await supertest(app)
|
|
559
|
+
.post("/api/auth/revoke-sessions")
|
|
560
|
+
.set("authorization", `Bearer ${bearer}`)
|
|
561
|
+
.send({})
|
|
562
|
+
.expect(200);
|
|
563
|
+
|
|
564
|
+
await supertest(app).post("/auth/refresh_token").send({refreshToken}).expect(401);
|
|
565
|
+
});
|
|
566
|
+
|
|
567
|
+
it("syncs a Better Auth password reset to the legacy password", async () => {
|
|
568
|
+
const {app, betterAuthApp} = buildApp();
|
|
569
|
+
const email = "dual-reset@example.com";
|
|
570
|
+
const {refreshToken} = await enrollDualUser(app, betterAuthApp, email);
|
|
571
|
+
|
|
572
|
+
await supertest(app)
|
|
573
|
+
.post("/api/auth/request-password-reset")
|
|
574
|
+
.send({email, redirectTo: "/reset"})
|
|
575
|
+
.expect(200);
|
|
576
|
+
const resetMail = mails.find(
|
|
577
|
+
(mail) => mail.to === email && mail.text.includes("resetPassword")
|
|
578
|
+
);
|
|
579
|
+
const token = decodeURIComponent(resetMail?.text.match(/token=([^\s&]+)/)?.[1] ?? "");
|
|
580
|
+
expect(token.length).toBeGreaterThan(0);
|
|
581
|
+
|
|
582
|
+
await supertest(app)
|
|
583
|
+
.post("/api/auth/reset-password")
|
|
584
|
+
.send({newPassword: NEW_PASSWORD, token})
|
|
585
|
+
.expect(200);
|
|
586
|
+
|
|
587
|
+
await supertest(app).post("/auth/login").send({email, password: OLD_PASSWORD}).expect(401);
|
|
588
|
+
await supertest(app).post("/auth/login").send({email, password: NEW_PASSWORD}).expect(200);
|
|
589
|
+
await supertest(app).post("/auth/refresh_token").send({refreshToken}).expect(401);
|
|
590
|
+
});
|
|
591
|
+
});
|
|
592
|
+
|
|
593
|
+
describe("BetterAuthApp cookie sessions on cross-site writes", () => {
|
|
594
|
+
const API_ORIGIN = "http://localhost:3000";
|
|
595
|
+
const WEB_ORIGIN = "https://web.example.com";
|
|
596
|
+
const EVIL_ORIGIN = "https://evil.example.com";
|
|
597
|
+
|
|
598
|
+
interface CsrfUserFields {
|
|
599
|
+
betterAuthId?: string;
|
|
600
|
+
email: string;
|
|
601
|
+
name?: string;
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
interface CsrfNoteFields {
|
|
605
|
+
ownerId?: string;
|
|
606
|
+
title?: string;
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
const getCsrfUserModel = (): mongoose.Model<CsrfUserFields> => {
|
|
610
|
+
if (mongoose.models.BetterAuthCsrfUser) {
|
|
611
|
+
return mongoose.models.BetterAuthCsrfUser as mongoose.Model<CsrfUserFields>;
|
|
612
|
+
}
|
|
613
|
+
const schema = new Schema<CsrfUserFields>({
|
|
614
|
+
betterAuthId: {description: "Linked Better Auth user id", index: true, type: String},
|
|
615
|
+
email: {description: "Email address", required: true, type: String},
|
|
616
|
+
name: {description: "Display name", type: String},
|
|
617
|
+
});
|
|
618
|
+
schema.plugin(
|
|
619
|
+
passportLocalMongoose as unknown as (
|
|
620
|
+
target: Schema,
|
|
621
|
+
options?: Record<string, unknown>
|
|
622
|
+
) => void,
|
|
623
|
+
{usernameField: "email"}
|
|
624
|
+
);
|
|
625
|
+
return mongoose.model<CsrfUserFields>("BetterAuthCsrfUser", schema);
|
|
626
|
+
};
|
|
627
|
+
|
|
628
|
+
const getCsrfNoteModel = (): mongoose.Model<CsrfNoteFields> => {
|
|
629
|
+
if (mongoose.models.BetterAuthCsrfNote) {
|
|
630
|
+
return mongoose.models.BetterAuthCsrfNote as mongoose.Model<CsrfNoteFields>;
|
|
631
|
+
}
|
|
632
|
+
const schema = new Schema<CsrfNoteFields>({
|
|
633
|
+
ownerId: {description: "Creator", type: String},
|
|
634
|
+
title: {description: "Note title", type: String},
|
|
635
|
+
});
|
|
636
|
+
return mongoose.model<CsrfNoteFields>("BetterAuthCsrfNote", schema);
|
|
637
|
+
};
|
|
638
|
+
|
|
639
|
+
const CsrfUser = getCsrfUserModel();
|
|
640
|
+
const CsrfNote = getCsrfNoteModel();
|
|
641
|
+
|
|
642
|
+
const buildApp = (): express.Application => {
|
|
643
|
+
const betterAuthApp = new BetterAuthApp({
|
|
644
|
+
config: {
|
|
645
|
+
baseURL: API_ORIGIN,
|
|
646
|
+
crossDomainCookies: true,
|
|
647
|
+
enabled: true,
|
|
648
|
+
secret: "test-secret-at-least-32-characters-long",
|
|
649
|
+
trustedOrigins: [WEB_ORIGIN],
|
|
650
|
+
},
|
|
651
|
+
userModel: CsrfUser as unknown as UserModel,
|
|
652
|
+
});
|
|
653
|
+
const noteRouter = modelRouter("/csrfNotes", CsrfNote, {
|
|
654
|
+
permissions: {
|
|
655
|
+
create: [Permissions.IsAuthenticated],
|
|
656
|
+
delete: [],
|
|
657
|
+
list: [Permissions.IsAuthenticated],
|
|
658
|
+
read: [Permissions.IsAuthenticated],
|
|
659
|
+
update: [],
|
|
660
|
+
},
|
|
661
|
+
preCreate: (body, req) => ({...body, ownerId: String(req.user?.id)}),
|
|
662
|
+
});
|
|
663
|
+
return new TerrenoApp({
|
|
664
|
+
corsOrigin: [WEB_ORIGIN],
|
|
665
|
+
skipListen: true,
|
|
666
|
+
userModel: CsrfUser as unknown as UserModel,
|
|
667
|
+
})
|
|
668
|
+
.register(betterAuthApp)
|
|
669
|
+
.register(noteRouter)
|
|
670
|
+
.build();
|
|
671
|
+
};
|
|
672
|
+
|
|
673
|
+
// Signs up from the trusted web origin and returns the session cookies and the bearer token.
|
|
674
|
+
const signUp = async (app: express.Application): Promise<{bearer: string; cookie: string}> => {
|
|
675
|
+
const res = await supertest(app)
|
|
676
|
+
.post("/api/auth/sign-up/email")
|
|
677
|
+
.set("origin", WEB_ORIGIN)
|
|
678
|
+
.send({email: "csrf-victim@example.com", name: "Victim", password: "password-123456"})
|
|
679
|
+
.expect(200);
|
|
680
|
+
const setCookie = res.headers["set-cookie"] as unknown as string[];
|
|
681
|
+
const cookie = setCookie.map((value) => value.split(";")[0]).join("; ");
|
|
682
|
+
return {bearer: res.body.token as string, cookie};
|
|
683
|
+
};
|
|
684
|
+
|
|
685
|
+
const formPost = (app: express.Application, cookie: string): supertest.Test =>
|
|
686
|
+
supertest(app)
|
|
687
|
+
.post("/csrfNotes")
|
|
688
|
+
.set("cookie", cookie)
|
|
689
|
+
.set("content-type", "application/x-www-form-urlencoded")
|
|
690
|
+
.send("title=forged");
|
|
691
|
+
|
|
692
|
+
beforeEach(async () => {
|
|
693
|
+
await CsrfUser.deleteMany({});
|
|
694
|
+
await CsrfNote.deleteMany({});
|
|
695
|
+
for (const collection of ["user", "session", "account"]) {
|
|
696
|
+
await mongoose.connection.db?.collection(collection).deleteMany({});
|
|
697
|
+
}
|
|
698
|
+
});
|
|
699
|
+
|
|
700
|
+
it("does not authenticate a cookie write from an untrusted origin", async () => {
|
|
701
|
+
const app = buildApp();
|
|
702
|
+
const {cookie} = await signUp(app);
|
|
703
|
+
|
|
704
|
+
const fromOrigin = await formPost(app, cookie)
|
|
705
|
+
.set("origin", EVIL_ORIGIN)
|
|
706
|
+
.set("sec-fetch-site", "cross-site");
|
|
707
|
+
const fromNullOrigin = await formPost(app, cookie).set("origin", "null");
|
|
708
|
+
const fromReferer = await formPost(app, cookie).set("referer", `${EVIL_ORIGIN}/page`);
|
|
709
|
+
const fromFetchMetadata = await formPost(app, cookie).set("sec-fetch-site", "cross-site");
|
|
710
|
+
const withOtherBearer = await formPost(app, cookie)
|
|
711
|
+
.set("origin", EVIL_ORIGIN)
|
|
712
|
+
.set("authorization", "Bearer not-the-session-token");
|
|
713
|
+
|
|
714
|
+
expect(fromOrigin.status).toBe(401);
|
|
715
|
+
expect(fromNullOrigin.status).toBe(401);
|
|
716
|
+
expect(fromReferer.status).toBe(401);
|
|
717
|
+
expect(fromFetchMetadata.status).toBe(401);
|
|
718
|
+
expect(withOtherBearer.status).toBe(401);
|
|
719
|
+
expect(await CsrfNote.countDocuments()).toBe(0);
|
|
720
|
+
});
|
|
721
|
+
|
|
722
|
+
it("authenticates cookie writes from a trusted origin and from non-browser clients", async () => {
|
|
723
|
+
const app = buildApp();
|
|
724
|
+
const {cookie} = await signUp(app);
|
|
725
|
+
|
|
726
|
+
await formPost(app, cookie).set("origin", WEB_ORIGIN).expect(201);
|
|
727
|
+
await formPost(app, cookie).set("origin", API_ORIGIN).expect(201);
|
|
728
|
+
await formPost(app, cookie).set("referer", `${WEB_ORIGIN}/notes`).expect(201);
|
|
729
|
+
await formPost(app, cookie).expect(201);
|
|
730
|
+
expect(await CsrfNote.countDocuments()).toBe(4);
|
|
731
|
+
});
|
|
732
|
+
|
|
733
|
+
it("still authenticates cookie reads and bearer writes from any origin", async () => {
|
|
734
|
+
const app = buildApp();
|
|
735
|
+
const {bearer, cookie} = await signUp(app);
|
|
736
|
+
|
|
737
|
+
await supertest(app)
|
|
738
|
+
.get("/csrfNotes")
|
|
739
|
+
.set("cookie", cookie)
|
|
740
|
+
.set("origin", EVIL_ORIGIN)
|
|
741
|
+
.expect(200);
|
|
742
|
+
await supertest(app)
|
|
743
|
+
.post("/csrfNotes")
|
|
744
|
+
.set("authorization", `Bearer ${bearer}`)
|
|
745
|
+
.set("origin", EVIL_ORIGIN)
|
|
746
|
+
.send({title: "bearer"})
|
|
747
|
+
.expect(201);
|
|
748
|
+
});
|
|
116
749
|
});
|
package/src/betterAuthApp.ts
CHANGED
|
@@ -19,6 +19,34 @@ import {
|
|
|
19
19
|
import {logger} from "./logger";
|
|
20
20
|
import type {TerrenoPlugin} from "./terrenoPlugin";
|
|
21
21
|
|
|
22
|
+
/**
|
|
23
|
+
* The capability a registered plugin offers when it owns the app's Better Auth instance, as
|
|
24
|
+
* BetterAuthApp does. TerrenoApp mounts its session middleware and RealtimeApp validates socket
|
|
25
|
+
* sessions with it, so both find the provider the same way: {@link findBetterAuthProvider}.
|
|
26
|
+
*/
|
|
27
|
+
export interface BetterAuthProvider {
|
|
28
|
+
getAuth: () => BetterAuthInstance | undefined;
|
|
29
|
+
ensureAuth?: () => BetterAuthInstance;
|
|
30
|
+
markSessionMiddlewareMounted?: () => void;
|
|
31
|
+
getBetterAuthBasePath?: () => string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Whether a registered plugin provides the app's Better Auth instance. */
|
|
35
|
+
export const isBetterAuthProvider = (plugin: unknown): plugin is BetterAuthProvider =>
|
|
36
|
+
typeof plugin === "object" &&
|
|
37
|
+
plugin !== null &&
|
|
38
|
+
typeof (plugin as Partial<BetterAuthProvider>).getAuth === "function";
|
|
39
|
+
|
|
40
|
+
/** The first registered plugin that provides the app's Better Auth instance, if any. */
|
|
41
|
+
export const findBetterAuthProvider = (
|
|
42
|
+
registrations: readonly unknown[]
|
|
43
|
+
): BetterAuthProvider | undefined => registrations.find(isBetterAuthProvider);
|
|
44
|
+
|
|
45
|
+
/** The provider's Better Auth instance, creating it when the provider supports that. */
|
|
46
|
+
export const getProvidedBetterAuth = (
|
|
47
|
+
provider: BetterAuthProvider | undefined
|
|
48
|
+
): BetterAuthInstance | undefined => provider?.ensureAuth?.() ?? provider?.getAuth();
|
|
49
|
+
|
|
22
50
|
export interface BetterAuthAppOptions {
|
|
23
51
|
config: BetterAuthConfig;
|
|
24
52
|
userModel?: UserModel;
|