@atproto/oauth-provider 0.20.2 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/dist/account/login-hint.d.ts +10 -0
  3. package/dist/account/login-hint.d.ts.map +1 -0
  4. package/dist/account/login-hint.js +19 -0
  5. package/dist/account/login-hint.js.map +1 -0
  6. package/dist/client/client-manager.d.ts.map +1 -1
  7. package/dist/client/client-manager.js +4 -6
  8. package/dist/client/client-manager.js.map +1 -1
  9. package/dist/client/client.d.ts +16 -0
  10. package/dist/client/client.d.ts.map +1 -1
  11. package/dist/client/client.js +31 -1
  12. package/dist/client/client.js.map +1 -1
  13. package/dist/oauth-constants.d.ts +14 -8
  14. package/dist/oauth-constants.d.ts.map +1 -1
  15. package/dist/oauth-constants.js +14 -8
  16. package/dist/oauth-constants.js.map +1 -1
  17. package/dist/oauth-provider.d.ts +1 -1
  18. package/dist/oauth-provider.d.ts.map +1 -1
  19. package/dist/oauth-provider.js +14 -14
  20. package/dist/oauth-provider.js.map +1 -1
  21. package/dist/request/request-manager.d.ts.map +1 -1
  22. package/dist/request/request-manager.js +4 -4
  23. package/dist/request/request-manager.js.map +1 -1
  24. package/dist/result/authorization-result-authorize-page.d.ts +6 -0
  25. package/dist/result/authorization-result-authorize-page.d.ts.map +1 -1
  26. package/dist/result/authorization-result-authorize-page.js.map +1 -1
  27. package/dist/router/assets/send-authorization-page.js +3 -3
  28. package/dist/router/assets/send-authorization-page.js.map +1 -1
  29. package/dist/router/create-api-middleware.d.ts.map +1 -1
  30. package/dist/router/create-api-middleware.js +27 -5
  31. package/dist/router/create-api-middleware.js.map +1 -1
  32. package/dist/signer/access-token-payload.d.ts +39 -39
  33. package/dist/token/token-manager.d.ts +2 -2
  34. package/dist/token/token-manager.d.ts.map +1 -1
  35. package/dist/token/token-manager.js +22 -8
  36. package/dist/token/token-manager.js.map +1 -1
  37. package/package.json +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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\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 authenticated,\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 if (\n !client.info.isTrusted &&\n !client.info.isFirstParty &&\n client.metadata.token_endpoint_auth_method === 'none'\n ) {\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 if (scopeOverride != null) {\n const allowedScopes = new Set(scopeOverride.split(' '))\n const existingScopes = parameters.scope?.split(' ')\n\n // Compute the intersection of the existing scopes and the overrides.\n const newScopes = existingScopes?.filter((s) => allowedScopes.has(s))\n\n // Validate: make sure the new scopes are valid\n if (!newScopes?.includes('atproto')) {\n throw new AccessDeniedError(\n parameters,\n 'The \"atproto\" scope is required',\n )\n }\n\n parameters = { ...parameters, scope: newScopes.join(' ') }\n }\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,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,uBA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,CAAC;QAED,IAAI,CAAC,uBAAuB,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,IAAI,KAAK,IAAI,EAAE,CAAC;YACzD,kEAAkE;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","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<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 if (scopeOverride != null) {\n const allowedScopes = new Set(scopeOverride.split(' '))\n const existingScopes = parameters.scope?.split(' ')\n\n // Compute the intersection of the existing scopes and the overrides.\n const newScopes = existingScopes?.filter((s) => allowedScopes.has(s))\n\n // Validate: make sure the new scopes are valid\n if (!newScopes?.includes('atproto')) {\n throw new AccessDeniedError(\n parameters,\n 'The \"atproto\" scope is required',\n )\n }\n\n parameters = { ...parameters, scope: newScopes.join(' ') }\n }\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"]}
@@ -11,5 +11,11 @@ export type AuthorizationResultAuthorizePage = {
11
11
  requestUri: RequestUri;
12
12
  sessions: readonly Session[];
13
13
  selectedDid?: Account['did'];
14
+ /**
15
+ * User-facing value of the `login_hint` parameter. Same as
16
+ * `parameters.login_hint`, except that a DID hint is resolved to the
17
+ * account's handle when the account is known to this server.
18
+ */
19
+ loginHint?: string;
14
20
  };
15
21
  //# sourceMappingURL=authorization-result-authorize-page.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"authorization-result-authorize-page.d.ts","sourceRoot":"","sources":["../../src/result/authorization-result-authorize-page.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAA;AACjE,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAA;AACnE,OAAO,KAAK,EAAE,mCAAmC,EAAE,MAAM,sBAAsB,CAAA;AAC/E,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAA;AACjD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAA;AAE3D,MAAM,MAAM,gCAAgC,GAAG;IAC7C,MAAM,EAAE,MAAM,CAAA;IACd,MAAM,EAAE,MAAM,CAAA;IACd,UAAU,EAAE,mCAAmC,CAAA;IAC/C,cAAc,EAAE,GAAG,CAAC,MAAM,EAAE,oBAAoB,CAAC,CAAA;IAEjD,UAAU,EAAE,UAAU,CAAA;IACtB,QAAQ,EAAE,SAAS,OAAO,EAAE,CAAA;IAC5B,WAAW,CAAC,EAAE,OAAO,CAAC,KAAK,CAAC,CAAA;CAC7B,CAAA"}
1
+ {"version":3,"file":"authorization-result-authorize-page.d.ts","sourceRoot":"","sources":["../../src/result/authorization-result-authorize-page.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAA;AACjE,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAA;AACnE,OAAO,KAAK,EAAE,mCAAmC,EAAE,MAAM,sBAAsB,CAAA;AAC/E,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAA;AACjD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAA;AAE3D,MAAM,MAAM,gCAAgC,GAAG;IAC7C,MAAM,EAAE,MAAM,CAAA;IACd,MAAM,EAAE,MAAM,CAAA;IACd,UAAU,EAAE,mCAAmC,CAAA;IAC/C,cAAc,EAAE,GAAG,CAAC,MAAM,EAAE,oBAAoB,CAAC,CAAA;IAEjD,UAAU,EAAE,UAAU,CAAA;IACtB,QAAQ,EAAE,SAAS,OAAO,EAAE,CAAA;IAC5B,WAAW,CAAC,EAAE,OAAO,CAAC,KAAK,CAAC,CAAA;IAE5B;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,CAAA;CACnB,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"authorization-result-authorize-page.js","sourceRoot":"","sources":["../../src/result/authorization-result-authorize-page.ts"],"names":[],"mappings":"","sourcesContent":["import type { LexiconPermissionSet } from '@atproto/lex-document'\nimport type { Account, Session } from '@atproto/oauth-provider-api'\nimport type { OAuthAuthorizationRequestParameters } from '@atproto/oauth-types'\nimport type { Client } from '../client/client.js'\nimport type { RequestUri } from '../request/request-uri.js'\n\nexport type AuthorizationResultAuthorizePage = {\n issuer: string\n client: Client\n parameters: OAuthAuthorizationRequestParameters\n permissionSets: Map<string, LexiconPermissionSet>\n\n requestUri: RequestUri\n sessions: readonly Session[]\n selectedDid?: Account['did']\n}\n"]}
1
+ {"version":3,"file":"authorization-result-authorize-page.js","sourceRoot":"","sources":["../../src/result/authorization-result-authorize-page.ts"],"names":[],"mappings":"","sourcesContent":["import type { LexiconPermissionSet } from '@atproto/lex-document'\nimport type { Account, Session } from '@atproto/oauth-provider-api'\nimport type { OAuthAuthorizationRequestParameters } from '@atproto/oauth-types'\nimport type { Client } from '../client/client.js'\nimport type { RequestUri } from '../request/request-uri.js'\n\nexport type AuthorizationResultAuthorizePage = {\n issuer: string\n client: Client\n parameters: OAuthAuthorizationRequestParameters\n permissionSets: Map<string, LexiconPermissionSet>\n\n requestUri: RequestUri\n sessions: readonly Session[]\n selectedDid?: Account['did']\n\n /**\n * User-facing value of the `login_hint` parameter. Same as\n * `parameters.login_hint`, except that a DID hint is resolved to the\n * account's handle when the account is known to this server.\n */\n loginHint?: string\n}\n"]}
@@ -8,11 +8,11 @@ export function sendAuthorizePageFactory(customization, options) {
8
8
  requestUri: data.requestUri,
9
9
  clientId: data.client.id,
10
10
  clientMetadata: data.client.metadata,
11
- clientTrusted: data.client.info.isTrusted,
12
- clientFirstParty: data.client.info.isFirstParty,
11
+ clientTrusted: data.client.isTrusted,
12
+ clientFirstParty: data.client.isFirstParty,
13
13
  scope: data.parameters.scope,
14
14
  uiLocales: data.parameters.ui_locales,
15
- loginHint: data.parameters.login_hint,
15
+ loginHint: data.loginHint,
16
16
  promptMode: data.parameters.prompt,
17
17
  permissionSets: Object.fromEntries(data.permissionSets),
18
18
  selectedDid: data.selectedDid,
@@ -1 +1 @@
1
- {"version":3,"file":"send-authorization-page.js","sourceRoot":"","sources":["../../../src/router/assets/send-authorization-page.ts"],"names":[],"mappings":"AAGA,OAAO,EAA0B,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAEvE,MAAM,UAAU,wBAAwB,CACtC,aAA4B,EAC5B,OAA2B;IAE3B,MAAM,OAAO,GAAG,iBAAiB,CAC/B,oBAAoB,EACpB,aAAa,EACb,OAAO,CACR,CAAA;IAED,OAAO,KAAK,UAAU,iBAAiB,CACrC,GAAoB,EACpB,GAAmB,EACnB,IAAsC;QAEtC,OAAO,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE;YACvB,IAAI,EAAE;gBACJ,eAAe,EAAE;oBACf,UAAU,EAAE,IAAI,CAAC,UAAU;oBAE3B,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE;oBACxB,cAAc,EAAE,IAAI,CAAC,MAAM,CAAC,QAAQ;oBACpC,aAAa,EAAE,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS;oBACzC,gBAAgB,EAAE,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,YAAY;oBAE/C,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK;oBAC5B,SAAS,EAAE,IAAI,CAAC,UAAU,CAAC,UAAU;oBACrC,SAAS,EAAE,IAAI,CAAC,UAAU,CAAC,UAAU;oBACrC,UAAU,EAAE,IAAI,CAAC,UAAU,CAAC,MAAM;oBAClC,cAAc,EAAE,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,cAAc,CAAC;oBACvD,WAAW,EAAE,IAAI,CAAC,WAAW;iBAC9B;gBACD,UAAU,EAAE,IAAI,CAAC,QAAQ;aAC1B;SACF,CAAC,CAAA;IACJ,CAAC,CAAA;AACH,CAAC","sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { Customization } from '../../customization/customization.js'\nimport type { AuthorizationResultAuthorizePage } from '../../result/authorization-result-authorize-page.js'\nimport { type SendWebAppOptions, sendWebAppFactory } from './assets.js'\n\nexport function sendAuthorizePageFactory(\n customization: Customization,\n options?: SendWebAppOptions,\n) {\n const sendApp = sendWebAppFactory(\n 'authorization-page',\n customization,\n options,\n )\n\n return async function sendAuthorizePage(\n req: IncomingMessage,\n res: ServerResponse,\n data: AuthorizationResultAuthorizePage,\n ): Promise<void> {\n return sendApp(req, res, {\n data: {\n __authorizeData: {\n requestUri: data.requestUri,\n\n clientId: data.client.id,\n clientMetadata: data.client.metadata,\n clientTrusted: data.client.info.isTrusted,\n clientFirstParty: data.client.info.isFirstParty,\n\n scope: data.parameters.scope,\n uiLocales: data.parameters.ui_locales,\n loginHint: data.parameters.login_hint,\n promptMode: data.parameters.prompt,\n permissionSets: Object.fromEntries(data.permissionSets),\n selectedDid: data.selectedDid,\n },\n __sessions: data.sessions,\n },\n })\n }\n}\n"]}
1
+ {"version":3,"file":"send-authorization-page.js","sourceRoot":"","sources":["../../../src/router/assets/send-authorization-page.ts"],"names":[],"mappings":"AAGA,OAAO,EAA0B,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAEvE,MAAM,UAAU,wBAAwB,CACtC,aAA4B,EAC5B,OAA2B;IAE3B,MAAM,OAAO,GAAG,iBAAiB,CAC/B,oBAAoB,EACpB,aAAa,EACb,OAAO,CACR,CAAA;IAED,OAAO,KAAK,UAAU,iBAAiB,CACrC,GAAoB,EACpB,GAAmB,EACnB,IAAsC;QAEtC,OAAO,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE;YACvB,IAAI,EAAE;gBACJ,eAAe,EAAE;oBACf,UAAU,EAAE,IAAI,CAAC,UAAU;oBAE3B,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE;oBACxB,cAAc,EAAE,IAAI,CAAC,MAAM,CAAC,QAAQ;oBACpC,aAAa,EAAE,IAAI,CAAC,MAAM,CAAC,SAAS;oBACpC,gBAAgB,EAAE,IAAI,CAAC,MAAM,CAAC,YAAY;oBAE1C,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK;oBAC5B,SAAS,EAAE,IAAI,CAAC,UAAU,CAAC,UAAU;oBACrC,SAAS,EAAE,IAAI,CAAC,SAAS;oBACzB,UAAU,EAAE,IAAI,CAAC,UAAU,CAAC,MAAM;oBAClC,cAAc,EAAE,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,cAAc,CAAC;oBACvD,WAAW,EAAE,IAAI,CAAC,WAAW;iBAC9B;gBACD,UAAU,EAAE,IAAI,CAAC,QAAQ;aAC1B;SACF,CAAC,CAAA;IACJ,CAAC,CAAA;AACH,CAAC","sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { Customization } from '../../customization/customization.js'\nimport type { AuthorizationResultAuthorizePage } from '../../result/authorization-result-authorize-page.js'\nimport { type SendWebAppOptions, sendWebAppFactory } from './assets.js'\n\nexport function sendAuthorizePageFactory(\n customization: Customization,\n options?: SendWebAppOptions,\n) {\n const sendApp = sendWebAppFactory(\n 'authorization-page',\n customization,\n options,\n )\n\n return async function sendAuthorizePage(\n req: IncomingMessage,\n res: ServerResponse,\n data: AuthorizationResultAuthorizePage,\n ): Promise<void> {\n return sendApp(req, res, {\n data: {\n __authorizeData: {\n requestUri: data.requestUri,\n\n clientId: data.client.id,\n clientMetadata: data.client.metadata,\n clientTrusted: data.client.isTrusted,\n clientFirstParty: data.client.isFirstParty,\n\n scope: data.parameters.scope,\n uiLocales: data.parameters.ui_locales,\n loginHint: data.loginHint,\n promptMode: data.parameters.prompt,\n permissionSets: Object.fromEntries(data.permissionSets),\n selectedDid: data.selectedDid,\n },\n __sessions: data.sessions,\n },\n })\n }\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;AAK7B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAA;AASzD,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,CAo4B3B;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;AAK7B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAA;AASzD,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,CA65B3B;AA2BD,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,GAAG,GAAG,oBAAoB,CA4C/D"}
@@ -298,17 +298,39 @@ export function createApiMiddleware(server, { onError }) {
298
298
  return undefined; // metadata won't be available in the UI
299
299
  },
300
300
  });
301
- // @TODO: We should ideally filter sessions that are expired (or even
302
- // expose the expiration date). This requires a change to the way
303
- // TokenInfo are stored (see TokenManager#isTokenExpired and
304
- // TokenManager#isTokenInactive).
305
- const json = tokenInfos.map(({ id, data }) => {
301
+ const json = tokenInfos
302
+ .filter(({ data }) => {
303
+ // Remove sessions that are expired, based on the maximum possible
304
+ // lifetime of a session. The client metadata is needed to determine
305
+ // the actual session and refresh lifetimes.
306
+ const client = clients.get(data.clientId);
307
+ // We were not able to load the client (see onError callback above).
308
+ // In this case, we will keep the session in the list, and let the
309
+ // UI show them as "broken" sessions (based on the absence of the
310
+ // clientMetadata in ActiveOAuthSession).
311
+ if (!client)
312
+ return true;
313
+ const sessionAge = Date.now() - data.createdAt.getTime();
314
+ if (sessionAge > client.sessionLifetime)
315
+ return false;
316
+ const refreshAge = Date.now() - data.updatedAt.getTime();
317
+ if (refreshAge > client.refreshLifetime)
318
+ return false;
319
+ // If the client cannot refresh, then the session is only valid if
320
+ // it has not yet expired.
321
+ if (!client.metadata.grant_types.includes('refresh_token')) {
322
+ return data.expiresAt.getTime() > Date.now();
323
+ }
324
+ return true;
325
+ })
326
+ .map(({ id, data }) => {
306
327
  return {
307
328
  tokenId: id,
308
329
  createdAt: data.createdAt.toISOString(),
309
330
  updatedAt: data.updatedAt.toISOString(),
310
331
  clientId: data.clientId,
311
332
  clientMetadata: clients.get(data.clientId)?.metadata,
333
+ active: data.expiresAt.getTime() > Date.now(),
312
334
  scope: data.parameters.scope,
313
335
  };
314
336
  });
@@ -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;AAQ9C,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAA;AACjE,OAAO,EAIL,sBAAsB,EACtB,uBAAuB,EACvB,gBAAgB,GACjB,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAA;AAC7D,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAA;AAC/D,OAAO,EAAiB,cAAc,EAAE,MAAM,wBAAwB,CAAA;AACtE,OAAO,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAA;AACrE,OAAO,EAEL,iBAAiB,EACjB,gBAAgB,GACjB,MAAM,2BAA2B,CAAA;AAClC,OAAO,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAA;AACxE,OAAO,EAAE,oBAAoB,EAAE,MAAM,qCAAqC,CAAA;AAC1E,OAAO,EAIL,MAAM,EAGN,WAAW,EACX,WAAW,EACX,gBAAgB,EAChB,MAAM,EACN,iBAAiB,EACjB,iBAAiB,EACjB,cAAc,EACd,gBAAgB,GACjB,MAAM,sBA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AC,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 ActiveDeviceSession,\n ActiveOAuthSession,\n ApiEndpoints,\n ISODateString,\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 { 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 { asArray } from '../lib/util/cast.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 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 } from '../types/email.js'\nimport { handleSchema } from '../types/handle.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 account = await server.accountManager.createAccount(\n deviceId,\n deviceMetadata,\n input,\n )\n\n // Remember when not in the context of a request by default\n const remember = requestUri == null\n\n // Only \"remember\" the newly created account if it was not created during an\n // OAuth flow.\n if (remember) {\n await server.accountManager.upsertDeviceAccount(deviceId, account.did)\n }\n\n const ephemeralToken = remember\n ? undefined\n : await server.signer.createEphemeralToken({\n sub: account.did,\n deviceId,\n requestUri: this.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.extend({ remember: z.boolean().optional() }),\n rotateDeviceCookies: true,\n async handler() {\n const { deviceId, deviceMetadata, requestUri } = this\n\n // Remember when not in the context of a request by default\n const { remember = requestUri == null, ...input } = this.input\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 = await server.accountManager.authenticateAccount(\n deviceId,\n deviceMetadata,\n input,\n clientId,\n )\n\n if (remember) {\n await server.accountManager.upsertDeviceAccount(deviceId, account.did)\n } else {\n // In case the user was already signed in, and signed in again, this\n // time without \"remember me\", let's sign them off of the device.\n await server.accountManager.removeDeviceAccount(deviceId, account.did)\n }\n\n const ephemeralToken = remember\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-out',\n schema: z\n .object({\n did: z.union([didSchema, z.array(didSchema)]),\n })\n .strict(),\n rotateDeviceCookies: true,\n async handler() {\n const uniqueSubs = new Set(asArray(this.input.did))\n\n for (const sub of uniqueSubs) {\n await server.accountManager.removeDeviceAccount(this.deviceId, sub)\n }\n\n return { json: { success: true as const } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/reset-password-request',\n schema: z\n .object({\n locale: localeSchema,\n email: emailSchema,\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: emailSchema,\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: '/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(\n (deviceAccount): ActiveDeviceSession => ({\n account: deviceAccount.account,\n loginRequired: server.checkLoginRequired(deviceAccount),\n }),\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 // @TODO: We should ideally filter sessions that are expired (or even\n // expose the expiration date). This requires a change to the way\n // TokenInfo are stored (see TokenManager#isTokenExpired and\n // TokenManager#isTokenInactive).\n const json = tokenInfos.map(({ id, data }): ActiveOAuthSession => {\n return {\n tokenId: id,\n\n createdAt: data.createdAt.toISOString() as ISODateString,\n updatedAt: data.updatedAt.toISOString() as ISODateString,\n\n clientId: data.clientId,\n clientMetadata: clients.get(data.clientId)?.metadata,\n\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 ISODateString,\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.removeDeviceAccount(\n this.input.deviceId,\n this.input.did,\n )\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 // Add the newly accepted scopes to the authorized scopes\n\n // @NOTE `oauthScopeSchema` ensures that `scope` contains no\n // leading/trailing/duplicate spaces.\n for (const s of parameters.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 ) {\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 return await server.accountManager.getAccount(payload.sub)\n }\n } catch (err) {\n throw 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;AAQ9C,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAA;AACjE,OAAO,EAIL,sBA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,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC;QACzC,KAAK,MAAM,GAAG,IAAI,mBAAmB,EAAE,CAAC;YACtC,MAAM,KAAK,GAAG,GAAG,CAAC,YAAY,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 ActiveDeviceSession,\n ActiveOAuthSession,\n ApiEndpoints,\n ISODateString,\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 { 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 { asArray } from '../lib/util/cast.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 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 } from '../types/email.js'\nimport { handleSchema } from '../types/handle.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 account = await server.accountManager.createAccount(\n deviceId,\n deviceMetadata,\n input,\n )\n\n // Remember when not in the context of a request by default\n const remember = requestUri == null\n\n // Only \"remember\" the newly created account if it was not created during an\n // OAuth flow.\n if (remember) {\n await server.accountManager.upsertDeviceAccount(deviceId, account.did)\n }\n\n const ephemeralToken = remember\n ? undefined\n : await server.signer.createEphemeralToken({\n sub: account.did,\n deviceId,\n requestUri: this.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.extend({ remember: z.boolean().optional() }),\n rotateDeviceCookies: true,\n async handler() {\n const { deviceId, deviceMetadata, requestUri } = this\n\n // Remember when not in the context of a request by default\n const { remember = requestUri == null, ...input } = this.input\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 = await server.accountManager.authenticateAccount(\n deviceId,\n deviceMetadata,\n input,\n clientId,\n )\n\n if (remember) {\n await server.accountManager.upsertDeviceAccount(deviceId, account.did)\n } else {\n // In case the user was already signed in, and signed in again, this\n // time without \"remember me\", let's sign them off of the device.\n await server.accountManager.removeDeviceAccount(deviceId, account.did)\n }\n\n const ephemeralToken = remember\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-out',\n schema: z\n .object({\n did: z.union([didSchema, z.array(didSchema)]),\n })\n .strict(),\n rotateDeviceCookies: true,\n async handler() {\n const uniqueSubs = new Set(asArray(this.input.did))\n\n for (const sub of uniqueSubs) {\n await server.accountManager.removeDeviceAccount(this.deviceId, sub)\n }\n\n return { json: { success: true as const } }\n },\n }),\n )\n\n router.use(\n apiRoute({\n method: 'POST',\n endpoint: '/reset-password-request',\n schema: z\n .object({\n locale: localeSchema,\n email: emailSchema,\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: emailSchema,\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: '/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(\n (deviceAccount): ActiveDeviceSession => ({\n account: deviceAccount.account,\n loginRequired: server.checkLoginRequired(deviceAccount),\n }),\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 ISODateString,\n updatedAt: data.updatedAt.toISOString() as ISODateString,\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 ISODateString,\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.removeDeviceAccount(\n this.input.deviceId,\n this.input.did,\n )\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 // Add the newly accepted scopes to the authorized scopes\n\n // @NOTE `oauthScopeSchema` ensures that `scope` contains no\n // leading/trailing/duplicate spaces.\n for (const s of parameters.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 ) {\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 return await server.accountManager.getAccount(payload.sub)\n }\n } catch (err) {\n throw 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"]}