@zgeoff/mcp-auth 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (205) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +76 -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/elysia/create-mcp-http-app.d.ts +17 -0
  15. package/dist/elysia/find-bearer-token.d.ts +1 -0
  16. package/dist/elysia/index.d.ts +2 -0
  17. package/dist/elysia/is-beside-prefix.d.ts +1 -0
  18. package/dist/grants/collect-granted-scopes.d.ts +7 -0
  19. package/dist/grants/read-access-payload.d.ts +9 -0
  20. package/dist/grants/read-client-scopes.d.ts +2 -0
  21. package/dist/grants/verify-oauth-access.d.ts +13 -0
  22. package/dist/index.d.ts +7 -0
  23. package/dist/mcp-auth-error.d.ts +5 -0
  24. package/dist/open-mcp-auth-admin.d.ts +2 -0
  25. package/dist/open-mcp-auth.d.ts +2 -0
  26. package/dist/passkeys/answer-enroll-request.d.ts +3 -0
  27. package/dist/passkeys/create-enrollment-state.d.ts +6 -0
  28. package/dist/passkeys/create-passkey.d.ts +10 -0
  29. package/dist/passkeys/passkey-script.d.ts +4 -0
  30. package/dist/passkeys/read-enrollment-token.d.ts +2 -0
  31. package/dist/passkeys/read-passkey-rows.d.ts +13 -0
  32. package/dist/passkeys/render-enroll-page.d.ts +11 -0
  33. package/dist/passkeys/render-login-page.d.ts +11 -0
  34. package/dist/passkeys/update-passkey-use.d.ts +9 -0
  35. package/dist/passkeys/verify-passkey-assertion.d.ts +10 -0
  36. package/dist/passkeys/verify-passkey-registration.d.ts +15 -0
  37. package/dist/passkeys/verify-session-passkey.d.ts +8 -0
  38. package/dist/routes/build-routes.d.ts +3 -0
  39. package/dist/routes/with-form-origin.d.ts +4 -0
  40. package/dist/service-tokens/build-service-token-verifier.d.ts +13 -0
  41. package/dist/service-tokens/parse-service-token-file.d.ts +7 -0
  42. package/dist/sign-in/answer-authorize-request.d.ts +3 -0
  43. package/dist/sign-in/answer-consent-request.d.ts +3 -0
  44. package/dist/sign-in/answer-login-request.d.ts +3 -0
  45. package/dist/sign-in/build-consent-binding.d.ts +1 -0
  46. package/dist/sign-in/create-sign-in-state.d.ts +43 -0
  47. package/dist/sign-in/pick-consent-choice.d.ts +8 -0
  48. package/dist/sign-in/pick-consent-outcome.d.ts +4 -0
  49. package/dist/sign-in/read-session-id.d.ts +2 -0
  50. package/dist/sign-in/read-stored-client-name.d.ts +3 -0
  51. package/dist/sign-in/read-url-field.d.ts +1 -0
  52. package/dist/sign-in/render-consent-page.d.ts +11 -0
  53. package/dist/sign-in/route-context.d.ts +17 -0
  54. package/dist/sign-in/verify-oauth-query.d.ts +1 -0
  55. package/dist/store/check-cascade-keys.d.ts +2 -0
  56. package/dist/store/check-foreign-keys.d.ts +2 -0
  57. package/dist/store/check-table-names.d.ts +2 -0
  58. package/dist/store/check-user-columns.d.ts +2 -0
  59. package/dist/store/create-auth-server.d.ts +103 -0
  60. package/dist/store/create-grant-plugin.d.ts +28 -0
  61. package/dist/store/create-owned-tables.d.ts +3 -0
  62. package/dist/store/open-store.d.ts +15 -0
  63. package/dist/store/read-table-columns.d.ts +2 -0
  64. package/dist/store/remove-grant-rows.d.ts +3 -0
  65. package/dist/store/store-schema.d.ts +63 -0
  66. package/dist/test-utils/authorize-test-client.d.ts +12 -0
  67. package/dist/test-utils/build-form-request.d.ts +1 -0
  68. package/dist/test-utils/build-seeder.d.ts +13 -0
  69. package/dist/test-utils/build-stub-authenticator.d.ts +49 -0
  70. package/dist/test-utils/build-stub-clock.d.ts +5 -0
  71. package/dist/test-utils/build-test-requester.d.ts +2 -0
  72. package/dist/test-utils/create-test-database.d.ts +2 -0
  73. package/dist/test-utils/hook-sqlite-statements.d.ts +2 -0
  74. package/dist/test-utils/index.d.ts +12 -0
  75. package/dist/test-utils/open-test-auth.d.ts +21 -0
  76. package/dist/test-utils/parse-passkey-page.d.ts +21 -0
  77. package/dist/test-utils/read-json-record.d.ts +5 -0
  78. package/dist/test-utils/run-sign-in-to-consent.d.ts +13 -0
  79. package/dist/test-utils/seed-client.d.ts +7 -0
  80. package/dist/test-utils/seed-enrollment-token.d.ts +2 -0
  81. package/dist/test-utils/seed-passkey.d.ts +7 -0
  82. package/dist/tokens/answer-error-request.d.ts +2 -0
  83. package/dist/tokens/answer-metadata-request.d.ts +2 -0
  84. package/dist/tokens/answer-revoke-request.d.ts +2 -0
  85. package/dist/tokens/answer-token-request.d.ts +3 -0
  86. package/dist/tokens/build-better-auth-request.d.ts +6 -0
  87. package/dist/tokens/build-oauth-error.d.ts +1 -0
  88. package/dist/tokens/read-error-code.d.ts +1 -0
  89. package/dist/tokens/read-error-description.d.ts +1 -0
  90. package/dist/tokens/record-token-exchange.d.ts +10 -0
  91. package/dist/tokens/remove-token-sessions.d.ts +2 -0
  92. package/dist/types.d.ts +185 -0
  93. package/dist/utils/build-page-response.d.ts +5 -0
  94. package/dist/utils/derive-token-hash.d.ts +1 -0
  95. package/dist/utils/is-allowed-redirect-uri.d.ts +1 -0
  96. package/dist/utils/is-loopback-host.d.ts +1 -0
  97. package/dist/utils/normalize-client-name.d.ts +1 -0
  98. package/dist/utils/parse-approved-by.d.ts +2 -0
  99. package/dist/utils/parse-json-strings.d.ts +1 -0
  100. package/dist/utils/read-body-text.d.ts +1 -0
  101. package/dist/utils/read-form.d.ts +2 -0
  102. package/dist/utils/to-html-text.d.ts +1 -0
  103. package/dist/utils/to-script-json.d.ts +1 -0
  104. package/package.json +73 -4
  105. package/src/admin/build-admin.ts +22 -0
  106. package/src/admin/build-client-admin.ts +112 -0
  107. package/src/admin/build-grant-admin.ts +62 -0
  108. package/src/admin/build-passkey-admin.ts +53 -0
  109. package/src/admin/check-redirect-uris.ts +17 -0
  110. package/src/admin/create-enrollment-token.ts +18 -0
  111. package/src/admin/read-client-name.ts +13 -0
  112. package/src/admin/read-sign-in-grants.ts +22 -0
  113. package/src/admin/remove-expired.ts +47 -0
  114. package/src/admin/to-client-view.ts +12 -0
  115. package/src/default-paths.ts +21 -0
  116. package/src/elysia/create-mcp-http-app.ts +218 -0
  117. package/src/elysia/find-bearer-token.ts +6 -0
  118. package/src/elysia/index.ts +2 -0
  119. package/src/elysia/is-beside-prefix.ts +7 -0
  120. package/src/grants/collect-granted-scopes.ts +19 -0
  121. package/src/grants/read-access-payload.ts +37 -0
  122. package/src/grants/read-client-scopes.ts +36 -0
  123. package/src/grants/verify-oauth-access.ts +113 -0
  124. package/src/index.ts +7 -0
  125. package/src/mcp-auth-error.ts +17 -0
  126. package/src/open-mcp-auth-admin.ts +14 -0
  127. package/src/open-mcp-auth.ts +89 -0
  128. package/src/passkeys/answer-enroll-request.ts +179 -0
  129. package/src/passkeys/create-enrollment-state.ts +54 -0
  130. package/src/passkeys/create-passkey.ts +39 -0
  131. package/src/passkeys/passkey-script.ts +48 -0
  132. package/src/passkeys/read-enrollment-token.ts +21 -0
  133. package/src/passkeys/read-passkey-rows.ts +30 -0
  134. package/src/passkeys/render-enroll-page.ts +58 -0
  135. package/src/passkeys/render-login-page.ts +59 -0
  136. package/src/passkeys/update-passkey-use.ts +24 -0
  137. package/src/passkeys/verify-passkey-assertion.ts +120 -0
  138. package/src/passkeys/verify-passkey-registration.ts +116 -0
  139. package/src/passkeys/verify-session-passkey.ts +42 -0
  140. package/src/routes/build-routes.ts +31 -0
  141. package/src/routes/with-form-origin.ts +18 -0
  142. package/src/service-tokens/build-service-token-verifier.ts +56 -0
  143. package/src/service-tokens/parse-service-token-file.ts +104 -0
  144. package/src/sign-in/answer-authorize-request.ts +133 -0
  145. package/src/sign-in/answer-consent-request.ts +220 -0
  146. package/src/sign-in/answer-login-request.ts +243 -0
  147. package/src/sign-in/build-consent-binding.ts +11 -0
  148. package/src/sign-in/create-sign-in-state.ts +229 -0
  149. package/src/sign-in/pick-consent-choice.ts +27 -0
  150. package/src/sign-in/pick-consent-outcome.ts +14 -0
  151. package/src/sign-in/read-session-id.ts +11 -0
  152. package/src/sign-in/read-stored-client-name.ts +15 -0
  153. package/src/sign-in/read-url-field.ts +12 -0
  154. package/src/sign-in/render-consent-page.ts +57 -0
  155. package/src/sign-in/route-context.ts +25 -0
  156. package/src/sign-in/verify-oauth-query.ts +39 -0
  157. package/src/store/check-cascade-keys.ts +36 -0
  158. package/src/store/check-foreign-keys.ts +20 -0
  159. package/src/store/check-table-names.ts +13 -0
  160. package/src/store/check-user-columns.ts +22 -0
  161. package/src/store/create-auth-server.ts +97 -0
  162. package/src/store/create-grant-plugin.ts +68 -0
  163. package/src/store/create-owned-tables.ts +45 -0
  164. package/src/store/open-store.ts +72 -0
  165. package/src/store/read-table-columns.ts +12 -0
  166. package/src/store/remove-grant-rows.ts +27 -0
  167. package/src/store/store-schema.ts +61 -0
  168. package/src/test-utils/authorize-test-client.ts +93 -0
  169. package/src/test-utils/build-form-request.ts +12 -0
  170. package/src/test-utils/build-seeder.ts +19 -0
  171. package/src/test-utils/build-stub-authenticator.ts +244 -0
  172. package/src/test-utils/build-stub-clock.ts +21 -0
  173. package/src/test-utils/build-test-requester.ts +5 -0
  174. package/src/test-utils/create-test-database.ts +7 -0
  175. package/src/test-utils/hook-sqlite-statements.ts +17 -0
  176. package/src/test-utils/index.ts +12 -0
  177. package/src/test-utils/open-test-auth.ts +72 -0
  178. package/src/test-utils/parse-passkey-page.ts +25 -0
  179. package/src/test-utils/read-json-record.ts +15 -0
  180. package/src/test-utils/run-sign-in-to-consent.ts +100 -0
  181. package/src/test-utils/seed-client.ts +16 -0
  182. package/src/test-utils/seed-enrollment-token.ts +5 -0
  183. package/src/test-utils/seed-passkey.ts +51 -0
  184. package/src/tokens/answer-error-request.ts +26 -0
  185. package/src/tokens/answer-metadata-request.ts +51 -0
  186. package/src/tokens/answer-revoke-request.ts +47 -0
  187. package/src/tokens/answer-token-request.ts +133 -0
  188. package/src/tokens/build-better-auth-request.ts +23 -0
  189. package/src/tokens/build-oauth-error.ts +7 -0
  190. package/src/tokens/read-error-code.ts +12 -0
  191. package/src/tokens/read-error-description.ts +11 -0
  192. package/src/tokens/record-token-exchange.ts +73 -0
  193. package/src/tokens/remove-token-sessions.ts +32 -0
  194. package/src/types.ts +247 -0
  195. package/src/utils/build-page-response.ts +24 -0
  196. package/src/utils/derive-token-hash.ts +5 -0
  197. package/src/utils/is-allowed-redirect-uri.ts +17 -0
  198. package/src/utils/is-loopback-host.ts +8 -0
  199. package/src/utils/normalize-client-name.ts +20 -0
  200. package/src/utils/parse-approved-by.ts +9 -0
  201. package/src/utils/parse-json-strings.ts +13 -0
  202. package/src/utils/read-body-text.ts +23 -0
  203. package/src/utils/read-form.ts +16 -0
  204. package/src/utils/to-html-text.ts +8 -0
  205. package/src/utils/to-script-json.ts +6 -0
package/src/types.ts ADDED
@@ -0,0 +1,247 @@
1
+ import type { Database } from 'bun:sqlite';
2
+ import type { Tagged } from 'type-fest';
3
+
4
+ export type GrantID = Tagged<string, 'GrantID'>;
5
+
6
+ export type OAuthClientID = Tagged<string, 'OAuthClientID'>;
7
+
8
+ export type PasskeyID = Tagged<string, 'PasskeyID'>;
9
+
10
+ // The same for every event of one sign-in.
11
+ export type CorrelationID = Tagged<string, 'CorrelationID'>;
12
+
13
+ // After `token:` comes an imp token ID.
14
+ export type ApprovedBy = 'passkey' | `token:${string}`;
15
+
16
+ export interface MCPAuthPaths {
17
+ readonly browser: {
18
+ readonly authorize: string;
19
+ readonly login: string;
20
+ readonly enroll: string;
21
+ readonly consent: string;
22
+ readonly error: string;
23
+ };
24
+ readonly machine: {
25
+ readonly mcp: string;
26
+ readonly root: string;
27
+ readonly token: string;
28
+ readonly revoke: string;
29
+ readonly authorizationServerMetadata: string;
30
+ readonly resourceMetadata: string;
31
+ readonly mcpResourceMetadata: string;
32
+ };
33
+ }
34
+
35
+ export interface MCPAuthTables {
36
+ // Owned by the app: the core reads and writes only the columns it needs.
37
+ readonly passkey: string;
38
+
39
+ // Owned by the core: token_hash, created_at, expires_at.
40
+ readonly enrollmentToken: string;
41
+ }
42
+
43
+ // The clock for the times the core stamps itself: sign-ins in progress,
44
+ // enrollments, lastUsedAt and removeExpired. better-auth stamps token, code
45
+ // and session expiries from Date.now().
46
+ export interface Clock {
47
+ readonly now: () => number;
48
+ }
49
+
50
+ export interface Requester {
51
+ readonly socketAddress: string | null;
52
+ readonly connectingIP: {
53
+ readonly address: string;
54
+ readonly provenance: 'trusted' | 'unverified';
55
+ } | null;
56
+ readonly userAgent: string | null;
57
+ }
58
+
59
+ export interface SecurityEvent {
60
+ readonly kind:
61
+ | 'authorize_started'
62
+ | 'authorize_invalid'
63
+ | 'owner_auth'
64
+ | 'consent'
65
+ | 'token_exchange'
66
+ | 'bearer'
67
+ | 'bad_host'
68
+ | 'bad_origin';
69
+ readonly outcome: 'accepted' | 'rejected' | 'succeeded' | 'failed' | 'allowed' | 'denied';
70
+ readonly reason?: string;
71
+ readonly path: string;
72
+ readonly requester: Requester;
73
+ readonly client?: { readonly id: OAuthClientID; readonly name: string };
74
+ readonly correlationID?: CorrelationID;
75
+ }
76
+
77
+ export interface SecuritySink {
78
+ readonly record: (event: SecurityEvent) => void;
79
+ }
80
+
81
+ export interface MCPAuthAdminOptions<Scope extends string> {
82
+ readonly database: Database;
83
+ readonly scopes: readonly Scope[];
84
+ readonly tables: MCPAuthTables;
85
+ readonly clock: Clock;
86
+ readonly onGrantRevoked: (grantID: GrantID) => void;
87
+ }
88
+
89
+ export interface ServiceClient<Scope extends string> {
90
+ readonly name: string;
91
+ readonly scopes: readonly Scope[];
92
+ readonly tokens: readonly string[];
93
+ }
94
+
95
+ export interface ServiceTokenFile<Scope extends string> {
96
+ readonly resource: string;
97
+ readonly clients: readonly ServiceClient<Scope>[];
98
+ }
99
+
100
+ export type ParsedServiceTokenFile<Scope extends string> =
101
+ | { readonly ok: true; readonly file: ServiceTokenFile<Scope> }
102
+ | { readonly ok: false; readonly reason: string };
103
+
104
+ export interface MCPAuthOptions<Scope extends string, Limits> extends MCPAuthAdminOptions<Scope> {
105
+ readonly origin: string;
106
+ readonly productName: string;
107
+ readonly paths: MCPAuthPaths;
108
+ readonly serviceTokens?: {
109
+ readonly prefix: string;
110
+ readonly file: ServiceTokenFile<Scope>;
111
+ };
112
+ readonly grantLimits?: GrantLimits<Limits>;
113
+ readonly security: SecuritySink;
114
+ }
115
+
116
+ export interface ClientView {
117
+ readonly clientID: OAuthClientID;
118
+ readonly name: string;
119
+ readonly redirectURIs: readonly string[];
120
+ readonly createdAt: string;
121
+ }
122
+
123
+ export interface GrantView {
124
+ readonly grantID: GrantID;
125
+ readonly clientID: OAuthClientID;
126
+ readonly clientName: string;
127
+ readonly scopes: readonly string[];
128
+ readonly approvedBy: ApprovedBy;
129
+ readonly createdAt: string;
130
+ readonly lastUsedAt: string | null;
131
+ }
132
+
133
+ export interface PasskeyView {
134
+ readonly id: PasskeyID;
135
+ readonly createdAt: string;
136
+ readonly lastUsedAt: string | null;
137
+ }
138
+
139
+ export interface MCPAuthAdmin {
140
+ readonly clients: {
141
+ readonly list: () => Promise<ClientView[]>;
142
+ readonly add: (name: string, redirectURIs: readonly string[]) => Promise<ClientView>;
143
+ readonly update: (name: string, redirectURIs: readonly string[]) => Promise<ClientView>;
144
+
145
+ // The number of grants it revoked.
146
+ readonly remove: (name: string) => Promise<number>;
147
+ };
148
+ readonly grants: {
149
+ // Grants with a live refresh token.
150
+ readonly list: () => Promise<GrantView[]>;
151
+
152
+ // False when no grant row has the ID.
153
+ readonly revoke: (grantID: GrantID) => Promise<boolean>;
154
+ };
155
+ readonly passkeys: {
156
+ // Shown once; the core stores its hash.
157
+ readonly createEnrollmentToken: () => Promise<string>;
158
+ readonly list: () => Promise<PasskeyView[]>;
159
+ readonly remove: (id: PasskeyID) => Promise<void>;
160
+
161
+ // Removes every passkey, and the grant row of each sign-in in progress.
162
+ readonly reset: () => Promise<void>;
163
+ };
164
+ readonly removeExpired: () => Promise<void>;
165
+
166
+ // Leaves the bun:sqlite connection open.
167
+ readonly close: () => Promise<void>;
168
+ }
169
+
170
+ export type MCPAuthRouteName =
171
+ | 'authorize'
172
+ | 'login'
173
+ | 'enroll'
174
+ | 'consent'
175
+ | 'error'
176
+ | 'token'
177
+ | 'revoke'
178
+ | 'authorizationServerMetadata'
179
+ | 'resourceMetadata';
180
+
181
+ export type MCPAuthRoutes = Record<
182
+ MCPAuthRouteName,
183
+ (request: Request, requester: Requester) => Promise<Response>
184
+ >;
185
+
186
+ export type Access<Scope extends string, Limits> =
187
+ | {
188
+ readonly kind: 'oauth';
189
+ readonly grantID: GrantID;
190
+ readonly clientID: OAuthClientID;
191
+ readonly clientName: string;
192
+ readonly scopes: readonly Scope[];
193
+ readonly limits: Limits | null;
194
+ }
195
+ | {
196
+ readonly kind: 'service';
197
+ readonly clientID: `service:${string}`;
198
+ readonly clientName: `service:${string}`;
199
+ readonly scopes: readonly Scope[];
200
+ };
201
+
202
+ export interface MCPAuth<Scope extends string, Limits = null> extends MCPAuthAdmin {
203
+ // `${origin}${paths.machine.mcp}`
204
+ readonly resource: string;
205
+ readonly issuer: string;
206
+ readonly paths: MCPAuthPaths;
207
+ readonly routes: MCPAuthRoutes;
208
+
209
+ // Null for an unknown, expired or revoked token, and for a DPoP-bound one.
210
+ // Throws when the app's GrantLimits.check throws.
211
+ readonly verify: (bearer: string) => Promise<Access<Scope, Limits> | null>;
212
+
213
+ // The scopes a client holds now, or null when it holds none.
214
+ readonly findClientScopes: (clientID: string) => Promise<readonly Scope[] | null>;
215
+ }
216
+
217
+ export interface ConsentRequest {
218
+ readonly clientID: OAuthClientID;
219
+ readonly clientName: string;
220
+ readonly scopes: readonly string[];
221
+ }
222
+
223
+ export interface StoredGrant<Limits> {
224
+ readonly grantID: GrantID;
225
+ readonly clientID: OAuthClientID;
226
+ readonly scopes: readonly string[];
227
+ readonly approvedBy: ApprovedBy;
228
+ readonly limits: Limits | null;
229
+ readonly createdAt: number;
230
+ readonly lastUsedAt: number | null;
231
+ }
232
+
233
+ export type GrantCheck =
234
+ | { readonly kind: 'allow'; readonly scopes: readonly string[] }
235
+ | { readonly kind: 'revoke'; readonly reason: string };
236
+
237
+ export interface GrantLimits<Limits> {
238
+ // HTML, escaped by the app.
239
+ readonly renderConsentFields: (request: ConsentRequest) => string;
240
+ readonly parseConsentFields: (
241
+ form: URLSearchParams,
242
+ ) => { ok: true; limits: Limits } | { ok: false; error: string };
243
+
244
+ // Null revokes the grant.
245
+ readonly parseStored: (json: unknown) => Limits | null;
246
+ readonly check: (grant: StoredGrant<Limits>) => Promise<GrantCheck>;
247
+ }
@@ -0,0 +1,24 @@
1
+ import { toHTMLText } from './to-html-text.ts';
2
+
3
+ export function buildPageResponse(
4
+ status: number,
5
+ body: { readonly page: string } | { readonly message: string },
6
+ formTargets: readonly string[] = [],
7
+ scriptSources: readonly string[] = [],
8
+ ): Response {
9
+ const html =
10
+ 'page' in body
11
+ ? body.page
12
+ : `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Sign in</title></head><body><p>${toHTMLText(body.message)}</p></body></html>`;
13
+
14
+ return new Response(html, {
15
+ status,
16
+ headers: {
17
+ 'content-type': 'text/html; charset=utf-8',
18
+ 'content-security-policy': `default-src 'none'; style-src 'unsafe-inline';${scriptSources.length === 0 ? '' : ` script-src ${scriptSources.join(' ')};`} form-action 'self'${formTargets.map((target) => ` ${target}`).join('')}; frame-ancestors 'none'; base-uri 'none'`,
19
+ 'x-frame-options': 'DENY',
20
+ 'cache-control': 'no-store',
21
+ 'referrer-policy': 'same-origin',
22
+ },
23
+ });
24
+ }
@@ -0,0 +1,5 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ export function deriveTokenHash(token: string): string {
4
+ return createHash('sha256').update(token).digest('base64url');
5
+ }
@@ -0,0 +1,17 @@
1
+ import { isLoopbackHost } from './is-loopback-host.ts';
2
+
3
+ export function isAllowedRedirectURI(raw: string): boolean {
4
+ let url: URL;
5
+
6
+ try {
7
+ url = new URL(raw);
8
+ } catch {
9
+ return false;
10
+ }
11
+
12
+ if (url.hash !== '' || url.username !== '' || url.password !== '') {
13
+ return false;
14
+ }
15
+
16
+ return url.protocol === 'https:' || (url.protocol === 'http:' && isLoopbackHost(url.hostname));
17
+ }
@@ -0,0 +1,8 @@
1
+ export function isLoopbackHost(host: string): boolean {
2
+ return (
3
+ host === 'localhost' ||
4
+ host === '::1' ||
5
+ host === '[::1]' ||
6
+ /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/u.test(host)
7
+ );
8
+ }
@@ -0,0 +1,20 @@
1
+ export function normalizeClientName(
2
+ raw: unknown,
3
+ fallback = 'unnamed client',
4
+ maxLength = 100,
5
+ ): string {
6
+ if (typeof raw !== 'string') {
7
+ return fallback;
8
+ }
9
+
10
+ const folded = raw
11
+ .replaceAll(/[\t\n\v\f\r]/gu, ' ')
12
+ .replaceAll(/[\p{Cc}\p{Cf}]/gu, '')
13
+ .replaceAll(/\s+/gu, ' ')
14
+ .trim();
15
+
16
+ // The cut counts code points, so it never splits a surrogate pair.
17
+ const cut = folded.replace(new RegExp(`^(?<kept>.{${maxLength}}).+$`, 'su'), '$<kept>').trim();
18
+
19
+ return cut === '' ? fallback : cut;
20
+ }
@@ -0,0 +1,9 @@
1
+ import type { ApprovedBy } from '../types.ts';
2
+
3
+ export function parseApprovedBy(text: string): ApprovedBy | null {
4
+ if (text === 'passkey') {
5
+ return text;
6
+ }
7
+
8
+ return text.startsWith('token:') ? `token:${text.slice('token:'.length)}` : null;
9
+ }
@@ -0,0 +1,13 @@
1
+ export function parseJSONStrings(raw: string): string[] | null {
2
+ let parsed: unknown;
3
+
4
+ try {
5
+ parsed = JSON.parse(raw);
6
+ } catch {
7
+ return null;
8
+ }
9
+
10
+ return Array.isArray(parsed)
11
+ ? parsed.filter((item): item is string => typeof item === 'string')
12
+ : null;
13
+ }
@@ -0,0 +1,23 @@
1
+ // The body as text, or null when it is absent or longer than the limit.
2
+ export async function readBodyText(request: Request, maxBytes: number): Promise<string | null> {
3
+ if (request.body === null) {
4
+ return null;
5
+ }
6
+
7
+ const body: ReadableStream<Uint8Array> = request.body;
8
+ const chunks: Uint8Array[] = [];
9
+ let total = 0;
10
+
11
+ // Leaving the loop early cancels the rest of the body.
12
+ for await (const chunk of body) {
13
+ total += chunk.byteLength;
14
+
15
+ if (total > maxBytes) {
16
+ return null;
17
+ }
18
+
19
+ chunks.push(chunk);
20
+ }
21
+
22
+ return new TextDecoder().decode(Buffer.concat(chunks));
23
+ }
@@ -0,0 +1,16 @@
1
+ import { readBodyText } from './read-body-text.ts';
2
+
3
+ export const MAX_FORM_BYTES = 16 * 1024;
4
+
5
+ // The fields of a form post, or an empty form for any other body.
6
+ export async function readForm(request: Request): Promise<URLSearchParams> {
7
+ const type = request.headers.get('content-type') ?? '';
8
+
9
+ if (!type.startsWith('application/x-www-form-urlencoded')) {
10
+ return new URLSearchParams();
11
+ }
12
+
13
+ const text = await readBodyText(request, MAX_FORM_BYTES);
14
+
15
+ return new URLSearchParams(text ?? '');
16
+ }
@@ -0,0 +1,8 @@
1
+ export function toHTMLText(text: string): string {
2
+ return text
3
+ .replaceAll('&', '&amp;')
4
+ .replaceAll('<', '&lt;')
5
+ .replaceAll('>', '&gt;')
6
+ .replaceAll('"', '&quot;')
7
+ .replaceAll("'", '&#39;');
8
+ }
@@ -0,0 +1,6 @@
1
+ export function toScriptJSON(value: unknown): string {
2
+ return JSON.stringify(value)
3
+ .replaceAll('<', String.raw`\u003c`)
4
+ .replaceAll('>', String.raw`\u003e`)
5
+ .replaceAll('&', String.raw`\u0026`);
6
+ }