@atproto/pds 0.5.0 → 0.5.1

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 (71) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/api/app/bsky/actor/getPreferences.d.ts.map +1 -1
  3. package/dist/api/app/bsky/actor/getPreferences.js +7 -2
  4. package/dist/api/app/bsky/actor/getPreferences.js.map +1 -1
  5. package/dist/api/app/bsky/actor/putPreferences.d.ts.map +1 -1
  6. package/dist/api/app/bsky/actor/putPreferences.js +7 -2
  7. package/dist/api/app/bsky/actor/putPreferences.js.map +1 -1
  8. package/dist/api/com/atproto/server/getServiceAuth.d.ts.map +1 -1
  9. package/dist/api/com/atproto/server/getServiceAuth.js +4 -0
  10. package/dist/api/com/atproto/server/getServiceAuth.js.map +1 -1
  11. package/dist/config/config.d.ts +5 -2
  12. package/dist/config/config.d.ts.map +1 -1
  13. package/dist/config/config.js +50 -46
  14. package/dist/config/config.js.map +1 -1
  15. package/dist/config/env.d.ts +1 -0
  16. package/dist/config/env.d.ts.map +1 -1
  17. package/dist/config/env.js +1 -0
  18. package/dist/config/env.js.map +1 -1
  19. package/dist/context.js +1 -1
  20. package/dist/context.js.map +1 -1
  21. package/dist/lexicons/chat/bsky/actor/getStatus.defs.d.ts +2 -0
  22. package/dist/lexicons/chat/bsky/actor/getStatus.defs.d.ts.map +1 -1
  23. package/dist/lexicons/chat/bsky/actor/getStatus.defs.js +1 -0
  24. package/dist/lexicons/chat/bsky/actor/getStatus.defs.js.map +1 -1
  25. package/dist/lexicons/chat/bsky/convo/defs.defs.d.ts +1 -1
  26. package/dist/lexicons/chat/bsky/convo/defs.defs.d.ts.map +1 -1
  27. package/dist/lexicons/chat/bsky/convo/defs.defs.js +1 -1
  28. package/dist/lexicons/chat/bsky/convo/defs.defs.js.map +1 -1
  29. package/dist/lexicons/com/atproto/server/getServiceAuth.defs.d.ts +2 -2
  30. package/dist/lexicons/com/atproto/server/getServiceAuth.defs.js +1 -1
  31. package/dist/lexicons/com/atproto/server/getServiceAuth.defs.js.map +1 -1
  32. package/dist/mailer/index.d.ts +3 -3
  33. package/dist/mailer/index.d.ts.map +1 -1
  34. package/dist/mailer/index.js +18 -9
  35. package/dist/mailer/index.js.map +1 -1
  36. package/dist/mailer/templates/confirm-email.js +11 -3
  37. package/dist/mailer/templates/confirm-email.js.map +2 -2
  38. package/dist/mailer/templates/delete-account.js +2 -2
  39. package/dist/mailer/templates/delete-account.js.map +2 -2
  40. package/dist/mailer/templates/plc-operation.js +2 -2
  41. package/dist/mailer/templates/plc-operation.js.map +2 -2
  42. package/dist/mailer/templates/reset-password.js +2 -2
  43. package/dist/mailer/templates/reset-password.js.map +2 -2
  44. package/dist/mailer/templates/update-email.js +2 -2
  45. package/dist/mailer/templates/update-email.js.map +2 -2
  46. package/dist/mailer/templates.d.ts +11 -0
  47. package/dist/mailer/templates.d.ts.map +1 -1
  48. package/dist/mailer/templates.js.map +1 -1
  49. package/dist/pipethrough.d.ts +3 -0
  50. package/dist/pipethrough.d.ts.map +1 -1
  51. package/dist/pipethrough.js +25 -9
  52. package/dist/pipethrough.js.map +1 -1
  53. package/package.json +11 -10
  54. package/src/api/app/bsky/actor/getPreferences.ts +11 -2
  55. package/src/api/app/bsky/actor/putPreferences.ts +11 -2
  56. package/src/api/com/atproto/server/getServiceAuth.ts +7 -0
  57. package/src/config/config.ts +69 -57
  58. package/src/config/env.ts +3 -0
  59. package/src/context.ts +1 -1
  60. package/src/mailer/index.ts +25 -9
  61. package/src/mailer/templates/confirm-email.hbs +18 -17
  62. package/src/mailer/templates/delete-account.hbs +6 -6
  63. package/src/mailer/templates/plc-operation.hbs +6 -6
  64. package/src/mailer/templates/reset-password.hbs +7 -7
  65. package/src/mailer/templates/update-email.hbs +6 -6
  66. package/src/mailer/templates.ts +12 -0
  67. package/src/pipethrough.ts +33 -12
  68. package/tests/app-passwords.test.ts +5 -5
  69. package/tests/get-service-auth.test.ts +81 -0
  70. package/tests/proxied/proxy-header.test.ts +1 -0
  71. package/tests/proxied/proxy-oauth-aud.test.ts +175 -0
@@ -1 +1 @@
1
- {"version":3,"file":"pipethrough.js","sourceRoot":"","sources":["../src/pipethrough.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAY,QAAQ,EAAE,MAAM,aAAa,CAAA;AAG7D,OAAO,EACL,YAAY,EACZ,kBAAkB,EAClB,IAAI,EACJ,kBAAkB,GACnB,MAAM,iBAAiB,CAAA;AAExB,OAAO,EAIL,mBAAmB,EACnB,mBAAmB,EACnB,YAAY,EACZ,SAAS,IAAI,eAAe,EAC5B,kBAAkB,EAClB,YAAY,GACb,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAA;AACtE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAA;AAEpD,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAA;AACtD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAExC,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,GAAe,EAAmB,EAAE;IAC/D,MAAM,WAAW,GAAG,GAAG,CAAC,YAAY,CAAC,aAAa,CAAqB;QACrE,SAAS,EAAE,CAAC,WAAW,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,WAAW,CAAC,SAAS,CAAC,MAAM,CAAC;KACtE,CAAC,CAAA;IAEF,OAAO,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC9B,eAAe;QACf,IAAI,CAAC;YACH,IACE,GAAG,CAAC,MAAM,KAAK,KAAK;gBACpB,GAAG,CAAC,MAAM,KAAK,MAAM;gBACrB,GAAG,CAAC,MAAM,KAAK,MAAM,EACrB,CAAC;gBACD,MAAM,IAAI,eAAe,CACvB,YAAY,CAAC,cAAc,EAC3B,0CAA0C,CAC3C,CAAA;YACH,CAAC;YAED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AAC,CAAA;AAED,MAAM,UAAU,GAAG,CAAC,GAAY,EAAsB,EAAE;IACtD,OAAO,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,CAAA;AAClD,CAAC,CAAA;AAED,SAAS,gBAAgB,CAAuB,GAAY;IAC1D,UAAU,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,EAAE,oCAAoC,CAAC,CAAA;AAChE,CAAC;AAED,MAAM,OAAO,wBAAyB,SAAQ,eAAe;IAC3D,YACW,QAGR,EACD,OAA6C,EAC7C,OAAsB;QAEtB,MAAM,MAAM,GACV,QAAQ,CAAC,UAAU,KAAK,GAAG;YACzB,CAAC,CAAC,YAAY,CAAC,eAAe;YAC9B,CAAC,CAAC,QAAQ,CAAC,UAAU,CAAA;QAEzB,KAAK,CAAC,MAAM,EAAE,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,CAAA;QAZ7C,aAAQ,GAAR,QAAQ,CAGhB;IAUH,CAAC;IAED,IAAI,OAAO;QACT,OAAO,MAAM,CAAC,WAAW,CAAC,eAAe,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAA;IAC1E,CAAC;IAED,IAAI,KAAK;QACP,OAAO,IAAI,CAAC,eAAe,IAAI,IAAI,CAAC,QAAQ,CAAA;IAC9C,CAAC;CACF","sourcesContent":["import { IncomingHttpHeaders, ServerResponse } from 'node:http'\nimport { PassThrough, Readable, finished } from 'node:stream'\nimport { Request } from 'express'\nimport { Dispatcher } from 'undici'\nimport {\n decodeStream,\n getServiceEndpoint,\n omit,\n streamToNodeBuffer,\n} from '@atproto/common'\nimport { RpcPermissionMatch } from '@atproto/oauth-scopes'\nimport {\n CatchallHandler,\n HandlerPipeThroughBuffer,\n HandlerPipeThroughStream,\n InternalServerError,\n InvalidRequestError,\n ResponseType,\n XRPCError as XRPCServerError,\n excludeErrorResult,\n parseReqNsid,\n} from '@atproto/xrpc-server'\nimport { buildProxiedContentEncoding } from '@atproto-labs/xrpc-utils'\nimport { isAccessPrivileged } from './auth-scope.js'\nimport { AppContext } from './context.js'\nimport { chat, com, tools } from './lexicons/index.js'\nimport { httpLogger } from './logger.js'\n\nexport const proxyHandler = (ctx: AppContext): CatchallHandler => {\n const performAuth = ctx.authVerifier.authorization<RpcPermissionMatch>({\n authorize: (permissions, { params }) => permissions.assertRpc(params),\n })\n\n return async (req, res, next) => {\n // /!\\ Hot path\n try {\n if (\n req.method !== 'GET' &&\n req.method !== 'HEAD' &&\n req.method !== 'POST'\n ) {\n throw new XRPCServerError(\n ResponseType.InvalidRequest,\n 'XRPC requests only supports GET and POST',\n )\n }\n\n const body = req.method === 'POST' ? req : undefined\n if (body != null && !body.readable) {\n // Body was already consumed by a previous middleware\n throw new InternalServerError('Request body is not readable')\n }\n\n const lxm = parseReqNsid(req)\n if (PROTECTED_METHODS.has(lxm)) {\n throw new InvalidRequestError('Bad token method', 'InvalidToken')\n }\n\n const { url: origin, did: aud } = await parseProxyInfo(ctx, req, lxm)\n\n const authResult = await performAuth({ req, res, params: { lxm, aud } })\n\n const { credentials } = excludeErrorResult(authResult)\n\n if (\n credentials.type === 'access' &&\n !isAccessPrivileged(credentials.scope) &&\n PRIVILEGED_METHODS.has(lxm)\n ) {\n throw new InvalidRequestError('Bad token method', 'InvalidToken')\n }\n\n const headers: IncomingHttpHeaders = {\n 'accept-encoding': req.headers['accept-encoding'] || 'identity',\n 'accept-language': req.headers['accept-language'],\n 'atproto-accept-labelers': req.headers['atproto-accept-labelers'],\n 'x-bsky-topics': req.headers['x-bsky-topics'],\n\n 'content-type': body && req.headers['content-type'],\n 'content-encoding': body && req.headers['content-encoding'],\n 'content-length': body && req.headers['content-length'],\n\n authorization: `Bearer ${await ctx.serviceAuthJwt(credentials.did, aud, lxm)}`,\n }\n\n const dispatchOptions: Dispatcher.RequestOptions = {\n origin,\n method: req.method,\n path: req.originalUrl,\n body,\n headers,\n }\n\n await pipethroughStream(ctx, req, dispatchOptions, (upstream) => {\n res.status(upstream.statusCode)\n\n for (const [name, val] of responseHeaders(upstream.headers)) {\n res.setHeader(name, val)\n }\n\n // Note that we should not need to manually handle errors here (e.g. by\n // destroying the response), as the http server will handle them for us.\n res.on('error', logResponseError)\n\n // Tell undici to write the upstream response directly to the response\n return res\n })\n } catch (err) {\n next(err)\n }\n }\n}\n\nexport type PipethroughOptions = {\n /**\n * Specify the issuer (requester) for service auth. If not provided, no\n * authorization headers will be added to the request.\n */\n iss?: string\n\n /**\n * Override the audience for service auth. If not provided, the audience will\n * be determined based on the proxy service.\n */\n aud?: string\n\n /**\n * Override the lexicon method for service auth. If not provided, the lexicon\n * method will be determined based on the request path.\n */\n lxm?: string\n}\n\nexport async function pipethrough(\n ctx: AppContext,\n req: Request,\n options?: PipethroughOptions,\n): Promise<\n HandlerPipeThroughStream & {\n stream: Readable\n headers: Record<string, string>\n encoding: string\n }\n> {\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n // pipethrough() is used from within xrpcServer handlers, which means that\n // the request body either has been parsed or is a readable stream that has\n // been piped for decoding & size limiting. Because of this, forwarding the\n // request body requires re-encoding it. Since we currently do not use\n // pipethrough() with procedures, proxying of request body is not\n // implemented.\n throw new InternalServerError(\n `Proxying of ${req.method} requests is not supported`,\n )\n }\n\n const lxm = parseReqNsid(req)\n\n const { url: origin, did: aud } = await parseProxyInfo(ctx, req, lxm)\n\n const dispatchOptions: Dispatcher.RequestOptions = {\n origin,\n method: req.method,\n path: req.originalUrl,\n headers: {\n 'accept-language': req.headers['accept-language'],\n 'atproto-accept-labelers': req.headers['atproto-accept-labelers'],\n 'x-bsky-topics': req.headers['x-bsky-topics'],\n\n // Because we sometimes need to interpret the response (e.g. during\n // read-after-write, through asPipeThroughBuffer()), we need to ask the\n // upstream server for an encoding that both the requester and the PDS can\n // understand. Since we might have to do the decoding ourselves, we will\n // use our own preferences (and weight) to negotiate the encoding.\n 'accept-encoding': buildProxiedContentEncoding(\n req.headers['accept-encoding'],\n ctx.cfg.proxy.preferCompressed,\n ),\n\n authorization: options?.iss\n ? `Bearer ${await ctx.serviceAuthJwt(options.iss, options.aud ?? aud, options.lxm ?? lxm)}`\n : undefined,\n },\n\n // Use a high water mark to buffer more data while performing async\n // operations before this stream is consumed. This is especially useful\n // while processing read-after-write operations.\n highWaterMark: 2 * 65536, // twice the default (64KiB)\n }\n\n const { headers, body } = await pipethroughRequest(ctx, req, dispatchOptions)\n\n return {\n encoding: safeString(headers['content-type']) ?? 'application/json',\n headers: Object.fromEntries(responseHeaders(headers)),\n stream: body,\n }\n}\n\n// Request setup/formatting\n// -------------------\n\nexport function computeProxyTo(\n ctx: AppContext,\n req: Request,\n lxm: string,\n): string {\n const proxyToHeader = req.header('atproto-proxy')\n if (proxyToHeader) return proxyToHeader\n\n const service = defaultService(ctx, lxm)\n if (service.serviceInfo) {\n return `${service.serviceInfo.did}#${service.serviceId}`\n }\n\n throw new InvalidRequestError(`No service configured for ${lxm}`)\n}\n\nexport async function parseProxyInfo(\n ctx: AppContext,\n req: Request,\n lxm: string,\n): Promise<{ url: string; did: string }> {\n // /!\\ Hot path\n\n const proxyToHeader = req.header('atproto-proxy')\n if (proxyToHeader) return parseProxyHeader(ctx, proxyToHeader)\n\n const { serviceInfo } = defaultService(ctx, lxm)\n if (serviceInfo) return serviceInfo\n\n throw new InvalidRequestError(`No service configured for ${lxm}`)\n}\n\nexport const parseProxyHeader = async (\n // Using subset of AppContext for testing purposes\n ctx: Pick<AppContext, 'cfg' | 'idResolver'>,\n proxyTo: string,\n): Promise<{ did: string; url: string }> => {\n // /!\\ Hot path\n\n const hashIndex = proxyTo.indexOf('#')\n\n if (hashIndex === 0) {\n throw new InvalidRequestError('no did specified in proxy header')\n }\n\n if (hashIndex === -1 || hashIndex === proxyTo.length - 1) {\n throw new InvalidRequestError('no service id specified in proxy header')\n }\n\n // More than one hash\n if (proxyTo.indexOf('#', hashIndex + 1) !== -1) {\n throw new InvalidRequestError('invalid proxy header format')\n }\n\n // Basic validation\n if (proxyTo.includes(' ')) {\n throw new InvalidRequestError('proxy header cannot contain spaces')\n }\n\n const did = proxyTo.slice(0, hashIndex)\n\n // Special case a configured appview, while still proxying correctly any other appview\n if (\n ctx.cfg.bskyAppView &&\n proxyTo === `${ctx.cfg.bskyAppView.did}#bsky_appview`\n ) {\n return { did, url: ctx.cfg.bskyAppView.url }\n }\n\n const didDoc = await ctx.idResolver.did.resolve(did)\n if (!didDoc) {\n throw new InvalidRequestError('could not resolve proxy did')\n }\n\n const serviceId = proxyTo.slice(hashIndex)\n const url = getServiceEndpoint(didDoc, { id: serviceId })\n if (!url) {\n throw new InvalidRequestError('could not resolve proxy did service url')\n }\n\n return { did, url }\n}\n\n/**\n * Utility function that wraps the undici stream() function and handles request\n * and response errors by wrapping them in XRPCError instances. This function is\n * more efficient than \"pipethroughRequest\" when a writable stream to pipe the\n * upstream response to is available.\n */\nasync function pipethroughStream(\n ctx: AppContext,\n req: Request,\n dispatchOptions: Dispatcher.RequestOptions,\n successStreamFactory: Dispatcher.StreamFactory,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n void ctx.proxyAgent\n .stream(dispatchOptions, (upstream) => {\n if (upstream.statusCode >= 400) {\n const passThrough = new PassThrough()\n\n void tryParsingError(upstream.headers, passThrough).then((parsed) => {\n const xrpcError = new PipethroughUpstreamError(upstream, parsed, {\n cause: dispatchOptions,\n })\n\n reject(xrpcError)\n }, reject)\n\n return passThrough\n }\n\n const writable = successStreamFactory(upstream)\n\n // As soon as the control was passed to the writable stream (i.e. by\n // returning the writable hereafter), pipethroughStream() is considered\n // to have succeeded. Any error occurring while writing upstream data to\n // the writable stream should be handled through the stream's error\n // state (i.e. successStreamFactory() must ensure that error events on\n // the returned writable will be handled).\n resolve()\n\n return writable\n })\n // The following catch block will be triggered with either network errors\n // or writable stream errors. In the latter case, the promise will already\n // be resolved, and reject()ing it there after will have no effect. Those\n // error would still be logged by the successStreamFactory() function.\n .catch(handleUpstreamRequestError.bind(req))\n .catch(reject)\n })\n}\n\n/**\n * Utility function that wraps the undici request() function and handles request\n * and response errors by wrapping them in XRPCError instances.\n */\nasync function pipethroughRequest(\n ctx: AppContext,\n req: Request,\n dispatchOptions: Dispatcher.RequestOptions,\n) {\n // HandlerPipeThroughStream requires a readable stream to be returned, so we\n // use the (less efficient) request() function instead.\n\n const upstream = await ctx.proxyAgent\n .request(dispatchOptions)\n .catch(handleUpstreamRequestError.bind(req))\n\n if (upstream.statusCode >= 400) {\n const parsed = await tryParsingError(upstream.headers, upstream.body)\n\n throw new PipethroughUpstreamError(upstream, parsed, {\n cause: dispatchOptions,\n })\n }\n\n return upstream\n}\n\nfunction handleUpstreamRequestError(\n this: Request,\n err: unknown,\n message = 'Upstream service unreachable',\n): never {\n const logger = isPinoHttpRequest(this) ? this.log : httpLogger\n logger.error({ err }, message)\n throw new XRPCServerError(ResponseType.UpstreamFailure, message, undefined, {\n cause: err,\n })\n}\n\nfunction isPinoHttpRequest(req: Request): req is Request & {\n log: { error: (obj: unknown, msg: string) => void }\n} {\n return typeof (req as { log?: any }).log?.error === 'function'\n}\n\n// Request parsing/forwarding\n// -------------------\n\nexport function isJsonContentType(contentType?: string): boolean | undefined {\n if (!contentType) return undefined\n return /application\\/(?:\\w+\\+)?json/i.test(contentType)\n}\n\nasync function tryParsingError(\n headers: IncomingHttpHeaders,\n readable: Readable,\n): Promise<{ error?: string; message?: string }> {\n if (isJsonContentType(headers['content-type']) === false) {\n // We don't known how to parse non JSON content types so we can discard the\n // whole response.\n\n // Since we don't care about the response, we would normally just destroy\n // the stream. However, if the underlying HTTP connection is an HTTP/1.1\n // connection, this also destroys the underlying (keep-alive) TCP socket. In\n // order to avoid destroying the TCP socket, while avoiding the cost of\n // consuming too much IO, we give it a chance to finish first.\n\n // @NOTE we need to listen (and ignore) \"error\" events, otherwise the\n // process could crash (since we drain the stream asynchronously here). This\n // is performed through the \"finished\" call below.\n\n const to = setTimeout(() => {\n readable.destroy()\n }, 100)\n finished(readable, (_err) => {\n clearTimeout(to)\n })\n readable.resume()\n\n return {}\n }\n\n try {\n const buffer = await bufferUpstreamResponse(\n readable,\n headers['content-encoding'],\n )\n\n const errInfo: unknown = JSON.parse(buffer.toString('utf8'))\n return {\n error: safeString(errInfo?.['error']),\n message: safeString(errInfo?.['message']),\n }\n } catch (err) {\n // Failed to read, decode, buffer or parse. No big deal.\n return {}\n }\n}\n\nasync function bufferUpstreamResponse(\n readable: Readable,\n contentEncoding?: string | string[],\n): Promise<Buffer> {\n try {\n return await streamToNodeBuffer(decodeStream(readable, contentEncoding))\n } catch (err) {\n if (!readable.destroyed) readable.destroy()\n\n throw new XRPCServerError(\n ResponseType.UpstreamFailure,\n err instanceof TypeError ? err.message : 'unable to decode request body',\n undefined,\n { cause: err },\n )\n }\n}\n\nexport async function asPipeThroughBuffer(\n input: HandlerPipeThroughStream,\n): Promise<HandlerPipeThroughBuffer> {\n return {\n buffer: await bufferUpstreamResponse(\n input.stream,\n input.headers?.['content-encoding'],\n ),\n headers: omit(input.headers, ['content-encoding', 'content-length']),\n encoding: input.encoding,\n }\n}\n\n// Response parsing/forwarding\n// -------------------\n\nconst RES_HEADERS_TO_FORWARD = [\n 'atproto-repo-rev',\n 'atproto-content-labelers',\n 'retry-after',\n]\n\nfunction* responseHeaders(\n headers: IncomingHttpHeaders,\n includeContentHeaders = true,\n): Generator<[string, string]> {\n if (includeContentHeaders) {\n const length = headers['content-length']\n if (length) yield ['content-length', length]\n\n const encoding = headers['content-encoding']\n if (encoding) yield ['content-encoding', encoding]\n\n const type = headers['content-type']\n if (type) yield ['content-type', type]\n\n const language = headers['content-language']\n if (language) yield ['content-language', language]\n }\n\n for (let i = 0; i < RES_HEADERS_TO_FORWARD.length; i++) {\n const name = RES_HEADERS_TO_FORWARD[i]\n const val = headers[name]\n\n if (val != null) {\n const value: string = Array.isArray(val) ? val.join(',') : val\n yield [name, value]\n }\n }\n}\n\n// Utils\n// -------------------\n\n/**\n * Performs lexicon method matching on a set of methods,\n * taking into account that they are treated case-insensitively.\n */\nexport class LxmSet {\n private inner: Set<string>\n private original: Iterable<string>\n constructor(items: Iterable<string>) {\n this.inner = new Set(Array.from(items, normalizeLxm))\n this.original = items\n }\n has(lxm: string) {\n return this.inner.has(normalizeLxm(lxm))\n }\n *[Symbol.iterator](): Iterator<string> {\n yield* this.original\n }\n}\n\nexport function normalizeLxm(lxm: string) {\n return lxm.toLowerCase()\n}\n\nexport const CHAT_BSKY_METHODS = new LxmSet([\n chat.bsky.actor.deleteAccount.$lxm,\n chat.bsky.actor.exportAccountData.$lxm,\n chat.bsky.convo.deleteMessageForSelf.$lxm,\n chat.bsky.convo.getConvo.$lxm,\n chat.bsky.convo.getConvoForMembers.$lxm,\n chat.bsky.convo.getLog.$lxm,\n chat.bsky.convo.getMessages.$lxm,\n chat.bsky.convo.leaveConvo.$lxm,\n chat.bsky.convo.listConvos.$lxm,\n chat.bsky.convo.muteConvo.$lxm,\n chat.bsky.convo.sendMessage.$lxm,\n chat.bsky.convo.sendMessageBatch.$lxm,\n chat.bsky.convo.unmuteConvo.$lxm,\n chat.bsky.convo.updateRead.$lxm,\n])\n\nexport const PRIVILEGED_METHODS = new LxmSet([\n ...CHAT_BSKY_METHODS,\n com.atproto.server.createAccount.$lxm,\n])\n\n// These endpoints are related to account management and must be used directly,\n// not proxied or service-authed. Service auth may be utilized between PDS and\n// entryway for these methods.\nexport const PROTECTED_METHODS = new LxmSet([\n com.atproto.admin.sendEmail.$lxm,\n com.atproto.identity.requestPlcOperationSignature.$lxm,\n com.atproto.identity.signPlcOperation.$lxm,\n com.atproto.identity.updateHandle.$lxm,\n com.atproto.server.activateAccount.$lxm,\n com.atproto.server.confirmEmail.$lxm,\n com.atproto.server.createAppPassword.$lxm,\n com.atproto.server.deactivateAccount.$lxm,\n com.atproto.server.getAccountInviteCodes.$lxm,\n com.atproto.server.getSession.$lxm,\n com.atproto.server.listAppPasswords.$lxm,\n com.atproto.server.requestAccountDelete.$lxm,\n com.atproto.server.requestEmailConfirmation.$lxm,\n com.atproto.server.requestEmailUpdate.$lxm,\n com.atproto.server.revokeAppPassword.$lxm,\n com.atproto.server.updateEmail.$lxm,\n])\n\nconst defaultService = (\n ctx: AppContext,\n nsid: string,\n): {\n serviceId: string\n serviceInfo: { url: string; did: string } | null\n} => {\n switch (nsid) {\n case tools.ozone.communication.createTemplate.$lxm:\n case tools.ozone.communication.deleteTemplate.$lxm:\n case tools.ozone.communication.listTemplates.$lxm:\n case tools.ozone.communication.updateTemplate.$lxm:\n case tools.ozone.moderation.cancelScheduledActions.$lxm:\n case tools.ozone.moderation.emitEvent.$lxm:\n case tools.ozone.moderation.getAccountTimeline.$lxm:\n case tools.ozone.moderation.getEvent.$lxm:\n case tools.ozone.moderation.getRecord.$lxm:\n case tools.ozone.moderation.getRepo.$lxm:\n case tools.ozone.moderation.listScheduledActions.$lxm:\n case tools.ozone.moderation.queryEvents.$lxm:\n case tools.ozone.moderation.queryStatuses.$lxm:\n case tools.ozone.moderation.scheduleAction.$lxm:\n case tools.ozone.moderation.searchRepos.$lxm:\n case tools.ozone.safelink.addRule.$lxm:\n case tools.ozone.safelink.queryEvents.$lxm:\n case tools.ozone.safelink.queryRules.$lxm:\n case tools.ozone.safelink.removeRule.$lxm:\n case tools.ozone.safelink.updateRule.$lxm:\n case tools.ozone.team.addMember.$lxm:\n case tools.ozone.team.deleteMember.$lxm:\n case tools.ozone.team.listMembers.$lxm:\n case tools.ozone.team.updateMember.$lxm:\n case tools.ozone.verification.grantVerifications.$lxm:\n case tools.ozone.verification.listVerifications.$lxm:\n case tools.ozone.verification.revokeVerifications.$lxm:\n return {\n serviceId: 'atproto_labeler',\n serviceInfo: ctx.cfg.modService,\n }\n case com.atproto.moderation.createReport.$lxm:\n return {\n serviceId: 'atproto_labeler',\n serviceInfo: ctx.cfg.reportService,\n }\n default:\n return {\n serviceId: 'bsky_appview',\n serviceInfo: ctx.cfg.bskyAppView,\n }\n }\n}\n\nconst safeString = (str: unknown): string | undefined => {\n return typeof str === 'string' ? str : undefined\n}\n\nfunction logResponseError(this: ServerResponse, err: unknown): void {\n httpLogger.warn({ err }, 'error forwarding upstream response')\n}\n\nexport class PipethroughUpstreamError extends XRPCServerError {\n constructor(\n readonly upstream: {\n statusCode: number\n headers: IncomingHttpHeaders\n },\n payload: { message?: string; error?: string },\n options?: ErrorOptions,\n ) {\n const status =\n upstream.statusCode === 500\n ? ResponseType.UpstreamFailure\n : upstream.statusCode\n\n super(status, payload.message, payload.error, options)\n }\n\n get headers(): Record<string, string> {\n return Object.fromEntries(responseHeaders(this.upstream.headers, false))\n }\n\n get error() {\n return this.customErrorName ?? this.typeName\n }\n}\n"]}
1
+ {"version":3,"file":"pipethrough.js","sourceRoot":"","sources":["../src/pipethrough.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAY,QAAQ,EAAE,MAAM,aAAa,CAAA;AAG7D,OAAO,EACL,YAAY,EACZ,kBAAkB,EAClB,IAAI,EACJ,kBAAkB,GACnB,MAAM,iBAAiB,CAAA;AAExB,OAAO,EAIL,mBAAmB,EACnB,mBAAmB,EACnB,YAAY,EACZ,SAAS,IAAI,eAAe,EAC5B,kBAAkB,EAClB,YAAY,GACb,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAA;AACtE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAA;AAEpD,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAA;AACtD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAExC,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,GAAe,EAAmB,EAAE;IAC/D,MAAM,WAAW,GAAG,GAAG,CAAC,YAAY,CAAC,aAAa,CAAqB;QACrE,SAAS,EAAE,CAAC,WAAW,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,WAAW,CAAC,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W,QAGR,EACD,OAA6C,EAC7C,OAAsB;QAEtB,MAAM,MAAM,GACV,QAAQ,CAAC,UAAU,KAAK,GAAG;YACzB,CAAC,CAAC,YAAY,CAAC,eAAe;YAC9B,CAAC,CAAC,QAAQ,CAAC,UAAU,CAAA;QAEzB,KAAK,CAAC,MAAM,EAAE,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,CAAA;QAZ7C,aAAQ,GAAR,QAAQ,CAGhB;IAUH,CAAC;IAED,IAAI,OAAO;QACT,OAAO,MAAM,CAAC,WAAW,CAAC,eAAe,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAA;IAC1E,CAAC;IAED,IAAI,KAAK;QACP,OAAO,IAAI,CAAC,eAAe,IAAI,IAAI,CAAC,QAAQ,CAAA;IAC9C,CAAC;CACF","sourcesContent":["import { IncomingHttpHeaders, ServerResponse } from 'node:http'\nimport { PassThrough, Readable, finished } from 'node:stream'\nimport { Request } from 'express'\nimport { Dispatcher } from 'undici'\nimport {\n decodeStream,\n getServiceEndpoint,\n omit,\n streamToNodeBuffer,\n} from '@atproto/common'\nimport { RpcPermissionMatch } from '@atproto/oauth-scopes'\nimport {\n CatchallHandler,\n HandlerPipeThroughBuffer,\n HandlerPipeThroughStream,\n InternalServerError,\n InvalidRequestError,\n ResponseType,\n XRPCError as XRPCServerError,\n excludeErrorResult,\n parseReqNsid,\n} from '@atproto/xrpc-server'\nimport { buildProxiedContentEncoding } from '@atproto-labs/xrpc-utils'\nimport { isAccessPrivileged } from './auth-scope.js'\nimport { AppContext } from './context.js'\nimport { chat, com, tools } from './lexicons/index.js'\nimport { httpLogger } from './logger.js'\n\nexport const proxyHandler = (ctx: AppContext): CatchallHandler => {\n const performAuth = ctx.authVerifier.authorization<RpcPermissionMatch>({\n authorize: (permissions, { params }) => permissions.assertRpc(params),\n })\n\n return async (req, res, next) => {\n // /!\\ Hot path\n try {\n if (\n req.method !== 'GET' &&\n req.method !== 'HEAD' &&\n req.method !== 'POST'\n ) {\n throw new XRPCServerError(\n ResponseType.InvalidRequest,\n 'XRPC requests only supports GET and POST',\n )\n }\n\n const body = req.method === 'POST' ? req : undefined\n if (body != null && !body.readable) {\n // Body was already consumed by a previous middleware\n throw new InternalServerError('Request body is not readable')\n }\n\n const lxm = parseReqNsid(req)\n if (PROTECTED_METHODS.has(lxm)) {\n throw new InvalidRequestError('Bad token method', 'InvalidToken')\n }\n\n const {\n url: origin,\n did,\n serviceId,\n } = await parseProxyInfo(ctx, req, lxm)\n // Phase 1 of service auth updates: the scope check sees the combined\n // did#serviceId form (so OAuth callers' rpc:?aud=did#service scopes\n // match), while the outbound service-auth JWT keeps bare-DID aud\n // regardless of session type.\n const scopeAud = `${did}#${serviceId}`\n const tokenAud = did\n\n const authResult = await performAuth({\n req,\n res,\n params: { lxm, aud: scopeAud },\n })\n\n const { credentials } = excludeErrorResult(authResult)\n\n if (\n credentials.type === 'access' &&\n !isAccessPrivileged(credentials.scope) &&\n PRIVILEGED_METHODS.has(lxm)\n ) {\n throw new InvalidRequestError('Bad token method', 'InvalidToken')\n }\n\n const headers: IncomingHttpHeaders = {\n 'accept-encoding': req.headers['accept-encoding'] || 'identity',\n 'accept-language': req.headers['accept-language'],\n 'atproto-accept-labelers': req.headers['atproto-accept-labelers'],\n 'x-bsky-topics': req.headers['x-bsky-topics'],\n\n 'content-type': body && req.headers['content-type'],\n 'content-encoding': body && req.headers['content-encoding'],\n 'content-length': body && req.headers['content-length'],\n\n authorization: `Bearer ${await ctx.serviceAuthJwt(credentials.did, tokenAud, lxm)}`,\n }\n\n const dispatchOptions: Dispatcher.RequestOptions = {\n origin,\n method: req.method,\n path: req.originalUrl,\n body,\n headers,\n }\n\n await pipethroughStream(ctx, req, dispatchOptions, (upstream) => {\n res.status(upstream.statusCode)\n\n for (const [name, val] of responseHeaders(upstream.headers)) {\n res.setHeader(name, val)\n }\n\n // Note that we should not need to manually handle errors here (e.g. by\n // destroying the response), as the http server will handle them for us.\n res.on('error', logResponseError)\n\n // Tell undici to write the upstream response directly to the response\n return res\n })\n } catch (err) {\n next(err)\n }\n }\n}\n\nexport type PipethroughOptions = {\n /**\n * Specify the issuer (requester) for service auth. If not provided, no\n * authorization headers will be added to the request.\n */\n iss?: string\n\n /**\n * Override the audience for service auth. If not provided, the audience will\n * be determined based on the proxy service.\n */\n aud?: string\n\n /**\n * Override the lexicon method for service auth. If not provided, the lexicon\n * method will be determined based on the request path.\n */\n lxm?: string\n}\n\nexport async function pipethrough(\n ctx: AppContext,\n req: Request,\n options?: PipethroughOptions,\n): Promise<\n HandlerPipeThroughStream & {\n stream: Readable\n headers: Record<string, string>\n encoding: string\n }\n> {\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n // pipethrough() is used from within xrpcServer handlers, which means that\n // the request body either has been parsed or is a readable stream that has\n // been piped for decoding & size limiting. Because of this, forwarding the\n // request body requires re-encoding it. Since we currently do not use\n // pipethrough() with procedures, proxying of request body is not\n // implemented.\n throw new InternalServerError(\n `Proxying of ${req.method} requests is not supported`,\n )\n }\n\n const lxm = parseReqNsid(req)\n\n const { url: origin, did: aud } = await parseProxyInfo(ctx, req, lxm)\n\n const dispatchOptions: Dispatcher.RequestOptions = {\n origin,\n method: req.method,\n path: req.originalUrl,\n headers: {\n 'accept-language': req.headers['accept-language'],\n 'atproto-accept-labelers': req.headers['atproto-accept-labelers'],\n 'x-bsky-topics': req.headers['x-bsky-topics'],\n\n // Because we sometimes need to interpret the response (e.g. during\n // read-after-write, through asPipeThroughBuffer()), we need to ask the\n // upstream server for an encoding that both the requester and the PDS can\n // understand. Since we might have to do the decoding ourselves, we will\n // use our own preferences (and weight) to negotiate the encoding.\n 'accept-encoding': buildProxiedContentEncoding(\n req.headers['accept-encoding'],\n ctx.cfg.proxy.preferCompressed,\n ),\n\n authorization: options?.iss\n ? `Bearer ${await ctx.serviceAuthJwt(options.iss, options.aud ?? aud, options.lxm ?? lxm)}`\n : undefined,\n },\n\n // Use a high water mark to buffer more data while performing async\n // operations before this stream is consumed. This is especially useful\n // while processing read-after-write operations.\n highWaterMark: 2 * 65536, // twice the default (64KiB)\n }\n\n const { headers, body } = await pipethroughRequest(ctx, req, dispatchOptions)\n\n return {\n encoding: safeString(headers['content-type']) ?? 'application/json',\n headers: Object.fromEntries(responseHeaders(headers)),\n stream: body,\n }\n}\n\n// Request setup/formatting\n// -------------------\n\nexport function computeProxyTo(\n ctx: AppContext,\n req: Request,\n lxm: string,\n): string {\n const proxyToHeader = req.header('atproto-proxy')\n if (proxyToHeader) return proxyToHeader\n\n const service = defaultService(ctx, lxm)\n if (service.serviceInfo) {\n return `${service.serviceInfo.did}#${service.serviceId}`\n }\n\n throw new InvalidRequestError(`No service configured for ${lxm}`)\n}\n\n// Bare-DID portion of `proxyTo`, suitable as a service-auth JWT audience\n// (Phase 1 of service auth updates).\nexport function bareDidFromProxyTo(proxyTo: string): string {\n const hashIndex = proxyTo.indexOf('#')\n return hashIndex === -1 ? proxyTo : proxyTo.slice(0, hashIndex)\n}\n\nexport async function parseProxyInfo(\n ctx: AppContext,\n req: Request,\n lxm: string,\n): Promise<{ url: string; did: string; serviceId: string }> {\n // /!\\ Hot path\n\n const proxyToHeader = req.header('atproto-proxy')\n if (proxyToHeader) return parseProxyHeader(ctx, proxyToHeader)\n\n const { serviceId, serviceInfo } = defaultService(ctx, lxm)\n if (serviceInfo) return { ...serviceInfo, serviceId }\n\n throw new InvalidRequestError(`No service configured for ${lxm}`)\n}\n\nexport const parseProxyHeader = async (\n // Using subset of AppContext for testing purposes\n ctx: Pick<AppContext, 'cfg' | 'idResolver'>,\n proxyTo: string,\n): Promise<{ did: string; url: string; serviceId: string }> => {\n // /!\\ Hot path\n\n const hashIndex = proxyTo.indexOf('#')\n\n if (hashIndex === 0) {\n throw new InvalidRequestError('no did specified in proxy header')\n }\n\n if (hashIndex === -1 || hashIndex === proxyTo.length - 1) {\n throw new InvalidRequestError('no service id specified in proxy header')\n }\n\n // More than one hash\n if (proxyTo.indexOf('#', hashIndex + 1) !== -1) {\n throw new InvalidRequestError('invalid proxy header format')\n }\n\n // Basic validation\n if (proxyTo.includes(' ')) {\n throw new InvalidRequestError('proxy header cannot contain spaces')\n }\n\n const did = proxyTo.slice(0, hashIndex)\n const serviceId = proxyTo.slice(hashIndex + 1)\n\n // Special case a configured appview, while still proxying correctly any other appview\n if (\n ctx.cfg.bskyAppView &&\n proxyTo === `${ctx.cfg.bskyAppView.did}#bsky_appview`\n ) {\n return { did, url: ctx.cfg.bskyAppView.url, serviceId }\n }\n\n const didDoc = await ctx.idResolver.did.resolve(did)\n if (!didDoc) {\n throw new InvalidRequestError('could not resolve proxy did')\n }\n\n const url = getServiceEndpoint(didDoc, { id: `#${serviceId}` })\n if (!url) {\n throw new InvalidRequestError('could not resolve proxy did service url')\n }\n\n return { did, url, serviceId }\n}\n\n/**\n * Utility function that wraps the undici stream() function and handles request\n * and response errors by wrapping them in XRPCError instances. This function is\n * more efficient than \"pipethroughRequest\" when a writable stream to pipe the\n * upstream response to is available.\n */\nasync function pipethroughStream(\n ctx: AppContext,\n req: Request,\n dispatchOptions: Dispatcher.RequestOptions,\n successStreamFactory: Dispatcher.StreamFactory,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n void ctx.proxyAgent\n .stream(dispatchOptions, (upstream) => {\n if (upstream.statusCode >= 400) {\n const passThrough = new PassThrough()\n\n void tryParsingError(upstream.headers, passThrough).then((parsed) => {\n const xrpcError = new PipethroughUpstreamError(upstream, parsed, {\n cause: dispatchOptions,\n })\n\n reject(xrpcError)\n }, reject)\n\n return passThrough\n }\n\n const writable = successStreamFactory(upstream)\n\n // As soon as the control was passed to the writable stream (i.e. by\n // returning the writable hereafter), pipethroughStream() is considered\n // to have succeeded. Any error occurring while writing upstream data to\n // the writable stream should be handled through the stream's error\n // state (i.e. successStreamFactory() must ensure that error events on\n // the returned writable will be handled).\n resolve()\n\n return writable\n })\n // The following catch block will be triggered with either network errors\n // or writable stream errors. In the latter case, the promise will already\n // be resolved, and reject()ing it there after will have no effect. Those\n // error would still be logged by the successStreamFactory() function.\n .catch(handleUpstreamRequestError.bind(req))\n .catch(reject)\n })\n}\n\n/**\n * Utility function that wraps the undici request() function and handles request\n * and response errors by wrapping them in XRPCError instances.\n */\nasync function pipethroughRequest(\n ctx: AppContext,\n req: Request,\n dispatchOptions: Dispatcher.RequestOptions,\n) {\n // HandlerPipeThroughStream requires a readable stream to be returned, so we\n // use the (less efficient) request() function instead.\n\n const upstream = await ctx.proxyAgent\n .request(dispatchOptions)\n .catch(handleUpstreamRequestError.bind(req))\n\n if (upstream.statusCode >= 400) {\n const parsed = await tryParsingError(upstream.headers, upstream.body)\n\n throw new PipethroughUpstreamError(upstream, parsed, {\n cause: dispatchOptions,\n })\n }\n\n return upstream\n}\n\nfunction handleUpstreamRequestError(\n this: Request,\n err: unknown,\n message = 'Upstream service unreachable',\n): never {\n const logger = isPinoHttpRequest(this) ? this.log : httpLogger\n logger.error({ err }, message)\n throw new XRPCServerError(ResponseType.UpstreamFailure, message, undefined, {\n cause: err,\n })\n}\n\nfunction isPinoHttpRequest(req: Request): req is Request & {\n log: { error: (obj: unknown, msg: string) => void }\n} {\n return typeof (req as { log?: any }).log?.error === 'function'\n}\n\n// Request parsing/forwarding\n// -------------------\n\nexport function isJsonContentType(contentType?: string): boolean | undefined {\n if (!contentType) return undefined\n return /application\\/(?:\\w+\\+)?json/i.test(contentType)\n}\n\nasync function tryParsingError(\n headers: IncomingHttpHeaders,\n readable: Readable,\n): Promise<{ error?: string; message?: string }> {\n if (isJsonContentType(headers['content-type']) === false) {\n // We don't known how to parse non JSON content types so we can discard the\n // whole response.\n\n // Since we don't care about the response, we would normally just destroy\n // the stream. However, if the underlying HTTP connection is an HTTP/1.1\n // connection, this also destroys the underlying (keep-alive) TCP socket. In\n // order to avoid destroying the TCP socket, while avoiding the cost of\n // consuming too much IO, we give it a chance to finish first.\n\n // @NOTE we need to listen (and ignore) \"error\" events, otherwise the\n // process could crash (since we drain the stream asynchronously here). This\n // is performed through the \"finished\" call below.\n\n const to = setTimeout(() => {\n readable.destroy()\n }, 100)\n finished(readable, (_err) => {\n clearTimeout(to)\n })\n readable.resume()\n\n return {}\n }\n\n try {\n const buffer = await bufferUpstreamResponse(\n readable,\n headers['content-encoding'],\n )\n\n const errInfo: unknown = JSON.parse(buffer.toString('utf8'))\n return {\n error: safeString(errInfo?.['error']),\n message: safeString(errInfo?.['message']),\n }\n } catch (err) {\n // Failed to read, decode, buffer or parse. No big deal.\n return {}\n }\n}\n\nasync function bufferUpstreamResponse(\n readable: Readable,\n contentEncoding?: string | string[],\n): Promise<Buffer> {\n try {\n return await streamToNodeBuffer(decodeStream(readable, contentEncoding))\n } catch (err) {\n if (!readable.destroyed) readable.destroy()\n\n throw new XRPCServerError(\n ResponseType.UpstreamFailure,\n err instanceof TypeError ? err.message : 'unable to decode request body',\n undefined,\n { cause: err },\n )\n }\n}\n\nexport async function asPipeThroughBuffer(\n input: HandlerPipeThroughStream,\n): Promise<HandlerPipeThroughBuffer> {\n return {\n buffer: await bufferUpstreamResponse(\n input.stream,\n input.headers?.['content-encoding'],\n ),\n headers: omit(input.headers, ['content-encoding', 'content-length']),\n encoding: input.encoding,\n }\n}\n\n// Response parsing/forwarding\n// -------------------\n\nconst RES_HEADERS_TO_FORWARD = [\n 'atproto-repo-rev',\n 'atproto-content-labelers',\n 'retry-after',\n]\n\nfunction* responseHeaders(\n headers: IncomingHttpHeaders,\n includeContentHeaders = true,\n): Generator<[string, string]> {\n if (includeContentHeaders) {\n const length = headers['content-length']\n if (length) yield ['content-length', length]\n\n const encoding = headers['content-encoding']\n if (encoding) yield ['content-encoding', encoding]\n\n const type = headers['content-type']\n if (type) yield ['content-type', type]\n\n const language = headers['content-language']\n if (language) yield ['content-language', language]\n }\n\n for (let i = 0; i < RES_HEADERS_TO_FORWARD.length; i++) {\n const name = RES_HEADERS_TO_FORWARD[i]\n const val = headers[name]\n\n if (val != null) {\n const value: string = Array.isArray(val) ? val.join(',') : val\n yield [name, value]\n }\n }\n}\n\n// Utils\n// -------------------\n\n/**\n * Performs lexicon method matching on a set of methods,\n * taking into account that they are treated case-insensitively.\n */\nexport class LxmSet {\n private inner: Set<string>\n private original: Iterable<string>\n constructor(items: Iterable<string>) {\n this.inner = new Set(Array.from(items, normalizeLxm))\n this.original = items\n }\n has(lxm: string) {\n return this.inner.has(normalizeLxm(lxm))\n }\n *[Symbol.iterator](): Iterator<string> {\n yield* this.original\n }\n}\n\nexport function normalizeLxm(lxm: string) {\n return lxm.toLowerCase()\n}\n\nexport const CHAT_BSKY_METHODS = new LxmSet([\n chat.bsky.actor.deleteAccount.$lxm,\n chat.bsky.actor.exportAccountData.$lxm,\n chat.bsky.convo.deleteMessageForSelf.$lxm,\n chat.bsky.convo.getConvo.$lxm,\n chat.bsky.convo.getConvoForMembers.$lxm,\n chat.bsky.convo.getLog.$lxm,\n chat.bsky.convo.getMessages.$lxm,\n chat.bsky.convo.leaveConvo.$lxm,\n chat.bsky.convo.listConvos.$lxm,\n chat.bsky.convo.muteConvo.$lxm,\n chat.bsky.convo.sendMessage.$lxm,\n chat.bsky.convo.sendMessageBatch.$lxm,\n chat.bsky.convo.unmuteConvo.$lxm,\n chat.bsky.convo.updateRead.$lxm,\n])\n\nexport const PRIVILEGED_METHODS = new LxmSet([\n ...CHAT_BSKY_METHODS,\n com.atproto.server.createAccount.$lxm,\n])\n\n// These endpoints are related to account management and must be used directly,\n// not proxied or service-authed. Service auth may be utilized between PDS and\n// entryway for these methods.\nexport const PROTECTED_METHODS = new LxmSet([\n com.atproto.admin.sendEmail.$lxm,\n com.atproto.identity.requestPlcOperationSignature.$lxm,\n com.atproto.identity.signPlcOperation.$lxm,\n com.atproto.identity.updateHandle.$lxm,\n com.atproto.server.activateAccount.$lxm,\n com.atproto.server.confirmEmail.$lxm,\n com.atproto.server.createAppPassword.$lxm,\n com.atproto.server.deactivateAccount.$lxm,\n com.atproto.server.getAccountInviteCodes.$lxm,\n com.atproto.server.getSession.$lxm,\n com.atproto.server.listAppPasswords.$lxm,\n com.atproto.server.requestAccountDelete.$lxm,\n com.atproto.server.requestEmailConfirmation.$lxm,\n com.atproto.server.requestEmailUpdate.$lxm,\n com.atproto.server.revokeAppPassword.$lxm,\n com.atproto.server.updateEmail.$lxm,\n])\n\nconst defaultService = (\n ctx: AppContext,\n nsid: string,\n): {\n serviceId: string\n serviceInfo: { url: string; did: string } | null\n} => {\n switch (nsid) {\n case tools.ozone.communication.createTemplate.$lxm:\n case tools.ozone.communication.deleteTemplate.$lxm:\n case tools.ozone.communication.listTemplates.$lxm:\n case tools.ozone.communication.updateTemplate.$lxm:\n case tools.ozone.moderation.cancelScheduledActions.$lxm:\n case tools.ozone.moderation.emitEvent.$lxm:\n case tools.ozone.moderation.getAccountTimeline.$lxm:\n case tools.ozone.moderation.getEvent.$lxm:\n case tools.ozone.moderation.getRecord.$lxm:\n case tools.ozone.moderation.getRepo.$lxm:\n case tools.ozone.moderation.listScheduledActions.$lxm:\n case tools.ozone.moderation.queryEvents.$lxm:\n case tools.ozone.moderation.queryStatuses.$lxm:\n case tools.ozone.moderation.scheduleAction.$lxm:\n case tools.ozone.moderation.searchRepos.$lxm:\n case tools.ozone.safelink.addRule.$lxm:\n case tools.ozone.safelink.queryEvents.$lxm:\n case tools.ozone.safelink.queryRules.$lxm:\n case tools.ozone.safelink.removeRule.$lxm:\n case tools.ozone.safelink.updateRule.$lxm:\n case tools.ozone.team.addMember.$lxm:\n case tools.ozone.team.deleteMember.$lxm:\n case tools.ozone.team.listMembers.$lxm:\n case tools.ozone.team.updateMember.$lxm:\n case tools.ozone.verification.grantVerifications.$lxm:\n case tools.ozone.verification.listVerifications.$lxm:\n case tools.ozone.verification.revokeVerifications.$lxm:\n return {\n serviceId: 'atproto_labeler',\n serviceInfo: ctx.cfg.modService,\n }\n case com.atproto.moderation.createReport.$lxm:\n return {\n serviceId: 'atproto_labeler',\n serviceInfo: ctx.cfg.reportService,\n }\n default:\n return {\n serviceId: 'bsky_appview',\n serviceInfo: ctx.cfg.bskyAppView,\n }\n }\n}\n\nconst safeString = (str: unknown): string | undefined => {\n return typeof str === 'string' ? str : undefined\n}\n\nfunction logResponseError(this: ServerResponse, err: unknown): void {\n httpLogger.warn({ err }, 'error forwarding upstream response')\n}\n\nexport class PipethroughUpstreamError extends XRPCServerError {\n constructor(\n readonly upstream: {\n statusCode: number\n headers: IncomingHttpHeaders\n },\n payload: { message?: string; error?: string },\n options?: ErrorOptions,\n ) {\n const status =\n upstream.statusCode === 500\n ? ResponseType.UpstreamFailure\n : upstream.statusCode\n\n super(status, payload.message, payload.error, options)\n }\n\n get headers(): Record<string, string> {\n return Object.fromEntries(responseHeaders(this.upstream.headers, false))\n }\n\n get error() {\n return this.customErrorName ?? this.typeName\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atproto/pds",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "license": "MIT",
5
5
  "description": "Reference implementation of atproto Personal Data Server (PDS)",
6
6
  "keywords": [
@@ -50,17 +50,18 @@
50
50
  "@atproto/aws": "^0.3.0",
51
51
  "@atproto/common": "^0.6.1",
52
52
  "@atproto/crypto": "^0.5.0",
53
+ "@atproto/did": "^0.5.0",
54
+ "@atproto/lex": "^0.1.3",
53
55
  "@atproto/identity": "^0.5.0",
54
- "@atproto/lex": "^0.1.2",
55
56
  "@atproto/lex-cbor": "^0.1.0",
56
57
  "@atproto/lex-data": "^0.1.1",
58
+ "@atproto/oauth-provider": "^0.18.1",
57
59
  "@atproto/lex-json": "^0.1.0",
58
- "@atproto/oauth-provider": "^0.18.0",
59
- "@atproto/oauth-scopes": "^0.4.0",
60
60
  "@atproto/repo": "^0.10.0",
61
- "@atproto/syntax": "^0.6.1",
61
+ "@atproto/xrpc-server": "^0.11.1",
62
62
  "@atproto/xrpc": "^0.8.0",
63
- "@atproto/xrpc-server": "^0.11.1"
63
+ "@atproto/oauth-scopes": "^0.5.0",
64
+ "@atproto/syntax": "^0.6.1"
64
65
  },
65
66
  "devDependencies": {
66
67
  "@did-plc/server": "^0.0.1",
@@ -78,10 +79,10 @@
78
79
  "ts-node": "^10.8.2",
79
80
  "typescript": "^6.0.3",
80
81
  "ws": "^8.12.0",
81
- "@atproto/api": "^0.20.5",
82
- "@atproto/bsky": "^0.0.234",
83
- "@atproto/lex-document": "^0.1.0",
84
- "@atproto/oauth-client-browser-example": "^0.1.1"
82
+ "@atproto/api": "^0.20.6",
83
+ "@atproto/bsky": "^0.0.235",
84
+ "@atproto/oauth-client-browser-example": "^0.1.1",
85
+ "@atproto/lex-document": "^0.1.0"
85
86
  },
86
87
  "type": "module",
87
88
  "exports": {
@@ -2,7 +2,11 @@ import { Server } from '@atproto/xrpc-server'
2
2
  import { AuthScope, isAccessFull } from '../../../../auth-scope.js'
3
3
  import { AppContext } from '../../../../context.js'
4
4
  import { app } from '../../../../lexicons/index.js'
5
- import { computeProxyTo, pipethrough } from '../../../../pipethrough.js'
5
+ import {
6
+ bareDidFromProxyTo,
7
+ computeProxyTo,
8
+ pipethrough,
9
+ } from '../../../../pipethrough.js'
6
10
 
7
11
  export default function (server: Server, ctx: AppContext) {
8
12
  const { bskyAppView } = ctx
@@ -26,7 +30,12 @@ export default function (server: Server, ctx: AppContext) {
26
30
  const lxm = app.bsky.actor.getPreferences.$lxm
27
31
  const aud = computeProxyTo(ctx, req, lxm)
28
32
  if (aud !== `${bskyAppView.did}#bsky_appview`) {
29
- return pipethrough(ctx, req, { iss: did, aud, lxm })
33
+ // Phase 1 of service auth updates: outbound JWT keeps bare-DID aud.
34
+ return pipethrough(ctx, req, {
35
+ iss: did,
36
+ aud: bareDidFromProxyTo(aud),
37
+ lxm,
38
+ })
30
39
  }
31
40
 
32
41
  const hasAccessFull =
@@ -3,7 +3,11 @@ import { AccountPreference } from '../../../../actor-store/preference/reader.js'
3
3
  import { isAccessFull } from '../../../../auth-scope.js'
4
4
  import { AppContext } from '../../../../context.js'
5
5
  import { app } from '../../../../lexicons/index.js'
6
- import { computeProxyTo, pipethrough } from '../../../../pipethrough.js'
6
+ import {
7
+ bareDidFromProxyTo,
8
+ computeProxyTo,
9
+ pipethrough,
10
+ } from '../../../../pipethrough.js'
7
11
 
8
12
  export default function (server: Server, ctx: AppContext) {
9
13
  const { bskyAppView } = ctx
@@ -27,7 +31,12 @@ export default function (server: Server, ctx: AppContext) {
27
31
  const lxm = app.bsky.actor.putPreferences.$lxm
28
32
  const aud = computeProxyTo(ctx, req, lxm)
29
33
  if (aud !== `${bskyAppView.did}#bsky_appview`) {
30
- return pipethrough(ctx, req, { iss: did, aud, lxm })
34
+ // Phase 1 of service auth updates: outbound JWT keeps bare-DID aud.
35
+ return pipethrough(ctx, req, {
36
+ iss: did,
37
+ aud: bareDidFromProxyTo(aud),
38
+ lxm,
39
+ })
31
40
  }
32
41
 
33
42
  const checkedPreferences: AccountPreference[] = []
@@ -1,4 +1,5 @@
1
1
  import { HOUR, MINUTE } from '@atproto/common'
2
+ import { isAtprotoDid, isAtprotoDidRefAbsolute } from '@atproto/did'
2
3
  import { l } from '@atproto/lex'
3
4
  import {
4
5
  InvalidRequestError,
@@ -34,6 +35,12 @@ export default function (server: Server, ctx: AppContext) {
34
35
  // @NOTE "exp" is expressed in seconds since epoch, not milliseconds
35
36
  const { aud, exp, lxm = null } = params
36
37
 
38
+ if (!isAtprotoDid(aud) && !isAtprotoDidRefAbsolute(aud)) {
39
+ throw new InvalidRequestError(
40
+ 'aud must be a valid atproto DID or did#serviceId reference',
41
+ )
42
+ }
43
+
37
44
  // Takendown accounts should not be able to generate service auth tokens except for methods necessary for account migration
38
45
  if (auth.credentials.type === 'access') {
39
46
  // @NOTE We should probably use "ForbiddenError" here. Using
@@ -1,10 +1,15 @@
1
1
  import assert from 'node:assert'
2
2
  import path from 'node:path'
3
3
  import { DAY, HOUR, SECOND } from '@atproto/common'
4
- import { BrandingInput, HcaptchaConfig } from '@atproto/oauth-provider'
4
+ import {
5
+ BrandingInput as BrandingConfig,
6
+ HcaptchaConfig,
7
+ } from '@atproto/oauth-provider'
5
8
  import { ensureValidDid } from '@atproto/syntax'
6
9
  import { ServerEnvironment } from './env.js'
7
10
 
11
+ export type { BrandingConfig }
12
+
8
13
  // off-config but still from env:
9
14
  // logging: LOG_LEVEL, LOG_SYSTEMS, LOG_ENABLED, LOG_DESTINATION
10
15
 
@@ -152,6 +157,7 @@ export const envToCfg = (env: ServerEnvironment): ServerConfig => {
152
157
  emailCfg = {
153
158
  smtpUrl: env.emailSmtpUrl,
154
159
  fromAddress: env.emailFromAddress,
160
+ disableConfirmationLink: env.emailDisableConfirmationLink ?? false,
155
161
  }
156
162
  }
157
163
 
@@ -167,6 +173,7 @@ export const envToCfg = (env: ServerEnvironment): ServerConfig => {
167
173
  moderationEmailCfg = {
168
174
  smtpUrl: env.moderationEmailSmtpUrl,
169
175
  fromAddress: env.moderationEmailAddress,
176
+ disableConfirmationLink: false,
170
177
  }
171
178
  }
172
179
 
@@ -254,6 +261,62 @@ export const envToCfg = (env: ServerEnvironment): ServerConfig => {
254
261
  preferCompressed: env.proxyPreferCompressed ?? false,
255
262
  }
256
263
 
264
+ const brandingCfg = {
265
+ name: env.serviceName ?? `${hostname} PDS`,
266
+ logo: env.logoUrl,
267
+ colors: {
268
+ light: env.lightColor,
269
+ dark: env.darkColor,
270
+
271
+ contrastSaturation: env.contrastSaturation,
272
+
273
+ primary: env.primaryColor,
274
+ primaryContrast: env.primaryColorContrast,
275
+ primaryHue: env.primaryColorHue,
276
+
277
+ error: env.errorColor,
278
+ errorContrast: env.errorColorContrast,
279
+ errorHue: env.errorColorHue,
280
+
281
+ warning: env.warningColor,
282
+ warningContrast: env.warningColorContrast,
283
+ warningHue: env.warningColorHue,
284
+
285
+ info: env.infoColor,
286
+ infoContrast: env.infoColorContrast,
287
+ infoHue: env.infoColorHue,
288
+
289
+ success: env.successColor,
290
+ successContrast: env.successColorContrast,
291
+ successHue: env.successColorHue,
292
+ },
293
+ links: [
294
+ {
295
+ title: { en: 'Home', fr: 'Accueil' },
296
+ href: env.homeUrl,
297
+ rel: 'canonical' as const, // Prevents login page from being indexed
298
+ },
299
+ {
300
+ title: { en: 'Terms of Service' },
301
+ href: env.termsOfServiceUrl,
302
+ rel: 'terms-of-service' as const,
303
+ },
304
+ {
305
+ title: { en: 'Privacy Policy' },
306
+ href: env.privacyPolicyUrl,
307
+ rel: 'privacy-policy' as const,
308
+ },
309
+ {
310
+ title: { en: 'Support' },
311
+ href: env.supportUrl,
312
+ rel: 'help' as const,
313
+ },
314
+ ].filter(
315
+ <T extends { href?: string }>(f: T): f is T & { href: string } =>
316
+ f.href != null && f.href !== '',
317
+ ),
318
+ }
319
+
257
320
  const oauthCfg: ServerConfig['oauth'] = entrywayCfg
258
321
  ? {
259
322
  issuer: entrywayCfg.url,
@@ -272,61 +335,7 @@ export const envToCfg = (env: ServerEnvironment): ServerConfig => {
272
335
  tokenSalt: env.hcaptchaTokenSalt,
273
336
  }
274
337
  : undefined,
275
- branding: {
276
- name: env.serviceName ?? `${hostname} PDS`,
277
- logo: env.logoUrl,
278
- colors: {
279
- light: env.lightColor,
280
- dark: env.darkColor,
281
-
282
- contrastSaturation: env.contrastSaturation,
283
-
284
- primary: env.primaryColor,
285
- primaryContrast: env.primaryColorContrast,
286
- primaryHue: env.primaryColorHue,
287
-
288
- error: env.errorColor,
289
- errorContrast: env.errorColorContrast,
290
- errorHue: env.errorColorHue,
291
-
292
- warning: env.warningColor,
293
- warningContrast: env.warningColorContrast,
294
- warningHue: env.warningColorHue,
295
-
296
- info: env.infoColor,
297
- infoContrast: env.infoColorContrast,
298
- infoHue: env.infoColorHue,
299
-
300
- success: env.successColor,
301
- successContrast: env.successColorContrast,
302
- successHue: env.successColorHue,
303
- },
304
- links: [
305
- {
306
- title: { en: 'Home', fr: 'Accueil' },
307
- href: env.homeUrl,
308
- rel: 'canonical' as const, // Prevents login page from being indexed
309
- },
310
- {
311
- title: { en: 'Terms of Service' },
312
- href: env.termsOfServiceUrl,
313
- rel: 'terms-of-service' as const,
314
- },
315
- {
316
- title: { en: 'Privacy Policy' },
317
- href: env.privacyPolicyUrl,
318
- rel: 'privacy-policy' as const,
319
- },
320
- {
321
- title: { en: 'Support' },
322
- href: env.supportUrl,
323
- rel: 'help' as const,
324
- },
325
- ].filter(
326
- <T extends { href?: string }>(f: T): f is T & { href: string } =>
327
- f.href != null && f.href !== '',
328
- ),
329
- },
338
+ branding: brandingCfg,
330
339
  trustedClients: env.trustedOAuthClients,
331
340
  },
332
341
  }
@@ -358,6 +367,7 @@ export const envToCfg = (env: ServerEnvironment): ServerConfig => {
358
367
  fetch: fetchCfg,
359
368
  lexicon: lexiconCfg,
360
369
  proxy: proxyCfg,
370
+ branding: brandingCfg,
361
371
  oauth: oauthCfg,
362
372
  }
363
373
  }
@@ -381,6 +391,7 @@ export type ServerConfig = {
381
391
  crawlers: string[]
382
392
  fetch: FetchConfig
383
393
  proxy: ProxyConfig
394
+ branding: BrandingConfig
384
395
  oauth: OAuthConfig
385
396
  lexicon: LexiconResolverConfig
386
397
  }
@@ -477,7 +488,7 @@ export type OAuthConfig = {
477
488
  issuer: string
478
489
  provider?: {
479
490
  hcaptcha?: HcaptchaConfig
480
- branding: BrandingInput
491
+ branding: BrandingConfig
481
492
  trustedClients?: string[]
482
493
  }
483
494
  }
@@ -499,6 +510,7 @@ export type InvitesConfig =
499
510
  export type EmailConfig = {
500
511
  smtpUrl: string
501
512
  fromAddress: string
513
+ disableConfirmationLink: boolean
502
514
  }
503
515
 
504
516
  export type SubscriptionConfig = {
package/src/config/env.ts CHANGED
@@ -97,6 +97,9 @@ export function readEnv() {
97
97
  // email
98
98
  emailSmtpUrl: envStr('PDS_EMAIL_SMTP_URL'),
99
99
  emailFromAddress: envStr('PDS_EMAIL_FROM_ADDRESS'),
100
+ emailDisableConfirmationLink: envBool(
101
+ 'PDS_EMAIL_DISABLE_CONFIRMATION_LINK',
102
+ ),
100
103
  moderationEmailSmtpUrl: envStr('PDS_MODERATION_EMAIL_SMTP_URL'),
101
104
  moderationEmailAddress: envStr('PDS_MODERATION_EMAIL_ADDRESS'),
102
105
 
package/src/context.ts CHANGED
@@ -156,7 +156,7 @@ export class AppContext {
156
156
  ? nodemailer.createTransport(cfg.email.smtpUrl)
157
157
  : nodemailer.createTransport({ jsonTransport: true })
158
158
 
159
- const mailer = new ServerMailer(mailTransport, cfg)
159
+ const mailer = new ServerMailer(mailTransport, cfg.email, cfg.branding)
160
160
 
161
161
  const modMailTransport =
162
162
  cfg.moderationEmail !== null
@@ -1,22 +1,38 @@
1
1
  import { SendMailOptions, Transporter } from 'nodemailer'
2
2
  import { htmlToText } from 'nodemailer-html-to-text'
3
- import { ServerConfig } from '../config/index.js'
3
+ import { BrandingConfig, EmailConfig } from '../config/index.js'
4
4
  import { mailerLogger } from '../logger.js'
5
5
  import * as templates from './templates.js'
6
6
 
7
7
  // @TODO Add support for i18n
8
8
 
9
+ const DEFAULT_LOGO_URL =
10
+ 'https://bsky.social/about/images/email/email_logo_default.png'
11
+ const DEFAULT_MARK_URL =
12
+ 'https://bsky.social/about/images/email/email_mark_dark.png'
13
+ const DEFAULT_HOME_URL = 'https://bsky.app'
14
+ const DEFAULT_PRIMARY_COLOR = '#067df7'
15
+
9
16
  export class ServerMailer {
17
+ private readonly config: templates.Config
18
+
10
19
  constructor(
11
20
  public readonly transporter: Transporter,
12
- private readonly config: ServerConfig,
21
+ private readonly email: EmailConfig | null,
22
+ branding: BrandingConfig,
13
23
  ) {
14
24
  transporter.use('compile', htmlToText())
15
- }
16
25
 
17
- // The returned config can be used inside email templates.
18
- static getEmailConfig(_config: ServerConfig) {
19
- return {}
26
+ this.config = {
27
+ serviceName: branding.name ?? 'Bluesky',
28
+ homeUrl:
29
+ branding.links?.find((link) => link.rel === 'canonical')?.href ??
30
+ DEFAULT_HOME_URL,
31
+ logoUrl: branding.logo ?? DEFAULT_LOGO_URL,
32
+ markUrl: branding.logo ?? DEFAULT_MARK_URL,
33
+ primaryColor: branding.colors?.primary ?? DEFAULT_PRIMARY_COLOR,
34
+ showBskyAppEmailConfirmationLink: email?.disableConfirmationLink !== true,
35
+ }
20
36
  }
21
37
 
22
38
  async sendResetPassword(
@@ -75,14 +91,14 @@ export class ServerMailer {
75
91
  ) {
76
92
  const html = templates[templateName]({
77
93
  ...params,
78
- config: ServerMailer.getEmailConfig(this.config),
94
+ config: this.config,
79
95
  } as any)
80
96
  const res = await this.transporter.sendMail({
81
97
  ...mailOpts,
82
- from: mailOpts.from ?? this.config.email?.fromAddress,
98
+ from: mailOpts.from ?? this.email?.fromAddress,
83
99
  html,
84
100
  })
85
- if (!this.config.email?.smtpUrl) {
101
+ if (!this.email?.smtpUrl) {
86
102
  mailerLogger.debug(
87
103
  'No SMTP URL has been configured. Intended to send email:\n' +
88
104
  JSON.stringify(res, null, 2),