@atproto/oauth-provider 0.18.1 → 0.18.3

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 (39) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/account/account-manager.d.ts +2 -1
  3. package/dist/account/account-manager.d.ts.map +1 -1
  4. package/dist/account/account-manager.js +16 -0
  5. package/dist/account/account-manager.js.map +1 -1
  6. package/dist/account/account-store.d.ts +8 -1
  7. package/dist/account/account-store.d.ts.map +1 -1
  8. package/dist/account/account-store.js +1 -0
  9. package/dist/account/account-store.js.map +1 -1
  10. package/dist/customization/build-customization-data.d.ts +1 -1
  11. package/dist/customization/build-customization-data.d.ts.map +1 -1
  12. package/dist/customization/build-customization-data.js +2 -1
  13. package/dist/customization/build-customization-data.js.map +1 -1
  14. package/dist/customization/customization.d.ts +6 -0
  15. package/dist/customization/customization.d.ts.map +1 -1
  16. package/dist/customization/customization.js +4 -0
  17. package/dist/customization/customization.js.map +1 -1
  18. package/dist/errors/handle-unavailable-error.d.ts +5 -3
  19. package/dist/errors/handle-unavailable-error.d.ts.map +1 -1
  20. package/dist/errors/handle-unavailable-error.js.map +1 -1
  21. package/dist/oauth-hooks.d.ts +23 -2
  22. package/dist/oauth-hooks.d.ts.map +1 -1
  23. package/dist/oauth-hooks.js.map +1 -1
  24. package/dist/oauth-middleware.js +3 -2
  25. package/dist/oauth-middleware.js.map +1 -1
  26. package/dist/router/create-api-middleware.d.ts.map +1 -1
  27. package/dist/router/create-api-middleware.js +16 -1
  28. package/dist/router/create-api-middleware.js.map +1 -1
  29. package/package.json +5 -5
  30. package/src/account/account-manager.ts +26 -0
  31. package/src/account/account-store.ts +10 -0
  32. package/src/customization/build-customization-data.ts +2 -0
  33. package/src/customization/customization.ts +4 -0
  34. package/src/errors/handle-unavailable-error.ts +6 -1
  35. package/src/oauth-hooks.ts +25 -0
  36. package/src/oauth-middleware.ts +9 -9
  37. package/src/router/create-api-middleware.ts +26 -1
  38. package/tsconfig.build.json +2 -2
  39. package/tsconfig.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"oauth-middleware.js","sourceRoot":"","sources":["../src/oauth-middleware.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAA;AAGxE,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAA;AAC5D,OAAO,EAAE,2BAA2B,EAAE,MAAM,4CAA4C,CAAA;AACxF,OAAO,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAA;AACvE,OAAO,EAAE,iCAAiC,EAAE,MAAM,kDAAkD,CAAA;AACpG,OAAO,EAAE,qBAAqB,EAAE,MAAM,qCAAqC,CAAA;AAa3E;;;GAGG;AACH,MAAM,UAAU,eAAe,CAI7B,MAAqB,EACrB,EAAE,GAAG,OAAO,KAAkC,EAAE;IAEhD,MAAM,EAAE,OAAO,EAAE,GAAG,OAAO,CAAA;IAE3B,sDAAsD;IACtD,OAAO,CAAC,OAAO;QACb,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,KAAK,aAAa;YACvC,CAAC,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE;gBACrB,OAAO,CAAC,KAAK,CAAC,wBAAwB,GAAG,IAAI,EAAE,GAAG,CAAC,CAAA;gBACnD,OAAO,OAAO,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA;YACtC,CAAC;YACH,CAAC,CAAC,OAAO,CAAA;IAEb,OAAO,SAAS,CACd,kBAAkB,CAAC;QACjB,gBAAgB;QAChB,qBAAqB,CAAC,MAAM,EAAE,OAAO,CAAC;QACtC,mBAAmB,CAAC,MAAM,EAAE,OAAO,CAAC;QACpC,iCAAiC,CAAC,MAAM,EAAE,OAAO,CAAC;QAClD,2BAA2B,CAAC,MAAM,EAAE,OAAO,CAAC;KAC7C,CAAC,CACH,CAAA;AACH,CAAC","sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http'\nimport { asHandler, combineMiddlewares } from './lib/http/middleware.js'\nimport { Handler } from './lib/http/types.js'\nimport { OAuthProvider } from './oauth-provider.js'\nimport { assetsMiddleware } from './router/assets/assets.js'\nimport { createAccountPageMiddleware } from './router/create-account-page-middleware.js'\nimport { createApiMiddleware } from './router/create-api-middleware.js'\nimport { createAuthorizationPageMiddleware } from './router/create-authorization-page-middleware.js'\nimport { createOAuthMiddleware } from './router/create-oauth-middleware.js'\nimport { ErrorHandler } from './router/error-handler.js'\nimport { MiddlewareOptions } from './router/middleware-options.js'\n\n// Export all the types exposed\nexport type {\n ErrorHandler,\n Handler,\n IncomingMessage,\n MiddlewareOptions,\n ServerResponse,\n}\n\n/**\n * @returns An http request handler that can be used with node's http server\n * or as a middleware with express / connect.\n */\nexport function oauthMiddleware<\n Req extends IncomingMessage = IncomingMessage,\n Res extends ServerResponse = ServerResponse,\n>(\n server: OAuthProvider,\n { ...options }: MiddlewareOptions<Req, Res> = {},\n): Handler<void, Req, Res> {\n const { onError } = options\n\n // options is shallow cloned so it's fine to mutate it\n options.onError =\n process.env['NODE_ENV'] === 'development'\n ? (req, res, err, msg) => {\n console.error(`OAuthProvider error (${msg}):`, err)\n return onError?.(req, res, err, msg)\n }\n : onError\n\n return asHandler(\n combineMiddlewares([\n assetsMiddleware,\n createOAuthMiddleware(server, options),\n createApiMiddleware(server, options),\n createAuthorizationPageMiddleware(server, options),\n createAccountPageMiddleware(server, options),\n ]),\n )\n}\n"]}
1
+ {"version":3,"file":"oauth-middleware.js","sourceRoot":"","sources":["../src/oauth-middleware.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAA;AAGxE,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAA;AAC5D,OAAO,EAAE,2BAA2B,EAAE,MAAM,4CAA4C,CAAA;AACxF,OAAO,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAA;AACvE,OAAO,EAAE,iCAAiC,EAAE,MAAM,kDAAkD,CAAA;AACpG,OAAO,EAAE,qBAAqB,EAAE,MAAM,qCAAqC,CAAA;AAa3E;;;GAGG;AACH,MAAM,UAAU,eAAe,CAI7B,MAAqB,EACrB,EAAE,GAAG,OAAO,KAAkC,EAAE;IAEhD,MAAM,EAAE,OAAO,EAAE,GAAG,OAAO,CAAA;IAE3B,sDAAsD;IACtD,OAAO,CAAC,OAAO;QACb,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,KAAK,aAAa;YACvC,CAAC,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE;gBACrB,OAAO,CAAC,KAAK,CAAC,wBAAwB,GAAG,IAAI,EAAE,GAAG,CAAC,CAAA;gBACnD,OAAO,OAAO,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA;YACtC,CAAC;YACH,CAAC,CAAC,OAAO,CAAA;IAEb,MAAM,UAAU,GAAG,kBAAkB,CAAC;QACpC,gBAAgB;QAChB,qBAAqB,CAAC,MAAM,EAAE,OAAO,CAAC;QACtC,mBAAmB,CAAC,MAAM,EAAE,OAAO,CAAC;QACpC,iCAAiC,CAAC,MAAM,EAAE,OAAO,CAAC;QAClD,2BAA2B,CAAC,MAAM,EAAE,OAAO,CAAC;KAC7C,CAAC,CAAA;IAEF,OAAO,SAAS,CAAC,UAAU,CAAC,CAAA;AAC9B,CAAC","sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http'\nimport { asHandler, combineMiddlewares } from './lib/http/middleware.js'\nimport { Handler } from './lib/http/types.js'\nimport { OAuthProvider } from './oauth-provider.js'\nimport { assetsMiddleware } from './router/assets/assets.js'\nimport { createAccountPageMiddleware } from './router/create-account-page-middleware.js'\nimport { createApiMiddleware } from './router/create-api-middleware.js'\nimport { createAuthorizationPageMiddleware } from './router/create-authorization-page-middleware.js'\nimport { createOAuthMiddleware } from './router/create-oauth-middleware.js'\nimport { ErrorHandler } from './router/error-handler.js'\nimport { MiddlewareOptions } from './router/middleware-options.js'\n\n// Export all the types exposed\nexport type {\n ErrorHandler,\n Handler,\n IncomingMessage,\n MiddlewareOptions,\n ServerResponse,\n}\n\n/**\n * @returns An http request handler that can be used with node's http server\n * or as a middleware with express / connect.\n */\nexport function oauthMiddleware<\n Req extends IncomingMessage = IncomingMessage,\n Res extends ServerResponse = ServerResponse,\n>(\n server: OAuthProvider,\n { ...options }: MiddlewareOptions<Req, Res> = {},\n): Handler<void, Req, Res> {\n const { onError } = options\n\n // options is shallow cloned so it's fine to mutate it\n options.onError =\n process.env['NODE_ENV'] === 'development'\n ? (req, res, err, msg) => {\n console.error(`OAuthProvider error (${msg}):`, err)\n return onError?.(req, res, err, msg)\n }\n : onError\n\n const middleware = combineMiddlewares([\n assetsMiddleware,\n createOAuthMiddleware(server, options),\n createApiMiddleware(server, options),\n createAuthorizationPageMiddleware(server, options),\n createAccountPageMiddleware(server, options),\n ])\n\n return asHandler(middleware)\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;AA8BhE,OAAO,EAEL,UAAU,EAaX,MAAM,sBAAsB,CAAA;AAK7B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAA;AAUzD,OAAO,EAEL,oBAAoB,EAMrB,MAAM,2BAA2B,CAAA;AAClC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAA;AAIhE,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,CA6yB3B;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;AA8BhE,OAAO,EAEL,UAAU,EAaX,MAAM,sBAAsB,CAAA;AAK7B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAA;AAUzD,OAAO,EAEL,oBAAoB,EAMrB,MAAM,2BAA2B,CAAA;AAClC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAA;AAIhE,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,CAs0B3B;AA2BD,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,GAAG,GAAG,oBAAoB,CA4C/D"}
@@ -175,8 +175,8 @@ export function createApiMiddleware(server, { onError }) {
175
175
  schema: z
176
176
  .object({
177
177
  sub: subSchema,
178
- token: emailOtpSchema,
179
178
  email: emailSchema,
179
+ token: emailOtpSchema.optional(),
180
180
  locale: localeSchema.optional(),
181
181
  })
182
182
  .strict(),
@@ -217,6 +217,21 @@ export function createApiMiddleware(server, { onError }) {
217
217
  return { json: { success: true } };
218
218
  },
219
219
  }));
220
+ router.use(apiRoute({
221
+ method: 'POST',
222
+ endpoint: '/update-handle',
223
+ schema: z
224
+ .object({
225
+ sub: subSchema,
226
+ handle: handleSchema,
227
+ })
228
+ .strict(),
229
+ async handler(req, res) {
230
+ const { account } = await authenticate.call(this, req, res);
231
+ await server.accountManager.updateHandle(this.deviceId, this.deviceMetadata, this.input, account);
232
+ return { json: { success: true } };
233
+ },
234
+ }));
220
235
  router.use(apiRoute({
221
236
  method: 'GET',
222
237
  endpoint: '/device-sessions',
@@ -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,EAAE,eAAe,EAAE,MAAM,cAAc,CAAA;AAC9C,OAAO,EACL,mBAAmB,GAMpB,MAAM,6BAA6B,CAAA;AACpC,OAAO,EAIL,sBAAsB,EACtB,uBAAuB,GACxB,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAA;AAC7D,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAA;AAC/D,OAAO,EAAY,cAAc,EAAE,MAAM,wBAAwB,CAAA;AACjE,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,sBAAsB,CAAA;AAC7B,OAAO,EAAY,WAAW,EAAE,M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,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 { signedJwtSchema } from '@atproto/jwk'\nimport {\n API_ENDPOINT_PREFIX,\n ActiveAccountSession,\n ActiveDeviceSession,\n ActiveOAuthSession,\n ApiEndpoints,\n ISODateString,\n} from '@atproto/oauth-provider-api'\nimport {\n OAuthAuthorizationRequestParameters,\n OAuthRedirectUri,\n OAuthResponseMode,\n oauthRedirectUriSchema,\n oauthResponseModeSchema,\n} from '@atproto/oauth-types'\nimport { signInDataSchema } from '../account/sign-in-data.js'\nimport { signUpInputSchema } from '../account/sign-up-input.js'\nimport { DeviceId, deviceIdSchema } from '../device/device-id.js'\nimport { AuthorizationError } from '../errors/authorization-error.js'\nimport {\n 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 JsonResponse,\n Middleware,\n RequestMetadata,\n Router,\n RouterCtx,\n SubCtx,\n flushStream,\n jsonHandler,\n parseHttpRequest,\n subCtx,\n validateFetchMode,\n validateFetchSite,\n validateOrigin,\n validateReferrer,\n} from '../lib/http/index.js'\nimport { 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 { Sub, subSchema } from '../oidc/sub.js'\nimport { RequestUri, requestUriSchema } from '../request/request-uri.js'\nimport { 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 } from '../types/password.js'\nimport { validateCsrfToken } from './assets/csrf.js'\nimport {\n ERROR_REDIRECT_KEYS,\n OAuthRedirectOptions,\n 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\nconst verifyHandleSchema = z.object({ handle: handleSchema }).strict()\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: verifyHandleSchema,\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.sub)\n }\n\n const ephemeralToken = remember\n ? undefined\n : await server.signer.createEphemeralToken({\n sub: account.sub,\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.sub)\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.sub)\n }\n\n const ephemeralToken = remember\n ? undefined\n : await server.signer.createEphemeralToken({\n sub: account.sub,\n deviceId,\n requestUri,\n })\n\n if (requestUri) {\n // Check if a consent is required for the client, but only if this\n // call is made within the context of an oauth request.\n\n const { clientId, parameters } = await server.requestManager.get(\n requestUri,\n deviceId,\n )\n\n const { authorizedClients } = await server.accountManager.getAccount(\n account.sub,\n )\n\n const json = {\n account,\n ephemeralToken,\n consentRequired: server.checkConsentRequired(\n parameters,\n authorizedClients.get(clientId),\n ),\n }\n\n return { json }\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 sub: z.union([subSchema, z.array(subSchema)]),\n })\n .strict(),\n rotateDeviceCookies: true,\n async handler() {\n const uniqueSubs = new Set(asArray(this.input.sub))\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 sub: subSchema,\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 sub: subSchema,\n token: emailOtpSchema,\n email: emailSchema,\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.updateEmailConfirm(\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-request',\n schema: z\n .object({\n sub: subSchema,\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 sub: subSchema,\n token: emailOtpSchema,\n email: emailSchema,\n })\n .strict(),\n async handler(req, res) {\n const { account } = await authenticate.call(this, req, res)\n\n await server.accountManager.verifyEmailConfirm(\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({ sub: subSchema }).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.sub,\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({ sub: subSchema }).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.sub,\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({ sub: subSchema, 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.sub,\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({ sub: subSchema, 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.sub !== account.sub) {\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({\n sub: z.union([subSchema, signedJwtSchema]),\n scope: z.string().optional(),\n })\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, { sub: Sub }>,\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.sub &&\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.sub,\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.sub} 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>\n : ApiEndpoints[E] extends { method: 'GET'; params: infer P }\n ? z.ZodType<P>\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,aAA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,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 { signedJwtSchema } from '@atproto/jwk'\nimport {\n API_ENDPOINT_PREFIX,\n ActiveAccountSession,\n ActiveDeviceSession,\n ActiveOAuthSession,\n ApiEndpoints,\n ISODateString,\n} from '@atproto/oauth-provider-api'\nimport {\n OAuthAuthorizationRequestParameters,\n OAuthRedirectUri,\n OAuthResponseMode,\n oauthRedirectUriSchema,\n oauthResponseModeSchema,\n} from '@atproto/oauth-types'\nimport { signInDataSchema } from '../account/sign-in-data.js'\nimport { signUpInputSchema } from '../account/sign-up-input.js'\nimport { DeviceId, deviceIdSchema } from '../device/device-id.js'\nimport { AuthorizationError } from '../errors/authorization-error.js'\nimport {\n 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 JsonResponse,\n Middleware,\n RequestMetadata,\n Router,\n RouterCtx,\n SubCtx,\n flushStream,\n jsonHandler,\n parseHttpRequest,\n subCtx,\n validateFetchMode,\n validateFetchSite,\n validateOrigin,\n validateReferrer,\n} from '../lib/http/index.js'\nimport { 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 { Sub, subSchema } from '../oidc/sub.js'\nimport { RequestUri, requestUriSchema } from '../request/request-uri.js'\nimport { 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 } from '../types/password.js'\nimport { validateCsrfToken } from './assets/csrf.js'\nimport {\n ERROR_REDIRECT_KEYS,\n OAuthRedirectOptions,\n 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\nconst verifyHandleSchema = z.object({ handle: handleSchema }).strict()\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: verifyHandleSchema,\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.sub)\n }\n\n const ephemeralToken = remember\n ? undefined\n : await server.signer.createEphemeralToken({\n sub: account.sub,\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.sub)\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.sub)\n }\n\n const ephemeralToken = remember\n ? undefined\n : await server.signer.createEphemeralToken({\n sub: account.sub,\n deviceId,\n requestUri,\n })\n\n if (requestUri) {\n // Check if a consent is required for the client, but only if this\n // call is made within the context of an oauth request.\n\n const { clientId, parameters } = await server.requestManager.get(\n requestUri,\n deviceId,\n )\n\n const { authorizedClients } = await server.accountManager.getAccount(\n account.sub,\n )\n\n const json = {\n account,\n ephemeralToken,\n consentRequired: server.checkConsentRequired(\n parameters,\n authorizedClients.get(clientId),\n ),\n }\n\n return { json }\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 sub: z.union([subSchema, z.array(subSchema)]),\n })\n .strict(),\n rotateDeviceCookies: true,\n async handler() {\n const uniqueSubs = new Set(asArray(this.input.sub))\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 sub: subSchema,\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 sub: subSchema,\n email: emailSchema,\n token: emailOtpSchema.optional(),\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.updateEmailConfirm(\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-request',\n schema: z\n .object({\n sub: subSchema,\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 sub: subSchema,\n token: emailOtpSchema,\n email: emailSchema,\n })\n .strict(),\n async handler(req, res) {\n const { account } = await authenticate.call(this, req, res)\n\n await server.accountManager.verifyEmailConfirm(\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: '/update-handle',\n schema: z\n .object({\n sub: subSchema,\n handle: handleSchema,\n })\n .strict(),\n async handler(req, res) {\n const { account } = await authenticate.call(this, req, res)\n\n await server.accountManager.updateHandle(\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({ sub: subSchema }).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.sub,\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({ sub: subSchema }).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.sub,\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({ sub: subSchema, 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.sub,\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({ sub: subSchema, 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.sub !== account.sub) {\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({\n sub: z.union([subSchema, signedJwtSchema]),\n scope: z.string().optional(),\n })\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, { sub: Sub }>,\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.sub &&\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.sub,\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.sub} 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>\n : ApiEndpoints[E] extends { method: 'GET'; params: infer P }\n ? z.ZodType<P>\n : void,\n >(options: {\n method: M\n endpoint: E\n schema: S\n rotateDeviceCookies?: boolean\n handler: (\n this: ApiContext<RouteCtx<C>, InferValidation<S>>,\n req: Req,\n res: Res,\n ) => Awaitable<JsonResponse<ErrorPayload | ApiEndpoints[E]['output']>>\n }): Middleware<C, Req, Res> {\n return createRoute(\n options.method,\n `${API_ENDPOINT_PREFIX}${options.endpoint}`,\n apiMiddleware(options),\n )\n }\n\n function apiMiddleware<C extends RouterCtx, S extends void | z.ZodTypeAny>({\n method,\n schema,\n rotateDeviceCookies,\n handler,\n }: {\n method: 'GET' | 'POST'\n schema: S\n rotateDeviceCookies?: boolean\n handler: (\n this: ApiContext<C, InferValidation<S>>,\n req: Req,\n res: Res,\n ) => Awaitable<JsonResponse>\n }): Middleware<C, Req, Res> {\n const parseInput: (this: C, req: Req) => Promise<InferValidation<S>> =\n schema == null // No schema means endpoint doesn't accept any input\n ? async function (req) {\n await flushStream(req)\n return undefined\n }\n : method === 'POST'\n ? async function (req) {\n const body = await parseHttpRequest(req, ['json'])\n return schema.parseAsync(body, { path: ['body'] })\n }\n : async function (req) {\n await flushStream(req)\n const query = Object.fromEntries(this.url.searchParams)\n return schema.parseAsync(query, { path: ['query'] })\n }\n\n return jsonHandler<C, Req, Res>(async function (req, res) {\n try {\n // Prevent caching of API routes\n res.setHeader('Cache-Control', 'no-store')\n res.setHeader('Pragma', 'no-cache')\n\n // Prevent CORS requests\n validateFetchMode(req, ['same-origin'])\n validateFetchSite(req, ['same-origin'])\n validateOrigin(req, issuerOrigin)\n const referrer = validateReferrer(req, { origin: issuerOrigin })\n\n // Ensure we are one the right page\n if (\n // trailing slashes are not allowed\n referrer.pathname !== '/oauth/authorize' &&\n referrer.pathname !== '/account' &&\n !referrer.pathname.startsWith(`/account/`)\n ) {\n throw createHttpError(400, `Invalid referrer ${referrer}`)\n }\n\n // Check if the request originated from the authorize page\n const requestUri =\n referrer.pathname === '/oauth/authorize'\n ? await requestUriSchema.parseAsync(\n referrer.searchParams.get('request_uri'),\n )\n : undefined\n\n // Validate CSRF token\n await validateCsrfToken(req, res)\n\n // Parse and validate the input data\n const input = await parseInput.call(this, req)\n\n // Load session data, rotating the session cookie if needed\n const { deviceId, deviceMetadata } = await server.deviceManager.load(\n req,\n res,\n rotateDeviceCookies,\n )\n\n const context: ApiContext<C, InferValidation<S>> = subCtx(this, {\n input,\n requestUri,\n deviceId,\n deviceMetadata,\n })\n\n return await handler.call(context, req, res)\n } catch (err) {\n onError?.(req, res, err, `Failed to handle API request`)\n\n // Make sore to always return a JSON response\n return buildErrorJsonResponse(err)\n }\n })\n }\n}\n\nfunction buildErrorJsonResponse(err: unknown) {\n // @TODO Rework the API error responses (relying on codes)\n const json = buildErrorPayload(err)\n const status = buildErrorStatus(err)\n\n return { json, status }\n}\n\nfunction buildRedirectUrl(\n iss: string,\n parameters: OAuthAuthorizationRequestParameters,\n redirect: AuthorizationRedirectParameters,\n): string {\n const url = new URL('/oauth/authorize/redirect', iss)\n\n url.searchParams.set('redirect_mode', buildRedirectMode(parameters))\n url.searchParams.set('redirect_uri', buildRedirectUri(parameters))\n\n for (const [key, value] of buildRedirectParams(iss, parameters, redirect)) {\n url.searchParams.set(key, value)\n }\n\n return url.href\n}\n\nexport function parseRedirectUrl(url: URL): OAuthRedirectOptions {\n if (url.pathname !== '/oauth/authorize/redirect') {\n throw new InvalidRequestError(\n `Invalid redirect URL: ${url.pathname} is not a valid path`,\n )\n }\n\n const params: [OAuthRedirectQueryParameter, string][] = []\n\n const state = url.searchParams.get('state')\n if (state) params.push(['state', state])\n\n const iss = url.searchParams.get('iss')\n if (iss) params.push(['iss', iss])\n\n if (url.searchParams.has('code')) {\n for (const key of SUCCESS_REDIRECT_KEYS) {\n const value = url.searchParams.get(key)\n if (value != null) params.push([key, value])\n }\n } else if (url.searchParams.has('error')) {\n for (const key of ERROR_REDIRECT_KEYS) {\n const value = url.searchParams.get(key)\n if (value != null) params.push([key, value])\n }\n } else {\n throw new InvalidRequestError(\n 'Invalid redirect URL: neither code nor error found',\n )\n }\n\n try {\n const mode: OAuthResponseMode = oauthResponseModeSchema.parse(\n url.searchParams.get('redirect_mode'),\n )\n\n const redirectUri: OAuthRedirectUri = oauthRedirectUriSchema.parse(\n url.searchParams.get('redirect_uri'),\n )\n\n return { mode, redirectUri, params }\n } catch (err) {\n throw InvalidRequestError.from(err, 'Invalid redirect URL')\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atproto/oauth-provider",
3
- "version": "0.18.1",
3
+ "version": "0.18.3",
4
4
  "license": "MIT",
5
5
  "description": "Generic OAuth2 and OpenID Connect provider for Node.js. Currently only supports features needed for Atproto.",
6
6
  "keywords": [
@@ -41,19 +41,19 @@
41
41
  "jose": "^5.2.0",
42
42
  "zod": "^3.23.8",
43
43
  "@atproto-labs/fetch": "^0.3.0",
44
- "@atproto-labs/fetch-node": "^0.3.0",
45
44
  "@atproto-labs/pipe": "^0.2.0",
45
+ "@atproto-labs/fetch-node": "^0.3.0",
46
46
  "@atproto-labs/simple-store": "^0.4.0",
47
+ "@atproto/common": "^0.6.2",
47
48
  "@atproto-labs/simple-store-memory": "^0.2.0",
48
- "@atproto/common": "^0.6.1",
49
49
  "@atproto/did": "^0.5.0",
50
50
  "@atproto/jwk": "^0.7.0",
51
51
  "@atproto/jwk-jose": "^0.2.0",
52
52
  "@atproto/lex-document": "^0.1.0",
53
53
  "@atproto/lex-resolver": "^0.1.0",
54
54
  "@atproto/oauth-types": "^0.7.1",
55
- "@atproto/oauth-provider-api": "0.6.0",
56
- "@atproto/oauth-provider-ui": "0.7.1",
55
+ "@atproto/oauth-provider-api": "0.6.1",
56
+ "@atproto/oauth-provider-ui": "0.7.3",
57
57
  "@atproto/oauth-scopes": "^0.5.0",
58
58
  "@atproto/syntax": "^0.6.1"
59
59
  },
@@ -23,6 +23,7 @@ import {
23
23
  SignUpData,
24
24
  UpdateEmailConfirmInput,
25
25
  UpdateEmailRequestInput,
26
+ UpdateHandleData,
26
27
  VerifyEmailConfirmInput,
27
28
  VerifyEmailRequestInput,
28
29
  } from './account-store.js'
@@ -453,4 +454,29 @@ export class AccountManager {
453
454
 
454
455
  return updatedAccount
455
456
  }
457
+
458
+ public async updateHandle(
459
+ deviceId: DeviceId,
460
+ deviceMetadata: RequestMetadata,
461
+ input: UpdateHandleData,
462
+ account: Account,
463
+ ): Promise<Account> {
464
+ await this.hooks.onUpdateHandle?.call(null, {
465
+ deviceId,
466
+ deviceMetadata,
467
+ input,
468
+ account,
469
+ })
470
+
471
+ const updatedAccount = await this.store.updateHandle(input)
472
+
473
+ await this.hooks.onUpdatedHandle?.call(null, {
474
+ deviceId,
475
+ deviceMetadata,
476
+ input,
477
+ account: updatedAccount,
478
+ })
479
+
480
+ return updatedAccount
481
+ }
456
482
  }
@@ -7,6 +7,7 @@ import type {
7
7
  InitiateEmailUpdateOutput,
8
8
  InitiateEmailVerificationInput,
9
9
  InitiatePasswordResetInput,
10
+ UpdateHandleInput,
10
11
  } from '@atproto/oauth-provider-api'
11
12
  import { OAuthScope } from '@atproto/oauth-types'
12
13
  import { ClientId } from '../client/client-id.js'
@@ -55,6 +56,7 @@ export type UpdateEmailRequestOutput = InitiateEmailUpdateOutput
55
56
  export type UpdateEmailConfirmInput = ConfirmEmailUpdateInput
56
57
  export type VerifyEmailRequestInput = InitiateEmailVerificationInput
57
58
  export type VerifyEmailConfirmInput = ConfirmEmailVerificationInput
59
+ export type UpdateHandleData = UpdateHandleInput
58
60
 
59
61
  export type CreateAccountData = {
60
62
  locale: string
@@ -216,6 +218,13 @@ export interface AccountStore {
216
218
  * @throws {HandleUnavailableError} - To indicate that the handle is already taken
217
219
  */
218
220
  verifyHandleAvailability(handle: string): Awaitable<void>
221
+
222
+ /**
223
+ * @throws {HandleUnavailableError} - To indicate that the handle is already taken
224
+ * @throws {InvalidRequestError} - To indicate that the handle is invalid or
225
+ * cannot be used
226
+ */
227
+ updateHandle(data: UpdateHandleData): Awaitable<Account>
219
228
  }
220
229
 
221
230
  export const isAccountStore = buildInterfaceChecker<AccountStore>([
@@ -234,6 +243,7 @@ export const isAccountStore = buildInterfaceChecker<AccountStore>([
234
243
  'verifyEmailRequest',
235
244
  'verifyEmailConfirm',
236
245
  'verifyHandleAvailability',
246
+ 'updateHandle',
237
247
  ])
238
248
 
239
249
  export function asAccountStore<V>(implementation: V): V & AccountStore {
@@ -5,6 +5,7 @@ export function buildCustomizationData({
5
5
  branding,
6
6
  availableUserDomains,
7
7
  inviteCodeRequired,
8
+ show2FaWarningOnEmailUpdate,
8
9
  hcaptcha,
9
10
  }: Customization): CustomizationData {
10
11
  // @NOTE the front end does not need colors here as they will be injected as
@@ -14,6 +15,7 @@ export function buildCustomizationData({
14
15
  return {
15
16
  availableUserDomains,
16
17
  inviteCodeRequired,
18
+ show2FaWarningOnEmailUpdate,
17
19
  hcaptchaSiteKey: hcaptcha?.siteKey,
18
20
  name: branding?.name,
19
21
  logo: branding?.logo,
@@ -16,6 +16,10 @@ export const customizationSchema = z.object({
16
16
  * Is an invite code required to sign up?
17
17
  */
18
18
  inviteCodeRequired: z.boolean().optional(),
19
+ /**
20
+ * Show a warning about 2FA being disabled when updating email address
21
+ */
22
+ show2FaWarningOnEmailUpdate: z.boolean().optional(),
19
23
  /**
20
24
  * Enables hCaptcha during sign-up.
21
25
  */
@@ -1,8 +1,13 @@
1
+ import { HandleUnavailableReason } from '@atproto/oauth-provider-api'
1
2
  import { OAuthError } from './oauth-error.js'
2
3
 
4
+ // @TODO this is *not* and "OAuthError" error but rather an ApiError.
5
+
6
+ export type { HandleUnavailableReason }
7
+
3
8
  export class HandleUnavailableError extends OAuthError {
4
9
  constructor(
5
- readonly reason: 'syntax' | 'domain' | 'slur' | 'taken',
10
+ readonly reason: HandleUnavailableReason,
6
11
  details: string = 'That handle is not available',
7
12
  cause?: unknown,
8
13
  ) {
@@ -14,6 +14,7 @@ import {
14
14
  SignUpData,
15
15
  UpdateEmailConfirmInput,
16
16
  UpdateEmailRequestInput,
17
+ UpdateHandleData,
17
18
  VerifyEmailConfirmInput,
18
19
  VerifyEmailRequestInput,
19
20
  } from './account/account-store.js'
@@ -76,6 +77,7 @@ export {
76
77
  type SignUpInput,
77
78
  type Sub,
78
79
  type TokenClaims,
80
+ type UpdateHandleData,
79
81
  }
80
82
 
81
83
  export type OAuthHooks = {
@@ -183,6 +185,29 @@ export type OAuthHooks = {
183
185
  account: Account
184
186
  }) => Awaitable<void>
185
187
 
188
+ /**
189
+ * This hook is called when a user requests a handle change, before the change
190
+ * is performed on the account store. Only triggered with authenticated
191
+ * sessions, so the `account` is always available.
192
+ */
193
+ onUpdateHandle?: (data: {
194
+ input: UpdateHandleData
195
+ deviceId: DeviceId
196
+ deviceMetadata: RequestMetadata
197
+ account: Account
198
+ }) => Awaitable<void>
199
+
200
+ /**
201
+ * This hook is called after a user successfully changed their handle on the
202
+ * account store.
203
+ */
204
+ onUpdatedHandle?: (data: {
205
+ input: UpdateHandleData
206
+ deviceId: DeviceId
207
+ deviceMetadata: RequestMetadata
208
+ account: Account
209
+ }) => Awaitable<void>
210
+
186
211
  /**
187
212
  * This hook is called when a user attempts to sign up, after every validation
188
213
  * has passed (including hcaptcha).
@@ -41,13 +41,13 @@ export function oauthMiddleware<
41
41
  }
42
42
  : onError
43
43
 
44
- return asHandler(
45
- combineMiddlewares([
46
- assetsMiddleware,
47
- createOAuthMiddleware(server, options),
48
- createApiMiddleware(server, options),
49
- createAuthorizationPageMiddleware(server, options),
50
- createAccountPageMiddleware(server, options),
51
- ]),
52
- )
44
+ const middleware = combineMiddlewares([
45
+ assetsMiddleware,
46
+ createOAuthMiddleware(server, options),
47
+ createApiMiddleware(server, options),
48
+ createAuthorizationPageMiddleware(server, options),
49
+ createAccountPageMiddleware(server, options),
50
+ ])
51
+
52
+ return asHandler(middleware)
53
53
  }
@@ -302,8 +302,8 @@ export function createApiMiddleware<
302
302
  schema: z
303
303
  .object({
304
304
  sub: subSchema,
305
- token: emailOtpSchema,
306
305
  email: emailSchema,
306
+ token: emailOtpSchema.optional(),
307
307
  locale: localeSchema.optional(),
308
308
  })
309
309
  .strict(),
@@ -373,6 +373,31 @@ export function createApiMiddleware<
373
373
  }),
374
374
  )
375
375
 
376
+ router.use(
377
+ apiRoute({
378
+ method: 'POST',
379
+ endpoint: '/update-handle',
380
+ schema: z
381
+ .object({
382
+ sub: subSchema,
383
+ handle: handleSchema,
384
+ })
385
+ .strict(),
386
+ async handler(req, res) {
387
+ const { account } = await authenticate.call(this, req, res)
388
+
389
+ await server.accountManager.updateHandle(
390
+ this.deviceId,
391
+ this.deviceMetadata,
392
+ this.input,
393
+ account,
394
+ )
395
+
396
+ return { json: { success: true } }
397
+ },
398
+ }),
399
+ )
400
+
376
401
  router.use(
377
402
  apiRoute({
378
403
  method: 'GET',
@@ -2,7 +2,7 @@
2
2
  "extends": ["../../../tsconfig/nodenext.json"],
3
3
  "compilerOptions": {
4
4
  "outDir": "dist",
5
- "rootDir": "src"
5
+ "rootDir": "src",
6
6
  },
7
- "include": ["src"]
7
+ "include": ["src"],
8
8
  }
package/tsconfig.json CHANGED
@@ -1,4 +1,4 @@
1
1
  {
2
2
  "include": [],
3
- "references": [{ "path": "./tsconfig.build.json" }]
3
+ "references": [{ "path": "./tsconfig.build.json" }],
4
4
  }