@zgeoff/mcp-auth 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +55 -2
  3. package/dist/admin/build-admin.d.ts +4 -0
  4. package/dist/admin/build-client-admin.d.ts +4 -0
  5. package/dist/admin/build-grant-admin.d.ts +3 -0
  6. package/dist/admin/build-passkey-admin.d.ts +3 -0
  7. package/dist/admin/check-redirect-uris.d.ts +1 -0
  8. package/dist/admin/create-enrollment-token.d.ts +2 -0
  9. package/dist/admin/read-client-name.d.ts +1 -0
  10. package/dist/admin/read-sign-in-grants.d.ts +3 -0
  11. package/dist/admin/remove-expired.d.ts +2 -0
  12. package/dist/admin/to-client-view.d.ts +3 -0
  13. package/dist/default-paths.d.ts +18 -0
  14. package/dist/grants/collect-granted-scopes.d.ts +7 -0
  15. package/dist/grants/read-access-payload.d.ts +9 -0
  16. package/dist/grants/read-client-scopes.d.ts +2 -0
  17. package/dist/grants/verify-oauth-access.d.ts +13 -0
  18. package/dist/index.d.ts +7 -0
  19. package/dist/mcp-auth-error.d.ts +5 -0
  20. package/dist/open-mcp-auth-admin.d.ts +2 -0
  21. package/dist/open-mcp-auth.d.ts +2 -0
  22. package/dist/passkeys/answer-enroll-request.d.ts +3 -0
  23. package/dist/passkeys/create-enrollment-state.d.ts +6 -0
  24. package/dist/passkeys/create-passkey.d.ts +10 -0
  25. package/dist/passkeys/passkey-script.d.ts +4 -0
  26. package/dist/passkeys/read-enrollment-token.d.ts +2 -0
  27. package/dist/passkeys/read-passkey-rows.d.ts +13 -0
  28. package/dist/passkeys/render-enroll-page.d.ts +11 -0
  29. package/dist/passkeys/render-login-page.d.ts +11 -0
  30. package/dist/passkeys/update-passkey-use.d.ts +9 -0
  31. package/dist/passkeys/verify-passkey-assertion.d.ts +10 -0
  32. package/dist/passkeys/verify-passkey-registration.d.ts +15 -0
  33. package/dist/passkeys/verify-session-passkey.d.ts +8 -0
  34. package/dist/routes/build-routes.d.ts +3 -0
  35. package/dist/routes/with-form-origin.d.ts +4 -0
  36. package/dist/service-tokens/build-service-token-verifier.d.ts +13 -0
  37. package/dist/service-tokens/parse-service-token-file.d.ts +7 -0
  38. package/dist/sign-in/answer-authorize-request.d.ts +3 -0
  39. package/dist/sign-in/answer-consent-request.d.ts +3 -0
  40. package/dist/sign-in/answer-login-request.d.ts +3 -0
  41. package/dist/sign-in/build-consent-binding.d.ts +1 -0
  42. package/dist/sign-in/create-sign-in-state.d.ts +43 -0
  43. package/dist/sign-in/pick-consent-choice.d.ts +8 -0
  44. package/dist/sign-in/pick-consent-outcome.d.ts +4 -0
  45. package/dist/sign-in/read-session-id.d.ts +2 -0
  46. package/dist/sign-in/read-stored-client-name.d.ts +3 -0
  47. package/dist/sign-in/read-url-field.d.ts +1 -0
  48. package/dist/sign-in/render-consent-page.d.ts +11 -0
  49. package/dist/sign-in/route-context.d.ts +17 -0
  50. package/dist/sign-in/verify-oauth-query.d.ts +1 -0
  51. package/dist/store/check-cascade-keys.d.ts +2 -0
  52. package/dist/store/check-foreign-keys.d.ts +2 -0
  53. package/dist/store/check-table-names.d.ts +2 -0
  54. package/dist/store/check-user-columns.d.ts +2 -0
  55. package/dist/store/create-auth-server.d.ts +103 -0
  56. package/dist/store/create-grant-plugin.d.ts +28 -0
  57. package/dist/store/create-owned-tables.d.ts +3 -0
  58. package/dist/store/open-store.d.ts +15 -0
  59. package/dist/store/read-table-columns.d.ts +2 -0
  60. package/dist/store/remove-grant-rows.d.ts +3 -0
  61. package/dist/store/store-schema.d.ts +63 -0
  62. package/dist/test-utils/authorize-test-client.d.ts +12 -0
  63. package/dist/test-utils/build-form-request.d.ts +1 -0
  64. package/dist/test-utils/build-seeder.d.ts +13 -0
  65. package/dist/test-utils/build-stub-authenticator.d.ts +49 -0
  66. package/dist/test-utils/build-stub-clock.d.ts +5 -0
  67. package/dist/test-utils/build-test-requester.d.ts +2 -0
  68. package/dist/test-utils/create-test-database.d.ts +2 -0
  69. package/dist/test-utils/hook-sqlite-statements.d.ts +2 -0
  70. package/dist/test-utils/index.d.ts +12 -0
  71. package/dist/test-utils/open-test-auth.d.ts +21 -0
  72. package/dist/test-utils/parse-passkey-page.d.ts +21 -0
  73. package/dist/test-utils/read-json-record.d.ts +5 -0
  74. package/dist/test-utils/run-sign-in-to-consent.d.ts +13 -0
  75. package/dist/test-utils/seed-client.d.ts +7 -0
  76. package/dist/test-utils/seed-enrollment-token.d.ts +2 -0
  77. package/dist/test-utils/seed-passkey.d.ts +7 -0
  78. package/dist/tokens/answer-error-request.d.ts +2 -0
  79. package/dist/tokens/answer-metadata-request.d.ts +2 -0
  80. package/dist/tokens/answer-revoke-request.d.ts +2 -0
  81. package/dist/tokens/answer-token-request.d.ts +3 -0
  82. package/dist/tokens/build-better-auth-request.d.ts +6 -0
  83. package/dist/tokens/build-oauth-error.d.ts +1 -0
  84. package/dist/tokens/read-error-code.d.ts +1 -0
  85. package/dist/tokens/read-error-description.d.ts +1 -0
  86. package/dist/tokens/record-token-exchange.d.ts +10 -0
  87. package/dist/tokens/remove-token-sessions.d.ts +2 -0
  88. package/dist/types.d.ts +185 -0
  89. package/dist/utils/build-page-response.d.ts +5 -0
  90. package/dist/utils/derive-token-hash.d.ts +1 -0
  91. package/dist/utils/is-allowed-redirect-uri.d.ts +1 -0
  92. package/dist/utils/is-loopback-host.d.ts +1 -0
  93. package/dist/utils/normalize-client-name.d.ts +1 -0
  94. package/dist/utils/parse-approved-by.d.ts +2 -0
  95. package/dist/utils/parse-json-strings.d.ts +1 -0
  96. package/dist/utils/read-body-text.d.ts +1 -0
  97. package/dist/utils/read-form.d.ts +2 -0
  98. package/dist/utils/to-html-text.d.ts +1 -0
  99. package/dist/utils/to-script-json.d.ts +1 -0
  100. package/package.json +62 -4
  101. package/src/admin/build-admin.ts +22 -0
  102. package/src/admin/build-client-admin.ts +112 -0
  103. package/src/admin/build-grant-admin.ts +62 -0
  104. package/src/admin/build-passkey-admin.ts +53 -0
  105. package/src/admin/check-redirect-uris.ts +17 -0
  106. package/src/admin/create-enrollment-token.ts +18 -0
  107. package/src/admin/read-client-name.ts +13 -0
  108. package/src/admin/read-sign-in-grants.ts +22 -0
  109. package/src/admin/remove-expired.ts +47 -0
  110. package/src/admin/to-client-view.ts +12 -0
  111. package/src/default-paths.ts +21 -0
  112. package/src/grants/collect-granted-scopes.ts +19 -0
  113. package/src/grants/read-access-payload.ts +37 -0
  114. package/src/grants/read-client-scopes.ts +36 -0
  115. package/src/grants/verify-oauth-access.ts +113 -0
  116. package/src/index.ts +7 -0
  117. package/src/mcp-auth-error.ts +17 -0
  118. package/src/open-mcp-auth-admin.ts +14 -0
  119. package/src/open-mcp-auth.ts +89 -0
  120. package/src/passkeys/answer-enroll-request.ts +179 -0
  121. package/src/passkeys/create-enrollment-state.ts +54 -0
  122. package/src/passkeys/create-passkey.ts +39 -0
  123. package/src/passkeys/passkey-script.ts +48 -0
  124. package/src/passkeys/read-enrollment-token.ts +21 -0
  125. package/src/passkeys/read-passkey-rows.ts +30 -0
  126. package/src/passkeys/render-enroll-page.ts +58 -0
  127. package/src/passkeys/render-login-page.ts +59 -0
  128. package/src/passkeys/update-passkey-use.ts +24 -0
  129. package/src/passkeys/verify-passkey-assertion.ts +120 -0
  130. package/src/passkeys/verify-passkey-registration.ts +116 -0
  131. package/src/passkeys/verify-session-passkey.ts +42 -0
  132. package/src/routes/build-routes.ts +31 -0
  133. package/src/routes/with-form-origin.ts +18 -0
  134. package/src/service-tokens/build-service-token-verifier.ts +56 -0
  135. package/src/service-tokens/parse-service-token-file.ts +104 -0
  136. package/src/sign-in/answer-authorize-request.ts +133 -0
  137. package/src/sign-in/answer-consent-request.ts +220 -0
  138. package/src/sign-in/answer-login-request.ts +243 -0
  139. package/src/sign-in/build-consent-binding.ts +11 -0
  140. package/src/sign-in/create-sign-in-state.ts +229 -0
  141. package/src/sign-in/pick-consent-choice.ts +27 -0
  142. package/src/sign-in/pick-consent-outcome.ts +14 -0
  143. package/src/sign-in/read-session-id.ts +11 -0
  144. package/src/sign-in/read-stored-client-name.ts +15 -0
  145. package/src/sign-in/read-url-field.ts +12 -0
  146. package/src/sign-in/render-consent-page.ts +57 -0
  147. package/src/sign-in/route-context.ts +25 -0
  148. package/src/sign-in/verify-oauth-query.ts +39 -0
  149. package/src/store/check-cascade-keys.ts +36 -0
  150. package/src/store/check-foreign-keys.ts +20 -0
  151. package/src/store/check-table-names.ts +13 -0
  152. package/src/store/check-user-columns.ts +22 -0
  153. package/src/store/create-auth-server.ts +97 -0
  154. package/src/store/create-grant-plugin.ts +68 -0
  155. package/src/store/create-owned-tables.ts +45 -0
  156. package/src/store/open-store.ts +72 -0
  157. package/src/store/read-table-columns.ts +12 -0
  158. package/src/store/remove-grant-rows.ts +27 -0
  159. package/src/store/store-schema.ts +61 -0
  160. package/src/test-utils/authorize-test-client.ts +93 -0
  161. package/src/test-utils/build-form-request.ts +12 -0
  162. package/src/test-utils/build-seeder.ts +19 -0
  163. package/src/test-utils/build-stub-authenticator.ts +244 -0
  164. package/src/test-utils/build-stub-clock.ts +21 -0
  165. package/src/test-utils/build-test-requester.ts +5 -0
  166. package/src/test-utils/create-test-database.ts +7 -0
  167. package/src/test-utils/hook-sqlite-statements.ts +17 -0
  168. package/src/test-utils/index.ts +12 -0
  169. package/src/test-utils/open-test-auth.ts +72 -0
  170. package/src/test-utils/parse-passkey-page.ts +25 -0
  171. package/src/test-utils/read-json-record.ts +15 -0
  172. package/src/test-utils/run-sign-in-to-consent.ts +100 -0
  173. package/src/test-utils/seed-client.ts +16 -0
  174. package/src/test-utils/seed-enrollment-token.ts +5 -0
  175. package/src/test-utils/seed-passkey.ts +51 -0
  176. package/src/tokens/answer-error-request.ts +26 -0
  177. package/src/tokens/answer-metadata-request.ts +51 -0
  178. package/src/tokens/answer-revoke-request.ts +47 -0
  179. package/src/tokens/answer-token-request.ts +133 -0
  180. package/src/tokens/build-better-auth-request.ts +23 -0
  181. package/src/tokens/build-oauth-error.ts +7 -0
  182. package/src/tokens/read-error-code.ts +12 -0
  183. package/src/tokens/read-error-description.ts +11 -0
  184. package/src/tokens/record-token-exchange.ts +73 -0
  185. package/src/tokens/remove-token-sessions.ts +32 -0
  186. package/src/types.ts +247 -0
  187. package/src/utils/build-page-response.ts +24 -0
  188. package/src/utils/derive-token-hash.ts +5 -0
  189. package/src/utils/is-allowed-redirect-uri.ts +17 -0
  190. package/src/utils/is-loopback-host.ts +8 -0
  191. package/src/utils/normalize-client-name.ts +20 -0
  192. package/src/utils/parse-approved-by.ts +9 -0
  193. package/src/utils/parse-json-strings.ts +13 -0
  194. package/src/utils/read-body-text.ts +23 -0
  195. package/src/utils/read-form.ts +16 -0
  196. package/src/utils/to-html-text.ts +8 -0
  197. package/src/utils/to-script-json.ts +6 -0
@@ -0,0 +1,229 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { toTagged } from '@zgeoff/std';
3
+ import type { CorrelationID, OAuthClientID } from '../types.ts';
4
+
5
+ interface SignInRequest {
6
+ // The signed authorization query the login page carries: one per request.
7
+ readonly key: string;
8
+ readonly clientID: OAuthClientID;
9
+ readonly clientName: string;
10
+ readonly redirectURI: string;
11
+ }
12
+
13
+ export interface PendingSignIn extends SignInRequest {
14
+ // Random, minted with the signIn and never taken from the request, so
15
+ // the security events of one authorization can be matched up.
16
+ readonly correlationID: CorrelationID;
17
+ failures: number;
18
+ readonly expiresAt: number;
19
+
20
+ // The one WebAuthn challenge this request's login page holds, if any.
21
+ challenge: { readonly value: string; readonly expiresAt: number } | null;
22
+ }
23
+
24
+ export type TakenChallenge =
25
+ | { readonly kind: 'taken'; readonly challenge: string }
26
+ | { readonly kind: 'expired' }
27
+ | { readonly kind: 'missing' };
28
+
29
+ // At most this many signIns wait at once across every client, and each
30
+ // client holds at most this many. Across every client, at most this many
31
+ // signIns start per minute.
32
+ const MAX_PENDING = 16;
33
+ const MAX_PENDING_PER_CLIENT = 3;
34
+ const MAX_STARTS_PER_MINUTE = 10;
35
+ const MAX_FAILURES = 5;
36
+ const MINUTE_MS = 60_000;
37
+
38
+ // How long a login page's challenge stays valid, unless its request
39
+ // expires sooner.
40
+ const CHALLENGE_MS = 5 * MINUTE_MS;
41
+
42
+ interface ApprovedSignIn {
43
+ readonly binding: string;
44
+ readonly correlationID: CorrelationID;
45
+ readonly expiresAt: number;
46
+ }
47
+
48
+ export interface SignInState {
49
+ // Returns null when the last minute already holds its share of starts.
50
+ readonly createPending: (request: SignInRequest) => PendingSignIn | null;
51
+
52
+ readonly findPending: (key: string) => PendingSignIn | null;
53
+
54
+ // A fresh random challenge for the request's login page, replacing any
55
+ // earlier one, or null when the request no longer waits.
56
+ readonly mintChallenge: (key: string) => string | null;
57
+
58
+ // Takes the request's challenge, so it verifies at most one assertion.
59
+ readonly claimChallenge: (key: string) => TakenChallenge;
60
+
61
+ // A failed sign-in counts against the request; the last allowed failure
62
+ // drops it.
63
+ readonly recordFailure: (key: string) => 'retry' | 'locked';
64
+
65
+ readonly removePending: (key: string) => void;
66
+
67
+ // Drops every sign-in a removed client started.
68
+ readonly removeClient: (clientID: OAuthClientID) => void;
69
+
70
+ readonly recordApproved: (sessionID: string, approved: Omit<ApprovedSignIn, 'expiresAt'>) => void;
71
+
72
+ // What an owner session approved, or null once it expired or went.
73
+ readonly findApproved: (sessionID: string) => ApprovedSignIn | null;
74
+
75
+ readonly removeApproved: (sessionID: string) => void;
76
+ }
77
+
78
+ export function createSignInState(pendingMs: number, now: () => number): SignInState {
79
+ const pending = new Map<string, PendingSignIn>();
80
+
81
+ // Owner session id to the binding of the request its sign-in approved.
82
+ const approved = new Map<string, ApprovedSignIn>();
83
+
84
+ // Sign-in start times within the last minute, oldest first.
85
+ let startedAt: readonly number[] = [];
86
+
87
+ const dropExpired = (at: number): void => {
88
+ for (const [key, signIn] of pending) {
89
+ if (signIn.expiresAt <= at) {
90
+ pending.delete(key);
91
+ }
92
+ }
93
+
94
+ for (const [sessionID, request] of approved) {
95
+ if (request.expiresAt <= at) {
96
+ approved.delete(sessionID);
97
+ }
98
+ }
99
+ };
100
+
101
+ const findPending = (key: string): PendingSignIn | null => {
102
+ dropExpired(now());
103
+
104
+ return pending.get(key) ?? null;
105
+ };
106
+
107
+ return {
108
+ createPending: (request) => {
109
+ const current = now();
110
+
111
+ dropExpired(current);
112
+
113
+ startedAt = startedAt.filter((at) => current - at < MINUTE_MS);
114
+
115
+ if (startedAt.length >= MAX_STARTS_PER_MINUTE) {
116
+ return null;
117
+ }
118
+
119
+ const own = [...pending].filter(([, signIn]) => signIn.clientID === request.clientID);
120
+ const [ownOldest] = own;
121
+
122
+ // a new signIn drops the oldest rather than being refused, so no client can
123
+ // hold the owner's signIns hostage.
124
+ if (own.length >= MAX_PENDING_PER_CLIENT && ownOldest !== undefined) {
125
+ pending.delete(ownOldest[0]);
126
+ }
127
+
128
+ const oldest = pending.keys().next();
129
+
130
+ if (pending.size >= MAX_PENDING && oldest.done !== true) {
131
+ pending.delete(oldest.value);
132
+ }
133
+
134
+ const signIn: PendingSignIn = {
135
+ ...request,
136
+ correlationID: toTagged<CorrelationID>(crypto.randomUUID()),
137
+ failures: 0,
138
+ expiresAt: current + pendingMs,
139
+ challenge: null,
140
+ };
141
+
142
+ pending.set(signIn.key, signIn);
143
+
144
+ startedAt = [...startedAt, current];
145
+
146
+ return signIn;
147
+ },
148
+
149
+ findPending,
150
+
151
+ mintChallenge: (key) => {
152
+ const signIn = findPending(key);
153
+
154
+ if (signIn === null) {
155
+ return null;
156
+ }
157
+
158
+ const value = randomBytes(32).toString('base64url');
159
+
160
+ signIn.challenge = {
161
+ value,
162
+ expiresAt: Math.min(now() + CHALLENGE_MS, signIn.expiresAt),
163
+ };
164
+
165
+ return value;
166
+ },
167
+
168
+ claimChallenge: (key) => {
169
+ const signIn = findPending(key);
170
+ const challenge = signIn?.challenge ?? null;
171
+
172
+ if (signIn === null || challenge === null) {
173
+ return { kind: 'missing' };
174
+ }
175
+
176
+ signIn.challenge = null;
177
+
178
+ if (challenge.expiresAt <= now()) {
179
+ return { kind: 'expired' };
180
+ }
181
+
182
+ return { kind: 'taken', challenge: challenge.value };
183
+ },
184
+
185
+ recordFailure: (key) => {
186
+ const signIn = findPending(key);
187
+
188
+ if (signIn === null) {
189
+ return 'locked';
190
+ }
191
+
192
+ signIn.failures += 1;
193
+
194
+ if (signIn.failures >= MAX_FAILURES) {
195
+ pending.delete(key);
196
+
197
+ return 'locked';
198
+ }
199
+
200
+ return 'retry';
201
+ },
202
+
203
+ removePending: (key) => {
204
+ pending.delete(key);
205
+ },
206
+
207
+ removeClient: (clientID) => {
208
+ for (const [key, signIn] of pending) {
209
+ if (signIn.clientID === clientID) {
210
+ pending.delete(key);
211
+ }
212
+ }
213
+ },
214
+
215
+ recordApproved: (sessionID, request) => {
216
+ approved.set(sessionID, { ...request, expiresAt: now() + pendingMs });
217
+ },
218
+
219
+ findApproved: (sessionID) => {
220
+ dropExpired(now());
221
+
222
+ return approved.get(sessionID) ?? null;
223
+ },
224
+
225
+ removeApproved: (sessionID) => {
226
+ approved.delete(sessionID);
227
+ },
228
+ };
229
+ }
@@ -0,0 +1,27 @@
1
+ // `scope` is what better-auth is asked to grant, null when the choice denies.
2
+ // `noneTicked` is an allow sent with no scope ticked, which denies.
3
+ interface ConsentChoice {
4
+ readonly accept: boolean;
5
+ readonly scopes: readonly string[];
6
+ readonly scope: string | null;
7
+ readonly noneTicked: boolean;
8
+ }
9
+
10
+ // The owner's answer on the consent form, from the scopes it ticked and its
11
+ // decision. A ticked value that is no scope of the server counts for nothing.
12
+ export function pickConsentChoice(
13
+ known: readonly string[],
14
+ ticked: readonly string[],
15
+ decision: string | null,
16
+ ): ConsentChoice {
17
+ const scopes = known.filter((scope) => ticked.includes(scope));
18
+ const allow = decision === 'approve';
19
+ const accept = allow && scopes.length > 0;
20
+
21
+ return {
22
+ accept,
23
+ scopes: accept ? scopes : [],
24
+ scope: accept ? [...scopes, 'offline_access'].join(' ') : null,
25
+ noneTicked: allow && !accept,
26
+ };
27
+ }
@@ -0,0 +1,14 @@
1
+ import type { SecurityEvent } from '../types.ts';
2
+
3
+ type ConsentOutcome = Pick<SecurityEvent, 'kind' | 'outcome' | 'reason'>;
4
+
5
+ // `noneTicked` is an allow sent with no scope ticked, which denies.
6
+ export function pickConsentOutcome(issuedCode: boolean, noneTicked: boolean): ConsentOutcome {
7
+ if (issuedCode) {
8
+ return { kind: 'consent', outcome: 'allowed' };
9
+ }
10
+
11
+ return noneTicked
12
+ ? { kind: 'consent', outcome: 'denied', reason: 'none_ticked' }
13
+ : { kind: 'consent', outcome: 'denied' };
14
+ }
@@ -0,0 +1,11 @@
1
+ import type { Store } from '../store/open-store.ts';
2
+
3
+ export async function readSessionID(store: Store, cookie: string | null): Promise<string | null> {
4
+ if (cookie === null || cookie === '') {
5
+ return null;
6
+ }
7
+
8
+ const found = await store.auth.api.getSession({ headers: new Headers({ cookie }) });
9
+
10
+ return found === null ? null : found.session.id;
11
+ }
@@ -0,0 +1,15 @@
1
+ import type { Store } from '../store/open-store.ts';
2
+ import type { OAuthClientID } from '../types.ts';
3
+ import { normalizeClientName } from '../utils/normalize-client-name.ts';
4
+
5
+ // The name the owner gave the client, cleaned for a page or an event, or the
6
+ // client's ID when the core holds no such client.
7
+ export async function readStoredClientName(store: Store, clientID: OAuthClientID): Promise<string> {
8
+ const row = await store.db
9
+ .selectFrom('oauthClient')
10
+ .select('name')
11
+ .where('clientId', '=', clientID)
12
+ .executeTakeFirst();
13
+
14
+ return normalizeClientName(row?.name, clientID);
15
+ }
@@ -0,0 +1,12 @@
1
+ import { isRecord } from '@zgeoff/std';
2
+
3
+ // The URL better-auth tells the browser to go to next, or null.
4
+ export function readURLField(body: unknown): string | null {
5
+ if (!isRecord(body)) {
6
+ return null;
7
+ }
8
+
9
+ const next = body['url'] ?? body['redirect_uri'];
10
+
11
+ return typeof next === 'string' ? next : null;
12
+ }
@@ -0,0 +1,57 @@
1
+ import { toHTMLText } from '../utils/to-html-text.ts';
2
+
3
+ interface ConsentPageView {
4
+ readonly consentPath: string;
5
+
6
+ // The signed authorization query the page posts back.
7
+ readonly oauthQuery: string;
8
+ readonly clientName: string;
9
+ readonly redirectURI: string;
10
+ readonly scopes: readonly string[];
11
+
12
+ // The app's own form fields, as HTML it has escaped.
13
+ readonly extraFields: string;
14
+ readonly error: string | null;
15
+ }
16
+
17
+ export function renderConsentPage(view: ConsentPageView): string {
18
+ const scopeRows = view.scopes
19
+ .map(
20
+ (scope) =>
21
+ `<label><input type="checkbox" name="scope" value="${toHTMLText(scope)}"> ${toHTMLText(scope)}</label>`,
22
+ )
23
+ .join('\n');
24
+
25
+ const error = view.error === null ? '' : `<p class="error">${toHTMLText(view.error)}</p>`;
26
+
27
+ return `<!doctype html>
28
+ <html lang="en">
29
+ <head>
30
+ <meta charset="utf-8">
31
+ <meta name="viewport" content="width=device-width, initial-scale=1">
32
+ <title>Choose what to allow</title>
33
+ <style>
34
+ body { font-family: system-ui, sans-serif; max-width: 32rem; margin: 3rem auto; padding: 0 1rem; line-height: 1.5; }
35
+ label { display: block; margin: 0.25rem 0; }
36
+ .error { color: #b00020; }
37
+ code { word-break: break-all; }
38
+ button { font: inherit; margin-right: 0.5rem; }
39
+ </style>
40
+ </head>
41
+ <body>
42
+ <h1>Choose what to allow</h1>
43
+ <p><strong>${toHTMLText(view.clientName)}</strong> returns to <code>${toHTMLText(view.redirectURI)}</code> with the access you allow here.</p>
44
+ ${error}
45
+ <form method="post" action="${toHTMLText(view.consentPath)}">
46
+ <input type="hidden" name="oauth_query" value="${toHTMLText(view.oauthQuery)}">
47
+ <fieldset>
48
+ <legend>Allow it to use these scopes</legend>
49
+ ${scopeRows}
50
+ </fieldset>
51
+ ${view.extraFields}
52
+ <p><button type="submit" name="decision" value="approve">Allow</button><button type="submit" name="decision" value="deny">Deny</button></p>
53
+ </form>
54
+ </body>
55
+ </html>
56
+ `;
57
+ }
@@ -0,0 +1,25 @@
1
+ import type { EnrollmentState } from '../passkeys/create-enrollment-state.ts';
2
+ import type { Store } from '../store/open-store.ts';
3
+ import type { Clock, GrantLimits, MCPAuthPaths, SecuritySink } from '../types.ts';
4
+ import type { SignInState } from './create-sign-in-state.ts';
5
+
6
+ // What every route reads: the server's identity, the sign-ins waiting for the
7
+ // owner, and the passkey enrollments in progress.
8
+ export interface RouteContext {
9
+ readonly store: Store;
10
+ readonly origin: string;
11
+
12
+ // The one resource every token is bound to.
13
+ readonly resource: string;
14
+ readonly paths: MCPAuthPaths;
15
+ readonly productName: string;
16
+ readonly scopes: readonly string[];
17
+ readonly clock: Clock;
18
+ readonly security: SecuritySink;
19
+ readonly signIns: SignInState;
20
+ readonly enrollments: EnrollmentState;
21
+ readonly consentFields: Pick<
22
+ GrantLimits<unknown>,
23
+ 'renderConsentFields' | 'parseConsentFields'
24
+ > | null;
25
+ }
@@ -0,0 +1,39 @@
1
+ import { constantTimeEqual, makeSignature } from 'better-auth/crypto';
2
+
3
+ export async function verifyOAuthQuery(
4
+ oauthQuery: string,
5
+ secret: string,
6
+ now: number,
7
+ ): Promise<boolean> {
8
+ const params = new URLSearchParams(oauthQuery);
9
+
10
+ const signatures = params.getAll('sig');
11
+ const [signature] = signatures;
12
+ const expiresAt = Number(params.get('exp')) * 1000;
13
+
14
+ if (signatures.length !== 1 || signature === undefined || signature === '') {
15
+ return false;
16
+ }
17
+
18
+ params.delete('sig');
19
+
20
+ // Ordered by name, then by value, comparing code units as better-auth does
21
+ // when it signs; the NUL separator sorts a name before any longer name it
22
+ // prefixes.
23
+ const canonical = new URLSearchParams(
24
+ [...params].toSorted(([keyA, valueA], [keyB, valueB]) => {
25
+ const pairA = `${keyA}\u0000${valueA}`;
26
+ const pairB = `${keyB}\u0000${valueB}`;
27
+
28
+ if (pairA === pairB) {
29
+ return 0;
30
+ }
31
+
32
+ return pairA < pairB ? -1 : 1;
33
+ }),
34
+ );
35
+
36
+ const expected = await makeSignature(canonical.toString(), secret);
37
+
38
+ return constantTimeEqual(signature, expected) && Number.isFinite(expiresAt) && expiresAt >= now;
39
+ }
@@ -0,0 +1,36 @@
1
+ import type { Database } from 'bun:sqlite';
2
+ import { z } from 'zod';
3
+ import { MCPAuthError } from '../mcp-auth-error.ts';
4
+
5
+ const CASCADING_TABLES = ['oauthAccessToken', 'oauthRefreshToken', 'session'] as const;
6
+
7
+ const KeyRowSchema = z.object({
8
+ table: z.string(),
9
+ from: z.string(),
10
+ to: z.string(),
11
+ on_delete: z.string(),
12
+ });
13
+
14
+ export function checkCascadeKeys(sqlite: Database): void {
15
+ 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));
20
+
21
+ const isCascading = keys.some(
22
+ (key) =>
23
+ key.table === 'user' &&
24
+ key.from === 'userId' &&
25
+ key.to === 'id' &&
26
+ key.on_delete === 'CASCADE',
27
+ );
28
+
29
+ if (!isCascading) {
30
+ throw new MCPAuthError(
31
+ 'invalid-setup',
32
+ `${table}.userId must reference user(id) on delete cascade`,
33
+ );
34
+ }
35
+ }
36
+ }
@@ -0,0 +1,20 @@
1
+ import type { Database } from 'bun:sqlite';
2
+ import { z } from 'zod';
3
+ import { MCPAuthError } from '../mcp-auth-error.ts';
4
+
5
+ const PragmaRowSchema = z.object({ foreign_keys: z.number() });
6
+
7
+ // A pragma inside a transaction does nothing, so the core reads the setting
8
+ // back instead of trusting the statement.
9
+ export function checkForeignKeys(sqlite: Database): void {
10
+ sqlite.run('PRAGMA foreign_keys = ON');
11
+
12
+ const row = PragmaRowSchema.parse(sqlite.query('PRAGMA foreign_keys').get());
13
+
14
+ if (row.foreign_keys === 0) {
15
+ throw new MCPAuthError(
16
+ 'invalid-setup',
17
+ 'foreign keys are off on the connection, so a revoke would not end the tokens of a grant',
18
+ );
19
+ }
20
+ }
@@ -0,0 +1,13 @@
1
+ import { MCPAuthError } from '../mcp-auth-error.ts';
2
+ import type { MCPAuthTables } from '../types.ts';
3
+
4
+ const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/u;
5
+
6
+ // The names go into DDL statements, so each is a plain identifier.
7
+ export function checkTableNames(tables: MCPAuthTables): void {
8
+ for (const name of [tables.passkey, tables.enrollmentToken]) {
9
+ if (!IDENTIFIER.test(name)) {
10
+ throw new MCPAuthError('invalid-setup', `${name} is not a plain table name`);
11
+ }
12
+ }
13
+ }
@@ -0,0 +1,22 @@
1
+ import type { Database } from 'bun:sqlite';
2
+ import { MCPAuthError } from '../mcp-auth-error.ts';
3
+ import { readTableColumns } from './read-table-columns.ts';
4
+
5
+ // A user table from before the grant columns cannot take them as new required
6
+ // columns, so the app's migration comes first.
7
+ export function checkUserColumns(sqlite: Database): void {
8
+ const columns = readTableColumns(sqlite, 'user');
9
+
10
+ if (columns.length === 0) {
11
+ return;
12
+ }
13
+
14
+ for (const required of ['clientId', 'approvedBy']) {
15
+ if (!columns.includes(required)) {
16
+ throw new MCPAuthError(
17
+ 'invalid-setup',
18
+ `the user table lacks the ${required} column; run the grant migration first`,
19
+ );
20
+ }
21
+ }
22
+ }
@@ -0,0 +1,97 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { mcp } from '@better-auth/mcp';
3
+ import { oauthProvider } from '@better-auth/oauth-provider';
4
+ import type { OAuthOptions, Scope as ProviderScope } from '@better-auth/oauth-provider';
5
+ import { betterAuth } from 'better-auth';
6
+ import type { BetterAuthPlugin } from 'better-auth';
7
+ import type { Kysely } from 'kysely';
8
+ import type { MCPAuthPaths } from '../types.ts';
9
+ import { deriveTokenHash } from '../utils/derive-token-hash.ts';
10
+ import { createGrantPlugin } from './create-grant-plugin.ts';
11
+ import type { StoreSchema } from './store-schema.ts';
12
+
13
+ export const ACCESS_TOKEN_SECONDS = 15 * 60;
14
+ export const REFRESH_TOKEN_SECONDS = 30 * 24 * 60 * 60;
15
+ export const CODE_SECONDS = 10 * 60;
16
+ export const SESSION_SECONDS = 30 * 60;
17
+
18
+ // A host with no origin, such as an admin command, builds a server that only
19
+ // shares the schema.
20
+ const SCHEMA_ORIGIN = 'http://127.0.0.1';
21
+
22
+ interface AuthServerOptions {
23
+ readonly db: Kysely<StoreSchema>;
24
+ readonly origin: string | null;
25
+ readonly paths: MCPAuthPaths;
26
+ readonly scopes: readonly string[];
27
+ }
28
+
29
+ export function createAuthServer(options: AuthServerOptions) {
30
+ // better-auth reads these when it builds its context; an empty endpoint
31
+ // turns its telemetry into a no-op.
32
+ process.env['BETTER_AUTH_TELEMETRY'] = '0';
33
+ process.env['BETTER_AUTH_TELEMETRY_ENDPOINT'] = '';
34
+
35
+ const origin = options.origin ?? SCHEMA_ORIGIN;
36
+
37
+ const providerOptions: OAuthOptions<ProviderScope[]> = {
38
+ loginPage: options.paths.browser.login,
39
+ consentPage: options.paths.browser.consent,
40
+ scopes: [...options.scopes, 'offline_access'],
41
+ disableJwtPlugin: true,
42
+ allowDynamicClientRegistration: false,
43
+ grantTypes: ['authorization_code', 'refresh_token'],
44
+
45
+ // The server holds one resource, so every client may request it.
46
+ enforcePerClientResources: false,
47
+ accessTokenExpiresIn: ACCESS_TOKEN_SECONDS,
48
+ refreshTokenExpiresIn: REFRESH_TOKEN_SECONDS,
49
+ codeExpiresIn: CODE_SECONDS,
50
+ refreshTokenReuseInterval: 0,
51
+ storeTokens: { hash: (token: string) => Promise.resolve(deriveTokenHash(token)) },
52
+ };
53
+
54
+ const provider =
55
+ options.origin === null
56
+ ? oauthProvider(providerOptions)
57
+ : mcp({ ...providerOptions, resource: `${origin}${options.paths.machine.mcp}` });
58
+
59
+ return betterAuth({
60
+ baseURL: origin,
61
+ basePath: '/',
62
+
63
+ // Drawn at each open, so a restart ends the sign-ins in progress.
64
+ secret: randomBytes(32).toString('base64url'),
65
+ database: { db: options.db, type: 'sqlite' },
66
+ telemetry: { enabled: false },
67
+ logger: { disabled: true },
68
+
69
+ // better-auth counts by client address, which a proxy hides, so all
70
+ // callers would share one bucket. The core limits sign-ins itself, and a
71
+ // guess fails on 32 random characters and PKCE.
72
+ rateLimit: { enabled: false },
73
+ advanced: { database: { validateSchema: false } },
74
+ trustedOrigins: [origin],
75
+ onAPIError: { errorURL: options.paths.browser.error },
76
+
77
+ // A session carries one sign-in from the login page to the code exchange,
78
+ // which detaches every token from it.
79
+ session: { expiresIn: SESSION_SECONDS, disableSessionRefresh: true },
80
+ user: {
81
+ additionalFields: {
82
+ clientId: { type: 'string', required: true, input: false },
83
+ scopes: { type: 'string', required: false, input: false },
84
+ approvedBy: { type: 'string', required: true, input: false },
85
+ limits: { type: 'string', required: false, input: false },
86
+ lastUsedAt: { type: 'date', required: false, input: false },
87
+ },
88
+ },
89
+
90
+ // The provider's endpoint types do not satisfy the plugin type under
91
+ // exactOptionalPropertyTypes.
92
+ // oxlint-disable-next-line typescript/consistent-type-assertions -- better-auth plugin type under exactOptionalPropertyTypes
93
+ plugins: [provider as BetterAuthPlugin, createGrantPlugin()],
94
+ });
95
+ }
96
+
97
+ export type AuthServer = ReturnType<typeof createAuthServer>;