@slotform/auth 0.0.0-stage → 0.1.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.
Files changed (175) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +26 -2
  3. package/dist/ability/index.d.ts +31 -0
  4. package/dist/ability/index.d.ts.map +1 -0
  5. package/dist/ability/index.js +64 -0
  6. package/dist/ability/index.js.map +1 -0
  7. package/dist/access.d.ts +19 -0
  8. package/dist/access.d.ts.map +1 -0
  9. package/dist/access.js +33 -0
  10. package/dist/access.js.map +1 -0
  11. package/dist/callback-stubs.d.ts +15 -0
  12. package/dist/callback-stubs.d.ts.map +1 -0
  13. package/dist/callback-stubs.js +28 -0
  14. package/dist/callback-stubs.js.map +1 -0
  15. package/dist/client.d.ts +38 -0
  16. package/dist/client.d.ts.map +1 -0
  17. package/dist/client.js +37 -0
  18. package/dist/client.js.map +1 -0
  19. package/dist/index.d.ts +190 -0
  20. package/dist/index.d.ts.map +1 -0
  21. package/dist/index.js +451 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/infer.d.ts +31 -0
  24. package/dist/infer.d.ts.map +1 -0
  25. package/dist/infer.js +2 -0
  26. package/dist/infer.js.map +1 -0
  27. package/dist/schema/devices.d.ts +404 -0
  28. package/dist/schema/devices.d.ts.map +1 -0
  29. package/dist/schema/devices.js +45 -0
  30. package/dist/schema/devices.js.map +1 -0
  31. package/dist/schema/index.d.ts +679 -0
  32. package/dist/schema/index.d.ts.map +1 -0
  33. package/dist/schema/index.js +94 -0
  34. package/dist/schema/index.js.map +1 -0
  35. package/dist/schema/oauth.d.ts +2062 -0
  36. package/dist/schema/oauth.d.ts.map +1 -0
  37. package/dist/schema/oauth.js +245 -0
  38. package/dist/schema/oauth.js.map +1 -0
  39. package/dist/schema/organization.d.ts +388 -0
  40. package/dist/schema/organization.d.ts.map +1 -0
  41. package/dist/schema/organization.js +75 -0
  42. package/dist/schema/organization.js.map +1 -0
  43. package/dist/schema/passkey.d.ts +215 -0
  44. package/dist/schema/passkey.d.ts.map +1 -0
  45. package/dist/schema/passkey.js +29 -0
  46. package/dist/schema/passkey.js.map +1 -0
  47. package/dist/schema/sets.d.ts +3715 -0
  48. package/dist/schema/sets.d.ts.map +1 -0
  49. package/dist/schema/sets.js +48 -0
  50. package/dist/schema/sets.js.map +1 -0
  51. package/dist/scope.d.ts +36 -0
  52. package/dist/scope.d.ts.map +1 -0
  53. package/dist/scope.js +59 -0
  54. package/dist/scope.js.map +1 -0
  55. package/dist/screens-fixtures.d.ts +148 -0
  56. package/dist/screens-fixtures.d.ts.map +1 -0
  57. package/dist/screens-fixtures.js +122 -0
  58. package/dist/screens-fixtures.js.map +1 -0
  59. package/dist/screens-session.d.ts +4 -0
  60. package/dist/screens-session.d.ts.map +1 -0
  61. package/dist/screens-session.js +24 -0
  62. package/dist/screens-session.js.map +1 -0
  63. package/dist/screens.d.ts +3 -0
  64. package/dist/screens.d.ts.map +1 -0
  65. package/dist/screens.js +8 -0
  66. package/dist/screens.js.map +1 -0
  67. package/dist/serve.d.ts +3 -0
  68. package/dist/serve.d.ts.map +1 -0
  69. package/dist/serve.js +44 -0
  70. package/dist/serve.js.map +1 -0
  71. package/dist/types.d.ts +152 -0
  72. package/dist/types.d.ts.map +1 -0
  73. package/dist/types.js +215 -0
  74. package/dist/types.js.map +1 -0
  75. package/dist/worker/callback-url.d.ts +6 -0
  76. package/dist/worker/callback-url.d.ts.map +1 -0
  77. package/dist/worker/callback-url.js +57 -0
  78. package/dist/worker/callback-url.js.map +1 -0
  79. package/dist/worker/cimd-transport.d.ts +2 -0
  80. package/dist/worker/cimd-transport.d.ts.map +1 -0
  81. package/dist/worker/cimd-transport.js +86 -0
  82. package/dist/worker/cimd-transport.js.map +1 -0
  83. package/dist/worker/devices.d.ts +6 -0
  84. package/dist/worker/devices.d.ts.map +1 -0
  85. package/dist/worker/devices.js +70 -0
  86. package/dist/worker/devices.js.map +1 -0
  87. package/dist/worker/email-key.d.ts +2 -0
  88. package/dist/worker/email-key.d.ts.map +1 -0
  89. package/dist/worker/email-key.js +20 -0
  90. package/dist/worker/email-key.js.map +1 -0
  91. package/dist/worker/index.d.ts +156 -0
  92. package/dist/worker/index.d.ts.map +1 -0
  93. package/dist/worker/index.js +507 -0
  94. package/dist/worker/index.js.map +1 -0
  95. package/dist/worker/listener.d.ts +12 -0
  96. package/dist/worker/listener.d.ts.map +1 -0
  97. package/dist/worker/listener.js +37 -0
  98. package/dist/worker/listener.js.map +1 -0
  99. package/dist/worker/oauth.d.ts +95 -0
  100. package/dist/worker/oauth.d.ts.map +1 -0
  101. package/dist/worker/oauth.js +456 -0
  102. package/dist/worker/oauth.js.map +1 -0
  103. package/dist/worker/outputs.d.ts +75 -0
  104. package/dist/worker/outputs.d.ts.map +1 -0
  105. package/dist/worker/outputs.js +7 -0
  106. package/dist/worker/outputs.js.map +1 -0
  107. package/dist/worker/procedures.d.ts +360 -0
  108. package/dist/worker/procedures.d.ts.map +1 -0
  109. package/dist/worker/procedures.js +464 -0
  110. package/dist/worker/procedures.js.map +1 -0
  111. package/dist/worker/rate-limit.d.ts +7 -0
  112. package/dist/worker/rate-limit.d.ts.map +1 -0
  113. package/dist/worker/rate-limit.js +49 -0
  114. package/dist/worker/rate-limit.js.map +1 -0
  115. package/dist/worker/reserved-slugs.d.ts +4 -0
  116. package/dist/worker/reserved-slugs.d.ts.map +1 -0
  117. package/dist/worker/reserved-slugs.js +30 -0
  118. package/dist/worker/reserved-slugs.js.map +1 -0
  119. package/dist/worker/session-ended.d.ts +6 -0
  120. package/dist/worker/session-ended.d.ts.map +1 -0
  121. package/dist/worker/session-ended.js +10 -0
  122. package/dist/worker/session-ended.js.map +1 -0
  123. package/dist/worker/sign-up-policy.d.ts +20 -0
  124. package/dist/worker/sign-up-policy.d.ts.map +1 -0
  125. package/dist/worker/sign-up-policy.js +65 -0
  126. package/dist/worker/sign-up-policy.js.map +1 -0
  127. package/dist/worker/tenancy.d.ts +23 -0
  128. package/dist/worker/tenancy.d.ts.map +1 -0
  129. package/dist/worker/tenancy.js +133 -0
  130. package/dist/worker/tenancy.js.map +1 -0
  131. package/guide/abilities.md +55 -0
  132. package/guide/add-a-role.md +33 -0
  133. package/guide/callbacks.md +97 -0
  134. package/guide/config.md +84 -0
  135. package/guide/devices.md +85 -0
  136. package/guide/mcp-oauth.md +97 -0
  137. package/guide/organizations.md +114 -0
  138. package/guide/protect-by-scope.md +29 -0
  139. package/guide/scopes.md +87 -0
  140. package/guide/sign-in.md +127 -0
  141. package/package.json +155 -3
  142. package/src/ability/index.ts +174 -0
  143. package/src/access.ts +45 -0
  144. package/src/callback-stubs.ts +45 -0
  145. package/src/client.ts +119 -0
  146. package/src/expo.tsx +275 -0
  147. package/src/index.ts +574 -0
  148. package/src/infer.ts +44 -0
  149. package/src/schema/devices.ts +54 -0
  150. package/src/schema/index.ts +128 -0
  151. package/src/schema/oauth.ts +320 -0
  152. package/src/schema/organization.ts +104 -0
  153. package/src/schema/passkey.ts +38 -0
  154. package/src/schema/sets.ts +73 -0
  155. package/src/scope.ts +135 -0
  156. package/src/screens-fixtures.ts +149 -0
  157. package/src/screens-session.ts +26 -0
  158. package/src/screens.ts +10 -0
  159. package/src/serve.ts +49 -0
  160. package/src/types.ts +313 -0
  161. package/src/worker/callback-url.ts +65 -0
  162. package/src/worker/cimd-transport.ts +115 -0
  163. package/src/worker/devices.ts +83 -0
  164. package/src/worker/email-key.ts +21 -0
  165. package/src/worker/index.ts +941 -0
  166. package/src/worker/listener.ts +55 -0
  167. package/src/worker/oauth.ts +709 -0
  168. package/src/worker/outputs.ts +102 -0
  169. package/src/worker/procedures.ts +758 -0
  170. package/src/worker/rate-limit.ts +64 -0
  171. package/src/worker/reserved-slugs.ts +39 -0
  172. package/src/worker/session-ended.ts +14 -0
  173. package/src/worker/sign-up-policy.ts +88 -0
  174. package/src/worker/tenancy.ts +229 -0
  175. package/templates/callbacks.ts +40 -0
@@ -0,0 +1,709 @@
1
+ import { cimd } from "@better-auth/cimd";
2
+ import { defineRequestState } from "@better-auth/core/context";
3
+ import {
4
+ createDpopReplayStore,
5
+ createInsufficientScopeError,
6
+ enforceDpopBinding,
7
+ isDpopBindingError,
8
+ parseAccessTokenAuthorization,
9
+ verifyJwsAccessToken,
10
+ } from "@better-auth/core/oauth2";
11
+ import { mcp } from "@better-auth/mcp";
12
+ import {
13
+ createResourceServerChallenge,
14
+ getOAuthProviderState,
15
+ } from "@better-auth/oauth-provider";
16
+ import type { RateLimitBinding } from "@slotform/api/procedure";
17
+ import {
18
+ and,
19
+ desc,
20
+ eq,
21
+ type InferSelectModel,
22
+ isNotNull,
23
+ sql,
24
+ } from "@slotform/db/orm";
25
+ import type { BetterAuthPlugin } from "better-auth";
26
+ import {
27
+ APIError,
28
+ createAuthMiddleware,
29
+ getSessionFromCtx,
30
+ isAPIError,
31
+ } from "better-auth/api";
32
+ import { jwt } from "better-auth/plugins/jwt";
33
+ import { user as userTable } from "../schema/index.ts";
34
+ import { oauthClient, oauthConsent, scopesOf } from "../schema/oauth.ts";
35
+ import { member as memberTable } from "../schema/organization.ts";
36
+ import {
37
+ type MemberRow,
38
+ type Membership,
39
+ organization as organizationScope,
40
+ } from "../scope.ts";
41
+ import { AUTH_PREFIX, CLIENT_IP_HEADER } from "../types.ts";
42
+ import { fetchClientMetadataResource } from "./cimd-transport.ts";
43
+ import type { OAuthGrant } from "./outputs.ts";
44
+ import {
45
+ createTenancy,
46
+ type DbClient,
47
+ listOrganizations,
48
+ type Tenancy,
49
+ } from "./tenancy.ts";
50
+
51
+ // The protected resource and the login pages are pinned: docs/architecture/plugins/auth.md, "MCP OAuth".
52
+ const MCP_RESOURCE_PATH = "/mcp";
53
+ const MCP_LOGIN_PAGE = "/sign-in";
54
+ const MCP_ORGANIZATION_PAGE = "/connect/organization";
55
+ const MCP_CONSENT_PAGE = "/connect/consent";
56
+
57
+ // The scopes an agent's grant holds: `mcp` is the whole tool list,
58
+ // `offline_access` the refresh token.
59
+ const MCP_SCOPE = "mcp";
60
+ const MCP_SCOPES = [MCP_SCOPE, "offline_access"] as const;
61
+
62
+ export function tooManyRequests(): Response {
63
+ return new Response(JSON.stringify({ code: "TOO_MANY_REQUESTS" }), {
64
+ status: 429,
65
+ headers: { "content-type": "application/json" },
66
+ });
67
+ }
68
+
69
+ // The organization an agent's authorization may act in is one the tenancy
70
+ // resolves for the member, and a refusal names this code.
71
+ const ORGANIZATION_NOT_RESOLVED = "ORGANIZATION_NOT_RESOLVED";
72
+
73
+ function organizationNotResolved(): APIError {
74
+ return new APIError("FORBIDDEN", {
75
+ code: ORGANIZATION_NOT_RESOLVED,
76
+ message:
77
+ "Choose an organization you are a member of; the one named is not available.",
78
+ });
79
+ }
80
+
81
+ // The grant lifetimes in seconds, the refresh token's reuse window after its
82
+ // rotation last. Pinned, not options, so a dependency bump never moves them.
83
+ const CODE_EXPIRES_IN = 600;
84
+ const ACCESS_TOKEN_EXPIRES_IN = 3600;
85
+ const REFRESH_TOKEN_EXPIRES_IN = 2592000;
86
+ const REFRESH_TOKEN_REUSE_INTERVAL = 30;
87
+
88
+ // The resource an access token is bound to and the issuer that signs it, from
89
+ // the app URL. One derivation for the provider and the verifier.
90
+ function mcpResource(appUrl: string): string {
91
+ return `${appUrl.replace(/\/+$/, "")}${MCP_RESOURCE_PATH}`;
92
+ }
93
+
94
+ function mcpIssuer(appUrl: string): string {
95
+ return `${appUrl.replace(/\/+$/, "")}${AUTH_PREFIX}`;
96
+ }
97
+
98
+ // ── Grants ──────────────────────────────────────────────────────────
99
+
100
+ // The adapter surface the grant deletions use: Better Auth's own, by model
101
+ // and field name.
102
+ export interface GrantAdapter {
103
+ deleteMany(args: {
104
+ model: string;
105
+ where: { field: string; value: unknown; operator?: string }[];
106
+ }): Promise<number>;
107
+ findOne<T>(args: {
108
+ model: string;
109
+ where: { field: string; value: unknown }[];
110
+ }): Promise<T | null>;
111
+ }
112
+
113
+ interface GrantFilter {
114
+ clientId?: string;
115
+ userId?: string;
116
+ referenceId: string;
117
+ }
118
+
119
+ function grantWhere(filter: GrantFilter) {
120
+ return [
121
+ { field: "referenceId", value: filter.referenceId },
122
+ ...(filter.clientId === undefined
123
+ ? []
124
+ : [{ field: "clientId", value: filter.clientId }]),
125
+ ...(filter.userId === undefined
126
+ ? []
127
+ : [{ field: "userId", value: filter.userId }]),
128
+ ];
129
+ }
130
+
131
+ // The access-token rows first, since `refreshId` has no cascade, then the
132
+ // refresh tokens. One `deleteMany` each (a batch is not portable: the sqlite
133
+ // client has none).
134
+ async function deleteTokens(
135
+ adapter: GrantAdapter,
136
+ where: { field: string; value: unknown; operator?: string }[],
137
+ ): Promise<void> {
138
+ await adapter.deleteMany({ model: "oauthAccessToken", where });
139
+ await adapter.deleteMany({ model: "oauthRefreshToken", where });
140
+ }
141
+
142
+ // Deletes one grant's rows, or every grant a filter names: its tokens, then
143
+ // the consent.
144
+ async function deleteGrants(
145
+ adapter: GrantAdapter,
146
+ filter: GrantFilter,
147
+ ): Promise<number> {
148
+ const where = grantWhere(filter);
149
+ await deleteTokens(adapter, where);
150
+ return adapter.deleteMany({ model: "oauthConsent", where });
151
+ }
152
+
153
+ // ── The verified call ───────────────────────────────────────────────
154
+
155
+ type UserRow = InferSelectModel<typeof userTable>;
156
+
157
+ export interface VerifiedAgent {
158
+ // The member's user row, marked as an agent's.
159
+ user: UserRow & { agent: true };
160
+ // The grant as a session: `id` is the consent id, never a token.
161
+ session: {
162
+ id: string;
163
+ userId: string;
164
+ activeOrganizationId: string;
165
+ createdAt: Date;
166
+ updatedAt: Date;
167
+ expiresAt: Date;
168
+ ipAddress: string | null;
169
+ userAgent: string | null;
170
+ };
171
+ member: MemberRow;
172
+ grant: {
173
+ id: string;
174
+ clientId: string;
175
+ organizationId: string;
176
+ scopes: string[];
177
+ };
178
+ // Resolves the grant's organization for the member and no other.
179
+ tenancy: Tenancy;
180
+ }
181
+
182
+ export interface OAuth {
183
+ // Turns a request's bearer access token into its member in the grant's
184
+ // organization, or answers the `401`, `403` or `429` response a client
185
+ // reads: the `WWW-Authenticate` challenge that starts or restarts the
186
+ // authorization flow.
187
+ verify(request: Request): Promise<VerifiedAgent | Response>;
188
+ // Ends a grant by its consent id: its access tokens, refresh tokens and
189
+ // consent. Answers whether one existed; with `userId`, whether one of that
190
+ // member's existed.
191
+ revokeGrant(id: string, userId?: string): Promise<boolean>;
192
+ // The grants of one member in every organization, newest first. Reads the
193
+ // client's public fields only.
194
+ listGrants(userId: string): Promise<OAuthGrant[]>;
195
+ }
196
+
197
+ // The auth context members the capability reads; `OAuthDeps.auth.$context`
198
+ // is `Promise<unknown>`, so the read casts to this.
199
+ interface AuthContextLike {
200
+ adapter: GrantAdapter;
201
+ internalAdapter: Parameters<typeof createDpopReplayStore>[0];
202
+ }
203
+
204
+ interface OAuthDeps {
205
+ auth: {
206
+ api: { getJwks(): Promise<unknown> };
207
+ $context: Promise<unknown>;
208
+ };
209
+ db: unknown;
210
+ roles: Record<string, unknown>;
211
+ membership: Membership | null;
212
+ appUrl: string;
213
+ // The per-grant limiter; absent under dev mode.
214
+ limiter?: RateLimitBinding;
215
+ }
216
+
217
+ // A signing key set is cached per auth instance, so a token verifies without
218
+ // a read of the keys on every call.
219
+ const jwksCacheKeys = new WeakMap<object, object>();
220
+
221
+ const JOSE_CODE = /^ERR_J/;
222
+
223
+ // A token the verifier cannot read or trust: a jose error, or the TypeError a
224
+ // value that is no JWT raises.
225
+ function isTokenError(error: unknown): boolean {
226
+ if (error instanceof TypeError) return true;
227
+ return (
228
+ error instanceof Error &&
229
+ "code" in error &&
230
+ typeof error.code === "string" &&
231
+ JOSE_CODE.test(error.code)
232
+ );
233
+ }
234
+
235
+ function unauthorized(message: string): APIError {
236
+ return new APIError("UNAUTHORIZED", { message });
237
+ }
238
+
239
+ export function createOAuth(deps: OAuthDeps): OAuth {
240
+ const resource = mcpResource(deps.appUrl);
241
+ const issuer = mcpIssuer(deps.appUrl);
242
+ const client = deps.db as DbClient;
243
+ let cacheKey = jwksCacheKeys.get(deps.auth);
244
+ if (!cacheKey) {
245
+ cacheKey = {};
246
+ jwksCacheKeys.set(deps.auth, cacheKey);
247
+ }
248
+
249
+ async function context(): Promise<AuthContextLike> {
250
+ return (await deps.auth.$context) as AuthContextLike;
251
+ }
252
+
253
+ function challenge(error: unknown): Response {
254
+ let failure = error;
255
+ if (isDpopBindingError(error)) {
256
+ failure = new APIError("UNAUTHORIZED", {
257
+ message: error.message,
258
+ error: error.code,
259
+ error_description: error.message,
260
+ });
261
+ } else if (!isAPIError(error) && isTokenError(error)) {
262
+ failure = unauthorized("invalid access token");
263
+ }
264
+ const answer = createResourceServerChallenge(failure, resource, {
265
+ challengeScopes: [...MCP_SCOPES],
266
+ });
267
+ if (!answer) throw error;
268
+ const headers = new Headers(answer.headers);
269
+ headers.set("content-type", "application/json");
270
+ return new Response(
271
+ JSON.stringify({
272
+ error:
273
+ answer.statusCode === 403 ? "insufficient_scope" : "unauthorized",
274
+ }),
275
+ { status: answer.statusCode, headers },
276
+ );
277
+ }
278
+
279
+ async function verify(request: Request): Promise<VerifiedAgent | Response> {
280
+ try {
281
+ const authorization = parseAccessTokenAuthorization(
282
+ request.headers.get("authorization"),
283
+ );
284
+ if (!authorization?.token) throw unauthorized("missing bearer token");
285
+ if (authorization.scheme === "Unknown") {
286
+ throw unauthorized("authorization scheme must be Bearer or DPoP");
287
+ }
288
+ const payload = await verifyJwsAccessToken(authorization.token, {
289
+ // `getJwks` answers a JWKS the verifier's typings spell with `never[]` keys.
290
+ jwksFetch: () =>
291
+ deps.auth.api.getJwks() as Promise<{ keys: never[] } | undefined>,
292
+ jwksCacheKey: cacheKey,
293
+ verifyOptions: { issuer, audience: resource, typ: "at+jwt" },
294
+ });
295
+ const granted =
296
+ typeof payload.scope === "string" ? payload.scope.split(" ") : [];
297
+ if (!granted.includes(MCP_SCOPE)) {
298
+ throw createInsufficientScopeError([MCP_SCOPE]);
299
+ }
300
+ const { internalAdapter } = await context();
301
+ await enforceDpopBinding({
302
+ payload,
303
+ authorization,
304
+ proofJwt: request.headers.get("dpop"),
305
+ method: request.method,
306
+ url: request.url,
307
+ replayStore: createDpopReplayStore(internalAdapter),
308
+ });
309
+
310
+ const userId = payload.sub;
311
+ const clientId = payload.azp;
312
+ const organizationId = payload.organization_id;
313
+ if (
314
+ typeof userId !== "string" ||
315
+ typeof clientId !== "string" ||
316
+ typeof organizationId !== "string" ||
317
+ typeof payload.iat !== "number" ||
318
+ typeof payload.exp !== "number"
319
+ ) {
320
+ throw unauthorized("access token claims are incomplete");
321
+ }
322
+
323
+ // The consent of the token's client, member and organization must
324
+ // stand, and the member's membership of it count.
325
+ const row = (await client
326
+ .select({
327
+ consent: oauthConsent,
328
+ user: userTable,
329
+ member: memberTable,
330
+ })
331
+ .from(oauthConsent)
332
+ .innerJoin(userTable, eq(oauthConsent.userId, userTable.id))
333
+ .innerJoin(
334
+ memberTable,
335
+ and(
336
+ eq(memberTable.userId, userTable.id),
337
+ eq(memberTable.organizationId, oauthConsent.referenceId),
338
+ ),
339
+ )
340
+ .where(
341
+ and(
342
+ eq(oauthConsent.userId, userId),
343
+ eq(oauthConsent.clientId, clientId),
344
+ eq(oauthConsent.referenceId, organizationId),
345
+ deps.membership ? sql`(${deps.membership.where})` : undefined,
346
+ ),
347
+ )
348
+ .get()) as
349
+ | {
350
+ consent: InferSelectModel<typeof oauthConsent>;
351
+ user: UserRow;
352
+ member: MemberRow;
353
+ }
354
+ | undefined;
355
+ if (!row?.consent.createdAt) throw unauthorized("grant not found");
356
+ // A token issued before the consent that now stands belongs to a
357
+ // grant that was revoked, whatever grant has since replaced it.
358
+ if (payload.iat < Math.floor(row.consent.createdAt.getTime() / 1000)) {
359
+ throw unauthorized("grant not found");
360
+ }
361
+ if (deps.limiter) {
362
+ const { success } = await deps.limiter.limit({ key: row.consent.id });
363
+ if (!success) return tooManyRequests();
364
+ }
365
+ const issuedAt = new Date(payload.iat * 1000);
366
+ return {
367
+ user: { ...row.user, agent: true },
368
+ session: {
369
+ id: row.consent.id,
370
+ userId: row.user.id,
371
+ activeOrganizationId: organizationId,
372
+ createdAt: issuedAt,
373
+ updatedAt: issuedAt,
374
+ expiresAt: new Date(payload.exp * 1000),
375
+ ipAddress: request.headers.get(CLIENT_IP_HEADER),
376
+ userAgent: request.headers.get("user-agent"),
377
+ },
378
+ member: row.member,
379
+ grant: {
380
+ id: row.consent.id,
381
+ clientId,
382
+ organizationId,
383
+ scopes: granted,
384
+ },
385
+ tenancy: createTenancy(
386
+ deps.db,
387
+ deps.roles,
388
+ deps.membership,
389
+ organizationId,
390
+ ),
391
+ };
392
+ } catch (error) {
393
+ return challenge(error);
394
+ }
395
+ }
396
+
397
+ async function listGrants(userId: string): Promise<OAuthGrant[]> {
398
+ const rows = (deps.db as DbClient)
399
+ .select({
400
+ id: oauthConsent.id,
401
+ clientId: oauthClient.clientId,
402
+ name: oauthClient.name,
403
+ uri: oauthClient.uri,
404
+ organizationId: oauthConsent.referenceId,
405
+ scopes: oauthConsent.scopes,
406
+ createdAt: oauthConsent.createdAt,
407
+ })
408
+ .from(oauthConsent)
409
+ .innerJoin(oauthClient, eq(oauthClient.clientId, oauthConsent.clientId))
410
+ .where(
411
+ and(
412
+ eq(oauthConsent.userId, userId),
413
+ isNotNull(oauthConsent.referenceId),
414
+ isNotNull(oauthConsent.createdAt),
415
+ ),
416
+ )
417
+ .orderBy(desc(oauthConsent.createdAt))
418
+ .all() as {
419
+ id: string;
420
+ clientId: string;
421
+ name: string | null;
422
+ uri: string | null;
423
+ organizationId: string;
424
+ scopes: string;
425
+ createdAt: Date;
426
+ }[];
427
+ return rows.map((row) => ({
428
+ id: row.id,
429
+ name: row.name ?? row.clientId,
430
+ uri: row.uri,
431
+ organizationId: row.organizationId,
432
+ scopes: scopesOf(row.scopes),
433
+ createdAt: row.createdAt,
434
+ }));
435
+ }
436
+
437
+ async function revokeGrant(id: string, userId?: string): Promise<boolean> {
438
+ const { adapter } = await context();
439
+ const consent = await adapter.findOne<{
440
+ clientId: string;
441
+ userId: string;
442
+ referenceId: string;
443
+ }>({ model: "oauthConsent", where: [{ field: "id", value: id }] });
444
+ if (!consent?.referenceId) return false;
445
+ if (userId !== undefined && consent.userId !== userId) return false;
446
+ await deleteGrants(adapter, consent);
447
+ return true;
448
+ }
449
+
450
+ return { verify, revokeGrant, listGrants };
451
+ }
452
+
453
+ // ── The provider ────────────────────────────────────────────────────
454
+
455
+ interface McpPluginsDeps {
456
+ appUrl: string;
457
+ db: unknown;
458
+ roles: Record<string, unknown>;
459
+ membership: Membership | null;
460
+ // The auth context, once the instance exists: the organization hooks run
461
+ // without one.
462
+ context: () => Promise<{ adapter: GrantAdapter }>;
463
+ }
464
+
465
+ // Set by the `set-active` call that carries the authorization's signed query:
466
+ // the member chose in this request, so the authorization it resumes goes on
467
+ // to consent instead of asking again.
468
+ const chosenInRequest = defineRequestState(() => false);
469
+
470
+ function promptWithConsent(existing: unknown): string {
471
+ const kept =
472
+ typeof existing === "string"
473
+ ? existing
474
+ .split(" ")
475
+ .filter((token) => token && token !== "none" && token !== "consent")
476
+ : [];
477
+ return [...kept, "consent"].join(" ");
478
+ }
479
+
480
+ // The plugins `auth({ mcp: true })` adds, in order (`jwt`, `mcp`, `cimd`, then
481
+ // the guards the framework puts around them), and the organization hooks that
482
+ // delete a member's grants with their membership.
483
+ export function mcpPlugins(deps: McpPluginsDeps): {
484
+ plugins: BetterAuthPlugin[];
485
+ organizationHooks: {
486
+ afterRemoveMember: (data: {
487
+ member: { organizationId: string; userId: string };
488
+ }) => Promise<void>;
489
+ afterDeleteOrganization: (data: {
490
+ organization: { id: string };
491
+ }) => Promise<void>;
492
+ };
493
+ } {
494
+ const tenancy = createTenancy(deps.db, deps.roles, deps.membership);
495
+ const resource = mcpResource(deps.appUrl);
496
+
497
+ // The organization a grant is for. A session's active organization is the
498
+ // member's choice and must still resolve for them, else the grant is
499
+ // refused, even when one other organization remains. Only with no active
500
+ // organization does a member of exactly one organization get that one.
501
+ async function consentReference(
502
+ userId: string,
503
+ activeOrganizationId: unknown,
504
+ ): Promise<string> {
505
+ if (typeof activeOrganizationId === "string" && activeOrganizationId) {
506
+ if (
507
+ await tenancy.resolve(organizationScope, activeOrganizationId, userId)
508
+ ) {
509
+ return activeOrganizationId;
510
+ }
511
+ throw organizationNotResolved();
512
+ }
513
+ const organizations = await listOrganizations(
514
+ deps.db,
515
+ deps.membership,
516
+ userId,
517
+ );
518
+ const only = organizations.length === 1 ? organizations[0] : undefined;
519
+ if (only) return only;
520
+ throw organizationNotResolved();
521
+ }
522
+
523
+ const provider = mcp({
524
+ loginPage: MCP_LOGIN_PAGE,
525
+ consentPage: MCP_CONSENT_PAGE,
526
+ resource,
527
+ scopes: [...MCP_SCOPES],
528
+ advertisedMetadata: { scopes_supported: [...MCP_SCOPES] },
529
+ grantTypes: ["authorization_code", "refresh_token"],
530
+ codeExpiresIn: CODE_EXPIRES_IN,
531
+ accessTokenExpiresIn: ACCESS_TOKEN_EXPIRES_IN,
532
+ refreshTokenExpiresIn: REFRESH_TOKEN_EXPIRES_IN,
533
+ refreshTokenReuseInterval: REFRESH_TOKEN_REUSE_INTERVAL,
534
+ allowDynamicClientRegistration: false,
535
+ allowUnauthenticatedClientRegistration: false,
536
+ // Clients come from metadata documents, never from a session.
537
+ clientPrivileges: () => false,
538
+ resourcePrivileges: () => false,
539
+ customAccessTokenClaims: ({ referenceId }) => ({
540
+ organization_id: referenceId,
541
+ }),
542
+ postLogin: {
543
+ page: MCP_ORGANIZATION_PAGE,
544
+ // A member of exactly one organization has nothing to choose; with
545
+ // none, the choice page shows its empty state and denies; with
546
+ // several, the member chooses once per authorization.
547
+ shouldRedirect: async ({ user }) => {
548
+ if (await chosenInRequest.get()) return false;
549
+ const organizations = await listOrganizations(
550
+ deps.db,
551
+ deps.membership,
552
+ user.id,
553
+ );
554
+ return organizations.length !== 1;
555
+ },
556
+ consentReferenceId: ({ user, session }) =>
557
+ consentReference(user.id, session.activeOrganizationId),
558
+ },
559
+ });
560
+
561
+ // CIMD clients share one `client_id` across every member and organization,
562
+ // so a standing consent must not skip the page: every external
563
+ // authorization asks. The provider's own resumes carry
564
+ // `authorizeSettings` and pass untouched, else consent loops.
565
+ const guards: BetterAuthPlugin = {
566
+ id: "mcp-guards",
567
+ hooks: {
568
+ before: [
569
+ {
570
+ matcher: (ctx) => ctx.path === "/oauth2/authorize",
571
+ handler: createAuthMiddleware(async (ctx) => {
572
+ // The provider sets `authorizeSettings` on its own resumes; the hook
573
+ // context's type does not carry it.
574
+ if ((ctx as { authorizeSettings?: unknown }).authorizeSettings) {
575
+ return;
576
+ }
577
+ const post = (ctx.request?.method ?? ctx.method) === "POST";
578
+ // The hook context types the body and query as `any`.
579
+ const source = (post ? ctx.body : ctx.query) as
580
+ | Record<string, unknown>
581
+ | undefined;
582
+ const prompt = promptWithConsent(source?.prompt);
583
+ return {
584
+ context: post
585
+ ? { body: { ...source, prompt } }
586
+ : { query: { ...source, prompt } },
587
+ };
588
+ }),
589
+ },
590
+ {
591
+ matcher: (ctx) =>
592
+ ctx.path === "/organization/set-active" &&
593
+ typeof ctx.body?.oauth_query === "string",
594
+ handler: createAuthMiddleware(async (ctx) => {
595
+ const session = await getSessionFromCtx(ctx);
596
+ // No session: the endpoint refuses it as it always does.
597
+ if (!session) return;
598
+ // The matcher held `oauth_query`; the endpoint's own input is not on the
599
+ // hook context's type.
600
+ const body = ctx.body as {
601
+ organizationId?: string | null;
602
+ organizationSlug?: string;
603
+ };
604
+ const found =
605
+ typeof body.organizationId === "string"
606
+ ? await tenancy.resolve(
607
+ organizationScope,
608
+ body.organizationId,
609
+ session.user.id,
610
+ )
611
+ : body.organizationId === undefined &&
612
+ typeof body.organizationSlug === "string"
613
+ ? await tenancy.bySlug(
614
+ organizationScope,
615
+ body.organizationSlug,
616
+ undefined,
617
+ session.user.id,
618
+ )
619
+ : null;
620
+ if (!found) throw organizationNotResolved();
621
+ await chosenInRequest.set(true);
622
+ }),
623
+ },
624
+ ],
625
+ after: [
626
+ {
627
+ // A new consent replaces a revoked one under the same client,
628
+ // member and organization, so the tokens issued before it
629
+ // belong to the grant it replaced. `createdAt` is the grant's
630
+ // start; the provider moves `updatedAt` on a standing consent.
631
+ matcher: (ctx) =>
632
+ ctx.path === "/oauth2/consent" && ctx.body?.accept === true,
633
+ handler: createAuthMiddleware(async (ctx) => {
634
+ if (isAPIError(ctx.context.returned)) return;
635
+ const session = await getSessionFromCtx(ctx);
636
+ const query = (await getOAuthProviderState())?.query;
637
+ const clientId = new URLSearchParams(query).get("client_id");
638
+ if (!session || !clientId) return;
639
+ const referenceId = await consentReference(
640
+ session.user.id,
641
+ session.session.activeOrganizationId,
642
+ );
643
+ // `GrantAdapter` is the slice of Better Auth's adapter the deletions use.
644
+ const adapter = ctx.context.adapter as unknown as GrantAdapter;
645
+ const consent = await adapter.findOne<{ createdAt: Date }>({
646
+ model: "oauthConsent",
647
+ where: [
648
+ { field: "clientId", value: clientId },
649
+ { field: "userId", value: session.user.id },
650
+ { field: "referenceId", value: referenceId },
651
+ ],
652
+ });
653
+ if (!consent) return;
654
+ await deleteTokens(adapter, [
655
+ ...grantWhere({ clientId, userId: session.user.id, referenceId }),
656
+ {
657
+ field: "createdAt",
658
+ value: new Date(consent.createdAt),
659
+ operator: "lt",
660
+ },
661
+ ]);
662
+ }),
663
+ },
664
+ {
665
+ // Leaving runs no organization hook.
666
+ matcher: (ctx) => ctx.path === "/organization/leave",
667
+ handler: createAuthMiddleware(async (ctx) => {
668
+ // `returned` is the endpoint's answer, `unknown` to a hook.
669
+ const left = ctx.context.returned as
670
+ | { organizationId?: string; userId?: string }
671
+ | undefined;
672
+ if (isAPIError(left) || !left?.organizationId || !left.userId) {
673
+ return;
674
+ }
675
+ await deleteGrants(ctx.context.adapter as unknown as GrantAdapter, {
676
+ userId: left.userId,
677
+ referenceId: left.organizationId,
678
+ });
679
+ }),
680
+ },
681
+ ],
682
+ },
683
+ };
684
+
685
+ return {
686
+ plugins: [
687
+ jwt({ disableSettingJwtHeader: true }),
688
+ provider,
689
+ cimd({
690
+ fetchClientMetadataResource,
691
+ metadataProfile: "mcp-2026-07-28",
692
+ }),
693
+ guards,
694
+ ],
695
+ organizationHooks: {
696
+ afterRemoveMember: async ({ member }) => {
697
+ await deleteGrants((await deps.context()).adapter, {
698
+ userId: member.userId,
699
+ referenceId: member.organizationId,
700
+ });
701
+ },
702
+ afterDeleteOrganization: async ({ organization }) => {
703
+ await deleteGrants((await deps.context()).adapter, {
704
+ referenceId: organization.id,
705
+ });
706
+ },
707
+ },
708
+ };
709
+ }