@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,133 @@
1
+ import { toTagged } from '@zgeoff/std';
2
+ import type { OAuthClientID, Requester } from '../types.ts';
3
+ import { buildPageResponse } from '../utils/build-page-response.ts';
4
+ import { readStoredClientName } from './read-stored-client-name.ts';
5
+ import type { RouteContext } from './route-context.ts';
6
+
7
+ export async function answerAuthorizeRequest(
8
+ ctx: RouteContext,
9
+ request: Request,
10
+ requester: Requester,
11
+ ): Promise<Response> {
12
+ const url = new URL(request.url);
13
+ const params = new URLSearchParams(url.searchParams);
14
+
15
+ // Every sign-in asks for a fresh passkey login and the consent page, whatever
16
+ // session or consent the browser kept.
17
+ params.set('prompt', 'login consent');
18
+
19
+ const asked = (params.get('scope') ?? '').split(' ').filter((item) => item !== '');
20
+
21
+ params.set(
22
+ 'scope',
23
+ [...new Set([...(asked.length === 0 ? ctx.scopes : asked), 'offline_access'])].join(' '),
24
+ );
25
+
26
+ if (!params.has('resource')) {
27
+ params.set('resource', ctx.resource);
28
+ }
29
+
30
+ const response = await ctx.store.auth.handler(
31
+ new Request(`${ctx.origin}/oauth2/authorize?${params.toString()}`, {
32
+ headers: { accept: 'text/html' },
33
+ }),
34
+ );
35
+
36
+ const location = response.headers.get('location');
37
+ const target = location === null ? null : new URL(location, ctx.origin);
38
+
39
+ if (
40
+ target === null ||
41
+ target.origin !== ctx.origin ||
42
+ target.pathname !== ctx.paths.browser.login
43
+ ) {
44
+ await recordInvalidRequest(ctx, { url, requester, target });
45
+
46
+ return response;
47
+ }
48
+
49
+ const clientID = toTagged<OAuthClientID>(target.searchParams.get('client_id') ?? '');
50
+ const redirectURI = target.searchParams.get('redirect_uri') ?? '';
51
+
52
+ const clientName = await readStoredClientName(ctx.store, clientID);
53
+
54
+ const context = { path: url.pathname, requester, client: { id: clientID, name: clientName } };
55
+
56
+ const signIn = ctx.signIns.createPending({
57
+ key: target.search.slice(1),
58
+ clientID,
59
+ clientName,
60
+ redirectURI,
61
+ });
62
+
63
+ if (signIn === null) {
64
+ ctx.security.record({
65
+ kind: 'authorize_started',
66
+ outcome: 'rejected',
67
+ reason: 'rate_limited',
68
+ ...context,
69
+ });
70
+
71
+ return buildPageResponse(429, {
72
+ message: 'Too many sign-ins started in the last minute. Wait a minute, then start again.',
73
+ });
74
+ }
75
+
76
+ ctx.security.record({
77
+ kind: 'authorize_started',
78
+ outcome: 'accepted',
79
+ ...context,
80
+ correlationID: signIn.correlationID,
81
+ });
82
+
83
+ return response;
84
+ }
85
+
86
+ interface InvalidRequest {
87
+ readonly url: URL;
88
+ readonly requester: Requester;
89
+ readonly target: URL | null;
90
+ }
91
+
92
+ // The better-auth error codes an `authorize_invalid` event may hold; any other
93
+ // code becomes `other`.
94
+ const AUTHORIZE_ERRORS: ReadonlySet<string> = new Set([
95
+ 'invalid_client',
96
+ 'client_disabled',
97
+ 'invalid_redirect',
98
+ 'unauthorized_client',
99
+ 'unsupported_response_type',
100
+ 'invalid_request',
101
+ 'invalid_scope',
102
+ 'invalid_target',
103
+ ]);
104
+
105
+ // The event holds the client's id and name only for a client the core holds.
106
+ async function recordInvalidRequest(ctx: RouteContext, invalid: InvalidRequest): Promise<void> {
107
+ const code = invalid.target?.searchParams.get('error') ?? null;
108
+ const clientParam = invalid.url.searchParams.get('client_id');
109
+ const clientID = clientParam === null ? null : toTagged<OAuthClientID>(clientParam);
110
+
111
+ const stored =
112
+ clientID === null
113
+ ? null
114
+ : await ctx.store.db
115
+ .selectFrom('oauthClient')
116
+ .select('clientId')
117
+ .where('clientId', '=', clientID)
118
+ .executeTakeFirst();
119
+
120
+ const name =
121
+ clientID === null || stored === null || stored === undefined
122
+ ? null
123
+ : await readStoredClientName(ctx.store, clientID);
124
+
125
+ ctx.security.record({
126
+ kind: 'authorize_invalid',
127
+ outcome: 'rejected',
128
+ reason: code !== null && AUTHORIZE_ERRORS.has(code) ? code : 'other',
129
+ path: invalid.url.pathname,
130
+ requester: invalid.requester,
131
+ ...(clientID === null || name === null ? {} : { client: { id: clientID, name } }),
132
+ });
133
+ }
@@ -0,0 +1,220 @@
1
+ import { toTagged } from '@zgeoff/std';
2
+ import { CODE_SECONDS } from '../store/create-auth-server.ts';
3
+ import type { OAuthClientID, Requester } from '../types.ts';
4
+ import { buildPageResponse } from '../utils/build-page-response.ts';
5
+ import { readForm } from '../utils/read-form.ts';
6
+ import { buildConsentBinding } from './build-consent-binding.ts';
7
+ import { pickConsentChoice } from './pick-consent-choice.ts';
8
+ import { pickConsentOutcome } from './pick-consent-outcome.ts';
9
+ import { readSessionID } from './read-session-id.ts';
10
+ import { readStoredClientName } from './read-stored-client-name.ts';
11
+ import { readURLField } from './read-url-field.ts';
12
+ import { renderConsentPage } from './render-consent-page.ts';
13
+ import type { RouteContext } from './route-context.ts';
14
+ import { verifyOAuthQuery } from './verify-oauth-query.ts';
15
+
16
+ const EXPIRED_MESSAGE = 'This sign-in expired or was already used. Start again from the client.';
17
+
18
+ export async function answerConsentRequest(
19
+ ctx: RouteContext,
20
+ request: Request,
21
+ requester: Requester,
22
+ ): Promise<Response> {
23
+ const url = new URL(request.url);
24
+
25
+ const isPost = request.method === 'POST';
26
+ const form = isPost ? await readForm(request) : new URLSearchParams();
27
+ const oauthQuery = isPost ? (form.get('oauth_query') ?? '') : url.search.slice(1);
28
+ const cookie = request.headers.get('cookie');
29
+
30
+ const verified = await verifyConsentRequest(ctx, oauthQuery, cookie);
31
+
32
+ if (verified === null) {
33
+ return buildPageResponse(400, { message: EXPIRED_MESSAGE });
34
+ }
35
+
36
+ const params = new URLSearchParams(oauthQuery);
37
+
38
+ const redirectURI = params.get('redirect_uri') ?? '';
39
+ const clientID = toTagged<OAuthClientID>(params.get('client_id') ?? '');
40
+
41
+ const clientName = await readStoredClientName(ctx.store, clientID);
42
+
43
+ const requested = (params.get('scope') ?? '').split(' ');
44
+ const offered = ctx.scopes.filter((scope) => requested.includes(scope));
45
+
46
+ // The form's answer redirects to the client, which the page's form-action
47
+ // policy has to allow.
48
+ const formTargets = URL.canParse(redirectURI) ? [new URL(redirectURI).origin] : [];
49
+
50
+ const renderPage = (status: number, error: string | null) =>
51
+ buildPageResponse(
52
+ status,
53
+ {
54
+ page: renderConsentPage({
55
+ consentPath: ctx.paths.browser.consent,
56
+ oauthQuery,
57
+ clientName,
58
+ redirectURI,
59
+ scopes: offered,
60
+ extraFields:
61
+ ctx.consentFields?.renderConsentFields({ clientID, clientName, scopes: offered }) ?? '',
62
+ error,
63
+ }),
64
+ },
65
+ formTargets,
66
+ );
67
+
68
+ if (!isPost) {
69
+ return renderPage(200, null);
70
+ }
71
+
72
+ const choice = pickConsentChoice(offered, form.getAll('scope'), form.get('decision'));
73
+ const parsed = choice.accept ? ctx.consentFields?.parseConsentFields(form) : undefined;
74
+
75
+ if (parsed?.ok === false) {
76
+ return renderPage(400, parsed.error);
77
+ }
78
+
79
+ // Either answer ends the session's binding, so one login approves one
80
+ // request.
81
+ ctx.signIns.removeApproved(verified.sessionID);
82
+
83
+ const limits = parsed === undefined ? null : parsed.limits;
84
+
85
+ if (choice.accept) {
86
+ await writeGrantChoice(ctx, verified.sessionID, {
87
+ scopes: choice.scopes,
88
+ limits: limits === null ? null : JSON.stringify(limits),
89
+ });
90
+ }
91
+
92
+ const consented = await ctx.store.auth.handler(
93
+ new Request(`${ctx.origin}/oauth2/consent`, {
94
+ method: 'POST',
95
+ headers: {
96
+ 'content-type': 'application/json',
97
+ accept: 'application/json',
98
+ origin: ctx.origin,
99
+ ...(cookie === null ? {} : { cookie }),
100
+ },
101
+ body: JSON.stringify({
102
+ accept: choice.accept,
103
+ ...(choice.scope === null ? {} : { scope: choice.scope }),
104
+ oauth_query: oauthQuery,
105
+ }),
106
+ }),
107
+ );
108
+
109
+ const answer: unknown = await consented.json();
110
+
111
+ const next = readURLField(answer);
112
+ const isIssued = consented.ok && next !== null && new URL(next).searchParams.has('code');
113
+
114
+ // The code exchange still needs the session, so it stays until the code
115
+ // expires; an answer that issued no code deletes it now.
116
+ await (isIssued
117
+ ? ctx.store.db
118
+ .updateTable('session')
119
+ .set({ expiresAt: new Date(ctx.clock.now() + CODE_SECONDS * 1000).toISOString() })
120
+ .where('id', '=', verified.sessionID)
121
+ .execute()
122
+ : ctx.store.db.deleteFrom('session').where('id', '=', verified.sessionID).execute());
123
+
124
+ ctx.security.record({
125
+ ...pickConsentOutcome(isIssued, choice.noneTicked),
126
+ path: url.pathname,
127
+ requester,
128
+ client: { id: clientID, name: clientName },
129
+ correlationID: verified.correlationID,
130
+ });
131
+
132
+ if (!consented.ok || next === null) {
133
+ return buildPageResponse(400, {
134
+ message: `${ctx.productName} could not record this choice. Start again from the client.`,
135
+ });
136
+ }
137
+
138
+ const authContext = await ctx.store.auth.$context;
139
+
140
+ const sessionCookie = authContext.authCookies.sessionToken;
141
+ const secure = sessionCookie.attributes.secure === true ? '; Secure' : '';
142
+
143
+ return new Response(null, {
144
+ status: 302,
145
+ headers: {
146
+ location: next,
147
+ 'cache-control': 'no-store',
148
+ 'referrer-policy': 'no-referrer',
149
+ 'set-cookie': `${sessionCookie.name}=; Max-Age=0; Path=/; HttpOnly; SameSite=Lax${secure}`,
150
+ },
151
+ });
152
+ }
153
+
154
+ interface VerifiedConsent {
155
+ readonly sessionID: string;
156
+ readonly correlationID: Parameters<RouteContext['signIns']['recordApproved']>[1]['correlationID'];
157
+ }
158
+
159
+ async function verifyConsentRequest(
160
+ ctx: RouteContext,
161
+ oauthQuery: string,
162
+ cookie: string | null,
163
+ ): Promise<VerifiedConsent | null> {
164
+ const authContext = await ctx.store.auth.$context;
165
+
166
+ if (!(await verifyOAuthQuery(oauthQuery, authContext.secret, ctx.clock.now()))) {
167
+ return null;
168
+ }
169
+
170
+ // A query still asking for a login is one better-auth signed for the login
171
+ // page, which no passkey login carried past.
172
+ const prompt = (new URLSearchParams(oauthQuery).get('prompt') ?? '').split(' ');
173
+
174
+ if (prompt.includes('login')) {
175
+ return null;
176
+ }
177
+
178
+ const sessionID = await readSessionID(ctx.store, cookie);
179
+
180
+ const approved = sessionID === null ? null : ctx.signIns.findApproved(sessionID);
181
+
182
+ if (
183
+ sessionID === null ||
184
+ approved === null ||
185
+ approved.binding !== buildConsentBinding(oauthQuery)
186
+ ) {
187
+ return null;
188
+ }
189
+
190
+ return { sessionID, correlationID: approved.correlationID };
191
+ }
192
+
193
+ interface GrantChoice {
194
+ readonly scopes: readonly string[];
195
+ readonly limits: string | null;
196
+ }
197
+
198
+ // The session belongs to one grant row, which the consent fills in before a
199
+ // code is issued, so no token ever exists for a grant without its scopes.
200
+ async function writeGrantChoice(
201
+ ctx: RouteContext,
202
+ sessionID: string,
203
+ choice: GrantChoice,
204
+ ): Promise<void> {
205
+ const session = await ctx.store.db
206
+ .selectFrom('session')
207
+ .select('userId')
208
+ .where('id', '=', sessionID)
209
+ .executeTakeFirst();
210
+
211
+ if (session === undefined) {
212
+ return;
213
+ }
214
+
215
+ await ctx.store.db
216
+ .updateTable('user')
217
+ .set({ scopes: JSON.stringify(choice.scopes), limits: choice.limits })
218
+ .where('id', '=', session.userId)
219
+ .execute();
220
+ }
@@ -0,0 +1,243 @@
1
+ import { PASSKEY_SCRIPT } from '../passkeys/passkey-script.ts';
2
+ import { readPasskeyRows } from '../passkeys/read-passkey-rows.ts';
3
+ import { renderLoginPage } from '../passkeys/render-login-page.ts';
4
+ import { verifyPasskeyAssertion } from '../passkeys/verify-passkey-assertion.ts';
5
+ import { verifySessionPasskey } from '../passkeys/verify-session-passkey.ts';
6
+ import type { PasskeyID, Requester, SecurityEvent } from '../types.ts';
7
+ import { buildPageResponse } from '../utils/build-page-response.ts';
8
+ import { readForm } from '../utils/read-form.ts';
9
+ import { buildConsentBinding } from './build-consent-binding.ts';
10
+ import type { PendingSignIn } from './create-sign-in-state.ts';
11
+ import { readSessionID } from './read-session-id.ts';
12
+ import { readURLField } from './read-url-field.ts';
13
+ import type { RouteContext } from './route-context.ts';
14
+
15
+ const EXPIRED_MESSAGE = 'This sign-in expired or was already used. Start again from the client.';
16
+
17
+ export async function answerLoginRequest(
18
+ ctx: RouteContext,
19
+ request: Request,
20
+ requester: Requester,
21
+ ): Promise<Response> {
22
+ const url = new URL(request.url);
23
+
24
+ const isPost = request.method === 'POST';
25
+ const form = isPost ? await readForm(request) : new URLSearchParams();
26
+ const oauthQuery = isPost ? (form.get('oauth_query') ?? '') : url.search.slice(1);
27
+ const signIn = ctx.signIns.findPending(oauthQuery);
28
+
29
+ if (signIn === null) {
30
+ if (isPost) {
31
+ ctx.security.record({
32
+ kind: 'owner_auth',
33
+ outcome: 'failed',
34
+ reason: 'expired',
35
+ path: url.pathname,
36
+ requester,
37
+ });
38
+ }
39
+
40
+ return buildPageResponse(400, { message: EXPIRED_MESSAGE });
41
+ }
42
+
43
+ const view = {
44
+ productName: ctx.productName,
45
+ loginPath: ctx.paths.browser.login,
46
+ oauthQuery,
47
+ clientName: signIn.clientName,
48
+ redirectURI: signIn.redirectURI,
49
+ };
50
+
51
+ const isEnrolled = await probePasskey(ctx);
52
+
53
+ if (!isPost) {
54
+ return isEnrolled
55
+ ? buildSignInResponse(ctx, 200, view, null)
56
+ : buildPageResponse(200, { page: renderLoginPage({ ...view, options: null, error: null }) });
57
+ }
58
+
59
+ // Read before the assertion is checked, since a login or the last failure
60
+ // ends the sign-in.
61
+ const context = {
62
+ path: url.pathname,
63
+ requester,
64
+ client: { id: signIn.clientID, name: signIn.clientName },
65
+ correlationID: signIn.correlationID,
66
+ };
67
+
68
+ if (!isEnrolled) {
69
+ ctx.security.record({
70
+ kind: 'owner_auth',
71
+ outcome: 'failed',
72
+ reason: 'not_enrolled',
73
+ ...context,
74
+ });
75
+
76
+ return buildPageResponse(400, {
77
+ page: renderLoginPage({ ...view, options: null, error: null }),
78
+ });
79
+ }
80
+
81
+ // The challenge is taken whether or not the assertion verifies, so it counts
82
+ // once.
83
+ const taken = ctx.signIns.claimChallenge(oauthQuery);
84
+
85
+ const passkeyID =
86
+ taken.kind === 'taken'
87
+ ? await verifyPasskeyAssertion(ctx.store, {
88
+ credential: form.get('credential') ?? '',
89
+ challenge: taken.challenge,
90
+ origin: ctx.origin,
91
+ rpID: new URL(ctx.origin).hostname,
92
+ })
93
+ : null;
94
+
95
+ if (passkeyID === null) {
96
+ const reason = taken.kind === 'expired' ? 'expired' : 'assertion_failed';
97
+
98
+ if (ctx.signIns.recordFailure(oauthQuery) === 'locked') {
99
+ ctx.security.record({ kind: 'owner_auth', outcome: 'failed', reason: 'locked', ...context });
100
+
101
+ return buildPageResponse(400, {
102
+ message: 'Too many failed sign-ins. Start again from the client.',
103
+ });
104
+ }
105
+
106
+ ctx.security.record({ kind: 'owner_auth', outcome: 'failed', reason, ...context });
107
+
108
+ const error =
109
+ reason === 'expired'
110
+ ? 'The sign-in took too long. Try again.'
111
+ : `That passkey did not sign you in. Try again with a passkey enrolled for ${ctx.productName}.`;
112
+
113
+ return buildSignInResponse(ctx, 400, view, error);
114
+ }
115
+
116
+ ctx.signIns.removePending(oauthQuery);
117
+
118
+ return completeLogin(ctx, { oauthQuery, signIn, passkeyID, context });
119
+ }
120
+
121
+ async function probePasskey(ctx: RouteContext): Promise<boolean> {
122
+ const rows = await readPasskeyRows(ctx.store.db, ctx.store.options.tables.passkey, null);
123
+
124
+ return rows.length > 0;
125
+ }
126
+
127
+ interface LoginView {
128
+ readonly productName: string;
129
+ readonly loginPath: string;
130
+ readonly oauthQuery: string;
131
+ readonly clientName: string;
132
+ readonly redirectURI: string;
133
+ }
134
+
135
+ // How long the browser's passkey prompt waits, in milliseconds.
136
+ const PROMPT_TIMEOUT_MS = 120_000;
137
+
138
+ // The sign-in page with a fresh challenge for its request. The options list no
139
+ // credential, so the authenticator offers the passkeys it holds for the RP ID,
140
+ // and they require user verification.
141
+ function buildSignInResponse(
142
+ ctx: RouteContext,
143
+ status: number,
144
+ view: LoginView,
145
+ error: string | null,
146
+ ): Response {
147
+ const challenge = ctx.signIns.mintChallenge(view.oauthQuery);
148
+
149
+ if (challenge === null) {
150
+ return buildPageResponse(400, { message: EXPIRED_MESSAGE });
151
+ }
152
+
153
+ const options = {
154
+ challenge,
155
+ rpId: new URL(ctx.origin).hostname,
156
+ timeout: PROMPT_TIMEOUT_MS,
157
+ userVerification: 'required',
158
+ allowCredentials: [],
159
+ };
160
+
161
+ return buildPageResponse(
162
+ status,
163
+ { page: renderLoginPage({ ...view, options, error }) },
164
+ [],
165
+ [PASSKEY_SCRIPT.policySource],
166
+ );
167
+ }
168
+
169
+ const RESTART_MESSAGE = 'The sign-in could not continue. Start again from the client.';
170
+
171
+ interface LoginCompletion {
172
+ readonly oauthQuery: string;
173
+ readonly signIn: PendingSignIn;
174
+ readonly passkeyID: PasskeyID;
175
+ readonly context: Pick<SecurityEvent, 'path' | 'requester' | 'client' | 'correlationID'>;
176
+ }
177
+
178
+ // The passkey signed in: a grant row and its session come into being, and the
179
+ // authorization resumes at the consent page.
180
+ async function completeLogin(ctx: RouteContext, login: LoginCompletion): Promise<Response> {
181
+ const context = login.context;
182
+
183
+ // Resuming the authorization reads the request better-auth was called with.
184
+ const headers = new Headers({ accept: 'application/json', 'content-type': 'application/json' });
185
+
186
+ const signedIn = await ctx.store.auth.api.signInGrant({
187
+ body: {
188
+ oauth_query: login.oauthQuery,
189
+ clientID: login.signIn.clientID,
190
+ clientName: login.signIn.clientName,
191
+ },
192
+ headers,
193
+ request: new Request(`${ctx.origin}/mcp-auth/sign-in-grant`, { method: 'POST', headers }),
194
+ asResponse: true,
195
+ });
196
+
197
+ const answer: unknown = await signedIn.json();
198
+
199
+ const next = readURLField(answer);
200
+ const setCookies = signedIn.headers.getSetCookie();
201
+ const cookie = setCookies.map((line) => line.split(';')[0]).join('; ');
202
+
203
+ const sessionID = await readSessionID(ctx.store, cookie);
204
+
205
+ if (!signedIn.ok || next === null || sessionID === null) {
206
+ ctx.security.record({ kind: 'owner_auth', outcome: 'failed', ...context });
207
+
208
+ return buildPageResponse(400, { message: RESTART_MESSAGE });
209
+ }
210
+
211
+ const isStillEnrolled = await verifySessionPasskey(ctx.store, {
212
+ sessionID,
213
+ passkeyID: login.passkeyID,
214
+ });
215
+
216
+ if (!isStillEnrolled) {
217
+ ctx.security.record({
218
+ kind: 'owner_auth',
219
+ outcome: 'failed',
220
+ reason: 'not_enrolled',
221
+ ...context,
222
+ });
223
+
224
+ return buildPageResponse(400, {
225
+ message: 'The passkey that signed you in is no longer enrolled. Start again from the client.',
226
+ });
227
+ }
228
+
229
+ ctx.signIns.recordApproved(sessionID, {
230
+ binding: buildConsentBinding(login.oauthQuery),
231
+ correlationID: login.signIn.correlationID,
232
+ });
233
+
234
+ ctx.security.record({ kind: 'owner_auth', outcome: 'succeeded', ...context });
235
+
236
+ const redirect = new Headers({ location: new URL(next, ctx.origin).href });
237
+
238
+ for (const line of setCookies) {
239
+ redirect.append('set-cookie', line);
240
+ }
241
+
242
+ return new Response(null, { status: 302, headers: redirect });
243
+ }
@@ -0,0 +1,11 @@
1
+ export function buildConsentBinding(oauthQuery: string): string {
2
+ const params = new URLSearchParams(oauthQuery);
3
+
4
+ // better-auth signs each page's query afresh, so the binding holds only the
5
+ // fields that stay the same from the login page to the consent page.
6
+ return JSON.stringify(
7
+ ['client_id', 'redirect_uri', 'scope', 'resource', 'state', 'code_challenge'].map(
8
+ (name) => params.get(name) ?? '',
9
+ ),
10
+ );
11
+ }