@authfn/oauth-provider 0.0.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +97 -1
  2. package/dist/authorize/index.d.ts +5 -0
  3. package/dist/authorize/index.d.ts.map +1 -0
  4. package/dist/authorize/index.js +247 -0
  5. package/dist/authorize/index.js.map +1 -0
  6. package/dist/http.d.ts +35 -0
  7. package/dist/http.d.ts.map +1 -0
  8. package/dist/http.js +161 -0
  9. package/dist/http.js.map +1 -0
  10. package/dist/index.d.ts +23 -0
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +52 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/introspection/index.d.ts +13 -0
  15. package/dist/introspection/index.d.ts.map +1 -0
  16. package/dist/introspection/index.js +47 -0
  17. package/dist/introspection/index.js.map +1 -0
  18. package/dist/metadata/index.d.ts +10 -0
  19. package/dist/metadata/index.d.ts.map +1 -0
  20. package/dist/metadata/index.js +41 -0
  21. package/dist/metadata/index.js.map +1 -0
  22. package/dist/pkce.d.ts +4 -0
  23. package/dist/pkce.d.ts.map +1 -0
  24. package/dist/pkce.js +17 -0
  25. package/dist/pkce.js.map +1 -0
  26. package/dist/registration/document.d.ts +49 -0
  27. package/dist/registration/document.d.ts.map +1 -0
  28. package/dist/registration/document.js +167 -0
  29. package/dist/registration/document.js.map +1 -0
  30. package/dist/registration/index.d.ts +38 -0
  31. package/dist/registration/index.d.ts.map +1 -0
  32. package/dist/registration/index.js +264 -0
  33. package/dist/registration/index.js.map +1 -0
  34. package/dist/registration/metadata.d.ts +27 -0
  35. package/dist/registration/metadata.d.ts.map +1 -0
  36. package/dist/registration/metadata.js +74 -0
  37. package/dist/registration/metadata.js.map +1 -0
  38. package/dist/registration/store.d.ts +82 -0
  39. package/dist/registration/store.d.ts.map +1 -0
  40. package/dist/registration/store.js +187 -0
  41. package/dist/registration/store.js.map +1 -0
  42. package/dist/revocation/index.d.ts +12 -0
  43. package/dist/revocation/index.d.ts.map +1 -0
  44. package/dist/revocation/index.js +34 -0
  45. package/dist/revocation/index.js.map +1 -0
  46. package/dist/runtime.d.ts +64 -0
  47. package/dist/runtime.d.ts.map +1 -0
  48. package/dist/runtime.js +228 -0
  49. package/dist/runtime.js.map +1 -0
  50. package/dist/store.d.ts +155 -0
  51. package/dist/store.d.ts.map +1 -0
  52. package/dist/store.js +467 -0
  53. package/dist/store.js.map +1 -0
  54. package/dist/token/code.d.ts +11 -0
  55. package/dist/token/code.d.ts.map +1 -0
  56. package/dist/token/code.js +64 -0
  57. package/dist/token/code.js.map +1 -0
  58. package/dist/token/index.d.ts +5 -0
  59. package/dist/token/index.d.ts.map +1 -0
  60. package/dist/token/index.js +39 -0
  61. package/dist/token/index.js.map +1 -0
  62. package/dist/token/refresh.d.ts +10 -0
  63. package/dist/token/refresh.d.ts.map +1 -0
  64. package/dist/token/refresh.js +47 -0
  65. package/dist/token/refresh.js.map +1 -0
  66. package/dist/types.d.ts +217 -0
  67. package/dist/types.d.ts.map +1 -0
  68. package/dist/types.js +7 -0
  69. package/dist/types.js.map +1 -0
  70. package/package.json +43 -1
package/README.md CHANGED
@@ -1,3 +1,99 @@
1
1
  # @authfn/oauth-provider
2
2
 
3
- Reserved. Real releases come from 21nCo/superfunctions.
3
+ OAuth 2.1 authorization server for AuthFn. It serves:
4
+
5
+ - `GET {basePath}/.well-known/oauth-authorization-server`: metadata (RFC 8414)
6
+ - `GET {basePath}/oauth/authorize`: authorization code with PKCE `S256` only
7
+ - `POST {basePath}/oauth/authorize`: the consent decision
8
+ - `POST {basePath}/oauth/token`: code exchange; refresh with rotation and reuse detection
9
+ - `POST {basePath}/oauth/revoke`: revocation (RFC 7009)
10
+ - `POST {basePath}/oauth/introspect`: introspection (RFC 7662)
11
+ - `POST {basePath}/oauth/register`: dynamic client registration (RFC 7591), when `registration.dynamic` is on
12
+
13
+ Every token is bound to one resource (RFC 8707) and carries the scopes the user granted, using the AuthFn scope registry.
14
+
15
+ ```ts
16
+ import { authfn } from 'authfn';
17
+ import { authFnOAuthProviderPlugin } from '@authfn/oauth-provider';
18
+
19
+ const scopes = { memotron: ['read', 'write'] } as const;
20
+
21
+ const app = authfn({
22
+ scopes,
23
+ plugins: [authFnOAuthProviderPlugin()]
24
+ });
25
+
26
+ const auth = app.createServer({
27
+ database,
28
+ pluginRuntime: {
29
+ oauthProvider: {
30
+ clients: [{ clientId: 'rhombus', name: 'Rhombus', trusted: true, redirectUris: ['https://rhombus.example.com/cb'] }],
31
+ resources: [{
32
+ resource: 'https://memotron.example.com/mcp',
33
+ scopes: ['memotron:read', 'memotron:write'],
34
+ introspectionSecret: env.MEMOTRON_INTROSPECTION_SECRET
35
+ }],
36
+ loginRequired: ({ request, returnTo }) =>
37
+ Response.redirect(new URL(`/sign-in?returnTo=${encodeURIComponent(returnTo)}`, request.url).toString(), 302),
38
+ consent: (input) => renderConsentPage(input)
39
+ }
40
+ }
41
+ });
42
+ ```
43
+
44
+ ## Rules
45
+
46
+ - Access tokens live 1 hour. Refresh tokens live 30 days and rotate on every use. Presenting a rotated refresh token again revokes the whole grant.
47
+ - An authorization code works once, for one minute. When the client it was issued to presents a used code again, with the matching `redirect_uri` and `code_verifier`, the grant and every token issued from it are revoked. Anyone else presenting a used code gets `invalid_grant` and the grant is untouched.
48
+ - The authorization request must send `resource`, which must exactly match a configured resource. `scope` must name scopes that resource offers; without `scope` the client asks for all of them.
49
+ - Redirect URIs match exactly, except that an `http://127.0.0.1` or `http://[::1]` redirect URI may use any port. A registered redirect URI uses `https`, `http` to one of those loopback IPs, or a native app's private-use scheme in reverse domain form such as `com.example.app:/oauth/cb` (RFC 8252 7.1). It must be written in visible ASCII (a non-ASCII host in punycode, anything else percent-encoded), and an `https` or `http` URI must begin with its origin as `scheme://host[:port]` (no `https:host`, backslashes or userinfo), since it is sent as is in the `Location` header. Any other URI, including `http://localhost`, `javascript:`, `data:`, `file:`, `ws:` and a scheme without a dot, is a configuration error. The response is the redirect URI byte for byte followed by the form-encoded response parameters, so a registered query is never rewritten; it must not use `code`, `state`, `iss`, `error`, `error_description` or `error_uri`.
50
+ - Client authentication failures are `invalid_client`: 401 with a `Basic` challenge when the client sent an `Authorization` header, otherwise 400. A public or `client_secret_post` client that sends any `Authorization` header fails.
51
+ - A `trusted` client asks for consent once per resource; later requests within the consented scopes skip the page. Any other client asks every time.
52
+ - Tokens stop working when their grant is revoked or their user is deleted or disabled (`metadata.disabled`).
53
+ - A code or refresh token is spent by a conditional write that also stores a claim ID, and the request that reads its own claim ID back wins; adapter row counts are not used. The new access and refresh tokens are stored first, each recording that claim ID, and a token is valid only while the code or refresh token it was issued for stores the same claim ID. So the claim is the single commit point and nothing is ever undone: a failure before it leaves the credential unspent and the stored tokens inert, and the loser of a concurrent exchange gets nothing usable. If the claim write fails, its read-back still decides, since the write may have committed. After the claim commits, the exchange checks the grant and user again: a disconnect, a revocation or a disabled or deleted user that took effect before the commit gets `invalid_grant`, never tokens; one that takes effect later revokes the tokens delivered. Only when the response is lost after the claim commits (including a lost write acknowledgement whose read-back also fails) is the credential spent without the client holding the tokens; presenting it again is a replay that revokes the grant, so the user authorizes again. Because validity reads the code or parent refresh token row, keep code rows and rotated refresh token rows while a token issued from them can still be valid (up to 30 days after their own refresh token was issued); deleting them makes those tokens inactive.
54
+
55
+ ## Client registration
56
+
57
+ MCP hosts and other public clients can register themselves. Both ways are off until `pluginRuntime.oauthProvider.registration` turns them on:
58
+
59
+ ```ts
60
+ registration: {
61
+ dynamic: true, // RFC 7591 at {basePath}/oauth/register
62
+ metadataDocuments: true, // an https client_id URL serving the client's metadata
63
+ rateLimit: { perIp: 20, global: 200, windowSeconds: 3600 }, // the defaults
64
+ // Only behind Cloudflare, which overwrites cf-connecting-ip; see below.
65
+ resolveClientIp: (request) => request.headers.get('cf-connecting-ip') ?? undefined,
66
+ fetch: egressRestrictedFetch // required with metadataDocuments
67
+ }
68
+ ```
69
+
70
+ `resolveClientIp` must return an address that your own ingress sets, never a header a caller can send: `cf-connecting-ip` only when every request passes through Cloudflare, which overwrites it, and `x-forwarded-for` only as appended by a proxy you run. Otherwise a caller picks a new "IP" for each request and only the overall limit holds.
71
+
72
+ - Only public clients are accepted: `token_endpoint_auth_method` must be `none` (or absent), and metadata carrying `client_secret` is refused with `invalid_client_metadata`. `grant_types`, when supplied, must include `authorization_code` and may add `refresh_token`; `response_types` may only be `code`. Other metadata is ignored.
73
+ - `redirect_uris` lists 1 to 10 URIs, each `https` or `http://127.0.0.1[:port]` (the port may vary at authorization), under the same rules as configured redirect URIs; anything else, including `http://localhost`, `http://[::1]` and native app schemes, is `invalid_redirect_uri`. An authorization request whose `redirect_uri` is not registered is refused without a redirect.
74
+ - A registered client is never `trusted`: it asks for consent on every authorization. Its name on the consent page is its `client_name`, or its `client_id` without one. RFC 7592 client management is not offered, and registered clients keep working after `dynamic` is turned off, which only stops new registrations.
75
+ - **Client ID Metadata Documents.** A `client_id` that is an `https` URL is resolved by fetching it. The URL must have a path and no query, fragment or credentials (not even an empty `?` or `#`), be written in normalized form, be at most 255 characters, and name a public DNS host of valid labels: IP literals, single-label names, empty labels such as `foo..example.com` and `localhost`, `.local`, `.internal`, `.localdomain` and `.home.arpa` names are refused without a request. The fetch does not follow redirects, must answer `200` within 5 seconds (body included) and at most 64 KB, and the document must name that exact URL as its `client_id` and pass the registration rules above. A usable document is stored and shared by every instance. A known client (one that has served a usable document) is refetched at most once per 5 minutes across all instances, so a changed document takes effect within about 10 minutes. These refetches are not rate-limited and do not use up the limit, so flooding only refuses new clients. When the host gives no usable answer (a network error, no complete answer within 5 seconds, a `5xx`, `408` or `429`), a known client keeps its last document. Any other answer that is not a usable UTF-8 JSON document makes the client unknown and drops its stored document. Only the request holding the current refetch claim stores or drops what it fetched; a refetch that stalls past its 5-minute claim, or runs on an instance whose clock is behind, changes nothing and serves the document stored by the newer claim. A public host name can still resolve to a private address, so `metadataDocuments` requires a `fetch` and the server refuses to start without one: pass one that cannot reach private or internal addresses (for example through an egress proxy that refuses them). Where the platform's own `fetch` already cannot reach them, pass that explicitly.
76
+ - **Rate limit.** Registrations and first fetches of unknown metadata document clients are limited separately, per client IP and overall, in fixed windows stored in the database, so every instance shares them. Over the limit the answer is `429` `temporarily_unavailable` with `Retry-After`. Without `resolveClientIp` (or AuthFn's `rateLimit.resolveClientIp`) only the overall limit applies. Concurrent requests never exceed a limit; at its edge they may all be refused, and refused requests do not use it up. A registration body must arrive complete within 5 seconds and be at most 64 KB, so a slow upload cannot hold a request open before it is counted.
77
+ - **Storage.** Registration uses the tables `oauth_provider_clients`, `oauth_provider_document_clients` and `oauth_provider_registration_events`. A custom plugin `schema` that leaves them out gets them added (one it defines itself is kept), so migrate them even while registration is off.
78
+
79
+ ## Host responsibilities
80
+
81
+ **Metadata path.** RFC 8414 clients look for `/.well-known/oauth-authorization-server` at the issuer's origin, followed by the issuer's path when it has one (RFC 8414 3.1): for the issuer `https://auth.example.com/tenant` that is `https://auth.example.com/.well-known/oauth-authorization-server/tenant`. Route that path to `{basePath}/.well-known/oauth-authorization-server`. The issuer is the AuthFn environment's `issuer` (the request origin by default).
82
+
83
+ **Consent page.** `consent` receives the user, client, resource, scopes, the validated `params` and a `decisionUrl`. The page POSTs `{ ...params, decision: 'approve' | 'deny' }` as JSON to `decisionUrl` with the session cookie and the `x-authfn-csrf` header, then sends the browser to `data.redirectTo`.
84
+
85
+ **Resource servers.** A remote resource server calls the introspection endpoint with `Authorization: Bearer <introspectionSecret>`; the secret must be an RFC 6750 `b64token` (letters, digits and `-._~+/`, optionally ending in `=`). Only access tokens issued for that resource are reported active. The response leaves out the optional `iss`, because tokens do not record the issuer they were issued under. A resource server in the same process can call `verifyOAuthAccessToken`:
86
+
87
+ ```ts
88
+ import { requireScopes } from 'authfn';
89
+ import { verifyOAuthAccessToken } from '@authfn/oauth-provider';
90
+
91
+ // Use the same database and namespace as the AuthFn server (`namespace` defaults to 'authfn').
92
+ const store = { database, namespace: 'authfn' };
93
+ const token = await verifyOAuthAccessToken(store, bearer, { resource: 'https://memotron.example.com/mcp' });
94
+ requireScopes(token, 'memotron:read', { registry: scopes });
95
+ ```
96
+
97
+ **Disconnecting an app.** `disconnectOAuthClient(store, { userId, clientId, resource })` removes the user's consent for that client and resource, so even a trusted client shows the consent page again, and revokes every grant the user gave that client for that resource: each authorization creates its own grant, so a client signed in on two devices holds two. Every code, access token and refresh token under those grants stops working. `revokeOAuthGrant(store, grantId, { userId })` does the same for the client and resource of one grant, for example the `grantId` that `verifyOAuthAccessToken` returns. A disconnect first writes a new disconnect generation for the user, client and resource: a row found by the triple (concurrent first disconnects may add a second), holding a value never used before. An authorization reads the generation before it reads or records consent, and records and reads consent for that generation only, so an approval begun before a disconnect never authorizes anything after it. It reads the generation again after it creates its grant; when it changed, it revokes that grant and deletes the consent it recorded. So an authorization in progress while the app is disconnected issues no usable code and leaves no consent: the silent path of a trusted client shows the consent page and an approval redirects with `access_denied`. Each approval stores a consent row with the union of the approvals it read, then deletes the rows it read, so the remembered scopes are the union of the rows, concurrent approvals do not overwrite each other, and a user, client and resource keep one row apart from approvals that ran concurrently.
98
+
99
+ Account deletion in `authfn` does not yet delete this plugin's rows. Tokens of a deleted user stop working, but the rows remain.
@@ -0,0 +1,5 @@
1
+ import type { Route } from '@superfunctions/http';
2
+ import { type OAuthProviderRuntime } from '../runtime.js';
3
+ export declare const OAUTH_AUTHORIZE_PATH = "/oauth/authorize";
4
+ export declare function createAuthorizeRoutes(runtime: OAuthProviderRuntime): Route[];
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/authorize/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAOlD,OAAO,EAKL,KAAK,oBAAoB,EAC1B,MAAM,eAAe,CAAC;AAWvB,eAAO,MAAM,oBAAoB,qBAAqB,CAAC;AAwKvD,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,oBAAoB,GAAG,KAAK,EAAE,CAmH5E"}
@@ -0,0 +1,247 @@
1
+ import { AuthFnValidationError } from 'authfn/core/errors';
2
+ import { assertValidCsrf, getCookieSessionState, requireCookieSession } from 'authfn/core/sessions';
3
+ import { createAuthFnRouteMeta, readOptionalJson } from 'authfn/http/router';
4
+ import { jsonSuccess } from 'authfn/http/envelopes';
5
+ import { OAuthError, oauthErrorResponse, readSingleParams } from '../http.js';
6
+ import { isS256Challenge } from '../pkce.js';
7
+ import { matchesRedirectUri, requireResource, resolveEndpoints, resolveRequestedScopes } from '../runtime.js';
8
+ import { createGrantWithCode, deleteConsent, findConsentScopes, readGeneration, recordConsent, revokeGrant } from '../store.js';
9
+ export const OAUTH_AUTHORIZE_PATH = '/oauth/authorize';
10
+ /**
11
+ * Validates an authorization request (RFC 6749 4.1.1, RFC 7636 4.3, RFC 8707
12
+ * 2). A problem with `client_id` or `redirect_uri` throws, because the client
13
+ * cannot be trusted with a redirect (RFC 6749 4.1.2.1); anything else is
14
+ * returned for an error redirect.
15
+ */
16
+ async function validateAuthorizationRequest(runtime, request, params) {
17
+ const clientId = params.get('client_id');
18
+ const client = clientId ? await runtime.resolveClient(clientId, request) : undefined;
19
+ if (!client) {
20
+ throw new OAuthError('invalid_request', 'Unknown client_id');
21
+ }
22
+ const redirectUri = params.get('redirect_uri');
23
+ if (!redirectUri || !matchesRedirectUri(client, redirectUri)) {
24
+ throw new OAuthError('invalid_request', 'redirect_uri is missing or not registered for this client');
25
+ }
26
+ const state = params.get('state');
27
+ try {
28
+ if (params.get('response_type') !== 'code') {
29
+ throw new OAuthError('unsupported_response_type', 'Only response_type=code is supported');
30
+ }
31
+ const challenge = params.get('code_challenge');
32
+ if (params.get('code_challenge_method') !== 'S256' || !challenge || !isS256Challenge(challenge)) {
33
+ throw new OAuthError('invalid_request', 'PKCE with code_challenge_method=S256 is required');
34
+ }
35
+ const resource = requireResource(runtime, params.get('resource'));
36
+ const scopes = resolveRequestedScopes(resource, params.get('scope'));
37
+ return {
38
+ ok: true,
39
+ client,
40
+ scopes,
41
+ params: {
42
+ response_type: 'code',
43
+ client_id: client.clientId,
44
+ redirect_uri: redirectUri,
45
+ scope: scopes.join(' '),
46
+ ...(state === undefined ? {} : { state }),
47
+ code_challenge: challenge,
48
+ code_challenge_method: 'S256',
49
+ resource: resource.resource
50
+ }
51
+ };
52
+ }
53
+ catch (error) {
54
+ if (error instanceof OAuthError) {
55
+ return { ok: false, redirectUri, state, error };
56
+ }
57
+ throw error;
58
+ }
59
+ }
60
+ /** Validates, answering a client or redirect URI problem directly. */
61
+ async function validateOrRespond(runtime, request, readParams) {
62
+ try {
63
+ return await validateAuthorizationRequest(runtime, request, readParams());
64
+ }
65
+ catch (error) {
66
+ if (error instanceof OAuthError) {
67
+ return oauthErrorResponse(error);
68
+ }
69
+ throw error;
70
+ }
71
+ }
72
+ /**
73
+ * Builds the redirect back to the client, with `iss` (RFC 9207): the
74
+ * redirect URI byte for byte, then the form-encoded response parameters
75
+ * (RFC 6749 3.1.2). The registered query is never parsed and reserialized;
76
+ * configuration rejects one that uses a response parameter name, so they
77
+ * never collide.
78
+ */
79
+ async function clientRedirectUrl(runtime, request, redirectUri, values) {
80
+ const response = new URLSearchParams();
81
+ for (const [name, value] of Object.entries(values)) {
82
+ if (value !== undefined) {
83
+ response.append(name, value);
84
+ }
85
+ }
86
+ response.append('iss', (await resolveEndpoints(runtime, request)).issuer);
87
+ // An empty query is a '?' that is the first and last character.
88
+ const query = redirectUri.indexOf('?');
89
+ let separator = '&';
90
+ if (query < 0) {
91
+ separator = '?';
92
+ }
93
+ else if (query === redirectUri.length - 1 || redirectUri.endsWith('&')) {
94
+ separator = '';
95
+ }
96
+ return `${redirectUri}${separator}${response.toString()}`;
97
+ }
98
+ function errorRedirectValues(error, state) {
99
+ return { error: error.error, error_description: error.description, state };
100
+ }
101
+ function isPlainObject(value) {
102
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
103
+ }
104
+ function redirect(location) {
105
+ return new Response(null, { status: 302, headers: { location, 'cache-control': 'no-store' } });
106
+ }
107
+ function consentCovers(consented, scopes) {
108
+ return consented !== null && scopes.every((scope) => consented.includes(scope));
109
+ }
110
+ /**
111
+ * Creates the grant and its code: for an approval (`approved`), after
112
+ * recording the consent; otherwise only when remembered consent covers the
113
+ * scopes. Returns `null` when there is no such consent or the app was
114
+ * disconnected meanwhile. The disconnect generation is read before consent
115
+ * and again after the grant exists (see `disconnectOAuthClient`); consent is
116
+ * recorded and read for that generation only, so an approval begun before a
117
+ * disconnect never authorizes anything after it. On a new generation this
118
+ * authorization revokes its grant and removes the consent it recorded.
119
+ */
120
+ async function issueCode(runtime, user, request, approved) {
121
+ const { store } = runtime;
122
+ const triple = { clientId: request.client.clientId, userId: user.id, resource: request.params.resource };
123
+ const generation = await readGeneration(store, triple);
124
+ const consentId = approved
125
+ ? await recordConsent(store, { ...triple, scopes: request.scopes, generation, now: runtime.now() })
126
+ : undefined;
127
+ if (!consentCovers(await findConsentScopes(store, triple, generation), request.scopes)) {
128
+ return null;
129
+ }
130
+ const { grantId, code } = await createGrantWithCode(store, {
131
+ ...triple,
132
+ scopes: request.scopes,
133
+ redirectUri: request.params.redirect_uri,
134
+ codeChallenge: request.params.code_challenge,
135
+ now: runtime.now()
136
+ });
137
+ if (await readGeneration(store, triple) === generation &&
138
+ consentCovers(await findConsentScopes(store, triple, generation), request.scopes)) {
139
+ return { code, state: request.params.state };
140
+ }
141
+ await revokeGrant(store, grantId, 'consent_withdrawn', runtime.now());
142
+ if (consentId) {
143
+ await deleteConsent(store, consentId);
144
+ }
145
+ return null;
146
+ }
147
+ export function createAuthorizeRoutes(runtime) {
148
+ return [
149
+ {
150
+ method: 'GET',
151
+ path: OAUTH_AUTHORIZE_PATH,
152
+ meta: createAuthFnRouteMeta('oauthAuthorize', 'OAuth 2.1 authorization endpoint', { mode: 'hybrid' }),
153
+ handler: async (request) => {
154
+ const validated = await validateOrRespond(runtime, request, () => readSingleParams(new URL(request.url).searchParams));
155
+ if (validated instanceof Response) {
156
+ return validated;
157
+ }
158
+ if (!validated.ok) {
159
+ return redirect(await clientRedirectUrl(runtime, request, validated.redirectUri, errorRedirectValues(validated.error, validated.state)));
160
+ }
161
+ const state = await getCookieSessionState(runtime.ctx.config, request);
162
+ if (!state.session || !state.user) {
163
+ return runtime.config.loginRequired({ request, returnTo: request.url });
164
+ }
165
+ const user = { id: state.user.id, primaryEmail: state.user.primaryEmail };
166
+ if (validated.client.trusted) {
167
+ // Without a code there is no remembered consent: ask for it.
168
+ const values = await issueCode(runtime, user, validated, false);
169
+ if (values) {
170
+ return redirect(await clientRedirectUrl(runtime, request, validated.params.redirect_uri, values));
171
+ }
172
+ }
173
+ return runtime.config.consent({
174
+ request,
175
+ user,
176
+ client: {
177
+ clientId: validated.client.clientId,
178
+ name: validated.client.name,
179
+ trusted: validated.client.trusted === true
180
+ },
181
+ resource: validated.params.resource,
182
+ scopes: validated.scopes,
183
+ params: validated.params,
184
+ decisionUrl: (await resolveEndpoints(runtime, request)).authorization
185
+ });
186
+ }
187
+ },
188
+ {
189
+ method: 'POST',
190
+ path: OAUTH_AUTHORIZE_PATH,
191
+ meta: createAuthFnRouteMeta('oauthAuthorizeDecision', 'Record the consent decision for an OAuth authorization', {
192
+ mode: 'cookie-session',
193
+ csrf: true
194
+ }),
195
+ handler: async (request) => {
196
+ const session = await requireCookieSession(runtime.ctx.config, request);
197
+ assertValidCsrf(request, session);
198
+ let body;
199
+ try {
200
+ body = await readOptionalJson(request);
201
+ }
202
+ catch (error) {
203
+ if (error instanceof AuthFnValidationError) {
204
+ return oauthErrorResponse(new OAuthError('invalid_request', 'The decision body must be valid JSON'));
205
+ }
206
+ throw error;
207
+ }
208
+ if (!isPlainObject(body)) {
209
+ return oauthErrorResponse(new OAuthError('invalid_request', 'The decision body must be a JSON object'));
210
+ }
211
+ const params = new Map();
212
+ const validated = await validateOrRespond(runtime, request, () => {
213
+ for (const [name, value] of Object.entries(body)) {
214
+ if (typeof value !== 'string') {
215
+ throw new OAuthError('invalid_request', `Parameter ${name} must be a string`);
216
+ }
217
+ params.set(name, value);
218
+ }
219
+ return params;
220
+ });
221
+ if (validated instanceof Response) {
222
+ return validated;
223
+ }
224
+ const decision = params.get('decision');
225
+ let values;
226
+ if (!validated.ok) {
227
+ values = errorRedirectValues(validated.error, validated.state);
228
+ }
229
+ else if (decision === 'approve') {
230
+ const user = { id: session.user.id, primaryEmail: session.user.primaryEmail };
231
+ values = await issueCode(runtime, user, validated, true) ?? errorRedirectValues(new OAuthError('access_denied', 'The authorization was withdrawn while it was being approved'), validated.params.state);
232
+ }
233
+ else if (decision === 'deny') {
234
+ values = errorRedirectValues(new OAuthError('access_denied', 'The user denied the authorization request'), validated.params.state);
235
+ }
236
+ else {
237
+ return oauthErrorResponse(new OAuthError('invalid_request', 'decision must be approve or deny'));
238
+ }
239
+ const redirectUri = validated.ok ? validated.params.redirect_uri : validated.redirectUri;
240
+ return jsonSuccess(request, {
241
+ redirectTo: await clientRedirectUrl(runtime, request, redirectUri, values)
242
+ }, { headers: { 'cache-control': 'no-store' } });
243
+ }
244
+ }
245
+ ];
246
+ }
247
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/authorize/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAAE,eAAe,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AACpG,OAAO,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAC7E,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAAE,UAAU,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9E,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,EACL,kBAA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7E,IAAI,UAAU,CAAC,eAAe,EAAE,6DAA6D,CAAC,EAC9F,SAAS,CAAC,MAAM,CAAC,KAAK,CACvB,CAAC;gBACJ,CAAC;qBAAM,IAAI,QAAQ,KAAK,MAAM,EAAE,CAAC;oBAC/B,MAAM,GAAG,mBAAmB,CAC1B,IAAI,UAAU,CAAC,eAAe,EAAE,2CAA2C,CAAC,EAC5E,SAAS,CAAC,MAAM,CAAC,KAAK,CACvB,CAAC;gBACJ,CAAC;qBAAM,CAAC;oBACN,OAAO,kBAAkB,CAAC,IAAI,UAAU,CAAC,iBAAiB,EAAE,kCAAkC,CAAC,CAAC,CAAC;gBACnG,CAAC;gBAED,MAAM,WAAW,GAAG,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC,CAAC,SAAS,CAAC,WAAW,CAAC;gBACzF,OAAO,WAAW,CAAC,OAAO,EAAE;oBAC1B,UAAU,EAAE,MAAM,iBAAiB,CAAC,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,CAAC;iBAC3E,EAAE,EAAE,OAAO,EAAE,EAAE,eAAe,EAAE,UAAU,EAAE,EAAE,CAAC,CAAC;YACnD,CAAC;SACF;KACF,CAAC;AACJ,CAAC"}
package/dist/http.d.ts ADDED
@@ -0,0 +1,35 @@
1
+ import type { OAuthProviderClient } from './types.js';
2
+ import type { OAuthProviderRuntime } from './runtime.js';
3
+ export type OAuthErrorCode = 'invalid_request' | 'invalid_client' | 'invalid_grant' | 'unsupported_grant_type' | 'invalid_scope' | 'invalid_target' | 'access_denied' | 'unsupported_response_type' | 'invalid_token' | 'invalid_redirect_uri' | 'invalid_client_metadata' | 'temporarily_unavailable';
4
+ /** An OAuth protocol error, rendered as RFC 6749 5.2 JSON or an error redirect. */
5
+ export declare class OAuthError extends Error {
6
+ readonly error: OAuthErrorCode;
7
+ readonly description: string;
8
+ readonly status: number;
9
+ readonly headers: Record<string, string>;
10
+ constructor(error: OAuthErrorCode, description: string, status?: number, headers?: Record<string, string>);
11
+ }
12
+ export declare function oauthJson(body: unknown, status?: number, headers?: Record<string, string>): Response;
13
+ export declare function oauthErrorResponse(error: OAuthError): Response;
14
+ /** Runs an endpoint body, rendering OAuth errors as RFC 6749 5.2 responses. */
15
+ export declare function handleOAuth(body: () => Promise<Response>): Promise<Response>;
16
+ /**
17
+ * Reads a single-valued parameter set. A parameter sent more than once is an
18
+ * `invalid_request` (RFC 6749 3.1, 3.2).
19
+ */
20
+ export declare function readSingleParams(params: URLSearchParams): Map<string, string>;
21
+ /** Reads an `application/x-www-form-urlencoded` POST body (RFC 6749 3.2). */
22
+ export declare function readFormBody(request: Request): Promise<Map<string, string>>;
23
+ export declare function requireParam(params: Map<string, string>, name: string): string;
24
+ /** Compares two secrets in time that depends only on their lengths. */
25
+ export declare function secretsEqual(actual: string, expected: string): boolean;
26
+ /**
27
+ * Authenticates the client at the token or revocation endpoint (RFC 6749
28
+ * 2.3.1). A public client sends only `client_id`; a confidential client uses
29
+ * the method it is registered with. Failures are `invalid_client`.
30
+ */
31
+ export declare function authenticateClient(runtime: OAuthProviderRuntime, request: Request, params: Map<string, string>): Promise<OAuthProviderClient>;
32
+ export declare function isBearerCredential(value: string): boolean;
33
+ /** The credential of an `Authorization: Bearer 1*SP <b64token>` header (RFC 6750 2.1), or null. */
34
+ export declare function readBearerToken(request: Request): string | null;
35
+ //# sourceMappingURL=http.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../src/http.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AACtD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAEzD,MAAM,MAAM,cAAc,GACtB,iBAAiB,GACjB,gBAAgB,GAChB,eAAe,GACf,wBAAwB,GACxB,eAAe,GACf,gBAAgB,GAChB,eAAe,GACf,2BAA2B,GAC3B,eAAe,GAC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,OAAO,EAAE,oBAAoB,EAC7B,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,GAC1B,OAAO,CAAC,mBAAmB,CAAC,CAmC9B;AA0CD,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAEzD;AAED,mGAAmG;AACnG,wBAAgB,eAAe,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAK/D"}
package/dist/http.js ADDED
@@ -0,0 +1,161 @@
1
+ import { timingSafeEqual } from 'node:crypto';
2
+ /** An OAuth protocol error, rendered as RFC 6749 5.2 JSON or an error redirect. */
3
+ export class OAuthError extends Error {
4
+ error;
5
+ description;
6
+ status;
7
+ headers;
8
+ constructor(error, description, status = error === 'invalid_client' || error === 'invalid_token' ? 401 : 400, headers = {}) {
9
+ super(description);
10
+ this.error = error;
11
+ this.description = description;
12
+ this.status = status;
13
+ this.headers = headers;
14
+ this.name = 'OAuthError';
15
+ }
16
+ }
17
+ const NO_STORE = { 'cache-control': 'no-store', pragma: 'no-cache' };
18
+ export function oauthJson(body, status = 200, headers = {}) {
19
+ return new Response(JSON.stringify(body), {
20
+ status,
21
+ headers: { 'content-type': 'application/json', ...NO_STORE, ...headers }
22
+ });
23
+ }
24
+ export function oauthErrorResponse(error) {
25
+ return oauthJson({ error: error.error, error_description: error.description }, error.status, error.headers);
26
+ }
27
+ /** Runs an endpoint body, rendering OAuth errors as RFC 6749 5.2 responses. */
28
+ export async function handleOAuth(body) {
29
+ try {
30
+ return await body();
31
+ }
32
+ catch (error) {
33
+ if (error instanceof OAuthError) {
34
+ return oauthErrorResponse(error);
35
+ }
36
+ throw error;
37
+ }
38
+ }
39
+ /**
40
+ * Reads a single-valued parameter set. A parameter sent more than once is an
41
+ * `invalid_request` (RFC 6749 3.1, 3.2).
42
+ */
43
+ export function readSingleParams(params) {
44
+ const values = new Map();
45
+ for (const [name, value] of params) {
46
+ if (values.has(name)) {
47
+ throw new OAuthError('invalid_request', `Parameter ${name} must not be repeated`);
48
+ }
49
+ values.set(name, value);
50
+ }
51
+ return values;
52
+ }
53
+ /** Reads an `application/x-www-form-urlencoded` POST body (RFC 6749 3.2). */
54
+ export async function readFormBody(request) {
55
+ const contentType = request.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase();
56
+ if (contentType !== 'application/x-www-form-urlencoded') {
57
+ throw new OAuthError('invalid_request', 'Request body must be application/x-www-form-urlencoded');
58
+ }
59
+ return readSingleParams(new URLSearchParams(await request.text()));
60
+ }
61
+ export function requireParam(params, name) {
62
+ const value = params.get(name);
63
+ if (!value) {
64
+ throw new OAuthError('invalid_request', `Parameter ${name} is required`);
65
+ }
66
+ return value;
67
+ }
68
+ /** Compares two secrets in time that depends only on their lengths. */
69
+ export function secretsEqual(actual, expected) {
70
+ const presented = Buffer.from(actual, 'utf8');
71
+ const stored = Buffer.from(expected, 'utf8');
72
+ return presented.length === stored.length && timingSafeEqual(presented, stored);
73
+ }
74
+ function clientAuthMethod(client) {
75
+ return client.tokenEndpointAuthMethod ?? (client.clientSecret ? 'client_secret_basic' : 'none');
76
+ }
77
+ /**
78
+ * Authenticates the client at the token or revocation endpoint (RFC 6749
79
+ * 2.3.1). A public client sends only `client_id`; a confidential client uses
80
+ * the method it is registered with. Failures are `invalid_client`.
81
+ */
82
+ export async function authenticateClient(runtime, request, params) {
83
+ const basic = readBasicCredentials(request);
84
+ // Any Authorization header is an attempt to authenticate with it (RFC 6749 5.2).
85
+ const viaHeader = request.headers.has('authorization');
86
+ const bodyId = params.get('client_id');
87
+ const clientId = basic?.clientId ?? bodyId;
88
+ if (!clientId || (basic && bodyId !== undefined && bodyId !== basic.clientId)) {
89
+ throw invalidClient(viaHeader);
90
+ }
91
+ const client = await runtime.resolveClient(clientId, request);
92
+ if (!client) {
93
+ throw invalidClient(viaHeader);
94
+ }
95
+ const method = clientAuthMethod(client);
96
+ let presented;
97
+ if (method === 'client_secret_basic') {
98
+ presented = basic?.clientSecret;
99
+ }
100
+ else if (method === 'client_secret_post') {
101
+ presented = params.get('client_secret');
102
+ }
103
+ // A client not registered for Basic must not send an Authorization header
104
+ // of any scheme, parsable or not (RFC 6749 2.3: one method per request).
105
+ const sentOtherCredential = method === 'client_secret_basic'
106
+ ? params.has('client_secret')
107
+ : viaHeader || (method === 'none' && params.has('client_secret'));
108
+ if (sentOtherCredential) {
109
+ throw invalidClient(viaHeader);
110
+ }
111
+ if (method !== 'none' && (!presented || !client.clientSecret || !secretsEqual(presented, client.clientSecret))) {
112
+ throw invalidClient(viaHeader);
113
+ }
114
+ return client;
115
+ }
116
+ /**
117
+ * RFC 6749 5.2: 401 with a Basic challenge when the client tried the
118
+ * Authorization header; otherwise 400, without a challenge.
119
+ */
120
+ function invalidClient(viaHeader) {
121
+ return viaHeader
122
+ ? new OAuthError('invalid_client', 'Client authentication failed', 401, { 'www-authenticate': 'Basic realm="oauth"' })
123
+ : new OAuthError('invalid_client', 'Client authentication failed', 400);
124
+ }
125
+ function readBasicCredentials(request) {
126
+ const header = request.headers.get('authorization')?.trim();
127
+ if (!header || !/^basic /i.test(header)) {
128
+ return null;
129
+ }
130
+ const decoded = Buffer.from(header.slice(6).trim(), 'base64').toString('utf8');
131
+ const separator = decoded.indexOf(':');
132
+ if (separator <= 0) {
133
+ throw invalidClient(true);
134
+ }
135
+ // RFC 6749 2.3.1: both halves are form-urlencoded before Basic encoding.
136
+ try {
137
+ return {
138
+ clientId: formDecode(decoded.slice(0, separator)),
139
+ clientSecret: formDecode(decoded.slice(separator + 1))
140
+ };
141
+ }
142
+ catch {
143
+ throw invalidClient(true);
144
+ }
145
+ }
146
+ function formDecode(value) {
147
+ return decodeURIComponent(value.replaceAll('+', ' '));
148
+ }
149
+ /** RFC 6750 2.1 `b64token`; the classes are disjoint, so matching is linear. */
150
+ const BEARER_CREDENTIAL = /^[A-Za-z0-9\-._~+/]+=*$/;
151
+ export function isBearerCredential(value) {
152
+ return BEARER_CREDENTIAL.test(value);
153
+ }
154
+ /** The credential of an `Authorization: Bearer 1*SP <b64token>` header (RFC 6750 2.1), or null. */
155
+ export function readBearerToken(request) {
156
+ const header = request.headers.get('authorization')?.trim() ?? '';
157
+ const scheme = /^bearer +/i.exec(header);
158
+ const token = scheme ? header.slice(scheme[0].length) : '';
159
+ return isBearerCredential(token) ? token : null;
160
+ }
161
+ //# sourceMappingURL=http.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.js","sourceRoot":"","sources":["../src/http.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAkB9C,mFAAmF;AACnF,MAAM,OAAO,UAAW,SAAQ,KAAK;IAExB;IACA;IACA;IACA;IAJX,YACW,KAAqB,EACrB,WAAmB,EACnB,SAAiB,KAAK,KAAK,gBAAgB,IAAI,KAAK,KAAK,eAAe,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EACpF,UAAkC,EAAE;QAE7C,KAAK,CAAC,WAAW,CAAC,CAAC;QALV,UAAK,GAAL,KAAK,CAAgB;QACrB,gBAAW,GAAX,WAAW,CAAQ;QACnB,WAAM,GAAN,MAAM,CAA8E;QACpF,YAAO,GAAP,OAAO,CAA6B;QAG7C,IAAI,CAAC,IAAI,GAAG,YAAY,CAAC;IAC3B,CAAC;CACF;AAED,MAAM,QAAQ,GAAG,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC;AAErE,MAAM,UAAU,SAAS,CAAC,IAAa,EAAE,MAAM,GAAG,GAAG,EAAE,UAAkC,EAAE;IACzF,OAAO,IAAI,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE;QACxC,MAAM;QACN,OAAO,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE,GAAG,QAAQ,EAAE,GAAG,OAAO,EAAE;KACzE,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,KAAiB;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AC,KAAa;IAC/B,OAAO,kBAAkB,CAAC,KAAK,CAAC,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC;AACxD,CAAC;AAED,gFAAgF;AAChF,MAAM,iBAAiB,GAAG,yBAAyB,CAAC;AAEpD,MAAM,UAAU,kBAAkB,CAAC,KAAa;IAC9C,OAAO,iBAAiB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACvC,CAAC;AAED,mGAAmG;AACnG,MAAM,UAAU,eAAe,CAAC,OAAgB;IAC9C,MAAM,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IAClE,MAAM,MAAM,GAAG,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACzC,MAAM,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IAC3D,OAAO,kBAAkB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;AAClD,CAAC"}
@@ -0,0 +1,23 @@
1
+ import type { AuthFnPlugin } from 'authfn';
2
+ import { OAUTH_PROVIDER_PLUGIN_NAME } from './runtime.js';
3
+ import type { OAuthProviderPluginConfig, OAuthProviderPluginRuntimeConfig } from './types.js';
4
+ export { OAUTH_AUTHORIZE_PATH } from './authorize/index.js';
5
+ export { OAUTH_INTROSPECTION_PATH } from './introspection/index.js';
6
+ export { OAUTH_METADATA_PATH } from './metadata/index.js';
7
+ export { OAUTH_REGISTRATION_PATH } from './registration/index.js';
8
+ export { OAUTH_REVOCATION_PATH } from './revocation/index.js';
9
+ export { OAUTH_TOKEN_PATH } from './token/index.js';
10
+ export { disconnectOAuthClient, revokeOAuthGrant, verifyOAuthAccessToken, type OAuthStore } from './store.js';
11
+ export * from './types.js';
12
+ /**
13
+ * OAuth 2.1 authorization server for AuthFn: RFC 8414 metadata, the
14
+ * authorization endpoint (authorization code with PKCE S256 only), the token
15
+ * endpoint (code exchange; refresh with rotation and reuse detection),
16
+ * revocation (RFC 7009) and introspection (RFC 7662). Every token is bound to
17
+ * one resource (RFC 8707) and carries the granted AuthFn scopes. Public
18
+ * clients such as MCP hosts can register themselves (RFC 7591) or use a
19
+ * Client ID Metadata Document URL as their `client_id` when `registration`
20
+ * enables it.
21
+ */
22
+ export declare function authFnOAuthProviderPlugin(config?: OAuthProviderPluginConfig): AuthFnPlugin<typeof OAUTH_PROVIDER_PLUGIN_NAME, OAuthProviderPluginRuntimeConfig, true>;
23
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAW3C,OAAO,EAEL,0BAA0B,EAE3B,MAAM,cAAc,CAAC;AAGtB,OAAO,KAAK,EAAE,yBAAyB,EAAE,gCAAgC,EAAE,MAAM,YAAY,CAAC;AAE9F,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAC5D,OAAO,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AACpE,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAC9D,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,sBAAsB,EAAE,KAAK,UAAU,EAAE,MAAM,YAAY,CAAC;AAC9G,cAAc,YAAY,CAAC;AAE3B;;;;;;;;;GASG;AACH,wBAAgB,yBAAyB,CACvC,MAAM,GAAE,yBAA8B,GACrC,YAAY,CAAC,OAAO,0BAA0B,EAAE,gCAAgC,EAAE,IAAI,CAAC,CAwBzF"}