@zgeoff/mcp-auth 0.0.0 → 0.2.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 (34) hide show
  1. package/README.md +28 -5
  2. package/dist/elysia/create-mcp-http-app.d.ts +17 -0
  3. package/dist/elysia/find-bearer-token.d.ts +1 -0
  4. package/dist/elysia/index.d.ts +2 -0
  5. package/dist/elysia/is-beside-prefix.d.ts +1 -0
  6. package/dist/index.d.ts +1 -0
  7. package/dist/passkeys/verify-passkey-assertion.d.ts +1 -0
  8. package/dist/passkeys/verify-passkey-registration.d.ts +1 -0
  9. package/dist/store/check-cascade-keys.d.ts +2 -2
  10. package/dist/store/check-foreign-keys.d.ts +2 -2
  11. package/dist/store/check-user-columns.d.ts +2 -2
  12. package/dist/store/create-owned-tables.d.ts +2 -2
  13. package/dist/store/open-store.d.ts +1 -0
  14. package/dist/store/read-table-columns.d.ts +2 -2
  15. package/dist/test-utils/open-test-auth.d.ts +2 -0
  16. package/dist/types.d.ts +5 -3
  17. package/package.json +13 -1
  18. package/src/admin/build-admin.ts +1 -1
  19. package/src/admin/build-client-admin.ts +24 -7
  20. package/src/elysia/create-mcp-http-app.ts +218 -0
  21. package/src/elysia/find-bearer-token.ts +6 -0
  22. package/src/elysia/index.ts +2 -0
  23. package/src/elysia/is-beside-prefix.ts +7 -0
  24. package/src/index.ts +1 -0
  25. package/src/passkeys/verify-passkey-assertion.ts +3 -0
  26. package/src/passkeys/verify-passkey-registration.ts +3 -0
  27. package/src/store/check-cascade-keys.ts +6 -6
  28. package/src/store/check-foreign-keys.ts +7 -4
  29. package/src/store/check-user-columns.ts +3 -3
  30. package/src/store/create-owned-tables.ts +22 -11
  31. package/src/store/open-store.ts +27 -7
  32. package/src/store/read-table-columns.ts +8 -4
  33. package/src/test-utils/open-test-auth.ts +6 -1
  34. package/src/types.ts +15 -4
package/README.md CHANGED
@@ -5,8 +5,9 @@ route. It is built on better-auth and `bun:sqlite`, and holds the OAuth routes a
5
5
  login for the owner, pre-registered clients, service tokens and grant revoke. Each app passes in its
6
6
  own scopes, paths, table names and grant limits.
7
7
 
8
- The package exports the core from `@zgeoff/mcp-auth` and the test helpers from
9
- `@zgeoff/mcp-auth/testing`. The package needs Bun.
8
+ The package exports the core from `@zgeoff/mcp-auth`, an Elysia 2 adapter from
9
+ `@zgeoff/mcp-auth/elysia` and the test helpers from `@zgeoff/mcp-auth/testing`. The package needs
10
+ Bun.
10
11
 
11
12
  ## Install
12
13
 
@@ -14,12 +15,14 @@ The package exports the core from `@zgeoff/mcp-auth` and the test helpers from
14
15
  bun add @zgeoff/mcp-auth kysely
15
16
  ```
16
17
 
17
- Kysely is a peer dependency.
18
+ Kysely is a peer dependency. Elysia 2 is an optional peer dependency, needed only for the adapter.
18
19
 
19
20
  ## Usage
20
21
 
21
- The app opens the server once at start, on a `bun:sqlite` connection that it owns. Each route is a
22
- function from `Request` to `Response`, and `verify` turns a bearer token into an `Access` or `null`.
22
+ The app opens the server once at start, on a `bun:sqlite` connection that it owns. An app whose own
23
+ Kysely runs on that connection passes the Kysely as `database` instead, so both share one driver
24
+ lock. Each route is a function from `Request` to `Response`, and `verify` turns a bearer token into
25
+ an `Access` or `null`.
23
26
 
24
27
  ```ts
25
28
  import { DEFAULT_PATHS, openMCPAuth } from '@zgeoff/mcp-auth';
@@ -39,6 +42,25 @@ const auth = await openMCPAuth({
39
42
  const access = await auth.verify(bearerToken);
40
43
  ```
41
44
 
45
+ `createMCPHTTPApp` from `@zgeoff/mcp-auth/elysia` serves the routes in an Elysia app. It refuses a
46
+ wrong Host or Origin header, and checks the bearer token before it hands a request to `mcp.fetch`.
47
+
48
+ ```ts
49
+ import { createMCPHTTPApp } from '@zgeoff/mcp-auth/elysia';
50
+
51
+ app.use(
52
+ createMCPHTTPApp({
53
+ auth,
54
+ hosts: new Set(['app.example.com']),
55
+ origins: new Set(['https://app.example.com']),
56
+ readRequester,
57
+ security: { record: (event) => console.log(event) },
58
+ mcp: { fetch: (request, access) => mcpHandler.fetch(request, access) },
59
+ besidePrefix: '/api',
60
+ }),
61
+ );
62
+ ```
63
+
42
64
  A command that only manages clients, grants and passkeys calls `openMCPAuthAdmin`, with no origin.
43
65
 
44
66
  ## Features
@@ -49,6 +71,7 @@ A command that only manages clients, grants and passkeys calls `openMCPAuthAdmin
49
71
  - A revoke that ends every token of a grant with one delete, even in the middle of a refresh.
50
72
  - Bearer tokens only: the token route drops DPoP, and `verify` refuses a token bound to a key.
51
73
  - Service tokens for clients that cannot run the browser flow.
74
+ - An Elysia adapter that checks Host, Origin and the bearer token of each MCP request.
52
75
  - Test helpers: `openTestAuth`, `authorizeTestClient`, and seeds for clients and passkeys.
53
76
 
54
77
  ## Documentation
@@ -0,0 +1,17 @@
1
+ import { Elysia } from 'elysia';
2
+ import type { Access, MCPAuth, Requester, SecuritySink } from '../types.ts';
3
+ export interface MCPHTTPAppOptions<Scope extends string, Limits> {
4
+ readonly auth: MCPAuth<Scope, Limits>;
5
+ readonly hosts: ReadonlySet<string>;
6
+ readonly origins: ReadonlySet<string>;
7
+ readonly readRequester: (request: Request) => Requester;
8
+ readonly security: SecuritySink;
9
+ readonly mcp: {
10
+ readonly fetch: (request: Request, access: Access<Scope, Limits>) => Promise<Response>;
11
+ };
12
+ readonly besidePrefix: string;
13
+ }
14
+ export declare function createMCPHTTPApp<Scope extends string, Limits>(options: MCPHTTPAppOptions<Scope, Limits>): Elysia<"", "local", import("elysia").DefaultSingleton, {
15
+ typebox: {};
16
+ error: [];
17
+ }, import("elysia").DefaultMetadata, {}, import("elysia").DefaultEphemeral, import("elysia").DefaultEphemeral>;
@@ -0,0 +1 @@
1
+ export declare function findBearerToken(authorization: string | null): string | null;
@@ -0,0 +1,2 @@
1
+ export { createMCPHTTPApp } from './create-mcp-http-app.ts';
2
+ export type { MCPHTTPAppOptions } from './create-mcp-http-app.ts';
@@ -0,0 +1 @@
1
+ export declare function isBesidePrefix(path: string, prefix: string): boolean;
package/dist/index.d.ts CHANGED
@@ -3,5 +3,6 @@ export { MCPAuthError } from './mcp-auth-error.ts';
3
3
  export type { MCPAuthErrorCode } from './mcp-auth-error.ts';
4
4
  export { openMCPAuth } from './open-mcp-auth.ts';
5
5
  export { openMCPAuthAdmin } from './open-mcp-auth-admin.ts';
6
+ export { normalizeClientName } from './utils/normalize-client-name.ts';
6
7
  export { parseServiceTokenFile } from './service-tokens/parse-service-token-file.ts';
7
8
  export type * from './types.ts';
@@ -1,3 +1,4 @@
1
+ import 'reflect-metadata';
1
2
  import type { Store } from '../store/open-store.ts';
2
3
  import type { PasskeyID } from '../types.ts';
3
4
  interface AssertionCheck {
@@ -1,3 +1,4 @@
1
+ import 'reflect-metadata';
1
2
  import type { PasskeyID } from '../types.ts';
2
3
  interface RegistrationCheck {
3
4
  readonly credential: string;
@@ -1,2 +1,2 @@
1
- import type { Database } from 'bun:sqlite';
2
- export declare function checkCascadeKeys(sqlite: Database): void;
1
+ import type { QueryExecutorProvider } from 'kysely';
2
+ export declare function checkCascadeKeys(db: QueryExecutorProvider): Promise<void>;
@@ -1,2 +1,2 @@
1
- import type { Database } from 'bun:sqlite';
2
- export declare function checkForeignKeys(sqlite: Database): void;
1
+ import type { QueryExecutorProvider } from 'kysely';
2
+ export declare function checkForeignKeys(db: QueryExecutorProvider): Promise<void>;
@@ -1,2 +1,2 @@
1
- import type { Database } from 'bun:sqlite';
2
- export declare function checkUserColumns(sqlite: Database): void;
1
+ import type { QueryExecutorProvider } from 'kysely';
2
+ export declare function checkUserColumns(db: QueryExecutorProvider): Promise<void>;
@@ -1,3 +1,3 @@
1
- import type { Database } from 'bun:sqlite';
1
+ import type { QueryExecutorProvider } from 'kysely';
2
2
  import type { MCPAuthTables } from '../types.ts';
3
- export declare function createOwnedTables(sqlite: Database, tables: MCPAuthTables): void;
3
+ export declare function createOwnedTables(db: QueryExecutorProvider, tables: MCPAuthTables): Promise<void>;
@@ -6,6 +6,7 @@ export interface Store {
6
6
  readonly db: Kysely<StoreSchema>;
7
7
  readonly auth: AuthServer;
8
8
  readonly options: MCPAuthAdminOptions<string>;
9
+ readonly close: () => Promise<void>;
9
10
  }
10
11
  interface StoreOptions {
11
12
  readonly origin: string | null;
@@ -1,2 +1,2 @@
1
- import type { Database } from 'bun:sqlite';
2
- export declare function readTableColumns(sqlite: Database, table: string): string[];
1
+ import type { QueryExecutorProvider } from 'kysely';
2
+ export declare function readTableColumns(db: QueryExecutorProvider, table: string): Promise<string[]>;
@@ -1,8 +1,10 @@
1
1
  import type { Database } from 'bun:sqlite';
2
+ import type { Kysely } from 'kysely';
2
3
  import type { GrantID, GrantLimits, MCPAuth, SecurityEvent, ServiceTokenFile } from '../types.ts';
3
4
  import { buildStubClock } from './build-stub-clock.ts';
4
5
  interface TestAuthInput<Limits> {
5
6
  readonly database?: Database;
7
+ readonly appKysely?: Kysely<any> | undefined;
6
8
  readonly grantLimits?: GrantLimits<Limits>;
7
9
  readonly serviceTokens?: {
8
10
  readonly prefix: string;
package/dist/types.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { Database } from 'bun:sqlite';
2
+ import type { Kysely } from 'kysely';
2
3
  import type { Tagged } from 'type-fest';
3
4
  export type GrantID = Tagged<string, 'GrantID'>;
4
5
  export type OAuthClientID = Tagged<string, 'OAuthClientID'>;
@@ -54,7 +55,7 @@ export interface SecuritySink {
54
55
  readonly record: (event: SecurityEvent) => void;
55
56
  }
56
57
  export interface MCPAuthAdminOptions<Scope extends string> {
57
- readonly database: Database;
58
+ readonly database: Database | Kysely<any>;
58
59
  readonly scopes: readonly Scope[];
59
60
  readonly tables: MCPAuthTables;
60
61
  readonly clock: Clock;
@@ -111,8 +112,9 @@ export interface MCPAuthAdmin {
111
112
  readonly clients: {
112
113
  readonly list: () => Promise<ClientView[]>;
113
114
  readonly add: (name: string, redirectURIs: readonly string[]) => Promise<ClientView>;
114
- readonly update: (name: string, redirectURIs: readonly string[]) => Promise<ClientView>;
115
- readonly remove: (name: string) => Promise<number>;
115
+ readonly readByName: (name: string) => Promise<ClientView[]>;
116
+ readonly update: (clientID: OAuthClientID, redirectURIs: readonly string[]) => Promise<ClientView>;
117
+ readonly remove: (clientID: OAuthClientID) => Promise<number>;
116
118
  };
117
119
  readonly grants: {
118
120
  readonly list: () => Promise<GrantView[]>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zgeoff/mcp-auth",
3
- "version": "0.0.0",
3
+ "version": "0.2.0",
4
4
  "description": "A shared OAuth server for the MCP route of an app, built on better-auth, with passkey sign-in for the owner",
5
5
  "keywords": [
6
6
  "better-auth",
@@ -25,6 +25,10 @@
25
25
  "types": "./dist/index.d.ts",
26
26
  "default": "./src/index.ts"
27
27
  },
28
+ "./elysia": {
29
+ "types": "./dist/elysia/index.d.ts",
30
+ "default": "./src/elysia/index.ts"
31
+ },
28
32
  "./testing": {
29
33
  "types": "./dist/test-utils/index.d.ts",
30
34
  "default": "./src/test-utils/index.ts"
@@ -44,20 +48,28 @@
44
48
  "@zgeoff/kysely-bun-sqlite": "0.3.2",
45
49
  "@zgeoff/std": "0.4.3",
46
50
  "better-auth": "1.7.15",
51
+ "reflect-metadata": "0.2.2",
47
52
  "ts-pattern": "5.9.2",
48
53
  "type-fest": "5.10.0",
49
54
  "zod": "4.6.7"
50
55
  },
51
56
  "devDependencies": {
52
57
  "@types/bun": "1.4.4",
58
+ "elysia": "2.0.0-rc.3",
53
59
  "kysely": "0.29.8",
54
60
  "tiny-invariant": "1.3.3",
55
61
  "tsrs": "0.18.0-ts7.1.0-dev.20260929",
56
62
  "typescript": "7.0.2"
57
63
  },
58
64
  "peerDependencies": {
65
+ "elysia": ">=2.0.0-rc.3 <3.0.0",
59
66
  "kysely": ">=0.29.5 <0.30.0"
60
67
  },
68
+ "peerDependenciesMeta": {
69
+ "elysia": {
70
+ "optional": true
71
+ }
72
+ },
61
73
  "engines": {
62
74
  "bun": ">=1.3"
63
75
  }
@@ -16,7 +16,7 @@ export function buildAdmin(
16
16
  passkeys: buildPasskeyAdmin(store),
17
17
  removeExpired: () => removeExpired(store),
18
18
  close: async () => {
19
- await store.db.destroy();
19
+ await store.close();
20
20
  },
21
21
  };
22
22
  }
@@ -5,6 +5,7 @@ import type { SignInState } from '../sign-in/create-sign-in-state.ts';
5
5
  import type { Store } from '../store/open-store.ts';
6
6
  import { removeGrantRows } from '../store/remove-grant-rows.ts';
7
7
  import type { GrantID, MCPAuthAdmin, OAuthClientID } from '../types.ts';
8
+ import { normalizeClientName } from '../utils/normalize-client-name.ts';
8
9
  import { checkRedirectURIs } from './check-redirect-uris.ts';
9
10
  import { readClientName } from './read-client-name.ts';
10
11
  import { toClientView } from './to-client-view.ts';
@@ -16,11 +17,15 @@ export function buildClientAdmin(
16
17
  const readClient = (name: string) =>
17
18
  store.db.selectFrom('oauthClient').selectAll().where('name', '=', name).executeTakeFirst();
18
19
 
19
- const requireClient = async (name: string) => {
20
- const client = await readClient(name);
20
+ const requireClient = async (clientID: OAuthClientID) => {
21
+ const client = await store.db
22
+ .selectFrom('oauthClient')
23
+ .selectAll()
24
+ .where('clientId', '=', clientID)
25
+ .executeTakeFirst();
21
26
 
22
27
  if (client === undefined) {
23
- throw new MCPAuthError('not-found', 'no client has that name');
28
+ throw new MCPAuthError('not-found', 'no client has that ID');
24
29
  }
25
30
 
26
31
  return client;
@@ -33,6 +38,18 @@ export function buildClientAdmin(
33
38
  return rows.map((row) => toClientView(row));
34
39
  },
35
40
 
41
+ // A database from the old apps can hold names that clean alike, so the
42
+ // match is on the cleaned stored name.
43
+ readByName: async (name) => {
44
+ const cleaned = readClientName(name);
45
+
46
+ const rows = await store.db.selectFrom('oauthClient').selectAll().orderBy('name').execute();
47
+
48
+ return rows
49
+ .filter((row) => normalizeClientName(row.name, '') === cleaned)
50
+ .map((row) => toClientView(row));
51
+ },
52
+
36
53
  add: async (name, redirectURIs) => {
37
54
  const cleaned = readClientName(name);
38
55
 
@@ -70,8 +87,8 @@ export function buildClientAdmin(
70
87
  return toClientView(row);
71
88
  },
72
89
 
73
- update: async (name, redirectURIs) => {
74
- const client = await requireClient(readClientName(name));
90
+ update: async (clientID, redirectURIs) => {
91
+ const client = await requireClient(clientID);
75
92
 
76
93
  checkRedirectURIs(redirectURIs);
77
94
 
@@ -88,8 +105,8 @@ export function buildClientAdmin(
88
105
  return toClientView(row);
89
106
  },
90
107
 
91
- remove: async (name) => {
92
- const client = await requireClient(readClientName(name));
108
+ remove: async (clientID) => {
109
+ const client = await requireClient(clientID);
93
110
 
94
111
  const grants = await store.db
95
112
  .selectFrom('user')
@@ -0,0 +1,218 @@
1
+ import { Elysia } from 'elysia';
2
+ import type { Access, MCPAuth, MCPAuthRouteName, Requester, SecuritySink } from '../types.ts';
3
+ import { findBearerToken } from './find-bearer-token.ts';
4
+ import { isBesidePrefix } from './is-beside-prefix.ts';
5
+
6
+ export interface MCPHTTPAppOptions<Scope extends string, Limits> {
7
+ readonly auth: MCPAuth<Scope, Limits>;
8
+
9
+ // The Host header values the app answers to.
10
+ readonly hosts: ReadonlySet<string>;
11
+
12
+ // The Origin header values a POST may carry.
13
+ readonly origins: ReadonlySet<string>;
14
+ readonly readRequester: (request: Request) => Requester;
15
+ readonly security: SecuritySink;
16
+ readonly mcp: {
17
+ readonly fetch: (request: Request, access: Access<Scope, Limits>) => Promise<Response>;
18
+ };
19
+
20
+ // Paths under this prefix belong to the app. The adapter serves none of
21
+ // them, and checks neither their Host nor their Origin header.
22
+ readonly besidePrefix: string;
23
+ }
24
+
25
+ interface RouteContext {
26
+ readonly request: Request;
27
+ }
28
+
29
+ type RouteMethod = 'get' | 'post';
30
+
31
+ interface RouteSpec {
32
+ readonly name: MCPAuthRouteName;
33
+ readonly path: (auth: MCPAuth<string, unknown>) => string;
34
+ readonly methods: readonly RouteMethod[];
35
+
36
+ // A form page refuses a POST that carries no Origin header.
37
+ readonly isPage: boolean;
38
+ }
39
+
40
+ const ROUTES: readonly RouteSpec[] = [
41
+ {
42
+ name: 'authorize',
43
+ path: (auth) => auth.paths.browser.authorize,
44
+ methods: ['get'],
45
+ isPage: false,
46
+ },
47
+ {
48
+ name: 'login',
49
+ path: (auth) => auth.paths.browser.login,
50
+ methods: ['get', 'post'],
51
+ isPage: true,
52
+ },
53
+ {
54
+ name: 'enroll',
55
+ path: (auth) => auth.paths.browser.enroll,
56
+ methods: ['get', 'post'],
57
+ isPage: true,
58
+ },
59
+ {
60
+ name: 'consent',
61
+ path: (auth) => auth.paths.browser.consent,
62
+ methods: ['get', 'post'],
63
+ isPage: true,
64
+ },
65
+ { name: 'error', path: (auth) => auth.paths.browser.error, methods: ['get'], isPage: false },
66
+ { name: 'token', path: (auth) => auth.paths.machine.token, methods: ['post'], isPage: false },
67
+ { name: 'revoke', path: (auth) => auth.paths.machine.revoke, methods: ['post'], isPage: false },
68
+ {
69
+ name: 'authorizationServerMetadata',
70
+ path: (auth) => auth.paths.machine.authorizationServerMetadata,
71
+ methods: ['get'],
72
+ isPage: false,
73
+ },
74
+ {
75
+ name: 'resourceMetadata',
76
+ path: (auth) => auth.paths.machine.resourceMetadata,
77
+ methods: ['get'],
78
+ isPage: false,
79
+ },
80
+ ];
81
+
82
+ export function createMCPHTTPApp<Scope extends string, Limits>(
83
+ options: MCPHTTPAppOptions<Scope, Limits>,
84
+ ) {
85
+ const auth = options.auth;
86
+
87
+ const app = new Elysia();
88
+
89
+ const recordRefusal = (
90
+ request: Request,
91
+ kind: 'bad_host' | 'bad_origin',
92
+ reason: string,
93
+ ): void => {
94
+ options.security.record({
95
+ kind,
96
+ outcome: 'rejected',
97
+ reason,
98
+ path: new URL(request.url).pathname,
99
+ requester: options.readRequester(request),
100
+ });
101
+ };
102
+
103
+ const isForeignOrigin = (request: Request, isPage: boolean): boolean => {
104
+ if (request.method !== 'POST') {
105
+ return false;
106
+ }
107
+
108
+ const origin = request.headers.get('origin');
109
+
110
+ return origin === null ? isPage : !options.origins.has(origin);
111
+ };
112
+
113
+ const guard = (request: Request, isPage: boolean): Response | null => {
114
+ if (isForeignOrigin(request, isPage)) {
115
+ recordRefusal(request, 'bad_origin', 'origin_not_allowed');
116
+
117
+ return new Response(null, { status: 403 });
118
+ }
119
+
120
+ return null;
121
+ };
122
+
123
+ app.onRequest((context: RouteContext): Response | undefined => {
124
+ const path = new URL(context.request.url).pathname;
125
+
126
+ const host = context.request.headers.get('host');
127
+
128
+ const isRefused =
129
+ !isBesidePrefix(path, options.besidePrefix) && (host === null || !options.hosts.has(host));
130
+
131
+ if (!isRefused) {
132
+ return undefined;
133
+ }
134
+
135
+ recordRefusal(context.request, 'bad_host', 'host_not_allowed');
136
+
137
+ return new Response(null, { status: 403 });
138
+ });
139
+
140
+ for (const spec of ROUTES) {
141
+ const path = spec.path(auth);
142
+
143
+ if (isBesidePrefix(path, options.besidePrefix)) {
144
+ continue;
145
+ }
146
+
147
+ const answer = (context: RouteContext): Response | Promise<Response> =>
148
+ guard(context.request, spec.isPage) ??
149
+ auth.routes[spec.name](context.request, options.readRequester(context.request));
150
+
151
+ if (spec.methods.includes('get')) {
152
+ app.get(path, answer);
153
+ }
154
+
155
+ if (spec.methods.includes('post')) {
156
+ app.post(path, answer);
157
+ }
158
+ }
159
+
160
+ const metadataURL = `${auth.issuer}${auth.paths.machine.mcpResourceMetadata}`;
161
+
162
+ const answerMCP = async (request: Request): Promise<Response> => {
163
+ const refused = guard(request, false);
164
+
165
+ if (refused !== null) {
166
+ return refused;
167
+ }
168
+
169
+ const authorization = request.headers.get('authorization');
170
+ const token = findBearerToken(authorization);
171
+
172
+ if (token === null) {
173
+ const reason = authorization === null ? 'missing' : 'malformed';
174
+
175
+ recordBearerRefusal(request, reason);
176
+
177
+ return buildChallenge(`Bearer resource_metadata="${metadataURL}"`);
178
+ }
179
+
180
+ const access = await auth.verify(token);
181
+
182
+ if (access === null) {
183
+ recordBearerRefusal(request, 'invalid_token');
184
+
185
+ return buildChallenge(`Bearer error="invalid_token", resource_metadata="${metadataURL}"`);
186
+ }
187
+
188
+ return options.mcp.fetch(request, access);
189
+ };
190
+
191
+ const recordBearerRefusal = (request: Request, reason: string): void => {
192
+ options.security.record({
193
+ kind: 'bearer',
194
+ outcome: 'rejected',
195
+ reason,
196
+ path: new URL(request.url).pathname,
197
+ requester: options.readRequester(request),
198
+ });
199
+ };
200
+
201
+ for (const path of [auth.paths.machine.mcp, auth.paths.machine.root]) {
202
+ if (!isBesidePrefix(path, options.besidePrefix)) {
203
+ app.all(path, (context: RouteContext) => answerMCP(context.request));
204
+ }
205
+ }
206
+
207
+ if (!isBesidePrefix(auth.paths.machine.mcpResourceMetadata, options.besidePrefix)) {
208
+ app.get(auth.paths.machine.mcpResourceMetadata, (context: RouteContext) =>
209
+ auth.routes.resourceMetadata(context.request, options.readRequester(context.request)),
210
+ );
211
+ }
212
+
213
+ return app;
214
+ }
215
+
216
+ function buildChallenge(challenge: string): Response {
217
+ return new Response(null, { status: 401, headers: { 'www-authenticate': challenge } });
218
+ }
@@ -0,0 +1,6 @@
1
+ const BEARER_PATTERN = /^Bearer (?<token>\S+)$/iu;
2
+
3
+ // Null when the header is missing or holds no bearer token.
4
+ export function findBearerToken(authorization: string | null): string | null {
5
+ return BEARER_PATTERN.exec(authorization ?? '')?.groups?.['token'] ?? null;
6
+ }
@@ -0,0 +1,2 @@
1
+ export { createMCPHTTPApp } from './create-mcp-http-app.ts';
2
+ export type { MCPHTTPAppOptions } from './create-mcp-http-app.ts';
@@ -0,0 +1,7 @@
1
+ // A path is beside the prefix when it is the prefix or lies under it, so
2
+ // `/api` covers `/api` and `/api/x` but not `/apiary`.
3
+ export function isBesidePrefix(path: string, prefix: string): boolean {
4
+ const base = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;
5
+
6
+ return path === base || path.startsWith(`${base}/`);
7
+ }
package/src/index.ts CHANGED
@@ -3,5 +3,6 @@ export { MCPAuthError } from './mcp-auth-error.ts';
3
3
  export type { MCPAuthErrorCode } from './mcp-auth-error.ts';
4
4
  export { openMCPAuth } from './open-mcp-auth.ts';
5
5
  export { openMCPAuthAdmin } from './open-mcp-auth-admin.ts';
6
+ export { normalizeClientName } from './utils/normalize-client-name.ts';
6
7
  export { parseServiceTokenFile } from './service-tokens/parse-service-token-file.ts';
7
8
  export type * from './types.ts';
@@ -1,3 +1,6 @@
1
+ // The certificate code of simplewebauthn needs the polyfill loaded first, and a compiled binary does not load it.
2
+ // oxlint-disable-next-line import/no-unassigned-import -- the polyfill is a side effect
3
+ import 'reflect-metadata';
1
4
  import { verifyAuthenticationResponse } from '@simplewebauthn/server';
2
5
  import type {
3
6
  AuthenticationResponseJSON,
@@ -1,3 +1,6 @@
1
+ // The certificate code of simplewebauthn needs the polyfill loaded first, and a compiled binary does not load it.
2
+ // oxlint-disable-next-line import/no-unassigned-import -- the polyfill is a side effect
3
+ import 'reflect-metadata';
1
4
  import type { RegistrationResponseJSON } from '@simplewebauthn/server';
2
5
  import { verifyRegistrationResponse } from '@simplewebauthn/server';
3
6
  import { toTagged } from '@zgeoff/std';
@@ -1,4 +1,5 @@
1
- import type { Database } from 'bun:sqlite';
1
+ import { sql } from 'kysely';
2
+ import type { QueryExecutorProvider } from 'kysely';
2
3
  import { z } from 'zod';
3
4
  import { MCPAuthError } from '../mcp-auth-error.ts';
4
5
 
@@ -11,12 +12,11 @@ const KeyRowSchema = z.object({
11
12
  on_delete: z.string(),
12
13
  });
13
14
 
14
- export function checkCascadeKeys(sqlite: Database): void {
15
+ export async function checkCascadeKeys(db: QueryExecutorProvider): Promise<void> {
15
16
  for (const table of CASCADING_TABLES) {
16
- const keys = sqlite
17
- .query(`PRAGMA foreign_key_list("${table}")`)
18
- .all()
19
- .map((row) => KeyRowSchema.parse(row));
17
+ const result = await sql`PRAGMA foreign_key_list(${sql.raw(`"${table}"`)})`.execute(db);
18
+
19
+ const keys = result.rows.map((row) => KeyRowSchema.parse(row));
20
20
 
21
21
  const isCascading = keys.some(
22
22
  (key) =>
@@ -1,4 +1,5 @@
1
- import type { Database } from 'bun:sqlite';
1
+ import { sql } from 'kysely';
2
+ import type { QueryExecutorProvider } from 'kysely';
2
3
  import { z } from 'zod';
3
4
  import { MCPAuthError } from '../mcp-auth-error.ts';
4
5
 
@@ -6,10 +7,12 @@ const PragmaRowSchema = z.object({ foreign_keys: z.number() });
6
7
 
7
8
  // A pragma inside a transaction does nothing, so the core reads the setting
8
9
  // back instead of trusting the statement.
9
- export function checkForeignKeys(sqlite: Database): void {
10
- sqlite.run('PRAGMA foreign_keys = ON');
10
+ export async function checkForeignKeys(db: QueryExecutorProvider): Promise<void> {
11
+ await sql`PRAGMA foreign_keys = ON`.execute(db);
11
12
 
12
- const row = PragmaRowSchema.parse(sqlite.query('PRAGMA foreign_keys').get());
13
+ const result = await sql`PRAGMA foreign_keys`.execute(db);
14
+
15
+ const row = PragmaRowSchema.parse(result.rows[0]);
13
16
 
14
17
  if (row.foreign_keys === 0) {
15
18
  throw new MCPAuthError(
@@ -1,11 +1,11 @@
1
- import type { Database } from 'bun:sqlite';
1
+ import type { QueryExecutorProvider } from 'kysely';
2
2
  import { MCPAuthError } from '../mcp-auth-error.ts';
3
3
  import { readTableColumns } from './read-table-columns.ts';
4
4
 
5
5
  // A user table from before the grant columns cannot take them as new required
6
6
  // columns, so the app's migration comes first.
7
- export function checkUserColumns(sqlite: Database): void {
8
- const columns = readTableColumns(sqlite, 'user');
7
+ export async function checkUserColumns(db: QueryExecutorProvider): Promise<void> {
8
+ const columns = await readTableColumns(db, 'user');
9
9
 
10
10
  if (columns.length === 0) {
11
11
  return;
@@ -1,4 +1,5 @@
1
- import type { Database } from 'bun:sqlite';
1
+ import { sql } from 'kysely';
2
+ import type { QueryExecutorProvider } from 'kysely';
2
3
  import { MCPAuthError } from '../mcp-auth-error.ts';
3
4
  import type { MCPAuthTables } from '../types.ts';
4
5
  import { readTableColumns } from './read-table-columns.ts';
@@ -16,12 +17,18 @@ const ENROLLMENT_COLUMNS = ['token_hash', 'created_at', 'expires_at'] as const;
16
17
 
17
18
  // The core creates its own table and any column of it that is missing. It
18
19
  // creates the app's passkey table when absent, and never adds a column to it.
19
- export function createOwnedTables(sqlite: Database, tables: MCPAuthTables): void {
20
- sqlite.run(
21
- `create table if not exists "${tables.passkey}" (id text primary key not null, public_key text not null, counter integer not null, transports text not null, created_at text not null, last_used_at text)`,
22
- );
20
+ export async function createOwnedTables(
21
+ db: QueryExecutorProvider,
22
+ tables: MCPAuthTables,
23
+ ): Promise<void> {
24
+ await sql
25
+ .raw(
26
+ `create table if not exists "${tables.passkey}" (id text primary key not null, public_key text not null, counter integer not null, transports text not null, created_at text not null, last_used_at text)`,
27
+ )
28
+ .execute(db);
29
+
30
+ const passkeyColumns = await readTableColumns(db, tables.passkey);
23
31
 
24
- const passkeyColumns = readTableColumns(sqlite, tables.passkey);
25
32
  const missing = PASSKEY_COLUMNS.filter((column) => !passkeyColumns.includes(column));
26
33
 
27
34
  if (missing.length > 0) {
@@ -31,15 +38,19 @@ export function createOwnedTables(sqlite: Database, tables: MCPAuthTables): void
31
38
  );
32
39
  }
33
40
 
34
- sqlite.run(
35
- `create table if not exists "${tables.enrollmentToken}" (token_hash text primary key not null, created_at text not null, expires_at text not null)`,
36
- );
41
+ await sql
42
+ .raw(
43
+ `create table if not exists "${tables.enrollmentToken}" (token_hash text primary key not null, created_at text not null, expires_at text not null)`,
44
+ )
45
+ .execute(db);
37
46
 
38
- const enrollmentColumns = readTableColumns(sqlite, tables.enrollmentToken);
47
+ const enrollmentColumns = await readTableColumns(db, tables.enrollmentToken);
39
48
 
40
49
  for (const column of ENROLLMENT_COLUMNS) {
41
50
  if (!enrollmentColumns.includes(column)) {
42
- sqlite.run(`alter table "${tables.enrollmentToken}" add column "${column}" text`);
51
+ await sql
52
+ .raw(`alter table "${tables.enrollmentToken}" add column "${column}" text`)
53
+ .execute(db);
43
54
  }
44
55
  }
45
56
  }
@@ -1,3 +1,4 @@
1
+ import { Database } from 'bun:sqlite';
1
2
  import { buildSQLiteDialect } from '@zgeoff/kysely-bun-sqlite';
2
3
  import { getMigrations } from 'better-auth/db/migration';
3
4
  import { Kysely } from 'kysely';
@@ -15,8 +16,14 @@ export interface Store {
15
16
  readonly db: Kysely<StoreSchema>;
16
17
  readonly auth: AuthServer;
17
18
  readonly options: MCPAuthAdminOptions<string>;
19
+
20
+ // Ends the Kysely the store built, and leaves the app's own Kysely running.
21
+ readonly close: () => Promise<void>;
18
22
  }
19
23
 
24
+ // A mapped type has the index signature that withTables asks for.
25
+ type StoreTables = { [Table in keyof StoreSchema]: StoreSchema[Table] };
26
+
20
27
  interface StoreOptions {
21
28
  readonly origin: string | null;
22
29
  readonly paths: MCPAuthPaths;
@@ -29,12 +36,25 @@ export async function openStore(
29
36
  options: StoreOptions,
30
37
  ): Promise<Store> {
31
38
  checkTableNames(admin.tables);
32
- checkForeignKeys(admin.database);
33
- checkUserColumns(admin.database);
34
39
 
35
- const db = new Kysely<StoreSchema>({ dialect: buildSQLiteDialect(admin.database) });
40
+ // A Kysely of the app is the app's driver and its one lock: a second Kysely
41
+ // over the same connection has a lock of its own, so a core statement could
42
+ // run inside an app transaction and an app rollback would undo it.
43
+ const db: Kysely<StoreSchema> =
44
+ admin.database instanceof Database
45
+ ? new Kysely<StoreSchema>({ dialect: buildSQLiteDialect(admin.database) })
46
+ : admin.database.$extendTables<StoreTables>();
47
+
48
+ const close = async () => {
49
+ if (admin.database instanceof Database) {
50
+ await db.destroy();
51
+ }
52
+ };
36
53
 
37
54
  try {
55
+ await checkForeignKeys(db);
56
+ await checkUserColumns(db);
57
+
38
58
  const auth = createAuthServer({
39
59
  db,
40
60
  origin: options.origin,
@@ -46,8 +66,8 @@ export async function openStore(
46
66
 
47
67
  await migrations.runMigrations();
48
68
 
49
- createOwnedTables(admin.database, admin.tables);
50
- checkCascadeKeys(admin.database);
69
+ await createOwnedTables(db, admin.tables);
70
+ await checkCascadeKeys(db);
51
71
 
52
72
  // better-auth starts its context when it is built, and that start queries
53
73
  // the database, so a close before it settles destroys the driver under it.
@@ -63,9 +83,9 @@ export async function openStore(
63
83
  onGrantRevoked: admin.onGrantRevoked,
64
84
  };
65
85
 
66
- return { db, auth, options: kept };
86
+ return { db, auth, options: kept, close };
67
87
  } catch (error) {
68
- await db.destroy();
88
+ await close();
69
89
 
70
90
  throw error;
71
91
  }
@@ -1,12 +1,16 @@
1
- import type { Database } from 'bun:sqlite';
1
+ import { sql } from 'kysely';
2
+ import type { QueryExecutorProvider } from 'kysely';
2
3
  import { z } from 'zod';
3
4
 
4
5
  const ColumnRowSchema = z.object({ name: z.string() });
5
6
 
6
7
  // The columns a table holds, or an empty list when it does not exist. The
7
8
  // table name goes into the statement, so the caller has checked it.
8
- export function readTableColumns(sqlite: Database, table: string): string[] {
9
- const rows = sqlite.query(`PRAGMA table_info("${table}")`).all();
9
+ export async function readTableColumns(
10
+ db: QueryExecutorProvider,
11
+ table: string,
12
+ ): Promise<string[]> {
13
+ const result = await sql`PRAGMA table_info(${sql.raw(`"${table}"`)})`.execute(db);
10
14
 
11
- return rows.map((row) => ColumnRowSchema.parse(row).name);
15
+ return result.rows.map((row) => ColumnRowSchema.parse(row).name);
12
16
  }
@@ -1,4 +1,5 @@
1
1
  import type { Database } from 'bun:sqlite';
2
+ import type { Kysely } from 'kysely';
2
3
  import { DEFAULT_PATHS } from '../default-paths.ts';
3
4
  import { openMCPAuth } from '../open-mcp-auth.ts';
4
5
  import type { GrantID, GrantLimits, MCPAuth, SecurityEvent, ServiceTokenFile } from '../types.ts';
@@ -7,6 +8,10 @@ import { createTestDatabase } from './create-test-database.ts';
7
8
 
8
9
  interface TestAuthInput<Limits> {
9
10
  readonly database?: Database;
11
+
12
+ // The app's Kysely over the database, which the core then shares.
13
+ // oxlint-disable-next-line typescript/no-explicit-any -- an app's Kysely is typed with its own tables
14
+ readonly appKysely?: Kysely<any> | undefined;
10
15
  readonly grantLimits?: GrantLimits<Limits>;
11
16
  readonly serviceTokens?: {
12
17
  readonly prefix: string;
@@ -38,7 +43,7 @@ export async function openTestAuth<Limits = null>(
38
43
  const revoked: GrantID[] = [];
39
44
 
40
45
  const auth = await openMCPAuth({
41
- database,
46
+ database: input.appKysely ?? database,
42
47
  origin: 'https://app.example',
43
48
  productName: 'app',
44
49
  scopes: ['read', 'write'],
package/src/types.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { Database } from 'bun:sqlite';
2
+ import type { Kysely } from 'kysely';
2
3
  import type { Tagged } from 'type-fest';
3
4
 
4
5
  export type GrantID = Tagged<string, 'GrantID'>;
@@ -79,7 +80,10 @@ export interface SecuritySink {
79
80
  }
80
81
 
81
82
  export interface MCPAuthAdminOptions<Scope extends string> {
82
- readonly database: Database;
83
+ // The app's own Kysely when one runs on this connection, so the core shares
84
+ // its driver lock. A Database only when no other Kysely uses it.
85
+ // oxlint-disable-next-line typescript/no-explicit-any -- an app's Kysely is typed with its own tables, which only any accepts
86
+ readonly database: Database | Kysely<any>;
83
87
  readonly scopes: readonly Scope[];
84
88
  readonly tables: MCPAuthTables;
85
89
  readonly clock: Clock;
@@ -140,10 +144,17 @@ export interface MCPAuthAdmin {
140
144
  readonly clients: {
141
145
  readonly list: () => Promise<ClientView[]>;
142
146
  readonly add: (name: string, redirectURIs: readonly string[]) => Promise<ClientView>;
143
- readonly update: (name: string, redirectURIs: readonly string[]) => Promise<ClientView>;
147
+
148
+ // The clients whose stored name cleans to the same text as `name`: more
149
+ // than one when an old database holds two names that clean alike.
150
+ readonly readByName: (name: string) => Promise<ClientView[]>;
151
+ readonly update: (
152
+ clientID: OAuthClientID,
153
+ redirectURIs: readonly string[],
154
+ ) => Promise<ClientView>;
144
155
 
145
156
  // The number of grants it revoked.
146
- readonly remove: (name: string) => Promise<number>;
157
+ readonly remove: (clientID: OAuthClientID) => Promise<number>;
147
158
  };
148
159
  readonly grants: {
149
160
  // Grants with a live refresh token.
@@ -163,7 +174,7 @@ export interface MCPAuthAdmin {
163
174
  };
164
175
  readonly removeExpired: () => Promise<void>;
165
176
 
166
- // Leaves the bun:sqlite connection open.
177
+ // Leaves the connection open, and the app's Kysely too.
167
178
  readonly close: () => Promise<void>;
168
179
  }
169
180