@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,59 @@
1
+ import { toHTMLText } from '../utils/to-html-text.ts';
2
+ import { toScriptJSON } from '../utils/to-script-json.ts';
3
+ import { PASSKEY_SCRIPT } from './passkey-script.ts';
4
+
5
+ interface LoginPageView {
6
+ readonly productName: string;
7
+ readonly loginPath: string;
8
+
9
+ // The signed authorization query the page posts back.
10
+ readonly oauthQuery: string;
11
+ readonly clientName: string;
12
+ readonly redirectURI: string;
13
+
14
+ // The WebAuthn request options for this page's challenge, or null when
15
+ // no passkey is enrolled, so there is nothing to sign in with.
16
+ readonly options: unknown;
17
+ readonly error: string | null;
18
+ }
19
+
20
+ export function renderLoginPage(view: LoginPageView): string {
21
+ const product = toHTMLText(view.productName);
22
+ const error = view.error === null ? '' : `<p class="error">${toHTMLText(view.error)}</p>`;
23
+
24
+ const signIn =
25
+ view.options === null
26
+ ? `<p class="error">No passkey is enrolled, so nobody can sign in. On the host that runs ${product}, make an enrollment token with its passkeys command, then follow what it prints.</p>`
27
+ : `<script type="application/json" id="mcp-auth-passkey">${toScriptJSON({ mode: 'get', options: view.options })}</script>
28
+ <form method="post" action="${toHTMLText(view.loginPath)}" id="mcp-auth-passkey-form">
29
+ <input type="hidden" name="oauth_query" value="${toHTMLText(view.oauthQuery)}">
30
+ <input type="hidden" name="credential" value="">
31
+ <button type="button" id="mcp-auth-passkey-start" autofocus>Sign in with a passkey</button>
32
+ </form>
33
+ <p id="mcp-auth-passkey-status" class="error" role="status"></p>
34
+ <script>${PASSKEY_SCRIPT.source}</script>`;
35
+
36
+ return `<!doctype html>
37
+ <html lang="en">
38
+ <head>
39
+ <meta charset="utf-8">
40
+ <meta name="viewport" content="width=device-width, initial-scale=1">
41
+ <title>Sign in to ${product}</title>
42
+ <style>
43
+ body { font-family: system-ui, sans-serif; max-width: 32rem; margin: 3rem auto; padding: 0 1rem; line-height: 1.5; }
44
+ .error { color: #b00020; }
45
+ code { word-break: break-all; }
46
+ button { font: inherit; }
47
+ </style>
48
+ </head>
49
+ <body>
50
+ <h1>Sign in to ${product}</h1>
51
+ <p><strong>${toHTMLText(view.clientName)}</strong> wants access to your ${product} data.</p>
52
+ <p>After approval it returns to <code>${toHTMLText(view.redirectURI)}</code>.</p>
53
+ <p>Sign in with your passkey. You choose what to allow on the next page.</p>
54
+ ${error}
55
+ ${signIn}
56
+ </body>
57
+ </html>
58
+ `;
59
+ }
@@ -0,0 +1,24 @@
1
+ import { sql } from 'kysely';
2
+ import type { Store } from '../store/open-store.ts';
3
+ import type { PasskeyID } from '../types.ts';
4
+
5
+ interface PasskeyUse {
6
+ readonly id: PasskeyID;
7
+
8
+ // The counter the verification read, which the passkey must still hold, so
9
+ // a passkey removed during the verification, or a concurrent assertion that
10
+ // stored a newer counter, makes this use fail.
11
+ readonly counter: number;
12
+ readonly newCounter: number;
13
+ }
14
+
15
+ export async function updatePasskeyUse(store: Store, use: PasskeyUse): Promise<boolean> {
16
+ const now = new Date(store.options.clock.now()).toISOString();
17
+
18
+ const stored =
19
+ await sql`update ${sql.table(store.options.tables.passkey)} set counter = ${use.newCounter}, last_used_at = ${now} where id = ${use.id} and counter = ${use.counter}`.execute(
20
+ store.db,
21
+ );
22
+
23
+ return (stored.numAffectedRows ?? 0n) > 0n;
24
+ }
@@ -0,0 +1,120 @@
1
+ import { verifyAuthenticationResponse } from '@simplewebauthn/server';
2
+ import type {
3
+ AuthenticationResponseJSON,
4
+ VerifiedAuthenticationResponse,
5
+ } from '@simplewebauthn/server';
6
+ import { toTagged } from '@zgeoff/std';
7
+ import { z } from 'zod';
8
+ import type { Store } from '../store/open-store.ts';
9
+ import type { PasskeyID } from '../types.ts';
10
+ import { parseJSONStrings } from '../utils/parse-json-strings.ts';
11
+ import { readPasskeyRows } from './read-passkey-rows.ts';
12
+ import { updatePasskeyUse } from './update-passkey-use.ts';
13
+
14
+ interface AssertionCheck {
15
+ // The credential JSON the sign-in page posted.
16
+ readonly credential: string;
17
+
18
+ // The challenge the page was given, which the caller has already taken.
19
+ readonly challenge: string;
20
+ readonly origin: string;
21
+ readonly rpID: string;
22
+ }
23
+
24
+ export async function verifyPasskeyAssertion(
25
+ store: Store,
26
+ check: AssertionCheck,
27
+ ): Promise<PasskeyID | null> {
28
+ const response = parseAssertion(check.credential);
29
+
30
+ if (response === null) {
31
+ return null;
32
+ }
33
+
34
+ const [passkey] = await readPasskeyRows(store.db, store.options.tables.passkey, response.id);
35
+
36
+ if (passkey === undefined) {
37
+ return null;
38
+ }
39
+
40
+ let verified: VerifiedAuthenticationResponse;
41
+
42
+ try {
43
+ verified = await verifyAuthenticationResponse({
44
+ response,
45
+ expectedChallenge: check.challenge,
46
+ expectedOrigin: check.origin,
47
+ expectedRPID: check.rpID,
48
+ expectedType: 'webauthn.get',
49
+ requireUserVerification: true,
50
+ credential: {
51
+ id: passkey.id,
52
+ publicKey: new Uint8Array(Buffer.from(passkey.public_key, 'base64url')),
53
+ counter: passkey.counter,
54
+ transports: (parseJSONStrings(passkey.transports) ?? []).flatMap((transport) =>
55
+ isTransport(transport) ? [transport] : [],
56
+ ),
57
+ },
58
+ });
59
+ } catch {
60
+ return null;
61
+ }
62
+
63
+ if (!verified.verified || !verified.authenticationInfo.userVerified) {
64
+ return null;
65
+ }
66
+
67
+ const stored = await updatePasskeyUse(store, {
68
+ id: toTagged<PasskeyID>(passkey.id),
69
+ counter: passkey.counter,
70
+ newCounter: verified.authenticationInfo.newCounter,
71
+ });
72
+
73
+ return stored ? toTagged<PasskeyID>(passkey.id) : null;
74
+ }
75
+
76
+ const AssertionSchema = z.object({
77
+ id: z.string().min(1),
78
+ rawId: z.string().min(1),
79
+ type: z.literal('public-key'),
80
+ response: z.object({
81
+ clientDataJSON: z.string(),
82
+ authenticatorData: z.string(),
83
+ signature: z.string(),
84
+ userHandle: z.string().optional(),
85
+ }),
86
+ });
87
+
88
+ // The posted JSON when it has the shape of an authentication response, else
89
+ // null; the verifier checks every value.
90
+ function parseAssertion(credential: string): AuthenticationResponseJSON | null {
91
+ let parsed: unknown;
92
+
93
+ try {
94
+ parsed = JSON.parse(credential);
95
+ } catch {
96
+ return null;
97
+ }
98
+
99
+ const result = AssertionSchema.safeParse(parsed);
100
+
101
+ if (!result.success) {
102
+ return null;
103
+ }
104
+
105
+ const { userHandle, ...response } = result.data.response;
106
+
107
+ return {
108
+ id: result.data.id,
109
+ rawId: result.data.rawId,
110
+ type: result.data.type,
111
+ response: userHandle === undefined ? response : { ...response, userHandle },
112
+ clientExtensionResults: {},
113
+ };
114
+ }
115
+
116
+ const TRANSPORTS = ['ble', 'cable', 'hybrid', 'internal', 'nfc', 'smart-card', 'usb'] as const;
117
+
118
+ function isTransport(value: string): value is (typeof TRANSPORTS)[number] {
119
+ return TRANSPORTS.some((transport) => transport === value);
120
+ }
@@ -0,0 +1,116 @@
1
+ import type { RegistrationResponseJSON } from '@simplewebauthn/server';
2
+ import { verifyRegistrationResponse } from '@simplewebauthn/server';
3
+ import { toTagged } from '@zgeoff/std';
4
+ import { z } from 'zod';
5
+ import type { PasskeyID } from '../types.ts';
6
+
7
+ interface RegistrationCheck {
8
+ // The credential JSON the enrollment page posted.
9
+ readonly credential: string;
10
+
11
+ // The challenge the page was given, which the caller has already taken.
12
+ readonly challenge: string;
13
+ readonly origin: string;
14
+ readonly rpID: string;
15
+ }
16
+
17
+ export interface RegisteredPasskey {
18
+ readonly id: PasskeyID;
19
+ readonly publicKey: Uint8Array;
20
+ readonly counter: number;
21
+ readonly transports: readonly string[];
22
+ }
23
+
24
+ export async function verifyPasskeyRegistration(
25
+ check: RegistrationCheck,
26
+ ): Promise<RegisteredPasskey | null> {
27
+ const response = parseRegistration(check.credential);
28
+
29
+ if (response === null) {
30
+ return null;
31
+ }
32
+
33
+ try {
34
+ const verified = await verifyRegistrationResponse({
35
+ response,
36
+ expectedChallenge: check.challenge,
37
+ expectedOrigin: check.origin,
38
+ expectedRPID: check.rpID,
39
+ expectedType: 'webauthn.create',
40
+ requireUserVerification: true,
41
+ });
42
+
43
+ if (!verified.verified || !verified.registrationInfo.userVerified) {
44
+ return null;
45
+ }
46
+
47
+ const credential = verified.registrationInfo.credential;
48
+
49
+ return {
50
+ id: toTagged<PasskeyID>(credential.id),
51
+ publicKey: credential.publicKey,
52
+ counter: credential.counter,
53
+ transports: response.response.transports ?? [],
54
+ };
55
+ } catch {
56
+ return null;
57
+ }
58
+ }
59
+
60
+ const TRANSPORTS: ReadonlySet<string> = new Set([
61
+ 'ble',
62
+ 'cable',
63
+ 'hybrid',
64
+ 'internal',
65
+ 'nfc',
66
+ 'smart-card',
67
+ 'usb',
68
+ ]);
69
+
70
+ const REGISTRATION_REPLY = z.object({
71
+ clientDataJSON: z.string(),
72
+ attestationObject: z.string(),
73
+ transports: z.string().array().optional(),
74
+ });
75
+
76
+ const REGISTRATION = z.object({
77
+ id: z.string().min(1),
78
+ rawId: z.string().min(1),
79
+ type: z.literal('public-key'),
80
+ response: REGISTRATION_REPLY,
81
+ });
82
+
83
+ // The posted JSON when it has the shape of a registration response, keeping
84
+ // only the transports WebAuthn defines, else null; the verifier checks
85
+ // every value.
86
+ function parseRegistration(credential: string): RegistrationResponseJSON | null {
87
+ let parsed: unknown;
88
+
89
+ try {
90
+ parsed = JSON.parse(credential);
91
+ } catch {
92
+ return null;
93
+ }
94
+
95
+ const result = REGISTRATION.safeParse(parsed);
96
+
97
+ if (!result.success) {
98
+ return null;
99
+ }
100
+
101
+ const transports = (result.data.response.transports ?? []).filter((transport) =>
102
+ TRANSPORTS.has(transport),
103
+ );
104
+
105
+ return {
106
+ id: result.data.id,
107
+ rawId: result.data.rawId,
108
+ type: result.data.type,
109
+ response: {
110
+ clientDataJSON: result.data.response.clientDataJSON,
111
+ attestationObject: result.data.response.attestationObject,
112
+ transports,
113
+ },
114
+ clientExtensionResults: {},
115
+ };
116
+ }
@@ -0,0 +1,42 @@
1
+ import type { Store } from '../store/open-store.ts';
2
+ import type { PasskeyID } from '../types.ts';
3
+ import { readPasskeyRows } from './read-passkey-rows.ts';
4
+
5
+ interface SessionPasskey {
6
+ // The session a passkey sign-in just created.
7
+ readonly sessionID: string;
8
+
9
+ // The passkey whose assertion signed the owner in.
10
+ readonly passkeyID: PasskeyID;
11
+ }
12
+
13
+ // A passkey removal that committed after the assertion verified and before the
14
+ // session existed deleted no session, so the session carries on only while the
15
+ // passkey that signed is still enrolled.
16
+ export async function verifySessionPasskey(store: Store, check: SessionPasskey): Promise<boolean> {
17
+ try {
18
+ return await store.db.transaction().execute(async (trx) => {
19
+ const passkeys = await readPasskeyRows(trx, store.options.tables.passkey, check.passkeyID);
20
+
21
+ const session = await trx
22
+ .selectFrom('session')
23
+ .select('id')
24
+ .where('id', '=', check.sessionID)
25
+ .executeTakeFirst();
26
+
27
+ if (passkeys.length > 0 && session !== undefined) {
28
+ return true;
29
+ }
30
+
31
+ await trx.deleteFrom('session').where('id', '=', check.sessionID).execute();
32
+
33
+ return false;
34
+ });
35
+ } catch {
36
+ // A transaction that fails, such as one a concurrent write keeps busy,
37
+ // still removes the session.
38
+ await store.db.deleteFrom('session').where('id', '=', check.sessionID).execute();
39
+
40
+ return false;
41
+ }
42
+ }
@@ -0,0 +1,31 @@
1
+ import { answerEnrollRequest } from '../passkeys/answer-enroll-request.ts';
2
+ import { answerAuthorizeRequest } from '../sign-in/answer-authorize-request.ts';
3
+ import { answerConsentRequest } from '../sign-in/answer-consent-request.ts';
4
+ import { answerLoginRequest } from '../sign-in/answer-login-request.ts';
5
+ import type { RouteContext } from '../sign-in/route-context.ts';
6
+ import { answerErrorRequest } from '../tokens/answer-error-request.ts';
7
+ import { answerMetadataRequest } from '../tokens/answer-metadata-request.ts';
8
+ import { answerRevokeRequest } from '../tokens/answer-revoke-request.ts';
9
+ import { answerTokenRequest } from '../tokens/answer-token-request.ts';
10
+ import type { MCPAuthRoutes } from '../types.ts';
11
+ import { withFormOrigin } from './with-form-origin.ts';
12
+
13
+ export function buildRoutes(ctx: RouteContext): MCPAuthRoutes {
14
+ return {
15
+ authorize: (request, requester) => answerAuthorizeRequest(ctx, request, requester),
16
+ login: withFormOrigin(ctx.origin, (request, requester) =>
17
+ answerLoginRequest(ctx, request, requester),
18
+ ),
19
+ enroll: withFormOrigin(ctx.origin, (request, requester) =>
20
+ answerEnrollRequest(ctx, request, requester),
21
+ ),
22
+ consent: withFormOrigin(ctx.origin, (request, requester) =>
23
+ answerConsentRequest(ctx, request, requester),
24
+ ),
25
+ error: (request) => Promise.resolve(answerErrorRequest(ctx, request)),
26
+ token: (request, requester) => answerTokenRequest(ctx, request, requester),
27
+ revoke: (request) => answerRevokeRequest(ctx, request),
28
+ authorizationServerMetadata: () => answerMetadataRequest(ctx, 'authorization-server'),
29
+ resourceMetadata: () => answerMetadataRequest(ctx, 'resource'),
30
+ };
31
+ }
@@ -0,0 +1,18 @@
1
+ import type { Requester } from '../types.ts';
2
+ import { buildPageResponse } from '../utils/build-page-response.ts';
3
+
4
+ type Route = (request: Request, requester: Requester) => Promise<Response>;
5
+
6
+ // A form posts from the server's own pages, so a post with no Origin header or
7
+ // another one is a forged form.
8
+ export function withFormOrigin(origin: string, route: Route): Route {
9
+ return (request, requester) => {
10
+ if (request.method === 'POST' && request.headers.get('origin') !== origin) {
11
+ return Promise.resolve(
12
+ buildPageResponse(403, { message: 'The form came from an unexpected origin.' }),
13
+ );
14
+ }
15
+
16
+ return route(request, requester);
17
+ };
18
+ }
@@ -0,0 +1,56 @@
1
+ import { createHash, timingSafeEqual } from 'node:crypto';
2
+ import type { Access, ServiceTokenFile } from '../types.ts';
3
+
4
+ interface StoredToken<Scope extends string> {
5
+ readonly digest: Buffer;
6
+ readonly access: Extract<Access<Scope, never>, { kind: 'service' }>;
7
+ }
8
+
9
+ export interface ServiceTokenVerifier<Scope extends string> {
10
+ // The access a service token grants, or null for any other value.
11
+ readonly verify: (token: string) => StoredToken<Scope>['access'] | null;
12
+
13
+ // The scopes of a service client, or null for an ID the file does not list.
14
+ readonly findScopes: (clientID: string) => readonly Scope[] | null;
15
+ }
16
+
17
+ // Only the digests of the tokens stay in memory.
18
+ export function buildServiceTokenVerifier<Scope extends string>(
19
+ file: ServiceTokenFile<Scope>,
20
+ ): ServiceTokenVerifier<Scope> {
21
+ const stored: StoredToken<Scope>[] = file.clients.flatMap((client) => {
22
+ const clientID: `service:${string}` = `service:${client.name}`;
23
+
24
+ const access: StoredToken<Scope>['access'] = {
25
+ kind: 'service',
26
+ clientID,
27
+ clientName: clientID,
28
+ scopes: client.scopes,
29
+ };
30
+
31
+ return client.tokens.map((token) => ({ digest: toDigest(token), access }));
32
+ });
33
+
34
+ return {
35
+ verify: (token) => {
36
+ const presented = toDigest(token);
37
+ let match: StoredToken<Scope>['access'] | null = null;
38
+
39
+ // Every stored token is compared, so the time taken does not say which
40
+ // one matched.
41
+ for (const entry of stored) {
42
+ if (timingSafeEqual(presented, entry.digest)) {
43
+ match = entry.access;
44
+ }
45
+ }
46
+
47
+ return match;
48
+ },
49
+ findScopes: (clientID) =>
50
+ stored.find((entry) => entry.access.clientID === clientID)?.access.scopes ?? null,
51
+ };
52
+ }
53
+
54
+ function toDigest(token: string): Buffer {
55
+ return createHash('sha256').update(token).digest();
56
+ }
@@ -0,0 +1,104 @@
1
+ import { z } from 'zod';
2
+ import type { ParsedServiceTokenFile } from '../types.ts';
3
+
4
+ interface ServiceTokenRules<Scope extends string> {
5
+ // Every service token starts with this, so a bearer is routed to the token
6
+ // file or to the database by its first characters.
7
+ readonly prefix: string;
8
+ readonly scopes: readonly Scope[];
9
+ }
10
+
11
+ // None of these messages holds the value it judges, because a value in the
12
+ // file may be a token.
13
+ const NAME_MESSAGE = 'a client name must match [a-z][a-z0-9-]{0,31}';
14
+ const NameSchema = z.string().regex(/^[a-z][a-z0-9-]{0,31}$/u, NAME_MESSAGE);
15
+
16
+ export function parseServiceTokenFile<Scope extends string>(
17
+ text: string,
18
+ rules: ServiceTokenRules<Scope>,
19
+ ): ParsedServiceTokenFile<Scope> {
20
+ let raw: unknown;
21
+
22
+ try {
23
+ raw = JSON.parse(text);
24
+ } catch {
25
+ // The parser's own message quotes the text.
26
+ return { ok: false, reason: 'the file is not valid JSON' };
27
+ }
28
+
29
+ const tokenMessage = `a token must be ${rules.prefix} followed by 32 or more of A-Z, a-z, 0-9, _ and -`;
30
+
31
+ const tokenPattern = new RegExp(`^${escapePattern(rules.prefix)}[A-Za-z0-9_-]{32,}$`, 'u');
32
+
33
+ const ClientSchema = z.strictObject({
34
+ scopes: z
35
+ .array(
36
+ z
37
+ .string()
38
+ .refine((scope): scope is Scope => rules.scopes.some((known) => known === scope), {
39
+ message: 'a scope must be one the server knows',
40
+ }),
41
+ )
42
+ .min(1, 'must name at least one scope'),
43
+ tokens: z
44
+ .array(z.string().regex(tokenPattern, tokenMessage))
45
+ .min(1, 'must hold 1 or 2 tokens')
46
+ .max(2, 'must hold 1 or 2 tokens'),
47
+ });
48
+
49
+ const FileSchema = z.strictObject({
50
+ resource: z.string().min(1, 'must be the resource URL the server serves'),
51
+ clients: z
52
+ .record(NameSchema, ClientSchema)
53
+ .refine((clients) => Object.keys(clients).length > 0, 'must name at least one client'),
54
+ });
55
+
56
+ const parsed = FileSchema.safeParse(raw);
57
+
58
+ if (!parsed.success) {
59
+ return { ok: false, reason: parsed.error.issues.map((issue) => formatIssue(issue)).join('; ') };
60
+ }
61
+
62
+ const clients = Object.entries(parsed.data.clients).map(([name, client]) => ({
63
+ name,
64
+ scopes: [...new Set(client.scopes)],
65
+ tokens: client.tokens,
66
+ }));
67
+
68
+ const tokens = clients.flatMap((client) => client.tokens);
69
+
70
+ if (new Set(tokens).size !== tokens.length) {
71
+ return { ok: false, reason: 'the same token appears more than once' };
72
+ }
73
+
74
+ return { ok: true, file: { resource: parsed.data.resource, clients } };
75
+ }
76
+
77
+ function escapePattern(text: string): string {
78
+ return text.replaceAll(/[.*+?^${}()|[\]\\]/gu, String.raw`\$&`);
79
+ }
80
+
81
+ function formatIssue(issue: z.core.$ZodIssue): string {
82
+ // A rejected key may be a misplaced token, so the message leaves it out.
83
+ if (issue.code === 'unrecognized_keys') {
84
+ return `${formatPath(issue.path)}has a field the file does not take`;
85
+ }
86
+
87
+ if (issue.code === 'invalid_key') {
88
+ return NAME_MESSAGE;
89
+ }
90
+
91
+ return `${formatPath(issue.path)}${issue.message}`;
92
+ }
93
+
94
+ function formatPath(path: readonly PropertyKey[]): string {
95
+ if (path.length === 0) {
96
+ return 'the file: ';
97
+ }
98
+
99
+ const text = path
100
+ .map((segment) => (typeof segment === 'number' ? `[${segment}]` : `.${String(segment)}`))
101
+ .join('');
102
+
103
+ return `${text.replace(/^\./u, '')}: `;
104
+ }