@atproto/oauth-client 0.8.10 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/dist/index.d.ts +1 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -3
- package/dist/index.js.map +1 -1
- package/dist/oauth-client.d.ts +3 -8
- package/dist/oauth-client.d.ts.map +1 -1
- package/dist/oauth-client.js +3 -12
- package/dist/oauth-client.js.map +1 -1
- package/dist/oauth-server-agent.d.ts +1 -1
- package/dist/oauth-server-agent.d.ts.map +1 -1
- package/dist/oauth-server-agent.js.map +1 -1
- package/dist/oauth-server-factory.d.ts +1 -2
- package/dist/oauth-server-factory.d.ts.map +1 -1
- package/dist/oauth-server-factory.js.map +1 -1
- package/dist/util.d.ts +0 -1
- package/dist/util.d.ts.map +1 -1
- package/dist/util.js +0 -3
- package/dist/util.js.map +1 -1
- package/package.json +6 -5
- package/dist/oauth-authorization-server-metadata-resolver.d.ts +0 -25
- package/dist/oauth-authorization-server-metadata-resolver.d.ts.map +0 -1
- package/dist/oauth-authorization-server-metadata-resolver.js +0 -54
- package/dist/oauth-authorization-server-metadata-resolver.js.map +0 -1
- package/dist/oauth-protected-resource-metadata-resolver.d.ts +0 -25
- package/dist/oauth-protected-resource-metadata-resolver.d.ts.map +0 -1
- package/dist/oauth-protected-resource-metadata-resolver.js +0 -54
- package/dist/oauth-protected-resource-metadata-resolver.js.map +0 -1
- package/dist/oauth-resolver-error.d.ts +0 -7
- package/dist/oauth-resolver-error.d.ts.map +0 -1
- package/dist/oauth-resolver-error.js +0 -19
- package/dist/oauth-resolver-error.js.map +0 -1
- package/dist/oauth-resolver.d.ts +0 -73
- package/dist/oauth-resolver.d.ts.map +0 -1
- package/dist/oauth-resolver.js +0 -99
- package/dist/oauth-resolver.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# @atproto/oauth-client
|
|
2
2
|
|
|
3
|
+
## 0.9.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#5687](https://github.com/bluesky-social/atproto/pull/5687) [`943170b`](https://github.com/bluesky-social/atproto/commit/943170bd390705fbb16920688f8f09ec7078a59b) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Factorize `OAuthResolver` logic in separate `@atproto/oauth-resolver` package (out of `@atproto/oauth-client`)
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- Updated dependencies [[`943170b`](https://github.com/bluesky-social/atproto/commit/943170bd390705fbb16920688f8f09ec7078a59b)]:
|
|
12
|
+
- @atproto/oauth-resolver@0.0.1
|
|
13
|
+
|
|
3
14
|
## 0.8.10
|
|
4
15
|
|
|
5
16
|
### Patch Changes
|
package/dist/index.d.ts
CHANGED
|
@@ -4,13 +4,11 @@ export { FetchError, FetchRequestError, FetchResponseError, } from '@atproto-lab
|
|
|
4
4
|
export * from '@atproto-labs/handle-resolver';
|
|
5
5
|
export * from '@atproto/did';
|
|
6
6
|
export * from '@atproto/jwk';
|
|
7
|
+
export * from '@atproto/oauth-resolver';
|
|
7
8
|
export * from '@atproto/oauth-types';
|
|
8
9
|
export * from './lock.js';
|
|
9
|
-
export * from './oauth-authorization-server-metadata-resolver.js';
|
|
10
10
|
export * from './oauth-callback-error.js';
|
|
11
11
|
export * from './oauth-client.js';
|
|
12
|
-
export * from './oauth-protected-resource-metadata-resolver.js';
|
|
13
|
-
export * from './oauth-resolver-error.js';
|
|
14
12
|
export * from './oauth-response-error.js';
|
|
15
13
|
export * from './oauth-server-agent.js';
|
|
16
14
|
export * from './oauth-server-factory.js';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,8BAA8B,CAAA;AAErC,cAAc,4BAA4B,CAAA;AAC1C,OAAO,EACL,UAAU,EACV,iBAAiB,EACjB,kBAAkB,GACnB,MAAM,qBAAqB,CAAA;AAC5B,cAAc,+BAA+B,CAAA;AAE7C,cAAc,cAAc,CAAA;AAC5B,cAAc,cAAc,CAAA;AAC5B,cAAc,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,8BAA8B,CAAA;AAErC,cAAc,4BAA4B,CAAA;AAC1C,OAAO,EACL,UAAU,EACV,iBAAiB,EACjB,kBAAkB,GACnB,MAAM,qBAAqB,CAAA;AAC5B,cAAc,+BAA+B,CAAA;AAE7C,cAAc,cAAc,CAAA;AAC5B,cAAc,cAAc,CAAA;AAC5B,cAAc,yBAAyB,CAAA;AACvC,cAAc,sBAAsB,CAAA;AAEpC,cAAc,WAAW,CAAA;AACzB,cAAc,2BAA2B,CAAA;AACzC,cAAc,mBAAmB,CAAA;AACjC,cAAc,2BAA2B,CAAA;AACzC,cAAc,yBAAyB,CAAA;AACvC,cAAc,2BAA2B,CAAA;AACzC,cAAc,oBAAoB,CAAA;AAClC,cAAc,6BAA6B,CAAA;AAC3C,cAAc,qBAAqB,CAAA;AACnC,cAAc,kBAAkB,CAAA;AAChC,cAAc,YAAY,CAAA;AAE1B,cAAc,iCAAiC,CAAA;AAC/C,cAAc,iCAAiC,CAAA;AAC/C,cAAc,iCAAiC,CAAA"}
|
package/dist/index.js
CHANGED
|
@@ -4,13 +4,11 @@ export { FetchError, FetchRequestError, FetchResponseError, } from '@atproto-lab
|
|
|
4
4
|
export * from '@atproto-labs/handle-resolver';
|
|
5
5
|
export * from '@atproto/did';
|
|
6
6
|
export * from '@atproto/jwk';
|
|
7
|
+
export * from '@atproto/oauth-resolver';
|
|
7
8
|
export * from '@atproto/oauth-types';
|
|
8
9
|
export * from './lock.js';
|
|
9
|
-
export * from './oauth-authorization-server-metadata-resolver.js';
|
|
10
10
|
export * from './oauth-callback-error.js';
|
|
11
11
|
export * from './oauth-client.js';
|
|
12
|
-
export * from './oauth-protected-resource-metadata-resolver.js';
|
|
13
|
-
export * from './oauth-resolver-error.js';
|
|
14
12
|
export * from './oauth-response-error.js';
|
|
15
13
|
export * from './oauth-server-agent.js';
|
|
16
14
|
export * from './oauth-server-factory.js';
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,8BAA8B,CAAA;AAErC,cAAc,4BAA4B,CAAA;AAC1C,OAAO,EACL,UAAU,EACV,iBAAiB,EACjB,kBAAkB,GACnB,MAAM,qBAAqB,CAAA;AAC5B,cAAc,+BAA+B,CAAA;AAE7C,cAAc,cAAc,CAAA;AAC5B,cAAc,cAAc,CAAA;AAC5B,cAAc,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,8BAA8B,CAAA;AAErC,cAAc,4BAA4B,CAAA;AAC1C,OAAO,EACL,UAAU,EACV,iBAAiB,EACjB,kBAAkB,GACnB,MAAM,qBAAqB,CAAA;AAC5B,cAAc,+BAA+B,CAAA;AAE7C,cAAc,cAAc,CAAA;AAC5B,cAAc,cAAc,CAAA;AAC5B,cAAc,yBAAyB,CAAA;AACvC,cAAc,sBAAsB,CAAA;AAEpC,cAAc,WAAW,CAAA;AACzB,cAAc,2BAA2B,CAAA;AACzC,cAAc,mBAAmB,CAAA;AACjC,cAAc,2BAA2B,CAAA;AACzC,cAAc,yBAAyB,CAAA;AACvC,cAAc,2BAA2B,CAAA;AACzC,cAAc,oBAAoB,CAAA;AAClC,cAAc,6BAA6B,CAAA;AAC3C,cAAc,qBAAqB,CAAA;AACnC,cAAc,kBAAkB,CAAA;AAChC,cAAc,YAAY,CAAA;AAE1B,cAAc,iCAAiC,CAAA;AAC/C,cAAc,iCAAiC,CAAA;AAC/C,cAAc,iCAAiC,CAAA","sourcesContent":["import 'core-js/es/symbol/dispose.js'\n\nexport * from '@atproto-labs/did-resolver'\nexport {\n FetchError,\n FetchRequestError,\n FetchResponseError,\n} from '@atproto-labs/fetch'\nexport * from '@atproto-labs/handle-resolver'\n\nexport * from '@atproto/did'\nexport * from '@atproto/jwk'\nexport * from '@atproto/oauth-resolver'\nexport * from '@atproto/oauth-types'\n\nexport * from './lock.js'\nexport * from './oauth-callback-error.js'\nexport * from './oauth-client.js'\nexport * from './oauth-response-error.js'\nexport * from './oauth-server-agent.js'\nexport * from './oauth-server-factory.js'\nexport * from './oauth-session.js'\nexport * from './runtime-implementation.js'\nexport * from './session-getter.js'\nexport * from './state-store.js'\nexport * from './types.js'\n\nexport * from './errors/token-invalid-error.js'\nexport * from './errors/token-refresh-error.js'\nexport * from './errors/token-revoked-error.js'\n"]}
|
package/dist/oauth-client.d.ts
CHANGED
|
@@ -1,12 +1,9 @@
|
|
|
1
1
|
import { Key, Keyset } from '@atproto/jwk';
|
|
2
|
+
import { type CreateOAuthResolverOptions, type OAuthResolver } from '@atproto/oauth-resolver';
|
|
2
3
|
import { type OAuthClientIdDiscoverable, type OAuthClientMetadata, type OAuthClientMetadataInput, type OAuthResponseMode } from '@atproto/oauth-types';
|
|
3
4
|
import { type AtprotoDid, type DidCache } from '@atproto-labs/did-resolver';
|
|
4
5
|
import type { Fetch } from '@atproto-labs/fetch';
|
|
5
6
|
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
|
-
import { OAuthResolver } from './oauth-resolver.js';
|
|
10
7
|
import type { DpopNonceCache, OAuthServerAgent } from './oauth-server-agent.js';
|
|
11
8
|
import { OAuthServerFactory } from './oauth-server-factory.js';
|
|
12
9
|
import { OAuthSession } from './oauth-session.js';
|
|
@@ -15,7 +12,7 @@ import { Runtime } from './runtime.js';
|
|
|
15
12
|
import { SessionGetter, type SessionGetterOptions, type SessionStore } from './session-getter.js';
|
|
16
13
|
import type { InternalStateData, StateStore } from './state-store.js';
|
|
17
14
|
import type { AuthorizeOptions, CallbackOptions, ClientMetadata } from './types.js';
|
|
18
|
-
export type {
|
|
15
|
+
export type { CreateOAuthResolverOptions, DidCache, DpopNonceCache, Fetch, HandleCache, HandleResolver, InternalStateData, OAuthClientMetadata, OAuthClientMetadataInput, OAuthResponseMode, RuntimeImplementation, SessionGetterOptions, SessionStore, StateStore, };
|
|
19
16
|
export { Key, Keyset };
|
|
20
17
|
export type OAuthClientOptions = {
|
|
21
18
|
responseMode: OAuthResponseMode;
|
|
@@ -38,12 +35,10 @@ export type OAuthClientOptions = {
|
|
|
38
35
|
allowHttp?: boolean;
|
|
39
36
|
stateStore: StateStore;
|
|
40
37
|
sessionStore: SessionStore;
|
|
41
|
-
authorizationServerMetadataCache?: AuthorizationServerMetadataCache;
|
|
42
|
-
protectedResourceMetadataCache?: ProtectedResourceMetadataCache;
|
|
43
38
|
dpopNonceCache?: DpopNonceCache;
|
|
44
39
|
runtimeImplementation: RuntimeImplementation;
|
|
45
40
|
fetch?: Fetch;
|
|
46
|
-
} &
|
|
41
|
+
} & CreateOAuthResolverOptions & SessionGetterOptions;
|
|
47
42
|
export type OAuthClientFetchMetadataOptions = {
|
|
48
43
|
clientId: OAuthClientIdDiscoverable;
|
|
49
44
|
fetch?: Fetch;
|
|
@@ -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,KAAK,yBAAyB,EAC9B,KAAK,mBAAmB,EACxB,KAAK,wBAAwB,EAC7B,KAAK,iBAAiB,EAEvB,MAAM,sBAAsB,CAA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,GACd,YAAY,CAEd;CACF"}
|
package/dist/oauth-client.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Key, Keyset } from '@atproto/jwk';
|
|
2
|
+
import { createOAuthResolver, } from '@atproto/oauth-resolver';
|
|
2
3
|
import { oauthClientMetadataSchema, } from '@atproto/oauth-types';
|
|
3
4
|
import { assertAtprotoDid, } from '@atproto-labs/did-resolver';
|
|
4
5
|
import { HANDLE_INVALID } from '@atproto-labs/identity-resolver';
|
|
@@ -6,12 +7,8 @@ import { SimpleStoreMemory } from '@atproto-labs/simple-store-memory';
|
|
|
6
7
|
import { FALLBACK_ALG } from './constants.js';
|
|
7
8
|
import { AuthMethodUnsatisfiableError } from './errors/auth-method-unsatisfiable-error.js';
|
|
8
9
|
import { TokenRevokedError } from './errors/token-revoked-error.js';
|
|
9
|
-
import { createIdentityResolver, } from './identity-resolver.js';
|
|
10
|
-
import { OAuthAuthorizationServerMetadataResolver, } from './oauth-authorization-server-metadata-resolver.js';
|
|
11
10
|
import { OAuthCallbackError } from './oauth-callback-error.js';
|
|
12
11
|
import { negotiateClientAuthMethod } from './oauth-client-auth.js';
|
|
13
|
-
import { OAuthProtectedResourceMetadataResolver, } from './oauth-protected-resource-metadata-resolver.js';
|
|
14
|
-
import { OAuthResolver } from './oauth-resolver.js';
|
|
15
12
|
import { OAuthServerFactory } from './oauth-server-factory.js';
|
|
16
13
|
import { OAuthSession } from './oauth-session.js';
|
|
17
14
|
import { Runtime } from './runtime.js';
|
|
@@ -41,13 +38,7 @@ export class OAuthClient {
|
|
|
41
38
|
return oauthClientMetadataSchema.parse(json);
|
|
42
39
|
}
|
|
43
40
|
constructor(options) {
|
|
44
|
-
const { stateStore, sessionStore, dpopNonceCache = new SimpleStoreMemory({ ttl: 60e3, max: 100 }),
|
|
45
|
-
ttl: 60e3,
|
|
46
|
-
max: 100,
|
|
47
|
-
}), protectedResourceMetadataCache = new SimpleStoreMemory({
|
|
48
|
-
ttl: 60e3,
|
|
49
|
-
max: 100,
|
|
50
|
-
}), responseMode, clientMetadata, runtimeImplementation, keyset, } = options;
|
|
41
|
+
const { stateStore, sessionStore, dpopNonceCache = new SimpleStoreMemory({ ttl: 60e3, max: 100 }), responseMode, clientMetadata, runtimeImplementation, keyset, } = options;
|
|
51
42
|
this.keyset = keyset
|
|
52
43
|
? keyset instanceof Keyset
|
|
53
44
|
? keyset
|
|
@@ -57,7 +48,7 @@ export class OAuthClient {
|
|
|
57
48
|
this.responseMode = responseMode;
|
|
58
49
|
this.runtime = new Runtime(runtimeImplementation);
|
|
59
50
|
this.fetch = options.fetch ?? globalThis.fetch;
|
|
60
|
-
this.oauthResolver =
|
|
51
|
+
this.oauthResolver = createOAuthResolver(options);
|
|
61
52
|
this.serverFactory = new OAuthServerFactory(this.clientMetadata, this.runtime, this.oauthResolver, this.fetch, this.keyset, dpopNonceCache);
|
|
62
53
|
this.stateStore = stateStore;
|
|
63
54
|
this.sessionGetter = new SessionGetter(sessionStore, this.serverFactory, this.runtime, options);
|
package/dist/oauth-client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth-client.js","sourceRoot":"","sources":["../src/oauth-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AAC1C,OAAO,EAML,yBAAyB,GAC1B,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAKL,gBAAgB,GACjB,MAAM,4BAA4B,CAAA;AAGnC,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAA;AAChE,OAAO,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAA;AACrE,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAA;AAC7C,OAAO,EAAE,4BAA4B,EAAE,MAAM,6CAA6C,CAAA;AAC1F,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAA;AACnE,OAAO,EAEL,sBAAsB,GACvB,MAAM,wBAAwB,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AQ,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 SessionGetterOptions,\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 SessionGetterOptions,\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 SessionGetterOptions\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":[],"mappings":"AAAA,OAAO,EAAE,GAA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AAM,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 CreateOAuthResolverOptions,\n type OAuthResolver,\n createOAuthResolver,\n} from '@atproto/oauth-resolver'\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 { OAuthCallbackError } from './oauth-callback-error.js'\nimport { negotiateClientAuthMethod } from './oauth-client-auth.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 SessionGetterOptions,\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 CreateOAuthResolverOptions,\n DidCache,\n DpopNonceCache,\n Fetch,\n HandleCache,\n HandleResolver,\n InternalStateData,\n OAuthClientMetadata,\n OAuthClientMetadataInput,\n OAuthResponseMode,\n RuntimeImplementation,\n SessionGetterOptions,\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 dpopNonceCache?: DpopNonceCache\n\n // Services\n runtimeImplementation: RuntimeImplementation\n fetch?: Fetch\n} & CreateOAuthResolverOptions &\n SessionGetterOptions\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\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 = createOAuthResolver(options)\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,10 +1,10 @@
|
|
|
1
1
|
import type { AtprotoDid } from '@atproto/did';
|
|
2
2
|
import type { Key, Keyset } from '@atproto/jwk';
|
|
3
|
+
import type { OAuthResolver } from '@atproto/oauth-resolver';
|
|
3
4
|
import { type AtprotoOAuthScope, type AtprotoOAuthTokenResponse, type OAuthAuthorizationRequestPar, type OAuthAuthorizationServerMetadata, type OAuthEndpointName, type OAuthParResponse, type OAuthRedirectUri, type OAuthTokenRequest } from '@atproto/oauth-types';
|
|
4
5
|
import { type Fetch, type Json } from '@atproto-labs/fetch';
|
|
5
6
|
import type { SimpleStore } from '@atproto-labs/simple-store';
|
|
6
7
|
import { type ClientAuthMethod, type ClientCredentialsFactory } from './oauth-client-auth.js';
|
|
7
|
-
import type { OAuthResolver } from './oauth-resolver.js';
|
|
8
8
|
import type { Runtime } from './runtime.js';
|
|
9
9
|
import type { ClientMetadata } from './types.js';
|
|
10
10
|
export type { AtprotoDid, AtprotoOAuthScope, AtprotoOAuthTokenResponse };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth-server-agent.d.ts","sourceRoot":"","sources":["../src/oauth-server-agent.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AAC9C,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,EAAE,MA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AAmB,CAAC,KAAwB;IACnD,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAA;IACrB,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,CAAA;IAEtB,QAAQ,OAAO,KAAK,EAAE,CAAC;QACrB,KAAK,QAAQ;YACX,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;QACtB,KAAK,QAAQ,CAAC;QACd,KAAK,SAAS;YACZ,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAA;QAC9B,SAAS,CAAC;YACR,MAAM,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAA;YACjC,IAAI,GAAG,KAAK,SAAS,EAAE,CAAC;gBACtB,MAAM,IAAI,KAAK,CAAC,8BAA8B,IAAI,KAAK,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAA;YACzE,CAAC;YACD,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;QACpB,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import type { AtprotoDid } from '@atproto/did'\nimport type { Key, Keyset } from '@atproto/jwk'\nimport {\n type AtprotoOAuthScope,\n type AtprotoOAuthTokenResponse,\n type OAuthAuthorizationRequestPar,\n type OAuthAuthorizationServerMetadata,\n type OAuthEndpointName,\n type OAuthParResponse,\n type OAuthRedirectUri,\n type OAuthTokenRequest,\n atprotoOAuthTokenResponseSchema,\n oauthParResponseSchema,\n} from '@atproto/oauth-types'\nimport {\n type Fetch,\n type Json,\n bindFetch,\n fetchJsonProcessor,\n} from '@atproto-labs/fetch'\nimport type { SimpleStore } from '@atproto-labs/simple-store'\nimport { TokenRefreshError } from './errors/token-refresh-error.js'\nimport { dpopFetchWrapper } from './fetch-dpop.js'\nimport {\n type ClientAuthMethod,\n type ClientCredentialsFactory,\n createClientCredentialsFactory,\n} from './oauth-client-auth.js'\nimport type { OAuthResolver } from './oauth-resolver.js'\nimport { OAuthResponseError } from './oauth-response-error.js'\nimport type { Runtime } from './runtime.js'\nimport type { ClientMetadata } from './types.js'\nimport { timeoutSignal } from './util.js'\n\nexport type { AtprotoDid, AtprotoOAuthScope, AtprotoOAuthTokenResponse }\n\nexport type TokenSet = {\n iss: string\n sub: AtprotoDid\n aud: string\n scope: AtprotoOAuthScope\n\n refresh_token?: string\n access_token: string\n token_type: 'DPoP'\n /** ISO Date */\n expires_at?: string\n}\n\nexport type DpopNonceCache = SimpleStore<string, string>\n\nexport class OAuthServerAgent {\n protected dpopFetch: Fetch<unknown>\n protected clientCredentialsFactory: ClientCredentialsFactory\n\n /**\n * @throws see {@link createClientCredentialsFactory}\n */\n constructor(\n readonly authMethod: ClientAuthMethod,\n readonly dpopKey: Key,\n readonly serverMetadata: OAuthAuthorizationServerMetadata,\n readonly clientMetadata: ClientMetadata,\n readonly dpopNonces: DpopNonceCache,\n readonly oauthResolver: OAuthResolver,\n readonly runtime: Runtime,\n readonly keyset?: Keyset,\n fetch?: Fetch,\n ) {\n this.clientCredentialsFactory = createClientCredentialsFactory(\n authMethod,\n serverMetadata,\n clientMetadata,\n runtime,\n keyset,\n )\n\n this.dpopFetch = dpopFetchWrapper<void>({\n fetch: bindFetch(fetch),\n key: dpopKey,\n supportedAlgs: serverMetadata.dpop_signing_alg_values_supported,\n sha256: async (v) => runtime.sha256(v),\n nonces: dpopNonces,\n isAuthServer: true,\n })\n }\n\n get issuer() {\n return this.serverMetadata.issuer\n }\n\n async revoke(token: string) {\n try {\n await this.request('revocation', { token })\n } catch {\n // Don't care\n }\n }\n\n async exchangeCode(\n code: string,\n codeVerifier?: string,\n redirectUri?: OAuthRedirectUri,\n ): Promise<TokenSet> {\n const now = Date.now()\n\n const tokenResponse = await this.request('token', {\n grant_type: 'authorization_code',\n // redirectUri should always be passed by the calling code, but if it is\n // not, default to the first redirect_uri registered for the client:\n redirect_uri: redirectUri ?? this.clientMetadata.redirect_uris[0],\n code,\n code_verifier: codeVerifier,\n })\n\n try {\n // /!\\ IMPORTANT /!\\\n //\n // The tokenResponse MUST always be valid before the \"sub\" it contains\n // can be trusted (see Atproto's OAuth spec for details).\n const aud = await this.verifyIssuer(tokenResponse.sub)\n\n return {\n aud,\n sub: tokenResponse.sub,\n iss: this.issuer,\n\n scope: tokenResponse.scope,\n refresh_token: tokenResponse.refresh_token,\n access_token: tokenResponse.access_token,\n token_type: tokenResponse.token_type,\n\n expires_at:\n typeof tokenResponse.expires_in === 'number'\n ? new Date(now + tokenResponse.expires_in * 1000).toISOString()\n : undefined,\n }\n } catch (err) {\n await this.revoke(tokenResponse.access_token)\n\n throw err\n }\n }\n\n async refresh(tokenSet: TokenSet): Promise<TokenSet> {\n if (!tokenSet.refresh_token) {\n throw new TokenRefreshError(tokenSet.sub, 'No refresh token available')\n }\n\n // /!\\ IMPORTANT /!\\\n //\n // The \"sub\" MUST be a DID, whose issuer authority is indeed the server we\n // are trying to obtain credentials from. Note that we are doing this\n // *before* we actually try to refresh the token:\n // 1) To avoid unnecessary refresh\n // 2) So that the refresh is the last async operation, ensuring as few\n // async operations happen before the result gets a chance to be stored.\n const aud = await this.verifyIssuer(tokenSet.sub)\n\n const now = Date.now()\n\n const tokenResponse = await this.request('token', {\n grant_type: 'refresh_token',\n refresh_token: tokenSet.refresh_token,\n })\n\n return {\n aud,\n sub: tokenSet.sub,\n iss: this.issuer,\n\n scope: tokenResponse.scope,\n refresh_token: tokenResponse.refresh_token,\n access_token: tokenResponse.access_token,\n token_type: tokenResponse.token_type,\n\n expires_at:\n typeof tokenResponse.expires_in === 'number'\n ? new Date(now + tokenResponse.expires_in * 1000).toISOString()\n : undefined,\n }\n }\n\n /**\n * VERY IMPORTANT ! Always call this to process token responses.\n *\n * Whenever an OAuth token response is received, we **MUST** verify that the\n * \"sub\" is a DID, whose issuer authority is indeed the server we just\n * obtained credentials from. This check is a critical step to actually be\n * able to use the \"sub\" (DID) as being the actual user's identifier.\n *\n * @returns The user's PDS URL (the resource server for the user)\n */\n protected async verifyIssuer(sub: AtprotoDid): Promise<string> {\n const resolved = await this.oauthResolver.resolveFromIdentity(sub, {\n noCache: true,\n allowStale: false,\n signal: timeoutSignal(10e3),\n })\n\n if (this.issuer !== resolved.metadata.issuer) {\n // Best case scenario; the user switched PDS. Worst case scenario; a bad\n // actor is trying to impersonate a user. In any case, we must not allow\n // this token to be used.\n throw new TypeError('Issuer mismatch')\n }\n\n return resolved.pds.href\n }\n\n async request<Endpoint extends OAuthEndpointName>(\n endpoint: Endpoint,\n payload: Endpoint extends 'token'\n ? OAuthTokenRequest\n : Endpoint extends 'pushed_authorization_request'\n ? OAuthAuthorizationRequestPar\n : Record<string, unknown>,\n ): Promise<\n Endpoint extends 'token'\n ? AtprotoOAuthTokenResponse\n : Endpoint extends 'pushed_authorization_request'\n ? OAuthParResponse\n : Json\n >\n async request(\n endpoint: OAuthEndpointName,\n payload: Record<string, unknown>,\n ): Promise<unknown> {\n const url = this.serverMetadata[`${endpoint}_endpoint`]\n if (!url) throw new Error(`No ${endpoint} endpoint available`)\n\n const auth = await this.clientCredentialsFactory()\n\n // https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13#section-3.2.2\n // https://datatracker.ietf.org/doc/html/rfc7009#section-2.1\n // https://datatracker.ietf.org/doc/html/rfc7662#section-2.1\n // https://datatracker.ietf.org/doc/html/rfc9126#section-2\n const { response, json } = await this.dpopFetch(url, {\n method: 'POST',\n headers: {\n ...auth.headers,\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: wwwFormUrlEncode({ ...payload, ...auth.payload }),\n }).then(fetchJsonProcessor())\n\n if (response.ok) {\n switch (endpoint) {\n case 'token':\n return atprotoOAuthTokenResponseSchema.parse(json)\n case 'pushed_authorization_request':\n return oauthParResponseSchema.parse(json)\n default:\n return json\n }\n } else {\n throw new OAuthResponseError(response, json)\n }\n }\n}\n\nfunction wwwFormUrlEncode(payload: Record<string, undefined | unknown>) {\n return new URLSearchParams(\n Object.entries(payload)\n .filter(entryHasDefinedValue)\n .map(stringifyEntryValue),\n ).toString()\n}\n\nfunction entryHasDefinedValue(\n entry: [string, unknown],\n): entry is [string, null | NonNullable<unknown>] {\n return entry[1] !== undefined\n}\n\nfunction stringifyEntryValue(entry: [string, unknown]): [string, string] {\n const name = entry[0]\n const value = entry[1]\n\n switch (typeof value) {\n case 'string':\n return [name, value]\n case 'number':\n case 'boolean':\n return [name, String(value)]\n default: {\n const enc = JSON.stringify(value)\n if (enc === undefined) {\n throw new Error(`Unsupported value type for ${name}: ${String(value)}`)\n }\n return [name, enc]\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"oauth-server-agent.js","sourceRoot":"","sources":["../src/oauth-server-agent.ts"],"names":[],"mappings":"AAGA,OAAO,EASL,+BAA+B,EAC/B,sBAAsB,GACvB,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAGL,SAAS,EACT,kBAAkB,GACnB,MAAM,qBAAqB,CAAA;AAE5B,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAA;AACnE,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAA;AAClD,OAAO,EAGL,8BAA8B,GAC/B,MAAM,wBAAwB,CAAA;AAC/B,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAA;AAG9D,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAA;AAmBzC,MAAM,OAAO,gBAAgB;IAI3B;;OAEG;IACH,YACW,UAA4B,EAC5B,OAAY,EACZ,cAAgD,EAChD,cAA8B,EAC9B,UAA0B,EAC1B,aAA4B,EAC5B,OAAgB,EAChB,MAAe,EACxB,KAAa;0BARJ,UAAU;uBACV,OAAO;8BACP,cAAc;8BACd,cAAc;0BACd,UAAU;6BACV,aAAa;uBACb,OAAO;sBACP,MAAM;QAGf,IAAI,CAAC,wBAAwB,GAAG,8BAA8B,CAC5D,UAAU,EACV,cAAc,EACd,cAAc,EACd,OAAO,EACP,MAAM,CACP,CAAA;QAED,IAAI,CAAC,SAAS,GAAG,gB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AAC,KAAK,CAAC,CAAC,CAAA;QAC9B,SAAS,CAAC;YACR,MAAM,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAA;YACjC,IAAI,GAAG,KAAK,SAAS,EAAE,CAAC;gBACtB,MAAM,IAAI,KAAK,CAAC,8BAA8B,IAAI,KAAK,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAA;YACzE,CAAC;YACD,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;QACpB,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import type { AtprotoDid } from '@atproto/did'\nimport type { Key, Keyset } from '@atproto/jwk'\nimport type { OAuthResolver } from '@atproto/oauth-resolver'\nimport {\n type AtprotoOAuthScope,\n type AtprotoOAuthTokenResponse,\n type OAuthAuthorizationRequestPar,\n type OAuthAuthorizationServerMetadata,\n type OAuthEndpointName,\n type OAuthParResponse,\n type OAuthRedirectUri,\n type OAuthTokenRequest,\n atprotoOAuthTokenResponseSchema,\n oauthParResponseSchema,\n} from '@atproto/oauth-types'\nimport {\n type Fetch,\n type Json,\n bindFetch,\n fetchJsonProcessor,\n} from '@atproto-labs/fetch'\nimport type { SimpleStore } from '@atproto-labs/simple-store'\nimport { TokenRefreshError } from './errors/token-refresh-error.js'\nimport { dpopFetchWrapper } from './fetch-dpop.js'\nimport {\n type ClientAuthMethod,\n type ClientCredentialsFactory,\n createClientCredentialsFactory,\n} from './oauth-client-auth.js'\nimport { OAuthResponseError } from './oauth-response-error.js'\nimport type { Runtime } from './runtime.js'\nimport type { ClientMetadata } from './types.js'\nimport { timeoutSignal } from './util.js'\n\nexport type { AtprotoDid, AtprotoOAuthScope, AtprotoOAuthTokenResponse }\n\nexport type TokenSet = {\n iss: string\n sub: AtprotoDid\n aud: string\n scope: AtprotoOAuthScope\n\n refresh_token?: string\n access_token: string\n token_type: 'DPoP'\n /** ISO Date */\n expires_at?: string\n}\n\nexport type DpopNonceCache = SimpleStore<string, string>\n\nexport class OAuthServerAgent {\n protected dpopFetch: Fetch<unknown>\n protected clientCredentialsFactory: ClientCredentialsFactory\n\n /**\n * @throws see {@link createClientCredentialsFactory}\n */\n constructor(\n readonly authMethod: ClientAuthMethod,\n readonly dpopKey: Key,\n readonly serverMetadata: OAuthAuthorizationServerMetadata,\n readonly clientMetadata: ClientMetadata,\n readonly dpopNonces: DpopNonceCache,\n readonly oauthResolver: OAuthResolver,\n readonly runtime: Runtime,\n readonly keyset?: Keyset,\n fetch?: Fetch,\n ) {\n this.clientCredentialsFactory = createClientCredentialsFactory(\n authMethod,\n serverMetadata,\n clientMetadata,\n runtime,\n keyset,\n )\n\n this.dpopFetch = dpopFetchWrapper<void>({\n fetch: bindFetch(fetch),\n key: dpopKey,\n supportedAlgs: serverMetadata.dpop_signing_alg_values_supported,\n sha256: async (v) => runtime.sha256(v),\n nonces: dpopNonces,\n isAuthServer: true,\n })\n }\n\n get issuer() {\n return this.serverMetadata.issuer\n }\n\n async revoke(token: string) {\n try {\n await this.request('revocation', { token })\n } catch {\n // Don't care\n }\n }\n\n async exchangeCode(\n code: string,\n codeVerifier?: string,\n redirectUri?: OAuthRedirectUri,\n ): Promise<TokenSet> {\n const now = Date.now()\n\n const tokenResponse = await this.request('token', {\n grant_type: 'authorization_code',\n // redirectUri should always be passed by the calling code, but if it is\n // not, default to the first redirect_uri registered for the client:\n redirect_uri: redirectUri ?? this.clientMetadata.redirect_uris[0],\n code,\n code_verifier: codeVerifier,\n })\n\n try {\n // /!\\ IMPORTANT /!\\\n //\n // The tokenResponse MUST always be valid before the \"sub\" it contains\n // can be trusted (see Atproto's OAuth spec for details).\n const aud = await this.verifyIssuer(tokenResponse.sub)\n\n return {\n aud,\n sub: tokenResponse.sub,\n iss: this.issuer,\n\n scope: tokenResponse.scope,\n refresh_token: tokenResponse.refresh_token,\n access_token: tokenResponse.access_token,\n token_type: tokenResponse.token_type,\n\n expires_at:\n typeof tokenResponse.expires_in === 'number'\n ? new Date(now + tokenResponse.expires_in * 1000).toISOString()\n : undefined,\n }\n } catch (err) {\n await this.revoke(tokenResponse.access_token)\n\n throw err\n }\n }\n\n async refresh(tokenSet: TokenSet): Promise<TokenSet> {\n if (!tokenSet.refresh_token) {\n throw new TokenRefreshError(tokenSet.sub, 'No refresh token available')\n }\n\n // /!\\ IMPORTANT /!\\\n //\n // The \"sub\" MUST be a DID, whose issuer authority is indeed the server we\n // are trying to obtain credentials from. Note that we are doing this\n // *before* we actually try to refresh the token:\n // 1) To avoid unnecessary refresh\n // 2) So that the refresh is the last async operation, ensuring as few\n // async operations happen before the result gets a chance to be stored.\n const aud = await this.verifyIssuer(tokenSet.sub)\n\n const now = Date.now()\n\n const tokenResponse = await this.request('token', {\n grant_type: 'refresh_token',\n refresh_token: tokenSet.refresh_token,\n })\n\n return {\n aud,\n sub: tokenSet.sub,\n iss: this.issuer,\n\n scope: tokenResponse.scope,\n refresh_token: tokenResponse.refresh_token,\n access_token: tokenResponse.access_token,\n token_type: tokenResponse.token_type,\n\n expires_at:\n typeof tokenResponse.expires_in === 'number'\n ? new Date(now + tokenResponse.expires_in * 1000).toISOString()\n : undefined,\n }\n }\n\n /**\n * VERY IMPORTANT ! Always call this to process token responses.\n *\n * Whenever an OAuth token response is received, we **MUST** verify that the\n * \"sub\" is a DID, whose issuer authority is indeed the server we just\n * obtained credentials from. This check is a critical step to actually be\n * able to use the \"sub\" (DID) as being the actual user's identifier.\n *\n * @returns The user's PDS URL (the resource server for the user)\n */\n protected async verifyIssuer(sub: AtprotoDid): Promise<string> {\n const resolved = await this.oauthResolver.resolveFromIdentity(sub, {\n noCache: true,\n allowStale: false,\n signal: timeoutSignal(10e3),\n })\n\n if (this.issuer !== resolved.metadata.issuer) {\n // Best case scenario; the user switched PDS. Worst case scenario; a bad\n // actor is trying to impersonate a user. In any case, we must not allow\n // this token to be used.\n throw new TypeError('Issuer mismatch')\n }\n\n return resolved.pds.href\n }\n\n async request<Endpoint extends OAuthEndpointName>(\n endpoint: Endpoint,\n payload: Endpoint extends 'token'\n ? OAuthTokenRequest\n : Endpoint extends 'pushed_authorization_request'\n ? OAuthAuthorizationRequestPar\n : Record<string, unknown>,\n ): Promise<\n Endpoint extends 'token'\n ? AtprotoOAuthTokenResponse\n : Endpoint extends 'pushed_authorization_request'\n ? OAuthParResponse\n : Json\n >\n async request(\n endpoint: OAuthEndpointName,\n payload: Record<string, unknown>,\n ): Promise<unknown> {\n const url = this.serverMetadata[`${endpoint}_endpoint`]\n if (!url) throw new Error(`No ${endpoint} endpoint available`)\n\n const auth = await this.clientCredentialsFactory()\n\n // https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13#section-3.2.2\n // https://datatracker.ietf.org/doc/html/rfc7009#section-2.1\n // https://datatracker.ietf.org/doc/html/rfc7662#section-2.1\n // https://datatracker.ietf.org/doc/html/rfc9126#section-2\n const { response, json } = await this.dpopFetch(url, {\n method: 'POST',\n headers: {\n ...auth.headers,\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: wwwFormUrlEncode({ ...payload, ...auth.payload }),\n }).then(fetchJsonProcessor())\n\n if (response.ok) {\n switch (endpoint) {\n case 'token':\n return atprotoOAuthTokenResponseSchema.parse(json)\n case 'pushed_authorization_request':\n return oauthParResponseSchema.parse(json)\n default:\n return json\n }\n } else {\n throw new OAuthResponseError(response, json)\n }\n }\n}\n\nfunction wwwFormUrlEncode(payload: Record<string, undefined | unknown>) {\n return new URLSearchParams(\n Object.entries(payload)\n .filter(entryHasDefinedValue)\n .map(stringifyEntryValue),\n ).toString()\n}\n\nfunction entryHasDefinedValue(\n entry: [string, unknown],\n): entry is [string, null | NonNullable<unknown>] {\n return entry[1] !== undefined\n}\n\nfunction stringifyEntryValue(entry: [string, unknown]): [string, string] {\n const name = entry[0]\n const value = entry[1]\n\n switch (typeof value) {\n case 'string':\n return [name, value]\n case 'number':\n case 'boolean':\n return [name, String(value)]\n default: {\n const enc = JSON.stringify(value)\n if (enc === undefined) {\n throw new Error(`Unsupported value type for ${name}: ${String(value)}`)\n }\n return [name, enc]\n }\n }\n}\n"]}
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import type { Key, Keyset } from '@atproto/jwk';
|
|
2
|
+
import type { GetCachedOptions, OAuthResolver } from '@atproto/oauth-resolver';
|
|
2
3
|
import type { OAuthAuthorizationServerMetadata } from '@atproto/oauth-types';
|
|
3
4
|
import type { Fetch } from '@atproto-labs/fetch';
|
|
4
|
-
import type { GetCachedOptions } from './oauth-authorization-server-metadata-resolver.js';
|
|
5
5
|
import type { ClientAuthMethod } from './oauth-client-auth.js';
|
|
6
|
-
import type { OAuthResolver } from './oauth-resolver.js';
|
|
7
6
|
import { type DpopNonceCache, OAuthServerAgent } from './oauth-server-agent.js';
|
|
8
7
|
import type { Runtime } from './runtime.js';
|
|
9
8
|
import type { ClientMetadata } from './types.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth-server-factory.d.ts","sourceRoot":"","sources":["../src/oauth-server-factory.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AAC/C,OAAO,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"oauth-server-factory.d.ts","sourceRoot":"","sources":["../src/oauth-server-factory.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AAC/C,OAAO,KAAK,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAA;AAC9E,OAAO,KAAK,EAAE,gCAAgC,EAAE,MAAM,sBAAsB,CAAA;AAC5E,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAA;AAChD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AAC9D,OAAO,EAAE,KAAK,cAAc,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAA;AAC/E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AAC3C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAEhD,qBAAa,kBAAkB;IAE3B,QAAQ,CAAC,cAAc,EAAE,cAAc;IACvC,QAAQ,CAAC,OAAO,EAAE,OAAO;IACzB,QAAQ,CAAC,QAAQ,EAAE,aAAa;IAChC,QAAQ,CAAC,KAAK,EAAE,KAAK;IACrB,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS;IACnC,QAAQ,CAAC,cAAc,EAAE,cAAc;IANzC,YACW,cAAc,EAAE,cAAc,EAC9B,OAAO,EAAE,OAAO,EAChB,QAAQ,EAAE,aAAa,EACvB,KAAK,EAAE,KAAK,EACZ,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,cAAc,EAAE,cAAc,EACrC;IAEJ;;;;;;;;OAQG;IACG,UAAU,CACd,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,gBAAgB,EAC5B,OAAO,EAAE,GAAG,EACZ,OAAO,CAAC,EAAE,gBAAgB,6BAQ3B;IAED;;OAEG;IACG,YAAY,CAChB,cAAc,EAAE,gCAAgC,EAChD,UAAU,EAAE,gBAAgB,EAC5B,OAAO,EAAE,GAAG,6BAab;CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth-server-factory.js","sourceRoot":"","sources":["../src/oauth-server-factory.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"oauth-server-factory.js","sourceRoot":"","sources":["../src/oauth-server-factory.ts"],"names":[],"mappings":"AAKA,OAAO,EAAuB,gBAAgB,EAAE,MAAM,yBAAyB,CAAA;AAI/E,MAAM,OAAO,kBAAkB;IAC7B,YACW,cAA8B,EAC9B,OAAgB,EAChB,QAAuB,EACvB,KAAY,EACZ,MAA0B,EAC1B,cAA8B;8BAL9B,cAAc;uBACd,OAAO;wBACP,QAAQ;qBACR,KAAK;sBACL,MAAM;8BACN,cAAc;IACtB,CAAC;IAEJ;;;;;;;;OAQG;IACH,KAAK,CAAC,UAAU,CACd,MAAc,EACd,UAA4B,EAC5B,OAAY,EACZ,OAA0B;QAE1B,MAAM,cAAc,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,8BAA8B,CACvE,MAAM,EACN,OAAO,CACR,CAAA;QAED,OAAO,IAAI,CAAC,YAAY,CAAC,cAAc,EAAE,UAAU,EAAE,OAAO,CAAC,CAAA;IAC/D,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,YAAY,CAChB,cAAgD,EAChD,UAA4B,EAC5B,OAAY;QAEZ,OAAO,IAAI,gBAAgB,CACzB,UAAU,EACV,OAAO,EACP,cAAc,EACd,IAAI,CAAC,cAAc,EACnB,IAAI,CAAC,cAAc,EACnB,IAAI,CAAC,QAAQ,EACb,IAAI,CAAC,OAAO,EACZ,IAAI,CAAC,MAAM,EACX,IAAI,CAAC,KAAK,CACX,CAAA;IACH,CAAC;CACF","sourcesContent":["import type { Key, Keyset } from '@atproto/jwk'\nimport type { GetCachedOptions, OAuthResolver } from '@atproto/oauth-resolver'\nimport type { OAuthAuthorizationServerMetadata } from '@atproto/oauth-types'\nimport type { Fetch } from '@atproto-labs/fetch'\nimport type { ClientAuthMethod } from './oauth-client-auth.js'\nimport { type DpopNonceCache, OAuthServerAgent } from './oauth-server-agent.js'\nimport type { Runtime } from './runtime.js'\nimport type { ClientMetadata } from './types.js'\n\nexport class OAuthServerFactory {\n constructor(\n readonly clientMetadata: ClientMetadata,\n readonly runtime: Runtime,\n readonly resolver: OAuthResolver,\n readonly fetch: Fetch,\n readonly keyset: Keyset | undefined,\n readonly dpopNonceCache: DpopNonceCache,\n ) {}\n\n /**\n * @param authMethod `undefined` means that we are restoring a session that\n * was created before we started storing the `authMethod` in the session. In\n * that case, we will use the first key from the keyset.\n *\n * Support for this might be removed in the future.\n *\n * @throws see {@link OAuthServerFactory.fromMetadata}\n */\n async fromIssuer(\n issuer: string,\n authMethod: ClientAuthMethod,\n dpopKey: Key,\n options?: GetCachedOptions,\n ) {\n const serverMetadata = await this.resolver.getAuthorizationServerMetadata(\n issuer,\n options,\n )\n\n return this.fromMetadata(serverMetadata, authMethod, dpopKey)\n }\n\n /**\n * @throws see {@link OAuthServerAgent}\n */\n async fromMetadata(\n serverMetadata: OAuthAuthorizationServerMetadata,\n authMethod: ClientAuthMethod,\n dpopKey: Key,\n ) {\n return new OAuthServerAgent(\n authMethod,\n dpopKey,\n serverMetadata,\n this.clientMetadata,\n this.dpopNonceCache,\n this.resolver,\n this.runtime,\n this.keyset,\n this.fetch,\n )\n }\n}\n"]}
|
package/dist/util.d.ts
CHANGED
|
@@ -3,7 +3,6 @@ export type Simplify<T> = {
|
|
|
3
3
|
[K in keyof T]: T[K];
|
|
4
4
|
} & NonNullable<unknown>;
|
|
5
5
|
export declare const ifString: <V>(v: V) => (V & string) | undefined;
|
|
6
|
-
export declare function contentMime(headers: Headers): string | undefined;
|
|
7
6
|
/**
|
|
8
7
|
* Returns an {@link AbortSignal} that aborts after `ms` milliseconds.
|
|
9
8
|
*
|
package/dist/util.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"util.d.ts","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,SAAS,CAAC,CAAC,IAAI,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,CAAA;AAC7C,MAAM,MAAM,QAAQ,CAAC,CAAC,IAAI;KAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;CAAE,GAAG,WAAW,CAAC,OAAO,CAAC,CAAA;AAEzE,eAAO,MAAM,QAAQ,GAAI,CAAC,KAAK,CAAC,6BAA4C,CAAA;AAE5E
|
|
1
|
+
{"version":3,"file":"util.d.ts","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,SAAS,CAAC,CAAC,IAAI,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,CAAA;AAC7C,MAAM,MAAM,QAAQ,CAAC,CAAC,IAAI;KAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;CAAE,GAAG,WAAW,CAAC,OAAO,CAAC,CAAA;AAEzE,eAAO,MAAM,QAAQ,GAAI,CAAC,KAAK,CAAC,6BAA4C,CAAA;AAE5E;;;;;;;;;;GAUG;AACH,wBAAgB,aAAa,CAAC,EAAE,EAAE,MAAM,GAAG,WAAW,CAQrD;AAgBD,wBAAgB,cAAc,CAC5B,OAAO,EAAE,SAAS,CAAC,WAAW,GAAG,SAAS,CAAC,EAAE,GAC5C,eAAe,GAAG,UAAU,CAwB9B"}
|
package/dist/util.js
CHANGED
package/dist/util.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"util.js","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":"AAGA,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAI,CAAI,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAA;AAE5E
|
|
1
|
+
{"version":3,"file":"util.js","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":"AAGA,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAI,CAAI,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAA;AAE5E;;;;;;;;;;GAUG;AACH,MAAM,UAAU,aAAa,CAAC,EAAU;IACtC,IAAI,OAAO,WAAW,CAAC,OAAO,KAAK,UAAU,EAAE,CAAC;QAC9C,OAAO,WAAW,CAAC,OAAO,CAAC,EAAE,CAAC,CAAA;IAChC,CAAC;IAED,MAAM,UAAU,GAAG,IAAI,eAAe,EAAE,CAAA;IACxC,UAAU,CAAC,GAAG,EAAE,CAAC,UAAU,CAAC,KAAK,CAAC,YAAY,CAAC,EAAE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C,CAAC,CAAA;IACvD,CAAC;CACF","sourcesContent":["export type Awaitable<T> = T | PromiseLike<T>\nexport type Simplify<T> = { [K in keyof T]: T[K] } & NonNullable<unknown>\n\nexport const ifString = <V>(v: V) => (typeof v === 'string' ? v : undefined)\n\n/**\n * Returns an {@link AbortSignal} that aborts after `ms` milliseconds.\n *\n * Uses the native {@link AbortSignal.timeout} when available, and otherwise\n * falls back to an {@link AbortController} + `setTimeout`. The static\n * `AbortSignal.timeout` method is not implemented in every runtime this package\n * targets (notably React Native / Expo), so relying on it directly throws a\n * `TypeError: AbortSignal.timeout is not a function` at runtime.\n *\n * @see {@link https://github.com/facebook/react-native/issues/42042}\n */\nexport function timeoutSignal(ms: number): AbortSignal {\n if (typeof AbortSignal.timeout === 'function') {\n return AbortSignal.timeout(ms)\n }\n\n const controller = new AbortController()\n setTimeout(() => controller.abort(timeoutError(ms)), ms)\n return controller.signal\n}\n\n/**\n * Builds the reason used to abort a {@link timeoutSignal} fallback. Mirrors the\n * native `AbortSignal.timeout` behaviour (a `TimeoutError` `DOMException`) when\n * `DOMException` is available, and degrades to a plain `Error` in runtimes that\n * lack it.\n */\nfunction timeoutError(ms: number): unknown {\n const message = `The operation timed out after ${ms} ms`\n if (typeof DOMException === 'function') {\n return new DOMException(message, 'TimeoutError')\n }\n return new Error(message)\n}\n\nexport function combineSignals(\n signals: readonly (AbortSignal | undefined)[],\n): AbortController & Disposable {\n const controller = new DisposableAbortController()\n\n const onAbort = function (this: AbortSignal, _event: Event) {\n const reason = new Error('This operation was aborted', {\n cause: this.reason,\n })\n\n controller.abort(reason)\n }\n\n try {\n for (const sig of signals) {\n if (sig) {\n sig.throwIfAborted()\n sig.addEventListener('abort', onAbort, { signal: controller.signal })\n }\n }\n\n return controller\n } catch (err) {\n controller.abort(err)\n throw err\n }\n}\n\n/**\n * Allows using {@link AbortController} with the `using` keyword, in order to\n * automatically abort them once the execution block ends.\n */\nclass DisposableAbortController extends AbortController implements Disposable {\n [Symbol.dispose]() {\n this.abort(new Error('AbortController was disposed'))\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@atproto/oauth-client",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "OAuth client for ATPROTO PDS. This package serves as common base for environment-specific implementations (NodeJS, Browser, React-Native).",
|
|
6
6
|
"keywords": [
|
|
@@ -34,16 +34,17 @@
|
|
|
34
34
|
"core-js": "^3.50.0",
|
|
35
35
|
"multiformats": "^13.0.0",
|
|
36
36
|
"zod": "^3.23.8",
|
|
37
|
+
"@atproto-labs/did-resolver": "^0.3.11",
|
|
37
38
|
"@atproto-labs/fetch": "^0.4.0",
|
|
38
|
-
"@atproto-labs/
|
|
39
|
+
"@atproto-labs/handle-resolver": "^0.4.10",
|
|
39
40
|
"@atproto-labs/identity-resolver": "^0.4.11",
|
|
41
|
+
"@atproto-labs/simple-store": "^0.5.1",
|
|
40
42
|
"@atproto-labs/simple-store-memory": "^0.2.6",
|
|
41
43
|
"@atproto/did": "^0.5.6",
|
|
42
44
|
"@atproto/jwk": "^0.7.4",
|
|
45
|
+
"@atproto/oauth-resolver": "^0.0.1",
|
|
43
46
|
"@atproto/oauth-types": "^0.7.7",
|
|
44
|
-
"@atproto/xrpc": "^0.8.16"
|
|
45
|
-
"@atproto-labs/did-resolver": "^0.3.11",
|
|
46
|
-
"@atproto-labs/handle-resolver": "^0.4.10"
|
|
47
|
+
"@atproto/xrpc": "^0.8.16"
|
|
47
48
|
},
|
|
48
49
|
"devDependencies": {
|
|
49
50
|
"vitest": "^4.1.10"
|
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
import { type OAuthAuthorizationServerMetadata } from '@atproto/oauth-types';
|
|
2
|
-
import { type Fetch } from '@atproto-labs/fetch';
|
|
3
|
-
import { CachedGetter, type GetCachedOptions, type SimpleStore, type StoreErrorHandler } from '@atproto-labs/simple-store';
|
|
4
|
-
export type { GetCachedOptions, OAuthAuthorizationServerMetadata };
|
|
5
|
-
export type AuthorizationServerMetadataCache = SimpleStore<string, OAuthAuthorizationServerMetadata>;
|
|
6
|
-
export type OAuthAuthorizationServerMetadataResolverConfig = {
|
|
7
|
-
allowHttpIssuer?: boolean;
|
|
8
|
-
/**
|
|
9
|
-
* Called when the metadata cache throws. The cache is best-effort: failures
|
|
10
|
-
* are logged (by default) and degrade to a cache miss + refetch, rather than
|
|
11
|
-
* being propagated.
|
|
12
|
-
*/
|
|
13
|
-
onCacheError?: StoreErrorHandler<string>;
|
|
14
|
-
};
|
|
15
|
-
/**
|
|
16
|
-
* @see {@link https://datatracker.ietf.org/doc/html/rfc8414}
|
|
17
|
-
*/
|
|
18
|
-
export declare class OAuthAuthorizationServerMetadataResolver extends CachedGetter<string, OAuthAuthorizationServerMetadata> {
|
|
19
|
-
private readonly fetch;
|
|
20
|
-
private readonly allowHttpIssuer;
|
|
21
|
-
constructor(cache: AuthorizationServerMetadataCache, fetch?: Fetch, config?: OAuthAuthorizationServerMetadataResolverConfig);
|
|
22
|
-
get(input: URL | string, options?: GetCachedOptions): Promise<OAuthAuthorizationServerMetadata>;
|
|
23
|
-
private fetchMetadata;
|
|
24
|
-
}
|
|
25
|
-
//# sourceMappingURL=oauth-authorization-server-metadata-resolver.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
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,EAChB,KAAK,iBAAiB,EAEvB,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;IAEzB;;;;OAIG;IACH,YAAY,CAAC,EAAE,iBAAiB,CAAC,MAAM,CAAC,CAAA;CACzC,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,EASxD;IAEK,GAAG,CACP,KAAK,EAAE,GAAG,GAAG,MAAM,EACnB,OAAO,CAAC,EAAE,gBAAgB,GACzB,OAAO,CAAC,gCAAgC,CAAC,CAQ3C;YAEa,aAAa;CAwD5B"}
|
|
@@ -1,54 +0,0 @@
|
|
|
1
|
-
import { oauthAuthorizationServerMetadataValidator, oauthIssuerIdentifierSchema, } from '@atproto/oauth-types';
|
|
2
|
-
import { FetchResponseError, bindFetch, cancelBody, } from '@atproto-labs/fetch';
|
|
3
|
-
import { CachedGetter, swallowStoreErrors, } from '@atproto-labs/simple-store';
|
|
4
|
-
import { contentMime } from './util.js';
|
|
5
|
-
/**
|
|
6
|
-
* @see {@link https://datatracker.ietf.org/doc/html/rfc8414}
|
|
7
|
-
*/
|
|
8
|
-
export class OAuthAuthorizationServerMetadataResolver extends CachedGetter {
|
|
9
|
-
constructor(cache, fetch, config) {
|
|
10
|
-
super(async (issuer, options) => this.fetchMetadata(issuer, options), swallowStoreErrors(cache, config?.onCacheError));
|
|
11
|
-
this.fetch = bindFetch(fetch);
|
|
12
|
-
this.allowHttpIssuer = config?.allowHttpIssuer === true;
|
|
13
|
-
}
|
|
14
|
-
async get(input, options) {
|
|
15
|
-
const issuer = oauthIssuerIdentifierSchema.parse(String(input));
|
|
16
|
-
if (!this.allowHttpIssuer && issuer.startsWith('http:')) {
|
|
17
|
-
throw new TypeError('Unsecure issuer URL protocol only allowed in development and test environments');
|
|
18
|
-
}
|
|
19
|
-
return super.get(issuer, options);
|
|
20
|
-
}
|
|
21
|
-
async fetchMetadata(issuer, options) {
|
|
22
|
-
const url = new URL(`/.well-known/oauth-authorization-server`, issuer);
|
|
23
|
-
const request = new Request(url, {
|
|
24
|
-
headers: { accept: 'application/json' },
|
|
25
|
-
cache: options?.noCache ? 'no-cache' : undefined,
|
|
26
|
-
signal: options?.signal,
|
|
27
|
-
redirect: 'manual', // response must be 200 OK
|
|
28
|
-
});
|
|
29
|
-
const response = await this.fetch(request);
|
|
30
|
-
// https://datatracker.ietf.org/doc/html/rfc8414#section-3.2
|
|
31
|
-
if (response.status !== 200) {
|
|
32
|
-
await cancelBody(response, 'log');
|
|
33
|
-
throw await FetchResponseError.from(response, `Unexpected status code ${response.status} for "${url}"`, undefined, { cause: request });
|
|
34
|
-
}
|
|
35
|
-
if (contentMime(response.headers) !== 'application/json') {
|
|
36
|
-
await cancelBody(response, 'log');
|
|
37
|
-
throw await FetchResponseError.from(response, `Unexpected content type for "${url}"`, undefined, { cause: request });
|
|
38
|
-
}
|
|
39
|
-
const metadata = oauthAuthorizationServerMetadataValidator.parse(await response.json());
|
|
40
|
-
// Validate the issuer (MIX-UP attacks)
|
|
41
|
-
// https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics#name-mix-up-attacks
|
|
42
|
-
// https://datatracker.ietf.org/doc/html/rfc8414#section-2
|
|
43
|
-
if (metadata.issuer !== issuer) {
|
|
44
|
-
throw new TypeError(`Invalid issuer ${metadata.issuer}`);
|
|
45
|
-
}
|
|
46
|
-
// ATPROTO requires client_id_metadata_document
|
|
47
|
-
// https://datatracker.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/
|
|
48
|
-
if (metadata.client_id_metadata_document_supported !== true) {
|
|
49
|
-
throw new TypeError(`Authorization server "${issuer}" does not support client_id_metadata_document`);
|
|
50
|
-
}
|
|
51
|
-
return metadata;
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
//# sourceMappingURL=oauth-authorization-server-metadata-resolver.js.map
|
|
@@ -1 +0,0 @@
|
|
|
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,EAIZ,kBAAkB,GACnB,MAAM,4BAA4B,CAAA;AACnC,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAoBvC;;GAEG;AACH,MAAM,OAAO,wCAAyC,SAAQ,YAG7D;IAIC,YACE,KAAuC,EACvC,KAAa,EACb,MAAuD;QAEvD,KAAK,CACH,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,MAAM,EAAE,OAAO,CAAC,EAC9D,kBAAkB,CAAC,KAAK,EAAE,MAAM,EAAE,YAAY,CAAC,CAChD,CAAA;QAED,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,CAA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C,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 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 type StoreErrorHandler,\n swallowStoreErrors,\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 * Called when the metadata cache throws. The cache is best-effort: failures\n * are logged (by default) and degrade to a cache miss + refetch, rather than\n * being propagated.\n */\n onCacheError?: StoreErrorHandler<string>\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(\n async (issuer, options) => this.fetchMetadata(issuer, options),\n swallowStoreErrors(cache, config?.onCacheError),\n )\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,25 +0,0 @@
|
|
|
1
|
-
import { type OAuthProtectedResourceMetadata } from '@atproto/oauth-types';
|
|
2
|
-
import { type Fetch } from '@atproto-labs/fetch';
|
|
3
|
-
import { CachedGetter, type GetCachedOptions, type SimpleStore, type StoreErrorHandler } from '@atproto-labs/simple-store';
|
|
4
|
-
export type { GetCachedOptions, OAuthProtectedResourceMetadata };
|
|
5
|
-
export type ProtectedResourceMetadataCache = SimpleStore<string, OAuthProtectedResourceMetadata | null>;
|
|
6
|
-
export type OAuthProtectedResourceMetadataResolverConfig = {
|
|
7
|
-
allowHttpResource?: boolean;
|
|
8
|
-
/**
|
|
9
|
-
* Called when the metadata cache throws. The cache is best-effort: failures
|
|
10
|
-
* are logged (by default) and degrade to a cache miss + refetch, rather than
|
|
11
|
-
* being propagated.
|
|
12
|
-
*/
|
|
13
|
-
onCacheError?: StoreErrorHandler<string>;
|
|
14
|
-
};
|
|
15
|
-
/**
|
|
16
|
-
* @see {@link https://www.rfc-editor.org/rfc/rfc9728.html}
|
|
17
|
-
*/
|
|
18
|
-
export declare class OAuthProtectedResourceMetadataResolver extends CachedGetter<string, OAuthProtectedResourceMetadata | null> {
|
|
19
|
-
private readonly fetch;
|
|
20
|
-
private readonly allowHttpResource;
|
|
21
|
-
constructor(cache: ProtectedResourceMetadataCache, fetch?: Fetch, config?: OAuthProtectedResourceMetadataResolverConfig);
|
|
22
|
-
get(resource: string | URL, options?: GetCachedOptions): Promise<OAuthProtectedResourceMetadata | null>;
|
|
23
|
-
private fetchMetadata;
|
|
24
|
-
}
|
|
25
|
-
//# sourceMappingURL=oauth-protected-resource-metadata-resolver.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
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,EAChB,KAAK,iBAAiB,EAEvB,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;IAE3B;;;;OAIG;IACH,YAAY,CAAC,EAAE,iBAAiB,CAAC,MAAM,CAAC,CAAA;CACzC,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,EAStD;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,54 +0,0 @@
|
|
|
1
|
-
import { oauthProtectedResourceMetadataSchema, } from '@atproto/oauth-types';
|
|
2
|
-
import { FetchResponseError, bindFetch, cancelBody, } from '@atproto-labs/fetch';
|
|
3
|
-
import { CachedGetter, swallowStoreErrors, } from '@atproto-labs/simple-store';
|
|
4
|
-
import { contentMime } from './util.js';
|
|
5
|
-
/**
|
|
6
|
-
* @see {@link https://www.rfc-editor.org/rfc/rfc9728.html}
|
|
7
|
-
*/
|
|
8
|
-
export class OAuthProtectedResourceMetadataResolver extends CachedGetter {
|
|
9
|
-
constructor(cache, fetch = globalThis.fetch, config) {
|
|
10
|
-
super(async (origin, options) => this.fetchMetadata(origin, options), swallowStoreErrors(cache, config?.onCacheError));
|
|
11
|
-
this.fetch = bindFetch(fetch);
|
|
12
|
-
this.allowHttpResource = config?.allowHttpResource === true;
|
|
13
|
-
}
|
|
14
|
-
async get(resource, options) {
|
|
15
|
-
const { protocol, origin } = new URL(resource);
|
|
16
|
-
if (protocol !== 'https:' && protocol !== 'http:') {
|
|
17
|
-
throw new TypeError(`Invalid protected resource metadata URL protocol: ${protocol}`);
|
|
18
|
-
}
|
|
19
|
-
if (protocol === 'http:' && !this.allowHttpResource) {
|
|
20
|
-
throw new TypeError(`Unsecure resource metadata URL (${protocol}) only allowed in development and test environments`);
|
|
21
|
-
}
|
|
22
|
-
return super.get(origin, options);
|
|
23
|
-
}
|
|
24
|
-
async fetchMetadata(origin, options) {
|
|
25
|
-
const url = new URL(`/.well-known/oauth-protected-resource`, origin);
|
|
26
|
-
const request = new Request(url, {
|
|
27
|
-
signal: options?.signal,
|
|
28
|
-
headers: { accept: 'application/json' },
|
|
29
|
-
cache: options?.noCache ? 'no-cache' : undefined,
|
|
30
|
-
redirect: 'manual', // response must be 200 OK
|
|
31
|
-
});
|
|
32
|
-
const response = await this.fetch(request);
|
|
33
|
-
if (response.status === 404) {
|
|
34
|
-
await cancelBody(response, 'log');
|
|
35
|
-
return null;
|
|
36
|
-
}
|
|
37
|
-
// https://www.rfc-editor.org/rfc/rfc9728.html#section-3.2
|
|
38
|
-
if (response.status !== 200) {
|
|
39
|
-
await cancelBody(response, 'log');
|
|
40
|
-
throw await FetchResponseError.from(response, `Unexpected status code ${response.status} for "${url}"`, undefined, { cause: request });
|
|
41
|
-
}
|
|
42
|
-
if (contentMime(response.headers) !== 'application/json') {
|
|
43
|
-
await cancelBody(response, 'log');
|
|
44
|
-
throw await FetchResponseError.from(response, `Unexpected content type for "${url}"`, undefined, { cause: request });
|
|
45
|
-
}
|
|
46
|
-
const metadata = oauthProtectedResourceMetadataSchema.parse(await response.json());
|
|
47
|
-
// https://www.rfc-editor.org/rfc/rfc9728.html#section-3.3
|
|
48
|
-
if (metadata.resource !== origin) {
|
|
49
|
-
throw new TypeError(`Invalid issuer ${metadata.resource}`);
|
|
50
|
-
}
|
|
51
|
-
return metadata;
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
//# sourceMappingURL=oauth-protected-resource-metadata-resolver.js.map
|
|
@@ -1 +0,0 @@
|
|
|
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,EAIZ,kBAAkB,GACnB,MAAM,4BAA4B,CAAA;AACnC,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAoBvC;;GAEG;AACH,MAAM,OAAO,sCAAuC,SAAQ,YAG3D;IAIC,YACE,KAAqC,EACrC,KAAK,GAAU,UAAU,CAAC,KAAK,EAC/B,MAAqD;QAErD,KAAK,CACH,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,MAAM,EAAE,OAAO,CAAC,EAC9D,kBAAkB,CAAC,KAAK,EAAE,MAAM,EAAE,YAAY,CAAC,CAChD,CAAA;QAED,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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,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 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 type StoreErrorHandler,\n swallowStoreErrors,\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 * Called when the metadata cache throws. The cache is best-effort: failures\n * are logged (by default) and degrade to a cache miss + refetch, rather than\n * being propagated.\n */\n onCacheError?: StoreErrorHandler<string>\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(\n async (origin, options) => this.fetchMetadata(origin, options),\n swallowStoreErrors(cache, config?.onCacheError),\n )\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 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"oauth-resolver-error.d.ts","sourceRoot":"","sources":["../src/oauth-resolver-error.ts"],"names":[],"mappings":"AAEA,qBAAa,kBAAmB,SAAQ,KAAK;IAC3C,YAAY,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,EAEzD;IAED,MAAM,CAAC,IAAI,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,kBAAkB,CAYhE;CACF"}
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
import { ZodError } from 'zod';
|
|
2
|
-
export class OAuthResolverError extends Error {
|
|
3
|
-
constructor(message, options) {
|
|
4
|
-
super(message, options);
|
|
5
|
-
}
|
|
6
|
-
static from(cause, message) {
|
|
7
|
-
if (cause instanceof OAuthResolverError)
|
|
8
|
-
return cause;
|
|
9
|
-
const validationReason = cause instanceof ZodError
|
|
10
|
-
? `${cause.errors[0].path} ${cause.errors[0].message}`
|
|
11
|
-
: null;
|
|
12
|
-
const fullMessage = (message ?? `Unable to resolve identity`) +
|
|
13
|
-
(validationReason ? ` (${validationReason})` : '');
|
|
14
|
-
return new OAuthResolverError(fullMessage, {
|
|
15
|
-
cause,
|
|
16
|
-
});
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
//# sourceMappingURL=oauth-resolver-error.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"oauth-resolver-error.js","sourceRoot":"","sources":["../src/oauth-resolver-error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,KAAK,CAAA;AAE9B,MAAM,OAAO,kBAAmB,SAAQ,KAAK;IAC3C,YAAY,OAAe,EAAE,OAA6B;QACxD,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAA;IACzB,CAAC;IAED,MAAM,CAAC,IAAI,CAAC,KAAc,EAAE,OAAgB;QAC1C,IAAI,KAAK,YAAY,kBAAkB;YAAE,OAAO,KAAK,CAAA;QACrD,MAAM,gBAAgB,GACpB,KAAK,YAAY,QAAQ;YACvB,CAAC,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE;YACtD,CAAC,CAAC,IAAI,CAAA;QACV,MAAM,WAAW,GACf,CAAC,OAAO,IAAI,4BAA4B,CAAC;YACzC,CAAC,gBAAgB,CAAC,CAAC,CAAC,KAAK,gBAAgB,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAA;QACpD,OAAO,IAAI,kBAAkB,CAAC,WAAW,EAAE;YACzC,KAAK;SACN,CAAC,CAAA;IACJ,CAAC;CACF","sourcesContent":["import { ZodError } from 'zod'\n\nexport class OAuthResolverError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options)\n }\n\n static from(cause: unknown, message?: string): OAuthResolverError {\n if (cause instanceof OAuthResolverError) return cause\n const validationReason =\n cause instanceof ZodError\n ? `${cause.errors[0].path} ${cause.errors[0].message}`\n : null\n const fullMessage =\n (message ?? `Unable to resolve identity`) +\n (validationReason ? ` (${validationReason})` : '')\n return new OAuthResolverError(fullMessage, {\n cause,\n })\n }\n}\n"]}
|
package/dist/oauth-resolver.d.ts
DELETED
|
@@ -1,73 +0,0 @@
|
|
|
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
|
-
export type { GetCachedOptions };
|
|
6
|
-
export type ResolveOAuthOptions = GetCachedOptions & ResolveIdentityOptions;
|
|
7
|
-
export declare class OAuthResolver {
|
|
8
|
-
readonly identityResolver: IdentityResolver;
|
|
9
|
-
readonly protectedResourceMetadataResolver: OAuthProtectedResourceMetadataResolver;
|
|
10
|
-
readonly authorizationServerMetadataResolver: OAuthAuthorizationServerMetadataResolver;
|
|
11
|
-
constructor(identityResolver: IdentityResolver, protectedResourceMetadataResolver: OAuthProtectedResourceMetadataResolver, authorizationServerMetadataResolver: OAuthAuthorizationServerMetadataResolver);
|
|
12
|
-
/**
|
|
13
|
-
* @param input - A handle, DID, PDS URL or Entryway URL
|
|
14
|
-
*/
|
|
15
|
-
resolve(input: string, options?: ResolveOAuthOptions): Promise<{
|
|
16
|
-
identityInfo?: IdentityInfo;
|
|
17
|
-
metadata: OAuthAuthorizationServerMetadata;
|
|
18
|
-
}>;
|
|
19
|
-
/**
|
|
20
|
-
* @note this method can be used to verify if a particular uri supports OAuth
|
|
21
|
-
* based sign-in (for compatibility with legacy implementation).
|
|
22
|
-
*/
|
|
23
|
-
resolveFromService(input: string, options?: ResolveOAuthOptions): Promise<{
|
|
24
|
-
metadata: OAuthAuthorizationServerMetadata;
|
|
25
|
-
}>;
|
|
26
|
-
resolveFromIdentity(input: string, options?: ResolveOAuthOptions): Promise<{
|
|
27
|
-
identityInfo: IdentityInfo;
|
|
28
|
-
metadata: OAuthAuthorizationServerMetadata;
|
|
29
|
-
pds: URL;
|
|
30
|
-
}>;
|
|
31
|
-
resolveIdentity(input: string, options?: ResolveIdentityOptions): Promise<IdentityInfo>;
|
|
32
|
-
getAuthorizationServerMetadata(issuer: string | URL, options?: GetCachedOptions): Promise<OAuthAuthorizationServerMetadata>;
|
|
33
|
-
getResourceServerMetadata(pdsUrl: string | URL, options?: GetCachedOptions): Promise<{
|
|
34
|
-
issuer: "http://127.0.0.1" | "http://localhost" | `http://127.0.0.1#${string}` | `http://127.0.0.1/${string}` | `http://127.0.0.1:${string}` | `http://127.0.0.1?${string}` | `http://[::1]${string}` | `http://localhost#${string}` | `http://localhost/${string}` | `http://localhost:${string}` | `http://localhost?${string}` | `https://${string}`;
|
|
35
|
-
claims_supported?: string[] | undefined;
|
|
36
|
-
claims_locales_supported?: string[] | undefined;
|
|
37
|
-
claims_parameter_supported?: boolean | undefined;
|
|
38
|
-
request_parameter_supported?: boolean | undefined;
|
|
39
|
-
request_uri_parameter_supported?: boolean | undefined;
|
|
40
|
-
require_request_uri_registration?: boolean | undefined;
|
|
41
|
-
scopes_supported?: string[] | undefined;
|
|
42
|
-
subject_types_supported?: string[] | undefined;
|
|
43
|
-
response_types_supported?: string[] | undefined;
|
|
44
|
-
response_modes_supported?: string[] | undefined;
|
|
45
|
-
grant_types_supported?: string[] | undefined;
|
|
46
|
-
code_challenge_methods_supported?: ("S256" | "plain")[] | undefined;
|
|
47
|
-
ui_locales_supported?: string[] | undefined;
|
|
48
|
-
id_token_signing_alg_values_supported?: string[] | undefined;
|
|
49
|
-
display_values_supported?: string[] | undefined;
|
|
50
|
-
request_object_signing_alg_values_supported?: string[] | undefined;
|
|
51
|
-
authorization_response_iss_parameter_supported?: boolean | undefined;
|
|
52
|
-
authorization_details_types_supported?: string[] | undefined;
|
|
53
|
-
request_object_encryption_alg_values_supported?: string[] | undefined;
|
|
54
|
-
request_object_encryption_enc_values_supported?: string[] | undefined;
|
|
55
|
-
jwks_uri?: "http://127.0.0.1" | "http://localhost" | `http://127.0.0.1#${string}` | `http://127.0.0.1/${string}` | `http://127.0.0.1:${string}` | `http://127.0.0.1?${string}` | `http://[::1]${string}` | `http://localhost#${string}` | `http://localhost/${string}` | `http://localhost:${string}` | `http://localhost?${string}` | `https://${string}` | undefined;
|
|
56
|
-
authorization_endpoint: "http://127.0.0.1" | "http://localhost" | `http://127.0.0.1#${string}` | `http://127.0.0.1/${string}` | `http://127.0.0.1:${string}` | `http://127.0.0.1?${string}` | `http://[::1]${string}` | `http://localhost#${string}` | `http://localhost/${string}` | `http://localhost:${string}` | `http://localhost?${string}` | `https://${string}`;
|
|
57
|
-
token_endpoint: "http://127.0.0.1" | "http://localhost" | `http://127.0.0.1#${string}` | `http://127.0.0.1/${string}` | `http://127.0.0.1:${string}` | `http://127.0.0.1?${string}` | `http://[::1]${string}` | `http://localhost#${string}` | `http://localhost/${string}` | `http://localhost:${string}` | `http://localhost?${string}` | `https://${string}`;
|
|
58
|
-
token_endpoint_auth_methods_supported: string[];
|
|
59
|
-
token_endpoint_auth_signing_alg_values_supported?: string[] | undefined;
|
|
60
|
-
revocation_endpoint?: "http://127.0.0.1" | "http://localhost" | `http://127.0.0.1#${string}` | `http://127.0.0.1/${string}` | `http://127.0.0.1:${string}` | `http://127.0.0.1?${string}` | `http://[::1]${string}` | `http://localhost#${string}` | `http://localhost/${string}` | `http://localhost:${string}` | `http://localhost?${string}` | `https://${string}` | undefined;
|
|
61
|
-
introspection_endpoint?: "http://127.0.0.1" | "http://localhost" | `http://127.0.0.1#${string}` | `http://127.0.0.1/${string}` | `http://127.0.0.1:${string}` | `http://127.0.0.1?${string}` | `http://[::1]${string}` | `http://localhost#${string}` | `http://localhost/${string}` | `http://localhost:${string}` | `http://localhost?${string}` | `https://${string}` | undefined;
|
|
62
|
-
pushed_authorization_request_endpoint?: "http://127.0.0.1" | "http://localhost" | `http://127.0.0.1#${string}` | `http://127.0.0.1/${string}` | `http://127.0.0.1:${string}` | `http://127.0.0.1?${string}` | `http://[::1]${string}` | `http://localhost#${string}` | `http://localhost/${string}` | `http://localhost:${string}` | `http://localhost?${string}` | `https://${string}` | undefined;
|
|
63
|
-
require_pushed_authorization_requests?: boolean | undefined;
|
|
64
|
-
userinfo_endpoint?: "http://127.0.0.1" | "http://localhost" | `http://127.0.0.1#${string}` | `http://127.0.0.1/${string}` | `http://127.0.0.1:${string}` | `http://127.0.0.1?${string}` | `http://[::1]${string}` | `http://localhost#${string}` | `http://localhost/${string}` | `http://localhost:${string}` | `http://localhost?${string}` | `https://${string}` | undefined;
|
|
65
|
-
end_session_endpoint?: "http://127.0.0.1" | "http://localhost" | `http://127.0.0.1#${string}` | `http://127.0.0.1/${string}` | `http://127.0.0.1:${string}` | `http://127.0.0.1?${string}` | `http://[::1]${string}` | `http://localhost#${string}` | `http://localhost/${string}` | `http://localhost:${string}` | `http://localhost?${string}` | `https://${string}` | undefined;
|
|
66
|
-
registration_endpoint?: "http://127.0.0.1" | "http://localhost" | `http://127.0.0.1#${string}` | `http://127.0.0.1/${string}` | `http://127.0.0.1:${string}` | `http://127.0.0.1?${string}` | `http://[::1]${string}` | `http://localhost#${string}` | `http://localhost/${string}` | `http://localhost:${string}` | `http://localhost?${string}` | `https://${string}` | undefined;
|
|
67
|
-
dpop_signing_alg_values_supported?: string[] | undefined;
|
|
68
|
-
protected_resources?: ("http://127.0.0.1" | "http://localhost" | `http://127.0.0.1#${string}` | `http://127.0.0.1/${string}` | `http://127.0.0.1:${string}` | `http://127.0.0.1?${string}` | `http://[::1]${string}` | `http://localhost#${string}` | `http://localhost/${string}` | `http://localhost:${string}` | `http://localhost?${string}` | `https://${string}`)[] | undefined;
|
|
69
|
-
client_id_metadata_document_supported?: boolean | undefined;
|
|
70
|
-
prompt_values_supported?: ("consent" | "create" | "login" | "none" | "select_account")[] | undefined;
|
|
71
|
-
}>;
|
|
72
|
-
}
|
|
73
|
-
//# sourceMappingURL=oauth-resolver.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
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,sBAAs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AAE,gBAAgB,GACzB,OAAO,CAAC,gCAAgC,CAAC,CAS3C;IAEY,yBAAyB,CACpC,MAAM,EAAE,MAAM,GAAG,GAAG,EACpB,OAAO,CAAC,EAAE,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA8C3B;CACF"}
|
package/dist/oauth-resolver.js
DELETED
|
@@ -1,99 +0,0 @@
|
|
|
1
|
-
import { extractPdsUrl } from '@atproto/did';
|
|
2
|
-
import { oauthIssuerIdentifierSchema, } from '@atproto/oauth-types';
|
|
3
|
-
import { OAuthResolverError } from './oauth-resolver-error.js';
|
|
4
|
-
export class OAuthResolver {
|
|
5
|
-
constructor(identityResolver, protectedResourceMetadataResolver, authorizationServerMetadataResolver) {
|
|
6
|
-
this.identityResolver = identityResolver;
|
|
7
|
-
this.protectedResourceMetadataResolver = protectedResourceMetadataResolver;
|
|
8
|
-
this.authorizationServerMetadataResolver = authorizationServerMetadataResolver;
|
|
9
|
-
}
|
|
10
|
-
/**
|
|
11
|
-
* @param input - A handle, DID, PDS URL or Entryway URL
|
|
12
|
-
*/
|
|
13
|
-
async resolve(input, options) {
|
|
14
|
-
// Allow using an entryway, or PDS url, directly as login input (e.g.
|
|
15
|
-
// when the user forgot their handle, or when the handle does not
|
|
16
|
-
// resolve to a DID)
|
|
17
|
-
return /^https?:\/\//.test(input)
|
|
18
|
-
? this.resolveFromService(input, options)
|
|
19
|
-
: this.resolveFromIdentity(input, options);
|
|
20
|
-
}
|
|
21
|
-
/**
|
|
22
|
-
* @note this method can be used to verify if a particular uri supports OAuth
|
|
23
|
-
* based sign-in (for compatibility with legacy implementation).
|
|
24
|
-
*/
|
|
25
|
-
async resolveFromService(input, options) {
|
|
26
|
-
try {
|
|
27
|
-
// Assume first that input is a PDS URL (as required by ATPROTO)
|
|
28
|
-
const metadata = await this.getResourceServerMetadata(input, options);
|
|
29
|
-
return { metadata };
|
|
30
|
-
}
|
|
31
|
-
catch (err) {
|
|
32
|
-
if (!options?.signal?.aborted && err instanceof OAuthResolverError) {
|
|
33
|
-
try {
|
|
34
|
-
// Fallback to trying to fetch as an issuer (Entryway)
|
|
35
|
-
const result = oauthIssuerIdentifierSchema.safeParse(input);
|
|
36
|
-
if (result.success) {
|
|
37
|
-
const metadata = await this.getAuthorizationServerMetadata(result.data, options);
|
|
38
|
-
return { metadata };
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
catch {
|
|
42
|
-
// Fallback failed, throw original error
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
throw err;
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
async resolveFromIdentity(input, options) {
|
|
49
|
-
const identityInfo = await this.resolveIdentity(input, options);
|
|
50
|
-
options?.signal?.throwIfAborted();
|
|
51
|
-
const pds = extractPdsUrl(identityInfo.didDoc);
|
|
52
|
-
const metadata = await this.getResourceServerMetadata(pds, options);
|
|
53
|
-
return { identityInfo, metadata, pds };
|
|
54
|
-
}
|
|
55
|
-
async resolveIdentity(input, options) {
|
|
56
|
-
try {
|
|
57
|
-
return await this.identityResolver.resolve(input, options);
|
|
58
|
-
}
|
|
59
|
-
catch (cause) {
|
|
60
|
-
throw OAuthResolverError.from(cause, `Failed to resolve identity: ${input}`);
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
async getAuthorizationServerMetadata(issuer, options) {
|
|
64
|
-
try {
|
|
65
|
-
return await this.authorizationServerMetadataResolver.get(issuer, options);
|
|
66
|
-
}
|
|
67
|
-
catch (cause) {
|
|
68
|
-
throw OAuthResolverError.from(cause, `Failed to resolve OAuth server metadata for issuer: ${issuer}`);
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
async getResourceServerMetadata(pdsUrl, options) {
|
|
72
|
-
try {
|
|
73
|
-
const rsMetadata = await this.protectedResourceMetadataResolver.get(pdsUrl, options);
|
|
74
|
-
if (!rsMetadata) {
|
|
75
|
-
return this.getAuthorizationServerMetadata(pdsUrl, options);
|
|
76
|
-
}
|
|
77
|
-
// ATPROTO requires one, and only one, authorization server entry
|
|
78
|
-
if (rsMetadata.authorization_servers?.length !== 1) {
|
|
79
|
-
throw new OAuthResolverError(rsMetadata.authorization_servers?.length
|
|
80
|
-
? `Unable to determine authorization server for PDS: ${pdsUrl}`
|
|
81
|
-
: `No authorization servers found for PDS: ${pdsUrl}`);
|
|
82
|
-
}
|
|
83
|
-
const issuer = rsMetadata.authorization_servers[0];
|
|
84
|
-
options?.signal?.throwIfAborted();
|
|
85
|
-
const asMetadata = await this.getAuthorizationServerMetadata(issuer, options);
|
|
86
|
-
// https://www.rfc-editor.org/rfc/rfc9728.html#section-4
|
|
87
|
-
if (asMetadata.protected_resources) {
|
|
88
|
-
if (!asMetadata.protected_resources.includes(rsMetadata.resource)) {
|
|
89
|
-
throw new OAuthResolverError(`PDS "${pdsUrl}" not protected by issuer "${issuer}"`);
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
return asMetadata;
|
|
93
|
-
}
|
|
94
|
-
catch (cause) {
|
|
95
|
-
throw OAuthResolverError.from(cause, `Failed to resolve OAuth server metadata for resource: ${pdsUrl}`);
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
//# sourceMappingURL=oauth-resolver.js.map
|
|
@@ -1 +0,0 @@
|
|
|
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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,EAAE,MAAM;oBACtC,CAAC,CAAC,qDAAqD,MAAM,EAAE;oBAC/D,CAAC,CAAC,2CAA2C,MAAM,EAAE,CACxD,CAAA;YACH,CAAC;YAED,MAAM,MAAM,GAAG,UAAU,CAAC,qBAAsB,CAAC,CAAC,CAAE,CAAA;YAEpD,OAAO,EAAE,MAAM,EAAE,cAAc,EAAE,CAAA;YAEjC,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,8BAA8B,CAC1D,MAAM,EACN,OAAO,CACR,CAAA;YAED,wDAAwD;YACxD,IAAI,UAAU,CAAC,mBAAmB,EAAE,CAAC;gBACnC,IAAI,CAAC,UAAU,CAAC,mBAAmB,CAAC,QAAQ,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;oBAClE,MAAM,IAAI,kBAAkB,CAC1B,QAAQ,MAAM,8BAA8B,MAAM,GAAG,CACtD,CAAA;gBACH,CAAC;YACH,CAAC;YAED,OAAO,UAAU,CAAA;QACnB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,kBAAkB,CAAC,IAAI,CAC3B,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"]}
|