@atproto/oauth-provider 0.25.1 → 0.25.2

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 CHANGED
@@ -1,5 +1,16 @@
1
1
  # @atproto/oauth-provider
2
2
 
3
+ ## 0.25.2
4
+
5
+ ### Patch Changes
6
+
7
+ - [#5747](https://github.com/bluesky-social/atproto/pull/5747) [`63bc474`](https://github.com/bluesky-social/atproto/commit/63bc4747175c82497596e9ffaeaaaf83804b0311) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Record the scopes a user approved on the consent screen, not the scopes the client requested.
8
+
9
+ - [#5753](https://github.com/bluesky-social/atproto/pull/5753) [`3bfd00f`](https://github.com/bluesky-social/atproto/commit/3bfd00f484dc144482c82a4ed248adc49e6be769) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Bound the decoded size of every stage of a multi-coding `content-encoding` chain, and reject bodies listing too many content-codings
10
+ - Updated dependencies [[`3bfd00f`](https://github.com/bluesky-social/atproto/commit/3bfd00f484dc144482c82a4ed248adc49e6be769), [`3bfd00f`](https://github.com/bluesky-social/atproto/commit/3bfd00f484dc144482c82a4ed248adc49e6be769), [`3bfd00f`](https://github.com/bluesky-social/atproto/commit/3bfd00f484dc144482c82a4ed248adc49e6be769), [`3bfd00f`](https://github.com/bluesky-social/atproto/commit/3bfd00f484dc144482c82a4ed248adc49e6be769)]:
11
+ - @atproto/common@0.8.7
12
+ - @atproto/lex-resolver@0.4.1
13
+
3
14
  ## 0.25.1
4
15
 
5
16
  ### Patch Changes
@@ -1 +1 @@
1
- {"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../../../src/lib/http/stream.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,WAAW,CAAA;AAChD,OAAO,EAAe,KAAK,QAAQ,EAAY,MAAM,aAAa,CAAA;AAOlE,OAAO,EACL,KAAK,UAAU,EAEf,KAAK,YAAY,EAGlB,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import createHttpError from 'http-errors';
3
- import { MaxSizeChecker, createDecoders, streamToNodeBuffer, } from '@atproto/common';
3
+ import { createDecoders, streamToNodeBuffer } from '@atproto/common';
4
4
  import { parseContentType, parsers, } from './parser.js';
5
5
  /**
6
6
  * Bounds the decoded request body, whichever content-encoding it arrived with.
@@ -11,10 +11,10 @@ export const DEFAULT_MAX_BODY_SIZE = 100 * 1024; // 100 KiB
11
11
  export function decodeHttpRequest(req, maxSize) {
12
12
  // @NOTE Content-Length counts the octets actually transferred, i.e. the
13
13
  // body *after* content-encoding. It therefore bounds the wire size, which
14
- // the MaxSizeChecker below does not (that one bounds the decoded size);
15
- // these are two distinct bounds that happen to share a constant. It is not
16
- // a substitute for the checker: the header is absent under chunked transfer
17
- // encoding, and a client may understate it.
14
+ // the `maxSize` passed to `createDecoders` below does not (that one bounds
15
+ // the decoded size); these are two distinct bounds that happen to share a
16
+ // constant. It is not a substitute for the decoded bound: the header is
17
+ // absent under chunked transfer encoding, and a client may understate it.
18
18
  const contentLength = req.headers['content-length'];
19
19
  if (contentLength != null) {
20
20
  const size = Number(contentLength);
@@ -26,12 +26,14 @@ export function decodeHttpRequest(req, maxSize) {
26
26
  }
27
27
  }
28
28
  try {
29
- // @NOTE The checker is applied even when the body is not encoded: nothing
30
- // else bounds the size of these requests.
29
+ // @NOTE `createDecoders` applies the decoded-size bound even when the body
30
+ // is not encoded: nothing else bounds the size of these requests.
31
31
  return pipeline([
32
32
  req,
33
- ...createDecoders(req.headers['content-encoding']),
34
- new MaxSizeChecker(maxSize, () => createHttpError(413, 'Payload too large')),
33
+ ...createDecoders(req.headers['content-encoding'], {
34
+ maxSize,
35
+ maxSizeError: () => createHttpError(413, 'Payload too large'),
36
+ }),
35
37
  ], () => { });
36
38
  }
37
39
  catch (cause) {
@@ -1 +1 @@
1
- {"version":3,"file":"stream.js","sourceRoot":"","sources":["../../../src/lib/http/stream.ts"],"names":[],"mappings":"AACA,OAAO,EAA8B,QAAQ,EAAE,MAAM,aAAa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S,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,0BAA0B,CAAA;QACzE,MAAM,eAAe,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,KAAK,EAAE,CAAC,CAAA;IAChD,CAAC;AACH,CAAC;AAED;;;;;GAKG;AAEH,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACpC,GAAoB,EACpB,KAAQ,EACR,OAAO,GAAW,qBAAqB;IAEvC,MAAM,IAAI,GAAG,gBAAgB,CAC3B,GAAG,CAAC,OAAO,CAAC,cAAc,CAAC,IAAI,0BAA0B,CAC1D,CAAA;IAED,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CACzB,CAAC,MAAM,EAAE,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAClE,CAAA;IAED,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,eAAe,CAAC,GAAG,EAAE,6BAA6B,IAAI,CAAC,IAAI,EAAE,CAAC,CAAA;IACtE,CAAC;IAED,MAAM,MAAM,GAAG,iBAAiB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAA;IAC9C,MAAM,MAAM,GAAG,MAAM,kBAAkB,CAAC,MAAM,CAAC,CAAA;IAC/C,OAAO,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,IAAI,CAE/B,CAAA;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,MAA0B;IAC1D,IAAI,KAAK,EAAE,MAAM,CAAC,IAAI,MAAM,EAAE,CAAC;QAC7B,mCAAmC;IACrC,CAAC;AACH,CAAC","sourcesContent":["import type { IncomingMessage } from 'node:http'\nimport { type Duplex, type Readable, pipeline } from 'node:stream'\nimport createHttpError from 'http-errors'\nimport {\n MaxSizeChecker,\n createDecoders,\n streamToNodeBuffer,\n} from '@atproto/common'\nimport {\n type KnownNames,\n type KnownParser,\n type ParserResult,\n parseContentType,\n parsers,\n} from './parser.js'\n\n/**\n * Bounds the decoded request body, whichever content-encoding it arrived with.\n * The payloads these routes legitimately carry are single-digit kilobytes, so\n * this leaves ample headroom.\n */\nexport const DEFAULT_MAX_BODY_SIZE = 100 * 1024 // 100 KiB\n\nexport function decodeHttpRequest(\n req: IncomingMessage,\n maxSize: number,\n): Readable {\n // @NOTE Content-Length counts the octets actually transferred, i.e. the\n // body *after* content-encoding. It therefore bounds the wire size, which\n // the MaxSizeChecker below does not (that one bounds the decoded size);\n // these are two distinct bounds that happen to share a constant. It is not\n // a substitute for the checker: the header is absent under chunked transfer\n // encoding, and a client may understate it.\n const contentLength = req.headers['content-length']\n if (contentLength != null) {\n const size = Number(contentLength)\n if (!Number.isInteger(size) || size < 0) {\n throw createHttpError(400, 'Invalid content-length')\n }\n if (size > maxSize) {\n throw createHttpError(413, 'Payload too large')\n }\n }\n\n try {\n // @NOTE The checker is applied even when the body is not encoded: nothing\n // else bounds the size of these requests.\n return pipeline(\n [\n req,\n ...createDecoders(req.headers['content-encoding']),\n new MaxSizeChecker(maxSize, () =>\n createHttpError(413, 'Payload too large'),\n ),\n ],\n () => {},\n ) as Duplex\n } catch (cause) {\n const message =\n cause instanceof TypeError ? cause.message : `Invalid content-encoding`\n throw createHttpError(415, message, { cause })\n }\n}\n\n/**\n * Generic method that parses a stream of unknown nature (HTTP request/response,\n * socket, file, etc.), but of known mime type, into a parsed object.\n *\n * @throws {TypeError} If the content-type is not valid or supported.\n */\n\nexport async function parseHttpRequest<A extends readonly KnownNames[]>(\n req: IncomingMessage,\n allow: A,\n maxSize: number = DEFAULT_MAX_BODY_SIZE,\n) {\n const type = parseContentType(\n req.headers['content-type'] ?? 'application/octet-stream',\n )\n\n const parser = parsers.find(\n (parser) => allow.includes(parser.name) && parser.test(type.mime),\n )\n\n if (!parser) {\n throw createHttpError(415, `Unsupported content-type: ${type.mime}`)\n }\n\n const stream = decodeHttpRequest(req, maxSize)\n const buffer = await streamToNodeBuffer(stream)\n return parser.parse(buffer, type) as ParserResult<\n Extract<KnownParser, { name: A[number] }>\n >\n}\n\nexport async function flushStream(stream: AsyncIterable<any>): Promise<void> {\n for await (const _ of stream) {\n // Consume the stream to completion\n }\n}\n"]}
1
+ {"version":3,"file":"stream.js","sourceRoot":"","sources":["../../../src/lib/http/stream.ts"],"names":[],"mappings":"AACA,OAAO,EAA8B,QAAQ,EAAE,MAAM,aAAa,CAAA;AAClE,OAAO,eAAe,MAAM,aAAa,CAAA;AACzC,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAA;AACpE,OAAO,EAIL,gBAAgB,EAChB,OAAO,GACR,MAAM,aAAa,CAAA;AAEpB;;;;GAIG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,GAAG,GAAG,IAAI,CAAA,CAAC,UAAU;AAE1D,MAAM,UAAU,iBAAiB,CAC/B,GAAoB,EACpB,OAAe;IAEf,wEAAwE;IACxE,0EAA0E;IAC1E,2EAA2E;IAC3E,0EAA0E;IAC1E,wEAAwE;IACxE,0EAA0E;IAC1E,MAAM,aAAa,GAAG,GAAG,CAAC,OAAO,CAAC,gBAAgB,CAAC,CAAA;IACnD,IAAI,aAAa,IAAI,IAAI,EAAE,CAAC;QAC1B,MAAM,IAAI,GAAG,MAAM,CAAC,aAAa,CAAC,CAAA;QAClC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,IAAI,GAAG,CAAC,EAAE,CAAC;YACxC,MAAM,eAAe,CAAC,GAAG,EAAE,wBAAwB,CAAC,CAAA;QACtD,CAAC;QACD,IAAI,IAAI,GAAG,OAAO,EAAE,CAAC;YACnB,MAAM,eAAe,CAAC,GAAG,EAAE,mBAAmB,CAAC,CAAA;QACjD,CAAC;IACH,CAAC;IAED,IAAI,CAAC;QACH,2EAA2E;QAC3E,kEAAkE;QAClE,OAAO,QAAQ,CACb;YACE,GAAG;YACH,GAAG,cAAc,CAAC,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C1D,IAAI,KAAK,EAAE,MAAM,CAAC,IAAI,MAAM,EAAE,CAAC;QAC7B,mCAAmC;IACrC,CAAC;AACH,CAAC","sourcesContent":["import type { IncomingMessage } from 'node:http'\nimport { type Duplex, type Readable, pipeline } from 'node:stream'\nimport createHttpError from 'http-errors'\nimport { createDecoders, streamToNodeBuffer } from '@atproto/common'\nimport {\n type KnownNames,\n type KnownParser,\n type ParserResult,\n parseContentType,\n parsers,\n} from './parser.js'\n\n/**\n * Bounds the decoded request body, whichever content-encoding it arrived with.\n * The payloads these routes legitimately carry are single-digit kilobytes, so\n * this leaves ample headroom.\n */\nexport const DEFAULT_MAX_BODY_SIZE = 100 * 1024 // 100 KiB\n\nexport function decodeHttpRequest(\n req: IncomingMessage,\n maxSize: number,\n): Readable {\n // @NOTE Content-Length counts the octets actually transferred, i.e. the\n // body *after* content-encoding. It therefore bounds the wire size, which\n // the `maxSize` passed to `createDecoders` below does not (that one bounds\n // the decoded size); these are two distinct bounds that happen to share a\n // constant. It is not a substitute for the decoded bound: the header is\n // absent under chunked transfer encoding, and a client may understate it.\n const contentLength = req.headers['content-length']\n if (contentLength != null) {\n const size = Number(contentLength)\n if (!Number.isInteger(size) || size < 0) {\n throw createHttpError(400, 'Invalid content-length')\n }\n if (size > maxSize) {\n throw createHttpError(413, 'Payload too large')\n }\n }\n\n try {\n // @NOTE `createDecoders` applies the decoded-size bound even when the body\n // is not encoded: nothing else bounds the size of these requests.\n return pipeline(\n [\n req,\n ...createDecoders(req.headers['content-encoding'], {\n maxSize,\n maxSizeError: () => createHttpError(413, 'Payload too large'),\n }),\n ],\n () => {},\n ) as Duplex\n } catch (cause) {\n const message =\n cause instanceof TypeError ? cause.message : `Invalid content-encoding`\n throw createHttpError(415, message, { cause })\n }\n}\n\n/**\n * Generic method that parses a stream of unknown nature (HTTP request/response,\n * socket, file, etc.), but of known mime type, into a parsed object.\n *\n * @throws {TypeError} If the content-type is not valid or supported.\n */\n\nexport async function parseHttpRequest<A extends readonly KnownNames[]>(\n req: IncomingMessage,\n allow: A,\n maxSize: number = DEFAULT_MAX_BODY_SIZE,\n) {\n const type = parseContentType(\n req.headers['content-type'] ?? 'application/octet-stream',\n )\n\n const parser = parsers.find(\n (parser) => allow.includes(parser.name) && parser.test(type.mime),\n )\n\n if (!parser) {\n throw createHttpError(415, `Unsupported content-type: ${type.mime}`)\n }\n\n const stream = decodeHttpRequest(req, maxSize)\n const buffer = await streamToNodeBuffer(stream)\n return parser.parse(buffer, type) as ParserResult<\n Extract<KnownParser, { name: A[number] }>\n >\n}\n\nexport async function flushStream(stream: AsyncIterable<any>): Promise<void> {\n for await (const _ of stream) {\n // Consume the stream to completion\n }\n}\n"]}
@@ -323,7 +323,7 @@ export class OAuthProvider extends OAuthVerifier {
323
323
  if (ssoSession.consentRequired) {
324
324
  throw new ConsentRequiredError(parameters);
325
325
  }
326
- const code = await this.requestManager.setAuthorized(requestUri, client, ssoSession.account, deviceId, deviceMetadata);
326
+ const { code } = await this.requestManager.setAuthorized(requestUri, client, ssoSession.account, deviceId, deviceMetadata);
327
327
  return { issuer, parameters, redirect: { code } };
328
328
  }
329
329
  // Automatic SSO when a hint was provided that matches a single session
@@ -331,7 +331,7 @@ export class OAuthProvider extends OAuthVerifier {
331
331
  if (ssoSessions.length === 1) {
332
332
  const ssoSession = ssoSessions[0];
333
333
  if (!ssoSession.loginRequired && !ssoSession.consentRequired) {
334
- const code = await this.requestManager.setAuthorized(requestUri, client, ssoSession.account, deviceId, deviceMetadata);
334
+ const { code } = await this.requestManager.setAuthorized(requestUri, client, ssoSession.account, deviceId, deviceMetadata);
335
335
  return { issuer, parameters, redirect: { code } };
336
336
  }
337
337
  }
@@ -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;AAGxC,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AAEnD,O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,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,EAgBhC,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,MAAM,yBAAyB,CAAA;AAG1D,OAAO,EACL,aAAa,GAEd,MAAM,4BAA4B,CAAA;AACnC,OAAO,EAAoB,aA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,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"]}
@@ -12,11 +12,6 @@ import { type Code } from './code.js';
12
12
  import { type RequestDataAuthorized } from './request-data.js';
13
13
  import type { RequestStore } from './request-store.js';
14
14
  import { type RequestUri } from './request-uri.js';
15
- /**
16
- * Intersects the requested parameters with the scopes approved on the consent
17
- * screen, so a client can never end up with more than it asked for.
18
- */
19
- export declare const narrowAuthorizedParameters: <P extends OAuthAuthorizationRequestParameters>(parameters: P, approvedScope: string | undefined) => P;
20
15
  export declare class RequestManager {
21
16
  protected readonly store: RequestStore;
22
17
  protected readonly lexiconManager: LexiconManager;
@@ -105,7 +100,10 @@ export declare class RequestManager {
105
100
  }>;
106
101
  clientId: string;
107
102
  }>;
108
- setAuthorized(requestUri: RequestUri, client: Client, account: Account, deviceId: DeviceId, deviceMetadata: RequestMetadata, scopeOverride?: string): Promise<Code>;
103
+ setAuthorized(requestUri: RequestUri, client: Client, account: Account, deviceId: DeviceId, deviceMetadata: RequestMetadata, scopeOverride?: string): Promise<{
104
+ code: Code;
105
+ parameters: Readonly<OAuthAuthorizationRequestParameters>;
106
+ }>;
109
107
  /**
110
108
  * @note If this method throws an error, any token previously generated from
111
109
  * the same `code` **must** me revoked.
@@ -113,4 +111,9 @@ export declare class RequestManager {
113
111
  consumeCode(code: Code): Promise<RequestDataAuthorized>;
114
112
  delete(requestUri: RequestUri): Promise<void>;
115
113
  }
114
+ /**
115
+ * Intersects the requested parameters with the scopes approved on the consent
116
+ * screen, so a client can never end up with more than it asked for.
117
+ */
118
+ export declare function narrowAuthorizedScope<P extends OAuthAuthorizationRequestParameters>(parameters: P, scopeOverride: string | undefined): P;
116
119
  //# sourceMappingURL=request-manager.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"request-manager.d.ts","sourceRoot":"","sources":["../../src/request/request-manager.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAA;AAE1D,OAAO,KAAK,EACV,mCAAmC,EACnC,gCAAgC,EACjC,MAAM,sBAAsB,CAAA;AAE7B,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,0BAA0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,6 @@ import { generateCode } from './code.js';
14
14
  import { isRequestDataAuthorized, } from './request-data.js';
15
15
  import { generateRequestId } from './request-id.js';
16
16
  import { decodeRequestUri, encodeRequestUri, } from './request-uri.js';
17
- /**
18
- * Intersects the requested parameters with the scopes approved on the consent
19
- * screen, so a client can never end up with more than it asked for.
20
- */
21
- export const narrowAuthorizedParameters = (parameters, approvedScope) => {
22
- if (approvedScope == null)
23
- return parameters;
24
- const allowedScopes = new Set(approvedScope.split(' '));
25
- const requestedScopes = parameters.scope?.split(' ');
26
- const newScopes = requestedScopes?.filter((s) => allowedScopes.has(s));
27
- if (!newScopes?.includes('atproto')) {
28
- throw new AccessDeniedError(parameters, 'The "atproto" scope is required');
29
- }
30
- return { ...parameters, scope: newScopes.join(' ') };
31
- };
32
17
  export class RequestManager {
33
18
  constructor(store, lexiconManager, signer, metadata, hooks, tokenMaxAge = TOKEN_MAX_AGE) {
34
19
  this.store = store;
@@ -297,7 +282,7 @@ export class RequestManager {
297
282
  // that every existing scope in the parameters is also present in the
298
283
  // override value. This allows the user to remove scopes from the request,
299
284
  // but not to add new ones.
300
- parameters = narrowAuthorizedParameters(parameters, scopeOverride);
285
+ parameters = narrowAuthorizedScope(parameters, scopeOverride);
301
286
  // Only response_type=code is supported
302
287
  const code = await generateCode();
303
288
  // Bind the request to the account, preventing it from being used again.
@@ -316,7 +301,7 @@ export class RequestManager {
316
301
  deviceMetadata,
317
302
  requestId,
318
303
  });
319
- return code;
304
+ return { code, parameters };
320
305
  }
321
306
  catch (err) {
322
307
  await this.store.deleteRequest(requestId);
@@ -354,4 +339,19 @@ export class RequestManager {
354
339
  await this.store.deleteRequest(requestId);
355
340
  }
356
341
  }
342
+ /**
343
+ * Intersects the requested parameters with the scopes approved on the consent
344
+ * screen, so a client can never end up with more than it asked for.
345
+ */
346
+ export function narrowAuthorizedScope(parameters, scopeOverride) {
347
+ if (scopeOverride == null || parameters.scope == null)
348
+ return parameters;
349
+ const requestedScopes = new Set(parameters.scope.split(' '));
350
+ const allowedScopes = new Set(scopeOverride.split(' '));
351
+ const newScopes = requestedScopes.intersection(allowedScopes);
352
+ if (!newScopes.has('atproto')) {
353
+ throw new AccessDeniedError(parameters, 'The "atproto" scope is required');
354
+ }
355
+ return { ...parameters, scope: Array.from(newScopes).join(' ') };
356
+ }
357
357
  //# sourceMappingURL=request-manager.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"request-manager.js","sourceRoot":"","sources":["../../src/request/request-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAA;AAC3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAA;AAExD,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAA;AAK3D,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAK/C,OAAO,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAA;AACpE,OAAO,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAA;AACrE,OAAO,EAAE,oBAAoB,EAAE,MAAM,qCAAqC,CAAA;AAC1E,OAAO,EAAE,gCAAgC,EAAE,MAAM,kDAAkD,CAAA;AACnG,OAAO,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAA;AACpE,OAAO,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAA;AACxE,OAAO,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAA;AAGpE,OAAO,EACL,gCAAgC,EAChC,QAAQ,EACR,cAAc,EACd,aAAa,GACd,MAAM,uBAAuB,CAAA;AAG9B,OAAO,EAAa,YAAY,EAAE,MAAM,WAAW,CAAA;AACnD,OAAO,EAEL,uBAAuB,GACxB,MAAM,mBAAmB,CAAA;AAC1B,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAA;AAEnD,OAAO,EAEL,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,kBAAkB,CAAA;AAEzB;;;GAGG;AACH,MAAM,CAAC,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,0BAA0B,CAAC,CAAA;QAC7C,CAAC;QAED,IAAI,IAAI,CAAC,SAAS,GAAG,IAAI,IAAI,EAAE,EAAE,CAAC;YAChC,MAAM,IAAI,iBAAiB,CAAC,uBAAuB,CAAC,CAAA;QACtD,CAAC;QAED,OAAO,IAAI,CAAA;IACb,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,UAAsB;QACjC,MAAM,SAAS,GAAG,gBAAgB,CAAC,UAAU,CAAC,CAAA;QAC9C,MAAM,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,SAAS,CAAC,CAAA;IAC3C,CAAC;CACF","sourcesContent":["import { isAtprotoDid } from '@atproto/did'\nimport { LexResolverError } from '@atproto/lex-resolver'\nimport type { Account } from '@atproto/oauth-provider-api'\nimport { isAtprotoOauthScope } from '@atproto/oauth-scopes'\nimport type {\n OAuthAuthorizationRequestParameters,\n OAuthAuthorizationServerMetadata,\n} from '@atproto/oauth-types'\nimport { isValidHandle } from '@atproto/syntax'\nimport type { ClientAuth } from '../client/client-auth.js'\nimport type { ClientId } from '../client/client-id.js'\nimport type { Client } from '../client/client.js'\nimport type { DeviceId } from '../device/device-id.js'\nimport { AccessDeniedError } from '../errors/access-denied-error.js'\nimport { AuthorizationError } from '../errors/authorization-error.js'\nimport { ConsentRequiredError } from '../errors/consent-required-error.js'\nimport { InvalidAuthorizationDetailsError } from '../errors/invalid-authorization-details-error.js'\nimport { InvalidGrantError } from '../errors/invalid-grant-error.js'\nimport { InvalidRequestError } from '../errors/invalid-request-error.js'\nimport { InvalidScopeError } from '../errors/invalid-scope-error.js'\nimport type { LexiconManager } from '../lexicon/lexicon-manager.js'\nimport type { RequestMetadata } from '../lib/http/request.js'\nimport {\n AUTHORIZATION_INACTIVITY_TIMEOUT,\n NODE_ENV,\n PAR_EXPIRES_IN,\n TOKEN_MAX_AGE,\n} from '../oauth-constants.js'\nimport type { OAuthHooks } from '../oauth-hooks.js'\nimport type { Signer } from '../signer/signer.js'\nimport { type Code, generateCode } from './code.js'\nimport {\n type RequestDataAuthorized,\n isRequestDataAuthorized,\n} from './request-data.js'\nimport { generateRequestId } from './request-id.js'\nimport type { RequestStore, UpdateRequestData } from './request-store.js'\nimport {\n type RequestUri,\n decodeRequestUri,\n encodeRequestUri,\n} from './request-uri.js'\n\n/**\n * Intersects the requested parameters with the scopes approved on the consent\n * screen, so a client can never end up with more than it asked for.\n */\nexport const narrowAuthorizedParameters = <\n P extends OAuthAuthorizationRequestParameters,\n>(\n parameters: P,\n approvedScope: string | undefined,\n): P => {\n if (approvedScope == null) return parameters\n\n const allowedScopes = new Set(approvedScope.split(' '))\n const requestedScopes = parameters.scope?.split(' ')\n\n const newScopes = requestedScopes?.filter((s) => allowedScopes.has(s))\n\n if (!newScopes?.includes('atproto')) {\n throw new AccessDeniedError(parameters, 'The \"atproto\" scope is required')\n }\n\n return { ...parameters, scope: newScopes.join(' ') }\n}\n\nexport class RequestManager {\n constructor(\n protected readonly store: RequestStore,\n protected readonly lexiconManager: LexiconManager,\n protected readonly signer: Signer,\n protected readonly metadata: OAuthAuthorizationServerMetadata,\n protected readonly hooks: OAuthHooks,\n protected readonly tokenMaxAge = TOKEN_MAX_AGE,\n ) {}\n\n protected createTokenExpiry() {\n return new Date(Date.now() + this.tokenMaxAge)\n }\n\n async createAuthorizationRequest(\n client: Client,\n clientAuth: null | ClientAuth,\n input: Readonly<OAuthAuthorizationRequestParameters>,\n deviceId: null | DeviceId,\n ) {\n const parameters = await this.validate(client, clientAuth, input)\n\n await this.hooks.onAuthorizationRequest?.call(null, {\n client,\n clientAuth,\n parameters,\n })\n\n const expiresAt = new Date(Date.now() + PAR_EXPIRES_IN)\n const requestId = await generateRequestId()\n\n await this.store.createRequest(requestId, {\n clientId: client.id,\n clientAuth,\n parameters,\n expiresAt,\n deviceId,\n did: null,\n code: null,\n })\n\n const requestUri = encodeRequestUri(requestId)\n return { requestUri, expiresAt, parameters }\n }\n\n protected async validate(\n client: Client,\n clientAuth: null | ClientAuth,\n parameters: Readonly<OAuthAuthorizationRequestParameters>,\n ): Promise<Readonly<OAuthAuthorizationRequestParameters>> {\n // -------------------------------\n // Validate unsupported parameters\n // -------------------------------\n\n for (const k of [\n // Known unsupported OIDC parameters\n 'claims',\n 'id_token_hint',\n 'nonce', // note that OIDC \"nonce\" is redundant with PKCE\n ] as const) {\n if (parameters[k] !== undefined) {\n throw new AuthorizationError(parameters, `Unsupported \"${k}\" parameter`)\n }\n }\n\n // -----------------------\n // Validate against server\n // -----------------------\n\n if (\n !this.metadata.response_types_supported?.includes(\n parameters.response_type,\n )\n ) {\n throw new AuthorizationError(\n parameters,\n `Unsupported response_type \"${parameters.response_type}\"`,\n 'unsupported_response_type',\n )\n }\n\n if (\n parameters.response_type === 'code' &&\n !this.metadata.grant_types_supported?.includes('authorization_code')\n ) {\n throw new AuthorizationError(\n parameters,\n `Unsupported grant_type \"authorization_code\"`,\n 'invalid_request',\n )\n }\n\n if (parameters.authorization_details) {\n for (const detail of parameters.authorization_details) {\n if (\n !this.metadata.authorization_details_types_supported?.includes(\n detail.type,\n )\n ) {\n throw new InvalidAuthorizationDetailsError(\n parameters,\n `Unsupported \"authorization_details\" type \"${detail.type}\"`,\n )\n }\n }\n }\n\n // -----------------------\n // Validate against client\n // -----------------------\n\n parameters = client.validateRequest(parameters)\n\n // -------------------\n // Validate parameters\n // -------------------\n\n if (!parameters.redirect_uri) {\n // Should already be ensured by client.validateRequest(). Adding here for\n // clarity & extra safety.\n throw new AuthorizationError(parameters, 'Missing \"redirect_uri\"')\n }\n\n // https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-10#section-1.4.1\n // > The authorization server MAY fully or partially ignore the scope\n // > requested by the client, based on the authorization server policy or\n // > the resource owner's instructions. If the issued access token scope is\n // > different from the one requested by the client, the authorization\n // > server MUST include the scope response parameter in the token response\n // > (Section 3.2.3) to inform the client of the actual scope granted.\n\n // Let's make sure the scopes are unique (to reduce the token & storage\n // size).\n const scopes = new Set(parameters.scope?.split(' '))\n\n // @NOTE An app requesting a not yet supported list of scopes will need to\n // re-authenticate the user once the scopes are supported. This is due to\n // the fact that the AS does not know how to properly display those scopes\n // to the user, so it cannot properly ask for consent.\n const scope =\n Array.from(scopes).filter(isAtprotoOauthScope).join(' ') || undefined\n parameters = { ...parameters, scope }\n\n if (parameters.code_challenge) {\n switch (parameters.code_challenge_method) {\n case undefined:\n // https://datatracker.ietf.org/doc/html/rfc7636#section-4.3\n parameters = { ...parameters, code_challenge_method: 'plain' }\n // falls through\n case 'plain':\n case 'S256':\n break\n default: {\n throw new AuthorizationError(\n parameters,\n `Unsupported code_challenge_method \"${parameters.code_challenge_method}\"`,\n )\n }\n }\n } else {\n if (parameters.code_challenge_method) {\n // https://datatracker.ietf.org/doc/html/rfc7636#section-4.4.1\n throw new AuthorizationError(\n parameters,\n 'code_challenge is required when code_challenge_method is provided',\n )\n }\n\n // https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-11#section-4.1.2.1\n //\n // > An AS MUST reject requests without a code_challenge from public\n // > clients, and MUST reject such requests from other clients unless\n // > there is reasonable assurance that the client mitigates\n // > authorization code injection in other ways. See Section 7.5.1 for\n // > details.\n //\n // > [...] In the specific deployment and the specific request, there is\n // > reasonable assurance by the authorization server that the client\n // > implements the OpenID Connect nonce mechanism properly.\n //\n // atproto does not implement the OpenID Connect nonce mechanism, so we\n // require the use of PKCE for all clients.\n\n throw new AuthorizationError(parameters, 'Use of PKCE is required')\n }\n\n // -----------------\n // atproto extension\n // -----------------\n\n if (parameters.response_type !== 'code') {\n throw new AuthorizationError(\n parameters,\n 'atproto only supports the \"code\" response_type',\n )\n }\n\n if (!scopes.has('atproto')) {\n throw new InvalidScopeError(parameters, 'The \"atproto\" scope is required')\n } else if (scopes.has('openid')) {\n throw new InvalidScopeError(\n parameters,\n 'OpenID Connect is not compatible with atproto',\n )\n }\n\n if (parameters.code_challenge_method !== 'S256') {\n throw new AuthorizationError(\n parameters,\n 'atproto requires use of \"S256\" code_challenge_method',\n )\n }\n\n // atproto extension: if the client is not trusted, and not confidential,\n // force users to consent to authorization requests. We do this to avoid\n // unauthenticated clients from being able to silently re-authenticate\n // users.\n // @NOTE First party clients are trusted by default, but they can\n // also be explicitly marked as un-trusted.\n if (!client.isConfidential && !client.isTrusted) {\n if (parameters.prompt === 'none') {\n throw new ConsentRequiredError(\n parameters,\n 'Public clients are not allowed to use silent-sign-on',\n )\n }\n\n // force \"consent\" for unauthenticated third party clients, unless they\n // are trying to create accounts:\n if (parameters.prompt !== 'create') {\n parameters = { ...parameters, prompt: 'consent' }\n }\n }\n\n // atproto extension: ensure that the login_hint is a valid handle or DID\n // @NOTE we to allow invalid case here, which is not spec'd anywhere.\n const hint = parameters.login_hint?.toLowerCase()\n if (hint) {\n if (!isAtprotoDid(hint) && !isValidHandle(hint)) {\n throw new AuthorizationError(parameters, `Invalid login_hint \"${hint}\"`)\n }\n\n // @TODO: ensure that the account actually exists on this server (there is\n // no point in showing the UI to the user if the account does not exist).\n\n // Update the parameters to ensure the right case is used\n parameters = { ...parameters, login_hint: hint }\n }\n\n // Make sure that every nsid in the scope resolves to a valid permission set\n // lexicon\n if (parameters.scope) {\n try {\n await this.lexiconManager.getPermissionSetsFromScope(parameters.scope)\n } catch (err) {\n // Parse expected errors\n if (err instanceof LexResolverError) {\n throw new AuthorizationError(\n parameters,\n err.message,\n 'invalid_scope',\n err,\n )\n }\n\n // Unexpected error\n throw err\n }\n }\n\n return parameters\n }\n\n /**\n * Reads the {@link ClientId} associated with a request URI without any of\n * the validation or side-effects performed by {@link RequestManager.get}\n *\n * Returns `undefined` when no such request exists.\n */\n async peekClientId(requestUri: RequestUri): Promise<ClientId | undefined> {\n const requestId = decodeRequestUri(requestUri)\n const data = await this.store.readRequest(requestId)\n return data?.clientId\n }\n\n async get(requestUri: RequestUri, deviceId?: DeviceId, clientId?: ClientId) {\n const requestId = decodeRequestUri(requestUri)\n\n const data = await this.store.readRequest(requestId)\n if (!data) throw new InvalidRequestError('Unknown request_uri')\n\n const updates: UpdateRequestData = {}\n\n try {\n if (data.did || data.code) {\n // If an account was linked to the request, the next step is to exchange\n // the code for a token.\n throw new AccessDeniedError(\n data.parameters,\n 'This request was already authorized',\n )\n }\n\n if (data.expiresAt < new Date()) {\n throw new AccessDeniedError(data.parameters, 'This request has expired')\n } else {\n updates.expiresAt = new Date(\n Date.now() + AUTHORIZATION_INACTIVITY_TIMEOUT,\n )\n }\n\n if (clientId != null && data.clientId !== clientId) {\n throw new AccessDeniedError(\n data.parameters,\n 'This request was initiated for another client',\n )\n }\n\n if (deviceId != null) {\n if (!data.deviceId) {\n updates.deviceId = deviceId\n } else if (data.deviceId !== deviceId) {\n throw new AccessDeniedError(\n data.parameters,\n 'This request was initiated from another device',\n )\n }\n }\n } catch (err) {\n await this.store.deleteRequest(requestId)\n throw err\n }\n\n if (Object.keys(updates).length > 0) {\n await this.store.updateRequest(requestId, updates)\n }\n\n return {\n requestUri,\n expiresAt: updates.expiresAt || data.expiresAt,\n parameters: data.parameters,\n clientId: data.clientId,\n }\n }\n\n async setAuthorized(\n requestUri: RequestUri,\n client: Client,\n account: Account,\n deviceId: DeviceId,\n deviceMetadata: RequestMetadata,\n scopeOverride?: string,\n ): Promise<Code> {\n const requestId = decodeRequestUri(requestUri)\n\n const data = await this.store.readRequest(requestId)\n if (!data) throw new InvalidRequestError('Unknown request_uri')\n\n let { parameters } = data\n\n try {\n if (account.deactivated) {\n throw new AccessDeniedError(\n parameters,\n 'This account has been deactivated',\n )\n }\n\n if (data.expiresAt < new Date()) {\n throw new AccessDeniedError(parameters, 'This request has expired')\n }\n if (!data.deviceId) {\n throw new AccessDeniedError(\n parameters,\n 'This request was not initiated',\n )\n }\n if (data.deviceId !== deviceId) {\n throw new AccessDeniedError(\n parameters,\n 'This request was initiated from another device',\n )\n }\n if (data.did || data.code) {\n throw new AccessDeniedError(\n parameters,\n 'This request was already authorized',\n )\n }\n\n // If a new scope value is provided, update the parameters by ensuring\n // that every existing scope in the parameters is also present in the\n // override value. This allows the user to remove scopes from the request,\n // but not to add new ones.\n parameters = narrowAuthorizedParameters(parameters, scopeOverride)\n\n // Only response_type=code is supported\n const code = await generateCode()\n\n // Bind the request to the account, preventing it from being used again.\n await this.store.updateRequest(requestId, {\n did: account.did,\n code,\n // Allow the client to exchange the code for a token within the next 60 seconds.\n expiresAt: new Date(Date.now() + AUTHORIZATION_INACTIVITY_TIMEOUT),\n parameters,\n })\n\n await this.hooks.onAuthorized?.call(null, {\n client,\n account,\n parameters,\n deviceId,\n deviceMetadata,\n requestId,\n })\n\n return code\n } catch (err) {\n await this.store.deleteRequest(requestId)\n throw err\n }\n }\n\n /**\n * @note If this method throws an error, any token previously generated from\n * the same `code` **must** me revoked.\n */\n public async consumeCode(code: Code): Promise<RequestDataAuthorized> {\n const result = await this.store.consumeRequestCode(code)\n if (!result) throw new InvalidGrantError('Invalid code')\n\n const { requestId, data } = result\n\n // Fool-proofing the store implementation against code replay attacks (in\n // case consumeRequestCode() does not delete the request).\n if (NODE_ENV !== 'production') {\n const result = await this.store.readRequest(requestId)\n if (result) {\n throw new Error('Invalid store implementation: request not deleted')\n }\n }\n\n if (!isRequestDataAuthorized(data) || data.code !== code) {\n // Should never happen: maybe the store implementation is faulty ?\n throw new Error('Unexpected request state')\n }\n\n if (data.expiresAt < new Date()) {\n throw new InvalidGrantError('This code has expired')\n }\n\n return data\n }\n\n async delete(requestUri: RequestUri): Promise<void> {\n const requestId = decodeRequestUri(requestUri)\n await this.store.deleteRequest(requestId)\n }\n}\n"]}
1
+ {"version":3,"file":"request-manager.js","sourceRoot":"","sources":["../../src/request/request-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAA;AAC3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAA;AAExD,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAA;AAK3D,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAK/C,OAAO,EAA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YAClE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAA;QAC7C,CAAC;QAED,IAAI,IAAI,CAAC,SAAS,GAAG,IAAI,IAAI,EAAE,EAAE,CAAC;YAChC,MAAM,IAAI,iBAAiB,CAAC,uBAAuB,CAAC,CAAA;QACtD,CAAC;QAED,OAAO,IAAI,CAAA;IACb,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,UAAsB;QACjC,MAAM,SAAS,GAAG,gBAAgB,CAAC,UAAU,CAAC,CAAA;QAC9C,MAAM,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,SAAS,CAAC,CAAA;IAC3C,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,UAAU,qBAAqB,CAEnC,UAAa,EAAE,aAAiC;IAChD,IAAI,aAAa,IAAI,IAAI,IAAI,UAAU,CAAC,KAAK,IAAI,IAAI;QAAE,OAAO,UAAU,CAAA;IAExE,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC,UAAU,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAA;IAC5D,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC,aAAa,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAA;IAEvD,MAAM,SAAS,GAAG,eAAe,CAAC,YAAY,CAAC,aAAa,CAAC,CAAA;IAC7D,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,CAAC;QAC9B,MAAM,IAAI,iBAAiB,CAAC,UAAU,EAAE,iCAAiC,CAAC,CAAA;IAC5E,CAAC;IAED,OAAO,EAAE,GAAG,UAAU,EAAE,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAA;AAClE,CAAC","sourcesContent":["import { isAtprotoDid } from '@atproto/did'\nimport { LexResolverError } from '@atproto/lex-resolver'\nimport type { Account } from '@atproto/oauth-provider-api'\nimport { isAtprotoOauthScope } from '@atproto/oauth-scopes'\nimport type {\n OAuthAuthorizationRequestParameters,\n OAuthAuthorizationServerMetadata,\n} from '@atproto/oauth-types'\nimport { isValidHandle } from '@atproto/syntax'\nimport type { ClientAuth } from '../client/client-auth.js'\nimport type { ClientId } from '../client/client-id.js'\nimport type { Client } from '../client/client.js'\nimport type { DeviceId } from '../device/device-id.js'\nimport { AccessDeniedError } from '../errors/access-denied-error.js'\nimport { AuthorizationError } from '../errors/authorization-error.js'\nimport { ConsentRequiredError } from '../errors/consent-required-error.js'\nimport { InvalidAuthorizationDetailsError } from '../errors/invalid-authorization-details-error.js'\nimport { InvalidGrantError } from '../errors/invalid-grant-error.js'\nimport { InvalidRequestError } from '../errors/invalid-request-error.js'\nimport { InvalidScopeError } from '../errors/invalid-scope-error.js'\nimport type { LexiconManager } from '../lexicon/lexicon-manager.js'\nimport type { RequestMetadata } from '../lib/http/request.js'\nimport {\n AUTHORIZATION_INACTIVITY_TIMEOUT,\n NODE_ENV,\n PAR_EXPIRES_IN,\n TOKEN_MAX_AGE,\n} from '../oauth-constants.js'\nimport type { OAuthHooks } from '../oauth-hooks.js'\nimport type { Signer } from '../signer/signer.js'\nimport { type Code, generateCode } from './code.js'\nimport {\n type RequestDataAuthorized,\n isRequestDataAuthorized,\n} from './request-data.js'\nimport { generateRequestId } from './request-id.js'\nimport type { RequestStore, UpdateRequestData } from './request-store.js'\nimport {\n type RequestUri,\n decodeRequestUri,\n encodeRequestUri,\n} from './request-uri.js'\n\nexport class RequestManager {\n constructor(\n protected readonly store: RequestStore,\n protected readonly lexiconManager: LexiconManager,\n protected readonly signer: Signer,\n protected readonly metadata: OAuthAuthorizationServerMetadata,\n protected readonly hooks: OAuthHooks,\n protected readonly tokenMaxAge = TOKEN_MAX_AGE,\n ) {}\n\n protected createTokenExpiry() {\n return new Date(Date.now() + this.tokenMaxAge)\n }\n\n async createAuthorizationRequest(\n client: Client,\n clientAuth: null | ClientAuth,\n input: Readonly<OAuthAuthorizationRequestParameters>,\n deviceId: null | DeviceId,\n ) {\n const parameters = await this.validate(client, clientAuth, input)\n\n await this.hooks.onAuthorizationRequest?.call(null, {\n client,\n clientAuth,\n parameters,\n })\n\n const expiresAt = new Date(Date.now() + PAR_EXPIRES_IN)\n const requestId = await generateRequestId()\n\n await this.store.createRequest(requestId, {\n clientId: client.id,\n clientAuth,\n parameters,\n expiresAt,\n deviceId,\n did: null,\n code: null,\n })\n\n const requestUri = encodeRequestUri(requestId)\n return { requestUri, expiresAt, parameters }\n }\n\n protected async validate(\n client: Client,\n clientAuth: null | ClientAuth,\n parameters: Readonly<OAuthAuthorizationRequestParameters>,\n ): Promise<Readonly<OAuthAuthorizationRequestParameters>> {\n // -------------------------------\n // Validate unsupported parameters\n // -------------------------------\n\n for (const k of [\n // Known unsupported OIDC parameters\n 'claims',\n 'id_token_hint',\n 'nonce', // note that OIDC \"nonce\" is redundant with PKCE\n ] as const) {\n if (parameters[k] !== undefined) {\n throw new AuthorizationError(parameters, `Unsupported \"${k}\" parameter`)\n }\n }\n\n // -----------------------\n // Validate against server\n // -----------------------\n\n if (\n !this.metadata.response_types_supported?.includes(\n parameters.response_type,\n )\n ) {\n throw new AuthorizationError(\n parameters,\n `Unsupported response_type \"${parameters.response_type}\"`,\n 'unsupported_response_type',\n )\n }\n\n if (\n parameters.response_type === 'code' &&\n !this.metadata.grant_types_supported?.includes('authorization_code')\n ) {\n throw new AuthorizationError(\n parameters,\n `Unsupported grant_type \"authorization_code\"`,\n 'invalid_request',\n )\n }\n\n if (parameters.authorization_details) {\n for (const detail of parameters.authorization_details) {\n if (\n !this.metadata.authorization_details_types_supported?.includes(\n detail.type,\n )\n ) {\n throw new InvalidAuthorizationDetailsError(\n parameters,\n `Unsupported \"authorization_details\" type \"${detail.type}\"`,\n )\n }\n }\n }\n\n // -----------------------\n // Validate against client\n // -----------------------\n\n parameters = client.validateRequest(parameters)\n\n // -------------------\n // Validate parameters\n // -------------------\n\n if (!parameters.redirect_uri) {\n // Should already be ensured by client.validateRequest(). Adding here for\n // clarity & extra safety.\n throw new AuthorizationError(parameters, 'Missing \"redirect_uri\"')\n }\n\n // https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-10#section-1.4.1\n // > The authorization server MAY fully or partially ignore the scope\n // > requested by the client, based on the authorization server policy or\n // > the resource owner's instructions. If the issued access token scope is\n // > different from the one requested by the client, the authorization\n // > server MUST include the scope response parameter in the token response\n // > (Section 3.2.3) to inform the client of the actual scope granted.\n\n // Let's make sure the scopes are unique (to reduce the token & storage\n // size).\n const scopes = new Set(parameters.scope?.split(' '))\n\n // @NOTE An app requesting a not yet supported list of scopes will need to\n // re-authenticate the user once the scopes are supported. This is due to\n // the fact that the AS does not know how to properly display those scopes\n // to the user, so it cannot properly ask for consent.\n const scope =\n Array.from(scopes).filter(isAtprotoOauthScope).join(' ') || undefined\n parameters = { ...parameters, scope }\n\n if (parameters.code_challenge) {\n switch (parameters.code_challenge_method) {\n case undefined:\n // https://datatracker.ietf.org/doc/html/rfc7636#section-4.3\n parameters = { ...parameters, code_challenge_method: 'plain' }\n // falls through\n case 'plain':\n case 'S256':\n break\n default: {\n throw new AuthorizationError(\n parameters,\n `Unsupported code_challenge_method \"${parameters.code_challenge_method}\"`,\n )\n }\n }\n } else {\n if (parameters.code_challenge_method) {\n // https://datatracker.ietf.org/doc/html/rfc7636#section-4.4.1\n throw new AuthorizationError(\n parameters,\n 'code_challenge is required when code_challenge_method is provided',\n )\n }\n\n // https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-11#section-4.1.2.1\n //\n // > An AS MUST reject requests without a code_challenge from public\n // > clients, and MUST reject such requests from other clients unless\n // > there is reasonable assurance that the client mitigates\n // > authorization code injection in other ways. See Section 7.5.1 for\n // > details.\n //\n // > [...] In the specific deployment and the specific request, there is\n // > reasonable assurance by the authorization server that the client\n // > implements the OpenID Connect nonce mechanism properly.\n //\n // atproto does not implement the OpenID Connect nonce mechanism, so we\n // require the use of PKCE for all clients.\n\n throw new AuthorizationError(parameters, 'Use of PKCE is required')\n }\n\n // -----------------\n // atproto extension\n // -----------------\n\n if (parameters.response_type !== 'code') {\n throw new AuthorizationError(\n parameters,\n 'atproto only supports the \"code\" response_type',\n )\n }\n\n if (!scopes.has('atproto')) {\n throw new InvalidScopeError(parameters, 'The \"atproto\" scope is required')\n } else if (scopes.has('openid')) {\n throw new InvalidScopeError(\n parameters,\n 'OpenID Connect is not compatible with atproto',\n )\n }\n\n if (parameters.code_challenge_method !== 'S256') {\n throw new AuthorizationError(\n parameters,\n 'atproto requires use of \"S256\" code_challenge_method',\n )\n }\n\n // atproto extension: if the client is not trusted, and not confidential,\n // force users to consent to authorization requests. We do this to avoid\n // unauthenticated clients from being able to silently re-authenticate\n // users.\n // @NOTE First party clients are trusted by default, but they can\n // also be explicitly marked as un-trusted.\n if (!client.isConfidential && !client.isTrusted) {\n if (parameters.prompt === 'none') {\n throw new ConsentRequiredError(\n parameters,\n 'Public clients are not allowed to use silent-sign-on',\n )\n }\n\n // force \"consent\" for unauthenticated third party clients, unless they\n // are trying to create accounts:\n if (parameters.prompt !== 'create') {\n parameters = { ...parameters, prompt: 'consent' }\n }\n }\n\n // atproto extension: ensure that the login_hint is a valid handle or DID\n // @NOTE we to allow invalid case here, which is not spec'd anywhere.\n const hint = parameters.login_hint?.toLowerCase()\n if (hint) {\n if (!isAtprotoDid(hint) && !isValidHandle(hint)) {\n throw new AuthorizationError(parameters, `Invalid login_hint \"${hint}\"`)\n }\n\n // @TODO: ensure that the account actually exists on this server (there is\n // no point in showing the UI to the user if the account does not exist).\n\n // Update the parameters to ensure the right case is used\n parameters = { ...parameters, login_hint: hint }\n }\n\n // Make sure that every nsid in the scope resolves to a valid permission set\n // lexicon\n if (parameters.scope) {\n try {\n await this.lexiconManager.getPermissionSetsFromScope(parameters.scope)\n } catch (err) {\n // Parse expected errors\n if (err instanceof LexResolverError) {\n throw new AuthorizationError(\n parameters,\n err.message,\n 'invalid_scope',\n err,\n )\n }\n\n // Unexpected error\n throw err\n }\n }\n\n return parameters\n }\n\n /**\n * Reads the {@link ClientId} associated with a request URI without any of\n * the validation or side-effects performed by {@link RequestManager.get}\n *\n * Returns `undefined` when no such request exists.\n */\n async peekClientId(requestUri: RequestUri): Promise<ClientId | undefined> {\n const requestId = decodeRequestUri(requestUri)\n const data = await this.store.readRequest(requestId)\n return data?.clientId\n }\n\n async get(requestUri: RequestUri, deviceId?: DeviceId, clientId?: ClientId) {\n const requestId = decodeRequestUri(requestUri)\n\n const data = await this.store.readRequest(requestId)\n if (!data) throw new InvalidRequestError('Unknown request_uri')\n\n const updates: UpdateRequestData = {}\n\n try {\n if (data.did || data.code) {\n // If an account was linked to the request, the next step is to exchange\n // the code for a token.\n throw new AccessDeniedError(\n data.parameters,\n 'This request was already authorized',\n )\n }\n\n if (data.expiresAt < new Date()) {\n throw new AccessDeniedError(data.parameters, 'This request has expired')\n } else {\n updates.expiresAt = new Date(\n Date.now() + AUTHORIZATION_INACTIVITY_TIMEOUT,\n )\n }\n\n if (clientId != null && data.clientId !== clientId) {\n throw new AccessDeniedError(\n data.parameters,\n 'This request was initiated for another client',\n )\n }\n\n if (deviceId != null) {\n if (!data.deviceId) {\n updates.deviceId = deviceId\n } else if (data.deviceId !== deviceId) {\n throw new AccessDeniedError(\n data.parameters,\n 'This request was initiated from another device',\n )\n }\n }\n } catch (err) {\n await this.store.deleteRequest(requestId)\n throw err\n }\n\n if (Object.keys(updates).length > 0) {\n await this.store.updateRequest(requestId, updates)\n }\n\n return {\n requestUri,\n expiresAt: updates.expiresAt || data.expiresAt,\n parameters: data.parameters,\n clientId: data.clientId,\n }\n }\n\n async setAuthorized(\n requestUri: RequestUri,\n client: Client,\n account: Account,\n deviceId: DeviceId,\n deviceMetadata: RequestMetadata,\n scopeOverride?: string,\n ): Promise<{\n code: Code\n parameters: Readonly<OAuthAuthorizationRequestParameters>\n }> {\n const requestId = decodeRequestUri(requestUri)\n\n const data = await this.store.readRequest(requestId)\n if (!data) throw new InvalidRequestError('Unknown request_uri')\n\n let { parameters } = data\n\n try {\n if (account.deactivated) {\n throw new AccessDeniedError(\n parameters,\n 'This account has been deactivated',\n )\n }\n\n if (data.expiresAt < new Date()) {\n throw new AccessDeniedError(parameters, 'This request has expired')\n }\n if (!data.deviceId) {\n throw new AccessDeniedError(\n parameters,\n 'This request was not initiated',\n )\n }\n if (data.deviceId !== deviceId) {\n throw new AccessDeniedError(\n parameters,\n 'This request was initiated from another device',\n )\n }\n if (data.did || data.code) {\n throw new AccessDeniedError(\n parameters,\n 'This request was already authorized',\n )\n }\n\n // If a new scope value is provided, update the parameters by ensuring\n // that every existing scope in the parameters is also present in the\n // override value. This allows the user to remove scopes from the request,\n // but not to add new ones.\n parameters = narrowAuthorizedScope(parameters, scopeOverride)\n\n // Only response_type=code is supported\n const code = await generateCode()\n\n // Bind the request to the account, preventing it from being used again.\n await this.store.updateRequest(requestId, {\n did: account.did,\n code,\n // Allow the client to exchange the code for a token within the next 60 seconds.\n expiresAt: new Date(Date.now() + AUTHORIZATION_INACTIVITY_TIMEOUT),\n parameters,\n })\n\n await this.hooks.onAuthorized?.call(null, {\n client,\n account,\n parameters,\n deviceId,\n deviceMetadata,\n requestId,\n })\n\n return { code, parameters }\n } catch (err) {\n await this.store.deleteRequest(requestId)\n throw err\n }\n }\n\n /**\n * @note If this method throws an error, any token previously generated from\n * the same `code` **must** me revoked.\n */\n public async consumeCode(code: Code): Promise<RequestDataAuthorized> {\n const result = await this.store.consumeRequestCode(code)\n if (!result) throw new InvalidGrantError('Invalid code')\n\n const { requestId, data } = result\n\n // Fool-proofing the store implementation against code replay attacks (in\n // case consumeRequestCode() does not delete the request).\n if (NODE_ENV !== 'production') {\n const result = await this.store.readRequest(requestId)\n if (result) {\n throw new Error('Invalid store implementation: request not deleted')\n }\n }\n\n if (!isRequestDataAuthorized(data) || data.code !== code) {\n // Should never happen: maybe the store implementation is faulty ?\n throw new Error('Unexpected request state')\n }\n\n if (data.expiresAt < new Date()) {\n throw new InvalidGrantError('This code has expired')\n }\n\n return data\n }\n\n async delete(requestUri: RequestUri): Promise<void> {\n const requestId = decodeRequestUri(requestUri)\n await this.store.deleteRequest(requestId)\n }\n}\n\n/**\n * Intersects the requested parameters with the scopes approved on the consent\n * screen, so a client can never end up with more than it asked for.\n */\nexport function narrowAuthorizedScope<\n P extends OAuthAuthorizationRequestParameters,\n>(parameters: P, scopeOverride: string | undefined): P {\n if (scopeOverride == null || parameters.scope == null) return parameters\n\n const requestedScopes = new Set(parameters.scope.split(' '))\n const allowedScopes = new Set(scopeOverride.split(' '))\n\n const newScopes = requestedScopes.intersection(allowedScopes)\n if (!newScopes.has('atproto')) {\n throw new AccessDeniedError(parameters, 'The \"atproto\" scope is required')\n }\n\n return { ...parameters, scope: Array.from(newScopes).join(' ') }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"create-api-middleware.d.ts","sourceRoot":"","sources":["../../src/router/create-api-middleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAA;AAgChE,OAAO,EAEL,KAAK,UAAU,EAahB,MAAM,sBAAsB,CAAA;AAI7B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAA;AAYzD,OAAO,EAEL,KAAK,oBAAoB,EAM1B,MAAM,2BAA2B,CAAA;AAClC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAA;AAEhE,wBAAgB,mBAAmB,CACjC,GAAG,SAAS,MAAM,GAAG,IAAI,GAAG,IAAI,EAChC,GAAG,SAAS,eAAe,GAAG,eAAe,EAC7C,GAAG,SAAS,cAAc,GAAG,cAAc,EAE3C,MAAM,EAAE,aAAa,EACrB,EAAE,OAAO,EAAE,EAAE,iBAAiB,CAAC,GAAG,EAAE,GAAG,CAAC,GACvC,UAAU,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CA88B3B;AA2BD,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,GAAG,GAAG,oBAAoB,CA4C/D"}
1
+ {"version":3,"file":"create-api-middleware.d.ts","sourceRoot":"","sources":["../../src/router/create-api-middleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAA;AAgChE,OAAO,EAEL,KAAK,UAAU,EAahB,MAAM,sBAAsB,CAAA;AAI7B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAA;AAWzD,OAAO,EAEL,KAAK,oBAAoB,EAM1B,MAAM,2BAA2B,CAAA;AAClC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAA;AAEhE,wBAAgB,mBAAmB,CACjC,GAAG,SAAS,MAAM,GAAG,IAAI,GAAG,IAAI,EAChC,GAAG,SAAS,eAAe,GAAG,eAAe,EAC7C,GAAG,SAAS,cAAc,GAAG,cAAc,EAE3C,MAAM,EAAE,aAAa,EACrB,EAAE,OAAO,EAAE,EAAE,iBAAiB,CAAC,GAAG,EAAE,GAAG,CAAC,GACvC,UAAU,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAg9B3B;AA2BD,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,GAAG,GAAG,oBAAoB,CA4C/D"}
@@ -14,7 +14,6 @@ import { WWWAuthenticateError } from '../errors/www-authenticate-error.js';
14
14
  import { Router, flushStream, jsonHandler, parseHttpRequest, subCtx, validateFetchMode, validateFetchSite, validateOrigin, validateReferrer, } from '../lib/http/index.js';
15
15
  import { createRoute } from '../lib/http/route.js';
16
16
  import { localeSchema } from '../lib/util/locale.js';
17
- import { narrowAuthorizedParameters } from '../request/request-manager.js';
18
17
  import { requestUriSchema } from '../request/request-uri.js';
19
18
  import { tokenIdSchema } from '../token/token-id.js';
20
19
  import { emailOtpSchema } from '../types/email-otp.js';
@@ -419,20 +418,22 @@ export function createApiMiddleware(server, { onError }) {
419
418
  try {
420
419
  const { account, authorizedClients } = await authenticate.call(this, req, res);
421
420
  const client = await server.clientManager.getClient(clientId);
422
- const code = await server.requestManager.setAuthorized(this.requestUri, client, account, this.deviceId, this.deviceMetadata, this.input.scope);
421
+ const { code, parameters } = await server.requestManager.setAuthorized(this.requestUri, client, account, this.deviceId, this.deviceMetadata, this.input.scope);
422
+ // If the user approved new scopes, update the authorized client
423
+ // accordingly
423
424
  const clientData = authorizedClients.get(clientId);
424
- if (server.checkConsentRequired(parameters, clientData)) {
425
- const scopes = new Set(clientData?.authorizedScopes);
426
- // `parameters` here is the requested set, not the approved one,
427
- // so record the intersection.
428
- // @NOTE `oauthScopeSchema` ensures that `scope` contains no
429
- // leading/trailing/duplicate spaces.
430
- const approved = narrowAuthorizedParameters(parameters, this.input.scope);
431
- for (const s of approved.scope?.split(' ') ?? [])
432
- scopes.add(s);
433
- await server.accountManager.setAuthorizedClient(account, client, {
425
+ const oldAuthorizedScopes = new Set(clientData?.authorizedScopes);
426
+ const newAuthorizedScopes = oldAuthorizedScopes.union(new Set(parameters.scope?.split(' ') ?? []));
427
+ if (clientData == null ||
428
+ newAuthorizedScopes.size !== oldAuthorizedScopes.size) {
429
+ await server.accountManager
430
+ .setAuthorizedClient(account, client, {
434
431
  ...clientData,
435
- authorizedScopes: [...scopes],
432
+ authorizedScopes: [...newAuthorizedScopes],
433
+ })
434
+ .catch((err) => {
435
+ // Errors are non-critical
436
+ onError?.(req, res, err, 'Failed to set authorized client');
436
437
  });
437
438
  }
438
439
  const url = buildRedirectUrl(server.issuer, parameters, { code });
@@ -1 +1 @@
1
- {"version":3,"file":"create-api-middleware.js","sourceRoot":"","sources":["../../src/router/create-api-middleware.ts"],"names":[],"mappings":"AACA,OAAO,eAAe,MAAM,aAAa,CAAA;AACzC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AACvB,OAAO,EAAY,SAAS,EAAE,MAAM,cAAc,CAAA;AAClD,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAA;AAO9C,OAAO,EAAE,mBAAmB,EAAE,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Y,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;YACvC,IAAI,KAAK,IAAI,IAAI;gBAAE,MAAM,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAA;QAC9C,CAAC;IACH,CAAC;SAAM,CAAC;QACN,MAAM,IAAI,mBAAmB,CAC3B,oDAAoD,CACrD,CAAA;IACH,CAAC;IAED,IAAI,CAAC;QACH,MAAM,IAAI,GAAsB,uBAAuB,CAAC,KAAK,CAC3D,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,eAAe,CAAC,CACtC,CAAA;QAED,MAAM,WAAW,GAAqB,sBAAsB,CAAC,KAAK,CAChE,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,cAAc,CAAC,CACrC,CAAA;QAED,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,CAAA;IACtC,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,mBAAmB,CAAC,IAAI,CAAC,GAAG,EAAE,sBAAsB,CAAC,CAAA;IAC7D,CAAC;AACH,CAAC","sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http'\nimport createHttpError from 'http-errors'\nimport { z } from 'zod'\nimport { type Did, didSchema } from '@atproto/did'\nimport { signedJwtSchema } from '@atproto/jwk'\nimport type {\n ActiveAccountSession,\n ActiveOAuthSession,\n ApiEndpoints,\n Session,\n} from '@atproto/oauth-provider-api'\nimport { API_ENDPOINT_PREFIX } from '@atproto/oauth-provider-api'\nimport {\n type OAuthAuthorizationRequestParameters,\n type OAuthRedirectUri,\n type OAuthResponseMode,\n oauthRedirectUriSchema,\n oauthResponseModeSchema,\n oauthScopeSchema,\n} from '@atproto/oauth-types'\nimport type { ISODatetimeString } from '@atproto/syntax'\nimport { signInDataSchema } from '../account/sign-in-data.js'\nimport { signUpInputSchema } from '../account/sign-up-input.js'\nimport { type DeviceId, deviceIdSchema } from '../device/device-id.js'\nimport { AuthorizationError } from '../errors/authorization-error.js'\nimport {\n type ErrorPayload,\n buildErrorPayload,\n buildErrorStatus,\n} from '../errors/error-parser.js'\nimport { InvalidRequestError } from '../errors/invalid-request-error.js'\nimport { WWWAuthenticateError } from '../errors/www-authenticate-error.js'\nimport {\n type JsonResponse,\n type Middleware,\n type RequestMetadata,\n Router,\n type RouterCtx,\n type SubCtx,\n flushStream,\n jsonHandler,\n parseHttpRequest,\n subCtx,\n validateFetchMode,\n validateFetchSite,\n validateOrigin,\n validateReferrer,\n} from '../lib/http/index.js'\nimport { type RouteCtx, createRoute } from '../lib/http/route.js'\nimport { localeSchema } from '../lib/util/locale.js'\nimport type { Awaitable } from '../lib/util/type.js'\nimport type { OAuthProvider } from '../oauth-provider.js'\nimport type { Account, AuthorizedClients } from '../oauth-store.js'\nimport { narrowAuthorizedParameters } from '../request/request-manager.js'\nimport { type RequestUri, requestUriSchema } from '../request/request-uri.js'\nimport type { AuthorizationRedirectParameters } from '../result/authorization-redirect-parameters.js'\nimport { tokenIdSchema } from '../token/token-id.js'\nimport { emailOtpSchema } from '../types/email-otp.js'\nimport { emailSchema, newEmailSchema } from '../types/email.js'\nimport { handleSchema } from '../types/handle.js'\nimport { identifierSchema } from '../types/indentifier.js'\nimport { newPasswordSchema, oldPasswordSchema } from '../types/password.js'\nimport { validateCsrfToken } from './assets/csrf.js'\nimport {\n ERROR_REDIRECT_KEYS,\n type OAuthRedirectOptions,\n type OAuthRedirectQueryParameter,\n SUCCESS_REDIRECT_KEYS,\n buildRedirectMode,\n buildRedirectParams,\n buildRedirectUri,\n} from './assets/send-redirect.js'\nimport type { MiddlewareOptions } from './middleware-options.js'\n\nexport function createApiMiddleware<\n Ctx extends object | void = void,\n Req extends IncomingMessage = IncomingMessage,\n Res extends ServerResponse = ServerResponse,\n>(\n server: OAuthProvider,\n { onError }: MiddlewareOptions<Req, Res>,\n): Middleware<Ctx, Req, Res> {\n const issuerUrl = new URL(server.issuer)\n const issuerOrigin = issuerUrl.origin\n const router = new Router<Ctx, Req, Res>(issuerUrl)\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/verify-handle-availability',\n schema: z.object({ handle: handleSchema }).strict(),\n async handler() {\n await server.accountManager.verifyHandleAvailability(this.input.handle)\n return { json: { available: true } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/sign-up',\n schema: signUpInputSchema,\n rotateDeviceCookies: true,\n async handler() {\n const { deviceId, deviceMetadata, input, requestUri } = this\n\n const clientId = requestUri\n ? await server.requestManager.peekClientId(requestUri)\n : undefined\n\n const { account, remembered } =\n await server.accountManager.createAccount(\n deviceId,\n deviceMetadata,\n input,\n clientId,\n )\n\n const ephemeralToken = remembered\n ? undefined\n : await server.signer.createEphemeralToken({\n sub: account.did,\n deviceId,\n requestUri,\n })\n\n const json = { account, ephemeralToken }\n return { json }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/sign-in',\n schema: signInDataSchema,\n rotateDeviceCookies: true,\n async handler() {\n const { deviceId, deviceMetadata, requestUri } = this\n\n // Look up the client identifier associated with the pending OAuth\n // request, if any, so it can be surfaced to the sign-in hooks.\n const clientId = requestUri\n ? await server.requestManager.peekClientId(requestUri)\n : undefined\n\n const { account, remembered } =\n await server.accountManager.authenticateAccount(\n deviceId,\n deviceMetadata,\n this.input,\n clientId,\n )\n\n // If the user was not \"remembered\", it's device-account association was\n // removed and any future interaction will require an ephemeral token\n // to authenticate the user.\n const ephemeralToken = remembered\n ? undefined\n : await server.signer.createEphemeralToken({\n sub: account.did,\n deviceId,\n requestUri,\n })\n\n return { json: { account, ephemeralToken } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/sign-out',\n schema: z.object({ did: didSchema }).strict(),\n rotateDeviceCookies: true,\n async handler() {\n await server.accountManager.signOut(this.deviceId, this.input.did)\n\n return { json: { success: true } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/reset-password-request',\n schema: z\n .object({\n identifier: identifierSchema,\n locale: localeSchema,\n })\n .strict(),\n async handler() {\n await server.accountManager.resetPasswordRequest(\n this.deviceId,\n this.deviceMetadata,\n this.input,\n )\n return { json: { success: true } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/reset-password-confirm',\n schema: z\n .object({\n token: emailOtpSchema,\n password: newPasswordSchema,\n })\n .strict(),\n async handler() {\n await server.accountManager.resetPasswordConfirm(\n this.deviceId,\n this.deviceMetadata,\n this.input,\n )\n return { json: { success: true } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/update-email-request',\n schema: z\n .object({\n did: didSchema,\n locale: localeSchema.optional(),\n })\n .strict(),\n async handler(req, res) {\n const { account } = await authenticate.call(this, req, res)\n\n const { tokenRequired } =\n await server.accountManager.updateEmailRequest(\n this.deviceId,\n this.deviceMetadata,\n this.input,\n account,\n )\n\n return { json: { tokenRequired } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/update-email-confirm',\n schema: z\n .object({\n did: didSchema,\n email: newEmailSchema,\n token: emailOtpSchema.optional(),\n locale: localeSchema.optional(),\n })\n .strict(),\n async handler(req, res) {\n let { account } = await authenticate.call(this, req, res)\n\n account = await server.accountManager.updateEmailConfirm(\n this.deviceId,\n this.deviceMetadata,\n this.input,\n account,\n )\n\n return { json: { account } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/verify-email-request',\n schema: z\n .object({\n did: didSchema,\n locale: localeSchema.optional(),\n })\n .strict(),\n async handler(req, res) {\n const { account } = await authenticate.call(this, req, res)\n\n await server.accountManager.verifyEmailRequest(\n this.deviceId,\n this.deviceMetadata,\n this.input,\n account,\n )\n\n return { json: { success: true } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/verify-email-confirm',\n schema: z\n .object({\n did: didSchema,\n token: emailOtpSchema,\n email: emailSchema,\n })\n .strict(),\n async handler(req, res) {\n let { account } = await authenticate.call(this, req, res)\n\n account = await server.accountManager.verifyEmailConfirm(\n this.deviceId,\n this.deviceMetadata,\n this.input,\n account,\n )\n\n return { json: { account } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/enable-email-otp',\n schema: z\n .object({\n did: didSchema,\n locale: localeSchema.optional(),\n })\n .strict(),\n async handler(req, res) {\n let { account } = await authenticate.call(this, req, res)\n\n account = await server.accountManager.enableEmailAuthFactor(\n this.deviceId,\n this.deviceMetadata,\n this.input,\n account,\n )\n\n return { json: { account } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/disable-email-otp',\n schema: z\n .object({\n did: didSchema,\n token: emailOtpSchema.optional(),\n locale: localeSchema.optional(),\n })\n .strict(),\n async handler(req, res) {\n let { account } = await authenticate.call(this, req, res)\n\n // @NOTE Phase 1 (no token provided) will cause an\n // SecondAuthenticationFactorRequiredError to be thrown, prompting the\n // client to provide the required token. Phase 2 (with a valid token)\n // will then disable the factor.\n account = await server.accountManager.disableEmailAuthFactor(\n this.deviceId,\n this.deviceMetadata,\n this.input,\n account,\n )\n\n return { json: { account } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/update-handle',\n schema: z\n .object({\n did: didSchema,\n handle: handleSchema,\n })\n .strict(),\n async handler(req, res) {\n let { account } = await authenticate.call(this, req, res)\n\n account = await server.accountManager.updateHandle(\n this.deviceId,\n this.deviceMetadata,\n this.input,\n account,\n )\n\n return { json: { account } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/deactivate-account',\n schema: z.object({ did: didSchema }).strict(),\n async handler(req, res) {\n let { account } = await authenticate.call(this, req, res)\n\n if (!account.deactivated) {\n account = await server.accountManager.deactivateAccount(\n this.deviceId,\n this.deviceMetadata,\n account,\n )\n }\n\n return { json: { account } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/reactivate-account',\n schema: z.object({ did: didSchema }).strict(),\n async handler(req, res) {\n let { account } = await authenticate.call(this, req, res)\n\n if (account.deactivated) {\n account = await server.accountManager.reactivateAccount(\n this.deviceId,\n this.deviceMetadata,\n account,\n )\n }\n\n return { json: { account } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/delete-account-request',\n schema: z\n .object({ did: didSchema, locale: localeSchema.optional() })\n .strict(),\n async handler(req, res) {\n const { account } = await authenticate.call(this, req, res)\n\n await server.accountManager.deleteAccountRequest(\n this.deviceId,\n this.deviceMetadata,\n this.input,\n account,\n )\n\n return { json: { success: true } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/delete-account-confirm',\n schema: z\n .object({\n did: didSchema,\n token: emailOtpSchema,\n password: oldPasswordSchema,\n })\n .strict(),\n async handler(req, res) {\n const { account } = await authenticate.call(this, req, res)\n\n await server.accountManager.deleteAccountConfirm(\n this.deviceId,\n this.deviceMetadata,\n this.input,\n account,\n )\n\n return { json: { success: true } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'GET',\n endpoint: '/device-sessions',\n schema: undefined,\n async handler() {\n const deviceAccounts = await server.accountManager.listDeviceAccounts(\n this.deviceId,\n )\n\n const json = deviceAccounts.map((deviceAccount): Session => ({\n account: deviceAccount.account,\n loginRequired: server.checkLoginRequired(deviceAccount),\n }))\n\n return { json }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'GET',\n endpoint: '/oauth-sessions',\n schema: z.object({ did: didSchema }).strict(),\n async handler(req, res) {\n const { account } = await authenticate.call(this, req, res)\n\n const tokenInfos = await server.tokenManager.listAccountTokens(\n account.did,\n )\n\n const clientIds = tokenInfos.map((tokenInfo) => tokenInfo.data.clientId)\n\n const clients = await server.clientManager.loadClients(clientIds, {\n onError: (err, clientId) => {\n onError?.(req, res, err, `Failed to load client ${clientId}`)\n return undefined // metadata won't be available in the UI\n },\n })\n\n const json = tokenInfos\n .filter(({ data }) => {\n // Remove sessions that are expired, based on the maximum possible\n // lifetime of a session. The client metadata is needed to determine\n // the actual session and refresh lifetimes.\n\n const client = clients.get(data.clientId)\n\n // We were not able to load the client (see onError callback above).\n // In this case, we will keep the session in the list, and let the\n // UI show them as \"broken\" sessions (based on the absence of the\n // clientMetadata in ActiveOAuthSession).\n if (!client) return true\n\n const sessionAge = Date.now() - data.createdAt.getTime()\n if (sessionAge > client.sessionLifetime) return false\n\n const refreshAge = Date.now() - data.updatedAt.getTime()\n if (refreshAge > client.refreshLifetime) return false\n\n // If the client cannot refresh, then the session is only valid if\n // it has not yet expired.\n if (!client.metadata.grant_types.includes('refresh_token')) {\n return data.expiresAt.getTime() > Date.now()\n }\n\n return true\n })\n .map(({ id, data }): ActiveOAuthSession => {\n return {\n tokenId: id,\n\n createdAt: data.createdAt.toISOString() as ISODatetimeString,\n updatedAt: data.updatedAt.toISOString() as ISODatetimeString,\n\n clientId: data.clientId,\n clientMetadata: clients.get(data.clientId)?.metadata,\n\n active: data.expiresAt.getTime() > Date.now(),\n scope: data.parameters.scope,\n }\n })\n\n return { json }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'GET',\n endpoint: '/account-sessions',\n schema: z.object({ did: didSchema }).strict(),\n async handler(req, res) {\n const { account } = await authenticate.call(this, req, res)\n\n const deviceAccounts = await server.accountManager.listAccountDevices(\n account.did,\n )\n\n const json = deviceAccounts.map(\n (accountSession): ActiveAccountSession => ({\n deviceId: accountSession.deviceId,\n deviceMetadata: {\n ipAddress: accountSession.deviceData.ipAddress,\n userAgent: accountSession.deviceData.userAgent,\n lastSeenAt:\n accountSession.deviceData.lastSeenAt.toISOString() as ISODatetimeString,\n },\n\n isCurrentDevice: accountSession.deviceId === this.deviceId,\n }),\n )\n\n return { json }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/revoke-account-session',\n schema: z.object({ did: didSchema, deviceId: deviceIdSchema }).strict(),\n async handler() {\n // @NOTE This route is not authenticated. If a user is able to steal\n // another user's session cookie, we allow them to revoke the device\n // session.\n\n await server.accountManager.signOut(this.input.deviceId, this.input.did)\n\n return { json: { success: true } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/revoke-oauth-session',\n schema: z.object({ did: didSchema, tokenId: tokenIdSchema }).strict(),\n async handler(req, res) {\n const { account } = await authenticate.call(this, req, res)\n\n const tokenInfo = await server.tokenManager.getTokenInfo(\n this.input.tokenId,\n )\n\n if (!tokenInfo || tokenInfo.account.did !== account.did) {\n // report this as though the token was not found\n throw new InvalidRequestError(`Invalid token`)\n }\n\n await server.tokenManager.deleteToken(tokenInfo.id)\n\n return { json: { success: true } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/consent',\n schema: z\n .object({ did: didSchema, scope: oauthScopeSchema.optional() })\n .strict(),\n async handler(req, res) {\n if (!this.requestUri) {\n throw new InvalidRequestError(\n 'This endpoint can only be used in the context of an OAuth request',\n )\n }\n\n // Any AuthorizationError caught in this block will result in a redirect\n // to the client's redirect_uri with an error.\n try {\n const { clientId, parameters } = await server.requestManager.get(\n this.requestUri,\n this.deviceId,\n )\n\n // Any error thrown in this block will be transformed into an\n // AuthorizationError.\n try {\n const { account, authorizedClients } = await authenticate.call(\n this,\n req,\n res,\n )\n\n const client = await server.clientManager.getClient(clientId)\n\n const code = await server.requestManager.setAuthorized(\n this.requestUri,\n client,\n account,\n this.deviceId,\n this.deviceMetadata,\n this.input.scope,\n )\n\n const clientData = authorizedClients.get(clientId)\n if (server.checkConsentRequired(parameters, clientData)) {\n const scopes = new Set(clientData?.authorizedScopes)\n\n // `parameters` here is the requested set, not the approved one,\n // so record the intersection.\n\n // @NOTE `oauthScopeSchema` ensures that `scope` contains no\n // leading/trailing/duplicate spaces.\n const approved = narrowAuthorizedParameters(\n parameters,\n this.input.scope,\n )\n for (const s of approved.scope?.split(' ') ?? []) scopes.add(s)\n\n await server.accountManager.setAuthorizedClient(account, client, {\n ...clientData,\n authorizedScopes: [...scopes],\n })\n }\n\n const url = buildRedirectUrl(server.issuer, parameters, { code })\n\n return { json: { url } }\n } catch (err) {\n // Since we have access to the parameters, we can re-throw an\n // AuthorizationError with the redirect_uri parameter.\n throw AuthorizationError.from(parameters, err)\n }\n } catch (err) {\n onError?.(req, res, err, 'Failed to consent authorization request')\n\n // If any error happened (unauthenticated, invalid request, etc.),\n // lets make sure the request can no longer be used.\n try {\n await server.requestManager.delete(this.requestUri)\n } catch (err) {\n onError?.(req, res, err, 'Failed to delete request')\n }\n\n if (err instanceof AuthorizationError) {\n try {\n const url = buildRedirectUrl(\n server.issuer,\n err.parameters,\n err.toJSON(),\n )\n\n return { json: { url } }\n } catch {\n // Unable to build redirect URL, ignore\n }\n }\n\n // @NOTE Not re-throwing the error here, as the error was already\n // handled by the `onError` callback, and apiRoute (`apiMiddleware`)\n // would call `onError` again.\n return buildErrorJsonResponse(err)\n }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/reject',\n schema: z.object({}).strict(),\n rotateDeviceCookies: true,\n async handler(req, res) {\n const { requestUri } = this\n if (!requestUri) {\n throw new InvalidRequestError(\n 'This endpoint can only be used in the context of an OAuth request',\n )\n }\n\n // Once this endpoint is called, the request will definitely be\n // rejected.\n try {\n // No need to authenticate the user here as they are not authorizing a\n // particular account (CSRF protection is enough).\n\n // @NOTE that the client could *technically* trigger this endpoint while\n // the user is on the authorize page by forging the request (because the\n // client knows the RequestURI from PAR and has all the info needed to\n // forge the request, including CSRF). This cannot be used as DoS attack\n // as the request ID is not guessable and would only result in a bad UX\n // for misbehaving clients, only for the users of those clients.\n\n const { parameters } = await server.requestManager.get(\n requestUri,\n this.deviceId,\n )\n\n const url = buildRedirectUrl(server.issuer, parameters, {\n error: 'access_denied',\n error_description: 'The user rejected the request',\n })\n\n return { json: { url } }\n } catch (err) {\n onError?.(req, res, err, 'Failed to reject authorization request')\n\n if (err instanceof AuthorizationError) {\n try {\n const url = buildRedirectUrl(\n server.issuer,\n err.parameters,\n err.toJSON(),\n )\n\n return { json: { url } }\n } catch {\n // Unable to build redirect URL, ignore\n }\n }\n\n return buildErrorJsonResponse(err)\n } finally {\n await server.requestManager.delete(requestUri).catch((err) => {\n onError?.(req, res, err, 'Failed to delete request')\n })\n }\n },\n }),\n )\n\n return router.buildMiddleware()\n\n async function authenticate(\n this: ApiContext<void, { did: Did }>,\n req: Req,\n _res: Res,\n ): Promise<{\n account: Account\n authorizedClients: AuthorizedClients\n }> {\n if (req.headers.authorization?.startsWith('Bearer ')) {\n try {\n // If there is an authorization header, verify that the ephemeral token it\n // contains is a jwt bound to the right [sub, device, request].\n const bearer = req.headers.authorization.slice(7)\n const ephemeralToken = signedJwtSchema.parse(bearer)\n const { payload } =\n await server.signer.verifyEphemeralToken(ephemeralToken)\n\n if (\n payload.sub === this.input.did &&\n payload.deviceId === this.deviceId &&\n payload.requestUri === this.requestUri\n ) {\n const accountData = await server.accountManager.getAccount(\n payload.sub,\n )\n if (accountData) return accountData\n throw new WWWAuthenticateError(\n 'unauthorized',\n `User ${payload.sub} does not exist`,\n { Bearer: {} },\n )\n }\n } catch (err) {\n throw err instanceof WWWAuthenticateError\n ? err\n : new WWWAuthenticateError(\n 'unauthorized',\n `Invalid or expired bearer token`,\n { Bearer: {} },\n err,\n )\n }\n }\n\n try {\n // Ensures the \"sub\" has an active session on the device\n const deviceAccount = await server.accountManager.getDeviceAccount(\n this.deviceId,\n this.input.did,\n )\n\n // The session exists but was created too long ago\n if (server.checkLoginRequired(deviceAccount)) {\n throw new InvalidRequestError('Login required')\n }\n\n return deviceAccount\n } catch (err) {\n throw new WWWAuthenticateError(\n 'unauthorized',\n `User ${this.input.did} not authenticated on this device`,\n { Bearer: {} },\n err,\n )\n }\n }\n\n type ApiContext<T extends object | void, I = void> = SubCtx<\n T,\n {\n deviceId: DeviceId\n deviceMetadata: RequestMetadata\n\n /**\n * The parsed input data (json payload if \"POST\", query params if \"GET\").\n */\n input: I\n\n /**\n * When defined, the request originated from the authorize page.\n */\n requestUri?: RequestUri\n }\n >\n\n type InferValidation<S extends void | z.ZodTypeAny> = S extends z.ZodTypeAny\n ? z.infer<S>\n : void\n\n /**\n * The main purpose of this function is to ensure that the endpoint\n * implementation matches its type definition from {@link ApiEndpoints}.\n * @private\n */\n function apiRoute<\n C extends RouterCtx<Ctx>,\n M extends 'GET' | 'POST',\n E extends `/${string}` &\n // Extract all the endpoint path that match the method (allows for\n // auto-complete & better error reporting)\n {\n [E in keyof ApiEndpoints]: ApiEndpoints[E] extends { method: M }\n ? E\n : never\n }[keyof ApiEndpoints],\n S extends // A schema that validates the POST input or GET params\n (ApiEndpoints[E] extends { method: 'POST'; input: infer I }\n ? z.ZodType<I, z.ZodTypeDef, unknown>\n : ApiEndpoints[E] extends { method: 'GET'; params: infer P }\n ? z.ZodType<P, z.ZodTypeDef, unknown>\n : void),\n >(options: {\n method: M\n endpoint: E\n schema: S\n rotateDeviceCookies?: boolean\n handler: (\n this: ApiContext<RouteCtx<C>, InferValidation<S>>,\n req: Req,\n res: Res,\n ) => Awaitable<JsonResponse<ErrorPayload | ApiEndpoints[E]['output']>>\n }): Middleware<C, Req, Res> {\n return createRoute(\n options.method,\n `${API_ENDPOINT_PREFIX}${options.endpoint}`,\n apiMiddleware(options),\n )\n }\n\n function apiMiddleware<C extends RouterCtx, S extends void | z.ZodTypeAny>({\n method,\n schema,\n rotateDeviceCookies,\n handler,\n }: {\n method: 'GET' | 'POST'\n schema: S\n rotateDeviceCookies?: boolean\n handler: (\n this: ApiContext<C, InferValidation<S>>,\n req: Req,\n res: Res,\n ) => Awaitable<JsonResponse>\n }): Middleware<C, Req, Res> {\n const parseInput: (this: C, req: Req) => Promise<InferValidation<S>> =\n schema == null // No schema means endpoint doesn't accept any input\n ? async function (req) {\n await flushStream(req)\n return undefined\n }\n : method === 'POST'\n ? async function (req) {\n const body = await parseHttpRequest(req, ['json'])\n return schema.parseAsync(body, { path: ['body'] })\n }\n : async function (req) {\n await flushStream(req)\n const query = Object.fromEntries(this.url.searchParams)\n return schema.parseAsync(query, { path: ['query'] })\n }\n\n return jsonHandler<C, Req, Res>(async function (req, res) {\n try {\n // Prevent caching of API routes\n res.setHeader('Cache-Control', 'no-store')\n res.setHeader('Pragma', 'no-cache')\n\n // Prevent CORS requests\n validateFetchMode(req, ['same-origin'])\n validateFetchSite(req, ['same-origin'])\n validateOrigin(req, issuerOrigin)\n const referrer = validateReferrer(req, { origin: issuerOrigin })\n\n // Ensure we are one the right page\n if (\n // trailing slashes are not allowed\n referrer.pathname !== '/oauth/authorize' &&\n referrer.pathname !== '/account' &&\n !referrer.pathname.startsWith(`/account/`)\n ) {\n throw createHttpError(400, `Invalid referrer ${referrer}`)\n }\n\n // Check if the request originated from the authorize page\n const requestUri =\n referrer.pathname === '/oauth/authorize'\n ? await requestUriSchema.parseAsync(\n referrer.searchParams.get('request_uri'),\n )\n : undefined\n\n // Validate CSRF token\n await validateCsrfToken(req, res)\n\n // Parse and validate the input data\n const input = await parseInput.call(this, req)\n\n // Load session data, rotating the session cookie if needed\n const { deviceId, deviceMetadata } = await server.deviceManager.load(\n req,\n res,\n rotateDeviceCookies,\n )\n\n const context: ApiContext<C, InferValidation<S>> = subCtx(this, {\n input,\n requestUri,\n deviceId,\n deviceMetadata,\n })\n\n return await handler.call(context, req, res)\n } catch (err) {\n onError?.(req, res, err, `Failed to handle API request`)\n\n // Make sore to always return a JSON response\n return buildErrorJsonResponse(err)\n }\n })\n }\n}\n\nfunction buildErrorJsonResponse(err: unknown) {\n // @TODO Rework the API error responses (relying on codes)\n const json = buildErrorPayload(err)\n const status = buildErrorStatus(err)\n\n return { json, status }\n}\n\nfunction buildRedirectUrl(\n iss: string,\n parameters: OAuthAuthorizationRequestParameters,\n redirect: AuthorizationRedirectParameters,\n): string {\n const url = new URL('/oauth/authorize/redirect', iss)\n\n url.searchParams.set('redirect_mode', buildRedirectMode(parameters))\n url.searchParams.set('redirect_uri', buildRedirectUri(parameters))\n\n for (const [key, value] of buildRedirectParams(iss, parameters, redirect)) {\n url.searchParams.set(key, value)\n }\n\n return url.href\n}\n\nexport function parseRedirectUrl(url: URL): OAuthRedirectOptions {\n if (url.pathname !== '/oauth/authorize/redirect') {\n throw new InvalidRequestError(\n `Invalid redirect URL: ${url.pathname} is not a valid path`,\n )\n }\n\n const params: [OAuthRedirectQueryParameter, string][] = []\n\n const state = url.searchParams.get('state')\n if (state) params.push(['state', state])\n\n const iss = url.searchParams.get('iss')\n if (iss) params.push(['iss', iss])\n\n if (url.searchParams.has('code')) {\n for (const key of SUCCESS_REDIRECT_KEYS) {\n const value = url.searchParams.get(key)\n if (value != null) params.push([key, value])\n }\n } else if (url.searchParams.has('error')) {\n for (const key of ERROR_REDIRECT_KEYS) {\n const value = url.searchParams.get(key)\n if (value != null) params.push([key, value])\n }\n } else {\n throw new InvalidRequestError(\n 'Invalid redirect URL: neither code nor error found',\n )\n }\n\n try {\n const mode: OAuthResponseMode = oauthResponseModeSchema.parse(\n url.searchParams.get('redirect_mode'),\n )\n\n const redirectUri: OAuthRedirectUri = oauthRedirectUriSchema.parse(\n url.searchParams.get('redirect_uri'),\n )\n\n return { mode, redirectUri, params }\n } catch (err) {\n throw InvalidRequestError.from(err, 'Invalid redirect URL')\n }\n}\n"]}
1
+ {"version":3,"file":"create-api-middleware.js","sourceRoot":"","sources":["../../src/router/create-api-middleware.ts"],"names":[],"mappings":"AACA,OAAO,eAAe,MAAM,aAAa,CAAA;AACzC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AACvB,OAAO,EAAY,SAAS,EAAE,MAAM,cAAc,CAAA;AAClD,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAA;AAO9C,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAA;AACjE,OAAO,EAIL,sBAAsB,EACtB,uBAAuB,EACvB,gBAAgB,GACjB,MAAM,sBAAsB,CAAA;AAE7B,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,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AK,CAAC,CAAC,CAAA;QAC9C,CAAC;IACH,CAAC;SAAM,CAAC;QACN,MAAM,IAAI,mBAAmB,CAC3B,oDAAoD,CACrD,CAAA;IACH,CAAC;IAED,IAAI,CAAC;QACH,MAAM,IAAI,GAAsB,uBAAuB,CAAC,KAAK,CAC3D,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,eAAe,CAAC,CACtC,CAAA;QAED,MAAM,WAAW,GAAqB,sBAAsB,CAAC,KAAK,CAChE,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,cAAc,CAAC,CACrC,CAAA;QAED,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,CAAA;IACtC,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,mBAAmB,CAAC,IAAI,CAAC,GAAG,EAAE,sBAAsB,CAAC,CAAA;IAC7D,CAAC;AACH,CAAC","sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http'\nimport createHttpError from 'http-errors'\nimport { z } from 'zod'\nimport { type Did, didSchema } from '@atproto/did'\nimport { signedJwtSchema } from '@atproto/jwk'\nimport type {\n ActiveAccountSession,\n ActiveOAuthSession,\n ApiEndpoints,\n Session,\n} from '@atproto/oauth-provider-api'\nimport { API_ENDPOINT_PREFIX } from '@atproto/oauth-provider-api'\nimport {\n type OAuthAuthorizationRequestParameters,\n type OAuthRedirectUri,\n type OAuthResponseMode,\n oauthRedirectUriSchema,\n oauthResponseModeSchema,\n oauthScopeSchema,\n} from '@atproto/oauth-types'\nimport type { ISODatetimeString } from '@atproto/syntax'\nimport { signInDataSchema } from '../account/sign-in-data.js'\nimport { signUpInputSchema } from '../account/sign-up-input.js'\nimport { type DeviceId, deviceIdSchema } from '../device/device-id.js'\nimport { AuthorizationError } from '../errors/authorization-error.js'\nimport {\n type ErrorPayload,\n buildErrorPayload,\n buildErrorStatus,\n} from '../errors/error-parser.js'\nimport { InvalidRequestError } from '../errors/invalid-request-error.js'\nimport { WWWAuthenticateError } from '../errors/www-authenticate-error.js'\nimport {\n type JsonResponse,\n type Middleware,\n type RequestMetadata,\n Router,\n type RouterCtx,\n type SubCtx,\n flushStream,\n jsonHandler,\n parseHttpRequest,\n subCtx,\n validateFetchMode,\n validateFetchSite,\n validateOrigin,\n validateReferrer,\n} from '../lib/http/index.js'\nimport { type RouteCtx, createRoute } from '../lib/http/route.js'\nimport { localeSchema } from '../lib/util/locale.js'\nimport type { Awaitable } from '../lib/util/type.js'\nimport type { OAuthProvider } from '../oauth-provider.js'\nimport type { Account, AuthorizedClients } from '../oauth-store.js'\nimport { type RequestUri, requestUriSchema } from '../request/request-uri.js'\nimport type { AuthorizationRedirectParameters } from '../result/authorization-redirect-parameters.js'\nimport { tokenIdSchema } from '../token/token-id.js'\nimport { emailOtpSchema } from '../types/email-otp.js'\nimport { emailSchema, newEmailSchema } from '../types/email.js'\nimport { handleSchema } from '../types/handle.js'\nimport { identifierSchema } from '../types/indentifier.js'\nimport { newPasswordSchema, oldPasswordSchema } from '../types/password.js'\nimport { validateCsrfToken } from './assets/csrf.js'\nimport {\n ERROR_REDIRECT_KEYS,\n type OAuthRedirectOptions,\n type OAuthRedirectQueryParameter,\n SUCCESS_REDIRECT_KEYS,\n buildRedirectMode,\n buildRedirectParams,\n buildRedirectUri,\n} from './assets/send-redirect.js'\nimport type { MiddlewareOptions } from './middleware-options.js'\n\nexport function createApiMiddleware<\n Ctx extends object | void = void,\n Req extends IncomingMessage = IncomingMessage,\n Res extends ServerResponse = ServerResponse,\n>(\n server: OAuthProvider,\n { onError }: MiddlewareOptions<Req, Res>,\n): Middleware<Ctx, Req, Res> {\n const issuerUrl = new URL(server.issuer)\n const issuerOrigin = issuerUrl.origin\n const router = new Router<Ctx, Req, Res>(issuerUrl)\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/verify-handle-availability',\n schema: z.object({ handle: handleSchema }).strict(),\n async handler() {\n await server.accountManager.verifyHandleAvailability(this.input.handle)\n return { json: { available: true } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/sign-up',\n schema: signUpInputSchema,\n rotateDeviceCookies: true,\n async handler() {\n const { deviceId, deviceMetadata, input, requestUri } = this\n\n const clientId = requestUri\n ? await server.requestManager.peekClientId(requestUri)\n : undefined\n\n const { account, remembered } =\n await server.accountManager.createAccount(\n deviceId,\n deviceMetadata,\n input,\n clientId,\n )\n\n const ephemeralToken = remembered\n ? undefined\n : await server.signer.createEphemeralToken({\n sub: account.did,\n deviceId,\n requestUri,\n })\n\n const json = { account, ephemeralToken }\n return { json }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/sign-in',\n schema: signInDataSchema,\n rotateDeviceCookies: true,\n async handler() {\n const { deviceId, deviceMetadata, requestUri } = this\n\n // Look up the client identifier associated with the pending OAuth\n // request, if any, so it can be surfaced to the sign-in hooks.\n const clientId = requestUri\n ? await server.requestManager.peekClientId(requestUri)\n : undefined\n\n const { account, remembered } =\n await server.accountManager.authenticateAccount(\n deviceId,\n deviceMetadata,\n this.input,\n clientId,\n )\n\n // If the user was not \"remembered\", it's device-account association was\n // removed and any future interaction will require an ephemeral token\n // to authenticate the user.\n const ephemeralToken = remembered\n ? undefined\n : await server.signer.createEphemeralToken({\n sub: account.did,\n deviceId,\n requestUri,\n })\n\n return { json: { account, ephemeralToken } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/sign-out',\n schema: z.object({ did: didSchema }).strict(),\n rotateDeviceCookies: true,\n async handler() {\n await server.accountManager.signOut(this.deviceId, this.input.did)\n\n return { json: { success: true } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/reset-password-request',\n schema: z\n .object({\n identifier: identifierSchema,\n locale: localeSchema,\n })\n .strict(),\n async handler() {\n await server.accountManager.resetPasswordRequest(\n this.deviceId,\n this.deviceMetadata,\n this.input,\n )\n return { json: { success: true } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/reset-password-confirm',\n schema: z\n .object({\n token: emailOtpSchema,\n password: newPasswordSchema,\n })\n .strict(),\n async handler() {\n await server.accountManager.resetPasswordConfirm(\n this.deviceId,\n this.deviceMetadata,\n this.input,\n )\n return { json: { success: true } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/update-email-request',\n schema: z\n .object({\n did: didSchema,\n locale: localeSchema.optional(),\n })\n .strict(),\n async handler(req, res) {\n const { account } = await authenticate.call(this, req, res)\n\n const { tokenRequired } =\n await server.accountManager.updateEmailRequest(\n this.deviceId,\n this.deviceMetadata,\n this.input,\n account,\n )\n\n return { json: { tokenRequired } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/update-email-confirm',\n schema: z\n .object({\n did: didSchema,\n email: newEmailSchema,\n token: emailOtpSchema.optional(),\n locale: localeSchema.optional(),\n })\n .strict(),\n async handler(req, res) {\n let { account } = await authenticate.call(this, req, res)\n\n account = await server.accountManager.updateEmailConfirm(\n this.deviceId,\n this.deviceMetadata,\n this.input,\n account,\n )\n\n return { json: { account } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/verify-email-request',\n schema: z\n .object({\n did: didSchema,\n locale: localeSchema.optional(),\n })\n .strict(),\n async handler(req, res) {\n const { account } = await authenticate.call(this, req, res)\n\n await server.accountManager.verifyEmailRequest(\n this.deviceId,\n this.deviceMetadata,\n this.input,\n account,\n )\n\n return { json: { success: true } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/verify-email-confirm',\n schema: z\n .object({\n did: didSchema,\n token: emailOtpSchema,\n email: emailSchema,\n })\n .strict(),\n async handler(req, res) {\n let { account } = await authenticate.call(this, req, res)\n\n account = await server.accountManager.verifyEmailConfirm(\n this.deviceId,\n this.deviceMetadata,\n this.input,\n account,\n )\n\n return { json: { account } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/enable-email-otp',\n schema: z\n .object({\n did: didSchema,\n locale: localeSchema.optional(),\n })\n .strict(),\n async handler(req, res) {\n let { account } = await authenticate.call(this, req, res)\n\n account = await server.accountManager.enableEmailAuthFactor(\n this.deviceId,\n this.deviceMetadata,\n this.input,\n account,\n )\n\n return { json: { account } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/disable-email-otp',\n schema: z\n .object({\n did: didSchema,\n token: emailOtpSchema.optional(),\n locale: localeSchema.optional(),\n })\n .strict(),\n async handler(req, res) {\n let { account } = await authenticate.call(this, req, res)\n\n // @NOTE Phase 1 (no token provided) will cause an\n // SecondAuthenticationFactorRequiredError to be thrown, prompting the\n // client to provide the required token. Phase 2 (with a valid token)\n // will then disable the factor.\n account = await server.accountManager.disableEmailAuthFactor(\n this.deviceId,\n this.deviceMetadata,\n this.input,\n account,\n )\n\n return { json: { account } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/update-handle',\n schema: z\n .object({\n did: didSchema,\n handle: handleSchema,\n })\n .strict(),\n async handler(req, res) {\n let { account } = await authenticate.call(this, req, res)\n\n account = await server.accountManager.updateHandle(\n this.deviceId,\n this.deviceMetadata,\n this.input,\n account,\n )\n\n return { json: { account } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/deactivate-account',\n schema: z.object({ did: didSchema }).strict(),\n async handler(req, res) {\n let { account } = await authenticate.call(this, req, res)\n\n if (!account.deactivated) {\n account = await server.accountManager.deactivateAccount(\n this.deviceId,\n this.deviceMetadata,\n account,\n )\n }\n\n return { json: { account } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/reactivate-account',\n schema: z.object({ did: didSchema }).strict(),\n async handler(req, res) {\n let { account } = await authenticate.call(this, req, res)\n\n if (account.deactivated) {\n account = await server.accountManager.reactivateAccount(\n this.deviceId,\n this.deviceMetadata,\n account,\n )\n }\n\n return { json: { account } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/delete-account-request',\n schema: z\n .object({ did: didSchema, locale: localeSchema.optional() })\n .strict(),\n async handler(req, res) {\n const { account } = await authenticate.call(this, req, res)\n\n await server.accountManager.deleteAccountRequest(\n this.deviceId,\n this.deviceMetadata,\n this.input,\n account,\n )\n\n return { json: { success: true } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/delete-account-confirm',\n schema: z\n .object({\n did: didSchema,\n token: emailOtpSchema,\n password: oldPasswordSchema,\n })\n .strict(),\n async handler(req, res) {\n const { account } = await authenticate.call(this, req, res)\n\n await server.accountManager.deleteAccountConfirm(\n this.deviceId,\n this.deviceMetadata,\n this.input,\n account,\n )\n\n return { json: { success: true } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'GET',\n endpoint: '/device-sessions',\n schema: undefined,\n async handler() {\n const deviceAccounts = await server.accountManager.listDeviceAccounts(\n this.deviceId,\n )\n\n const json = deviceAccounts.map((deviceAccount): Session => ({\n account: deviceAccount.account,\n loginRequired: server.checkLoginRequired(deviceAccount),\n }))\n\n return { json }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'GET',\n endpoint: '/oauth-sessions',\n schema: z.object({ did: didSchema }).strict(),\n async handler(req, res) {\n const { account } = await authenticate.call(this, req, res)\n\n const tokenInfos = await server.tokenManager.listAccountTokens(\n account.did,\n )\n\n const clientIds = tokenInfos.map((tokenInfo) => tokenInfo.data.clientId)\n\n const clients = await server.clientManager.loadClients(clientIds, {\n onError: (err, clientId) => {\n onError?.(req, res, err, `Failed to load client ${clientId}`)\n return undefined // metadata won't be available in the UI\n },\n })\n\n const json = tokenInfos\n .filter(({ data }) => {\n // Remove sessions that are expired, based on the maximum possible\n // lifetime of a session. The client metadata is needed to determine\n // the actual session and refresh lifetimes.\n\n const client = clients.get(data.clientId)\n\n // We were not able to load the client (see onError callback above).\n // In this case, we will keep the session in the list, and let the\n // UI show them as \"broken\" sessions (based on the absence of the\n // clientMetadata in ActiveOAuthSession).\n if (!client) return true\n\n const sessionAge = Date.now() - data.createdAt.getTime()\n if (sessionAge > client.sessionLifetime) return false\n\n const refreshAge = Date.now() - data.updatedAt.getTime()\n if (refreshAge > client.refreshLifetime) return false\n\n // If the client cannot refresh, then the session is only valid if\n // it has not yet expired.\n if (!client.metadata.grant_types.includes('refresh_token')) {\n return data.expiresAt.getTime() > Date.now()\n }\n\n return true\n })\n .map(({ id, data }): ActiveOAuthSession => {\n return {\n tokenId: id,\n\n createdAt: data.createdAt.toISOString() as ISODatetimeString,\n updatedAt: data.updatedAt.toISOString() as ISODatetimeString,\n\n clientId: data.clientId,\n clientMetadata: clients.get(data.clientId)?.metadata,\n\n active: data.expiresAt.getTime() > Date.now(),\n scope: data.parameters.scope,\n }\n })\n\n return { json }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'GET',\n endpoint: '/account-sessions',\n schema: z.object({ did: didSchema }).strict(),\n async handler(req, res) {\n const { account } = await authenticate.call(this, req, res)\n\n const deviceAccounts = await server.accountManager.listAccountDevices(\n account.did,\n )\n\n const json = deviceAccounts.map(\n (accountSession): ActiveAccountSession => ({\n deviceId: accountSession.deviceId,\n deviceMetadata: {\n ipAddress: accountSession.deviceData.ipAddress,\n userAgent: accountSession.deviceData.userAgent,\n lastSeenAt:\n accountSession.deviceData.lastSeenAt.toISOString() as ISODatetimeString,\n },\n\n isCurrentDevice: accountSession.deviceId === this.deviceId,\n }),\n )\n\n return { json }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/revoke-account-session',\n schema: z.object({ did: didSchema, deviceId: deviceIdSchema }).strict(),\n async handler() {\n // @NOTE This route is not authenticated. If a user is able to steal\n // another user's session cookie, we allow them to revoke the device\n // session.\n\n await server.accountManager.signOut(this.input.deviceId, this.input.did)\n\n return { json: { success: true } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/revoke-oauth-session',\n schema: z.object({ did: didSchema, tokenId: tokenIdSchema }).strict(),\n async handler(req, res) {\n const { account } = await authenticate.call(this, req, res)\n\n const tokenInfo = await server.tokenManager.getTokenInfo(\n this.input.tokenId,\n )\n\n if (!tokenInfo || tokenInfo.account.did !== account.did) {\n // report this as though the token was not found\n throw new InvalidRequestError(`Invalid token`)\n }\n\n await server.tokenManager.deleteToken(tokenInfo.id)\n\n return { json: { success: true } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/consent',\n schema: z\n .object({ did: didSchema, scope: oauthScopeSchema.optional() })\n .strict(),\n async handler(req, res) {\n if (!this.requestUri) {\n throw new InvalidRequestError(\n 'This endpoint can only be used in the context of an OAuth request',\n )\n }\n\n // Any AuthorizationError caught in this block will result in a redirect\n // to the client's redirect_uri with an error.\n try {\n const { clientId, parameters } = await server.requestManager.get(\n this.requestUri,\n this.deviceId,\n )\n\n // Any error thrown in this block will be transformed into an\n // AuthorizationError.\n try {\n const { account, authorizedClients } = await authenticate.call(\n this,\n req,\n res,\n )\n\n const client = await server.clientManager.getClient(clientId)\n\n const { code, parameters } =\n await server.requestManager.setAuthorized(\n this.requestUri,\n client,\n account,\n this.deviceId,\n this.deviceMetadata,\n this.input.scope,\n )\n\n // If the user approved new scopes, update the authorized client\n // accordingly\n const clientData = authorizedClients.get(clientId)\n const oldAuthorizedScopes = new Set(clientData?.authorizedScopes)\n const newAuthorizedScopes = oldAuthorizedScopes.union(\n new Set(parameters.scope?.split(' ') ?? []),\n )\n if (\n clientData == null ||\n newAuthorizedScopes.size !== oldAuthorizedScopes.size\n ) {\n await server.accountManager\n .setAuthorizedClient(account, client, {\n ...clientData,\n authorizedScopes: [...newAuthorizedScopes],\n })\n .catch((err) => {\n // Errors are non-critical\n onError?.(req, res, err, 'Failed to set authorized client')\n })\n }\n\n const url = buildRedirectUrl(server.issuer, parameters, { code })\n\n return { json: { url } }\n } catch (err) {\n // Since we have access to the parameters, we can re-throw an\n // AuthorizationError with the redirect_uri parameter.\n throw AuthorizationError.from(parameters, err)\n }\n } catch (err) {\n onError?.(req, res, err, 'Failed to consent authorization request')\n\n // If any error happened (unauthenticated, invalid request, etc.),\n // lets make sure the request can no longer be used.\n try {\n await server.requestManager.delete(this.requestUri)\n } catch (err) {\n onError?.(req, res, err, 'Failed to delete request')\n }\n\n if (err instanceof AuthorizationError) {\n try {\n const url = buildRedirectUrl(\n server.issuer,\n err.parameters,\n err.toJSON(),\n )\n\n return { json: { url } }\n } catch {\n // Unable to build redirect URL, ignore\n }\n }\n\n // @NOTE Not re-throwing the error here, as the error was already\n // handled by the `onError` callback, and apiRoute (`apiMiddleware`)\n // would call `onError` again.\n return buildErrorJsonResponse(err)\n }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/reject',\n schema: z.object({}).strict(),\n rotateDeviceCookies: true,\n async handler(req, res) {\n const { requestUri } = this\n if (!requestUri) {\n throw new InvalidRequestError(\n 'This endpoint can only be used in the context of an OAuth request',\n )\n }\n\n // Once this endpoint is called, the request will definitely be\n // rejected.\n try {\n // No need to authenticate the user here as they are not authorizing a\n // particular account (CSRF protection is enough).\n\n // @NOTE that the client could *technically* trigger this endpoint while\n // the user is on the authorize page by forging the request (because the\n // client knows the RequestURI from PAR and has all the info needed to\n // forge the request, including CSRF). This cannot be used as DoS attack\n // as the request ID is not guessable and would only result in a bad UX\n // for misbehaving clients, only for the users of those clients.\n\n const { parameters } = await server.requestManager.get(\n requestUri,\n this.deviceId,\n )\n\n const url = buildRedirectUrl(server.issuer, parameters, {\n error: 'access_denied',\n error_description: 'The user rejected the request',\n })\n\n return { json: { url } }\n } catch (err) {\n onError?.(req, res, err, 'Failed to reject authorization request')\n\n if (err instanceof AuthorizationError) {\n try {\n const url = buildRedirectUrl(\n server.issuer,\n err.parameters,\n err.toJSON(),\n )\n\n return { json: { url } }\n } catch {\n // Unable to build redirect URL, ignore\n }\n }\n\n return buildErrorJsonResponse(err)\n } finally {\n await server.requestManager.delete(requestUri).catch((err) => {\n onError?.(req, res, err, 'Failed to delete request')\n })\n }\n },\n }),\n )\n\n return router.buildMiddleware()\n\n async function authenticate(\n this: ApiContext<void, { did: Did }>,\n req: Req,\n _res: Res,\n ): Promise<{\n account: Account\n authorizedClients: AuthorizedClients\n }> {\n if (req.headers.authorization?.startsWith('Bearer ')) {\n try {\n // If there is an authorization header, verify that the ephemeral token it\n // contains is a jwt bound to the right [sub, device, request].\n const bearer = req.headers.authorization.slice(7)\n const ephemeralToken = signedJwtSchema.parse(bearer)\n const { payload } =\n await server.signer.verifyEphemeralToken(ephemeralToken)\n\n if (\n payload.sub === this.input.did &&\n payload.deviceId === this.deviceId &&\n payload.requestUri === this.requestUri\n ) {\n const accountData = await server.accountManager.getAccount(\n payload.sub,\n )\n if (accountData) return accountData\n throw new WWWAuthenticateError(\n 'unauthorized',\n `User ${payload.sub} does not exist`,\n { Bearer: {} },\n )\n }\n } catch (err) {\n throw err instanceof WWWAuthenticateError\n ? err\n : new WWWAuthenticateError(\n 'unauthorized',\n `Invalid or expired bearer token`,\n { Bearer: {} },\n err,\n )\n }\n }\n\n try {\n // Ensures the \"sub\" has an active session on the device\n const deviceAccount = await server.accountManager.getDeviceAccount(\n this.deviceId,\n this.input.did,\n )\n\n // The session exists but was created too long ago\n if (server.checkLoginRequired(deviceAccount)) {\n throw new InvalidRequestError('Login required')\n }\n\n return deviceAccount\n } catch (err) {\n throw new WWWAuthenticateError(\n 'unauthorized',\n `User ${this.input.did} not authenticated on this device`,\n { Bearer: {} },\n err,\n )\n }\n }\n\n type ApiContext<T extends object | void, I = void> = SubCtx<\n T,\n {\n deviceId: DeviceId\n deviceMetadata: RequestMetadata\n\n /**\n * The parsed input data (json payload if \"POST\", query params if \"GET\").\n */\n input: I\n\n /**\n * When defined, the request originated from the authorize page.\n */\n requestUri?: RequestUri\n }\n >\n\n type InferValidation<S extends void | z.ZodTypeAny> = S extends z.ZodTypeAny\n ? z.infer<S>\n : void\n\n /**\n * The main purpose of this function is to ensure that the endpoint\n * implementation matches its type definition from {@link ApiEndpoints}.\n * @private\n */\n function apiRoute<\n C extends RouterCtx<Ctx>,\n M extends 'GET' | 'POST',\n E extends `/${string}` &\n // Extract all the endpoint path that match the method (allows for\n // auto-complete & better error reporting)\n {\n [E in keyof ApiEndpoints]: ApiEndpoints[E] extends { method: M }\n ? E\n : never\n }[keyof ApiEndpoints],\n S extends // A schema that validates the POST input or GET params\n (ApiEndpoints[E] extends { method: 'POST'; input: infer I }\n ? z.ZodType<I, z.ZodTypeDef, unknown>\n : ApiEndpoints[E] extends { method: 'GET'; params: infer P }\n ? z.ZodType<P, z.ZodTypeDef, unknown>\n : void),\n >(options: {\n method: M\n endpoint: E\n schema: S\n rotateDeviceCookies?: boolean\n handler: (\n this: ApiContext<RouteCtx<C>, InferValidation<S>>,\n req: Req,\n res: Res,\n ) => Awaitable<JsonResponse<ErrorPayload | ApiEndpoints[E]['output']>>\n }): Middleware<C, Req, Res> {\n return createRoute(\n options.method,\n `${API_ENDPOINT_PREFIX}${options.endpoint}`,\n apiMiddleware(options),\n )\n }\n\n function apiMiddleware<C extends RouterCtx, S extends void | z.ZodTypeAny>({\n method,\n schema,\n rotateDeviceCookies,\n handler,\n }: {\n method: 'GET' | 'POST'\n schema: S\n rotateDeviceCookies?: boolean\n handler: (\n this: ApiContext<C, InferValidation<S>>,\n req: Req,\n res: Res,\n ) => Awaitable<JsonResponse>\n }): Middleware<C, Req, Res> {\n const parseInput: (this: C, req: Req) => Promise<InferValidation<S>> =\n schema == null // No schema means endpoint doesn't accept any input\n ? async function (req) {\n await flushStream(req)\n return undefined\n }\n : method === 'POST'\n ? async function (req) {\n const body = await parseHttpRequest(req, ['json'])\n return schema.parseAsync(body, { path: ['body'] })\n }\n : async function (req) {\n await flushStream(req)\n const query = Object.fromEntries(this.url.searchParams)\n return schema.parseAsync(query, { path: ['query'] })\n }\n\n return jsonHandler<C, Req, Res>(async function (req, res) {\n try {\n // Prevent caching of API routes\n res.setHeader('Cache-Control', 'no-store')\n res.setHeader('Pragma', 'no-cache')\n\n // Prevent CORS requests\n validateFetchMode(req, ['same-origin'])\n validateFetchSite(req, ['same-origin'])\n validateOrigin(req, issuerOrigin)\n const referrer = validateReferrer(req, { origin: issuerOrigin })\n\n // Ensure we are one the right page\n if (\n // trailing slashes are not allowed\n referrer.pathname !== '/oauth/authorize' &&\n referrer.pathname !== '/account' &&\n !referrer.pathname.startsWith(`/account/`)\n ) {\n throw createHttpError(400, `Invalid referrer ${referrer}`)\n }\n\n // Check if the request originated from the authorize page\n const requestUri =\n referrer.pathname === '/oauth/authorize'\n ? await requestUriSchema.parseAsync(\n referrer.searchParams.get('request_uri'),\n )\n : undefined\n\n // Validate CSRF token\n await validateCsrfToken(req, res)\n\n // Parse and validate the input data\n const input = await parseInput.call(this, req)\n\n // Load session data, rotating the session cookie if needed\n const { deviceId, deviceMetadata } = await server.deviceManager.load(\n req,\n res,\n rotateDeviceCookies,\n )\n\n const context: ApiContext<C, InferValidation<S>> = subCtx(this, {\n input,\n requestUri,\n deviceId,\n deviceMetadata,\n })\n\n return await handler.call(context, req, res)\n } catch (err) {\n onError?.(req, res, err, `Failed to handle API request`)\n\n // Make sore to always return a JSON response\n return buildErrorJsonResponse(err)\n }\n })\n }\n}\n\nfunction buildErrorJsonResponse(err: unknown) {\n // @TODO Rework the API error responses (relying on codes)\n const json = buildErrorPayload(err)\n const status = buildErrorStatus(err)\n\n return { json, status }\n}\n\nfunction buildRedirectUrl(\n iss: string,\n parameters: OAuthAuthorizationRequestParameters,\n redirect: AuthorizationRedirectParameters,\n): string {\n const url = new URL('/oauth/authorize/redirect', iss)\n\n url.searchParams.set('redirect_mode', buildRedirectMode(parameters))\n url.searchParams.set('redirect_uri', buildRedirectUri(parameters))\n\n for (const [key, value] of buildRedirectParams(iss, parameters, redirect)) {\n url.searchParams.set(key, value)\n }\n\n return url.href\n}\n\nexport function parseRedirectUrl(url: URL): OAuthRedirectOptions {\n if (url.pathname !== '/oauth/authorize/redirect') {\n throw new InvalidRequestError(\n `Invalid redirect URL: ${url.pathname} is not a valid path`,\n )\n }\n\n const params: [OAuthRedirectQueryParameter, string][] = []\n\n const state = url.searchParams.get('state')\n if (state) params.push(['state', state])\n\n const iss = url.searchParams.get('iss')\n if (iss) params.push(['iss', iss])\n\n if (url.searchParams.has('code')) {\n for (const key of SUCCESS_REDIRECT_KEYS) {\n const value = url.searchParams.get(key)\n if (value != null) params.push([key, value])\n }\n } else if (url.searchParams.has('error')) {\n for (const key of ERROR_REDIRECT_KEYS) {\n const value = url.searchParams.get(key)\n if (value != null) params.push([key, value])\n }\n } else {\n throw new InvalidRequestError(\n 'Invalid redirect URL: neither code nor error found',\n )\n }\n\n try {\n const mode: OAuthResponseMode = oauthResponseModeSchema.parse(\n url.searchParams.get('redirect_mode'),\n )\n\n const redirectUri: OAuthRedirectUri = oauthRedirectUriSchema.parse(\n url.searchParams.get('redirect_uri'),\n )\n\n return { mode, redirectUri, params }\n } catch (err) {\n throw InvalidRequestError.from(err, 'Invalid redirect URL')\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atproto/oauth-provider",
3
- "version": "0.25.1",
3
+ "version": "0.25.2",
4
4
  "license": "MIT",
5
5
  "description": "Generic OAuth2 and OpenID Connect provider for Node.js. Currently only supports features needed for Atproto.",
6
6
  "keywords": [
@@ -78,12 +78,12 @@
78
78
  "@atproto-labs/pipe": "^0.2.4",
79
79
  "@atproto-labs/simple-store": "^0.5.1",
80
80
  "@atproto-labs/simple-store-memory": "^0.2.6",
81
- "@atproto/common": "^0.8.6",
82
- "@atproto/did": "^0.5.6",
81
+ "@atproto/common": "^0.8.7",
83
82
  "@atproto/jwk": "^0.7.4",
83
+ "@atproto/did": "^0.5.6",
84
84
  "@atproto/jwk-jose": "^0.2.4",
85
85
  "@atproto/lex-document": "^0.1.14",
86
- "@atproto/lex-resolver": "^0.4.0",
86
+ "@atproto/lex-resolver": "^0.4.1",
87
87
  "@atproto/oauth-types": "^0.7.7",
88
88
  "@atproto/oauth-provider-api": "0.11.0",
89
89
  "@atproto/oauth-provider-ui": "0.11.0",