@atproto/oauth-client 0.7.8 → 0.7.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/dist/fetch-dpop.d.ts +3 -3
- package/dist/fetch-dpop.d.ts.map +1 -1
- package/dist/fetch-dpop.js +1 -1
- package/dist/fetch-dpop.js.map +1 -1
- package/dist/lock.d.ts +1 -1
- package/dist/lock.d.ts.map +1 -1
- package/dist/lock.js.map +1 -1
- package/dist/oauth-authorization-server-metadata-resolver.d.ts +3 -3
- package/dist/oauth-authorization-server-metadata-resolver.d.ts.map +1 -1
- package/dist/oauth-authorization-server-metadata-resolver.js.map +1 -1
- package/dist/oauth-client-auth.d.ts +5 -5
- package/dist/oauth-client-auth.d.ts.map +1 -1
- package/dist/oauth-client-auth.js.map +1 -1
- package/dist/oauth-client.d.ts +12 -12
- package/dist/oauth-client.d.ts.map +1 -1
- package/dist/oauth-client.js.map +1 -1
- package/dist/oauth-protected-resource-metadata-resolver.d.ts +3 -3
- package/dist/oauth-protected-resource-metadata-resolver.d.ts.map +1 -1
- package/dist/oauth-protected-resource-metadata-resolver.js.map +1 -1
- package/dist/oauth-resolver.d.ts +4 -4
- package/dist/oauth-resolver.d.ts.map +1 -1
- package/dist/oauth-resolver.js.map +1 -1
- package/dist/oauth-response-error.d.ts +1 -1
- package/dist/oauth-response-error.d.ts.map +1 -1
- package/dist/oauth-response-error.js.map +1 -1
- package/dist/oauth-server-agent.d.ts +9 -9
- package/dist/oauth-server-agent.d.ts.map +1 -1
- package/dist/oauth-server-agent.js +1 -1
- package/dist/oauth-server-agent.js.map +1 -1
- package/dist/oauth-server-factory.d.ts +9 -9
- package/dist/oauth-server-factory.d.ts.map +1 -1
- package/dist/oauth-server-factory.js.map +1 -1
- package/dist/oauth-session.d.ts +5 -5
- package/dist/oauth-session.d.ts.map +1 -1
- package/dist/oauth-session.js.map +1 -1
- package/dist/runtime-implementation.d.ts +2 -2
- package/dist/runtime-implementation.d.ts.map +1 -1
- package/dist/runtime-implementation.js.map +1 -1
- package/dist/runtime.d.ts +2 -2
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js.map +1 -1
- package/dist/session-getter.d.ts +7 -7
- package/dist/session-getter.d.ts.map +1 -1
- package/dist/session-getter.js.map +1 -1
- package/dist/state-store.d.ts +3 -3
- package/dist/state-store.d.ts.map +1 -1
- package/dist/state-store.js.map +1 -1
- package/dist/types.d.ts +3 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/validate-client-metadata.d.ts +3 -3
- package/dist/validate-client-metadata.d.ts.map +1 -1
- package/dist/validate-client-metadata.js.map +1 -1
- package/package.json +11 -11
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth-response-error.d.ts","sourceRoot":"","sources":["../src/oauth-response-error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAA;
|
|
1
|
+
{"version":3,"file":"oauth-response-error.d.ts","sourceRoot":"","sources":["../src/oauth-response-error.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAA;AAG/C,qBAAa,kBAAmB,SAAQ,KAAK;aAKzB,QAAQ,EAAE,QAAQ;aAClB,OAAO,EAAE,IAAI;IAL/B,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAA;IAElC,YACkB,QAAQ,EAAE,QAAQ,EAClB,OAAO,EAAE,IAAI,EAc9B;IAED,IAAI,MAAM,WAET;IAED,IAAI,OAAO,YAEV;CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth-response-error.js","sourceRoot":"","sources":["../src/oauth-response-error.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AAEpC,MAAM,OAAO,kBAAmB,SAAQ,KAAK;IAI3C,YACkB,QAAkB,EAClB,OAAa;QAE7B,MAAM,UAAU,GAAG,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAA;QACpE,MAAM,KAAK,GAAG,QAAQ,CAAC,UAAU,EAAE,CAAC,OAAO,CAAC,CAAC,CAAA;QAC7C,MAAM,gBAAgB,GAAG,QAAQ,CAAC,UAAU,EAAE,CAAC,mBAAmB,CAAC,CAAC,CAAA;QAEpE,MAAM,YAAY,GAAG,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,GAAG,CAAC,CAAC,CAAC,SAAS,CAAA;QACrD,MAAM,WAAW,GAAG,gBAAgB,CAAC,CAAC,CAAC,KAAK,gBAAgB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAA;QACnE,MAAM,OAAO,GAAG,SAAS,YAAY,SAAS,WAAW,EAAE,CAAA;QAE3D,KAAK,CAAC,OAAO,CAAC,CAAA;wBAXE,QAAQ;uBACR,OAAO;QAYvB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;QAClB,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,CAAA;IAC1C,CAAC;IAED,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAA;IAC7B,CAAC;IAED,IAAI,OAAO;QACT,OAAO,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAA;IAC9B,CAAC;CACF","sourcesContent":["import { Json } from '@atproto-labs/fetch'\nimport { ifString } from './util.js'\n\nexport class OAuthResponseError extends Error {\n readonly error?: string\n readonly errorDescription?: string\n\n constructor(\n public readonly response: Response,\n public readonly payload: Json,\n ) {\n const objPayload = typeof payload === 'object' ? payload : undefined\n const error = ifString(objPayload?.['error'])\n const errorDescription = ifString(objPayload?.['error_description'])\n\n const messageError = error ? `\"${error}\"` : 'unknown'\n const messageDesc = errorDescription ? `: ${errorDescription}` : ''\n const message = `OAuth ${messageError} error${messageDesc}`\n\n super(message)\n\n this.error = error\n this.errorDescription = errorDescription\n }\n\n get status() {\n return this.response.status\n }\n\n get headers() {\n return this.response.headers\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"oauth-response-error.js","sourceRoot":"","sources":["../src/oauth-response-error.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AAEpC,MAAM,OAAO,kBAAmB,SAAQ,KAAK;IAI3C,YACkB,QAAkB,EAClB,OAAa;QAE7B,MAAM,UAAU,GAAG,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAA;QACpE,MAAM,KAAK,GAAG,QAAQ,CAAC,UAAU,EAAE,CAAC,OAAO,CAAC,CAAC,CAAA;QAC7C,MAAM,gBAAgB,GAAG,QAAQ,CAAC,UAAU,EAAE,CAAC,mBAAmB,CAAC,CAAC,CAAA;QAEpE,MAAM,YAAY,GAAG,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,GAAG,CAAC,CAAC,CAAC,SAAS,CAAA;QACrD,MAAM,WAAW,GAAG,gBAAgB,CAAC,CAAC,CAAC,KAAK,gBAAgB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAA;QACnE,MAAM,OAAO,GAAG,SAAS,YAAY,SAAS,WAAW,EAAE,CAAA;QAE3D,KAAK,CAAC,OAAO,CAAC,CAAA;wBAXE,QAAQ;uBACR,OAAO;QAYvB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;QAClB,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,CAAA;IAC1C,CAAC;IAED,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAA;IAC7B,CAAC;IAED,IAAI,OAAO;QACT,OAAO,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAA;IAC9B,CAAC;CACF","sourcesContent":["import type { Json } from '@atproto-labs/fetch'\nimport { ifString } from './util.js'\n\nexport class OAuthResponseError extends Error {\n readonly error?: string\n readonly errorDescription?: string\n\n constructor(\n public readonly response: Response,\n public readonly payload: Json,\n ) {\n const objPayload = typeof payload === 'object' ? payload : undefined\n const error = ifString(objPayload?.['error'])\n const errorDescription = ifString(objPayload?.['error_description'])\n\n const messageError = error ? `\"${error}\"` : 'unknown'\n const messageDesc = errorDescription ? `: ${errorDescription}` : ''\n const message = `OAuth ${messageError} error${messageDesc}`\n\n super(message)\n\n this.error = error\n this.errorDescription = errorDescription\n }\n\n get status() {\n return this.response.status\n }\n\n get headers() {\n return this.response.headers\n }\n}\n"]}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import { AtprotoDid } from '@atproto/did';
|
|
2
|
-
import { Key, Keyset } from '@atproto/jwk';
|
|
3
|
-
import { AtprotoOAuthScope, AtprotoOAuthTokenResponse, OAuthAuthorizationRequestPar, OAuthAuthorizationServerMetadata, OAuthEndpointName, OAuthParResponse, OAuthRedirectUri, OAuthTokenRequest } from '@atproto/oauth-types';
|
|
4
|
-
import { Fetch, Json } from '@atproto-labs/fetch';
|
|
5
|
-
import { SimpleStore } from '@atproto-labs/simple-store';
|
|
6
|
-
import { ClientAuthMethod, ClientCredentialsFactory } from './oauth-client-auth.js';
|
|
7
|
-
import { OAuthResolver } from './oauth-resolver.js';
|
|
8
|
-
import { Runtime } from './runtime.js';
|
|
9
|
-
import { ClientMetadata } from './types.js';
|
|
1
|
+
import type { AtprotoDid } from '@atproto/did';
|
|
2
|
+
import type { Key, Keyset } from '@atproto/jwk';
|
|
3
|
+
import { type AtprotoOAuthScope, type AtprotoOAuthTokenResponse, type OAuthAuthorizationRequestPar, type OAuthAuthorizationServerMetadata, type OAuthEndpointName, type OAuthParResponse, type OAuthRedirectUri, type OAuthTokenRequest } from '@atproto/oauth-types';
|
|
4
|
+
import { type Fetch, type Json } from '@atproto-labs/fetch';
|
|
5
|
+
import type { SimpleStore } from '@atproto-labs/simple-store';
|
|
6
|
+
import { type ClientAuthMethod, type ClientCredentialsFactory } from './oauth-client-auth.js';
|
|
7
|
+
import type { OAuthResolver } from './oauth-resolver.js';
|
|
8
|
+
import type { Runtime } from './runtime.js';
|
|
9
|
+
import type { ClientMetadata } from './types.js';
|
|
10
10
|
export type { AtprotoOAuthScope, AtprotoOAuthTokenResponse };
|
|
11
11
|
export type TokenSet = {
|
|
12
12
|
iss: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth-server-agent.d.ts","sourceRoot":"","sources":["../src/oauth-server-agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;
|
|
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,MAAM,cAAc,CAAA;AAC/C,OAAO,EACL,KAAK,iBAAiB,EACtB,KAAK,yBAAyB,EAC9B,KAAK,4BAA4B,EACjC,KAAK,gCAAgC,EACrC,KAAK,iBAAiB,EACtB,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,EACrB,KAAK,iBAAiB,EAGvB,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EACL,KAAK,KAAK,EACV,KAAK,IAAI,EAGV,MAAM,qBAAqB,CAAA;AAC5B,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAA;AAG7D,OAAO,EACL,KAAK,gBAAgB,EACrB,KAAK,wBAAwB,EAE9B,MAAM,wBAAwB,CAAA;AAC/B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAExD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AAC3C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAGhD,YAAY,EAAE,iBAAiB,EAAE,yBAAyB,EAAE,CA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AAW,CAAC,EAAE,gBAAgB,GAC7B,OAAO,CAAC,QAAQ,CAAC,CAuCnB;IAEK,OAAO,CAAC,QAAQ,EAAE,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,CAqCnD;IAED;;;;;;;;;OASG;IACH,UAAgB,YAAY,CAAC,GAAG,EAAE,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,CAe7D;IAEK,OAAO,CAAC,QAAQ,SAAS,iBAAiB,EAC9C,QAAQ,EAAE,QAAQ,EAClB,OAAO,EAAE,QAAQ,SAAS,OAAO,GAC7B,iBAAiB,GACjB,QAAQ,SAAS,8BAA8B,GAC7C,4BAA4B,GAC5B,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC5B,OAAO,CACR,QAAQ,SAAS,OAAO,GACpB,yBAAyB,GACzB,QAAQ,SAAS,8BAA8B,GAC7C,gBAAgB,GAChB,IAAI,CACX,CAAA;CAoCF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { atprotoOAuthTokenResponseSchema, oauthParResponseSchema, } from '@atproto/oauth-types';
|
|
2
|
-
import { bindFetch, fetchJsonProcessor } from '@atproto-labs/fetch';
|
|
2
|
+
import { bindFetch, fetchJsonProcessor, } from '@atproto-labs/fetch';
|
|
3
3
|
import { TokenRefreshError } from './errors/token-refresh-error.js';
|
|
4
4
|
import { dpopFetchWrapper } from './fetch-dpop.js';
|
|
5
5
|
import { createClientCredentialsFactory, } from './oauth-client-auth.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth-server-agent.js","sourceRoot":"","sources":["../src/oauth-server-agent.ts"],"names":[],"mappings":"AAEA,OAAO,EASL,+BAA+B,EAC/B,sBAAsB,GACvB,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAAe,SAAS,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAA;AAEhF,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAA;AACnE,OAAO,EAAE,gBAAg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,IAAI,eAAe,CACxB,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC;SACpB,MAAM,CAAC,oBAAoB,CAAC;SAC5B,GAAG,CAAC,mBAAmB,CAAC,CAC5B,CAAC,QAAQ,EAAE,CAAA;AACd,CAAC;AAED,SAAS,oBAAoB,CAC3B,KAAwB;IAExB,OAAO,KAAK,CAAC,CAAC,CAAC,KAAK,SAAS,CAAA;AAC/B,CAAC;AAED,SAAS,mBAAmB,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 { AtprotoDid } from '@atproto/did'\nimport { Key, Keyset } from '@atproto/jwk'\nimport {\n AtprotoOAuthScope,\n AtprotoOAuthTokenResponse,\n OAuthAuthorizationRequestPar,\n OAuthAuthorizationServerMetadata,\n OAuthEndpointName,\n OAuthParResponse,\n OAuthRedirectUri,\n OAuthTokenRequest,\n atprotoOAuthTokenResponseSchema,\n oauthParResponseSchema,\n} from '@atproto/oauth-types'\nimport { Fetch, Json, bindFetch, fetchJsonProcessor } from '@atproto-labs/fetch'\nimport { SimpleStore } from '@atproto-labs/simple-store'\nimport { TokenRefreshError } from './errors/token-refresh-error.js'\nimport { dpopFetchWrapper } from './fetch-dpop.js'\nimport {\n ClientAuthMethod,\n ClientCredentialsFactory,\n createClientCredentialsFactory,\n} from './oauth-client-auth.js'\nimport { OAuthResolver } from './oauth-resolver.js'\nimport { OAuthResponseError } from './oauth-response-error.js'\nimport { Runtime } from './runtime.js'\nimport { ClientMetadata } from './types.js'\nimport { timeoutSignal } from './util.js'\n\nexport type { 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":"AAEA,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;AAE/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;0B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B,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 { 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,12 +1,12 @@
|
|
|
1
|
-
import { Key, Keyset } from '@atproto/jwk';
|
|
2
|
-
import { OAuthAuthorizationServerMetadata } from '@atproto/oauth-types';
|
|
3
|
-
import { Fetch } from '@atproto-labs/fetch';
|
|
4
|
-
import { GetCachedOptions } from './oauth-authorization-server-metadata-resolver.js';
|
|
5
|
-
import { ClientAuthMethod } from './oauth-client-auth.js';
|
|
6
|
-
import { OAuthResolver } from './oauth-resolver.js';
|
|
7
|
-
import { DpopNonceCache, OAuthServerAgent } from './oauth-server-agent.js';
|
|
8
|
-
import { Runtime } from './runtime.js';
|
|
9
|
-
import { ClientMetadata } from './types.js';
|
|
1
|
+
import type { Key, Keyset } from '@atproto/jwk';
|
|
2
|
+
import type { OAuthAuthorizationServerMetadata } from '@atproto/oauth-types';
|
|
3
|
+
import type { Fetch } from '@atproto-labs/fetch';
|
|
4
|
+
import type { GetCachedOptions } from './oauth-authorization-server-metadata-resolver.js';
|
|
5
|
+
import type { ClientAuthMethod } from './oauth-client-auth.js';
|
|
6
|
+
import type { OAuthResolver } from './oauth-resolver.js';
|
|
7
|
+
import { type DpopNonceCache, OAuthServerAgent } from './oauth-server-agent.js';
|
|
8
|
+
import type { Runtime } from './runtime.js';
|
|
9
|
+
import type { ClientMetadata } from './types.js';
|
|
10
10
|
export declare class OAuthServerFactory {
|
|
11
11
|
readonly clientMetadata: ClientMetadata;
|
|
12
12
|
readonly runtime: Runtime;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth-server-factory.d.ts","sourceRoot":"","sources":["../src/oauth-server-factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;
|
|
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,gCAAgC,EAAE,MAAM,sBAAsB,CAAA;AAC5E,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAA;AAChD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mDAAmD,CAAA;AACzF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AAC9D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AACxD,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":"AAMA,OAAO,
|
|
1
|
+
{"version":3,"file":"oauth-server-factory.js","sourceRoot":"","sources":["../src/oauth-server-factory.ts"],"names":[],"mappings":"AAMA,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 { OAuthAuthorizationServerMetadata } from '@atproto/oauth-types'\nimport type { Fetch } from '@atproto-labs/fetch'\nimport type { GetCachedOptions } from './oauth-authorization-server-metadata-resolver.js'\nimport type { ClientAuthMethod } from './oauth-client-auth.js'\nimport type { OAuthResolver } from './oauth-resolver.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/oauth-session.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { AtprotoDid } from '@atproto/did';
|
|
2
|
-
import { AtprotoOAuthScope, OAuthAuthorizationServerMetadata } from '@atproto/oauth-types';
|
|
3
|
-
import { Fetch } from '@atproto-labs/fetch';
|
|
4
|
-
import { OAuthServerAgent, TokenSet } from './oauth-server-agent.js';
|
|
5
|
-
import { SessionGetter } from './session-getter.js';
|
|
1
|
+
import type { AtprotoDid } from '@atproto/did';
|
|
2
|
+
import type { AtprotoOAuthScope, OAuthAuthorizationServerMetadata } from '@atproto/oauth-types';
|
|
3
|
+
import { type Fetch } from '@atproto-labs/fetch';
|
|
4
|
+
import type { OAuthServerAgent, TokenSet } from './oauth-server-agent.js';
|
|
5
|
+
import type { SessionGetter } from './session-getter.js';
|
|
6
6
|
export type { AtprotoDid, AtprotoOAuthScope };
|
|
7
7
|
export type TokenInfo = {
|
|
8
8
|
expiresAt?: Date;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth-session.d.ts","sourceRoot":"","sources":["../src/oauth-session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;
|
|
1
|
+
{"version":3,"file":"oauth-session.d.ts","sourceRoot":"","sources":["../src/oauth-session.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AAC9C,OAAO,KAAK,EACV,iBAAiB,EACjB,gCAAgC,EACjC,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAAE,KAAK,KAAK,EAAa,MAAM,qBAAqB,CAAA;AAI3D,OAAO,KAAK,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAA;AACzE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAMxD,YAAY,EAAE,UAAU,EAAE,iBAAiB,EAAE,CAAA;AAC7C,MAAM,MAAM,SAAS,GAAG;IACtB,SAAS,CAAC,EAAE,IAAI,CAAA;IAChB,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,KAAK,EAAE,iBAAiB,CAAA;IACxB,GAAG,EAAE,MAAM,CAAA;IACX,GAAG,EAAE,MAAM,CAAA;IACX,GAAG,EAAE,UAAU,CAAA;CAChB,CAAA;AAED,qBAAa,YAAY;aAIL,MAAM,EAAE,gBAAgB;aACxB,GAAG,EAAE,UAAU;IAC/B,OAAO,CAAC,QAAQ,CAAC,aAAa;IALhC,SAAS,CAAC,SAAS,EAAE,KAAK,CAAC,OAAO,CAAC,CAAA;IAEnC,YACkB,MAAM,EAAE,gBAAgB,EACxB,GAAG,EAAE,UAAU,EACd,aAAa,EAAE,aAAa,EAC7C,KAAK,GAAE,KAAwB,EAUhC;IAED,IAAI,GAAG,IAAI,UAAU,CAEpB;IAED,IAAI,cAAc,IAAI,QAAQ,CAAC,gCAAgC,CAAC,CAE/D;IAED;;;;;OAKG;IACH,UAAgB,WAAW,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAIxE;IAEK,YAAY,CAAC,OAAO,GAAE,OAAO,GAAG,MAAe,GAAG,OAAO,CAAC,SAAS,CAAC,CAiBzE;IAEK,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAU7B;IAEK,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,CAAC,CA0D1E;CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth-session.js","sourceRoot":"","sources":["../src/oauth-session.ts"],"names":[],"mappings":"AAKA,OAAO,
|
|
1
|
+
{"version":3,"file":"oauth-session.js","sourceRoot":"","sources":["../src/oauth-session.ts"],"names":[],"mappings":"AAKA,OAAO,EAAc,SAAS,EAAE,MAAM,qBAAqB,CAAA;AAC3D,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAA;AACnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAA;AACnE,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAA;AAIlD,MAAM,cAAc,GAAG,UAAU,CAAC,cAErB,CAAA;AAYb,MAAM,OAAO,YAAY;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AQ,CAAC,OAAO,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAA;IACxD,OAAO,CACL,OAAO,IAAI,IAAI;QACf,CAAC,OAAO,CAAC,UAAU,CAAC,SAAS,CAAC,IAAI,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;QAC9D,OAAO,CAAC,QAAQ,CAAC,uBAAuB,CAAC,CAC1C,CAAA;AACH,CAAC","sourcesContent":["import type { AtprotoDid } from '@atproto/did'\nimport type {\n AtprotoOAuthScope,\n OAuthAuthorizationServerMetadata,\n} from '@atproto/oauth-types'\nimport { type Fetch, bindFetch } from '@atproto-labs/fetch'\nimport { TokenInvalidError } from './errors/token-invalid-error.js'\nimport { TokenRevokedError } from './errors/token-revoked-error.js'\nimport { dpopFetchWrapper } from './fetch-dpop.js'\nimport type { OAuthServerAgent, TokenSet } from './oauth-server-agent.js'\nimport type { SessionGetter } from './session-getter.js'\n\nconst ReadableStream = globalThis.ReadableStream as\n | typeof globalThis.ReadableStream\n | undefined\n\nexport type { AtprotoDid, AtprotoOAuthScope }\nexport type TokenInfo = {\n expiresAt?: Date\n expired?: boolean\n scope: AtprotoOAuthScope\n iss: string\n aud: string\n sub: AtprotoDid\n}\n\nexport class OAuthSession {\n protected dpopFetch: Fetch<unknown>\n\n constructor(\n public readonly server: OAuthServerAgent,\n public readonly sub: AtprotoDid,\n private readonly sessionGetter: SessionGetter,\n fetch: Fetch = globalThis.fetch,\n ) {\n this.dpopFetch = dpopFetchWrapper<void>({\n fetch: bindFetch(fetch),\n key: server.dpopKey,\n supportedAlgs: server.serverMetadata.dpop_signing_alg_values_supported,\n sha256: async (v) => server.runtime.sha256(v),\n nonces: server.dpopNonces,\n isAuthServer: false,\n })\n }\n\n get did(): AtprotoDid {\n return this.sub\n }\n\n get serverMetadata(): Readonly<OAuthAuthorizationServerMetadata> {\n return this.server.serverMetadata\n }\n\n /**\n * @param refresh When `true`, the credentials will be refreshed even if they\n * are not expired. When `false`, the credentials will not be refreshed even\n * if they are expired. When `undefined`, the credentials will be refreshed\n * if, and only if, they are (about to be) expired. Defaults to `undefined`.\n */\n protected async getTokenSet(refresh: boolean | 'auto'): Promise<TokenSet> {\n const { tokenSet } = await this.sessionGetter.getSession(this.sub, refresh)\n\n return tokenSet\n }\n\n async getTokenInfo(refresh: boolean | 'auto' = 'auto'): Promise<TokenInfo> {\n const tokenSet = await this.getTokenSet(refresh)\n const expiresAt =\n tokenSet.expires_at == null ? undefined : new Date(tokenSet.expires_at)\n\n return {\n expiresAt,\n get expired() {\n return expiresAt == null\n ? undefined\n : expiresAt.getTime() < Date.now() - 5e3\n },\n scope: tokenSet.scope,\n iss: tokenSet.iss,\n aud: tokenSet.aud,\n sub: tokenSet.sub,\n }\n }\n\n async signOut(): Promise<void> {\n try {\n const tokenSet = await this.getTokenSet(false)\n await this.server.revoke(tokenSet.access_token)\n } finally {\n await this.sessionGetter.delStored(\n this.sub,\n new TokenRevokedError(this.sub),\n )\n }\n }\n\n async fetchHandler(pathname: string, init?: RequestInit): Promise<Response> {\n // This will try and refresh the token if it is known to be expired\n const tokenSet = await this.getTokenSet('auto')\n\n const initialUrl = new URL(pathname, tokenSet.aud satisfies string)\n const initialAuth = `${tokenSet.token_type} ${tokenSet.access_token}`\n\n const headers = new Headers(init?.headers)\n headers.set('Authorization', initialAuth)\n\n const initialResponse = await this.dpopFetch(initialUrl, {\n ...init,\n headers,\n })\n\n // If the token is not expired, we don't need to refresh it\n if (!isInvalidTokenResponse(initialResponse)) {\n return initialResponse\n }\n\n let tokenSetFresh: TokenSet\n try {\n // Force a refresh\n tokenSetFresh = await this.getTokenSet(true)\n } catch (err) {\n return initialResponse\n }\n\n // The stream was already consumed. We cannot retry the request. A solution\n // would be to tee() the input stream but that would bufferize the entire\n // stream in memory which can lead to memory starvation. Instead, we will\n // return the original response and let the calling code handle retries.\n if (ReadableStream && init?.body instanceof ReadableStream) {\n return initialResponse\n }\n\n const finalAuth = `${tokenSetFresh.token_type} ${tokenSetFresh.access_token}`\n const finalUrl = new URL(pathname, tokenSetFresh.aud)\n\n headers.set('Authorization', finalAuth)\n\n const finalResponse = await this.dpopFetch(finalUrl, { ...init, headers })\n\n // The token was successfully refreshed, but is still not accepted by the\n // resource server. This might be due to the resource server not accepting\n // credentials from the authorization server (e.g. because some migration\n // occurred). Any ways, there is no point in keeping the session.\n if (isInvalidTokenResponse(finalResponse)) {\n // @TODO Is there a \"softer\" way to handle this, e.g. by marking the\n // session as \"expired\" in the session store, allowing the user to trigger\n // a new login (using login_hint)?\n await this.sessionGetter.delStored(\n this.sub,\n new TokenInvalidError(this.sub),\n )\n }\n\n return finalResponse\n }\n}\n\n/**\n * @see {@link https://datatracker.ietf.org/doc/html/rfc6750#section-3}\n * @see {@link https://datatracker.ietf.org/doc/html/rfc9449#name-resource-server-provided-no}\n */\nfunction isInvalidTokenResponse(response: Response) {\n if (response.status !== 401) return false\n const wwwAuth = response.headers.get('WWW-Authenticate')\n return (\n wwwAuth != null &&\n (wwwAuth.startsWith('Bearer ') || wwwAuth.startsWith('DPoP ')) &&\n wwwAuth.includes('error=\"invalid_token\"')\n )\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Key } from '@atproto/jwk';
|
|
2
|
-
import { Awaitable } from './util.js';
|
|
1
|
+
import type { Key } from '@atproto/jwk';
|
|
2
|
+
import type { Awaitable } from './util.js';
|
|
3
3
|
export type { Key };
|
|
4
4
|
export type RuntimeKeyFactory = (algs: string[]) => Key | PromiseLike<Key>;
|
|
5
5
|
export type RuntimeRandomValues = (length: number) => Awaitable<Uint8Array>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-implementation.d.ts","sourceRoot":"","sources":["../src/runtime-implementation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,cAAc,CAAA;
|
|
1
|
+
{"version":3,"file":"runtime-implementation.d.ts","sourceRoot":"","sources":["../src/runtime-implementation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,cAAc,CAAA;AACvC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,WAAW,CAAA;AAE1C,YAAY,EAAE,GAAG,EAAE,CAAA;AACnB,MAAM,MAAM,iBAAiB,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,GAAG,GAAG,WAAW,CAAC,GAAG,CAAC,CAAA;AAE1E,MAAM,MAAM,mBAAmB,GAAG,CAAC,MAAM,EAAE,MAAM,KAAK,SAAS,CAAC,UAAU,CAAC,CAAA;AAE3E,MAAM,MAAM,eAAe,GAAG;IAAE,IAAI,EAAE,QAAQ,GAAG,QAAQ,GAAG,QAAQ,CAAA;CAAE,CAAA;AACtE,MAAM,MAAM,aAAa,GAAG,CAC1B,IAAI,EAAE,UAAU,CAAC,WAAW,CAAC,EAC7B,GAAG,EAAE,eAAe,KACjB,SAAS,CAAC,UAAU,CAAC,CAAA;AAE1B,MAAM,MAAM,WAAW,GAAG,CAAC,CAAC,EAC1B,IAAI,EAAE,MAAM,EACZ,EAAE,EAAE,MAAM,SAAS,CAAC,CAAC,CAAC,KACnB,SAAS,CAAC,CAAC,CAAC,CAAA;AAEjB,MAAM,WAAW,qBAAqB;IACpC,SAAS,EAAE,iBAAiB,CAAA;IAC5B,eAAe,EAAE,mBAAmB,CAAA;IACpC,MAAM,EAAE,aAAa,CAAA;IACrB,WAAW,CAAC,EAAE,WAAW,CAAA;CAC1B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-implementation.js","sourceRoot":"","sources":["../src/runtime-implementation.ts"],"names":[],"mappings":"","sourcesContent":["import { Key } from '@atproto/jwk'\nimport { Awaitable } from './util.js'\n\nexport type { Key }\nexport type RuntimeKeyFactory = (algs: string[]) => Key | PromiseLike<Key>\n\nexport type RuntimeRandomValues = (length: number) => Awaitable<Uint8Array>\n\nexport type DigestAlgorithm = { name: 'sha256' | 'sha384' | 'sha512' }\nexport type RuntimeDigest = (\n data: Uint8Array<ArrayBuffer>,\n alg: DigestAlgorithm,\n) => Awaitable<Uint8Array>\n\nexport type RuntimeLock = <T>(\n name: string,\n fn: () => Awaitable<T>,\n) => Awaitable<T>\n\nexport interface RuntimeImplementation {\n createKey: RuntimeKeyFactory\n getRandomValues: RuntimeRandomValues\n digest: RuntimeDigest\n requestLock?: RuntimeLock\n}\n"]}
|
|
1
|
+
{"version":3,"file":"runtime-implementation.js","sourceRoot":"","sources":["../src/runtime-implementation.ts"],"names":[],"mappings":"","sourcesContent":["import type { Key } from '@atproto/jwk'\nimport type { Awaitable } from './util.js'\n\nexport type { Key }\nexport type RuntimeKeyFactory = (algs: string[]) => Key | PromiseLike<Key>\n\nexport type RuntimeRandomValues = (length: number) => Awaitable<Uint8Array>\n\nexport type DigestAlgorithm = { name: 'sha256' | 'sha384' | 'sha512' }\nexport type RuntimeDigest = (\n data: Uint8Array<ArrayBuffer>,\n alg: DigestAlgorithm,\n) => Awaitable<Uint8Array>\n\nexport type RuntimeLock = <T>(\n name: string,\n fn: () => Awaitable<T>,\n) => Awaitable<T>\n\nexport interface RuntimeImplementation {\n createKey: RuntimeKeyFactory\n getRandomValues: RuntimeRandomValues\n digest: RuntimeDigest\n requestLock?: RuntimeLock\n}\n"]}
|
package/dist/runtime.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Key } from '@atproto/jwk';
|
|
2
|
-
import { RuntimeImplementation, RuntimeLock } from './runtime-implementation.js';
|
|
1
|
+
import type { Key } from '@atproto/jwk';
|
|
2
|
+
import type { RuntimeImplementation, RuntimeLock } from './runtime-implementation.js';
|
|
3
3
|
export declare class Runtime {
|
|
4
4
|
protected implementation: RuntimeImplementation;
|
|
5
5
|
readonly hasImplementationLock: boolean;
|
package/dist/runtime.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,GAAG,EAAE,MAAM,cAAc,CAAA;
|
|
1
|
+
{"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,cAAc,CAAA;AAEvC,OAAO,KAAK,EACV,qBAAqB,EACrB,WAAW,EACZ,MAAM,6BAA6B,CAAA;AAEpC,qBAAa,OAAO;IAIN,SAAS,CAAC,cAAc,EAAE,qBAAqB;IAH3D,QAAQ,CAAC,qBAAqB,EAAE,OAAO,CAAA;IACvC,QAAQ,CAAC,SAAS,EAAE,WAAW,CAAA;IAE/B,YAAsB,cAAc,EAAE,qBAAqB,EAQ1D;IAEY,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC,CAGrD;IAEY,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAIjD;IAEY,aAAa,CAAC,MAAM,SAAK,GAAG,OAAO,CAAC,MAAM,CAAC,CAGvD;IAEY,YAAY,CAAC,UAAU,CAAC,EAAE,MAAM;;;gBAKjC,MAAM;OAEjB;IAEY,sBAAsB,CAAC,GAAG,KAAA,mBAItC;IAED;;;;;;OAMG;IACH,UAAgB,gBAAgB,CAAC,UAAU,SAAK,mBAM/C;CACF"}
|
package/dist/runtime.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAA;AAErD,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAA;
|
|
1
|
+
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAA;AAErD,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAA;AAM5C,MAAM,OAA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CAAC;IAED,iDAAiD;IACjD,OAAO,CAAC,CAAA;AACV,CAAC","sourcesContent":["import { base64url } from 'multiformats/bases/base64'\nimport type { Key } from '@atproto/jwk'\nimport { requestLocalLock } from './lock.js'\nimport type {\n RuntimeImplementation,\n RuntimeLock,\n} from './runtime-implementation.js'\n\nexport class Runtime {\n readonly hasImplementationLock: boolean\n readonly usingLock: RuntimeLock\n\n constructor(protected implementation: RuntimeImplementation) {\n const { requestLock } = implementation\n\n this.hasImplementationLock = requestLock != null\n this.usingLock =\n requestLock?.bind(implementation) ||\n // Falling back to a local lock\n requestLocalLock\n }\n\n public async generateKey(algs: string[]): Promise<Key> {\n const algsSorted = Array.from(algs).sort(compareAlgos)\n return this.implementation.createKey(algsSorted)\n }\n\n public async sha256(text: string): Promise<string> {\n const bytes = new TextEncoder().encode(text)\n const digest = await this.implementation.digest(bytes, { name: 'sha256' })\n return base64url.baseEncode(digest)\n }\n\n public async generateNonce(length = 16): Promise<string> {\n const bytes = await this.implementation.getRandomValues(length)\n return base64url.baseEncode(bytes)\n }\n\n public async generatePKCE(byteLength?: number) {\n const verifier = await this.generateVerifier(byteLength)\n return {\n verifier,\n challenge: await this.sha256(verifier),\n method: 'S256' as const,\n }\n }\n\n public async calculateJwkThumbprint(jwk) {\n const components = extractJktComponents(jwk)\n const data = JSON.stringify(components)\n return this.sha256(data)\n }\n\n /**\n * @see {@link https://datatracker.ietf.org/doc/html/rfc7636#section-4.1}\n * @note It is RECOMMENDED that the output of a suitable random number generator\n * be used to create a 32-octet sequence. The octet sequence is then\n * base64url-encoded to produce a 43-octet URL safe string to use as the code\n * verifier.\n */\n protected async generateVerifier(byteLength = 32) {\n if (byteLength < 32 || byteLength > 96) {\n throw new TypeError('Invalid code_verifier length')\n }\n const bytes = await this.implementation.getRandomValues(byteLength)\n return base64url.baseEncode(bytes)\n }\n}\n\nfunction extractJktComponents(jwk) {\n const get = (field) => {\n const value = jwk[field]\n if (typeof value !== 'string' || !value) {\n throw new TypeError(`\"${field}\" Parameter missing or invalid`)\n }\n return value\n }\n\n switch (jwk.kty) {\n case 'EC':\n return { crv: get('crv'), kty: get('kty'), x: get('x'), y: get('y') }\n case 'OKP':\n return { crv: get('crv'), kty: get('kty'), x: get('x') }\n case 'RSA':\n return { e: get('e'), kty: get('kty'), n: get('n') }\n case 'oct':\n return { k: get('k'), kty: get('kty') }\n default:\n throw new TypeError('\"kty\" (Key Type) Parameter missing or unsupported')\n }\n}\n\n/**\n * 256K > ES (256 > 384 > 512) > PS (256 > 384 > 512) > RS (256 > 384 > 512) > other (in original order)\n */\nfunction compareAlgos(a: string, b: string): number {\n if (a === 'ES256K') return -1\n if (b === 'ES256K') return 1\n\n for (const prefix of ['ES', 'PS', 'RS']) {\n if (a.startsWith(prefix)) {\n if (b.startsWith(prefix)) {\n const aLen = parseInt(a.slice(2, 5))\n const bLen = parseInt(b.slice(2, 5))\n\n // Prefer shorter key lengths\n return aLen - bLen\n }\n return -1\n } else if (b.startsWith(prefix)) {\n return 1\n }\n }\n\n // Don't know how to compare, keep original order\n return 0\n}\n"]}
|
package/dist/session-getter.d.ts
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import { AtprotoDid } from '@atproto/did';
|
|
2
|
-
import { Key } from '@atproto/jwk';
|
|
3
|
-
import { CachedGetter, GetCachedOptions, GetOptions, SimpleStore } from '@atproto-labs/simple-store';
|
|
1
|
+
import type { AtprotoDid } from '@atproto/did';
|
|
2
|
+
import type { Key } from '@atproto/jwk';
|
|
3
|
+
import { CachedGetter, type GetCachedOptions, type GetOptions, type SimpleStore } from '@atproto-labs/simple-store';
|
|
4
4
|
import { AuthMethodUnsatisfiableError } from './errors/auth-method-unsatisfiable-error.js';
|
|
5
5
|
import { TokenInvalidError } from './errors/token-invalid-error.js';
|
|
6
6
|
import { TokenRefreshError } from './errors/token-refresh-error.js';
|
|
7
7
|
import { TokenRevokedError } from './errors/token-revoked-error.js';
|
|
8
|
-
import { ClientAuthMethod } from './oauth-client-auth.js';
|
|
9
|
-
import { TokenSet } from './oauth-server-agent.js';
|
|
10
|
-
import { OAuthServerFactory } from './oauth-server-factory.js';
|
|
11
|
-
import { Runtime } from './runtime.js';
|
|
8
|
+
import type { ClientAuthMethod } from './oauth-client-auth.js';
|
|
9
|
+
import type { TokenSet } from './oauth-server-agent.js';
|
|
10
|
+
import type { OAuthServerFactory } from './oauth-server-factory.js';
|
|
11
|
+
import type { Runtime } from './runtime.js';
|
|
12
12
|
export type Session = {
|
|
13
13
|
dpopKey: Key;
|
|
14
14
|
authMethod: ClientAuthMethod;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-getter.d.ts","sourceRoot":"","sources":["../src/session-getter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;
|
|
1
|
+
{"version":3,"file":"session-getter.d.ts","sourceRoot":"","sources":["../src/session-getter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AAC9C,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,cAAc,CAAA;AACvC,OAAO,EACL,YAAY,EACZ,KAAK,gBAAgB,EACrB,KAAK,UAAU,EACf,KAAK,WAAW,EACjB,MAAM,4BAA4B,CAAA;AACnC,OAAO,EAAE,4BAA4B,EAAE,MAAM,6CAA6C,CAAA;AAC1F,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAA;AACnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAA;AACnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAA;AACnE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AAE9D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAA;AACvD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAA;AACnE,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cA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,GAAG,KAAK,OAAO,CAAC,QAAQ,CAAC,GAAG,EAAE,CAAC;YACjC,uDAAuD;YACvD,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAA;QAC9D,CAAC;QAED,OAAO,OAAO,CAAA;IAChB,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,UAAU,CAAC,GAAe,EAAE,OAAO,GAAqB,MAAM;QAClE,OAAO,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE;YACnB,OAAO,EAAE,OAAO,KAAK,IAAI;YACzB,UAAU,EAAE,OAAO,KAAK,KAAK;SAC9B,CAAC,CAAA;IACJ,CAAC;CACF","sourcesContent":["import { AtprotoDid } from '@atproto/did'\nimport { Key } from '@atproto/jwk'\nimport {\n CachedGetter,\n GetCachedOptions,\n GetOptions,\n SimpleStore,\n} from '@atproto-labs/simple-store'\nimport { AuthMethodUnsatisfiableError } from './errors/auth-method-unsatisfiable-error.js'\nimport { TokenInvalidError } from './errors/token-invalid-error.js'\nimport { TokenRefreshError } from './errors/token-refresh-error.js'\nimport { TokenRevokedError } from './errors/token-revoked-error.js'\nimport { ClientAuthMethod } from './oauth-client-auth.js'\nimport { OAuthResponseError } from './oauth-response-error.js'\nimport { TokenSet } from './oauth-server-agent.js'\nimport { OAuthServerFactory } from './oauth-server-factory.js'\nimport { Runtime } from './runtime.js'\nimport { combineSignals, timeoutSignal } from './util.js'\n\nexport type Session = {\n dpopKey: Key\n authMethod: ClientAuthMethod\n tokenSet: TokenSet\n}\n\nexport type SessionStore = SimpleStore<string, Session>\n\nexport type SessionHooks = {\n onUpdate?: (sub: AtprotoDid, session: Session) => void\n onDelete?: (\n sub: AtprotoDid,\n cause: TokenRefreshError | TokenRevokedError | TokenInvalidError | unknown,\n ) => void\n}\n\nexport function isExpectedSessionError(err: unknown) {\n return (\n err instanceof TokenRefreshError ||\n err instanceof TokenRevokedError ||\n err instanceof TokenInvalidError ||\n err instanceof AuthMethodUnsatisfiableError ||\n // The stored session is invalid (e.g. missing properties) and cannot\n // be used properly\n err instanceof TypeError\n )\n}\n\n/**\n * There are several advantages to wrapping the sessionStore in a (single)\n * CachedGetter, the main of which is that the cached getter will ensure that at\n * most one fresh call is ever being made. Another advantage, is that it\n * contains the logic for reading from the cache which, if the cache is based on\n * localStorage/indexedDB, will sync across multiple tabs (for a given sub).\n */\nexport class SessionGetter extends CachedGetter<AtprotoDid, Session> {\n constructor(\n sessionStore: SessionStore,\n serverFactory: OAuthServerFactory,\n private readonly runtime: Runtime,\n private readonly hooks: SessionHooks = {},\n ) {\n super(\n async (sub, { signal }, storedSession) => {\n // There needs to be a previous session to be able to refresh. If\n // storedSession is undefined, it means that the store does not contain\n // a session for the given sub.\n if (storedSession === undefined) {\n // Because the session is not in the store, this.delStored() method\n // will not be called by the CachedGetter class (because there is\n // nothing to delete). This would typically happen if there is no\n // synchronization mechanism between instances of this class. Let's\n // make sure an event is dispatched here if this occurs.\n const msg = 'The session was deleted by another process'\n const cause = new TokenRefreshError(sub, msg)\n await hooks.onDelete?.call(null, sub, cause)\n throw cause\n }\n\n // @NOTE Throwing a TokenRefreshError (or any other error class defined\n // in the deleteOnError options) will result in this.delStored() being\n // called.\n\n const { dpopKey, authMethod, tokenSet } = storedSession\n\n if (sub !== tokenSet.sub) {\n // Fool-proofing (e.g. against invalid session storage)\n throw new TokenRefreshError(sub, 'Stored session sub mismatch')\n }\n\n if (!tokenSet.refresh_token) {\n throw new TokenRefreshError(sub, 'No refresh token available')\n }\n\n const server = await serverFactory.fromIssuer(\n tokenSet.iss,\n authMethod,\n dpopKey,\n )\n\n // Because refresh tokens can only be used once, we must not use the\n // \"signal\" to abort the refresh, or throw any abort error beyond this\n // point. Any thrown error beyond this point will prevent the\n // TokenGetter from obtaining, and storing, the new token set,\n // effectively rendering the currently saved session unusable.\n signal?.throwIfAborted()\n\n try {\n const newTokenSet = await server.refresh(tokenSet)\n\n if (sub !== newTokenSet.sub) {\n // The server returned another sub. Was the tokenSet manipulated?\n throw new TokenRefreshError(sub, 'Token set sub mismatch')\n }\n\n return {\n dpopKey,\n tokenSet: newTokenSet,\n authMethod: server.authMethod,\n }\n } catch (cause) {\n // Since refresh tokens can only be used once, we might run into\n // concurrency issues if multiple instances (e.g. browser tabs) are\n // trying to refresh the same token simultaneously. The chances of\n // this happening when multiple instances are started simultaneously\n // is reduced by randomizing the expiry time (see isStale() below).\n // The best solution is to use a mutex/lock to ensure that only one\n // instance is refreshing the token at a time (runtime.usingLock) but\n // that is not always possible. Let's try to recover from concurrency\n // issues, or force the session to be deleted by throwing a\n // TokenRefreshError.\n if (\n cause instanceof OAuthResponseError &&\n cause.status === 400 &&\n cause.error === 'invalid_grant'\n ) {\n // In case there is no lock implementation in the runtime, we will\n // wait for a short time to give the other concurrent instances a\n // chance to finish their refreshing of the token. If a concurrent\n // refresh did occur, we will pretend that this one succeeded.\n if (!runtime.hasImplementationLock) {\n await new Promise((r) => setTimeout(r, 1000))\n\n const stored = await this.getStored(sub)\n if (stored === undefined) {\n // A concurrent refresh occurred and caused the session to be\n // deleted (for a reason we can't know at this point).\n\n // Using a distinct error message mainly for debugging\n // purposes. Also, throwing a TokenRefreshError to trigger\n // deletion through the deleteOnError callback.\n const msg = 'The session was deleted by another process'\n throw new TokenRefreshError(sub, msg, { cause })\n } else if (\n stored.tokenSet.access_token !== tokenSet.access_token ||\n stored.tokenSet.refresh_token !== tokenSet.refresh_token\n ) {\n // A concurrent refresh occurred. Pretend this one succeeded.\n return stored\n } else {\n // There were no concurrent refresh. The token is (likely)\n // simply no longer valid.\n }\n }\n\n // Make sure the session gets deleted from the store\n const msg = cause.errorDescription ?? 'The session was revoked'\n throw new TokenRefreshError(sub, msg, { cause })\n }\n\n throw cause\n }\n },\n sessionStore,\n {\n isStale: (sub, { tokenSet }) => {\n return (\n tokenSet.expires_at != null &&\n new Date(tokenSet.expires_at).getTime() <\n Date.now() +\n // Add some lee way to ensure the token is not expired when it\n // reaches the server.\n 10e3 +\n // Add some randomness to reduce the chances of multiple\n // instances trying to refresh the token at the same.\n 30e3 * Math.random()\n )\n },\n onStoreError: async (err, sub, { tokenSet, dpopKey, authMethod }) => {\n // If the token data cannot be stored, let's revoke it\n try {\n const server = await serverFactory.fromIssuer(\n tokenSet.iss,\n authMethod,\n dpopKey,\n )\n await server.revoke(tokenSet.refresh_token ?? tokenSet.access_token)\n } catch {\n // At least we tried...\n }\n\n // Attempt to delete the session from the store. Note that this might\n // fail if the store is not available, which is fine.\n try {\n await this.delStored(sub, err)\n } catch {\n // Ignore (better to propagate the original storage error)\n }\n\n throw err\n },\n deleteOnError: isExpectedSessionError,\n },\n )\n }\n\n override async getStored(\n sub: AtprotoDid,\n options?: GetOptions,\n ): Promise<Session | undefined> {\n return super.getStored(sub, options)\n }\n\n override async setStored(sub: AtprotoDid, session: Session) {\n // Prevent tampering with the stored value\n if (sub !== session.tokenSet.sub) {\n throw new TypeError('Token set does not match the expected sub')\n }\n await super.setStored(sub, session)\n await this.hooks.onUpdate?.call(null, sub, session)\n }\n\n override async delStored(sub: AtprotoDid, cause?: unknown): Promise<void> {\n await super.delStored(sub, cause)\n await this.hooks.onDelete?.call(null, sub, cause)\n }\n\n /**\n * @deprecated Use {@link getSession} instead\n * @internal (not really deprecated)\n */\n override async get(\n sub: AtprotoDid,\n options?: GetCachedOptions,\n ): Promise<Session> {\n const session = await this.runtime.usingLock(\n `@atproto-oauth-client-${sub}`,\n async () => {\n // Make sure, even if there is no signal in the options, that the\n // request will be cancelled after at most 30 seconds.\n const signal = timeoutSignal(30e3)\n\n using abortController = combineSignals([options?.signal, signal])\n\n return await super.get(sub, {\n ...options,\n signal: abortController.signal,\n })\n },\n )\n\n if (sub !== session.tokenSet.sub) {\n // Fool-proofing (e.g. against invalid session storage)\n throw new Error('Token set does not match the expected sub')\n }\n\n return session\n }\n\n /**\n * @param refresh When `true`, the credentials will be refreshed even if they\n * are not expired. When `false`, the credentials will not be refreshed even\n * if they are expired. When `undefined`, the credentials will be refreshed\n * if, and only if, they are (about to be) expired. Defaults to `undefined`.\n */\n async getSession(sub: AtprotoDid, refresh: boolean | 'auto' = 'auto') {\n return this.get(sub, {\n noCache: refresh === true,\n allowStale: refresh === false,\n })\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"session-getter.js","sourceRoot":"","sources":["../src/session-getter.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,OAAO,EACL,YAAY,GAIb,MAAM,4BAA4B,CAAA;AACnC,OAAO,EAAE,4BAA4B,EAAE,MAAM,6CAA6C,CAAA;AAC1F,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAA;AACnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAA;AACnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAA;AAEnE,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAA;AAI9D,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,WAAW,CAAA;AAkBzD,MAAM,UAAU,sBAAsB,CAAC,GAAY;IACjD,OAAO,CACL,GAAG,YAAY,iBAAiB;QAChC,GAAG,YAAY,iBAAiB;QAChC,GAAG,YAAY,iBAAiB;QAChC,GAAG,YAAY,4BAA4B;QAC3C,qEAAqE;QACrE,mBAAmB;QACnB,GAAG,YAAY,SAAS,CACzB,CAAA;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,OAAO,aAAc,SAAQ,YAAiC;IAClE,YACE,YAA0B,EAC1B,aAAiC,EAChB,OAAgB,EAChB,KAAK,GAAiB,EAAE;QAEzC,KAAK,CACH,KAAK,EAAE,GAAG,EAAE,EAAE,MAAM,EAAE,EAAE,aAAa,EAAE,EAAE;YACvC,iEAAiE;YACjE,uEAAuE;YACvE,+BAA+B;YAC/B,IAAI,aAAa,KAAK,SAAS,EAAE,CAAC;gBAChC,mEAAmE;gBACnE,iEAAiE;gBACjE,iEAAiE;gBACjE,mEAAmE;g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,CAAA;QAED,IAAI,GAAG,KAAK,OAAO,CAAC,QAAQ,CAAC,GAAG,EAAE,CAAC;YACjC,uDAAuD;YACvD,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAA;QAC9D,CAAC;QAED,OAAO,OAAO,CAAA;IAChB,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,UAAU,CAAC,GAAe,EAAE,OAAO,GAAqB,MAAM;QAClE,OAAO,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE;YACnB,OAAO,EAAE,OAAO,KAAK,IAAI;YACzB,UAAU,EAAE,OAAO,KAAK,KAAK;SAC9B,CAAC,CAAA;IACJ,CAAC;CACF","sourcesContent":["import type { AtprotoDid } from '@atproto/did'\nimport type { Key } from '@atproto/jwk'\nimport {\n CachedGetter,\n type GetCachedOptions,\n type GetOptions,\n type SimpleStore,\n} from '@atproto-labs/simple-store'\nimport { AuthMethodUnsatisfiableError } from './errors/auth-method-unsatisfiable-error.js'\nimport { TokenInvalidError } from './errors/token-invalid-error.js'\nimport { TokenRefreshError } from './errors/token-refresh-error.js'\nimport { TokenRevokedError } from './errors/token-revoked-error.js'\nimport type { ClientAuthMethod } from './oauth-client-auth.js'\nimport { OAuthResponseError } from './oauth-response-error.js'\nimport type { TokenSet } from './oauth-server-agent.js'\nimport type { OAuthServerFactory } from './oauth-server-factory.js'\nimport type { Runtime } from './runtime.js'\nimport { combineSignals, timeoutSignal } from './util.js'\n\nexport type Session = {\n dpopKey: Key\n authMethod: ClientAuthMethod\n tokenSet: TokenSet\n}\n\nexport type SessionStore = SimpleStore<string, Session>\n\nexport type SessionHooks = {\n onUpdate?: (sub: AtprotoDid, session: Session) => void\n onDelete?: (\n sub: AtprotoDid,\n cause: TokenRefreshError | TokenRevokedError | TokenInvalidError | unknown,\n ) => void\n}\n\nexport function isExpectedSessionError(err: unknown) {\n return (\n err instanceof TokenRefreshError ||\n err instanceof TokenRevokedError ||\n err instanceof TokenInvalidError ||\n err instanceof AuthMethodUnsatisfiableError ||\n // The stored session is invalid (e.g. missing properties) and cannot\n // be used properly\n err instanceof TypeError\n )\n}\n\n/**\n * There are several advantages to wrapping the sessionStore in a (single)\n * CachedGetter, the main of which is that the cached getter will ensure that at\n * most one fresh call is ever being made. Another advantage, is that it\n * contains the logic for reading from the cache which, if the cache is based on\n * localStorage/indexedDB, will sync across multiple tabs (for a given sub).\n */\nexport class SessionGetter extends CachedGetter<AtprotoDid, Session> {\n constructor(\n sessionStore: SessionStore,\n serverFactory: OAuthServerFactory,\n private readonly runtime: Runtime,\n private readonly hooks: SessionHooks = {},\n ) {\n super(\n async (sub, { signal }, storedSession) => {\n // There needs to be a previous session to be able to refresh. If\n // storedSession is undefined, it means that the store does not contain\n // a session for the given sub.\n if (storedSession === undefined) {\n // Because the session is not in the store, this.delStored() method\n // will not be called by the CachedGetter class (because there is\n // nothing to delete). This would typically happen if there is no\n // synchronization mechanism between instances of this class. Let's\n // make sure an event is dispatched here if this occurs.\n const msg = 'The session was deleted by another process'\n const cause = new TokenRefreshError(sub, msg)\n await hooks.onDelete?.call(null, sub, cause)\n throw cause\n }\n\n // @NOTE Throwing a TokenRefreshError (or any other error class defined\n // in the deleteOnError options) will result in this.delStored() being\n // called.\n\n const { dpopKey, authMethod, tokenSet } = storedSession\n\n if (sub !== tokenSet.sub) {\n // Fool-proofing (e.g. against invalid session storage)\n throw new TokenRefreshError(sub, 'Stored session sub mismatch')\n }\n\n if (!tokenSet.refresh_token) {\n throw new TokenRefreshError(sub, 'No refresh token available')\n }\n\n const server = await serverFactory.fromIssuer(\n tokenSet.iss,\n authMethod,\n dpopKey,\n )\n\n // Because refresh tokens can only be used once, we must not use the\n // \"signal\" to abort the refresh, or throw any abort error beyond this\n // point. Any thrown error beyond this point will prevent the\n // TokenGetter from obtaining, and storing, the new token set,\n // effectively rendering the currently saved session unusable.\n signal?.throwIfAborted()\n\n try {\n const newTokenSet = await server.refresh(tokenSet)\n\n if (sub !== newTokenSet.sub) {\n // The server returned another sub. Was the tokenSet manipulated?\n throw new TokenRefreshError(sub, 'Token set sub mismatch')\n }\n\n return {\n dpopKey,\n tokenSet: newTokenSet,\n authMethod: server.authMethod,\n }\n } catch (cause) {\n // Since refresh tokens can only be used once, we might run into\n // concurrency issues if multiple instances (e.g. browser tabs) are\n // trying to refresh the same token simultaneously. The chances of\n // this happening when multiple instances are started simultaneously\n // is reduced by randomizing the expiry time (see isStale() below).\n // The best solution is to use a mutex/lock to ensure that only one\n // instance is refreshing the token at a time (runtime.usingLock) but\n // that is not always possible. Let's try to recover from concurrency\n // issues, or force the session to be deleted by throwing a\n // TokenRefreshError.\n if (\n cause instanceof OAuthResponseError &&\n cause.status === 400 &&\n cause.error === 'invalid_grant'\n ) {\n // In case there is no lock implementation in the runtime, we will\n // wait for a short time to give the other concurrent instances a\n // chance to finish their refreshing of the token. If a concurrent\n // refresh did occur, we will pretend that this one succeeded.\n if (!runtime.hasImplementationLock) {\n await new Promise((r) => setTimeout(r, 1000))\n\n const stored = await this.getStored(sub)\n if (stored === undefined) {\n // A concurrent refresh occurred and caused the session to be\n // deleted (for a reason we can't know at this point).\n\n // Using a distinct error message mainly for debugging\n // purposes. Also, throwing a TokenRefreshError to trigger\n // deletion through the deleteOnError callback.\n const msg = 'The session was deleted by another process'\n throw new TokenRefreshError(sub, msg, { cause })\n } else if (\n stored.tokenSet.access_token !== tokenSet.access_token ||\n stored.tokenSet.refresh_token !== tokenSet.refresh_token\n ) {\n // A concurrent refresh occurred. Pretend this one succeeded.\n return stored\n } else {\n // There were no concurrent refresh. The token is (likely)\n // simply no longer valid.\n }\n }\n\n // Make sure the session gets deleted from the store\n const msg = cause.errorDescription ?? 'The session was revoked'\n throw new TokenRefreshError(sub, msg, { cause })\n }\n\n throw cause\n }\n },\n sessionStore,\n {\n isStale: (sub, { tokenSet }) => {\n return (\n tokenSet.expires_at != null &&\n new Date(tokenSet.expires_at).getTime() <\n Date.now() +\n // Add some lee way to ensure the token is not expired when it\n // reaches the server.\n 10e3 +\n // Add some randomness to reduce the chances of multiple\n // instances trying to refresh the token at the same.\n 30e3 * Math.random()\n )\n },\n onStoreError: async (err, sub, { tokenSet, dpopKey, authMethod }) => {\n // If the token data cannot be stored, let's revoke it\n try {\n const server = await serverFactory.fromIssuer(\n tokenSet.iss,\n authMethod,\n dpopKey,\n )\n await server.revoke(tokenSet.refresh_token ?? tokenSet.access_token)\n } catch {\n // At least we tried...\n }\n\n // Attempt to delete the session from the store. Note that this might\n // fail if the store is not available, which is fine.\n try {\n await this.delStored(sub, err)\n } catch {\n // Ignore (better to propagate the original storage error)\n }\n\n throw err\n },\n deleteOnError: isExpectedSessionError,\n },\n )\n }\n\n override async getStored(\n sub: AtprotoDid,\n options?: GetOptions,\n ): Promise<Session | undefined> {\n return super.getStored(sub, options)\n }\n\n override async setStored(sub: AtprotoDid, session: Session) {\n // Prevent tampering with the stored value\n if (sub !== session.tokenSet.sub) {\n throw new TypeError('Token set does not match the expected sub')\n }\n await super.setStored(sub, session)\n await this.hooks.onUpdate?.call(null, sub, session)\n }\n\n override async delStored(sub: AtprotoDid, cause?: unknown): Promise<void> {\n await super.delStored(sub, cause)\n await this.hooks.onDelete?.call(null, sub, cause)\n }\n\n /**\n * @deprecated Use {@link getSession} instead\n * @internal (not really deprecated)\n */\n override async get(\n sub: AtprotoDid,\n options?: GetCachedOptions,\n ): Promise<Session> {\n const session = await this.runtime.usingLock(\n `@atproto-oauth-client-${sub}`,\n async () => {\n // Make sure, even if there is no signal in the options, that the\n // request will be cancelled after at most 30 seconds.\n const signal = timeoutSignal(30e3)\n\n using abortController = combineSignals([options?.signal, signal])\n\n return await super.get(sub, {\n ...options,\n signal: abortController.signal,\n })\n },\n )\n\n if (sub !== session.tokenSet.sub) {\n // Fool-proofing (e.g. against invalid session storage)\n throw new Error('Token set does not match the expected sub')\n }\n\n return session\n }\n\n /**\n * @param refresh When `true`, the credentials will be refreshed even if they\n * are not expired. When `false`, the credentials will not be refreshed even\n * if they are expired. When `undefined`, the credentials will be refreshed\n * if, and only if, they are (about to be) expired. Defaults to `undefined`.\n */\n async getSession(sub: AtprotoDid, refresh: boolean | 'auto' = 'auto') {\n return this.get(sub, {\n noCache: refresh === true,\n allowStale: refresh === false,\n })\n }\n}\n"]}
|
package/dist/state-store.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { Key } from '@atproto/jwk';
|
|
2
|
-
import { SimpleStore } from '@atproto-labs/simple-store';
|
|
3
|
-
import { ClientAuthMethod } from './oauth-client-auth.js';
|
|
1
|
+
import type { Key } from '@atproto/jwk';
|
|
2
|
+
import type { SimpleStore } from '@atproto-labs/simple-store';
|
|
3
|
+
import type { ClientAuthMethod } from './oauth-client-auth.js';
|
|
4
4
|
export type InternalStateData = {
|
|
5
5
|
iss: string;
|
|
6
6
|
dpopKey: Key;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"state-store.d.ts","sourceRoot":"","sources":["../src/state-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,cAAc,CAAA;
|
|
1
|
+
{"version":3,"file":"state-store.d.ts","sourceRoot":"","sources":["../src/state-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,cAAc,CAAA;AACvC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAA;AAC7D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AAE9D,MAAM,MAAM,iBAAiB,GAAG;IAC9B,GAAG,EAAE,MAAM,CAAA;IACX,OAAO,EAAE,GAAG,CAAA;IACZ,UAAU,EAAE,gBAAgB,CAAA;IAC5B,QAAQ,EAAE,MAAM,CAAA;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB,CAAA;AAED;;;;;;;;;;GAUG;AACH,MAAM,MAAM,UAAU,GAAG,WAAW,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAA"}
|
package/dist/state-store.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"state-store.js","sourceRoot":"","sources":["../src/state-store.ts"],"names":[],"mappings":"","sourcesContent":["import { Key } from '@atproto/jwk'\nimport { SimpleStore } from '@atproto-labs/simple-store'\nimport { ClientAuthMethod } from './oauth-client-auth.js'\n\nexport type InternalStateData = {\n iss: string\n dpopKey: Key\n authMethod: ClientAuthMethod\n verifier: string\n appState?: string\n}\n\n/**\n * A store pending oauth authorization flows. The key is the \"state\" parameter\n * used in the authorization request, and the value is an object containing the\n * necessary information to complete the flow once the user is redirected back\n * to the client.\n *\n * @note The data stored in this store is typically short-lived. It should be\n * automatically cleared after a certain period of time (e.g. 1 hour) to prevent\n * the store from growing indefinitely. It is up to the implementation to\n * implement this cleanup mechanism.\n */\nexport type StateStore = SimpleStore<string, InternalStateData>\n"]}
|
|
1
|
+
{"version":3,"file":"state-store.js","sourceRoot":"","sources":["../src/state-store.ts"],"names":[],"mappings":"","sourcesContent":["import type { Key } from '@atproto/jwk'\nimport type { SimpleStore } from '@atproto-labs/simple-store'\nimport type { ClientAuthMethod } from './oauth-client-auth.js'\n\nexport type InternalStateData = {\n iss: string\n dpopKey: Key\n authMethod: ClientAuthMethod\n verifier: string\n appState?: string\n}\n\n/**\n * A store pending oauth authorization flows. The key is the \"state\" parameter\n * used in the authorization request, and the value is an object containing the\n * necessary information to complete the flow once the user is redirected back\n * to the client.\n *\n * @note The data stored in this store is typically short-lived. It should be\n * automatically cleared after a certain period of time (e.g. 1 hour) to prevent\n * the store from growing indefinitely. It is up to the implementation to\n * implement this cleanup mechanism.\n */\nexport type StateStore = SimpleStore<string, InternalStateData>\n"]}
|
package/dist/types.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { TypeOf, z } from 'zod';
|
|
2
|
-
import { OAuthAuthorizationRequestParameters } from '@atproto/oauth-types';
|
|
3
|
-
import { Simplify } from './util.js';
|
|
1
|
+
import { type TypeOf, z } from 'zod';
|
|
2
|
+
import { type OAuthAuthorizationRequestParameters } from '@atproto/oauth-types';
|
|
3
|
+
import type { Simplify } from './util.js';
|
|
4
4
|
export type AuthorizeOptions = Simplify<Omit<OAuthAuthorizationRequestParameters, 'client_id' | 'response_mode' | 'response_type' | 'login_hint' | 'code_challenge' | 'code_challenge_method'> & {
|
|
5
5
|
signal?: AbortSignal;
|
|
6
6
|
}>;
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AACpC,OAAO,EACL,KAAK,mCAAmC,EAIzC,MAAM,sBAAsB,CAAA;AAC7B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AAMzC,MAAM,MAAM,gBAAgB,GAAG,QAAQ,CACrC,IAAI,CACF,mCAAmC,EACjC,WAAW,GACX,eAAe,GACf,eAAe,GACf,YAAY,GACZ,gBAAgB,GAChB,uBAAuB,CAC1B,GAAG;IACF,MAAM,CAAC,EAAE,WAAW,CAAA;CACrB,CACF,CAAA;AAED,MAAM,MAAM,eAAe,GAAG,QAAQ,CACpC,OAAO,CAAC,IAAI,CAAC,mCAAmC,EAAE,cAAc,CAAC,CAAC,CACnE,CAAA;AAED,eAAO,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAK/B,CAAA;AAEF,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC,OAAO,oBAAoB,CAAC,CAAA"}
|
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,CAAC,EAAE,MAAM,KAAK,CAAA;AACpC,OAAO,EAEL,+BAA+B,EAC/B,2BAA2B,EAC3B,yBAAyB,GAC1B,MAAM,sBAAsB,CAAA;AAyB7B,MAAM,CAAC,MAAM,oBAAoB,GAAG,yBAAyB,CAAC,MAAM,CAAC;IACnE,SAAS,EAAE,CAAC,CAAC,KAAK,CAAC;QACjB,+BAA+B;QAC/B,2BAA2B;KAC5B,CAAC;CACH,CAAC,CAAA","sourcesContent":["import { type TypeOf, z } from 'zod'\nimport {\n type OAuthAuthorizationRequestParameters,\n oauthClientIdDiscoverableSchema,\n oauthClientIdLoopbackSchema,\n oauthClientMetadataSchema,\n} from '@atproto/oauth-types'\nimport type { Simplify } from './util.js'\n\n// Note: These types are not prefixed with `OAuth` because they are not specific\n// to OAuth. They are specific to this packages. OAuth specific types are in\n// `@atproto/oauth-types`.\n\nexport type AuthorizeOptions = Simplify<\n Omit<\n OAuthAuthorizationRequestParameters,\n | 'client_id'\n | 'response_mode'\n | 'response_type'\n | 'login_hint'\n | 'code_challenge'\n | 'code_challenge_method'\n > & {\n signal?: AbortSignal\n }\n>\n\nexport type CallbackOptions = Simplify<\n Partial<Pick<OAuthAuthorizationRequestParameters, 'redirect_uri'>>\n>\n\nexport const clientMetadataSchema = oauthClientMetadataSchema.extend({\n client_id: z.union([\n oauthClientIdDiscoverableSchema,\n oauthClientIdLoopbackSchema,\n ]),\n})\n\nexport type ClientMetadata = TypeOf<typeof clientMetadataSchema>\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Keyset } from '@atproto/jwk';
|
|
2
|
-
import { OAuthClientMetadataInput } from '@atproto/oauth-types';
|
|
3
|
-
import { ClientMetadata } from './types.js';
|
|
1
|
+
import type { Keyset } from '@atproto/jwk';
|
|
2
|
+
import { type OAuthClientMetadataInput } from '@atproto/oauth-types';
|
|
3
|
+
import { type ClientMetadata } from './types.js';
|
|
4
4
|
export declare function validateClientMetadata(input: OAuthClientMetadataInput, keyset?: Keyset): ClientMetadata;
|
|
5
5
|
//# sourceMappingURL=validate-client-metadata.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validate-client-metadata.d.ts","sourceRoot":"","sources":["../src/validate-client-metadata.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;
|
|
1
|
+
{"version":3,"file":"validate-client-metadata.d.ts","sourceRoot":"","sources":["../src/validate-client-metadata.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AAC1C,OAAO,EACL,KAAK,wBAAwB,EAG9B,MAAM,sBAAsB,CAAA;AAE7B,OAAO,EAAE,KAAK,cAAc,EAAwB,MAAM,YAAY,CAAA;AAEtE,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,wBAAwB,EAC/B,MAAM,CAAC,EAAE,MAAM,GACd,cAAc,CAuGhB"}
|