@atproto/oauth-provider 0.25.6 → 0.27.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 +79 -0
- package/dist/account/account-manager.d.ts +5 -11
- package/dist/account/account-manager.d.ts.map +1 -1
- package/dist/account/account-manager.js +17 -59
- package/dist/account/account-manager.js.map +1 -1
- package/dist/account/account-store.d.ts +2 -8
- package/dist/account/account-store.d.ts.map +1 -1
- package/dist/account/account-store.js.map +1 -1
- package/dist/errors/captcha-rejected-error.d.ts +12 -0
- package/dist/errors/captcha-rejected-error.d.ts.map +1 -0
- package/dist/errors/captcha-rejected-error.js +18 -0
- package/dist/errors/captcha-rejected-error.js.map +1 -0
- package/dist/errors/captcha-required-error.d.ts +9 -0
- package/dist/errors/captcha-required-error.d.ts.map +1 -0
- package/dist/errors/captcha-required-error.js +11 -0
- package/dist/errors/captcha-required-error.js.map +1 -0
- package/dist/errors/oauth-error.d.ts +1 -0
- package/dist/errors/oauth-error.d.ts.map +1 -1
- package/dist/errors/oauth-error.js +3 -0
- package/dist/errors/oauth-error.js.map +1 -1
- package/dist/errors/rate-limit-exceeded-error.d.ts +12 -0
- package/dist/errors/rate-limit-exceeded-error.d.ts.map +1 -0
- package/dist/errors/rate-limit-exceeded-error.js +14 -0
- package/dist/errors/rate-limit-exceeded-error.js.map +1 -0
- package/dist/errors/www-authenticate-error.d.ts +1 -0
- package/dist/errors/www-authenticate-error.d.ts.map +1 -1
- package/dist/errors/www-authenticate-error.js +4 -0
- package/dist/errors/www-authenticate-error.js.map +1 -1
- package/dist/hcaptcha/hcaptcha-client-tokens.d.ts +7 -0
- package/dist/hcaptcha/hcaptcha-client-tokens.d.ts.map +1 -0
- package/dist/hcaptcha/hcaptcha-client-tokens.js +2 -0
- package/dist/hcaptcha/hcaptcha-client-tokens.js.map +1 -0
- package/dist/hcaptcha/hcaptcha-manager.d.ts +23 -0
- package/dist/hcaptcha/hcaptcha-manager.d.ts.map +1 -0
- package/dist/hcaptcha/hcaptcha-manager.js +83 -0
- package/dist/hcaptcha/hcaptcha-manager.js.map +1 -0
- package/dist/hcaptcha/hcaptcha-verify-data.d.ts +15 -0
- package/dist/hcaptcha/hcaptcha-verify-data.d.ts.map +1 -0
- package/dist/hcaptcha/hcaptcha-verify-data.js +2 -0
- package/dist/hcaptcha/hcaptcha-verify-data.js.map +1 -0
- package/dist/lib/hcaptcha.d.ts +5 -11
- package/dist/lib/hcaptcha.d.ts.map +1 -1
- package/dist/lib/hcaptcha.js +12 -20
- package/dist/lib/hcaptcha.js.map +1 -1
- package/dist/lib/http/response.d.ts +1 -1
- package/dist/lib/http/response.d.ts.map +1 -1
- package/dist/lib/http/response.js +15 -17
- package/dist/lib/http/response.js.map +1 -1
- package/dist/lib/identifier.d.ts +3 -0
- package/dist/lib/identifier.d.ts.map +1 -0
- package/dist/lib/identifier.js +4 -0
- package/dist/lib/identifier.js.map +1 -0
- package/dist/lib/redis.d.ts.map +1 -1
- package/dist/lib/redis.js +7 -1
- package/dist/lib/redis.js.map +1 -1
- package/dist/oauth-errors.d.ts +3 -0
- package/dist/oauth-errors.d.ts.map +1 -1
- package/dist/oauth-errors.js +3 -0
- package/dist/oauth-errors.js.map +1 -1
- package/dist/oauth-hooks.d.ts +16 -14
- package/dist/oauth-hooks.d.ts.map +1 -1
- package/dist/oauth-hooks.js.map +1 -1
- package/dist/oauth-provider.d.ts +26 -7
- package/dist/oauth-provider.d.ts.map +1 -1
- package/dist/oauth-provider.js +28 -48
- package/dist/oauth-provider.js.map +1 -1
- package/dist/rate-limit/rate-limit-manager.d.ts +39 -0
- package/dist/rate-limit/rate-limit-manager.d.ts.map +1 -0
- package/dist/rate-limit/rate-limit-manager.js +99 -0
- package/dist/rate-limit/rate-limit-manager.js.map +1 -0
- package/dist/rate-limit/rate-limit-policies.d.ts +108 -0
- package/dist/rate-limit/rate-limit-policies.d.ts.map +1 -0
- package/dist/rate-limit/rate-limit-policies.js +90 -0
- package/dist/rate-limit/rate-limit-policies.js.map +1 -0
- package/dist/rate-limit/rate-limiter.d.ts +36 -0
- package/dist/rate-limit/rate-limiter.d.ts.map +1 -0
- package/dist/rate-limit/rate-limiter.js +2 -0
- package/dist/rate-limit/rate-limiter.js.map +1 -0
- package/dist/router/assets/send-error-page.d.ts.map +1 -1
- package/dist/router/assets/send-error-page.js +3 -2
- package/dist/router/assets/send-error-page.js.map +1 -1
- package/dist/router/create-api-middleware.d.ts.map +1 -1
- package/dist/router/create-api-middleware.js +72 -15
- package/dist/router/create-api-middleware.js.map +1 -1
- package/dist/router/create-authorization-page-middleware.d.ts.map +1 -1
- package/dist/router/create-authorization-page-middleware.js +18 -17
- package/dist/router/create-authorization-page-middleware.js.map +1 -1
- package/dist/router/create-oauth-middleware.d.ts.map +1 -1
- package/dist/router/create-oauth-middleware.js +9 -8
- package/dist/router/create-oauth-middleware.js.map +1 -1
- package/dist/types/email.d.ts +2 -1
- package/dist/types/email.d.ts.map +1 -1
- package/dist/types/email.js.map +1 -1
- package/dist/types/indentifier.d.ts +2 -3
- package/dist/types/indentifier.d.ts.map +1 -1
- package/dist/types/indentifier.js.map +1 -1
- package/package.json +17 -17
- package/dist/account/sign-in-data.d.ts +0 -22
- package/dist/account/sign-in-data.d.ts.map +0 -1
- package/dist/account/sign-in-data.js +0 -15
- package/dist/account/sign-in-data.js.map +0 -1
- package/dist/account/sign-up-input.d.ts +0 -28
- package/dist/account/sign-up-input.d.ts.map +0 -1
- package/dist/account/sign-up-input.js +0 -19
- package/dist/account/sign-up-input.js.map +0 -1
package/dist/oauth-provider.js
CHANGED
|
@@ -22,6 +22,7 @@ import { InvalidDpopProofError } from './errors/invalid-dpop-proof-error.js';
|
|
|
22
22
|
import { InvalidGrantError } from './errors/invalid-grant-error.js';
|
|
23
23
|
import { InvalidRequestError } from './errors/invalid-request-error.js';
|
|
24
24
|
import { LoginRequiredError } from './errors/login-required-error.js';
|
|
25
|
+
import { HCaptchaManager } from './hcaptcha/hcaptcha-manager.js';
|
|
25
26
|
import { LexiconManager } from './lexicon/lexicon-manager.js';
|
|
26
27
|
import { asLexiconStore } from './lexicon/lexicon-store.js';
|
|
27
28
|
import { dateToRelativeSeconds } from './lib/util/date.js';
|
|
@@ -30,6 +31,8 @@ import { isOlderThan } from './lib/util/time.js';
|
|
|
30
31
|
import { buildMetadata, } from './metadata/build-metadata.js';
|
|
31
32
|
import { AUTHENTICATION_MAX_AGE, TOKEN_MAX_AGE } from './oauth-constants.js';
|
|
32
33
|
import { OAuthVerifier, } from './oauth-verifier.js';
|
|
34
|
+
import { RateLimitManager } from './rate-limit/rate-limit-manager.js';
|
|
35
|
+
import { DEFAULT_RATE_LIMIT_POLICIES, authenticatedClientKey, identifierIpKey, identifierKey, ipKey, publicClientIpKey, } from './rate-limit/rate-limit-policies.js';
|
|
33
36
|
import { ifReplayStore } from './replay/replay-store.js';
|
|
34
37
|
import { codeSchema } from './request/code.js';
|
|
35
38
|
import { RequestManager } from './request/request-manager.js';
|
|
@@ -45,11 +48,11 @@ export { safeFetchWrap } from '@atproto-labs/fetch-node';
|
|
|
45
48
|
export { Keyset } from '@atproto/jwk';
|
|
46
49
|
export { JoseKey } from '@atproto/jwk-jose';
|
|
47
50
|
export { LexResolver, LexResolverError } from '@atproto/lex-resolver';
|
|
48
|
-
export { AccessTokenMode };
|
|
51
|
+
export { AccessTokenMode, DEFAULT_RATE_LIMIT_POLICIES, authenticatedClientKey, identifierIpKey, identifierKey, ipKey, publicClientIpKey, };
|
|
49
52
|
export class OAuthProvider extends OAuthVerifier {
|
|
50
53
|
constructor({
|
|
51
54
|
// OAuthProviderConfig
|
|
52
|
-
authenticationMaxAge = AUTHENTICATION_MAX_AGE, tokenMaxAge = TOKEN_MAX_AGE, accessTokenMode = AccessTokenMode.stateless, metadata, loopbackMetadata = atprotoLoopbackClientMetadata,
|
|
55
|
+
authenticationMaxAge = AUTHENTICATION_MAX_AGE, tokenMaxAge = TOKEN_MAX_AGE, accessTokenMode = AccessTokenMode.stateless, metadata, loopbackMetadata = atprotoLoopbackClientMetadata, rateLimits,
|
|
53
56
|
// Services
|
|
54
57
|
fetch: unsafeFetch = globalThis.fetch, // Inherited from options
|
|
55
58
|
safeFetch = safeFetchWrap({ fetch: unsafeFetch }), lexResolver = new LexResolver({ fetch: safeFetch }),
|
|
@@ -94,6 +97,8 @@ export class OAuthProvider extends OAuthVerifier {
|
|
|
94
97
|
secure: !this.issuer.startsWith('http:'),
|
|
95
98
|
},
|
|
96
99
|
});
|
|
100
|
+
this.hcaptchaManager = new HCaptchaManager(this.issuer, this.hooks, this.customization.hcaptcha);
|
|
101
|
+
this.rateLimitManager = new RateLimitManager(this.hcaptchaManager, rateLimits);
|
|
97
102
|
this.accountManager = new AccountManager(this.issuer, accountStore, this.hooks, createOAuthResolver({
|
|
98
103
|
handleResolver: createHandleResolverNode({ ...rest, safeFetch }),
|
|
99
104
|
didResolver: rest.didResolver,
|
|
@@ -182,13 +187,19 @@ export class OAuthProvider extends OAuthVerifier {
|
|
|
182
187
|
/**
|
|
183
188
|
* @see {@link https://datatracker.ietf.org/doc/html/rfc9126}
|
|
184
189
|
*/
|
|
185
|
-
async pushedAuthorizationRequest(credentials, authorizationRequest, dpopProof) {
|
|
190
|
+
async pushedAuthorizationRequest(credentials, authorizationRequest, dpopProof, deviceMetadata) {
|
|
186
191
|
try {
|
|
187
192
|
const { client, clientAuth } = await this.authenticateClient(credentials, dpopProof,
|
|
188
193
|
// Allow missing DPoP header for PAR requests as rfc9449 allows it
|
|
189
194
|
// (though the dpop_jkt parameter must be present in that case, see
|
|
190
195
|
// check bellow).
|
|
191
196
|
{ allowMissingDpopProof: true });
|
|
197
|
+
await this.rateLimitManager.consume('pushed-authorization-request', {
|
|
198
|
+
kind: 'client',
|
|
199
|
+
deviceMetadata,
|
|
200
|
+
client,
|
|
201
|
+
clientAuth,
|
|
202
|
+
});
|
|
192
203
|
const parameters = 'request' in authorizationRequest // Handle JAR
|
|
193
204
|
? await this.decodeJAR(client, authorizationRequest)
|
|
194
205
|
: authorizationRequest;
|
|
@@ -231,50 +242,20 @@ export class OAuthProvider extends OAuthVerifier {
|
|
|
231
242
|
throw err;
|
|
232
243
|
}
|
|
233
244
|
}
|
|
234
|
-
async processAuthorizationRequest(client, deviceId, query) {
|
|
235
|
-
// PAR
|
|
236
|
-
if ('request_uri' in query) {
|
|
237
|
-
const requestUri = parseRequestUri(query.request_uri, {
|
|
238
|
-
path: ['query', 'request_uri'],
|
|
239
|
-
});
|
|
240
|
-
return this.requestManager.get(requestUri, deviceId, client.id);
|
|
241
|
-
}
|
|
242
|
-
// JAR
|
|
243
|
-
if ('request' in query) {
|
|
244
|
-
// @NOTE Since JAR are signed with the client's private key, a JAR *could*
|
|
245
|
-
// technically be used to authenticate the client when requests are
|
|
246
|
-
// created without PAR (i.e. created on the fly by the authorize
|
|
247
|
-
// endpoint). This implementation actually used to support this
|
|
248
|
-
// (un-spec'd) behavior. That support was removed:
|
|
249
|
-
// - Because it was not actually used
|
|
250
|
-
// - Because it was not part of any standard
|
|
251
|
-
// - Because it makes extending the client authentication mechanism more
|
|
252
|
-
// complex since any extension would not only need to affect the
|
|
253
|
-
// "private_key_jwt" auth method but also the JAR "request" object.
|
|
254
|
-
const parameters = await this.decodeJAR(client, query);
|
|
255
|
-
return this.requestManager.createAuthorizationRequest(client, null, parameters, deviceId);
|
|
256
|
-
}
|
|
257
|
-
// "Regular" authorization request (created on the fly by directing the user
|
|
258
|
-
// to the authorization endpoint with all the parameters in the url).
|
|
259
|
-
return this.requestManager.createAuthorizationRequest(client, null, query, deviceId);
|
|
260
|
-
}
|
|
261
245
|
/**
|
|
246
|
+
* Only requests created through
|
|
247
|
+
* {@link OAuthProvider.pushedAuthorizationRequest PAR} are accepted.
|
|
248
|
+
*
|
|
262
249
|
* @see {@link https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-11#section-4.1.1}
|
|
250
|
+
* @see {@link https://datatracker.ietf.org/doc/html/rfc9126#section-4}
|
|
263
251
|
*/
|
|
264
252
|
async authorize(query, { deviceId, deviceMetadata }) {
|
|
265
253
|
const { issuer } = this;
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
throw AuthorizationError.from(query, err);
|
|
272
|
-
}
|
|
273
|
-
: null;
|
|
274
|
-
const client = await this.clientManager
|
|
275
|
-
.getClient(query.client_id)
|
|
276
|
-
.catch(throwAuthorizationError);
|
|
277
|
-
const { parameters, requestUri } = await this.processAuthorizationRequest(client, deviceId, query).catch(throwAuthorizationError);
|
|
254
|
+
const client = await this.clientManager.getClient(query.client_id);
|
|
255
|
+
const requestUri = parseRequestUri(query.request_uri, {
|
|
256
|
+
path: ['query', 'request_uri'],
|
|
257
|
+
});
|
|
258
|
+
const { parameters } = await this.requestManager.get(requestUri, deviceId, client.id);
|
|
278
259
|
try {
|
|
279
260
|
const sessions = (await this.accountManager.listDeviceAccounts(deviceId)).map((deviceAccount) => ({
|
|
280
261
|
account: deviceAccount.account,
|
|
@@ -404,12 +385,11 @@ export class OAuthProvider extends OAuthVerifier {
|
|
|
404
385
|
}
|
|
405
386
|
}
|
|
406
387
|
if (!initial.clientAuth) {
|
|
407
|
-
//
|
|
408
|
-
//
|
|
409
|
-
//
|
|
410
|
-
//
|
|
411
|
-
//
|
|
412
|
-
// clientAuth).
|
|
388
|
+
// Sessions whose authorization request was not pushed (PAR) were not
|
|
389
|
+
// authenticated when the request was created. Since the token exchange
|
|
390
|
+
// currently taking place *is* authenticated (`clientAuth`), we allow
|
|
391
|
+
// "upgrading" the authentication method (the token created will be bound
|
|
392
|
+
// to the current clientAuth).
|
|
413
393
|
return;
|
|
414
394
|
}
|
|
415
395
|
switch (initial.clientAuth.method) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth-provider.js","sourceRoot":"","sources":["../src/oauth-provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAG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K,eAAe,CAAC,SAAS,EAAE,CAAC;YACvD,wEAAwE;YACxE,uEAAuE;YACvE,uEAAuE;YACvE,WAAW;YAEX,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,YAAY,CAAC,eAAe,CACzD,SAAS,EACT,YAAY,CACb,CAAA;YAED,MAAM,CAAC,MAAM,CAAC,YAAY,EAAE,WAAW,CAAC,CAAA;QAC1C,CAAC;QAED,OAAO,YAAY,CAAA;IACrB,CAAC;CACF;AAED,SAAS,WAAW,CAElB,EAAE,OAAO,EAAwB;IAEjC,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAA;IAC5B,IAAI,CAAC,IAAI;QAAE,OAAO,KAAK,CAAA;IAEvB,OAAO,OAAO,CAAC,GAAG,KAAK,IAAI,IAAI,OAAO,CAAC,MAAM,KAAK,IAAI,CAAA;AACxD,CAAC;AAED,SAAS,gBAAgB,CAAC,EAAE,OAAO,EAAwB;IACzD,OAAO,CAAC,OAAO,CAAC,WAAW,CAAA;AAC7B,CAAC","sourcesContent":["import { createHash } from 'node:crypto'\nimport type { Redis, RedisOptions } from 'ioredis'\nimport type { Jwks } from '@atproto/jwk'\nimport { LexResolver } from '@atproto/lex-resolver'\nimport type { Account } from '@atproto/oauth-provider-api'\nimport { createOAuthResolver } from '@atproto/oauth-resolver'\nimport {\n CLIENT_ASSERTION_TYPE_JWT_BEARER,\n type OAuthAccessToken,\n type OAuthAuthorizationCodeGrantTokenRequest,\n type OAuthAuthorizationRequestJar,\n type OAuthAuthorizationRequestPar,\n type OAuthAuthorizationRequestParameters,\n type OAuthAuthorizationRequestQuery,\n type OAuthAuthorizationServerMetadata,\n type OAuthClientCredentials,\n type OAuthClientMetadata,\n type OAuthParResponse,\n type OAuthRefreshTokenGrantTokenRequest,\n type OAuthTokenIdentification,\n type OAuthTokenRequest,\n type OAuthTokenResponse,\n type OAuthTokenType,\n atprotoLoopbackClientMetadata,\n oauthAuthorizationRequestParametersSchema,\n} from '@atproto/oauth-types'\nimport type { CreateDidResolverOptions } from '@atproto-labs/did-resolver'\nimport { safeFetchWrap } from '@atproto-labs/fetch-node'\nimport {\n type CreateHandleResolverNodeOptions,\n createHandleResolverNode,\n} from '@atproto-labs/handle-resolver-node'\nimport type { SimpleStore } from '@atproto-labs/simple-store'\nimport { SimpleStoreMemory } from '@atproto-labs/simple-store-memory'\nimport { AccessTokenMode } from './access-token/access-token-mode.js'\nimport { AccountManager } from './account/account-manager.js'\nimport {\n type AccountStore,\n type AuthorizedClientData,\n type DeviceAccount,\n asAccountStore,\n} from './account/account-store.js'\nimport { resolveLoginHint } from './account/login-hint.js'\nimport type { ClientAuth, ClientAuthLegacy } from './client/client-auth.js'\nimport type { ClientId } from './client/client-id.js'\nimport {\n ClientManager,\n type LoopbackMetadataGetter,\n} from './client/client-manager.js'\nimport { type ClientStore, ifClientStore } from './client/client-store.js'\nimport type { Client } from './client/client.js'\nimport type { Branding, BrandingConfig } from './customization/branding.js'\nimport {\n type Customization,\n type CustomizationConfig,\n customizationSchema,\n} from './customization/customization.js'\nimport type { DeviceId } from './device/device-id.js'\nimport {\n type DeviceInfo,\n DeviceManager,\n type DeviceManagerOptions,\n} from './device/device-manager.js'\nimport { type DeviceStore, asDeviceStore } from './device/device-store.js'\nimport { AccountSelectionRequiredError } from './errors/account-selection-required-error.js'\nimport { AuthorizationError } from './errors/authorization-error.js'\nimport { ConsentRequiredError } from './errors/consent-required-error.js'\nimport { InvalidDpopKeyBindingError } from './errors/invalid-dpop-key-binding-error.js'\nimport { InvalidDpopProofError } from './errors/invalid-dpop-proof-error.js'\nimport { InvalidGrantError } from './errors/invalid-grant-error.js'\nimport { InvalidRequestError } from './errors/invalid-request-error.js'\nimport { LoginRequiredError } from './errors/login-required-error.js'\nimport { LexiconManager } from './lexicon/lexicon-manager.js'\nimport { type LexiconStore, asLexiconStore } from './lexicon/lexicon-store.js'\nimport type { HcaptchaConfig } from './lib/hcaptcha.js'\nimport type { RequestMetadata } from './lib/http/request.js'\nimport { dateToRelativeSeconds } from './lib/util/date.js'\nimport { formatError } from './lib/util/error.js'\nimport type { MultiLangString } from './lib/util/locale.js'\nimport { isOlderThan } from './lib/util/time.js'\nimport {\n type CustomMetadata,\n buildMetadata,\n} from './metadata/build-metadata.js'\nimport { AUTHENTICATION_MAX_AGE, TOKEN_MAX_AGE } from './oauth-constants.js'\nimport type { OAuthHooks } from './oauth-hooks.js'\nimport {\n type DpopProof,\n OAuthVerifier,\n type OAuthVerifierOptions,\n type VerifyTokenPayloadOptions,\n} from './oauth-verifier.js'\nimport { type ReplayStore, ifReplayStore } from './replay/replay-store.js'\nimport { codeSchema } from './request/code.js'\nimport { RequestManager } from './request/request-manager.js'\nimport { type RequestStore, asRequestStore } from './request/request-store.js'\nimport { parseRequestUri } from './request/request-uri.js'\nimport type { AuthorizationRedirectParameters } from './result/authorization-redirect-parameters.js'\nimport type { AuthorizationResultAuthorizePage } from './result/authorization-result-authorize-page.js'\nimport type { AuthorizationResultRedirect } from './result/authorization-result-redirect.js'\nimport type { ErrorHandler } from './router/error-handler.js'\nimport type { AccessTokenPayload } from './signer/access-token-payload.js'\nimport { refreshTokenSchema } from './token/refresh-token.js'\nimport type { TokenData } from './token/token-data.js'\nimport { TokenManager } from './token/token-manager.js'\nimport { type TokenStore, asTokenStore } from './token/token-store.js'\nimport { isPARResponseError } from './types/par-response-error.js'\n\n// Re-export dependencies that are part of the public API of this package, so\n// that consumers don't have to install them separately.\nexport { safeFetchWrap } from '@atproto-labs/fetch-node'\nexport type * from '@atproto/jwk'\nexport { Keyset } from '@atproto/jwk'\nexport type * from '@atproto/jwk-jose'\nexport { JoseKey } from '@atproto/jwk-jose'\nexport type * from '@atproto/lex-resolver'\nexport { LexResolver, LexResolverError } from '@atproto/lex-resolver'\n\nexport { AccessTokenMode }\nexport type {\n AccessTokenPayload,\n AuthorizationRedirectParameters,\n AuthorizationResultAuthorizePage as AuthorizationResultAuthorize,\n AuthorizationResultRedirect,\n Branding,\n BrandingConfig,\n CustomMetadata,\n Customization,\n CustomizationConfig,\n ErrorHandler,\n HcaptchaConfig,\n LoopbackMetadataGetter,\n MultiLangString,\n OAuthAuthorizationServerMetadata,\n VerifyTokenPayloadOptions,\n}\n\nexport type ClientJwksCache = SimpleStore<string, Jwks>\nexport type ClientMetadataCache = SimpleStore<string, OAuthClientMetadata>\nexport type OAuthStore = AccountStore &\n ClientStore &\n DeviceStore &\n LexiconStore &\n ReplayStore &\n RequestStore &\n TokenStore\n\ntype OAuthProviderConfig = {\n /**\n * Maximum age a device/account session can be before requiring\n * re-authentication.\n */\n authenticationMaxAge?: number\n\n /**\n * Maximum age access & id tokens can be before requiring a refresh.\n */\n tokenMaxAge?: number\n\n /**\n * If set to {@link AccessTokenMode.stateless}, the generated access tokens\n * will contain all the necessary information to validate the token without\n * needing to query the database. This is useful for cases where the Resource\n * Server is on a different host/server than the Authorization Server.\n *\n * When set to {@link AccessTokenMode.light}, the access tokens will contain\n * only the necessary information to validate the token, but the token id\n * will need to be queried from the database to retrieve the full token\n * information (scope, audience, etc.)\n *\n * @see {@link AccessTokenMode}\n * @default {AccessTokenMode.stateless}\n */\n accessTokenMode?: AccessTokenMode\n\n /**\n * Additional metadata to be included in the discovery document.\n */\n metadata?: CustomMetadata\n\n /**\n * A Lexicon resolver instance to use for fetching lexicon schemas.\n */\n lexResolver?: LexResolver\n\n /**\n * A custom fetch function that can be used to fetch the client metadata from\n * the internet. By default, the fetch function is a safeFetchWrap() function\n * that protects against SSRF attacks, large responses & known bad domains. If\n * you want to disable all protections, you can provide `globalThis.fetch` as\n * fetch function.\n */\n safeFetch?: typeof globalThis.fetch\n\n /**\n * A redis instance to use for replay protection. If not provided, replay\n * protection will use memory storage.\n */\n redis?: Redis | RedisOptions | string\n\n /**\n * This will be used as the default store for all the stores. If a store is\n * not provided, this store will be used instead. If the `store` does not\n * implement a specific store, a runtime error will be thrown. Make sure that\n * this store implements all the interfaces not provided in the other\n * `<name>Store` options.\n */\n store?: Partial<OAuthStore>\n\n accountStore?: AccountStore\n clientStore?: ClientStore\n deviceStore?: DeviceStore\n lexiconStore?: LexiconStore\n replayStore?: ReplayStore\n requestStore?: RequestStore\n tokenStore?: TokenStore\n\n /**\n * In order to speed up the client fetching process, you can provide a cache\n * to store HTTP responses.\n *\n * @note the cached entries should automatically expire after a certain time (typically 10 minutes)\n */\n clientJwksCache?: ClientJwksCache\n\n /**\n * In order to speed up the client fetching process, you can provide a cache\n * to store HTTP responses.\n *\n * @note the cached entries should automatically expire after a certain time (typically 10 minutes)\n */\n clientMetadataCache?: ClientMetadataCache\n\n /**\n * In order to enable loopback clients, you can provide a function that\n * returns the client metadata for a given loopback URL. This is useful for\n * development and testing purposes. This function is not called for internet\n * clients.\n *\n * @default is as specified by ATPROTO\n */\n loopbackMetadata?: null | false | LoopbackMetadataGetter\n}\n\nexport type OAuthProviderOptions = OAuthProviderConfig &\n OAuthVerifierOptions &\n OAuthHooks &\n CreateDidResolverOptions &\n CreateHandleResolverNodeOptions &\n DeviceManagerOptions &\n CustomizationConfig\n\nexport class OAuthProvider extends OAuthVerifier {\n protected readonly accessTokenMode: AccessTokenMode\n protected readonly hooks: OAuthHooks\n\n public readonly metadata: OAuthAuthorizationServerMetadata\n public readonly customization: Customization\n\n public readonly authenticationMaxAge: number\n\n public readonly accountManager: AccountManager\n public readonly deviceManager: DeviceManager\n public readonly clientManager: ClientManager\n public readonly lexiconManager: LexiconManager\n public readonly requestManager: RequestManager\n public readonly tokenManager: TokenManager\n\n public constructor({\n // OAuthProviderConfig\n authenticationMaxAge = AUTHENTICATION_MAX_AGE,\n tokenMaxAge = TOKEN_MAX_AGE,\n accessTokenMode = AccessTokenMode.stateless,\n\n metadata,\n loopbackMetadata = atprotoLoopbackClientMetadata,\n\n // Services\n fetch: unsafeFetch = globalThis.fetch, // Inherited from options\n safeFetch = safeFetchWrap({ fetch: unsafeFetch }),\n lexResolver = new LexResolver({ fetch: safeFetch }),\n\n // compound store implementation\n store,\n\n // Required stores\n accountStore = asAccountStore(store),\n deviceStore = asDeviceStore(store),\n lexiconStore = asLexiconStore(store),\n tokenStore = asTokenStore(store),\n requestStore = asRequestStore(store),\n\n // Optional stores\n clientStore = ifClientStore(store),\n replayStore = ifReplayStore(store),\n\n clientJwksCache = new SimpleStoreMemory({\n maxSize: 50_000_000,\n ttl: 600e3,\n }),\n clientMetadataCache = new SimpleStoreMemory({\n maxSize: 50_000_000,\n ttl: 600e3,\n }),\n\n // OAuthHooks &\n // CreateDidResolverOptions &\n // CreateHandleResolverNodeOptions &\n // OAuthVerifierOptions &\n // DeviceManagerOptions &\n // Customization\n ...rest\n }: OAuthProviderOptions) {\n super({ replayStore, ...rest })\n\n // @NOTE: hooks don't really need a type parser, as all zod can actually\n // check at runtime is the fact that the values are functions. The only way\n // we would benefit from zod here would be to wrap the functions with a\n // validator for the provided function's return types, which we don't\n // really need if types are respected.\n this.hooks = rest\n\n this.accessTokenMode = accessTokenMode\n this.authenticationMaxAge = authenticationMaxAge\n this.metadata = buildMetadata(this.issuer, this.keyset, metadata)\n this.customization = customizationSchema.parse(rest)\n\n this.deviceManager = new DeviceManager(deviceStore, {\n ...rest,\n cookie: {\n ...rest.cookie,\n // \"secure\" defaults to \"true\" in DeviceManager. For the oauth routes to\n // work from localhost on Safari, we need to explicitly set secure to\n // false for localhost usage. This is not really an issue with Chrome\n // and Firefox, but Safari enforces it strictly.\n secure: !this.issuer.startsWith('http:'),\n },\n })\n this.accountManager = new AccountManager(\n this.issuer,\n accountStore,\n this.hooks,\n createOAuthResolver({\n handleResolver: createHandleResolverNode({ ...rest, safeFetch }),\n didResolver: rest.didResolver,\n didCache: rest.didCache,\n onDidCacheError: rest.onDidCacheError,\n plcDirectoryUrl: rest.plcDirectoryUrl,\n fetch: safeFetch,\n allowHttp: rest.allowHttp,\n }),\n this.customization,\n )\n this.clientManager = new ClientManager(\n this.metadata,\n this.keyset,\n this.hooks,\n clientStore || null,\n loopbackMetadata || null,\n safeFetch,\n clientJwksCache,\n clientMetadataCache,\n )\n this.lexiconManager = new LexiconManager(lexiconStore, lexResolver)\n this.requestManager = new RequestManager(\n requestStore,\n this.lexiconManager,\n this.signer,\n this.metadata,\n this.hooks,\n )\n this.tokenManager = new TokenManager(\n tokenStore,\n this.lexiconManager,\n this.signer,\n this.hooks,\n this.accessTokenMode,\n tokenMaxAge,\n )\n }\n\n get jwks() {\n return this.keyset.publicJwks\n }\n\n /**\n * @returns true if the user's consent is required for the requested scopes\n */\n public checkConsentRequired(\n parameters: OAuthAuthorizationRequestParameters,\n clientData?: AuthorizedClientData,\n ) {\n // Client was never authorized before\n if (!clientData) return true\n\n // Client explicitly asked for consent\n if (parameters.prompt === 'consent') return true\n\n // No scope requested, and client is known by user, no consent required\n const requestedScopes = parameters.scope?.split(' ')\n if (requestedScopes == null) return false\n\n // Ensure that all requested scopes were previously authorized by the user\n const { authorizedScopes } = clientData\n return !requestedScopes.every((scope) => authorizedScopes.includes(scope))\n }\n\n public checkLoginRequired(deviceAccount: DeviceAccount) {\n return isOlderThan(deviceAccount.updatedAt, this.authenticationMaxAge)\n }\n\n protected async authenticateClient(\n clientCredentials: OAuthClientCredentials,\n dpopProof: null | DpopProof,\n options?: {\n allowMissingDpopProof?: boolean\n },\n ): Promise<{\n client: Client\n clientAuth: ClientAuth\n }> {\n const client = await this.clientManager.getClient(\n clientCredentials.client_id,\n )\n\n if (\n client.metadata.dpop_bound_access_tokens &&\n !dpopProof &&\n !options?.allowMissingDpopProof\n ) {\n throw new InvalidDpopProofError('DPoP proof required')\n }\n\n if (dpopProof && !client.metadata.dpop_bound_access_tokens) {\n throw new InvalidDpopProofError('DPoP proof not allowed for this client')\n }\n\n const clientAuth = await client.authenticate(clientCredentials, {\n authorizationServerIdentifier: this.issuer,\n })\n\n if (clientAuth.method === 'private_key_jwt') {\n // Clients MUST NOT use their client assertion key to sign DPoP proofs\n if (dpopProof && clientAuth.jkt === dpopProof.jkt) {\n throw new InvalidRequestError(\n 'The DPoP proof must be signed with a different key than the client assertion',\n )\n }\n\n // https://www.rfc-editor.org/rfc/rfc7523.html#section-3\n // > 7. [...] The authorization server MAY ensure that JWTs are not\n // > replayed by maintaining the set of used \"jti\" values for the\n // > length of time for which the JWT would be considered valid based\n // > on the applicable \"exp\" instant.\n\n const unique = await this.replayManager.uniqueAuth(\n clientAuth.jti,\n client.id,\n clientAuth.exp,\n )\n if (!unique) {\n throw new InvalidGrantError(`${clientAuth.method} jti reused`)\n }\n }\n\n return { client, clientAuth }\n }\n\n async decodeJAR(\n client: Client,\n input: OAuthAuthorizationRequestJar,\n ): Promise<OAuthAuthorizationRequestParameters> {\n const { payload } = await client.decodeRequestObject(\n input.request,\n this.issuer,\n )\n\n const { jti } = payload\n if (!jti) {\n throw new InvalidRequestError(\n 'Request object payload must contain a \"jti\" claim',\n )\n }\n if (!(await this.replayManager.uniqueJar(jti, client.id))) {\n throw new InvalidRequestError('Request object was replayed')\n }\n\n const parameters = await oauthAuthorizationRequestParametersSchema\n .parseAsync(payload)\n .catch((err) => {\n const msg = formatError(err, 'Invalid parameters in JAR')\n throw new InvalidRequestError(msg, err)\n })\n\n return parameters\n }\n\n /**\n * @see {@link https://datatracker.ietf.org/doc/html/rfc9126}\n */\n public async pushedAuthorizationRequest(\n credentials: OAuthClientCredentials,\n authorizationRequest: OAuthAuthorizationRequestPar,\n dpopProof: null | DpopProof,\n ): Promise<OAuthParResponse> {\n try {\n const { client, clientAuth } = await this.authenticateClient(\n credentials,\n dpopProof,\n // Allow missing DPoP header for PAR requests as rfc9449 allows it\n // (though the dpop_jkt parameter must be present in that case, see\n // check bellow).\n { allowMissingDpopProof: true },\n )\n\n const parameters =\n 'request' in authorizationRequest // Handle JAR\n ? await this.decodeJAR(client, authorizationRequest)\n : authorizationRequest\n\n if (!parameters.dpop_jkt) {\n if (client.metadata.dpop_bound_access_tokens) {\n if (dpopProof) parameters.dpop_jkt = dpopProof.jkt\n else {\n // @NOTE When both PAR and DPoP are used, either the DPoP header, or\n // the dpop_jkt parameter must be present. We do not enforce this\n // for legacy reasons.\n // https://datatracker.ietf.org/doc/html/rfc9449#section-10.1\n }\n }\n } else {\n if (!client.metadata.dpop_bound_access_tokens) {\n throw new InvalidRequestError(\n 'DPoP bound access tokens are not enabled for this client',\n )\n }\n\n // Proof is optional if the dpop_jkt is provided, but if it is provided,\n // it must match the DPoP proof JKT.\n if (dpopProof && dpopProof.jkt !== parameters.dpop_jkt) {\n throw new InvalidDpopKeyBindingError()\n }\n }\n\n const { requestUri, expiresAt } =\n await this.requestManager.createAuthorizationRequest(\n client,\n clientAuth,\n parameters,\n null,\n )\n\n return {\n request_uri: requestUri,\n expires_in: dateToRelativeSeconds(expiresAt),\n }\n } catch (err) {\n // https://datatracker.ietf.org/doc/html/rfc9126#section-2.3-1\n // > Since initial processing of the pushed authorization request does not\n // > involve resource owner interaction, error codes related to user\n // > interaction, such as \"access_denied\", are never returned.\n if (err instanceof AuthorizationError && !isPARResponseError(err.error)) {\n throw new InvalidRequestError(err.error_description, err)\n }\n throw err\n }\n }\n\n private async processAuthorizationRequest(\n client: Client,\n deviceId: DeviceId,\n query: OAuthAuthorizationRequestQuery,\n ) {\n // PAR\n if ('request_uri' in query) {\n const requestUri = parseRequestUri(query.request_uri, {\n path: ['query', 'request_uri'],\n })\n return this.requestManager.get(requestUri, deviceId, client.id)\n }\n\n // JAR\n if ('request' in query) {\n // @NOTE Since JAR are signed with the client's private key, a JAR *could*\n // technically be used to authenticate the client when requests are\n // created without PAR (i.e. created on the fly by the authorize\n // endpoint). This implementation actually used to support this\n // (un-spec'd) behavior. That support was removed:\n // - Because it was not actually used\n // - Because it was not part of any standard\n // - Because it makes extending the client authentication mechanism more\n // complex since any extension would not only need to affect the\n // \"private_key_jwt\" auth method but also the JAR \"request\" object.\n const parameters = await this.decodeJAR(client, query)\n\n return this.requestManager.createAuthorizationRequest(\n client,\n null,\n parameters,\n deviceId,\n )\n }\n\n // \"Regular\" authorization request (created on the fly by directing the user\n // to the authorization endpoint with all the parameters in the url).\n return this.requestManager.createAuthorizationRequest(\n client,\n null,\n query,\n deviceId,\n )\n }\n\n /**\n * @see {@link https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-11#section-4.1.1}\n */\n public async authorize(\n query: OAuthAuthorizationRequestQuery,\n { deviceId, deviceMetadata }: DeviceInfo,\n ): Promise<AuthorizationResultRedirect | AuthorizationResultAuthorizePage> {\n const { issuer } = this\n\n // If there is a chance to redirect the user to the client, let's do\n // it by wrapping the error in an AuthorizationError.\n const throwAuthorizationError =\n 'redirect_uri' in query\n ? (err: unknown): never => {\n // https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-11#section-4.1.2.1\n throw AuthorizationError.from(query, err)\n }\n : null\n\n const client = await this.clientManager\n .getClient(query.client_id)\n .catch(throwAuthorizationError)\n\n const { parameters, requestUri } = await this.processAuthorizationRequest(\n client,\n deviceId,\n query,\n ).catch(throwAuthorizationError)\n\n try {\n const sessions = (\n await this.accountManager.listDeviceAccounts(deviceId)\n ).map((deviceAccount) => ({\n account: deviceAccount.account,\n\n // @TODO Return the session expiration date instead of a boolean to\n // avoid having to rely on a leeway when \"accepting\" the request.\n loginRequired:\n parameters.prompt === 'login' ||\n this.checkLoginRequired(deviceAccount),\n consentRequired: this.checkConsentRequired(\n parameters,\n deviceAccount.authorizedClients.get(client.id),\n ),\n }))\n\n // https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest\n\n // prompt=select_account\n //\n // > The Authorization Server SHOULD prompt the End-User to select a user\n // > account. This enables an End-User who has multiple accounts at the\n // > Authorization Server to select amongst the multiple accounts that\n // > they might have current sessions for. If it cannot obtain an account\n // > selection choice made by the End-User, it MUST return an error,\n // > typically account_selection_required.\n if (parameters.prompt === 'select_account' && !sessions.length) {\n throw new AccountSelectionRequiredError(parameters)\n }\n\n const ssoSessions = sessions\n .filter(hasActiveAccount)\n .filter(matchesHint, parameters)\n\n // prompt=none\n //\n // > The Authorization Server MUST NOT display any authentication or\n // > consent user interface pages. An error is returned if an End-User is\n // > not already authenticated or the Client does not have pre-configured\n // > consent for the requested Claims or does not fulfill other conditions\n // > for processing the request. The error code will typically be\n // > login_required, interaction_required, or another code defined in\n // > Section 3.1.2.6. This can be used as a method to check for existing\n // > authentication and/or consent.\n if (parameters.prompt === 'none') {\n if (ssoSessions.length > 1) {\n throw new AccountSelectionRequiredError(parameters)\n }\n if (ssoSessions.length < 1) {\n throw new LoginRequiredError(parameters)\n }\n\n const ssoSession = ssoSessions[0]!\n if (ssoSession.loginRequired) {\n throw new LoginRequiredError(parameters)\n }\n if (ssoSession.consentRequired) {\n throw new ConsentRequiredError(parameters)\n }\n\n const { code } = await this.requestManager.setAuthorized(\n requestUri,\n client,\n ssoSession.account,\n deviceId,\n deviceMetadata,\n )\n\n return { issuer, parameters, redirect: { code } }\n }\n\n // Automatic SSO when a hint was provided that matches a single session\n if (parameters.prompt == null && parameters.login_hint != null) {\n if (ssoSessions.length === 1) {\n const ssoSession = ssoSessions[0]!\n if (!ssoSession.loginRequired && !ssoSession.consentRequired) {\n const { code } = await this.requestManager.setAuthorized(\n requestUri,\n client,\n ssoSession.account,\n deviceId,\n deviceMetadata,\n )\n\n return { issuer, parameters, redirect: { code } }\n }\n }\n }\n\n return {\n issuer,\n client,\n parameters,\n requestUri,\n sessions: sessions\n // Strip un-necessary information (like consentRequired)\n .map(({ account, loginRequired }) => ({ account, loginRequired })),\n selectedDid:\n parameters.prompt == null ||\n parameters.prompt === 'login' ||\n parameters.prompt === 'consent'\n ? sessions.find(matchesHint, parameters)?.account.did\n : undefined,\n loginHint: await resolveLoginHint(\n parameters.login_hint,\n this.accountManager,\n ),\n permissionSets: await this.lexiconManager\n .getPermissionSetsFromScope(parameters.scope)\n .catch((cause) => {\n throw new AuthorizationError(\n parameters,\n 'Unable to retrieve permission sets',\n 'invalid_scope',\n cause,\n )\n }),\n }\n } catch (err) {\n try {\n await this.requestManager.delete(requestUri)\n } catch {\n // There are two error here. Better keep the outer one.\n //\n // @TODO Maybe move this entire code to the /authorize endpoint\n // (allowing to log this error)\n }\n\n throw AuthorizationError.from(parameters, err)\n }\n }\n\n public async token(\n clientCredentials: OAuthClientCredentials,\n clientMetadata: RequestMetadata,\n request: OAuthTokenRequest,\n dpopProof: null | DpopProof,\n ): Promise<OAuthTokenResponse> {\n const { client, clientAuth } = await this.authenticateClient(\n clientCredentials,\n dpopProof,\n )\n\n if (!this.metadata.grant_types_supported?.includes(request.grant_type)) {\n throw new InvalidGrantError(\n `Grant type \"${request.grant_type}\" is not supported by the server`,\n )\n }\n\n if (!client.metadata.grant_types.includes(request.grant_type)) {\n throw new InvalidGrantError(\n `\"${request.grant_type}\" grant type is not allowed for this client`,\n )\n }\n\n if (request.grant_type === 'authorization_code') {\n return this.authorizationCodeGrant(\n client,\n clientAuth,\n clientMetadata,\n request,\n dpopProof,\n )\n }\n\n if (request.grant_type === 'refresh_token') {\n return this.refreshTokenGrant(\n client,\n clientAuth,\n clientMetadata,\n request,\n dpopProof,\n )\n }\n\n throw new InvalidGrantError(\n `Grant type \"${request.grant_type}\" not supported`,\n )\n }\n\n protected async compareClientAuth(\n client: Client,\n clientAuth: ClientAuth,\n dpopProof: null | DpopProof,\n initial: {\n parameters: OAuthAuthorizationRequestParameters\n clientId: ClientId\n clientAuth: null | ClientAuth | ClientAuthLegacy\n },\n ): Promise<void> {\n // Fool proofing, ensure that the client is authenticating using the right method\n if (clientAuth.method !== client.metadata.token_endpoint_auth_method) {\n throw new InvalidGrantError(\n `Client authentication method mismatch (expected ${client.metadata.token_endpoint_auth_method}, got ${clientAuth.method})`,\n )\n }\n\n if (initial.clientId !== client.id) {\n throw new InvalidGrantError(`Token was not issued to this client`)\n }\n\n const { parameters } = initial\n if (parameters.dpop_jkt) {\n if (!dpopProof) {\n throw new InvalidGrantError(`DPoP proof is required for this request`)\n } else if (parameters.dpop_jkt !== dpopProof.jkt) {\n throw new InvalidGrantError(\n `DPoP proof does not match the expected JKT`,\n )\n }\n }\n\n if (!initial.clientAuth) {\n // If the client did not use PAR, it was not authenticated when the request\n // was initially created (see authorize() method in OAuthProvider). Since\n // PAR is not mandatory, and since the token exchange currently taking place\n // *is* authenticated (`clientAuth`), we allow \"upgrading\" the\n // authentication method (the token created will be bound to the current\n // clientAuth).\n return\n }\n\n switch (initial.clientAuth.method) {\n case CLIENT_ASSERTION_TYPE_JWT_BEARER: // LEGACY\n case 'private_key_jwt':\n if (clientAuth.method !== 'private_key_jwt') {\n throw new InvalidGrantError(\n `Client authentication method mismatch (expected ${initial.clientAuth.method})`,\n )\n }\n if (\n clientAuth.kid !== initial.clientAuth.kid ||\n clientAuth.alg !== initial.clientAuth.alg ||\n clientAuth.jkt !== initial.clientAuth.jkt\n ) {\n throw new InvalidGrantError(\n `The session was initiated with a different key than the client assertion currently used`,\n )\n }\n break\n case 'none':\n // @NOTE We allow the client to \"upgrade\" to a confidential client if\n // the session was initially created without client authentication.\n break\n default:\n throw new InvalidGrantError(\n // @ts-expect-error (future proof, backwards compatibility)\n `Invalid method \"${initial.clientAuth.method}\"`,\n )\n }\n }\n\n protected async authorizationCodeGrant(\n client: Client,\n clientAuth: ClientAuth,\n clientMetadata: RequestMetadata,\n input: OAuthAuthorizationCodeGrantTokenRequest,\n dpopProof: null | DpopProof,\n ): Promise<OAuthTokenResponse> {\n const code = await codeSchema\n .parseAsync(input.code, { path: ['code'] })\n .catch((err) => {\n const msg = formatError(err, 'Invalid code')\n throw new InvalidGrantError(msg, err)\n })\n\n const data = await this.requestManager\n .consumeCode(code)\n .catch(async (err) => {\n // Code not found in request manager: delete the existing OAuth session\n // if the code was replayed (already converted into a token)\n const tokenInfo = await this.tokenManager.findByCode(code)\n if (tokenInfo) {\n await this.tokenManager.deleteToken(tokenInfo.id)\n }\n\n throw InvalidGrantError.from(err, `Invalid code`)\n })\n\n // @NOTE at this point, the request data was removed from the store and only\n // exists in memory here (in the \"data\" variable). Because of this, any\n // error thrown after this point will permanently cause the request data to\n // be lost.\n\n await this.compareClientAuth(client, clientAuth, dpopProof, data)\n\n // If the DPoP proof was not provided earlier (PAR / authorize), let's add\n // it now.\n const parameters =\n dpopProof &&\n client.metadata.dpop_bound_access_tokens &&\n !data.parameters.dpop_jkt\n ? { ...data.parameters, dpop_jkt: dpopProof.jkt }\n : data.parameters\n\n await this.validateCodeGrant(parameters, input)\n\n const accountData = await this.accountManager.getAccount(data.did)\n\n if (!accountData) {\n throw new InvalidGrantError('Account no longer exists')\n }\n\n return this.tokenManager.createToken(\n client,\n clientAuth,\n clientMetadata,\n accountData.account,\n data.deviceId,\n parameters,\n code,\n )\n }\n\n protected async validateCodeGrant(\n parameters: OAuthAuthorizationRequestParameters,\n input: OAuthAuthorizationCodeGrantTokenRequest,\n ): Promise<void> {\n if (parameters.redirect_uri !== input.redirect_uri) {\n throw new InvalidGrantError(\n 'The redirect_uri parameter must match the one used in the authorization request',\n )\n }\n\n if (parameters.code_challenge) {\n if (!input.code_verifier) {\n throw new InvalidGrantError('code_verifier is required')\n }\n if (input.code_verifier.length < 43) {\n throw new InvalidGrantError('code_verifier too short')\n }\n switch (parameters.code_challenge_method) {\n case undefined: // default is \"plain\"\n case 'plain':\n if (parameters.code_challenge !== input.code_verifier) {\n throw new InvalidGrantError('Invalid code_verifier')\n }\n break\n\n case 'S256': {\n const inputChallenge = Buffer.from(\n parameters.code_challenge,\n 'base64',\n )\n const computedChallenge = createHash('sha256')\n .update(input.code_verifier)\n .digest()\n if (inputChallenge.compare(computedChallenge) !== 0) {\n throw new InvalidGrantError('Invalid code_verifier')\n }\n break\n }\n\n default:\n // Should never happen (because request validation should catch this)\n throw new Error(`Unsupported code_challenge_method`)\n }\n const unique = await this.replayManager.uniqueCodeChallenge(\n parameters.code_challenge,\n )\n if (!unique) {\n throw new InvalidGrantError('Code challenge already used')\n }\n } else if (input.code_verifier !== undefined) {\n throw new InvalidRequestError(\"code_challenge parameter wasn't provided\")\n }\n }\n\n protected async refreshTokenGrant(\n client: Client,\n clientAuth: ClientAuth,\n clientMetadata: RequestMetadata,\n input: OAuthRefreshTokenGrantTokenRequest,\n dpopProof: null | DpopProof,\n ): Promise<OAuthTokenResponse> {\n const refreshToken = await refreshTokenSchema\n .parseAsync(input.refresh_token, { path: ['refresh_token'] })\n .catch((err) => {\n const msg = formatError(err, 'Invalid refresh token')\n throw new InvalidGrantError(msg, err)\n })\n\n const tokenInfo = await this.tokenManager.consumeRefreshToken(refreshToken)\n\n try {\n const { data } = tokenInfo\n const now = new Date()\n\n await this.compareClientAuth(client, clientAuth, dpopProof, data)\n await this.validateRefreshGrant(client, data, now)\n\n return await this.tokenManager.rotateToken(\n client,\n clientAuth,\n clientMetadata,\n tokenInfo,\n now,\n )\n } catch (err) {\n await this.tokenManager.deleteToken(tokenInfo.id)\n\n throw err\n }\n }\n\n protected async validateRefreshGrant(\n client: Client,\n data: TokenData,\n now = new Date(),\n ): Promise<void> {\n if (!client.metadata.grant_types.includes('refresh_token')) {\n throw new InvalidGrantError(`Refresh token grant not allowed`)\n }\n\n const sessionAge = now.getTime() - data.createdAt.getTime()\n\n if (sessionAge > client.sessionLifetime) {\n throw new InvalidGrantError(`Session expired`)\n }\n\n const refreshAge = now.getTime() - data.updatedAt.getTime()\n if (refreshAge > client.refreshLifetime) {\n throw new InvalidGrantError(`Refresh token expired`)\n }\n }\n\n /**\n * @see {@link https://datatracker.ietf.org/doc/html/rfc7009#section-2.1 rfc7009}\n */\n public async revoke(\n clientCredentials: OAuthClientCredentials,\n { token }: OAuthTokenIdentification,\n dpopProof: null | DpopProof,\n ) {\n // > The authorization server first validates the client credentials (in\n // > case of a confidential client)\n const { client, clientAuth } = await this.authenticateClient(\n clientCredentials,\n dpopProof,\n )\n\n const tokenInfo = await this.tokenManager.findToken(token)\n if (tokenInfo) {\n // > [...] and then verifies whether the token was issued to the client\n // > making the revocation request.\n const { data } = tokenInfo\n await this.compareClientAuth(client, clientAuth, dpopProof, data)\n\n // > In the next step, the authorization server invalidates the token. The\n // > invalidation takes place immediately, and the token cannot be used\n // > again after the revocation.\n await this.tokenManager.deleteToken(tokenInfo.id)\n }\n }\n\n protected override async decodeToken(\n tokenType: OAuthTokenType,\n token: OAuthAccessToken,\n dpopProof: null | DpopProof,\n ): Promise<AccessTokenPayload> {\n const tokenPayload = await super.decodeToken(tokenType, token, dpopProof)\n\n if (this.accessTokenMode !== AccessTokenMode.stateless) {\n // @NOTE in non stateless mode, some claims can be omitted (most notably\n // \"scope\"). We load the token claims here (allowing to ensure that the\n // token is still valid, and to retrieve a (potentially updated) set of\n // claims).\n\n const tokenClaims = await this.tokenManager.loadTokenClaims(\n tokenType,\n tokenPayload,\n )\n\n Object.assign(tokenPayload, tokenClaims)\n }\n\n return tokenPayload\n }\n}\n\nfunction matchesHint(\n this: OAuthAuthorizationRequestParameters,\n { account }: { account: Account },\n): boolean {\n const hint = this.login_hint\n if (!hint) return false\n\n return account.did === hint || account.handle === hint\n}\n\nfunction hasActiveAccount({ account }: { account: Account }): boolean {\n return !account.deactivated\n}\n"]}
|
|
1
|
+
{"version":3,"file":"oauth-provider.js","sourceRoot":"","sources":["../src/oauth-provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAGxC,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AAEnD,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAA;AAC7D,OAAO,EACL,gCAAgC,EAiBhC,6BAA6B,EAC7B,yCAAyC,GAC1C,MAAM,sBAAsB,CAAA;AAE7B,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAA;AACxD,OAAO,EAEL,wBAAwB,GACzB,MAAM,oCAAoC,CAAA;AAE3C,OAAO,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAA;AACrE,OAAO,EAAE,eAAe,EAAE,MAAM,qCAAqC,CAAA;AACrE,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAA;AAC7D,OAAO,EAIL,cAAc,GACf,MAAM,4BAA4B,CAAA;AACnC,OAAO,EAAE,gBAAgB,EAAE,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AgC;YAChC,MAAM,IAAI,CAAC,YAAY,CAAC,WAAW,CAAC,SAAS,CAAC,EAAE,CAAC,CAAA;QACnD,CAAC;IACH,CAAC;IAEkB,KAAK,CAAC,WAAW,CAClC,SAAyB,EACzB,KAAuB,EACvB,SAA2B;QAE3B,MAAM,YAAY,GAAG,MAAM,KAAK,CAAC,WAAW,CAAC,SAAS,EAAE,KAAK,EAAE,SAAS,CAAC,CAAA;QAEzE,IAAI,IAAI,CAAC,eAAe,KAAK,eAAe,CAAC,SAAS,EAAE,CAAC;YACvD,wEAAwE;YACxE,uEAAuE;YACvE,uEAAuE;YACvE,WAAW;YAEX,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,YAAY,CAAC,eAAe,CACzD,SAAS,EACT,YAAY,CACb,CAAA;YAED,MAAM,CAAC,MAAM,CAAC,YAAY,EAAE,WAAW,CAAC,CAAA;QAC1C,CAAC;QAED,OAAO,YAAY,CAAA;IACrB,CAAC;CACF;AAED,SAAS,WAAW,CAElB,EAAE,OAAO,EAAwB;IAEjC,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAA;IAC5B,IAAI,CAAC,IAAI;QAAE,OAAO,KAAK,CAAA;IAEvB,OAAO,OAAO,CAAC,GAAG,KAAK,IAAI,IAAI,OAAO,CAAC,MAAM,KAAK,IAAI,CAAA;AACxD,CAAC;AAED,SAAS,gBAAgB,CAAC,EAAE,OAAO,EAAwB;IACzD,OAAO,CAAC,OAAO,CAAC,WAAW,CAAA;AAC7B,CAAC","sourcesContent":["import { createHash } from 'node:crypto'\nimport type { Redis, RedisOptions } from 'ioredis'\nimport type { Jwks } from '@atproto/jwk'\nimport { LexResolver } from '@atproto/lex-resolver'\nimport type { Account } from '@atproto/oauth-provider-api'\nimport { createOAuthResolver } from '@atproto/oauth-resolver'\nimport {\n CLIENT_ASSERTION_TYPE_JWT_BEARER,\n type OAuthAccessToken,\n type OAuthAuthorizationCodeGrantTokenRequest,\n type OAuthAuthorizationRequestJar,\n type OAuthAuthorizationRequestPar,\n type OAuthAuthorizationRequestParameters,\n type OAuthAuthorizationRequestQuery,\n type OAuthAuthorizationRequestUri,\n type OAuthAuthorizationServerMetadata,\n type OAuthClientCredentials,\n type OAuthClientMetadata,\n type OAuthParResponse,\n type OAuthRefreshTokenGrantTokenRequest,\n type OAuthTokenIdentification,\n type OAuthTokenRequest,\n type OAuthTokenResponse,\n type OAuthTokenType,\n atprotoLoopbackClientMetadata,\n oauthAuthorizationRequestParametersSchema,\n} from '@atproto/oauth-types'\nimport type { CreateDidResolverOptions } from '@atproto-labs/did-resolver'\nimport { safeFetchWrap } from '@atproto-labs/fetch-node'\nimport {\n type CreateHandleResolverNodeOptions,\n createHandleResolverNode,\n} from '@atproto-labs/handle-resolver-node'\nimport type { SimpleStore } from '@atproto-labs/simple-store'\nimport { SimpleStoreMemory } from '@atproto-labs/simple-store-memory'\nimport { AccessTokenMode } from './access-token/access-token-mode.js'\nimport { AccountManager } from './account/account-manager.js'\nimport {\n type AccountStore,\n type AuthorizedClientData,\n type DeviceAccount,\n asAccountStore,\n} from './account/account-store.js'\nimport { resolveLoginHint } from './account/login-hint.js'\nimport type { ClientAuth, ClientAuthLegacy } from './client/client-auth.js'\nimport type { ClientId } from './client/client-id.js'\nimport {\n ClientManager,\n type LoopbackMetadataGetter,\n} from './client/client-manager.js'\nimport { type ClientStore, ifClientStore } from './client/client-store.js'\nimport type { Client } from './client/client.js'\nimport type { Branding, BrandingConfig } from './customization/branding.js'\nimport {\n type Customization,\n type CustomizationConfig,\n customizationSchema,\n} from './customization/customization.js'\nimport {\n type DeviceInfo,\n DeviceManager,\n type DeviceManagerOptions,\n} from './device/device-manager.js'\nimport { type DeviceStore, asDeviceStore } from './device/device-store.js'\nimport { AccountSelectionRequiredError } from './errors/account-selection-required-error.js'\nimport { AuthorizationError } from './errors/authorization-error.js'\nimport { ConsentRequiredError } from './errors/consent-required-error.js'\nimport { InvalidDpopKeyBindingError } from './errors/invalid-dpop-key-binding-error.js'\nimport { InvalidDpopProofError } from './errors/invalid-dpop-proof-error.js'\nimport { InvalidGrantError } from './errors/invalid-grant-error.js'\nimport { InvalidRequestError } from './errors/invalid-request-error.js'\nimport { LoginRequiredError } from './errors/login-required-error.js'\nimport { HCaptchaManager } from './hcaptcha/hcaptcha-manager.js'\nimport { LexiconManager } from './lexicon/lexicon-manager.js'\nimport { type LexiconStore, asLexiconStore } from './lexicon/lexicon-store.js'\nimport type { HcaptchaConfig } from './lib/hcaptcha.js'\nimport type { RequestMetadata } from './lib/http/request.js'\nimport { dateToRelativeSeconds } from './lib/util/date.js'\nimport { formatError } from './lib/util/error.js'\nimport type { MultiLangString } from './lib/util/locale.js'\nimport { isOlderThan } from './lib/util/time.js'\nimport {\n type CustomMetadata,\n buildMetadata,\n} from './metadata/build-metadata.js'\nimport { AUTHENTICATION_MAX_AGE, TOKEN_MAX_AGE } from './oauth-constants.js'\nimport type { OAuthHooks } from './oauth-hooks.js'\nimport {\n type DpopProof,\n OAuthVerifier,\n type OAuthVerifierOptions,\n type VerifyTokenPayloadOptions,\n} from './oauth-verifier.js'\nimport { RateLimitManager } from './rate-limit/rate-limit-manager.js'\nimport {\n DEFAULT_RATE_LIMIT_POLICIES,\n type RateLimitKeyGetter,\n type RateLimitPolicies,\n type RateLimitPolicy,\n type RateLimitPolicyContexts,\n type RateLimitPolicyName,\n type RateLimitRule,\n type RateLimitsOptions,\n authenticatedClientKey,\n identifierIpKey,\n identifierKey,\n ipKey,\n publicClientIpKey,\n} from './rate-limit/rate-limit-policies.js'\nimport type {\n RateLimiter,\n RateLimiterFactory,\n RateLimiterOptions,\n} from './rate-limit/rate-limiter.js'\nimport { type ReplayStore, ifReplayStore } from './replay/replay-store.js'\nimport { codeSchema } from './request/code.js'\nimport { RequestManager } from './request/request-manager.js'\nimport { type RequestStore, asRequestStore } from './request/request-store.js'\nimport { parseRequestUri } from './request/request-uri.js'\nimport type { AuthorizationRedirectParameters } from './result/authorization-redirect-parameters.js'\nimport type { AuthorizationResultAuthorizePage } from './result/authorization-result-authorize-page.js'\nimport type { AuthorizationResultRedirect } from './result/authorization-result-redirect.js'\nimport type { ErrorHandler } from './router/error-handler.js'\nimport type { AccessTokenPayload } from './signer/access-token-payload.js'\nimport { refreshTokenSchema } from './token/refresh-token.js'\nimport type { TokenData } from './token/token-data.js'\nimport { TokenManager } from './token/token-manager.js'\nimport { type TokenStore, asTokenStore } from './token/token-store.js'\nimport { isPARResponseError } from './types/par-response-error.js'\n\n// Re-export dependencies that are part of the public API of this package, so\n// that consumers don't have to install them separately.\nexport { safeFetchWrap } from '@atproto-labs/fetch-node'\nexport type * from '@atproto/jwk'\nexport { Keyset } from '@atproto/jwk'\nexport type * from '@atproto/jwk-jose'\nexport { JoseKey } from '@atproto/jwk-jose'\nexport type * from '@atproto/lex-resolver'\nexport { LexResolver, LexResolverError } from '@atproto/lex-resolver'\n\nexport {\n AccessTokenMode,\n DEFAULT_RATE_LIMIT_POLICIES,\n authenticatedClientKey,\n identifierIpKey,\n identifierKey,\n ipKey,\n publicClientIpKey,\n}\nexport type {\n AccessTokenPayload,\n AuthorizationRedirectParameters,\n AuthorizationResultAuthorizePage as AuthorizationResultAuthorize,\n AuthorizationResultRedirect,\n Branding,\n BrandingConfig,\n CustomMetadata,\n Customization,\n CustomizationConfig,\n ErrorHandler,\n HcaptchaConfig,\n LoopbackMetadataGetter,\n MultiLangString,\n OAuthAuthorizationServerMetadata,\n RateLimitKeyGetter,\n RateLimitPolicies,\n RateLimitPolicy,\n RateLimitPolicyContexts,\n RateLimitPolicyName,\n RateLimitRule,\n RateLimiter,\n RateLimiterFactory,\n RateLimiterOptions,\n RateLimitsOptions,\n VerifyTokenPayloadOptions,\n}\n\nexport type ClientJwksCache = SimpleStore<string, Jwks>\nexport type ClientMetadataCache = SimpleStore<string, OAuthClientMetadata>\nexport type OAuthStore = AccountStore &\n ClientStore &\n DeviceStore &\n LexiconStore &\n ReplayStore &\n RequestStore &\n TokenStore\n\ntype OAuthProviderConfig = {\n /**\n * Maximum age a device/account session can be before requiring\n * re-authentication.\n */\n authenticationMaxAge?: number\n\n /**\n * Maximum age access & id tokens can be before requiring a refresh.\n */\n tokenMaxAge?: number\n\n /**\n * If set to {@link AccessTokenMode.stateless}, the generated access tokens\n * will contain all the necessary information to validate the token without\n * needing to query the database. This is useful for cases where the Resource\n * Server is on a different host/server than the Authorization Server.\n *\n * When set to {@link AccessTokenMode.light}, the access tokens will contain\n * only the necessary information to validate the token, but the token id\n * will need to be queried from the database to retrieve the full token\n * information (scope, audience, etc.)\n *\n * @see {@link AccessTokenMode}\n * @default {AccessTokenMode.stateless}\n */\n accessTokenMode?: AccessTokenMode\n\n /**\n * Additional metadata to be included in the discovery document.\n */\n metadata?: CustomMetadata\n\n /**\n * A Lexicon resolver instance to use for fetching lexicon schemas.\n */\n lexResolver?: LexResolver\n\n /**\n * A custom fetch function that can be used to fetch the client metadata from\n * the internet. By default, the fetch function is a safeFetchWrap() function\n * that protects against SSRF attacks, large responses & known bad domains. If\n * you want to disable all protections, you can provide `globalThis.fetch` as\n * fetch function.\n */\n safeFetch?: typeof globalThis.fetch\n\n /**\n * A redis instance to use for replay protection. If not provided, replay\n * protection will use memory storage.\n */\n redis?: Redis | RedisOptions | string\n\n /**\n * This will be used as the default store for all the stores. If a store is\n * not provided, this store will be used instead. If the `store` does not\n * implement a specific store, a runtime error will be thrown. Make sure that\n * this store implements all the interfaces not provided in the other\n * `<name>Store` options.\n */\n store?: Partial<OAuthStore>\n\n accountStore?: AccountStore\n clientStore?: ClientStore\n deviceStore?: DeviceStore\n lexiconStore?: LexiconStore\n replayStore?: ReplayStore\n requestStore?: RequestStore\n tokenStore?: TokenStore\n\n /**\n * In order to speed up the client fetching process, you can provide a cache\n * to store HTTP responses.\n *\n * @note the cached entries should automatically expire after a certain time (typically 10 minutes)\n */\n clientJwksCache?: ClientJwksCache\n\n /**\n * In order to speed up the client fetching process, you can provide a cache\n * to store HTTP responses.\n *\n * @note the cached entries should automatically expire after a certain time (typically 10 minutes)\n */\n clientMetadataCache?: ClientMetadataCache\n\n /**\n * In order to enable loopback clients, you can provide a function that\n * returns the client metadata for a given loopback URL. This is useful for\n * development and testing purposes. This function is not called for internet\n * clients.\n *\n * @default is as specified by ATPROTO\n */\n loopbackMetadata?: null | false | LoopbackMetadataGetter\n\n /**\n * Enables rate limiting of the OAuth and account routes that create\n * authorization requests, check credentials, or send emails. The host\n * provides the storage backend through {@link RateLimitsOptions.factory}.\n *\n * When not provided, no rate limiting is performed. The default rules that\n * have no points, which need no storage, still apply: sign-ups always require\n * a captcha (when hCaptcha is configured).\n */\n rateLimits?: RateLimitsOptions\n}\n\nexport type OAuthProviderOptions = OAuthProviderConfig &\n OAuthVerifierOptions &\n OAuthHooks &\n CreateDidResolverOptions &\n CreateHandleResolverNodeOptions &\n DeviceManagerOptions &\n CustomizationConfig\n\nexport class OAuthProvider extends OAuthVerifier {\n protected readonly accessTokenMode: AccessTokenMode\n protected readonly hooks: OAuthHooks\n\n public readonly metadata: OAuthAuthorizationServerMetadata\n public readonly customization: Customization\n\n public readonly authenticationMaxAge: number\n\n public readonly hcaptchaManager: HCaptchaManager\n public readonly rateLimitManager: RateLimitManager\n public readonly accountManager: AccountManager\n public readonly deviceManager: DeviceManager\n public readonly clientManager: ClientManager\n public readonly lexiconManager: LexiconManager\n public readonly requestManager: RequestManager\n public readonly tokenManager: TokenManager\n\n public constructor({\n // OAuthProviderConfig\n authenticationMaxAge = AUTHENTICATION_MAX_AGE,\n tokenMaxAge = TOKEN_MAX_AGE,\n accessTokenMode = AccessTokenMode.stateless,\n\n metadata,\n loopbackMetadata = atprotoLoopbackClientMetadata,\n rateLimits,\n\n // Services\n fetch: unsafeFetch = globalThis.fetch, // Inherited from options\n safeFetch = safeFetchWrap({ fetch: unsafeFetch }),\n lexResolver = new LexResolver({ fetch: safeFetch }),\n\n // compound store implementation\n store,\n\n // Required stores\n accountStore = asAccountStore(store),\n deviceStore = asDeviceStore(store),\n lexiconStore = asLexiconStore(store),\n tokenStore = asTokenStore(store),\n requestStore = asRequestStore(store),\n\n // Optional stores\n clientStore = ifClientStore(store),\n replayStore = ifReplayStore(store),\n\n clientJwksCache = new SimpleStoreMemory({\n maxSize: 50_000_000,\n ttl: 600e3,\n }),\n clientMetadataCache = new SimpleStoreMemory({\n maxSize: 50_000_000,\n ttl: 600e3,\n }),\n\n // OAuthHooks &\n // CreateDidResolverOptions &\n // CreateHandleResolverNodeOptions &\n // OAuthVerifierOptions &\n // DeviceManagerOptions &\n // Customization\n ...rest\n }: OAuthProviderOptions) {\n super({ replayStore, ...rest })\n\n // @NOTE: hooks don't really need a type parser, as all zod can actually\n // check at runtime is the fact that the values are functions. The only way\n // we would benefit from zod here would be to wrap the functions with a\n // validator for the provided function's return types, which we don't\n // really need if types are respected.\n this.hooks = rest\n\n this.accessTokenMode = accessTokenMode\n this.authenticationMaxAge = authenticationMaxAge\n this.metadata = buildMetadata(this.issuer, this.keyset, metadata)\n this.customization = customizationSchema.parse(rest)\n\n this.deviceManager = new DeviceManager(deviceStore, {\n ...rest,\n cookie: {\n ...rest.cookie,\n // \"secure\" defaults to \"true\" in DeviceManager. For the oauth routes to\n // work from localhost on Safari, we need to explicitly set secure to\n // false for localhost usage. This is not really an issue with Chrome\n // and Firefox, but Safari enforces it strictly.\n secure: !this.issuer.startsWith('http:'),\n },\n })\n this.hcaptchaManager = new HCaptchaManager(\n this.issuer,\n this.hooks,\n this.customization.hcaptcha,\n )\n this.rateLimitManager = new RateLimitManager(\n this.hcaptchaManager,\n rateLimits,\n )\n this.accountManager = new AccountManager(\n this.issuer,\n accountStore,\n this.hooks,\n createOAuthResolver({\n handleResolver: createHandleResolverNode({ ...rest, safeFetch }),\n didResolver: rest.didResolver,\n didCache: rest.didCache,\n onDidCacheError: rest.onDidCacheError,\n plcDirectoryUrl: rest.plcDirectoryUrl,\n fetch: safeFetch,\n allowHttp: rest.allowHttp,\n }),\n this.customization,\n )\n this.clientManager = new ClientManager(\n this.metadata,\n this.keyset,\n this.hooks,\n clientStore || null,\n loopbackMetadata || null,\n safeFetch,\n clientJwksCache,\n clientMetadataCache,\n )\n this.lexiconManager = new LexiconManager(lexiconStore, lexResolver)\n this.requestManager = new RequestManager(\n requestStore,\n this.lexiconManager,\n this.signer,\n this.metadata,\n this.hooks,\n )\n this.tokenManager = new TokenManager(\n tokenStore,\n this.lexiconManager,\n this.signer,\n this.hooks,\n this.accessTokenMode,\n tokenMaxAge,\n )\n }\n\n get jwks() {\n return this.keyset.publicJwks\n }\n\n /**\n * @returns true if the user's consent is required for the requested scopes\n */\n public checkConsentRequired(\n parameters: OAuthAuthorizationRequestParameters,\n clientData?: AuthorizedClientData,\n ) {\n // Client was never authorized before\n if (!clientData) return true\n\n // Client explicitly asked for consent\n if (parameters.prompt === 'consent') return true\n\n // No scope requested, and client is known by user, no consent required\n const requestedScopes = parameters.scope?.split(' ')\n if (requestedScopes == null) return false\n\n // Ensure that all requested scopes were previously authorized by the user\n const { authorizedScopes } = clientData\n return !requestedScopes.every((scope) => authorizedScopes.includes(scope))\n }\n\n public checkLoginRequired(deviceAccount: DeviceAccount) {\n return isOlderThan(deviceAccount.updatedAt, this.authenticationMaxAge)\n }\n\n protected async authenticateClient(\n clientCredentials: OAuthClientCredentials,\n dpopProof: null | DpopProof,\n options?: {\n allowMissingDpopProof?: boolean\n },\n ): Promise<{\n client: Client\n clientAuth: ClientAuth\n }> {\n const client = await this.clientManager.getClient(\n clientCredentials.client_id,\n )\n\n if (\n client.metadata.dpop_bound_access_tokens &&\n !dpopProof &&\n !options?.allowMissingDpopProof\n ) {\n throw new InvalidDpopProofError('DPoP proof required')\n }\n\n if (dpopProof && !client.metadata.dpop_bound_access_tokens) {\n throw new InvalidDpopProofError('DPoP proof not allowed for this client')\n }\n\n const clientAuth = await client.authenticate(clientCredentials, {\n authorizationServerIdentifier: this.issuer,\n })\n\n if (clientAuth.method === 'private_key_jwt') {\n // Clients MUST NOT use their client assertion key to sign DPoP proofs\n if (dpopProof && clientAuth.jkt === dpopProof.jkt) {\n throw new InvalidRequestError(\n 'The DPoP proof must be signed with a different key than the client assertion',\n )\n }\n\n // https://www.rfc-editor.org/rfc/rfc7523.html#section-3\n // > 7. [...] The authorization server MAY ensure that JWTs are not\n // > replayed by maintaining the set of used \"jti\" values for the\n // > length of time for which the JWT would be considered valid based\n // > on the applicable \"exp\" instant.\n\n const unique = await this.replayManager.uniqueAuth(\n clientAuth.jti,\n client.id,\n clientAuth.exp,\n )\n if (!unique) {\n throw new InvalidGrantError(`${clientAuth.method} jti reused`)\n }\n }\n\n return { client, clientAuth }\n }\n\n async decodeJAR(\n client: Client,\n input: OAuthAuthorizationRequestJar,\n ): Promise<OAuthAuthorizationRequestParameters> {\n const { payload } = await client.decodeRequestObject(\n input.request,\n this.issuer,\n )\n\n const { jti } = payload\n if (!jti) {\n throw new InvalidRequestError(\n 'Request object payload must contain a \"jti\" claim',\n )\n }\n if (!(await this.replayManager.uniqueJar(jti, client.id))) {\n throw new InvalidRequestError('Request object was replayed')\n }\n\n const parameters = await oauthAuthorizationRequestParametersSchema\n .parseAsync(payload)\n .catch((err) => {\n const msg = formatError(err, 'Invalid parameters in JAR')\n throw new InvalidRequestError(msg, err)\n })\n\n return parameters\n }\n\n /**\n * @see {@link https://datatracker.ietf.org/doc/html/rfc9126}\n */\n public async pushedAuthorizationRequest(\n credentials: OAuthClientCredentials,\n authorizationRequest: OAuthAuthorizationRequestPar,\n dpopProof: null | DpopProof,\n deviceMetadata: RequestMetadata,\n ): Promise<OAuthParResponse> {\n try {\n const { client, clientAuth } = await this.authenticateClient(\n credentials,\n dpopProof,\n // Allow missing DPoP header for PAR requests as rfc9449 allows it\n // (though the dpop_jkt parameter must be present in that case, see\n // check bellow).\n { allowMissingDpopProof: true },\n )\n\n await this.rateLimitManager.consume('pushed-authorization-request', {\n kind: 'client',\n deviceMetadata,\n client,\n clientAuth,\n })\n\n const parameters =\n 'request' in authorizationRequest // Handle JAR\n ? await this.decodeJAR(client, authorizationRequest)\n : authorizationRequest\n\n if (!parameters.dpop_jkt) {\n if (client.metadata.dpop_bound_access_tokens) {\n if (dpopProof) parameters.dpop_jkt = dpopProof.jkt\n else {\n // @NOTE When both PAR and DPoP are used, either the DPoP header, or\n // the dpop_jkt parameter must be present. We do not enforce this\n // for legacy reasons.\n // https://datatracker.ietf.org/doc/html/rfc9449#section-10.1\n }\n }\n } else {\n if (!client.metadata.dpop_bound_access_tokens) {\n throw new InvalidRequestError(\n 'DPoP bound access tokens are not enabled for this client',\n )\n }\n\n // Proof is optional if the dpop_jkt is provided, but if it is provided,\n // it must match the DPoP proof JKT.\n if (dpopProof && dpopProof.jkt !== parameters.dpop_jkt) {\n throw new InvalidDpopKeyBindingError()\n }\n }\n\n const { requestUri, expiresAt } =\n await this.requestManager.createAuthorizationRequest(\n client,\n clientAuth,\n parameters,\n null,\n )\n\n return {\n request_uri: requestUri,\n expires_in: dateToRelativeSeconds(expiresAt),\n }\n } catch (err) {\n // https://datatracker.ietf.org/doc/html/rfc9126#section-2.3-1\n // > Since initial processing of the pushed authorization request does not\n // > involve resource owner interaction, error codes related to user\n // > interaction, such as \"access_denied\", are never returned.\n if (err instanceof AuthorizationError && !isPARResponseError(err.error)) {\n throw new InvalidRequestError(err.error_description, err)\n }\n throw err\n }\n }\n\n /**\n * Only requests created through\n * {@link OAuthProvider.pushedAuthorizationRequest PAR} are accepted.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-11#section-4.1.1}\n * @see {@link https://datatracker.ietf.org/doc/html/rfc9126#section-4}\n */\n public async authorize(\n query: Extract<\n OAuthAuthorizationRequestQuery,\n OAuthAuthorizationRequestUri\n >,\n { deviceId, deviceMetadata }: DeviceInfo,\n ): Promise<AuthorizationResultRedirect | AuthorizationResultAuthorizePage> {\n const { issuer } = this\n\n const client = await this.clientManager.getClient(query.client_id)\n\n const requestUri = parseRequestUri(query.request_uri, {\n path: ['query', 'request_uri'],\n })\n const { parameters } = await this.requestManager.get(\n requestUri,\n deviceId,\n client.id,\n )\n\n try {\n const sessions = (\n await this.accountManager.listDeviceAccounts(deviceId)\n ).map((deviceAccount) => ({\n account: deviceAccount.account,\n\n // @TODO Return the session expiration date instead of a boolean to\n // avoid having to rely on a leeway when \"accepting\" the request.\n loginRequired:\n parameters.prompt === 'login' ||\n this.checkLoginRequired(deviceAccount),\n consentRequired: this.checkConsentRequired(\n parameters,\n deviceAccount.authorizedClients.get(client.id),\n ),\n }))\n\n // https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest\n\n // prompt=select_account\n //\n // > The Authorization Server SHOULD prompt the End-User to select a user\n // > account. This enables an End-User who has multiple accounts at the\n // > Authorization Server to select amongst the multiple accounts that\n // > they might have current sessions for. If it cannot obtain an account\n // > selection choice made by the End-User, it MUST return an error,\n // > typically account_selection_required.\n if (parameters.prompt === 'select_account' && !sessions.length) {\n throw new AccountSelectionRequiredError(parameters)\n }\n\n const ssoSessions = sessions\n .filter(hasActiveAccount)\n .filter(matchesHint, parameters)\n\n // prompt=none\n //\n // > The Authorization Server MUST NOT display any authentication or\n // > consent user interface pages. An error is returned if an End-User is\n // > not already authenticated or the Client does not have pre-configured\n // > consent for the requested Claims or does not fulfill other conditions\n // > for processing the request. The error code will typically be\n // > login_required, interaction_required, or another code defined in\n // > Section 3.1.2.6. This can be used as a method to check for existing\n // > authentication and/or consent.\n if (parameters.prompt === 'none') {\n if (ssoSessions.length > 1) {\n throw new AccountSelectionRequiredError(parameters)\n }\n if (ssoSessions.length < 1) {\n throw new LoginRequiredError(parameters)\n }\n\n const ssoSession = ssoSessions[0]!\n if (ssoSession.loginRequired) {\n throw new LoginRequiredError(parameters)\n }\n if (ssoSession.consentRequired) {\n throw new ConsentRequiredError(parameters)\n }\n\n const { code } = await this.requestManager.setAuthorized(\n requestUri,\n client,\n ssoSession.account,\n deviceId,\n deviceMetadata,\n )\n\n return { issuer, parameters, redirect: { code } }\n }\n\n // Automatic SSO when a hint was provided that matches a single session\n if (parameters.prompt == null && parameters.login_hint != null) {\n if (ssoSessions.length === 1) {\n const ssoSession = ssoSessions[0]!\n if (!ssoSession.loginRequired && !ssoSession.consentRequired) {\n const { code } = await this.requestManager.setAuthorized(\n requestUri,\n client,\n ssoSession.account,\n deviceId,\n deviceMetadata,\n )\n\n return { issuer, parameters, redirect: { code } }\n }\n }\n }\n\n return {\n issuer,\n client,\n parameters,\n requestUri,\n sessions: sessions\n // Strip un-necessary information (like consentRequired)\n .map(({ account, loginRequired }) => ({ account, loginRequired })),\n selectedDid:\n parameters.prompt == null ||\n parameters.prompt === 'login' ||\n parameters.prompt === 'consent'\n ? sessions.find(matchesHint, parameters)?.account.did\n : undefined,\n loginHint: await resolveLoginHint(\n parameters.login_hint,\n this.accountManager,\n ),\n permissionSets: await this.lexiconManager\n .getPermissionSetsFromScope(parameters.scope)\n .catch((cause) => {\n throw new AuthorizationError(\n parameters,\n 'Unable to retrieve permission sets',\n 'invalid_scope',\n cause,\n )\n }),\n }\n } catch (err) {\n try {\n await this.requestManager.delete(requestUri)\n } catch {\n // There are two error here. Better keep the outer one.\n //\n // @TODO Maybe move this entire code to the /authorize endpoint\n // (allowing to log this error)\n }\n\n throw AuthorizationError.from(parameters, err)\n }\n }\n\n public async token(\n clientCredentials: OAuthClientCredentials,\n clientMetadata: RequestMetadata,\n request: OAuthTokenRequest,\n dpopProof: null | DpopProof,\n ): Promise<OAuthTokenResponse> {\n const { client, clientAuth } = await this.authenticateClient(\n clientCredentials,\n dpopProof,\n )\n\n if (!this.metadata.grant_types_supported?.includes(request.grant_type)) {\n throw new InvalidGrantError(\n `Grant type \"${request.grant_type}\" is not supported by the server`,\n )\n }\n\n if (!client.metadata.grant_types.includes(request.grant_type)) {\n throw new InvalidGrantError(\n `\"${request.grant_type}\" grant type is not allowed for this client`,\n )\n }\n\n if (request.grant_type === 'authorization_code') {\n return this.authorizationCodeGrant(\n client,\n clientAuth,\n clientMetadata,\n request,\n dpopProof,\n )\n }\n\n if (request.grant_type === 'refresh_token') {\n return this.refreshTokenGrant(\n client,\n clientAuth,\n clientMetadata,\n request,\n dpopProof,\n )\n }\n\n throw new InvalidGrantError(\n `Grant type \"${request.grant_type}\" not supported`,\n )\n }\n\n protected async compareClientAuth(\n client: Client,\n clientAuth: ClientAuth,\n dpopProof: null | DpopProof,\n initial: {\n parameters: OAuthAuthorizationRequestParameters\n clientId: ClientId\n clientAuth: null | ClientAuth | ClientAuthLegacy\n },\n ): Promise<void> {\n // Fool proofing, ensure that the client is authenticating using the right method\n if (clientAuth.method !== client.metadata.token_endpoint_auth_method) {\n throw new InvalidGrantError(\n `Client authentication method mismatch (expected ${client.metadata.token_endpoint_auth_method}, got ${clientAuth.method})`,\n )\n }\n\n if (initial.clientId !== client.id) {\n throw new InvalidGrantError(`Token was not issued to this client`)\n }\n\n const { parameters } = initial\n if (parameters.dpop_jkt) {\n if (!dpopProof) {\n throw new InvalidGrantError(`DPoP proof is required for this request`)\n } else if (parameters.dpop_jkt !== dpopProof.jkt) {\n throw new InvalidGrantError(\n `DPoP proof does not match the expected JKT`,\n )\n }\n }\n\n if (!initial.clientAuth) {\n // Sessions whose authorization request was not pushed (PAR) were not\n // authenticated when the request was created. Since the token exchange\n // currently taking place *is* authenticated (`clientAuth`), we allow\n // \"upgrading\" the authentication method (the token created will be bound\n // to the current clientAuth).\n return\n }\n\n switch (initial.clientAuth.method) {\n case CLIENT_ASSERTION_TYPE_JWT_BEARER: // LEGACY\n case 'private_key_jwt':\n if (clientAuth.method !== 'private_key_jwt') {\n throw new InvalidGrantError(\n `Client authentication method mismatch (expected ${initial.clientAuth.method})`,\n )\n }\n if (\n clientAuth.kid !== initial.clientAuth.kid ||\n clientAuth.alg !== initial.clientAuth.alg ||\n clientAuth.jkt !== initial.clientAuth.jkt\n ) {\n throw new InvalidGrantError(\n `The session was initiated with a different key than the client assertion currently used`,\n )\n }\n break\n case 'none':\n // @NOTE We allow the client to \"upgrade\" to a confidential client if\n // the session was initially created without client authentication.\n break\n default:\n throw new InvalidGrantError(\n // @ts-expect-error (future proof, backwards compatibility)\n `Invalid method \"${initial.clientAuth.method}\"`,\n )\n }\n }\n\n protected async authorizationCodeGrant(\n client: Client,\n clientAuth: ClientAuth,\n clientMetadata: RequestMetadata,\n input: OAuthAuthorizationCodeGrantTokenRequest,\n dpopProof: null | DpopProof,\n ): Promise<OAuthTokenResponse> {\n const code = await codeSchema\n .parseAsync(input.code, { path: ['code'] })\n .catch((err) => {\n const msg = formatError(err, 'Invalid code')\n throw new InvalidGrantError(msg, err)\n })\n\n const data = await this.requestManager\n .consumeCode(code)\n .catch(async (err) => {\n // Code not found in request manager: delete the existing OAuth session\n // if the code was replayed (already converted into a token)\n const tokenInfo = await this.tokenManager.findByCode(code)\n if (tokenInfo) {\n await this.tokenManager.deleteToken(tokenInfo.id)\n }\n\n throw InvalidGrantError.from(err, `Invalid code`)\n })\n\n // @NOTE at this point, the request data was removed from the store and only\n // exists in memory here (in the \"data\" variable). Because of this, any\n // error thrown after this point will permanently cause the request data to\n // be lost.\n\n await this.compareClientAuth(client, clientAuth, dpopProof, data)\n\n // If the DPoP proof was not provided earlier (PAR / authorize), let's add\n // it now.\n const parameters =\n dpopProof &&\n client.metadata.dpop_bound_access_tokens &&\n !data.parameters.dpop_jkt\n ? { ...data.parameters, dpop_jkt: dpopProof.jkt }\n : data.parameters\n\n await this.validateCodeGrant(parameters, input)\n\n const accountData = await this.accountManager.getAccount(data.did)\n\n if (!accountData) {\n throw new InvalidGrantError('Account no longer exists')\n }\n\n return this.tokenManager.createToken(\n client,\n clientAuth,\n clientMetadata,\n accountData.account,\n data.deviceId,\n parameters,\n code,\n )\n }\n\n protected async validateCodeGrant(\n parameters: OAuthAuthorizationRequestParameters,\n input: OAuthAuthorizationCodeGrantTokenRequest,\n ): Promise<void> {\n if (parameters.redirect_uri !== input.redirect_uri) {\n throw new InvalidGrantError(\n 'The redirect_uri parameter must match the one used in the authorization request',\n )\n }\n\n if (parameters.code_challenge) {\n if (!input.code_verifier) {\n throw new InvalidGrantError('code_verifier is required')\n }\n if (input.code_verifier.length < 43) {\n throw new InvalidGrantError('code_verifier too short')\n }\n switch (parameters.code_challenge_method) {\n case undefined: // default is \"plain\"\n case 'plain':\n if (parameters.code_challenge !== input.code_verifier) {\n throw new InvalidGrantError('Invalid code_verifier')\n }\n break\n\n case 'S256': {\n const inputChallenge = Buffer.from(\n parameters.code_challenge,\n 'base64',\n )\n const computedChallenge = createHash('sha256')\n .update(input.code_verifier)\n .digest()\n if (inputChallenge.compare(computedChallenge) !== 0) {\n throw new InvalidGrantError('Invalid code_verifier')\n }\n break\n }\n\n default:\n // Should never happen (because request validation should catch this)\n throw new Error(`Unsupported code_challenge_method`)\n }\n const unique = await this.replayManager.uniqueCodeChallenge(\n parameters.code_challenge,\n )\n if (!unique) {\n throw new InvalidGrantError('Code challenge already used')\n }\n } else if (input.code_verifier !== undefined) {\n throw new InvalidRequestError(\"code_challenge parameter wasn't provided\")\n }\n }\n\n protected async refreshTokenGrant(\n client: Client,\n clientAuth: ClientAuth,\n clientMetadata: RequestMetadata,\n input: OAuthRefreshTokenGrantTokenRequest,\n dpopProof: null | DpopProof,\n ): Promise<OAuthTokenResponse> {\n const refreshToken = await refreshTokenSchema\n .parseAsync(input.refresh_token, { path: ['refresh_token'] })\n .catch((err) => {\n const msg = formatError(err, 'Invalid refresh token')\n throw new InvalidGrantError(msg, err)\n })\n\n const tokenInfo = await this.tokenManager.consumeRefreshToken(refreshToken)\n\n try {\n const { data } = tokenInfo\n const now = new Date()\n\n await this.compareClientAuth(client, clientAuth, dpopProof, data)\n await this.validateRefreshGrant(client, data, now)\n\n return await this.tokenManager.rotateToken(\n client,\n clientAuth,\n clientMetadata,\n tokenInfo,\n now,\n )\n } catch (err) {\n await this.tokenManager.deleteToken(tokenInfo.id)\n\n throw err\n }\n }\n\n protected async validateRefreshGrant(\n client: Client,\n data: TokenData,\n now = new Date(),\n ): Promise<void> {\n if (!client.metadata.grant_types.includes('refresh_token')) {\n throw new InvalidGrantError(`Refresh token grant not allowed`)\n }\n\n const sessionAge = now.getTime() - data.createdAt.getTime()\n\n if (sessionAge > client.sessionLifetime) {\n throw new InvalidGrantError(`Session expired`)\n }\n\n const refreshAge = now.getTime() - data.updatedAt.getTime()\n if (refreshAge > client.refreshLifetime) {\n throw new InvalidGrantError(`Refresh token expired`)\n }\n }\n\n /**\n * @see {@link https://datatracker.ietf.org/doc/html/rfc7009#section-2.1 rfc7009}\n */\n public async revoke(\n clientCredentials: OAuthClientCredentials,\n { token }: OAuthTokenIdentification,\n dpopProof: null | DpopProof,\n ) {\n // > The authorization server first validates the client credentials (in\n // > case of a confidential client)\n const { client, clientAuth } = await this.authenticateClient(\n clientCredentials,\n dpopProof,\n )\n\n const tokenInfo = await this.tokenManager.findToken(token)\n if (tokenInfo) {\n // > [...] and then verifies whether the token was issued to the client\n // > making the revocation request.\n const { data } = tokenInfo\n await this.compareClientAuth(client, clientAuth, dpopProof, data)\n\n // > In the next step, the authorization server invalidates the token. The\n // > invalidation takes place immediately, and the token cannot be used\n // > again after the revocation.\n await this.tokenManager.deleteToken(tokenInfo.id)\n }\n }\n\n protected override async decodeToken(\n tokenType: OAuthTokenType,\n token: OAuthAccessToken,\n dpopProof: null | DpopProof,\n ): Promise<AccessTokenPayload> {\n const tokenPayload = await super.decodeToken(tokenType, token, dpopProof)\n\n if (this.accessTokenMode !== AccessTokenMode.stateless) {\n // @NOTE in non stateless mode, some claims can be omitted (most notably\n // \"scope\"). We load the token claims here (allowing to ensure that the\n // token is still valid, and to retrieve a (potentially updated) set of\n // claims).\n\n const tokenClaims = await this.tokenManager.loadTokenClaims(\n tokenType,\n tokenPayload,\n )\n\n Object.assign(tokenPayload, tokenClaims)\n }\n\n return tokenPayload\n }\n}\n\nfunction matchesHint(\n this: OAuthAuthorizationRequestParameters,\n { account }: { account: Account },\n): boolean {\n const hint = this.login_hint\n if (!hint) return false\n\n return account.did === hint || account.handle === hint\n}\n\nfunction hasActiveAccount({ account }: { account: Account }): boolean {\n return !account.deactivated\n}\n"]}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { HCaptchaManager } from '../hcaptcha/hcaptcha-manager.js';
|
|
2
|
+
import { type RateLimitContext, type RateLimitKeyGetter, type RateLimitPolicyContexts, type RateLimitPolicyName, type RateLimitsOptions } from './rate-limit-policies.js';
|
|
3
|
+
import type { RateLimiter } from './rate-limiter.js';
|
|
4
|
+
type Tier = 'captcha' | 'block';
|
|
5
|
+
type BoundRule<C extends RateLimitContext> = {
|
|
6
|
+
key: RateLimitKeyGetter<C>;
|
|
7
|
+
limiter: RateLimiter;
|
|
8
|
+
};
|
|
9
|
+
type BoundPolicy<C extends RateLimitContext> = Record<Tier, readonly BoundRule<C>[]>;
|
|
10
|
+
type BoundPolicies = {
|
|
11
|
+
readonly [P in RateLimitPolicyName]: BoundPolicy<RateLimitPolicyContexts[P]>;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Enforces the {@link RateLimitsOptions.policies rate limit policies}. When a
|
|
15
|
+
* policy has a captcha tier, exceeding it requires a valid hCaptcha token
|
|
16
|
+
* (verified through the {@link HCaptchaManager}), while exceeding the block
|
|
17
|
+
* tier rejects the request.
|
|
18
|
+
*
|
|
19
|
+
* When no rate limits are configured, only the default rules that have no
|
|
20
|
+
* points (which need no storage) are enforced.
|
|
21
|
+
*/
|
|
22
|
+
export declare class RateLimitManager {
|
|
23
|
+
protected readonly hcaptchaManager: HCaptchaManager;
|
|
24
|
+
protected readonly policies: BoundPolicies;
|
|
25
|
+
constructor(hcaptchaManager: HCaptchaManager, options?: RateLimitsOptions);
|
|
26
|
+
/**
|
|
27
|
+
* Consumes one point from every applicable rule of the `action`'s policy.
|
|
28
|
+
* When a captcha tier rule is exceeded, the hCaptcha token of the form input
|
|
29
|
+
* (`ctx.data`) is verified.
|
|
30
|
+
*
|
|
31
|
+
* @throws {RateLimitExceededError} if any block tier rule is exceeded
|
|
32
|
+
* @throws {CaptchaRequiredError} if any captcha tier rule is exceeded and the
|
|
33
|
+
* form input carries no hCaptcha token
|
|
34
|
+
* @throws {CaptchaRejectedError} if the hCaptcha token's verification failed
|
|
35
|
+
*/
|
|
36
|
+
consume<P extends RateLimitPolicyName>(policy: P, ctx: RateLimitPolicyContexts[P]): Promise<void>;
|
|
37
|
+
}
|
|
38
|
+
export {};
|
|
39
|
+
//# sourceMappingURL=rate-limit-manager.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rate-limit-manager.d.ts","sourceRoot":"","sources":["../../src/rate-limit/rate-limit-manager.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iCAAiC,CAAA;AACtE,OAAO,EAEL,KAAK,gBAAgB,EAErB,KAAK,kBAAkB,EACvB,KAAK,uBAAuB,EAC5B,KAAK,mBAAmB,EAExB,KAAK,iBAAiB,EAEvB,MAAM,0BAA0B,CAAA;AACjC,OAAO,KAAK,EAAE,WAAW,EAA4B,MAAM,mBAAmB,CAAA;AAE9E,KAAK,IAAI,GAAG,SAAS,GAAG,OAAO,CAAA;AAE/B,KAAK,SAAS,CAAC,CAAC,SAAS,gBAAgB,IAAI;IAC3C,GAAG,EAAE,kBAAkB,CAAC,CAAC,CAAC,CAAA;IAC1B,OAAO,EAAE,WAAW,CAAA;CACrB,CAAA;AAED,KAAK,WAAW,CAAC,CAAC,SAAS,gBAAgB,IAAI,MAAM,CACnD,IAAI,EACJ,SAAS,SAAS,CAAC,CAAC,CAAC,EAAE,CACxB,CAAA;AAED,KAAK,aAAa,GAAG;IACnB,QAAQ,EAAE,CAAC,IAAI,mBAAmB,GAAG,WAAW,CAAC,uBAAuB,CAAC,CAAC,CAAC,CAAC;CAC7E,CAAA;AAED;;;;;;;;GAQG;AACH,qBAAa,gBAAgB;IAIzB,SAAS,CAAC,QAAQ,CAAC,eAAe,EAAE,eAAe;IAHrD,SAAS,CAAC,QAAQ,CAAC,QAAQ,EAAE,aAAa,CAAA;IAE1C,YACqB,eAAe,EAAE,eAAe,EACnD,OAAO,CAAC,EAAE,iBAAiB,EAiE5B;IAED;;;;;;;;;OASG;IACU,OAAO,CAAC,CAAC,SAAS,mBAAmB,EAChD,MAAM,EAAE,CAAC,EACT,GAAG,EAAE,uBAAuB,CAAC,CAAC,CAAC,GAC9B,OAAO,CAAC,IAAI,CAAC,CAwBf;CACF"}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { RateLimitExceededError } from '../errors/rate-limit-exceeded-error.js';
|
|
2
|
+
import { DEFAULT_RATE_LIMIT_POLICIES, isRateLimitDevicePolicyName, } from './rate-limit-policies.js';
|
|
3
|
+
/**
|
|
4
|
+
* Enforces the {@link RateLimitsOptions.policies rate limit policies}. When a
|
|
5
|
+
* policy has a captcha tier, exceeding it requires a valid hCaptcha token
|
|
6
|
+
* (verified through the {@link HCaptchaManager}), while exceeding the block
|
|
7
|
+
* tier rejects the request.
|
|
8
|
+
*
|
|
9
|
+
* When no rate limits are configured, only the default rules that have no
|
|
10
|
+
* points (which need no storage) are enforced.
|
|
11
|
+
*/
|
|
12
|
+
export class RateLimitManager {
|
|
13
|
+
constructor(hcaptchaManager, options) {
|
|
14
|
+
this.hcaptchaManager = hcaptchaManager;
|
|
15
|
+
const bindRules = (policy, tier, rules = []) => rules.flatMap(({ key, points, durationMs }, index) => {
|
|
16
|
+
if (points <= 0) {
|
|
17
|
+
return [{ key, limiter: exceededLimiter(points, durationMs) }];
|
|
18
|
+
}
|
|
19
|
+
if (!options)
|
|
20
|
+
return [];
|
|
21
|
+
// @NOTE The name is likely to be used as a storage key prefix by the
|
|
22
|
+
// factory, so it must be stable across deploys. Since rules are only
|
|
23
|
+
// identified by their position, the window is part of the name: should
|
|
24
|
+
// the rules of a tier be reordered, a rule must never inherit the
|
|
25
|
+
// counters of a rule with a different window (e.g. a 5 minutes rule
|
|
26
|
+
// inheriting a daily count would block its keys for up to a day).
|
|
27
|
+
const name = `oauth-${policy}-${tier}-${index}-${durationMs}`;
|
|
28
|
+
return [
|
|
29
|
+
{
|
|
30
|
+
key,
|
|
31
|
+
limiter: options.factory({ name, points, durationMs }),
|
|
32
|
+
},
|
|
33
|
+
];
|
|
34
|
+
});
|
|
35
|
+
const bindPolicy = (policy, defaults) => {
|
|
36
|
+
const supportsCaptcha = isRateLimitDevicePolicyName(policy);
|
|
37
|
+
const { captcha, block } = (options?.policies?.[policy] || {});
|
|
38
|
+
// @NOTE Enforced by the types, unless they were bypassed
|
|
39
|
+
if (!supportsCaptcha && captcha != null) {
|
|
40
|
+
throw new TypeError(`The "${policy}" rate limit policy does not support a captcha tier`);
|
|
41
|
+
}
|
|
42
|
+
const boundPolicy = {
|
|
43
|
+
captcha: hcaptchaManager.enabled && supportsCaptcha
|
|
44
|
+
? bindRules(policy, 'captcha', captcha ?? defaults.captcha)
|
|
45
|
+
: [],
|
|
46
|
+
block: bindRules(policy, 'block', block ?? defaults.block),
|
|
47
|
+
};
|
|
48
|
+
return boundPolicy;
|
|
49
|
+
};
|
|
50
|
+
this.policies = Object.fromEntries(Object.entries(DEFAULT_RATE_LIMIT_POLICIES).map(([name, defaults]) => [name, bindPolicy(name, defaults)]));
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Consumes one point from every applicable rule of the `action`'s policy.
|
|
54
|
+
* When a captcha tier rule is exceeded, the hCaptcha token of the form input
|
|
55
|
+
* (`ctx.data`) is verified.
|
|
56
|
+
*
|
|
57
|
+
* @throws {RateLimitExceededError} if any block tier rule is exceeded
|
|
58
|
+
* @throws {CaptchaRequiredError} if any captcha tier rule is exceeded and the
|
|
59
|
+
* form input carries no hCaptcha token
|
|
60
|
+
* @throws {CaptchaRejectedError} if the hCaptcha token's verification failed
|
|
61
|
+
*/
|
|
62
|
+
async consume(policy, ctx) {
|
|
63
|
+
const bound = this.policies[policy];
|
|
64
|
+
const [captchaResults, blockResults] = await Promise.all([
|
|
65
|
+
consumeAll(bound.captcha, ctx),
|
|
66
|
+
consumeAll(bound.block, ctx),
|
|
67
|
+
]);
|
|
68
|
+
if (blockResults.some(isExceeded)) {
|
|
69
|
+
const msBeforeNext = Math.max(...blockResults.filter(isExceeded).map((s) => s.msBeforeNext));
|
|
70
|
+
throw new RateLimitExceededError(msBeforeNext);
|
|
71
|
+
}
|
|
72
|
+
// @NOTE the kind check is only necessary for TS: BoundPolicy will never
|
|
73
|
+
// have any captcha rules for non-device contexts (see supportsCaptcha)
|
|
74
|
+
if (ctx.kind === 'device' && captchaResults.some(isExceeded)) {
|
|
75
|
+
await this.hcaptchaManager.verify(ctx.deviceId, ctx.deviceMetadata, ctx.data);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* The limiter of a rule that has no points: every request exceeds it.
|
|
81
|
+
*/
|
|
82
|
+
function exceededLimiter(points, durationMs) {
|
|
83
|
+
return {
|
|
84
|
+
consume: async (_key, consumed) => ({
|
|
85
|
+
remainingPoints: points - consumed,
|
|
86
|
+
msBeforeNext: durationMs,
|
|
87
|
+
}),
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
function consumeAll(rules, ctx) {
|
|
91
|
+
return Promise.all(rules.flatMap(({ key, limiter }) => {
|
|
92
|
+
const keyValue = key(ctx);
|
|
93
|
+
return keyValue == null ? [] : [limiter.consume(keyValue, 1)];
|
|
94
|
+
}));
|
|
95
|
+
}
|
|
96
|
+
function isExceeded(result) {
|
|
97
|
+
return result.remainingPoints < 0;
|
|
98
|
+
}
|
|
99
|
+
//# sourceMappingURL=rate-limit-manager.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rate-limit-manager.js","sourceRoot":"","sources":["../../src/rate-limit/rate-limit-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAA;AAE/E,OAAO,EACL,2BAA2B,EAQ3B,2BAA2B,GAC5B,MAAM,0BAA0B,CAAA;AAmBjC;;;;;;;;GAQG;AACH,MAAM,OAAO,g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C,IAAI,KAAK,QAAQ,IAAI,cAAc,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;YAC7D,MAAM,IAAI,CAAC,eAAe,CAAC,MAAM,CAC/B,GAAG,CAAC,QAAQ,EACZ,GAAG,CAAC,cAAc,EAClB,GAAG,CAAC,IAAI,CACT,CAAA;QACH,CAAC;IACH,CAAC;CACF;AAED;;GAEG;AACH,SAAS,eAAe,CAAC,MAAc,EAAE,UAAkB;IACzD,OAAO;QACL,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,EAAE,CAAC,CAAC;YAClC,eAAe,EAAE,MAAM,GAAG,QAAQ;YAClC,YAAY,EAAE,UAAU;SACzB,CAAC;KACH,CAAA;AACH,CAAC;AAED,SAAS,UAAU,CACjB,KAA8B,EAC9B,GAAM;IAEN,OAAO,OAAO,CAAC,GAAG,CAChB,KAAK,CAAC,OAAO,CAAC,CAAC,EAAE,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE;QACjC,MAAM,QAAQ,GAAG,GAAG,CAAC,GAAG,CAAC,CAAA;QACzB,OAAO,QAAQ,IAAI,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAA;IAC/D,CAAC,CAAC,CACH,CAAA;AACH,CAAC;AAED,SAAS,UAAU,CAAC,MAAgC;IAClD,OAAO,MAAM,CAAC,eAAe,GAAG,CAAC,CAAA;AACnC,CAAC","sourcesContent":["import { RateLimitExceededError } from '../errors/rate-limit-exceeded-error.js'\nimport type { HCaptchaManager } from '../hcaptcha/hcaptcha-manager.js'\nimport {\n DEFAULT_RATE_LIMIT_POLICIES,\n type RateLimitContext,\n type RateLimitDevicePolicy,\n type RateLimitKeyGetter,\n type RateLimitPolicyContexts,\n type RateLimitPolicyName,\n type RateLimitRule,\n type RateLimitsOptions,\n isRateLimitDevicePolicyName,\n} from './rate-limit-policies.js'\nimport type { RateLimiter, RateLimiterConsumeResult } from './rate-limiter.js'\n\ntype Tier = 'captcha' | 'block'\n\ntype BoundRule<C extends RateLimitContext> = {\n key: RateLimitKeyGetter<C>\n limiter: RateLimiter\n}\n\ntype BoundPolicy<C extends RateLimitContext> = Record<\n Tier,\n readonly BoundRule<C>[]\n>\n\ntype BoundPolicies = {\n readonly [P in RateLimitPolicyName]: BoundPolicy<RateLimitPolicyContexts[P]>\n}\n\n/**\n * Enforces the {@link RateLimitsOptions.policies rate limit policies}. When a\n * policy has a captcha tier, exceeding it requires a valid hCaptcha token\n * (verified through the {@link HCaptchaManager}), while exceeding the block\n * tier rejects the request.\n *\n * When no rate limits are configured, only the default rules that have no\n * points (which need no storage) are enforced.\n */\nexport class RateLimitManager {\n protected readonly policies: BoundPolicies\n\n constructor(\n protected readonly hcaptchaManager: HCaptchaManager,\n options?: RateLimitsOptions,\n ) {\n const bindRules = <C extends RateLimitContext>(\n policy: RateLimitPolicyName,\n tier: Tier,\n rules: readonly RateLimitRule<C>[] = [],\n ): BoundRule<C>[] =>\n rules.flatMap(({ key, points, durationMs }, index) => {\n if (points <= 0) {\n return [{ key, limiter: exceededLimiter(points, durationMs) }]\n }\n\n if (!options) return []\n\n // @NOTE The name is likely to be used as a storage key prefix by the\n // factory, so it must be stable across deploys. Since rules are only\n // identified by their position, the window is part of the name: should\n // the rules of a tier be reordered, a rule must never inherit the\n // counters of a rule with a different window (e.g. a 5 minutes rule\n // inheriting a daily count would block its keys for up to a day).\n const name = `oauth-${policy}-${tier}-${index}-${durationMs}`\n\n return [\n {\n key,\n limiter: options.factory({ name, points, durationMs }),\n },\n ]\n })\n\n const bindPolicy = <P extends RateLimitPolicyName>(\n policy: P,\n defaults: RateLimitDevicePolicy,\n ): BoundPolicy<RateLimitPolicyContexts[P]> => {\n const supportsCaptcha = isRateLimitDevicePolicyName(policy)\n const { captcha, block } = (options?.policies?.[policy] || {}) as Partial<\n RateLimitDevicePolicy<any>\n >\n\n // @NOTE Enforced by the types, unless they were bypassed\n if (!supportsCaptcha && captcha != null) {\n throw new TypeError(\n `The \"${policy}\" rate limit policy does not support a captcha tier`,\n )\n }\n\n const boundPolicy: BoundPolicy<any> = {\n captcha:\n hcaptchaManager.enabled && supportsCaptcha\n ? bindRules(policy, 'captcha', captcha ?? defaults.captcha)\n : [],\n block: bindRules(policy, 'block', block ?? defaults.block),\n }\n\n return boundPolicy\n }\n\n this.policies = Object.fromEntries(\n (\n Object.entries(DEFAULT_RATE_LIMIT_POLICIES) as [\n RateLimitPolicyName,\n RateLimitDevicePolicy,\n ][]\n ).map(([name, defaults]) => [name, bindPolicy(name, defaults)]),\n ) as BoundPolicies\n }\n\n /**\n * Consumes one point from every applicable rule of the `action`'s policy.\n * When a captcha tier rule is exceeded, the hCaptcha token of the form input\n * (`ctx.data`) is verified.\n *\n * @throws {RateLimitExceededError} if any block tier rule is exceeded\n * @throws {CaptchaRequiredError} if any captcha tier rule is exceeded and the\n * form input carries no hCaptcha token\n * @throws {CaptchaRejectedError} if the hCaptcha token's verification failed\n */\n public async consume<P extends RateLimitPolicyName>(\n policy: P,\n ctx: RateLimitPolicyContexts[P],\n ): Promise<void> {\n const bound: BoundPolicy<RateLimitPolicyContexts[P]> = this.policies[policy]\n\n const [captchaResults, blockResults] = await Promise.all([\n consumeAll(bound.captcha, ctx),\n consumeAll(bound.block, ctx),\n ])\n\n if (blockResults.some(isExceeded)) {\n const msBeforeNext = Math.max(\n ...blockResults.filter(isExceeded).map((s) => s.msBeforeNext),\n )\n throw new RateLimitExceededError(msBeforeNext)\n }\n\n // @NOTE the kind check is only necessary for TS: BoundPolicy will never\n // have any captcha rules for non-device contexts (see supportsCaptcha)\n if (ctx.kind === 'device' && captchaResults.some(isExceeded)) {\n await this.hcaptchaManager.verify(\n ctx.deviceId,\n ctx.deviceMetadata,\n ctx.data,\n )\n }\n }\n}\n\n/**\n * The limiter of a rule that has no points: every request exceeds it.\n */\nfunction exceededLimiter(points: number, durationMs: number): RateLimiter {\n return {\n consume: async (_key, consumed) => ({\n remainingPoints: points - consumed,\n msBeforeNext: durationMs,\n }),\n }\n}\n\nfunction consumeAll<C extends RateLimitContext>(\n rules: readonly BoundRule<C>[],\n ctx: C,\n): Promise<RateLimiterConsumeResult[]> {\n return Promise.all(\n rules.flatMap(({ key, limiter }) => {\n const keyValue = key(ctx)\n return keyValue == null ? [] : [limiter.consume(keyValue, 1)]\n }),\n )\n}\n\nfunction isExceeded(result: RateLimiterConsumeResult): boolean {\n return result.remainingPoints < 0\n}\n"]}
|