@atproto/oauth-client 0.7.8 → 0.7.9
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.
- package/CHANGELOG.md +18 -0
- package/dist/fetch-dpop.d.ts +3 -3
- package/dist/fetch-dpop.d.ts.map +1 -1
- package/dist/fetch-dpop.js +1 -1
- package/dist/fetch-dpop.js.map +1 -1
- package/dist/lock.d.ts +1 -1
- package/dist/lock.d.ts.map +1 -1
- package/dist/lock.js.map +1 -1
- package/dist/oauth-authorization-server-metadata-resolver.d.ts +3 -3
- package/dist/oauth-authorization-server-metadata-resolver.d.ts.map +1 -1
- package/dist/oauth-authorization-server-metadata-resolver.js.map +1 -1
- package/dist/oauth-client-auth.d.ts +5 -5
- package/dist/oauth-client-auth.d.ts.map +1 -1
- package/dist/oauth-client-auth.js.map +1 -1
- package/dist/oauth-client.d.ts +12 -12
- package/dist/oauth-client.d.ts.map +1 -1
- package/dist/oauth-client.js.map +1 -1
- package/dist/oauth-protected-resource-metadata-resolver.d.ts +3 -3
- package/dist/oauth-protected-resource-metadata-resolver.d.ts.map +1 -1
- package/dist/oauth-protected-resource-metadata-resolver.js.map +1 -1
- package/dist/oauth-resolver.d.ts +4 -4
- package/dist/oauth-resolver.d.ts.map +1 -1
- package/dist/oauth-resolver.js.map +1 -1
- package/dist/oauth-response-error.d.ts +1 -1
- package/dist/oauth-response-error.d.ts.map +1 -1
- package/dist/oauth-response-error.js.map +1 -1
- package/dist/oauth-server-agent.d.ts +9 -9
- package/dist/oauth-server-agent.d.ts.map +1 -1
- package/dist/oauth-server-agent.js +1 -1
- package/dist/oauth-server-agent.js.map +1 -1
- package/dist/oauth-server-factory.d.ts +9 -9
- package/dist/oauth-server-factory.d.ts.map +1 -1
- package/dist/oauth-server-factory.js.map +1 -1
- package/dist/oauth-session.d.ts +5 -5
- package/dist/oauth-session.d.ts.map +1 -1
- package/dist/oauth-session.js.map +1 -1
- package/dist/runtime-implementation.d.ts +2 -2
- package/dist/runtime-implementation.d.ts.map +1 -1
- package/dist/runtime-implementation.js.map +1 -1
- package/dist/runtime.d.ts +2 -2
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js.map +1 -1
- package/dist/session-getter.d.ts +7 -7
- package/dist/session-getter.d.ts.map +1 -1
- package/dist/session-getter.js.map +1 -1
- package/dist/state-store.d.ts +3 -3
- package/dist/state-store.d.ts.map +1 -1
- package/dist/state-store.js.map +1 -1
- package/dist/types.d.ts +3 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/validate-client-metadata.d.ts +3 -3
- package/dist/validate-client-metadata.d.ts.map +1 -1
- package/dist/validate-client-metadata.js.map +1 -1
- package/package.json +11 -11
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# @atproto/oauth-client
|
|
2
2
|
|
|
3
|
+
## 0.7.9
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#5197](https://github.com/bluesky-social/atproto/pull/5197) [`a0c49d9`](https://github.com/bluesky-social/atproto/commit/a0c49d9e8bc685c5a747a8d3b2775c73c63fdb6f) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Rewrite import statements to be compatible with TypeScript's `verbatimModuleSyntax` config.
|
|
8
|
+
|
|
9
|
+
- Updated dependencies [[`a0c49d9`](https://github.com/bluesky-social/atproto/commit/a0c49d9e8bc685c5a747a8d3b2775c73c63fdb6f)]:
|
|
10
|
+
- @atproto-labs/simple-store-memory@0.2.4
|
|
11
|
+
- @atproto-labs/identity-resolver@0.4.4
|
|
12
|
+
- @atproto-labs/handle-resolver@0.4.5
|
|
13
|
+
- @atproto-labs/did-resolver@0.3.5
|
|
14
|
+
- @atproto-labs/simple-store@0.4.4
|
|
15
|
+
- @atproto/oauth-types@0.7.5
|
|
16
|
+
- @atproto-labs/fetch@0.3.4
|
|
17
|
+
- @atproto/jwk@0.7.4
|
|
18
|
+
- @atproto/xrpc@0.8.5
|
|
19
|
+
- @atproto/did@0.5.4
|
|
20
|
+
|
|
3
21
|
## 0.7.8
|
|
4
22
|
|
|
5
23
|
### Patch Changes
|
package/dist/fetch-dpop.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { Key } from '@atproto/jwk';
|
|
2
|
-
import { Fetch, FetchContext } from '@atproto-labs/fetch';
|
|
3
|
-
import { SimpleStore } from '@atproto-labs/simple-store';
|
|
1
|
+
import type { Key } from '@atproto/jwk';
|
|
2
|
+
import { type Fetch, type FetchContext } from '@atproto-labs/fetch';
|
|
3
|
+
import type { SimpleStore } from '@atproto-labs/simple-store';
|
|
4
4
|
export type DpopFetchWrapperOptions<C = FetchContext> = {
|
|
5
5
|
key: Key;
|
|
6
6
|
nonces: SimpleStore<string, string>;
|
package/dist/fetch-dpop.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch-dpop.d.ts","sourceRoot":"","sources":["../src/fetch-dpop.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,GAAG,EAAE,MAAM,cAAc,CAAA;
|
|
1
|
+
{"version":3,"file":"fetch-dpop.d.ts","sourceRoot":"","sources":["../src/fetch-dpop.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,cAAc,CAAA;AACvC,OAAO,EACL,KAAK,KAAK,EACV,KAAK,YAAY,EAGlB,MAAM,qBAAqB,CAAA;AAC5B,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAA;AAS7D,MAAM,MAAM,uBAAuB,CAAC,CAAC,GAAG,YAAY,IAAI;IACtD,GAAG,EAAE,GAAG,CAAA;IACR,MAAM,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IACnC,aAAa,CAAC,EAAE,MAAM,EAAE,CAAA;IACxB,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAA;IAE3C;;;;;;OAMG;IACH,YAAY,CAAC,EAAE,OAAO,CAAA;IACtB,KAAK,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,CAAA;CACjB,CAAA;AAED,wBAAgB,gBAAgB,CAAC,CAAC,GAAG,YAAY,EAAE,EACjD,GAAG,EAEH,aAAa,EACb,MAAM,EACN,MAAiE,EACjE,YAAY,EACZ,KAAwB,GACzB,EAAE,uBAAuB,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAsGvC"}
|
package/dist/fetch-dpop.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { base64url } from 'multiformats/bases/base64';
|
|
2
|
-
import { cancelBody, peekJson } from '@atproto-labs/fetch';
|
|
2
|
+
import { cancelBody, peekJson, } from '@atproto-labs/fetch';
|
|
3
3
|
// "undefined" in non https environments or environments without crypto
|
|
4
4
|
const subtle = globalThis.crypto?.subtle;
|
|
5
5
|
const ReadableStream = globalThis.ReadableStream;
|
package/dist/fetch-dpop.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch-dpop.js","sourceRoot":"","sources":["../src/fetch-dpop.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAA;AAErD,OAAO,EAAuB,UAAU,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAA;AAG/E,uEAAuE;AACvE,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,EAAE,MAAkC,CAAA;AAEpE,MAAM,cAAc,GAAG,UAAU,CAAC,cAErB,CAAA;AAmBb,MAAM,UAAU,gBAAgB,CAAmB,EACjD,GAAG;AACH,mDAAmD;AACnD,aAAa,EACb,MAAM,EACN,MAAM,GAAG,OAAO,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,SAAS,EACjE,YAAY,EACZ,KAAK,GAAG,UAAU,CAAC,KAAK,GACG;IAC3B,IAAI,CAAC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E;gBAClE,OAAO,KAAK,CAAA;YACd,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO,KAAK,CAAA;AACd,CAAC;AAED,SAAS,YAAY,CAAC,GAAQ,EAAE,aAAmC;IACjE,IAAI,aAAa,EAAE,CAAC;QAClB,2CAA2C;QAC3C,MAAM,GAAG,GAAG,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAA;QACjE,IAAI,GAAG;YAAE,OAAO,GAAG,CAAA;IACrB,CAAC;SAAM,CAAC;QACN,MAAM,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,UAAU,CAAA;QAC5B,IAAI,GAAG;YAAE,OAAO,GAAG,CAAA;IACrB,CAAC;IAED,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAA;AACvE,CAAC;AAED,KAAK,UAAU,YAAY,CAAC,KAAa;IACvC,IAAI,MAAM,IAAI,IAAI,EAAE,CAAC;QACnB,MAAM,IAAI,KAAK,CACb,uFAAuF,CACxF,CAAA;IACH,CAAC;IAED,MAAM,KAAK,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;IAC7C,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,KAAK,CAAC,CAAA;IACpD,MAAM,WAAW,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,CAAA;IAC1C,OAAO,SAAS,CAAC,UAAU,CAAC,WAAW,CAAC,CAAA;AAC1C,CAAC","sourcesContent":["import { base64url } from 'multiformats/bases/base64'\nimport { Key } from '@atproto/jwk'\nimport { Fetch, FetchContext, cancelBody, peekJson } from '@atproto-labs/fetch'\nimport { SimpleStore } from '@atproto-labs/simple-store'\n\n// \"undefined\" in non https environments or environments without crypto\nconst subtle = globalThis.crypto?.subtle as SubtleCrypto | undefined\n\nconst ReadableStream = globalThis.ReadableStream as\n | typeof globalThis.ReadableStream\n | undefined\n\nexport type DpopFetchWrapperOptions<C = FetchContext> = {\n key: Key\n nonces: SimpleStore<string, string>\n supportedAlgs?: string[]\n sha256?: (input: string) => Promise<string>\n\n /**\n * Is the intended server an authorization server (true) or a resource server\n * (false)? Setting this may allow to avoid parsing the response body to\n * determine the dpop-nonce.\n *\n * @default undefined\n */\n isAuthServer?: boolean\n fetch?: Fetch<C>\n}\n\nexport function dpopFetchWrapper<C = FetchContext>({\n key,\n // @TODO we should provide a default based on specs\n supportedAlgs,\n nonces,\n sha256 = typeof subtle !== 'undefined' ? subtleSha256 : undefined,\n isAuthServer,\n fetch = globalThis.fetch,\n}: DpopFetchWrapperOptions<C>): Fetch<C> {\n if (!sha256) {\n throw new TypeError(\n `crypto.subtle is not available in this environment. Please provide a sha256 function.`,\n )\n }\n\n // Throws if negotiation fails\n const alg = negotiateAlg(key, supportedAlgs)\n\n return async function (this: C, input, init) {\n const request: Request =\n init == null && input instanceof Request\n ? input\n : new Request(input, init)\n\n const authorizationHeader = request.headers.get('Authorization')\n const ath = authorizationHeader?.startsWith('DPoP ')\n ? await sha256(authorizationHeader.slice(5))\n : undefined\n\n const { origin } = new URL(request.url)\n\n const htm = request.method\n const htu = buildHtu(request.url)\n\n let initNonce: string | undefined\n try {\n initNonce = await nonces.get(origin)\n } catch {\n // Ignore get errors, we will just not send a nonce\n }\n\n const initProof = await buildProof(key, alg, htm, htu, initNonce, ath)\n request.headers.set('DPoP', initProof)\n\n const initResponse = await fetch.call(this, request)\n\n // Make sure the response body is consumed. Either by the caller (when the\n // response is returned), of if an error is thrown (catch block).\n\n const nextNonce = initResponse.headers.get('DPoP-Nonce')\n if (!nextNonce || nextNonce === initNonce) {\n // No nonce was returned or it is the same as the one we sent. No need to\n // update the nonce store, or retry the request.\n return initResponse\n }\n\n // Store the fresh nonce for future requests\n try {\n await nonces.set(origin, nextNonce)\n } catch {\n // Ignore set errors\n }\n\n const shouldRetry = await isUseDpopNonceError(initResponse, isAuthServer)\n if (!shouldRetry) {\n // Not a \"use_dpop_nonce\" error, so there is no need to retry\n return initResponse\n }\n\n // If the input stream was already consumed, we cannot retry the request. A\n // solution would be to clone() the request but that would bufferize the\n // entire stream in memory which can lead to memory starvation. Instead, we\n // will return the original response and let the calling code handle retries.\n\n if (input === request) {\n // The input request body was consumed. We cannot retry the request.\n return initResponse\n }\n\n if (ReadableStream && init?.body instanceof ReadableStream) {\n // The init body was consumed. We cannot retry the request.\n return initResponse\n }\n\n // We will now retry the request with the fresh nonce.\n\n // The initial response body must be consumed (see cancelBody's doc).\n await cancelBody(initResponse, 'log')\n\n const nextProof = await buildProof(key, alg, htm, htu, nextNonce, ath)\n const nextRequest = new Request(input, init)\n nextRequest.headers.set('DPoP', nextProof)\n\n const retryRequest = await fetch.call(this, nextRequest)\n const retryNonce = retryRequest.headers.get('DPoP-Nonce')\n if (!retryNonce || retryNonce === initNonce) {\n // No nonce was returned or it is the same as the one we sent. No need to\n // update the nonce store, or retry the request.\n return retryRequest\n }\n\n // Store the fresh nonce for future requests\n try {\n await nonces.set(origin, retryNonce)\n } catch {\n // Ignore set errors\n }\n\n return retryRequest\n }\n}\n\n/**\n * Strip query and fragment\n *\n * @see {@link https://www.rfc-editor.org/rfc/rfc9449.html#section-4.2-4.6}\n */\nfunction buildHtu(url: string): string {\n const fragmentIndex = url.indexOf('#')\n const queryIndex = url.indexOf('?')\n\n const end =\n fragmentIndex === -1\n ? queryIndex\n : queryIndex === -1\n ? fragmentIndex\n : Math.min(fragmentIndex, queryIndex)\n\n return end === -1 ? url : url.slice(0, end)\n}\n\nasync function buildProof(\n key: Key,\n alg: string,\n htm: string,\n htu: string,\n nonce?: string,\n ath?: string,\n) {\n const jwk = key.bareJwk\n if (!jwk) {\n throw new Error('Only asymmetric keys can be used as DPoP proofs')\n }\n\n const now = Math.floor(Date.now() / 1e3)\n\n return key.createJwt(\n // https://datatracker.ietf.org/doc/html/rfc9449#section-4.2\n {\n alg,\n typ: 'dpop+jwt',\n jwk,\n },\n {\n iat: now,\n // Any collision will cause the request to be rejected by the server. no biggie.\n jti: Math.random().toString(36).slice(2),\n htm,\n htu,\n nonce,\n ath,\n },\n )\n}\n\nasync function isUseDpopNonceError(\n response: Response,\n isAuthServer?: boolean,\n): Promise<boolean> {\n // https://datatracker.ietf.org/doc/html/rfc6750#section-3\n // https://datatracker.ietf.org/doc/html/rfc9449#name-resource-server-provided-no\n if (isAuthServer === undefined || isAuthServer === false) {\n if (response.status === 401) {\n const wwwAuth = response.headers.get('WWW-Authenticate')\n if (wwwAuth?.startsWith('DPoP')) {\n return wwwAuth.includes('error=\"use_dpop_nonce\"')\n }\n }\n }\n\n // https://datatracker.ietf.org/doc/html/rfc9449#name-authorization-server-provid\n if (isAuthServer === undefined || isAuthServer === true) {\n if (response.status === 400) {\n try {\n const json = await peekJson(response, 10 * 1024)\n return typeof json === 'object' && json?.['error'] === 'use_dpop_nonce'\n } catch {\n // Response too big (to be \"use_dpop_nonce\" error) or invalid JSON\n return false\n }\n }\n }\n\n return false\n}\n\nfunction negotiateAlg(key: Key, supportedAlgs: string[] | undefined): string {\n if (supportedAlgs) {\n // Use order of supportedAlgs as preference\n const alg = supportedAlgs.find((a) => key.algorithms.includes(a))\n if (alg) return alg\n } else {\n const [alg] = key.algorithms\n if (alg) return alg\n }\n\n throw new Error('Key does not match any alg supported by the server')\n}\n\nasync function subtleSha256(input: string): Promise<string> {\n if (subtle == null) {\n throw new Error(\n `crypto.subtle is not available in this environment. Please provide a sha256 function.`,\n )\n }\n\n const bytes = new TextEncoder().encode(input)\n const digest = await subtle.digest('SHA-256', bytes)\n const digestBytes = new Uint8Array(digest)\n return base64url.baseEncode(digestBytes)\n}\n"]}
|
|
1
|
+
{"version":3,"file":"fetch-dpop.js","sourceRoot":"","sources":["../src/fetch-dpop.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAA;AAErD,OAAO,EAGL,UAAU,EACV,QAAQ,GACT,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AE,KAAK,CAAC,CAAA;IACpD,MAAM,WAAW,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,CAAA;IAC1C,OAAO,SAAS,CAAC,UAAU,CAAC,WAAW,CAAC,CAAA;AAC1C,CAAC","sourcesContent":["import { base64url } from 'multiformats/bases/base64'\nimport type { Key } from '@atproto/jwk'\nimport {\n type Fetch,\n type FetchContext,\n cancelBody,\n peekJson,\n} from '@atproto-labs/fetch'\nimport type { SimpleStore } from '@atproto-labs/simple-store'\n\n// \"undefined\" in non https environments or environments without crypto\nconst subtle = globalThis.crypto?.subtle as SubtleCrypto | undefined\n\nconst ReadableStream = globalThis.ReadableStream as\n | typeof globalThis.ReadableStream\n | undefined\n\nexport type DpopFetchWrapperOptions<C = FetchContext> = {\n key: Key\n nonces: SimpleStore<string, string>\n supportedAlgs?: string[]\n sha256?: (input: string) => Promise<string>\n\n /**\n * Is the intended server an authorization server (true) or a resource server\n * (false)? Setting this may allow to avoid parsing the response body to\n * determine the dpop-nonce.\n *\n * @default undefined\n */\n isAuthServer?: boolean\n fetch?: Fetch<C>\n}\n\nexport function dpopFetchWrapper<C = FetchContext>({\n key,\n // @TODO we should provide a default based on specs\n supportedAlgs,\n nonces,\n sha256 = typeof subtle !== 'undefined' ? subtleSha256 : undefined,\n isAuthServer,\n fetch = globalThis.fetch,\n}: DpopFetchWrapperOptions<C>): Fetch<C> {\n if (!sha256) {\n throw new TypeError(\n `crypto.subtle is not available in this environment. Please provide a sha256 function.`,\n )\n }\n\n // Throws if negotiation fails\n const alg = negotiateAlg(key, supportedAlgs)\n\n return async function (this: C, input, init) {\n const request: Request =\n init == null && input instanceof Request\n ? input\n : new Request(input, init)\n\n const authorizationHeader = request.headers.get('Authorization')\n const ath = authorizationHeader?.startsWith('DPoP ')\n ? await sha256(authorizationHeader.slice(5))\n : undefined\n\n const { origin } = new URL(request.url)\n\n const htm = request.method\n const htu = buildHtu(request.url)\n\n let initNonce: string | undefined\n try {\n initNonce = await nonces.get(origin)\n } catch {\n // Ignore get errors, we will just not send a nonce\n }\n\n const initProof = await buildProof(key, alg, htm, htu, initNonce, ath)\n request.headers.set('DPoP', initProof)\n\n const initResponse = await fetch.call(this, request)\n\n // Make sure the response body is consumed. Either by the caller (when the\n // response is returned), of if an error is thrown (catch block).\n\n const nextNonce = initResponse.headers.get('DPoP-Nonce')\n if (!nextNonce || nextNonce === initNonce) {\n // No nonce was returned or it is the same as the one we sent. No need to\n // update the nonce store, or retry the request.\n return initResponse\n }\n\n // Store the fresh nonce for future requests\n try {\n await nonces.set(origin, nextNonce)\n } catch {\n // Ignore set errors\n }\n\n const shouldRetry = await isUseDpopNonceError(initResponse, isAuthServer)\n if (!shouldRetry) {\n // Not a \"use_dpop_nonce\" error, so there is no need to retry\n return initResponse\n }\n\n // If the input stream was already consumed, we cannot retry the request. A\n // solution would be to clone() the request but that would bufferize the\n // entire stream in memory which can lead to memory starvation. Instead, we\n // will return the original response and let the calling code handle retries.\n\n if (input === request) {\n // The input request body was consumed. We cannot retry the request.\n return initResponse\n }\n\n if (ReadableStream && init?.body instanceof ReadableStream) {\n // The init body was consumed. We cannot retry the request.\n return initResponse\n }\n\n // We will now retry the request with the fresh nonce.\n\n // The initial response body must be consumed (see cancelBody's doc).\n await cancelBody(initResponse, 'log')\n\n const nextProof = await buildProof(key, alg, htm, htu, nextNonce, ath)\n const nextRequest = new Request(input, init)\n nextRequest.headers.set('DPoP', nextProof)\n\n const retryRequest = await fetch.call(this, nextRequest)\n const retryNonce = retryRequest.headers.get('DPoP-Nonce')\n if (!retryNonce || retryNonce === initNonce) {\n // No nonce was returned or it is the same as the one we sent. No need to\n // update the nonce store, or retry the request.\n return retryRequest\n }\n\n // Store the fresh nonce for future requests\n try {\n await nonces.set(origin, retryNonce)\n } catch {\n // Ignore set errors\n }\n\n return retryRequest\n }\n}\n\n/**\n * Strip query and fragment\n *\n * @see {@link https://www.rfc-editor.org/rfc/rfc9449.html#section-4.2-4.6}\n */\nfunction buildHtu(url: string): string {\n const fragmentIndex = url.indexOf('#')\n const queryIndex = url.indexOf('?')\n\n const end =\n fragmentIndex === -1\n ? queryIndex\n : queryIndex === -1\n ? fragmentIndex\n : Math.min(fragmentIndex, queryIndex)\n\n return end === -1 ? url : url.slice(0, end)\n}\n\nasync function buildProof(\n key: Key,\n alg: string,\n htm: string,\n htu: string,\n nonce?: string,\n ath?: string,\n) {\n const jwk = key.bareJwk\n if (!jwk) {\n throw new Error('Only asymmetric keys can be used as DPoP proofs')\n }\n\n const now = Math.floor(Date.now() / 1e3)\n\n return key.createJwt(\n // https://datatracker.ietf.org/doc/html/rfc9449#section-4.2\n {\n alg,\n typ: 'dpop+jwt',\n jwk,\n },\n {\n iat: now,\n // Any collision will cause the request to be rejected by the server. no biggie.\n jti: Math.random().toString(36).slice(2),\n htm,\n htu,\n nonce,\n ath,\n },\n )\n}\n\nasync function isUseDpopNonceError(\n response: Response,\n isAuthServer?: boolean,\n): Promise<boolean> {\n // https://datatracker.ietf.org/doc/html/rfc6750#section-3\n // https://datatracker.ietf.org/doc/html/rfc9449#name-resource-server-provided-no\n if (isAuthServer === undefined || isAuthServer === false) {\n if (response.status === 401) {\n const wwwAuth = response.headers.get('WWW-Authenticate')\n if (wwwAuth?.startsWith('DPoP')) {\n return wwwAuth.includes('error=\"use_dpop_nonce\"')\n }\n }\n }\n\n // https://datatracker.ietf.org/doc/html/rfc9449#name-authorization-server-provid\n if (isAuthServer === undefined || isAuthServer === true) {\n if (response.status === 400) {\n try {\n const json = await peekJson(response, 10 * 1024)\n return typeof json === 'object' && json?.['error'] === 'use_dpop_nonce'\n } catch {\n // Response too big (to be \"use_dpop_nonce\" error) or invalid JSON\n return false\n }\n }\n }\n\n return false\n}\n\nfunction negotiateAlg(key: Key, supportedAlgs: string[] | undefined): string {\n if (supportedAlgs) {\n // Use order of supportedAlgs as preference\n const alg = supportedAlgs.find((a) => key.algorithms.includes(a))\n if (alg) return alg\n } else {\n const [alg] = key.algorithms\n if (alg) return alg\n }\n\n throw new Error('Key does not match any alg supported by the server')\n}\n\nasync function subtleSha256(input: string): Promise<string> {\n if (subtle == null) {\n throw new Error(\n `crypto.subtle is not available in this environment. Please provide a sha256 function.`,\n )\n }\n\n const bytes = new TextEncoder().encode(input)\n const digest = await subtle.digest('SHA-256', bytes)\n const digestBytes = new Uint8Array(digest)\n return base64url.baseEncode(digestBytes)\n}\n"]}
|
package/dist/lock.d.ts
CHANGED
package/dist/lock.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lock.d.ts","sourceRoot":"","sources":["../src/lock.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAA;
|
|
1
|
+
{"version":3,"file":"lock.d.ts","sourceRoot":"","sources":["../src/lock.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAA;AAwB9D,eAAO,MAAM,gBAAgB,EAAE,WAQ9B,CAAA"}
|
package/dist/lock.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lock.js","sourceRoot":"","sources":["../src/lock.ts"],"names":[],"mappings":"AAEA,MAAM,KAAK,GAAG,IAAI,GAAG,EAA0B,CAAA;AAE/C,SAAS,gBAAgB,CAAC,IAAa;IACrC,OAAO,IAAI,OAAO,CAAC,CAAC,cAAc,EAAE,EAAE;QACpC,MAAM,IAAI,GAAG,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,OAAO,CAAC,OAAO,EAAE,CAAA;QACjD,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE;YAC1B,OAAO,IAAI,OAAO,CAAO,CAAC,cAAc,EAAE,EAAE;gBAC1C,MAAM,OAAO,GAAG,GAAG,EAAE;oBACnB,sDAAsD;oBACtD,IAAI,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,IAAI;wBAAE,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;oBAEhD,cAAc,EAAE,CAAA;gBAClB,CAAC,CAAA;gBAED,cAAc,CAAC,OAAO,CAAC,CAAA;YACzB,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;QAEF,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;IACvB,CAAC,CAAC,CAAA;AACJ,CAAC;AAED,MAAM,CAAC,MAAM,gBAAgB,GAAgB,CAAC,IAAI,EAAE,EAAE,EAAE,EAAE;IACxD,OAAO,gBAAgB,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE;QACnD,IAAI,CAAC;YACH,OAAO,MAAM,EAAE,EAAE,CAAA;QACnB,CAAC;gBAAS,CAAC;YACT,OAAO,EAAE,CAAA;QACX,CAAC;IACH,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA","sourcesContent":["import { RuntimeLock } from './runtime-implementation.js'\n\nconst locks = new Map<unknown, Promise<void>>()\n\nfunction acquireLocalLock(name: unknown): Promise<() => void> {\n return new Promise((resolveAcquire) => {\n const prev = locks.get(name) ?? Promise.resolve()\n const next = prev.then(() => {\n return new Promise<void>((resolveRelease) => {\n const release = () => {\n // Only delete the lock if it is still the current one\n if (locks.get(name) === next) locks.delete(name)\n\n resolveRelease()\n }\n\n resolveAcquire(release)\n })\n })\n\n locks.set(name, next)\n })\n}\n\nexport const requestLocalLock: RuntimeLock = (name, fn) => {\n return acquireLocalLock(name).then(async (release) => {\n try {\n return await fn()\n } finally {\n release()\n }\n })\n}\n"]}
|
|
1
|
+
{"version":3,"file":"lock.js","sourceRoot":"","sources":["../src/lock.ts"],"names":[],"mappings":"AAEA,MAAM,KAAK,GAAG,IAAI,GAAG,EAA0B,CAAA;AAE/C,SAAS,gBAAgB,CAAC,IAAa;IACrC,OAAO,IAAI,OAAO,CAAC,CAAC,cAAc,EAAE,EAAE;QACpC,MAAM,IAAI,GAAG,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,OAAO,CAAC,OAAO,EAAE,CAAA;QACjD,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE;YAC1B,OAAO,IAAI,OAAO,CAAO,CAAC,cAAc,EAAE,EAAE;gBAC1C,MAAM,OAAO,GAAG,GAAG,EAAE;oBACnB,sDAAsD;oBACtD,IAAI,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,IAAI;wBAAE,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;oBAEhD,cAAc,EAAE,CAAA;gBAClB,CAAC,CAAA;gBAED,cAAc,CAAC,OAAO,CAAC,CAAA;YACzB,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;QAEF,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;IACvB,CAAC,CAAC,CAAA;AACJ,CAAC;AAED,MAAM,CAAC,MAAM,gBAAgB,GAAgB,CAAC,IAAI,EAAE,EAAE,EAAE,EAAE;IACxD,OAAO,gBAAgB,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE;QACnD,IAAI,CAAC;YACH,OAAO,MAAM,EAAE,EAAE,CAAA;QACnB,CAAC;gBAAS,CAAC;YACT,OAAO,EAAE,CAAA;QACX,CAAC;IACH,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA","sourcesContent":["import type { RuntimeLock } from './runtime-implementation.js'\n\nconst locks = new Map<unknown, Promise<void>>()\n\nfunction acquireLocalLock(name: unknown): Promise<() => void> {\n return new Promise((resolveAcquire) => {\n const prev = locks.get(name) ?? Promise.resolve()\n const next = prev.then(() => {\n return new Promise<void>((resolveRelease) => {\n const release = () => {\n // Only delete the lock if it is still the current one\n if (locks.get(name) === next) locks.delete(name)\n\n resolveRelease()\n }\n\n resolveAcquire(release)\n })\n })\n\n locks.set(name, next)\n })\n}\n\nexport const requestLocalLock: RuntimeLock = (name, fn) => {\n return acquireLocalLock(name).then(async (release) => {\n try {\n return await fn()\n } finally {\n release()\n }\n })\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { OAuthAuthorizationServerMetadata } from '@atproto/oauth-types';
|
|
2
|
-
import { Fetch } from '@atproto-labs/fetch';
|
|
3
|
-
import { CachedGetter, GetCachedOptions, SimpleStore } from '@atproto-labs/simple-store';
|
|
1
|
+
import { type OAuthAuthorizationServerMetadata } from '@atproto/oauth-types';
|
|
2
|
+
import { type Fetch } from '@atproto-labs/fetch';
|
|
3
|
+
import { CachedGetter, type GetCachedOptions, type SimpleStore } from '@atproto-labs/simple-store';
|
|
4
4
|
export type { GetCachedOptions, OAuthAuthorizationServerMetadata };
|
|
5
5
|
export type AuthorizationServerMetadataCache = SimpleStore<string, OAuthAuthorizationServerMetadata>;
|
|
6
6
|
export type OAuthAuthorizationServerMetadataResolverConfig = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth-authorization-server-metadata-resolver.d.ts","sourceRoot":"","sources":["../src/oauth-authorization-server-metadata-resolver.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gCAAgC,
|
|
1
|
+
{"version":3,"file":"oauth-authorization-server-metadata-resolver.d.ts","sourceRoot":"","sources":["../src/oauth-authorization-server-metadata-resolver.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,gCAAgC,EAGtC,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EACL,KAAK,KAAK,EAIX,MAAM,qBAAqB,CAAA;AAC5B,OAAO,EACL,YAAY,EACZ,KAAK,gBAAgB,EACrB,KAAK,WAAW,EACjB,MAAM,4BAA4B,CAAA;AAGnC,YAAY,EAAE,gBAAgB,EAAE,gCAAgC,EAAE,CAAA;AAElE,MAAM,MAAM,gCAAgC,GAAG,WAAW,CACxD,MAAM,EACN,gCAAgC,CACjC,CAAA;AAED,MAAM,MAAM,8CAA8C,GAAG;IAC3D,eAAe,CAAC,EAAE,OAAO,CAAA;CAC1B,CAAA;AAED;;GAEG;AACH,qBAAa,wCAAyC,SAAQ,YAAY,CACxE,MAAM,EACN,gCAAgC,CACjC;IACC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAgB;IACtC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IAEzC,YACE,KAAK,EAAE,gCAAgC,EACvC,KAAK,CAAC,EAAE,KAAK,EACb,MAAM,CAAC,EAAE,8CAA8C,EAMxD;IAEK,GAAG,CACP,KAAK,EAAE,GAAG,GAAG,MAAM,EACnB,OAAO,CAAC,EAAE,gBAAgB,GACzB,OAAO,CAAC,gCAAgC,CAAC,CAQ3C;YAEa,aAAa;CAwD5B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth-authorization-server-metadata-resolver.js","sourceRoot":"","sources":["../src/oauth-authorization-server-metadata-resolver.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,yCAAyC,EACzC,2BAA2B,GAC5B,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAEL,kBAAkB,EAClB,SAAS,EACT,UAAU,GACX,MAAM,qBAAqB,CAAA;AAC5B,OAAO,EACL,YAAY,GAGb,MAAM,4BAA4B,CAAA;AACnC,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAavC;;GAEG;AACH,MAAM,OAAO,wCAAyC,SAAQ,YAG7D;IAIC,YACE,KAAuC,EACvC,KAAa,EACb,MAAuD;QAEvD,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,KAAK,CAAC,CAAA;QAE5E,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC,KAAK,CAAC,CAAA;QAC7B,IAAI,CAAC,eAAe,GAAG,MAAM,EAAE,eAAe,KAAK,IAAI,CAAA;IACzD,CAAC;IAED,KAAK,CAAC,GAAG,CACP,KAAmB,EACnB,OAA0B;QAE1B,MAAM,MAAM,GAAG,2BA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AC,IAAI,CACjC,QAAQ,EACR,gCAAgC,GAAG,GAAG,EACtC,SAAS,EACT,EAAE,KAAK,EAAE,OAAO,EAAE,CACnB,CAAA;QACH,CAAC;QAED,MAAM,QAAQ,GAAG,yCAAyC,CAAC,KAAK,CAC9D,MAAM,QAAQ,CAAC,IAAI,EAAE,CACtB,CAAA;QAED,uCAAuC;QACvC,6FAA6F;QAC7F,0DAA0D;QAC1D,IAAI,QAAQ,CAAC,MAAM,KAAK,MAAM,EAAE,CAAC;YAC/B,MAAM,IAAI,SAAS,CAAC,kBAAkB,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAA;QAC1D,CAAC;QAED,+CAA+C;QAC/C,iFAAiF;QACjF,IAAI,QAAQ,CAAC,qCAAqC,KAAK,IAAI,EAAE,CAAC;YAC5D,MAAM,IAAI,SAAS,CACjB,yBAAyB,MAAM,gDAAgD,CAChF,CAAA;QACH,CAAC;QAED,OAAO,QAAQ,CAAA;IACjB,CAAC;CACF","sourcesContent":["import {\n OAuthAuthorizationServerMetadata,\n oauthAuthorizationServerMetadataValidator,\n oauthIssuerIdentifierSchema,\n} from '@atproto/oauth-types'\nimport {\n Fetch,\n FetchResponseError,\n bindFetch,\n cancelBody,\n} from '@atproto-labs/fetch'\nimport {\n CachedGetter,\n GetCachedOptions,\n SimpleStore,\n} from '@atproto-labs/simple-store'\nimport { contentMime } from './util.js'\n\nexport type { GetCachedOptions, OAuthAuthorizationServerMetadata }\n\nexport type AuthorizationServerMetadataCache = SimpleStore<\n string,\n OAuthAuthorizationServerMetadata\n>\n\nexport type OAuthAuthorizationServerMetadataResolverConfig = {\n allowHttpIssuer?: boolean\n}\n\n/**\n * @see {@link https://datatracker.ietf.org/doc/html/rfc8414}\n */\nexport class OAuthAuthorizationServerMetadataResolver extends CachedGetter<\n string,\n OAuthAuthorizationServerMetadata\n> {\n private readonly fetch: Fetch<unknown>\n private readonly allowHttpIssuer: boolean\n\n constructor(\n cache: AuthorizationServerMetadataCache,\n fetch?: Fetch,\n config?: OAuthAuthorizationServerMetadataResolverConfig,\n ) {\n super(async (issuer, options) => this.fetchMetadata(issuer, options), cache)\n\n this.fetch = bindFetch(fetch)\n this.allowHttpIssuer = config?.allowHttpIssuer === true\n }\n\n async get(\n input: URL | string,\n options?: GetCachedOptions,\n ): Promise<OAuthAuthorizationServerMetadata> {\n const issuer = oauthIssuerIdentifierSchema.parse(String(input))\n if (!this.allowHttpIssuer && issuer.startsWith('http:')) {\n throw new TypeError(\n 'Unsecure issuer URL protocol only allowed in development and test environments',\n )\n }\n return super.get(issuer, options)\n }\n\n private async fetchMetadata(\n issuer: string,\n options?: GetCachedOptions,\n ): Promise<OAuthAuthorizationServerMetadata> {\n const url = new URL(`/.well-known/oauth-authorization-server`, issuer)\n const request = new Request(url, {\n headers: { accept: 'application/json' },\n cache: options?.noCache ? 'no-cache' : undefined,\n signal: options?.signal,\n redirect: 'manual', // response must be 200 OK\n })\n\n const response = await this.fetch(request)\n\n // https://datatracker.ietf.org/doc/html/rfc8414#section-3.2\n if (response.status !== 200) {\n await cancelBody(response, 'log')\n throw await FetchResponseError.from(\n response,\n `Unexpected status code ${response.status} for \"${url}\"`,\n undefined,\n { cause: request },\n )\n }\n\n if (contentMime(response.headers) !== 'application/json') {\n await cancelBody(response, 'log')\n throw await FetchResponseError.from(\n response,\n `Unexpected content type for \"${url}\"`,\n undefined,\n { cause: request },\n )\n }\n\n const metadata = oauthAuthorizationServerMetadataValidator.parse(\n await response.json(),\n )\n\n // Validate the issuer (MIX-UP attacks)\n // https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics#name-mix-up-attacks\n // https://datatracker.ietf.org/doc/html/rfc8414#section-2\n if (metadata.issuer !== issuer) {\n throw new TypeError(`Invalid issuer ${metadata.issuer}`)\n }\n\n // ATPROTO requires client_id_metadata_document\n // https://datatracker.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/\n if (metadata.client_id_metadata_document_supported !== true) {\n throw new TypeError(\n `Authorization server \"${issuer}\" does not support client_id_metadata_document`,\n )\n }\n\n return metadata\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"oauth-authorization-server-metadata-resolver.js","sourceRoot":"","sources":["../src/oauth-authorization-server-metadata-resolver.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,yCAAyC,EACzC,2BAA2B,GAC5B,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAEL,kBAAkB,EAClB,SAAS,EACT,UAAU,GACX,MAAM,qBAAqB,CAAA;AAC5B,OAAO,EACL,YAAY,GAGb,MAAM,4BAA4B,CAAA;AACnC,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAavC;;GAEG;AACH,MAAM,OAAO,wCAAyC,SAAQ,YAG7D;IAIC,YACE,KAAuC,EACvC,KAAa,EACb,MAAuD;QAEvD,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,KAAK,CAAC,CAAA;QAE5E,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC,KAAK,CAAC,CAAA;QAC7B,IAAI,CAAC,eAAe,GAAG,MAAM,EAAE,eAAe,KAAK,IAAI,CAAA;IACzD,CAAC;IAED,KAAK,CAAC,GAAG,CACP,KAAmB,EACnB,OAA0B;QAE1B,MAAM,MAAM,GAAG,2BAA2B,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAA;QAC/D,IAAI,CAAC,IAAI,CAAC,eAAe,IAAI,MAAM,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE,CAAC;YACxD,MAAM,IAAI,SAAS,CACjB,gFAAgF,CACjF,CAAA;QACH,CAAC;QACD,OAAO,KAAK,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IACnC,CAAC;IAEO,KAAK,CAAC,aAAa,CACzB,MAAc,EACd,OAA0B;QAE1B,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC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AAC,CAAA;QAC1D,CAAC;QAED,+CAA+C;QAC/C,iFAAiF;QACjF,IAAI,QAAQ,CAAC,qCAAqC,KAAK,IAAI,EAAE,CAAC;YAC5D,MAAM,IAAI,SAAS,CACjB,yBAAyB,MAAM,gDAAgD,CAChF,CAAA;QACH,CAAC;QAED,OAAO,QAAQ,CAAA;IACjB,CAAC;CACF","sourcesContent":["import {\n type OAuthAuthorizationServerMetadata,\n oauthAuthorizationServerMetadataValidator,\n oauthIssuerIdentifierSchema,\n} from '@atproto/oauth-types'\nimport {\n type Fetch,\n FetchResponseError,\n bindFetch,\n cancelBody,\n} from '@atproto-labs/fetch'\nimport {\n CachedGetter,\n type GetCachedOptions,\n type SimpleStore,\n} from '@atproto-labs/simple-store'\nimport { contentMime } from './util.js'\n\nexport type { GetCachedOptions, OAuthAuthorizationServerMetadata }\n\nexport type AuthorizationServerMetadataCache = SimpleStore<\n string,\n OAuthAuthorizationServerMetadata\n>\n\nexport type OAuthAuthorizationServerMetadataResolverConfig = {\n allowHttpIssuer?: boolean\n}\n\n/**\n * @see {@link https://datatracker.ietf.org/doc/html/rfc8414}\n */\nexport class OAuthAuthorizationServerMetadataResolver extends CachedGetter<\n string,\n OAuthAuthorizationServerMetadata\n> {\n private readonly fetch: Fetch<unknown>\n private readonly allowHttpIssuer: boolean\n\n constructor(\n cache: AuthorizationServerMetadataCache,\n fetch?: Fetch,\n config?: OAuthAuthorizationServerMetadataResolverConfig,\n ) {\n super(async (issuer, options) => this.fetchMetadata(issuer, options), cache)\n\n this.fetch = bindFetch(fetch)\n this.allowHttpIssuer = config?.allowHttpIssuer === true\n }\n\n async get(\n input: URL | string,\n options?: GetCachedOptions,\n ): Promise<OAuthAuthorizationServerMetadata> {\n const issuer = oauthIssuerIdentifierSchema.parse(String(input))\n if (!this.allowHttpIssuer && issuer.startsWith('http:')) {\n throw new TypeError(\n 'Unsecure issuer URL protocol only allowed in development and test environments',\n )\n }\n return super.get(issuer, options)\n }\n\n private async fetchMetadata(\n issuer: string,\n options?: GetCachedOptions,\n ): Promise<OAuthAuthorizationServerMetadata> {\n const url = new URL(`/.well-known/oauth-authorization-server`, issuer)\n const request = new Request(url, {\n headers: { accept: 'application/json' },\n cache: options?.noCache ? 'no-cache' : undefined,\n signal: options?.signal,\n redirect: 'manual', // response must be 200 OK\n })\n\n const response = await this.fetch(request)\n\n // https://datatracker.ietf.org/doc/html/rfc8414#section-3.2\n if (response.status !== 200) {\n await cancelBody(response, 'log')\n throw await FetchResponseError.from(\n response,\n `Unexpected status code ${response.status} for \"${url}\"`,\n undefined,\n { cause: request },\n )\n }\n\n if (contentMime(response.headers) !== 'application/json') {\n await cancelBody(response, 'log')\n throw await FetchResponseError.from(\n response,\n `Unexpected content type for \"${url}\"`,\n undefined,\n { cause: request },\n )\n }\n\n const metadata = oauthAuthorizationServerMetadataValidator.parse(\n await response.json(),\n )\n\n // Validate the issuer (MIX-UP attacks)\n // https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics#name-mix-up-attacks\n // https://datatracker.ietf.org/doc/html/rfc8414#section-2\n if (metadata.issuer !== issuer) {\n throw new TypeError(`Invalid issuer ${metadata.issuer}`)\n }\n\n // ATPROTO requires client_id_metadata_document\n // https://datatracker.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/\n if (metadata.client_id_metadata_document_supported !== true) {\n throw new TypeError(\n `Authorization server \"${issuer}\" does not support client_id_metadata_document`,\n )\n }\n\n return metadata\n }\n}\n"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { Keyset } from '@atproto/jwk';
|
|
2
|
-
import { OAuthAuthorizationServerMetadata, OAuthClientCredentials } from '@atproto/oauth-types';
|
|
3
|
-
import { Runtime } from './runtime.js';
|
|
4
|
-
import { ClientMetadata } from './types.js';
|
|
5
|
-
import { Awaitable } from './util.js';
|
|
1
|
+
import type { Keyset } from '@atproto/jwk';
|
|
2
|
+
import { type OAuthAuthorizationServerMetadata, type OAuthClientCredentials } from '@atproto/oauth-types';
|
|
3
|
+
import type { Runtime } from './runtime.js';
|
|
4
|
+
import type { ClientMetadata } from './types.js';
|
|
5
|
+
import type { Awaitable } from './util.js';
|
|
6
6
|
export type ClientAuthMethod = {
|
|
7
7
|
method: 'none';
|
|
8
8
|
} | {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth-client-auth.d.ts","sourceRoot":"","sources":["../src/oauth-client-auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;
|
|
1
|
+
{"version":3,"file":"oauth-client-auth.d.ts","sourceRoot":"","sources":["../src/oauth-client-auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AAC1C,OAAO,EAEL,KAAK,gCAAgC,EACrC,KAAK,sBAAsB,EAC5B,MAAM,sBAAsB,CAAA;AAG7B,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AAC3C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAChD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,WAAW,CAAA;AAE1C,MAAM,MAAM,gBAAgB,GACxB;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,GAClB;IAAE,MAAM,EAAE,iBAAiB,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAAA;AAE9C,wBAAgB,yBAAyB,CACvC,cAAc,EAAE,gCAAgC,EAChD,cAAc,EAAE,cAAc,EAC9B,MAAM,CAAC,EAAE,MAAM,GACd,gBAAgB,CAkDlB;AAED,MAAM,MAAM,wBAAwB,GAAG,MAAM,SAAS,CAAC;IACrD,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAChC,OAAO,CAAC,EAAE,sBAAsB,CAAA;CACjC,CAAC,CAAA;AAEF;;;;GAIG;AACH,wBAAgB,8BAA8B,CAC5C,UAAU,EAAE,gBAAgB,EAC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B;IACpC,mBAAmB;IACnB,2BAA2B,UAAU,CAAC,MAAM,EAAE,CAC/C,CAAA;AACH,CAAC;AAED,SAAS,gBAAgB,CAAC,cAAgD;IACxE,OAAO,cAAc,CAAC,uCAAuC,CAAC,CAAA;AAChE,CAAC;AAED,SAAS,aAAa,CAAC,cAAgD;IACrE,OAAO,CACL,cAAc,CAAC,kDAAkD,CAAC,IAAI;QACpE,oEAAoE;QACpE,wCAAwC;QACxC,EAAE;QACF,uEAAuE;QACvE,sDAAsD;QACtD,EAAE;QACF,qEAAqE;QACrE,YAAY;KACb,CACF,CAAA;AACH,CAAC","sourcesContent":["import { Keyset } from '@atproto/jwk'\nimport {\n CLIENT_ASSERTION_TYPE_JWT_BEARER,\n OAuthAuthorizationServerMetadata,\n OAuthClientCredentials,\n} from '@atproto/oauth-types'\nimport { FALLBACK_ALG } from './constants.js'\nimport { AuthMethodUnsatisfiableError } from './errors/auth-method-unsatisfiable-error.js'\nimport { Runtime } from './runtime.js'\nimport { ClientMetadata } from './types.js'\nimport { Awaitable } from './util.js'\n\nexport type ClientAuthMethod =\n | { method: 'none' }\n | { method: 'private_key_jwt'; kid: string }\n\nexport function negotiateClientAuthMethod(\n serverMetadata: OAuthAuthorizationServerMetadata,\n clientMetadata: ClientMetadata,\n keyset?: Keyset,\n): ClientAuthMethod {\n const method = clientMetadata.token_endpoint_auth_method\n\n // @NOTE ATproto spec requires that AS support both \"none\" and\n // \"private_key_jwt\", and that clients use one of the other. The following\n // check ensures that the AS is indeed compliant with this client's\n // configuration.\n const methods = supportedMethods(serverMetadata)\n if (!methods.includes(method)) {\n throw new Error(\n `The server does not support \"${method}\" authentication. Supported methods are: ${methods.join(\n ', ',\n )}.`,\n )\n }\n\n if (method === 'private_key_jwt') {\n // Invalid client configuration. This should not happen as\n // \"validateClientMetadata\" already check this.\n if (!keyset) throw new Error('A keyset is required for private_key_jwt')\n\n const alg = supportedAlgs(serverMetadata)\n\n // @NOTE we can't use `keyset.findPrivateKey` here because we can't enforce\n // that the returned key contains a \"kid\". The following implementation is\n // more robust against keysets containing keys without a \"kid\" property.\n for (const key of keyset.list({ alg, usage: 'sign' })) {\n // Return the first key from the key set that matches the server's\n // supported algorithms.\n if (key.kid) return { method: 'private_key_jwt', kid: key.kid }\n }\n\n throw new Error(\n alg.includes(FALLBACK_ALG)\n ? `Client authentication method \"${method}\" requires at least one \"${FALLBACK_ALG}\" signing key with a \"kid\" property`\n : // AS is not compliant with the ATproto OAuth spec.\n `Authorization server requires \"${method}\" authentication method, but does not support \"${FALLBACK_ALG}\" algorithm.`,\n )\n }\n\n if (method === 'none') {\n return { method: 'none' }\n }\n\n throw new Error(\n `The ATProto OAuth spec requires that client use either \"none\" or \"private_key_jwt\" authentication method.` +\n (method === 'client_secret_basic'\n ? ' You might want to explicitly set \"token_endpoint_auth_method\" to one of those values in the client metadata document.'\n : ` You set \"${method}\" which is not allowed.`),\n )\n}\n\nexport type ClientCredentialsFactory = () => Awaitable<{\n headers?: Record<string, string>\n payload?: OAuthClientCredentials\n}>\n\n/**\n * @throws {AuthMethodUnsatisfiableError} if the authentication method is no\n * long usable (either because the AS changed, of because the key is no longer\n * available in the keyset).\n */\nexport function createClientCredentialsFactory(\n authMethod: ClientAuthMethod,\n serverMetadata: OAuthAuthorizationServerMetadata,\n clientMetadata: ClientMetadata,\n runtime: Runtime,\n keyset?: Keyset,\n): ClientCredentialsFactory {\n // Ensure the AS still supports the auth method.\n if (!supportedMethods(serverMetadata).includes(authMethod.method)) {\n throw new AuthMethodUnsatisfiableError(\n `Client authentication method \"${authMethod.method}\" no longer supported`,\n )\n }\n\n if (authMethod.method === 'none') {\n return () => ({\n payload: {\n client_id: clientMetadata.client_id,\n },\n })\n }\n\n if (authMethod.method === 'private_key_jwt') {\n try {\n // The client used to be a confidential client but no longer has a keyset.\n if (!keyset) throw new Error('A keyset is required for private_key_jwt')\n\n // @NOTE throws if no matching key can be found\n const { key, alg } = keyset.findPrivateKey({\n usage: 'sign',\n kid: authMethod.kid,\n alg: supportedAlgs(serverMetadata),\n })\n\n // https://www.rfc-editor.org/rfc/rfc7523.html#section-3\n return async () => ({\n payload: {\n client_id: clientMetadata.client_id,\n client_assertion_type: CLIENT_ASSERTION_TYPE_JWT_BEARER,\n client_assertion: await key.createJwt(\n { alg },\n {\n // > The JWT MUST contain an \"iss\" (issuer) claim that contains a\n // > unique identifier for the entity that issued the JWT.\n iss: clientMetadata.client_id,\n // > For client authentication, the subject MUST be the\n // > \"client_id\" of the OAuth client.\n sub: clientMetadata.client_id,\n // > The JWT MUST contain an \"aud\" (audience) claim containing a value\n // > that identifies the authorization server as an intended audience.\n // > The token endpoint URL of the authorization server MAY be used as a\n // > value for an \"aud\" element to identify the authorization server as an\n // > intended audience of the JWT.\n aud: serverMetadata.issuer,\n // > The JWT MAY contain a \"jti\" (JWT ID) claim that provides a\n // > unique identifier for the token.\n jti: await runtime.generateNonce(),\n // > The JWT MAY contain an \"iat\" (issued at) claim that\n // > identifies the time at which the JWT was issued.\n iat: Math.floor(Date.now() / 1000),\n // > The JWT MUST contain an \"exp\" (expiration time) claim that\n // > limits the time window during which the JWT can be used.\n exp: Math.floor(Date.now() / 1000) + 60, // 1 minute\n },\n ),\n },\n })\n } catch (cause) {\n throw new AuthMethodUnsatisfiableError('Failed to load private key', {\n cause,\n })\n }\n }\n\n throw new AuthMethodUnsatisfiableError(\n // @ts-expect-error\n `Unsupported auth method ${authMethod.method}`,\n )\n}\n\nfunction supportedMethods(serverMetadata: OAuthAuthorizationServerMetadata) {\n return serverMetadata['token_endpoint_auth_methods_supported']\n}\n\nfunction supportedAlgs(serverMetadata: OAuthAuthorizationServerMetadata) {\n return (\n serverMetadata['token_endpoint_auth_signing_alg_values_supported'] ?? [\n // @NOTE If not specified, assume that the server supports the ES256\n // algorithm, as prescribed by the spec:\n //\n // > Clients and Authorization Servers currently must support the ES256\n // > cryptographic system [for client authentication].\n //\n // https://atproto.com/specs/oauth#confidential-client-authentication\n FALLBACK_ALG,\n ]\n )\n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uC,CAAC,CAAA;AAChE,CAAC;AAED,SAAS,aAAa,CAAC,cAAgD;IACrE,OAAO,CACL,cAAc,CAAC,kDAAkD,CAAC,IAAI;QACpE,oEAAoE;QACpE,wCAAwC;QACxC,EAAE;QACF,uEAAuE;QACvE,sDAAsD;QACtD,EAAE;QACF,qEAAqE;QACrE,YAAY;KACb,CACF,CAAA;AACH,CAAC","sourcesContent":["import type { Keyset } from '@atproto/jwk'\nimport {\n CLIENT_ASSERTION_TYPE_JWT_BEARER,\n type OAuthAuthorizationServerMetadata,\n type OAuthClientCredentials,\n} from '@atproto/oauth-types'\nimport { FALLBACK_ALG } from './constants.js'\nimport { AuthMethodUnsatisfiableError } from './errors/auth-method-unsatisfiable-error.js'\nimport type { Runtime } from './runtime.js'\nimport type { ClientMetadata } from './types.js'\nimport type { Awaitable } from './util.js'\n\nexport type ClientAuthMethod =\n | { method: 'none' }\n | { method: 'private_key_jwt'; kid: string }\n\nexport function negotiateClientAuthMethod(\n serverMetadata: OAuthAuthorizationServerMetadata,\n clientMetadata: ClientMetadata,\n keyset?: Keyset,\n): ClientAuthMethod {\n const method = clientMetadata.token_endpoint_auth_method\n\n // @NOTE ATproto spec requires that AS support both \"none\" and\n // \"private_key_jwt\", and that clients use one of the other. The following\n // check ensures that the AS is indeed compliant with this client's\n // configuration.\n const methods = supportedMethods(serverMetadata)\n if (!methods.includes(method)) {\n throw new Error(\n `The server does not support \"${method}\" authentication. Supported methods are: ${methods.join(\n ', ',\n )}.`,\n )\n }\n\n if (method === 'private_key_jwt') {\n // Invalid client configuration. This should not happen as\n // \"validateClientMetadata\" already check this.\n if (!keyset) throw new Error('A keyset is required for private_key_jwt')\n\n const alg = supportedAlgs(serverMetadata)\n\n // @NOTE we can't use `keyset.findPrivateKey` here because we can't enforce\n // that the returned key contains a \"kid\". The following implementation is\n // more robust against keysets containing keys without a \"kid\" property.\n for (const key of keyset.list({ alg, usage: 'sign' })) {\n // Return the first key from the key set that matches the server's\n // supported algorithms.\n if (key.kid) return { method: 'private_key_jwt', kid: key.kid }\n }\n\n throw new Error(\n alg.includes(FALLBACK_ALG)\n ? `Client authentication method \"${method}\" requires at least one \"${FALLBACK_ALG}\" signing key with a \"kid\" property`\n : // AS is not compliant with the ATproto OAuth spec.\n `Authorization server requires \"${method}\" authentication method, but does not support \"${FALLBACK_ALG}\" algorithm.`,\n )\n }\n\n if (method === 'none') {\n return { method: 'none' }\n }\n\n throw new Error(\n `The ATProto OAuth spec requires that client use either \"none\" or \"private_key_jwt\" authentication method.` +\n (method === 'client_secret_basic'\n ? ' You might want to explicitly set \"token_endpoint_auth_method\" to one of those values in the client metadata document.'\n : ` You set \"${method}\" which is not allowed.`),\n )\n}\n\nexport type ClientCredentialsFactory = () => Awaitable<{\n headers?: Record<string, string>\n payload?: OAuthClientCredentials\n}>\n\n/**\n * @throws {AuthMethodUnsatisfiableError} if the authentication method is no\n * long usable (either because the AS changed, of because the key is no longer\n * available in the keyset).\n */\nexport function createClientCredentialsFactory(\n authMethod: ClientAuthMethod,\n serverMetadata: OAuthAuthorizationServerMetadata,\n clientMetadata: ClientMetadata,\n runtime: Runtime,\n keyset?: Keyset,\n): ClientCredentialsFactory {\n // Ensure the AS still supports the auth method.\n if (!supportedMethods(serverMetadata).includes(authMethod.method)) {\n throw new AuthMethodUnsatisfiableError(\n `Client authentication method \"${authMethod.method}\" no longer supported`,\n )\n }\n\n if (authMethod.method === 'none') {\n return () => ({\n payload: {\n client_id: clientMetadata.client_id,\n },\n })\n }\n\n if (authMethod.method === 'private_key_jwt') {\n try {\n // The client used to be a confidential client but no longer has a keyset.\n if (!keyset) throw new Error('A keyset is required for private_key_jwt')\n\n // @NOTE throws if no matching key can be found\n const { key, alg } = keyset.findPrivateKey({\n usage: 'sign',\n kid: authMethod.kid,\n alg: supportedAlgs(serverMetadata),\n })\n\n // https://www.rfc-editor.org/rfc/rfc7523.html#section-3\n return async () => ({\n payload: {\n client_id: clientMetadata.client_id,\n client_assertion_type: CLIENT_ASSERTION_TYPE_JWT_BEARER,\n client_assertion: await key.createJwt(\n { alg },\n {\n // > The JWT MUST contain an \"iss\" (issuer) claim that contains a\n // > unique identifier for the entity that issued the JWT.\n iss: clientMetadata.client_id,\n // > For client authentication, the subject MUST be the\n // > \"client_id\" of the OAuth client.\n sub: clientMetadata.client_id,\n // > The JWT MUST contain an \"aud\" (audience) claim containing a value\n // > that identifies the authorization server as an intended audience.\n // > The token endpoint URL of the authorization server MAY be used as a\n // > value for an \"aud\" element to identify the authorization server as an\n // > intended audience of the JWT.\n aud: serverMetadata.issuer,\n // > The JWT MAY contain a \"jti\" (JWT ID) claim that provides a\n // > unique identifier for the token.\n jti: await runtime.generateNonce(),\n // > The JWT MAY contain an \"iat\" (issued at) claim that\n // > identifies the time at which the JWT was issued.\n iat: Math.floor(Date.now() / 1000),\n // > The JWT MUST contain an \"exp\" (expiration time) claim that\n // > limits the time window during which the JWT can be used.\n exp: Math.floor(Date.now() / 1000) + 60, // 1 minute\n },\n ),\n },\n })\n } catch (cause) {\n throw new AuthMethodUnsatisfiableError('Failed to load private key', {\n cause,\n })\n }\n }\n\n throw new AuthMethodUnsatisfiableError(\n // @ts-expect-error\n `Unsupported auth method ${authMethod.method}`,\n )\n}\n\nfunction supportedMethods(serverMetadata: OAuthAuthorizationServerMetadata) {\n return serverMetadata['token_endpoint_auth_methods_supported']\n}\n\nfunction supportedAlgs(serverMetadata: OAuthAuthorizationServerMetadata) {\n return (\n serverMetadata['token_endpoint_auth_signing_alg_values_supported'] ?? [\n // @NOTE If not specified, assume that the server supports the ES256\n // algorithm, as prescribed by the spec:\n //\n // > Clients and Authorization Servers currently must support the ES256\n // > cryptographic system [for client authentication].\n //\n // https://atproto.com/specs/oauth#confidential-client-authentication\n FALLBACK_ALG,\n ]\n )\n}\n"]}
|
package/dist/oauth-client.d.ts
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
import { Key, Keyset } from '@atproto/jwk';
|
|
2
|
-
import { OAuthClientIdDiscoverable, OAuthClientMetadata, OAuthClientMetadataInput, OAuthResponseMode } from '@atproto/oauth-types';
|
|
3
|
-
import { AtprotoDid, DidCache } from '@atproto-labs/did-resolver';
|
|
4
|
-
import { Fetch } from '@atproto-labs/fetch';
|
|
5
|
-
import { HandleCache, HandleResolver } from '@atproto-labs/handle-resolver';
|
|
6
|
-
import { CreateIdentityResolverOptions } from './identity-resolver.js';
|
|
7
|
-
import { AuthorizationServerMetadataCache } from './oauth-authorization-server-metadata-resolver.js';
|
|
8
|
-
import { ProtectedResourceMetadataCache } from './oauth-protected-resource-metadata-resolver.js';
|
|
2
|
+
import { type OAuthClientIdDiscoverable, type OAuthClientMetadata, type OAuthClientMetadataInput, type OAuthResponseMode } from '@atproto/oauth-types';
|
|
3
|
+
import { type AtprotoDid, type DidCache } from '@atproto-labs/did-resolver';
|
|
4
|
+
import type { Fetch } from '@atproto-labs/fetch';
|
|
5
|
+
import type { HandleCache, HandleResolver } from '@atproto-labs/handle-resolver';
|
|
6
|
+
import { type CreateIdentityResolverOptions } from './identity-resolver.js';
|
|
7
|
+
import { type AuthorizationServerMetadataCache } from './oauth-authorization-server-metadata-resolver.js';
|
|
8
|
+
import { type ProtectedResourceMetadataCache } from './oauth-protected-resource-metadata-resolver.js';
|
|
9
9
|
import { OAuthResolver } from './oauth-resolver.js';
|
|
10
|
-
import { DpopNonceCache, OAuthServerAgent } from './oauth-server-agent.js';
|
|
10
|
+
import type { DpopNonceCache, OAuthServerAgent } from './oauth-server-agent.js';
|
|
11
11
|
import { OAuthServerFactory } from './oauth-server-factory.js';
|
|
12
12
|
import { OAuthSession } from './oauth-session.js';
|
|
13
|
-
import { RuntimeImplementation } from './runtime-implementation.js';
|
|
13
|
+
import type { RuntimeImplementation } from './runtime-implementation.js';
|
|
14
14
|
import { Runtime } from './runtime.js';
|
|
15
|
-
import { SessionGetter, SessionHooks, SessionStore } from './session-getter.js';
|
|
16
|
-
import { InternalStateData, StateStore } from './state-store.js';
|
|
17
|
-
import { AuthorizeOptions, CallbackOptions, ClientMetadata } from './types.js';
|
|
15
|
+
import { SessionGetter, type SessionHooks, type SessionStore } from './session-getter.js';
|
|
16
|
+
import type { InternalStateData, StateStore } from './state-store.js';
|
|
17
|
+
import type { AuthorizeOptions, CallbackOptions, ClientMetadata } from './types.js';
|
|
18
18
|
export type { AuthorizationServerMetadataCache, CreateIdentityResolverOptions, DidCache, DpopNonceCache, Fetch, HandleCache, HandleResolver, InternalStateData, OAuthClientMetadata, OAuthClientMetadataInput, OAuthResponseMode, ProtectedResourceMetadataCache, RuntimeImplementation, SessionHooks, SessionStore, StateStore, };
|
|
19
19
|
export { Key, Keyset };
|
|
20
20
|
export type OAuthClientOptions = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth-client.d.ts","sourceRoot":"","sources":["../src/oauth-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AAC1C,OAAO,EAEL,yBAAyB,
|
|
1
|
+
{"version":3,"file":"oauth-client.d.ts","sourceRoot":"","sources":["../src/oauth-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AAC1C,OAAO,EAEL,KAAK,yBAAyB,EAC9B,KAAK,mBAAmB,EACxB,KAAK,wBAAwB,EAC7B,KAAK,iBAAiB,EAEvB,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EACL,KAAK,UAAU,EACf,KAAK,QAAQ,EAId,MAAM,4BAA4B,CAAA;AACnC,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAA;AAChD,OAAO,KAAK,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAA;AAMhF,OAAO,EACL,KAAK,6BAA6B,EAEnC,MAAM,wBAAwB,CAAA;AAC/B,OAAO,EACL,KAAK,gCAAgC,EAEtC,MAAM,mDAAmD,CAAA;AAG1D,OAAO,EAEL,KAAK,8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AC;YACH,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,aAAa,CAAC,UAAU,CAChD,QAAQ,CAAC,GAAG,EACZ,UAAU,EACV,OAAO,CACR,CAAA;YACD,MAAM,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAA;QAC5C,CAAC;gBAAS,CAAC;YACT,MAAM,IAAI,CAAC,aAAa,CAAC,SAAS,CAAC,GAAG,EAAE,IAAI,iBAAiB,CAAC,GAAG,CAAC,CAAC,CAAA;QACrE,CAAC;IACH,CAAC;IAES,aAAa,CACrB,MAAwB,EACxB,GAAe;QAEf,OAAO,IAAI,YAAY,CAAC,MAAM,EAAE,GAAG,EAAE,IAAI,CAAC,aAAa,EAAE,IAAI,CAAC,KAAK,CAAC,CAAA;IACtE,CAAC;CACF","sourcesContent":["import { Key, Keyset } from '@atproto/jwk'\nimport {\n OAuthAuthorizationRequestParameters,\n OAuthClientIdDiscoverable,\n OAuthClientMetadata,\n OAuthClientMetadataInput,\n OAuthResponseMode,\n oauthClientMetadataSchema,\n} from '@atproto/oauth-types'\nimport {\n AtprotoDid,\n DidCache,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n type DidResolverCommonOptions,\n assertAtprotoDid,\n} from '@atproto-labs/did-resolver'\nimport { Fetch } from '@atproto-labs/fetch'\nimport { HandleCache, HandleResolver } from '@atproto-labs/handle-resolver'\nimport { HANDLE_INVALID } from '@atproto-labs/identity-resolver'\nimport { SimpleStoreMemory } from '@atproto-labs/simple-store-memory'\nimport { FALLBACK_ALG } from './constants.js'\nimport { AuthMethodUnsatisfiableError } from './errors/auth-method-unsatisfiable-error.js'\nimport { TokenRevokedError } from './errors/token-revoked-error.js'\nimport {\n CreateIdentityResolverOptions,\n createIdentityResolver,\n} from './identity-resolver.js'\nimport {\n AuthorizationServerMetadataCache,\n OAuthAuthorizationServerMetadataResolver,\n} from './oauth-authorization-server-metadata-resolver.js'\nimport { OAuthCallbackError } from './oauth-callback-error.js'\nimport { negotiateClientAuthMethod } from './oauth-client-auth.js'\nimport {\n OAuthProtectedResourceMetadataResolver,\n ProtectedResourceMetadataCache,\n} from './oauth-protected-resource-metadata-resolver.js'\nimport { OAuthResolver } from './oauth-resolver.js'\nimport { DpopNonceCache, OAuthServerAgent } from './oauth-server-agent.js'\nimport { OAuthServerFactory } from './oauth-server-factory.js'\nimport { OAuthSession } from './oauth-session.js'\nimport { RuntimeImplementation } from './runtime-implementation.js'\nimport { Runtime } from './runtime.js'\nimport {\n SessionGetter,\n SessionHooks,\n SessionStore,\n isExpectedSessionError,\n} from './session-getter.js'\nimport { InternalStateData, StateStore } from './state-store.js'\nimport { AuthorizeOptions, CallbackOptions, ClientMetadata } from './types.js'\nimport { validateClientMetadata } from './validate-client-metadata.js'\n\n// Export all types needed to construct OAuthClientOptions\nexport type {\n AuthorizationServerMetadataCache,\n CreateIdentityResolverOptions,\n DidCache,\n DpopNonceCache,\n Fetch,\n HandleCache,\n HandleResolver,\n InternalStateData,\n OAuthClientMetadata,\n OAuthClientMetadataInput,\n OAuthResponseMode,\n ProtectedResourceMetadataCache,\n RuntimeImplementation,\n SessionHooks,\n SessionStore,\n StateStore,\n}\n\nexport { Key, Keyset }\n\nexport type OAuthClientOptions = {\n // Config\n responseMode: OAuthResponseMode\n clientMetadata: Readonly<OAuthClientMetadataInput>\n keyset?: Keyset | Iterable<Key | undefined | null | false>\n /**\n * Determines if the client will allow communicating with the OAuth Servers\n * (Authorization & Resource), or to retrieve \"did:web\" documents, over\n * unsafe HTTP connections. It is recommended to set this to `true` only for\n * development purposes.\n *\n * @note This does not affect the identity resolution mechanism, which will\n * allow HTTP connections to the PLC Directory (if the provided directory url\n * is \"http:\" based).\n * @default false\n * @see {@link OAuthProtectedResourceMetadataResolver.allowHttpResource}\n * @see {@link OAuthAuthorizationServerMetadataResolver.allowHttpIssuer}\n * @see {@link DidResolverCommonOptions.allowHttp}\n */\n allowHttp?: boolean\n\n // Stores\n stateStore: StateStore\n sessionStore: SessionStore\n authorizationServerMetadataCache?: AuthorizationServerMetadataCache\n protectedResourceMetadataCache?: ProtectedResourceMetadataCache\n dpopNonceCache?: DpopNonceCache\n\n // Services\n runtimeImplementation: RuntimeImplementation\n fetch?: Fetch\n} & CreateIdentityResolverOptions &\n SessionHooks\n\nexport type OAuthClientFetchMetadataOptions = {\n clientId: OAuthClientIdDiscoverable\n fetch?: Fetch\n signal?: AbortSignal\n}\n\nexport class OAuthClient {\n static async fetchMetadata({\n clientId,\n fetch = globalThis.fetch,\n signal,\n }: OAuthClientFetchMetadataOptions) {\n signal?.throwIfAborted()\n\n const request = new Request(clientId, {\n redirect: 'error',\n signal: signal,\n })\n const response = await fetch(request)\n\n if (response.status !== 200) {\n response.body?.cancel?.()\n throw new TypeError(`Failed to fetch client metadata: ${response.status}`)\n }\n\n // https://www.ietf.org/archive/id/draft-ietf-oauth-client-id-metadata-document-00.html#section-4.1\n const mime = response.headers.get('content-type')?.split(';')[0].trim()\n if (mime !== 'application/json') {\n response.body?.cancel?.()\n throw new TypeError(`Invalid client metadata content type: ${mime}`)\n }\n\n const json: unknown = await response.json()\n\n signal?.throwIfAborted()\n\n return oauthClientMetadataSchema.parse(json)\n }\n\n // Config\n readonly clientMetadata: ClientMetadata\n readonly responseMode: OAuthResponseMode\n readonly keyset?: Keyset\n\n // Services\n readonly runtime: Runtime\n readonly fetch: Fetch\n readonly oauthResolver: OAuthResolver\n readonly serverFactory: OAuthServerFactory\n\n // Stores\n protected readonly sessionGetter: SessionGetter\n protected readonly stateStore: StateStore\n\n constructor(options: OAuthClientOptions) {\n const {\n stateStore,\n sessionStore,\n\n dpopNonceCache = new SimpleStoreMemory({ ttl: 60e3, max: 100 }),\n authorizationServerMetadataCache = new SimpleStoreMemory({\n ttl: 60e3,\n max: 100,\n }),\n protectedResourceMetadataCache = new SimpleStoreMemory({\n ttl: 60e3,\n max: 100,\n }),\n\n responseMode,\n clientMetadata,\n runtimeImplementation,\n keyset,\n } = options\n\n this.keyset = keyset\n ? keyset instanceof Keyset\n ? keyset\n : new Keyset(keyset)\n : undefined\n this.clientMetadata = validateClientMetadata(clientMetadata, this.keyset)\n this.responseMode = responseMode\n\n this.runtime = new Runtime(runtimeImplementation)\n this.fetch = options.fetch ?? globalThis.fetch\n this.oauthResolver = new OAuthResolver(\n createIdentityResolver(options),\n new OAuthProtectedResourceMetadataResolver(\n protectedResourceMetadataCache,\n this.fetch,\n { allowHttpResource: options.allowHttp },\n ),\n new OAuthAuthorizationServerMetadataResolver(\n authorizationServerMetadataCache,\n this.fetch,\n { allowHttpIssuer: options.allowHttp },\n ),\n )\n this.serverFactory = new OAuthServerFactory(\n this.clientMetadata,\n this.runtime,\n this.oauthResolver,\n this.fetch,\n this.keyset,\n dpopNonceCache,\n )\n\n this.stateStore = stateStore\n this.sessionGetter = new SessionGetter(\n sessionStore,\n this.serverFactory,\n this.runtime,\n options,\n )\n }\n\n // Exposed as public API for convenience\n get identityResolver() {\n return this.oauthResolver.identityResolver\n }\n\n get jwks() {\n return this.keyset?.publicJwks ?? ({ keys: [] as const } as const)\n }\n\n async authorize(\n input: string,\n { signal, ...options }: AuthorizeOptions = {},\n ): Promise<URL> {\n const redirectUri =\n options?.redirect_uri ?? this.clientMetadata.redirect_uris[0]\n if (!this.clientMetadata.redirect_uris.includes(redirectUri)) {\n // The server will enforce this, but let's catch it early\n throw new TypeError('Invalid redirect_uri')\n }\n\n const { identityInfo, metadata } = await this.oauthResolver.resolve(input, {\n signal,\n })\n\n const pkce = await this.runtime.generatePKCE()\n const dpopKey = await this.runtime.generateKey(\n metadata.dpop_signing_alg_values_supported || [FALLBACK_ALG],\n )\n\n const authMethod = negotiateClientAuthMethod(\n metadata,\n this.clientMetadata,\n this.keyset,\n )\n const state = await this.runtime.generateNonce()\n\n await this.stateStore.set(state, {\n iss: metadata.issuer,\n dpopKey,\n authMethod,\n verifier: pkce.verifier,\n appState: options?.state,\n })\n\n const parameters: OAuthAuthorizationRequestParameters = {\n ...options,\n\n client_id: this.clientMetadata.client_id,\n redirect_uri: redirectUri,\n code_challenge: pkce.challenge,\n code_challenge_method: pkce.method,\n state,\n login_hint: identityInfo\n ? identityInfo.handle !== HANDLE_INVALID\n ? identityInfo.handle\n : identityInfo.did\n : undefined,\n response_mode: this.responseMode,\n response_type: 'code' as const,\n scope: options?.scope ?? this.clientMetadata.scope,\n }\n\n const authorizationUrl = new URL(metadata.authorization_endpoint)\n\n // Since the user will be redirected to the authorization_endpoint url using\n // a browser, we need to make sure that the url is valid.\n if (\n authorizationUrl.protocol !== 'https:' &&\n authorizationUrl.protocol !== 'http:'\n ) {\n throw new TypeError(\n `Invalid authorization endpoint protocol: ${authorizationUrl.protocol}`,\n )\n }\n\n if (metadata.pushed_authorization_request_endpoint) {\n const server = await this.serverFactory.fromMetadata(\n metadata,\n authMethod,\n dpopKey,\n )\n const parResponse = await server.request(\n 'pushed_authorization_request',\n parameters,\n )\n\n authorizationUrl.searchParams.set(\n 'client_id',\n this.clientMetadata.client_id,\n )\n authorizationUrl.searchParams.set('request_uri', parResponse.request_uri)\n return authorizationUrl\n } else if (metadata.require_pushed_authorization_requests) {\n throw new Error(\n 'Server requires pushed authorization requests (PAR) but no PAR endpoint is available',\n )\n } else {\n for (const [key, value] of Object.entries(parameters)) {\n if (value) authorizationUrl.searchParams.set(key, String(value))\n }\n\n // Length of the URL that will be sent to the server\n const urlLength =\n authorizationUrl.pathname.length + authorizationUrl.search.length\n if (urlLength < 2048) {\n return authorizationUrl\n } else if (!metadata.pushed_authorization_request_endpoint) {\n throw new Error('Login URL too long')\n }\n }\n\n throw new Error(\n 'Server does not support pushed authorization requests (PAR)',\n )\n }\n\n /**\n * This method allows the client to proactively revoke the request_uri it\n * created through PAR.\n */\n async abortRequest(authorizeUrl: URL) {\n const requestUri = authorizeUrl.searchParams.get('request_uri')\n if (!requestUri) return\n\n // @NOTE This is not implemented here because, 1) the request server should\n // invalidate the request_uri after some delay anyways, and 2) I am not sure\n // that the revocation endpoint is even supposed to support this (and I\n // don't want to spend the time checking now).\n\n // @TODO investigate actual necessity & feasibility of this feature\n }\n\n async callback(\n params: URLSearchParams,\n options: CallbackOptions = {},\n ): Promise<{\n session: OAuthSession\n state: string | null\n }> {\n const responseJwt = params.get('response')\n if (responseJwt != null) {\n // https://openid.net/specs/oauth-v2-jarm.html\n throw new OAuthCallbackError(params, 'JARM not supported')\n }\n\n const issuerParam = params.get('iss')\n const stateParam = params.get('state')\n const errorParam = params.get('error')\n const codeParam = params.get('code')\n\n if (!stateParam) {\n throw new OAuthCallbackError(params, 'Missing \"state\" parameter')\n }\n const stateData = await this.stateStore.get(stateParam)\n if (stateData) {\n // Prevent any kind of replay\n await this.stateStore.del(stateParam)\n } else {\n throw new OAuthCallbackError(\n params,\n `Unknown authorization session \"${stateParam}\"`,\n )\n }\n\n try {\n if (errorParam != null) {\n throw new OAuthCallbackError(params, undefined, stateData.appState)\n }\n\n if (!codeParam) {\n throw new OAuthCallbackError(\n params,\n 'Missing \"code\" query param',\n stateData.appState,\n )\n }\n\n const server = await this.serverFactory.fromIssuer(\n stateData.iss,\n stateData.authMethod,\n stateData.dpopKey,\n )\n\n if (issuerParam != null) {\n if (!server.issuer) {\n throw new OAuthCallbackError(\n params,\n 'Issuer not found in metadata',\n stateData.appState,\n )\n }\n if (server.issuer !== issuerParam) {\n throw new OAuthCallbackError(\n params,\n 'Issuer mismatch',\n stateData.appState,\n )\n }\n } else if (\n server.serverMetadata.authorization_response_iss_parameter_supported\n ) {\n throw new OAuthCallbackError(\n params,\n 'iss missing from the response',\n stateData.appState,\n )\n }\n\n const tokenSet = await server.exchangeCode(\n codeParam,\n stateData.verifier,\n options?.redirect_uri ?? server.clientMetadata.redirect_uris[0],\n )\n\n // We revoke any existing session first to avoid leaving orphaned sessions\n // on the AS.\n try {\n await this.revoke(tokenSet.sub)\n } catch {\n // No existing session, or failed to get it. This is fine.\n }\n\n try {\n await this.sessionGetter.setStored(tokenSet.sub, {\n dpopKey: stateData.dpopKey,\n authMethod: server.authMethod,\n tokenSet,\n })\n\n const session = this.createSession(server, tokenSet.sub)\n\n return { session, state: stateData.appState ?? null }\n } catch (err) {\n await server.revoke(tokenSet.refresh_token || tokenSet.access_token)\n\n throw err\n }\n } catch (err) {\n // Make sure, whatever the underlying error, that the appState is\n // available in the calling code\n throw OAuthCallbackError.from(err, params, stateData.appState)\n }\n }\n\n /**\n * Load a stored session. This will refresh the token only if needed (about to\n * expire) by default.\n *\n * @see {@link SessionGetter.restore}\n */\n async restore(\n sub: string,\n refresh: boolean | 'auto' = 'auto',\n ): Promise<OAuthSession> {\n // sub arg is lightly typed for convenience of library user\n assertAtprotoDid(sub)\n\n const { dpopKey, authMethod, tokenSet } =\n await this.sessionGetter.getSession(sub, refresh)\n\n try {\n const server = await this.serverFactory.fromIssuer(\n tokenSet.iss,\n authMethod,\n dpopKey,\n {\n noCache: refresh === true,\n allowStale: refresh === false,\n },\n )\n\n return this.createSession(server, sub)\n } catch (err) {\n if (err instanceof AuthMethodUnsatisfiableError) {\n await this.sessionGetter.delStored(sub, err)\n }\n\n throw err\n }\n }\n\n async revoke(sub: string) {\n // sub arg is lightly typed for convenience of library user\n assertAtprotoDid(sub)\n\n const res = await this.sessionGetter.getSession(sub, false).catch((err) => {\n if (isExpectedSessionError(err)) return null\n throw err\n })\n\n if (!res) return\n\n const { dpopKey, authMethod, tokenSet } = res\n\n // NOT using `;(await this.restore(sub, false)).signOut()` because we want\n // the tokens to be deleted even if it was not possible to fetch the issuer\n // data.\n try {\n const server = await this.serverFactory.fromIssuer(\n tokenSet.iss,\n authMethod,\n dpopKey,\n )\n await server.revoke(tokenSet.access_token)\n } finally {\n await this.sessionGetter.delStored(sub, new TokenRevokedError(sub))\n }\n }\n\n protected createSession(\n server: OAuthServerAgent,\n sub: AtprotoDid,\n ): OAuthSession {\n return new OAuthSession(server, sub, this.sessionGetter, this.fetch)\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"oauth-client.js","sourceRoot":"","sources":["../src/oauth-client.ts"],"names":[],"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QAErB,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,aAAa,CAAC,UAAU,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;YACxE,IAAI,sBAAsB,CAAC,GAAG,CAAC;gBAAE,OAAO,IAAI,CAAA;YAC5C,MAAM,GAAG,CAAA;QACX,CAAC,CAAC,CAAA;QAEF,IAAI,CAAC,GAAG;YAAE,OAAM;QAEhB,MAAM,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,GAAG,GAAG,CAAA;QAE7C,0EAA0E;QAC1E,2EAA2E;QAC3E,QAAQ;QACR,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,aAAa,CAAC,UAAU,CAChD,QAAQ,CAAC,GAAG,EACZ,UAAU,EACV,OAAO,CACR,CAAA;YACD,MAAM,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAA;QAC5C,CAAC;gBAAS,CAAC;YACT,MAAM,IAAI,CAAC,aAAa,CAAC,SAAS,CAAC,GAAG,EAAE,IAAI,iBAAiB,CAAC,GAAG,CAAC,CAAC,CAAA;QACrE,CAAC;IACH,CAAC;IAES,aAAa,CACrB,MAAwB,EACxB,GAAe;QAEf,OAAO,IAAI,YAAY,CAAC,MAAM,EAAE,GAAG,EAAE,IAAI,CAAC,aAAa,EAAE,IAAI,CAAC,KAAK,CAAC,CAAA;IACtE,CAAC;CACF","sourcesContent":["import { Key, Keyset } from '@atproto/jwk'\nimport {\n type OAuthAuthorizationRequestParameters,\n type OAuthClientIdDiscoverable,\n type OAuthClientMetadata,\n type OAuthClientMetadataInput,\n type OAuthResponseMode,\n oauthClientMetadataSchema,\n} from '@atproto/oauth-types'\nimport {\n type AtprotoDid,\n type DidCache,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n type DidResolverCommonOptions,\n assertAtprotoDid,\n} from '@atproto-labs/did-resolver'\nimport type { Fetch } from '@atproto-labs/fetch'\nimport type { HandleCache, HandleResolver } from '@atproto-labs/handle-resolver'\nimport { HANDLE_INVALID } from '@atproto-labs/identity-resolver'\nimport { SimpleStoreMemory } from '@atproto-labs/simple-store-memory'\nimport { FALLBACK_ALG } from './constants.js'\nimport { AuthMethodUnsatisfiableError } from './errors/auth-method-unsatisfiable-error.js'\nimport { TokenRevokedError } from './errors/token-revoked-error.js'\nimport {\n type CreateIdentityResolverOptions,\n createIdentityResolver,\n} from './identity-resolver.js'\nimport {\n type AuthorizationServerMetadataCache,\n OAuthAuthorizationServerMetadataResolver,\n} from './oauth-authorization-server-metadata-resolver.js'\nimport { OAuthCallbackError } from './oauth-callback-error.js'\nimport { negotiateClientAuthMethod } from './oauth-client-auth.js'\nimport {\n OAuthProtectedResourceMetadataResolver,\n type ProtectedResourceMetadataCache,\n} from './oauth-protected-resource-metadata-resolver.js'\nimport { OAuthResolver } from './oauth-resolver.js'\nimport type { DpopNonceCache, OAuthServerAgent } from './oauth-server-agent.js'\nimport { OAuthServerFactory } from './oauth-server-factory.js'\nimport { OAuthSession } from './oauth-session.js'\nimport type { RuntimeImplementation } from './runtime-implementation.js'\nimport { Runtime } from './runtime.js'\nimport {\n SessionGetter,\n type SessionHooks,\n type SessionStore,\n isExpectedSessionError,\n} from './session-getter.js'\nimport type { InternalStateData, StateStore } from './state-store.js'\nimport type {\n AuthorizeOptions,\n CallbackOptions,\n ClientMetadata,\n} from './types.js'\nimport { validateClientMetadata } from './validate-client-metadata.js'\n\n// Export all types needed to construct OAuthClientOptions\nexport type {\n AuthorizationServerMetadataCache,\n CreateIdentityResolverOptions,\n DidCache,\n DpopNonceCache,\n Fetch,\n HandleCache,\n HandleResolver,\n InternalStateData,\n OAuthClientMetadata,\n OAuthClientMetadataInput,\n OAuthResponseMode,\n ProtectedResourceMetadataCache,\n RuntimeImplementation,\n SessionHooks,\n SessionStore,\n StateStore,\n}\n\nexport { Key, Keyset }\n\nexport type OAuthClientOptions = {\n // Config\n responseMode: OAuthResponseMode\n clientMetadata: Readonly<OAuthClientMetadataInput>\n keyset?: Keyset | Iterable<Key | undefined | null | false>\n /**\n * Determines if the client will allow communicating with the OAuth Servers\n * (Authorization & Resource), or to retrieve \"did:web\" documents, over\n * unsafe HTTP connections. It is recommended to set this to `true` only for\n * development purposes.\n *\n * @note This does not affect the identity resolution mechanism, which will\n * allow HTTP connections to the PLC Directory (if the provided directory url\n * is \"http:\" based).\n * @default false\n * @see {@link OAuthProtectedResourceMetadataResolver.allowHttpResource}\n * @see {@link OAuthAuthorizationServerMetadataResolver.allowHttpIssuer}\n * @see {@link DidResolverCommonOptions.allowHttp}\n */\n allowHttp?: boolean\n\n // Stores\n stateStore: StateStore\n sessionStore: SessionStore\n authorizationServerMetadataCache?: AuthorizationServerMetadataCache\n protectedResourceMetadataCache?: ProtectedResourceMetadataCache\n dpopNonceCache?: DpopNonceCache\n\n // Services\n runtimeImplementation: RuntimeImplementation\n fetch?: Fetch\n} & CreateIdentityResolverOptions &\n SessionHooks\n\nexport type OAuthClientFetchMetadataOptions = {\n clientId: OAuthClientIdDiscoverable\n fetch?: Fetch\n signal?: AbortSignal\n}\n\nexport class OAuthClient {\n static async fetchMetadata({\n clientId,\n fetch = globalThis.fetch,\n signal,\n }: OAuthClientFetchMetadataOptions) {\n signal?.throwIfAborted()\n\n const request = new Request(clientId, {\n redirect: 'error',\n signal: signal,\n })\n const response = await fetch(request)\n\n if (response.status !== 200) {\n response.body?.cancel?.()\n throw new TypeError(`Failed to fetch client metadata: ${response.status}`)\n }\n\n // https://www.ietf.org/archive/id/draft-ietf-oauth-client-id-metadata-document-00.html#section-4.1\n const mime = response.headers.get('content-type')?.split(';')[0].trim()\n if (mime !== 'application/json') {\n response.body?.cancel?.()\n throw new TypeError(`Invalid client metadata content type: ${mime}`)\n }\n\n const json: unknown = await response.json()\n\n signal?.throwIfAborted()\n\n return oauthClientMetadataSchema.parse(json)\n }\n\n // Config\n readonly clientMetadata: ClientMetadata\n readonly responseMode: OAuthResponseMode\n readonly keyset?: Keyset\n\n // Services\n readonly runtime: Runtime\n readonly fetch: Fetch\n readonly oauthResolver: OAuthResolver\n readonly serverFactory: OAuthServerFactory\n\n // Stores\n protected readonly sessionGetter: SessionGetter\n protected readonly stateStore: StateStore\n\n constructor(options: OAuthClientOptions) {\n const {\n stateStore,\n sessionStore,\n\n dpopNonceCache = new SimpleStoreMemory({ ttl: 60e3, max: 100 }),\n authorizationServerMetadataCache = new SimpleStoreMemory({\n ttl: 60e3,\n max: 100,\n }),\n protectedResourceMetadataCache = new SimpleStoreMemory({\n ttl: 60e3,\n max: 100,\n }),\n\n responseMode,\n clientMetadata,\n runtimeImplementation,\n keyset,\n } = options\n\n this.keyset = keyset\n ? keyset instanceof Keyset\n ? keyset\n : new Keyset(keyset)\n : undefined\n this.clientMetadata = validateClientMetadata(clientMetadata, this.keyset)\n this.responseMode = responseMode\n\n this.runtime = new Runtime(runtimeImplementation)\n this.fetch = options.fetch ?? globalThis.fetch\n this.oauthResolver = new OAuthResolver(\n createIdentityResolver(options),\n new OAuthProtectedResourceMetadataResolver(\n protectedResourceMetadataCache,\n this.fetch,\n { allowHttpResource: options.allowHttp },\n ),\n new OAuthAuthorizationServerMetadataResolver(\n authorizationServerMetadataCache,\n this.fetch,\n { allowHttpIssuer: options.allowHttp },\n ),\n )\n this.serverFactory = new OAuthServerFactory(\n this.clientMetadata,\n this.runtime,\n this.oauthResolver,\n this.fetch,\n this.keyset,\n dpopNonceCache,\n )\n\n this.stateStore = stateStore\n this.sessionGetter = new SessionGetter(\n sessionStore,\n this.serverFactory,\n this.runtime,\n options,\n )\n }\n\n // Exposed as public API for convenience\n get identityResolver() {\n return this.oauthResolver.identityResolver\n }\n\n get jwks() {\n return this.keyset?.publicJwks ?? ({ keys: [] as const } as const)\n }\n\n async authorize(\n input: string,\n { signal, ...options }: AuthorizeOptions = {},\n ): Promise<URL> {\n const redirectUri =\n options?.redirect_uri ?? this.clientMetadata.redirect_uris[0]\n if (!this.clientMetadata.redirect_uris.includes(redirectUri)) {\n // The server will enforce this, but let's catch it early\n throw new TypeError('Invalid redirect_uri')\n }\n\n const { identityInfo, metadata } = await this.oauthResolver.resolve(input, {\n signal,\n })\n\n const pkce = await this.runtime.generatePKCE()\n const dpopKey = await this.runtime.generateKey(\n metadata.dpop_signing_alg_values_supported || [FALLBACK_ALG],\n )\n\n const authMethod = negotiateClientAuthMethod(\n metadata,\n this.clientMetadata,\n this.keyset,\n )\n const state = await this.runtime.generateNonce()\n\n await this.stateStore.set(state, {\n iss: metadata.issuer,\n dpopKey,\n authMethod,\n verifier: pkce.verifier,\n appState: options?.state,\n })\n\n const parameters: OAuthAuthorizationRequestParameters = {\n ...options,\n\n client_id: this.clientMetadata.client_id,\n redirect_uri: redirectUri,\n code_challenge: pkce.challenge,\n code_challenge_method: pkce.method,\n state,\n login_hint: identityInfo\n ? identityInfo.handle !== HANDLE_INVALID\n ? identityInfo.handle\n : identityInfo.did\n : undefined,\n response_mode: this.responseMode,\n response_type: 'code' as const,\n scope: options?.scope ?? this.clientMetadata.scope,\n }\n\n const authorizationUrl = new URL(metadata.authorization_endpoint)\n\n // Since the user will be redirected to the authorization_endpoint url using\n // a browser, we need to make sure that the url is valid.\n if (\n authorizationUrl.protocol !== 'https:' &&\n authorizationUrl.protocol !== 'http:'\n ) {\n throw new TypeError(\n `Invalid authorization endpoint protocol: ${authorizationUrl.protocol}`,\n )\n }\n\n if (metadata.pushed_authorization_request_endpoint) {\n const server = await this.serverFactory.fromMetadata(\n metadata,\n authMethod,\n dpopKey,\n )\n const parResponse = await server.request(\n 'pushed_authorization_request',\n parameters,\n )\n\n authorizationUrl.searchParams.set(\n 'client_id',\n this.clientMetadata.client_id,\n )\n authorizationUrl.searchParams.set('request_uri', parResponse.request_uri)\n return authorizationUrl\n } else if (metadata.require_pushed_authorization_requests) {\n throw new Error(\n 'Server requires pushed authorization requests (PAR) but no PAR endpoint is available',\n )\n } else {\n for (const [key, value] of Object.entries(parameters)) {\n if (value) authorizationUrl.searchParams.set(key, String(value))\n }\n\n // Length of the URL that will be sent to the server\n const urlLength =\n authorizationUrl.pathname.length + authorizationUrl.search.length\n if (urlLength < 2048) {\n return authorizationUrl\n } else if (!metadata.pushed_authorization_request_endpoint) {\n throw new Error('Login URL too long')\n }\n }\n\n throw new Error(\n 'Server does not support pushed authorization requests (PAR)',\n )\n }\n\n /**\n * This method allows the client to proactively revoke the request_uri it\n * created through PAR.\n */\n async abortRequest(authorizeUrl: URL) {\n const requestUri = authorizeUrl.searchParams.get('request_uri')\n if (!requestUri) return\n\n // @NOTE This is not implemented here because, 1) the request server should\n // invalidate the request_uri after some delay anyways, and 2) I am not sure\n // that the revocation endpoint is even supposed to support this (and I\n // don't want to spend the time checking now).\n\n // @TODO investigate actual necessity & feasibility of this feature\n }\n\n async callback(\n params: URLSearchParams,\n options: CallbackOptions = {},\n ): Promise<{\n session: OAuthSession\n state: string | null\n }> {\n const responseJwt = params.get('response')\n if (responseJwt != null) {\n // https://openid.net/specs/oauth-v2-jarm.html\n throw new OAuthCallbackError(params, 'JARM not supported')\n }\n\n const issuerParam = params.get('iss')\n const stateParam = params.get('state')\n const errorParam = params.get('error')\n const codeParam = params.get('code')\n\n if (!stateParam) {\n throw new OAuthCallbackError(params, 'Missing \"state\" parameter')\n }\n const stateData = await this.stateStore.get(stateParam)\n if (stateData) {\n // Prevent any kind of replay\n await this.stateStore.del(stateParam)\n } else {\n throw new OAuthCallbackError(\n params,\n `Unknown authorization session \"${stateParam}\"`,\n )\n }\n\n try {\n if (errorParam != null) {\n throw new OAuthCallbackError(params, undefined, stateData.appState)\n }\n\n if (!codeParam) {\n throw new OAuthCallbackError(\n params,\n 'Missing \"code\" query param',\n stateData.appState,\n )\n }\n\n const server = await this.serverFactory.fromIssuer(\n stateData.iss,\n stateData.authMethod,\n stateData.dpopKey,\n )\n\n if (issuerParam != null) {\n if (!server.issuer) {\n throw new OAuthCallbackError(\n params,\n 'Issuer not found in metadata',\n stateData.appState,\n )\n }\n if (server.issuer !== issuerParam) {\n throw new OAuthCallbackError(\n params,\n 'Issuer mismatch',\n stateData.appState,\n )\n }\n } else if (\n server.serverMetadata.authorization_response_iss_parameter_supported\n ) {\n throw new OAuthCallbackError(\n params,\n 'iss missing from the response',\n stateData.appState,\n )\n }\n\n const tokenSet = await server.exchangeCode(\n codeParam,\n stateData.verifier,\n options?.redirect_uri ?? server.clientMetadata.redirect_uris[0],\n )\n\n // We revoke any existing session first to avoid leaving orphaned sessions\n // on the AS.\n try {\n await this.revoke(tokenSet.sub)\n } catch {\n // No existing session, or failed to get it. This is fine.\n }\n\n try {\n await this.sessionGetter.setStored(tokenSet.sub, {\n dpopKey: stateData.dpopKey,\n authMethod: server.authMethod,\n tokenSet,\n })\n\n const session = this.createSession(server, tokenSet.sub)\n\n return { session, state: stateData.appState ?? null }\n } catch (err) {\n await server.revoke(tokenSet.refresh_token || tokenSet.access_token)\n\n throw err\n }\n } catch (err) {\n // Make sure, whatever the underlying error, that the appState is\n // available in the calling code\n throw OAuthCallbackError.from(err, params, stateData.appState)\n }\n }\n\n /**\n * Load a stored session. This will refresh the token only if needed (about to\n * expire) by default.\n *\n * @see {@link SessionGetter.restore}\n */\n async restore(\n sub: string,\n refresh: boolean | 'auto' = 'auto',\n ): Promise<OAuthSession> {\n // sub arg is lightly typed for convenience of library user\n assertAtprotoDid(sub)\n\n const { dpopKey, authMethod, tokenSet } =\n await this.sessionGetter.getSession(sub, refresh)\n\n try {\n const server = await this.serverFactory.fromIssuer(\n tokenSet.iss,\n authMethod,\n dpopKey,\n {\n noCache: refresh === true,\n allowStale: refresh === false,\n },\n )\n\n return this.createSession(server, sub)\n } catch (err) {\n if (err instanceof AuthMethodUnsatisfiableError) {\n await this.sessionGetter.delStored(sub, err)\n }\n\n throw err\n }\n }\n\n async revoke(sub: string) {\n // sub arg is lightly typed for convenience of library user\n assertAtprotoDid(sub)\n\n const res = await this.sessionGetter.getSession(sub, false).catch((err) => {\n if (isExpectedSessionError(err)) return null\n throw err\n })\n\n if (!res) return\n\n const { dpopKey, authMethod, tokenSet } = res\n\n // NOT using `;(await this.restore(sub, false)).signOut()` because we want\n // the tokens to be deleted even if it was not possible to fetch the issuer\n // data.\n try {\n const server = await this.serverFactory.fromIssuer(\n tokenSet.iss,\n authMethod,\n dpopKey,\n )\n await server.revoke(tokenSet.access_token)\n } finally {\n await this.sessionGetter.delStored(sub, new TokenRevokedError(sub))\n }\n }\n\n protected createSession(\n server: OAuthServerAgent,\n sub: AtprotoDid,\n ): OAuthSession {\n return new OAuthSession(server, sub, this.sessionGetter, this.fetch)\n }\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { OAuthProtectedResourceMetadata } from '@atproto/oauth-types';
|
|
2
|
-
import { Fetch } from '@atproto-labs/fetch';
|
|
3
|
-
import { CachedGetter, GetCachedOptions, SimpleStore } from '@atproto-labs/simple-store';
|
|
1
|
+
import { type OAuthProtectedResourceMetadata } from '@atproto/oauth-types';
|
|
2
|
+
import { type Fetch } from '@atproto-labs/fetch';
|
|
3
|
+
import { CachedGetter, type GetCachedOptions, type SimpleStore } from '@atproto-labs/simple-store';
|
|
4
4
|
export type { GetCachedOptions, OAuthProtectedResourceMetadata };
|
|
5
5
|
export type ProtectedResourceMetadataCache = SimpleStore<string, OAuthProtectedResourceMetadata | null>;
|
|
6
6
|
export type OAuthProtectedResourceMetadataResolverConfig = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth-protected-resource-metadata-resolver.d.ts","sourceRoot":"","sources":["../src/oauth-protected-resource-metadata-resolver.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,8BAA8B,
|
|
1
|
+
{"version":3,"file":"oauth-protected-resource-metadata-resolver.d.ts","sourceRoot":"","sources":["../src/oauth-protected-resource-metadata-resolver.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,8BAA8B,EAEpC,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EACL,KAAK,KAAK,EAIX,MAAM,qBAAqB,CAAA;AAC5B,OAAO,EACL,YAAY,EACZ,KAAK,gBAAgB,EACrB,KAAK,WAAW,EACjB,MAAM,4BAA4B,CAAA;AAGnC,YAAY,EAAE,gBAAgB,EAAE,8BAA8B,EAAE,CAAA;AAEhE,MAAM,MAAM,8BAA8B,GAAG,WAAW,CACtD,MAAM,EACN,8BAA8B,GAAG,IAAI,CACtC,CAAA;AAED,MAAM,MAAM,4CAA4C,GAAG;IACzD,iBAAiB,CAAC,EAAE,OAAO,CAAA;CAC5B,CAAA;AAED;;GAEG;AACH,qBAAa,sCAAuC,SAAQ,YAAY,CACtE,MAAM,EACN,8BAA8B,GAAG,IAAI,CACtC;IACC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAgB;IACtC,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAS;IAE3C,YACE,KAAK,EAAE,8BAA8B,EACrC,KAAK,GAAE,KAAwB,EAC/B,MAAM,CAAC,EAAE,4CAA4C,EAMtD;IAEK,GAAG,CACP,QAAQ,EAAE,MAAM,GAAG,GAAG,EACtB,OAAO,CAAC,EAAE,gBAAgB,GACzB,OAAO,CAAC,8BAA8B,GAAG,IAAI,CAAC,CAgBhD;YAEa,aAAa;CAmD5B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth-protected-resource-metadata-resolver.js","sourceRoot":"","sources":["../src/oauth-protected-resource-metadata-resolver.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,oCAAoC,GACrC,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAEL,kBAAkB,EAClB,SAAS,EACT,UAAU,GACX,MAAM,qBAAqB,CAAA;AAC5B,OAAO,EACL,YAAY,GAGb,MAAM,4BAA4B,CAAA;AACnC,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAavC;;GAEG;AACH,MAAM,OAAO,sCAAuC,SAAQ,YAG3D;IAIC,YACE,KAAqC,EACrC,KAAK,GAAU,UAAU,CAAC,KAAK,EAC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Q,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAA;QAE1C,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;YAC5B,MAAM,UAAU,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAA;YACjC,OAAO,IAAI,CAAA;QACb,CAAC;QAED,0DAA0D;QAC1D,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;YAC5B,MAAM,UAAU,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAA;YACjC,MAAM,MAAM,kBAAkB,CAAC,IAAI,CACjC,QAAQ,EACR,0BAA0B,QAAQ,CAAC,MAAM,SAAS,GAAG,GAAG,EACxD,SAAS,EACT,EAAE,KAAK,EAAE,OAAO,EAAE,CACnB,CAAA;QACH,CAAC;QAED,IAAI,WAAW,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,kBAAkB,EAAE,CAAC;YACzD,MAAM,UAAU,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAA;YACjC,MAAM,MAAM,kBAAkB,CAAC,IAAI,CACjC,QAAQ,EACR,gCAAgC,GAAG,GAAG,EACtC,SAAS,EACT,EAAE,KAAK,EAAE,OAAO,EAAE,CACnB,CAAA;QACH,CAAC;QAED,MAAM,QAAQ,GAAG,oCAAoC,CAAC,KAAK,CACzD,MAAM,QAAQ,CAAC,IAAI,EAAE,CACtB,CAAA;QAED,0DAA0D;QAC1D,IAAI,QAAQ,CAAC,QAAQ,KAAK,MAAM,EAAE,CAAC;YACjC,MAAM,IAAI,SAAS,CAAC,kBAAkB,QAAQ,CAAC,QAAQ,EAAE,CAAC,CAAA;QAC5D,CAAC;QAED,OAAO,QAAQ,CAAA;IACjB,CAAC;CACF","sourcesContent":["import {\n OAuthProtectedResourceMetadata,\n oauthProtectedResourceMetadataSchema,\n} from '@atproto/oauth-types'\nimport {\n Fetch,\n FetchResponseError,\n bindFetch,\n cancelBody,\n} from '@atproto-labs/fetch'\nimport {\n CachedGetter,\n GetCachedOptions,\n SimpleStore,\n} from '@atproto-labs/simple-store'\nimport { contentMime } from './util.js'\n\nexport type { GetCachedOptions, OAuthProtectedResourceMetadata }\n\nexport type ProtectedResourceMetadataCache = SimpleStore<\n string,\n OAuthProtectedResourceMetadata | null\n>\n\nexport type OAuthProtectedResourceMetadataResolverConfig = {\n allowHttpResource?: boolean\n}\n\n/**\n * @see {@link https://www.rfc-editor.org/rfc/rfc9728.html}\n */\nexport class OAuthProtectedResourceMetadataResolver extends CachedGetter<\n string,\n OAuthProtectedResourceMetadata | null\n> {\n private readonly fetch: Fetch<unknown>\n private readonly allowHttpResource: boolean\n\n constructor(\n cache: ProtectedResourceMetadataCache,\n fetch: Fetch = globalThis.fetch,\n config?: OAuthProtectedResourceMetadataResolverConfig,\n ) {\n super(async (origin, options) => this.fetchMetadata(origin, options), cache)\n\n this.fetch = bindFetch(fetch)\n this.allowHttpResource = config?.allowHttpResource === true\n }\n\n async get(\n resource: string | URL,\n options?: GetCachedOptions,\n ): Promise<OAuthProtectedResourceMetadata | null> {\n const { protocol, origin } = new URL(resource)\n\n if (protocol !== 'https:' && protocol !== 'http:') {\n throw new TypeError(\n `Invalid protected resource metadata URL protocol: ${protocol}`,\n )\n }\n\n if (protocol === 'http:' && !this.allowHttpResource) {\n throw new TypeError(\n `Unsecure resource metadata URL (${protocol}) only allowed in development and test environments`,\n )\n }\n\n return super.get(origin, options)\n }\n\n private async fetchMetadata(\n origin: string,\n options?: GetCachedOptions,\n ): Promise<OAuthProtectedResourceMetadata | null> {\n const url = new URL(`/.well-known/oauth-protected-resource`, origin)\n const request = new Request(url, {\n signal: options?.signal,\n headers: { accept: 'application/json' },\n cache: options?.noCache ? 'no-cache' : undefined,\n redirect: 'manual', // response must be 200 OK\n })\n\n const response = await this.fetch(request)\n\n if (response.status === 404) {\n await cancelBody(response, 'log')\n return null\n }\n\n // https://www.rfc-editor.org/rfc/rfc9728.html#section-3.2\n if (response.status !== 200) {\n await cancelBody(response, 'log')\n throw await FetchResponseError.from(\n response,\n `Unexpected status code ${response.status} for \"${url}\"`,\n undefined,\n { cause: request },\n )\n }\n\n if (contentMime(response.headers) !== 'application/json') {\n await cancelBody(response, 'log')\n throw await FetchResponseError.from(\n response,\n `Unexpected content type for \"${url}\"`,\n undefined,\n { cause: request },\n )\n }\n\n const metadata = oauthProtectedResourceMetadataSchema.parse(\n await response.json(),\n )\n\n // https://www.rfc-editor.org/rfc/rfc9728.html#section-3.3\n if (metadata.resource !== origin) {\n throw new TypeError(`Invalid issuer ${metadata.resource}`)\n }\n\n return metadata\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"oauth-protected-resource-metadata-resolver.js","sourceRoot":"","sources":["../src/oauth-protected-resource-metadata-resolver.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,oCAAoC,GACrC,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAEL,kBAAkB,EAClB,SAAS,EACT,UAAU,GACX,MAAM,qBAAqB,CAAA;AAC5B,OAAO,EACL,YAAY,GAGb,MAAM,4BAA4B,CAAA;AACnC,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAavC;;GAEG;AACH,MAAM,OAAO,sCAAuC,SAAQ,YAG3D;IAIC,YACE,KAAqC,EACrC,KAAK,GAAU,UAAU,CAAC,KAAK,EAC/B,MAAqD;QAErD,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,KAAK,CAAC,CAAA;QAE5E,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC,KAAK,CAAC,CAAA;QAC7B,IAAI,CAAC,iBAAiB,GAAG,MAAM,EAAE,iBAAiB,KAAK,IAAI,CAAA;IAC7D,CAAC;IAED,KAAK,CAAC,GAAG,CACP,QAAsB,EACtB,OAA0B;QAE1B,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,IAAI,GAAG,CAAC,QA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,SAAS,GAAG,GAAG,EACxD,SAAS,EACT,EAAE,KAAK,EAAE,OAAO,EAAE,CACnB,CAAA;QACH,CAAC;QAED,IAAI,WAAW,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,kBAAkB,EAAE,CAAC;YACzD,MAAM,UAAU,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAA;YACjC,MAAM,MAAM,kBAAkB,CAAC,IAAI,CACjC,QAAQ,EACR,gCAAgC,GAAG,GAAG,EACtC,SAAS,EACT,EAAE,KAAK,EAAE,OAAO,EAAE,CACnB,CAAA;QACH,CAAC;QAED,MAAM,QAAQ,GAAG,oCAAoC,CAAC,KAAK,CACzD,MAAM,QAAQ,CAAC,IAAI,EAAE,CACtB,CAAA;QAED,0DAA0D;QAC1D,IAAI,QAAQ,CAAC,QAAQ,KAAK,MAAM,EAAE,CAAC;YACjC,MAAM,IAAI,SAAS,CAAC,kBAAkB,QAAQ,CAAC,QAAQ,EAAE,CAAC,CAAA;QAC5D,CAAC;QAED,OAAO,QAAQ,CAAA;IACjB,CAAC;CACF","sourcesContent":["import {\n type OAuthProtectedResourceMetadata,\n oauthProtectedResourceMetadataSchema,\n} from '@atproto/oauth-types'\nimport {\n type Fetch,\n FetchResponseError,\n bindFetch,\n cancelBody,\n} from '@atproto-labs/fetch'\nimport {\n CachedGetter,\n type GetCachedOptions,\n type SimpleStore,\n} from '@atproto-labs/simple-store'\nimport { contentMime } from './util.js'\n\nexport type { GetCachedOptions, OAuthProtectedResourceMetadata }\n\nexport type ProtectedResourceMetadataCache = SimpleStore<\n string,\n OAuthProtectedResourceMetadata | null\n>\n\nexport type OAuthProtectedResourceMetadataResolverConfig = {\n allowHttpResource?: boolean\n}\n\n/**\n * @see {@link https://www.rfc-editor.org/rfc/rfc9728.html}\n */\nexport class OAuthProtectedResourceMetadataResolver extends CachedGetter<\n string,\n OAuthProtectedResourceMetadata | null\n> {\n private readonly fetch: Fetch<unknown>\n private readonly allowHttpResource: boolean\n\n constructor(\n cache: ProtectedResourceMetadataCache,\n fetch: Fetch = globalThis.fetch,\n config?: OAuthProtectedResourceMetadataResolverConfig,\n ) {\n super(async (origin, options) => this.fetchMetadata(origin, options), cache)\n\n this.fetch = bindFetch(fetch)\n this.allowHttpResource = config?.allowHttpResource === true\n }\n\n async get(\n resource: string | URL,\n options?: GetCachedOptions,\n ): Promise<OAuthProtectedResourceMetadata | null> {\n const { protocol, origin } = new URL(resource)\n\n if (protocol !== 'https:' && protocol !== 'http:') {\n throw new TypeError(\n `Invalid protected resource metadata URL protocol: ${protocol}`,\n )\n }\n\n if (protocol === 'http:' && !this.allowHttpResource) {\n throw new TypeError(\n `Unsecure resource metadata URL (${protocol}) only allowed in development and test environments`,\n )\n }\n\n return super.get(origin, options)\n }\n\n private async fetchMetadata(\n origin: string,\n options?: GetCachedOptions,\n ): Promise<OAuthProtectedResourceMetadata | null> {\n const url = new URL(`/.well-known/oauth-protected-resource`, origin)\n const request = new Request(url, {\n signal: options?.signal,\n headers: { accept: 'application/json' },\n cache: options?.noCache ? 'no-cache' : undefined,\n redirect: 'manual', // response must be 200 OK\n })\n\n const response = await this.fetch(request)\n\n if (response.status === 404) {\n await cancelBody(response, 'log')\n return null\n }\n\n // https://www.rfc-editor.org/rfc/rfc9728.html#section-3.2\n if (response.status !== 200) {\n await cancelBody(response, 'log')\n throw await FetchResponseError.from(\n response,\n `Unexpected status code ${response.status} for \"${url}\"`,\n undefined,\n { cause: request },\n )\n }\n\n if (contentMime(response.headers) !== 'application/json') {\n await cancelBody(response, 'log')\n throw await FetchResponseError.from(\n response,\n `Unexpected content type for \"${url}\"`,\n undefined,\n { cause: request },\n )\n }\n\n const metadata = oauthProtectedResourceMetadataSchema.parse(\n await response.json(),\n )\n\n // https://www.rfc-editor.org/rfc/rfc9728.html#section-3.3\n if (metadata.resource !== origin) {\n throw new TypeError(`Invalid issuer ${metadata.resource}`)\n }\n\n return metadata\n }\n}\n"]}
|
package/dist/oauth-resolver.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { OAuthAuthorizationServerMetadata } from '@atproto/oauth-types';
|
|
2
|
-
import { IdentityInfo, IdentityResolver, ResolveIdentityOptions } from '@atproto-labs/identity-resolver';
|
|
3
|
-
import { GetCachedOptions, OAuthAuthorizationServerMetadataResolver } from './oauth-authorization-server-metadata-resolver.js';
|
|
4
|
-
import { OAuthProtectedResourceMetadataResolver } from './oauth-protected-resource-metadata-resolver.js';
|
|
1
|
+
import { type OAuthAuthorizationServerMetadata } from '@atproto/oauth-types';
|
|
2
|
+
import type { IdentityInfo, IdentityResolver, ResolveIdentityOptions } from '@atproto-labs/identity-resolver';
|
|
3
|
+
import type { GetCachedOptions, OAuthAuthorizationServerMetadataResolver } from './oauth-authorization-server-metadata-resolver.js';
|
|
4
|
+
import type { OAuthProtectedResourceMetadataResolver } from './oauth-protected-resource-metadata-resolver.js';
|
|
5
5
|
export type { GetCachedOptions };
|
|
6
6
|
export type ResolveOAuthOptions = GetCachedOptions & ResolveIdentityOptions;
|
|
7
7
|
export declare class OAuthResolver {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth-resolver.d.ts","sourceRoot":"","sources":["../src/oauth-resolver.ts"],"names":[],"mappings":"AACA,OAAO,EACL,gCAAgC,
|
|
1
|
+
{"version":3,"file":"oauth-resolver.d.ts","sourceRoot":"","sources":["../src/oauth-resolver.ts"],"names":[],"mappings":"AACA,OAAO,EACL,KAAK,gCAAgC,EAEtC,MAAM,sBAAsB,CAAA;AAC7B,OAAO,KAAK,EACV,YAAY,EACZ,gBAAgB,EAChB,sBAAsB,EACvB,MAAM,iCAAiC,CAAA;AACxC,OAAO,KAAK,EACV,gBAAgB,EAChB,wCAAwC,EACzC,MAAM,mDAAmD,CAAA;AAC1D,OAAO,KAAK,EAAE,sCAAsC,EAAE,MAAM,iDAAiD,CAAA;AAG7G,YAAY,EAAE,gBAAgB,EAAE,CAAA;AAChC,MAAM,MAAM,mBAAmB,GAAG,gBAA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IdentifierSchema,\n} from '@atproto/oauth-types'\nimport {\n IdentityInfo,\n IdentityResolver,\n ResolveIdentityOptions,\n} from '@atproto-labs/identity-resolver'\nimport {\n GetCachedOptions,\n OAuthAuthorizationServerMetadataResolver,\n} from './oauth-authorization-server-metadata-resolver.js'\nimport { OAuthProtectedResourceMetadataResolver } from './oauth-protected-resource-metadata-resolver.js'\nimport { OAuthResolverError } from './oauth-resolver-error.js'\n\nexport type { GetCachedOptions }\nexport type ResolveOAuthOptions = GetCachedOptions & ResolveIdentityOptions\n\nexport class OAuthResolver {\n constructor(\n readonly identityResolver: IdentityResolver,\n readonly protectedResourceMetadataResolver: OAuthProtectedResourceMetadataResolver,\n readonly authorizationServerMetadataResolver: OAuthAuthorizationServerMetadataResolver,\n ) {}\n\n /**\n * @param input - A handle, DID, PDS URL or Entryway URL\n */\n public async resolve(\n input: string,\n options?: ResolveOAuthOptions,\n ): Promise<{\n identityInfo?: IdentityInfo\n metadata: OAuthAuthorizationServerMetadata\n }> {\n // Allow using an entryway, or PDS url, directly as login input (e.g.\n // when the user forgot their handle, or when the handle does not\n // resolve to a DID)\n return /^https?:\\/\\//.test(input)\n ? this.resolveFromService(input, options)\n : this.resolveFromIdentity(input, options)\n }\n\n /**\n * @note this method can be used to verify if a particular uri supports OAuth\n * based sign-in (for compatibility with legacy implementation).\n */\n public async resolveFromService(\n input: string,\n options?: ResolveOAuthOptions,\n ): Promise<{\n metadata: OAuthAuthorizationServerMetadata\n }> {\n try {\n // Assume first that input is a PDS URL (as required by ATPROTO)\n const metadata = await this.getResourceServerMetadata(input, options)\n return { metadata }\n } catch (err) {\n if (!options?.signal?.aborted && err instanceof OAuthResolverError) {\n try {\n // Fallback to trying to fetch as an issuer (Entryway)\n const result = oauthIssuerIdentifierSchema.safeParse(input)\n if (result.success) {\n const metadata = await this.getAuthorizationServerMetadata(\n result.data,\n options,\n )\n return { metadata }\n }\n } catch {\n // Fallback failed, throw original error\n }\n }\n\n throw err\n }\n }\n\n public async resolveFromIdentity(\n input: string,\n options?: ResolveOAuthOptions,\n ): Promise<{\n identityInfo: IdentityInfo\n metadata: OAuthAuthorizationServerMetadata\n pds: URL\n }> {\n const identityInfo = await this.resolveIdentity(input, options)\n\n options?.signal?.throwIfAborted()\n\n const pds = extractPdsUrl(identityInfo.didDoc)\n\n const metadata = await this.getResourceServerMetadata(pds, options)\n\n return { identityInfo, metadata, pds }\n }\n\n public async resolveIdentity(\n input: string,\n options?: ResolveIdentityOptions,\n ): Promise<IdentityInfo> {\n try {\n return await this.identityResolver.resolve(input, options)\n } catch (cause) {\n throw OAuthResolverError.from(\n cause,\n `Failed to resolve identity: ${input}`,\n )\n }\n }\n\n public async getAuthorizationServerMetadata(\n issuer: string | URL,\n options?: GetCachedOptions,\n ): Promise<OAuthAuthorizationServerMetadata> {\n try {\n return await this.authorizationServerMetadataResolver.get(issuer, options)\n } catch (cause) {\n throw OAuthResolverError.from(\n cause,\n `Failed to resolve OAuth server metadata for issuer: ${issuer}`,\n )\n }\n }\n\n public async getResourceServerMetadata(\n pdsUrl: string | URL,\n options?: GetCachedOptions,\n ) {\n try {\n const rsMetadata = await this.protectedResourceMetadataResolver.get(\n pdsUrl,\n options,\n )\n\n if (!rsMetadata) {\n return this.getAuthorizationServerMetadata(pdsUrl, options)\n }\n\n // ATPROTO requires one, and only one, authorization server entry\n if (rsMetadata.authorization_servers?.length !== 1) {\n throw new OAuthResolverError(\n rsMetadata.authorization_servers?.length\n ? `Unable to determine authorization server for PDS: ${pdsUrl}`\n : `No authorization servers found for PDS: ${pdsUrl}`,\n )\n }\n\n const issuer = rsMetadata.authorization_servers![0]!\n\n options?.signal?.throwIfAborted()\n\n const asMetadata = await this.getAuthorizationServerMetadata(\n issuer,\n options,\n )\n\n // https://www.rfc-editor.org/rfc/rfc9728.html#section-4\n if (asMetadata.protected_resources) {\n if (!asMetadata.protected_resources.includes(rsMetadata.resource)) {\n throw new OAuthResolverError(\n `PDS \"${pdsUrl}\" not protected by issuer \"${issuer}\"`,\n )\n }\n }\n\n return asMetadata\n } catch (cause) {\n throw OAuthResolverError.from(\n cause,\n `Failed to resolve OAuth server metadata for resource: ${pdsUrl}`,\n )\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"oauth-resolver.js","sourceRoot":"","sources":["../src/oauth-resolver.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAA;AAC5C,OAAO,EAEL,2BAA2B,GAC5B,MAAM,sBAAsB,CAAA;AAW7B,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAA;AAK9D,MAAM,OAAO,aAAa;IACxB,YACW,gBAAkC,EAClC,iCAAyE,EACzE,mCAA6E;gCAF7E,gBAAgB;iDAChB,iCAAiC;mDACjC,mCAAmC;IAC3C,CAAC;IAEJ;;OAEG;IACI,KAAK,CAAC,OAAO,CAClB,KAAa,EACb,OAA6B;QAK7B,qEAAqE;QACrE,iEAAiE;QACjE,oBAAoB;QACpB,OAAO,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC;YAC/B,CAAC,CAAC,IAAI,CAAC,kBAAkB,CAAC,KAAK,EAAE,OAAO,CAAC;YACzC,CAAC,CAAC,IAAI,CAAC,mBAAmB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAA;IAC9C,CAAC;IAED;;;OAGG;IACI,KAAK,CAAC,kBAAkB,CAC7B,KAAa,EACb,OAA6B;QAI7B,IAAI,CAAC;YACH,gEAAgE;YAChE,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,yBAAyB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAA;YACrE,OAAO,EAAE,QAAQ,EAAE,CAAA;QACrB,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,IAAI,GAAG,YAAY,kBAAkB,EAAE,CAAC;gBACnE,IAAI,CAAC;oBACH,sDAAsD;oBACtD,MAAM,MAAM,GAAG,2BAA2B,CAA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B,KAAK,EACL,yDAAyD,MAAM,EAAE,CAClE,CAAA;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["import { extractPdsUrl } from '@atproto/did'\nimport {\n type OAuthAuthorizationServerMetadata,\n oauthIssuerIdentifierSchema,\n} from '@atproto/oauth-types'\nimport type {\n IdentityInfo,\n IdentityResolver,\n ResolveIdentityOptions,\n} from '@atproto-labs/identity-resolver'\nimport type {\n GetCachedOptions,\n OAuthAuthorizationServerMetadataResolver,\n} from './oauth-authorization-server-metadata-resolver.js'\nimport type { OAuthProtectedResourceMetadataResolver } from './oauth-protected-resource-metadata-resolver.js'\nimport { OAuthResolverError } from './oauth-resolver-error.js'\n\nexport type { GetCachedOptions }\nexport type ResolveOAuthOptions = GetCachedOptions & ResolveIdentityOptions\n\nexport class OAuthResolver {\n constructor(\n readonly identityResolver: IdentityResolver,\n readonly protectedResourceMetadataResolver: OAuthProtectedResourceMetadataResolver,\n readonly authorizationServerMetadataResolver: OAuthAuthorizationServerMetadataResolver,\n ) {}\n\n /**\n * @param input - A handle, DID, PDS URL or Entryway URL\n */\n public async resolve(\n input: string,\n options?: ResolveOAuthOptions,\n ): Promise<{\n identityInfo?: IdentityInfo\n metadata: OAuthAuthorizationServerMetadata\n }> {\n // Allow using an entryway, or PDS url, directly as login input (e.g.\n // when the user forgot their handle, or when the handle does not\n // resolve to a DID)\n return /^https?:\\/\\//.test(input)\n ? this.resolveFromService(input, options)\n : this.resolveFromIdentity(input, options)\n }\n\n /**\n * @note this method can be used to verify if a particular uri supports OAuth\n * based sign-in (for compatibility with legacy implementation).\n */\n public async resolveFromService(\n input: string,\n options?: ResolveOAuthOptions,\n ): Promise<{\n metadata: OAuthAuthorizationServerMetadata\n }> {\n try {\n // Assume first that input is a PDS URL (as required by ATPROTO)\n const metadata = await this.getResourceServerMetadata(input, options)\n return { metadata }\n } catch (err) {\n if (!options?.signal?.aborted && err instanceof OAuthResolverError) {\n try {\n // Fallback to trying to fetch as an issuer (Entryway)\n const result = oauthIssuerIdentifierSchema.safeParse(input)\n if (result.success) {\n const metadata = await this.getAuthorizationServerMetadata(\n result.data,\n options,\n )\n return { metadata }\n }\n } catch {\n // Fallback failed, throw original error\n }\n }\n\n throw err\n }\n }\n\n public async resolveFromIdentity(\n input: string,\n options?: ResolveOAuthOptions,\n ): Promise<{\n identityInfo: IdentityInfo\n metadata: OAuthAuthorizationServerMetadata\n pds: URL\n }> {\n const identityInfo = await this.resolveIdentity(input, options)\n\n options?.signal?.throwIfAborted()\n\n const pds = extractPdsUrl(identityInfo.didDoc)\n\n const metadata = await this.getResourceServerMetadata(pds, options)\n\n return { identityInfo, metadata, pds }\n }\n\n public async resolveIdentity(\n input: string,\n options?: ResolveIdentityOptions,\n ): Promise<IdentityInfo> {\n try {\n return await this.identityResolver.resolve(input, options)\n } catch (cause) {\n throw OAuthResolverError.from(\n cause,\n `Failed to resolve identity: ${input}`,\n )\n }\n }\n\n public async getAuthorizationServerMetadata(\n issuer: string | URL,\n options?: GetCachedOptions,\n ): Promise<OAuthAuthorizationServerMetadata> {\n try {\n return await this.authorizationServerMetadataResolver.get(issuer, options)\n } catch (cause) {\n throw OAuthResolverError.from(\n cause,\n `Failed to resolve OAuth server metadata for issuer: ${issuer}`,\n )\n }\n }\n\n public async getResourceServerMetadata(\n pdsUrl: string | URL,\n options?: GetCachedOptions,\n ) {\n try {\n const rsMetadata = await this.protectedResourceMetadataResolver.get(\n pdsUrl,\n options,\n )\n\n if (!rsMetadata) {\n return this.getAuthorizationServerMetadata(pdsUrl, options)\n }\n\n // ATPROTO requires one, and only one, authorization server entry\n if (rsMetadata.authorization_servers?.length !== 1) {\n throw new OAuthResolverError(\n rsMetadata.authorization_servers?.length\n ? `Unable to determine authorization server for PDS: ${pdsUrl}`\n : `No authorization servers found for PDS: ${pdsUrl}`,\n )\n }\n\n const issuer = rsMetadata.authorization_servers![0]!\n\n options?.signal?.throwIfAborted()\n\n const asMetadata = await this.getAuthorizationServerMetadata(\n issuer,\n options,\n )\n\n // https://www.rfc-editor.org/rfc/rfc9728.html#section-4\n if (asMetadata.protected_resources) {\n if (!asMetadata.protected_resources.includes(rsMetadata.resource)) {\n throw new OAuthResolverError(\n `PDS \"${pdsUrl}\" not protected by issuer \"${issuer}\"`,\n )\n }\n }\n\n return asMetadata\n } catch (cause) {\n throw OAuthResolverError.from(\n cause,\n `Failed to resolve OAuth server metadata for resource: ${pdsUrl}`,\n )\n }\n }\n}\n"]}
|