@atproto/pds 0.5.6 → 0.5.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/dist/background.d.ts +12 -6
- package/dist/background.d.ts.map +1 -1
- package/dist/background.js +32 -13
- package/dist/background.js.map +1 -1
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js +4 -31
- package/dist/context.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +33 -11
- package/dist/index.js.map +1 -1
- package/dist/lexicons/app/bsky/notification/defs.defs.d.ts +5 -0
- package/dist/lexicons/app/bsky/notification/defs.defs.d.ts.map +1 -1
- package/dist/lexicons/app/bsky/notification/defs.defs.js +1 -0
- package/dist/lexicons/app/bsky/notification/defs.defs.js.map +1 -1
- package/dist/lexicons/chat/bsky/notification/defs.d.ts +2 -0
- package/dist/lexicons/chat/bsky/notification/defs.d.ts.map +1 -0
- package/dist/lexicons/chat/bsky/notification/defs.defs.d.ts +20 -0
- package/dist/lexicons/chat/bsky/notification/defs.defs.d.ts.map +1 -0
- package/dist/lexicons/chat/bsky/notification/defs.defs.js +19 -0
- package/dist/lexicons/chat/bsky/notification/defs.defs.js.map +1 -0
- package/dist/lexicons/chat/bsky/notification/defs.js +5 -0
- package/dist/lexicons/chat/bsky/notification/defs.js.map +1 -0
- package/dist/lexicons/chat/bsky/notification/getPreferences.d.ts +3 -0
- package/dist/lexicons/chat/bsky/notification/getPreferences.d.ts.map +1 -0
- package/dist/lexicons/chat/bsky/notification/getPreferences.defs.d.ts +18 -0
- package/dist/lexicons/chat/bsky/notification/getPreferences.defs.d.ts.map +1 -0
- package/dist/lexicons/chat/bsky/notification/getPreferences.defs.js +16 -0
- package/dist/lexicons/chat/bsky/notification/getPreferences.defs.js.map +1 -0
- package/dist/lexicons/chat/bsky/notification/getPreferences.js +6 -0
- package/dist/lexicons/chat/bsky/notification/getPreferences.js.map +1 -0
- package/dist/lexicons/chat/bsky/notification/putPreferences.d.ts +3 -0
- package/dist/lexicons/chat/bsky/notification/putPreferences.d.ts.map +1 -0
- package/dist/lexicons/chat/bsky/notification/putPreferences.defs.d.ts +27 -0
- package/dist/lexicons/chat/bsky/notification/putPreferences.defs.d.ts.map +1 -0
- package/dist/lexicons/chat/bsky/notification/putPreferences.defs.js +22 -0
- package/dist/lexicons/chat/bsky/notification/putPreferences.defs.js.map +1 -0
- package/dist/lexicons/chat/bsky/notification/putPreferences.js +6 -0
- package/dist/lexicons/chat/bsky/notification/putPreferences.js.map +1 -0
- package/dist/lexicons/chat/bsky/notification.d.ts +4 -0
- package/dist/lexicons/chat/bsky/notification.d.ts.map +1 -0
- package/dist/lexicons/chat/bsky/notification.js +7 -0
- package/dist/lexicons/chat/bsky/notification.js.map +1 -0
- package/dist/lexicons/chat/bsky.d.ts +1 -0
- package/dist/lexicons/chat/bsky.d.ts.map +1 -1
- package/dist/lexicons/chat/bsky.js +1 -0
- package/dist/lexicons/chat/bsky.js.map +1 -1
- package/dist/lexicons/tools/ozone/report/defs.defs.d.ts +4 -0
- package/dist/lexicons/tools/ozone/report/defs.defs.d.ts.map +1 -1
- package/dist/lexicons/tools/ozone/report/defs.defs.js +2 -0
- package/dist/lexicons/tools/ozone/report/defs.defs.js.map +1 -1
- package/dist/lexicons/tools/ozone/report/queryActivities.d.ts +3 -0
- package/dist/lexicons/tools/ozone/report/queryActivities.d.ts.map +1 -0
- package/dist/lexicons/tools/ozone/report/queryActivities.defs.d.ts +42 -0
- package/dist/lexicons/tools/ozone/report/queryActivities.defs.d.ts.map +1 -0
- package/dist/lexicons/tools/ozone/report/queryActivities.defs.js +31 -0
- package/dist/lexicons/tools/ozone/report/queryActivities.defs.js.map +1 -0
- package/dist/lexicons/tools/ozone/report/queryActivities.js +6 -0
- package/dist/lexicons/tools/ozone/report/queryActivities.js.map +1 -0
- package/dist/lexicons/tools/ozone/report.d.ts +1 -0
- package/dist/lexicons/tools/ozone/report.d.ts.map +1 -1
- package/dist/lexicons/tools/ozone/report.js +1 -0
- package/dist/lexicons/tools/ozone/report.js.map +1 -1
- package/dist/pipethrough.d.ts +3 -0
- package/dist/pipethrough.d.ts.map +1 -1
- package/dist/pipethrough.js +32 -0
- package/dist/pipethrough.js.map +1 -1
- package/package.json +11 -11
- package/src/background.ts +49 -18
- package/src/context.ts +4 -37
- package/src/index.ts +31 -13
- package/src/pipethrough.ts +38 -1
- package/tests/_util.ts +8 -25
- package/tests/account-deactivation.test.ts +1 -1
- package/tests/account-deletion.test.ts +1 -1
- package/tests/account-migration.test.ts +2 -2
- package/tests/account-status.test.ts +1 -1
- package/tests/account.test.ts +1 -1
- package/tests/app-passwords.test.ts +1 -1
- package/tests/auth.test.ts +1 -1
- package/tests/blob-deletes.test.ts +1 -1
- package/tests/create-post.test.ts +1 -1
- package/tests/crud.test.ts +1 -1
- package/tests/db.test.ts +1 -1
- package/tests/email-confirmation.test.ts +1 -1
- package/tests/file-uploads.test.ts +2 -2
- package/tests/get-service-auth.test.ts +1 -1
- package/tests/handles.test.ts +1 -1
- package/tests/invite-codes.test.ts +1 -1
- package/tests/invites-admin.test.ts +1 -1
- package/tests/moderation.test.ts +1 -1
- package/tests/moderator-auth.test.ts +1 -1
- package/tests/plc-operations.test.ts +1 -1
- package/tests/preferences.test.ts +1 -1
- package/tests/proxied/admin.test.ts +1 -1
- package/tests/proxied/feedgen.test.ts +1 -1
- package/tests/proxied/notif.test.ts +6 -13
- package/tests/proxied/procedures.test.ts +1 -1
- package/tests/proxied/proxy-catchall.test.ts +9 -8
- package/tests/proxied/proxy-header.test.ts +12 -8
- package/tests/proxied/proxy-oauth-aud.test.ts +17 -10
- package/tests/proxied/read-after-write.test.ts +4 -5
- package/tests/proxied/views.test.ts +1 -1
- package/tests/races.test.ts +1 -1
- package/tests/rate-limits.test.ts +1 -1
- package/tests/recovery.test.ts +1 -1
- package/tests/seeds/basic.ts +2 -2
- package/tests/seeds/users.ts +4 -1
- package/tests/sequencer.test.ts +1 -1
- package/tests/server.test.ts +9 -12
- package/tests/sync/invertible-ops.test.ts +1 -1
- package/tests/sync/list.test.ts +1 -1
- package/tests/sync/subscribe-repos.test.ts +1 -1
- package/tests/sync/sync.test.ts +1 -1
- package/tests/takedown-appeal.test.ts +1 -1
- package/tsconfig.build.tsbuildinfo +1 -1
package/dist/pipethrough.js.map
CHANGED
|
@@ -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,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AEzB,KAAK,CAAC,MAAM,EAAE,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,CAAA;wBAZ7C,QAAQ;IAanB,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"]}
|
|
1
|
+
{"version":3,"file":"pipethrough.js","sourceRoot":"","sources":["../src/pipethrough.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAY,QAAQ,EAAE,MAAM,aAAa,CAAA;AAE7D,OAAO,EAAE,KAAK,EAAc,IAAI,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAA;AAC9D,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,WAAW,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAA;AACrE,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAA;AACtE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAA;AAGpD,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAA;AACtD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAExC,MAAM,UAAU,eAAe,CAAC,GAAgB;IAC9C,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC;QACtB,OAAO,EAAE,GAAG,CAAC,UAAU;QACvB,cAAc,EAAE,GAAG,CAAC,cAAc;QAClC,eAAe,EAAE,GAAG,CAAC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;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;wBAZ7C,QAAQ;IAanB,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 { Agent, Dispatcher, Pool, interceptors } 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 { isUnicastIp, unicastLookup } from '@atproto-labs/fetch-node'\nimport { buildProxiedContentEncoding } from '@atproto-labs/xrpc-utils'\nimport { isAccessPrivileged } from './auth-scope.js'\nimport { ProxyConfig } from './config/config.js'\nimport { AppContext } from './context.js'\nimport { chat, com, tools } from './lexicons/index.js'\nimport { httpLogger } from './logger.js'\n\nexport function buildProxyAgent(cfg: ProxyConfig): Dispatcher {\n const agent = new Agent({\n allowH2: cfg.allowHTTP2,\n headersTimeout: cfg.headersTimeout,\n maxResponseSize: cfg.maxResponseSize,\n bodyTimeout: cfg.bodyTimeout,\n factory: cfg.disableSsrfProtection\n ? undefined\n : (origin, opts) => {\n const { protocol, hostname } =\n origin instanceof URL ? origin : new URL(origin)\n if (protocol !== 'https:') {\n throw new Error(`Forbidden protocol \"${protocol}\"`)\n }\n if (isUnicastIp(hostname) === false) {\n throw new Error('Hostname resolved to non-unicast address')\n }\n return new Pool(origin, opts)\n },\n connect: {\n lookup: cfg.disableSsrfProtection ? undefined : unicastLookup,\n },\n })\n\n return agent.compose(\n cfg.maxRetries > 0\n ? interceptors.retry({\n statusCodes: [], // Only retry on socket errors\n methods: ['GET', 'HEAD'],\n maxRetries: cfg.maxRetries,\n })\n : (dispatch) => dispatch,\n )\n}\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.
|
|
3
|
+
"version": "0.5.7",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "Reference implementation of atproto Personal Data Server (PDS)",
|
|
6
6
|
"keywords": [
|
|
@@ -40,28 +40,28 @@
|
|
|
40
40
|
"pino-http": "^8.2.1",
|
|
41
41
|
"typed-emitter": "^2.1.0",
|
|
42
42
|
"uint8arrays": "^5.0.0",
|
|
43
|
-
"undici": "^
|
|
43
|
+
"undici": "^8.5.0",
|
|
44
44
|
"zod": "^3.23.8",
|
|
45
|
-
"@atproto-labs/fetch-node": "^0.3.
|
|
45
|
+
"@atproto-labs/fetch-node": "^0.3.2",
|
|
46
46
|
"@atproto-labs/simple-store": "^0.4.1",
|
|
47
47
|
"@atproto-labs/simple-store-memory": "^0.2.1",
|
|
48
|
-
"@atproto-labs/xrpc-utils": "^0.1.1",
|
|
49
48
|
"@atproto-labs/simple-store-redis": "^0.1.1",
|
|
50
49
|
"@atproto/common": "^0.6.3",
|
|
50
|
+
"@atproto-labs/xrpc-utils": "^0.1.1",
|
|
51
51
|
"@atproto/aws": "^0.3.1",
|
|
52
52
|
"@atproto/crypto": "^0.5.1",
|
|
53
53
|
"@atproto/did": "^0.5.1",
|
|
54
54
|
"@atproto/identity": "^0.5.1",
|
|
55
55
|
"@atproto/lex": "^0.1.4",
|
|
56
56
|
"@atproto/lex-cbor": "^0.1.1",
|
|
57
|
-
"@atproto/lex-
|
|
57
|
+
"@atproto/lex-json": "^0.1.1",
|
|
58
|
+
"@atproto/oauth-provider": "^0.19.1",
|
|
58
59
|
"@atproto/oauth-scopes": "^0.5.1",
|
|
59
60
|
"@atproto/repo": "^0.10.1",
|
|
60
|
-
"@atproto/lex-json": "^0.1.1",
|
|
61
61
|
"@atproto/syntax": "^0.6.2",
|
|
62
|
+
"@atproto/xrpc-server": "^0.11.2",
|
|
62
63
|
"@atproto/xrpc": "^0.8.1",
|
|
63
|
-
"@atproto/
|
|
64
|
-
"@atproto/xrpc-server": "^0.11.2"
|
|
64
|
+
"@atproto/lex-data": "^0.1.2"
|
|
65
65
|
},
|
|
66
66
|
"devDependencies": {
|
|
67
67
|
"@did-plc/server": "^0.0.1",
|
|
@@ -78,10 +78,10 @@
|
|
|
78
78
|
"puppeteer": "^23.11.1",
|
|
79
79
|
"ts-node": "^10.8.2",
|
|
80
80
|
"ws": "^8.12.0",
|
|
81
|
-
"@atproto/
|
|
81
|
+
"@atproto/api": "^0.20.17",
|
|
82
82
|
"@atproto/lex-document": "^0.1.1",
|
|
83
|
-
"@atproto/
|
|
84
|
-
"@atproto/
|
|
83
|
+
"@atproto/bsky": "^0.0.244",
|
|
84
|
+
"@atproto/oauth-client-browser-example": "^0.1.1"
|
|
85
85
|
},
|
|
86
86
|
"type": "module",
|
|
87
87
|
"exports": {
|
package/src/background.ts
CHANGED
|
@@ -1,34 +1,65 @@
|
|
|
1
1
|
import PQueue from 'p-queue'
|
|
2
2
|
import { dbLogger } from './logger.js'
|
|
3
|
-
|
|
4
3
|
// A simple queue for in-process, out-of-band/backgrounded work
|
|
5
4
|
|
|
6
|
-
|
|
7
|
-
queue: InstanceType<typeof PQueue> = new PQueue({ concurrency: 5 })
|
|
8
|
-
destroyed = false
|
|
9
|
-
constructor() {}
|
|
5
|
+
type Task<TContext> = (ctx: TContext, signal: AbortSignal) => Promise<void>
|
|
10
6
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
7
|
+
export type BackgroundQueueOptions = NonNullable<
|
|
8
|
+
ConstructorParameters<typeof PQueue>[0]
|
|
9
|
+
> & {
|
|
10
|
+
concurrency: number
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// @NOTE Keep this in sync with the BackgroundQueue in
|
|
14
|
+
// - packages/bsky/src/data-plane/server/background.ts
|
|
15
|
+
// - packages/ozone/src/background.ts
|
|
16
|
+
// - packages/pds/src/background.ts
|
|
17
|
+
export class BackgroundQueue<TContext = unknown> {
|
|
18
|
+
private abortController = new AbortController()
|
|
19
|
+
private queue: PQueue
|
|
20
|
+
|
|
21
|
+
public get signal(): AbortSignal {
|
|
22
|
+
return this.abortController.signal
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
public get destroyed() {
|
|
26
|
+
return this.signal.aborted
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
constructor(
|
|
30
|
+
private readonly context: TContext,
|
|
31
|
+
options?: BackgroundQueueOptions,
|
|
32
|
+
) {
|
|
33
|
+
this.queue = new PQueue(options)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
add(task: Task<TContext>) {
|
|
37
|
+
if (this.destroyed) return
|
|
38
|
+
|
|
39
|
+
this.queue.add<void>(async () => {
|
|
40
|
+
try {
|
|
41
|
+
// The task will receive a signal allowing it to abort if the
|
|
42
|
+
// backgroundQueue is destroyed.
|
|
43
|
+
await task(this.context, this.signal)
|
|
44
|
+
} catch (err) {
|
|
18
45
|
dbLogger.error({ err }, 'background queue task failed')
|
|
19
|
-
}
|
|
46
|
+
}
|
|
47
|
+
})
|
|
20
48
|
}
|
|
21
49
|
|
|
22
50
|
async processAll() {
|
|
23
|
-
|
|
51
|
+
const { queue } = this
|
|
52
|
+
while (queue.size || queue.pending) await queue.onIdle()
|
|
24
53
|
}
|
|
25
54
|
|
|
26
55
|
// On destroy we stop accepting new tasks, but complete all pending/in-progress tasks.
|
|
27
56
|
// The application calls this only once http connections have drained (tasks no longer being added).
|
|
28
57
|
async destroy() {
|
|
29
|
-
this.destroyed
|
|
30
|
-
|
|
58
|
+
if (this.destroyed) {
|
|
59
|
+
dbLogger.warn('BackgroundQueue.destroy() called multiple times')
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
this.abortController.abort()
|
|
63
|
+
return this.processAll()
|
|
31
64
|
}
|
|
32
65
|
}
|
|
33
|
-
|
|
34
|
-
type Task = () => Promise<void>
|
package/src/context.ts
CHANGED
|
@@ -21,12 +21,7 @@ import {
|
|
|
21
21
|
createServiceAuthHeaders,
|
|
22
22
|
createServiceJwt,
|
|
23
23
|
} from '@atproto/xrpc-server'
|
|
24
|
-
import {
|
|
25
|
-
Fetch,
|
|
26
|
-
isUnicastIp,
|
|
27
|
-
safeFetchWrap,
|
|
28
|
-
unicastLookup,
|
|
29
|
-
} from '@atproto-labs/fetch-node'
|
|
24
|
+
import { Fetch, safeFetchWrap } from '@atproto-labs/fetch-node'
|
|
30
25
|
import { AccountManager } from './account-manager/account-manager.js'
|
|
31
26
|
import { OAuthStore } from './account-manager/oauth-store.js'
|
|
32
27
|
import { ScopeReferenceGetter } from './account-manager/scope-reference-getter.js'
|
|
@@ -47,6 +42,7 @@ import { ImageUrlBuilder } from './image/image-url-builder.js'
|
|
|
47
42
|
import { fetchLogger, lexiconResolverLogger, oauthLogger } from './logger.js'
|
|
48
43
|
import { ServerMailer } from './mailer/index.js'
|
|
49
44
|
import { ModerationMailer } from './mailer/moderation.js'
|
|
45
|
+
import { buildProxyAgent } from './pipethrough.js'
|
|
50
46
|
import { LocalViewer, LocalViewerCreator } from './read-after-write/viewer.js'
|
|
51
47
|
import { getRedisClient } from './redis.js'
|
|
52
48
|
import { Sequencer } from './sequencer/index.js'
|
|
@@ -181,7 +177,7 @@ export class AppContext {
|
|
|
181
177
|
})
|
|
182
178
|
const plcClient = new plc.Client(cfg.identity.plcUrl)
|
|
183
179
|
|
|
184
|
-
const backgroundQueue = new BackgroundQueue()
|
|
180
|
+
const backgroundQueue = new BackgroundQueue(undefined, { concurrency: 5 })
|
|
185
181
|
const crawlers = new Crawlers(
|
|
186
182
|
backgroundQueue,
|
|
187
183
|
cfg.service.hostname,
|
|
@@ -295,36 +291,7 @@ export class AppContext {
|
|
|
295
291
|
)
|
|
296
292
|
|
|
297
293
|
// An agent for performing HTTP requests based on user provided URLs.
|
|
298
|
-
const
|
|
299
|
-
allowH2: cfg.proxy.allowHTTP2, // This is experimental
|
|
300
|
-
headersTimeout: cfg.proxy.headersTimeout,
|
|
301
|
-
maxResponseSize: cfg.proxy.maxResponseSize,
|
|
302
|
-
bodyTimeout: cfg.proxy.bodyTimeout,
|
|
303
|
-
factory: cfg.proxy.disableSsrfProtection
|
|
304
|
-
? undefined
|
|
305
|
-
: (origin, opts) => {
|
|
306
|
-
const { protocol, hostname } =
|
|
307
|
-
origin instanceof URL ? origin : new URL(origin)
|
|
308
|
-
if (protocol !== 'https:') {
|
|
309
|
-
throw new Error(`Forbidden protocol "${protocol}"`)
|
|
310
|
-
}
|
|
311
|
-
if (isUnicastIp(hostname) === false) {
|
|
312
|
-
throw new Error('Hostname resolved to non-unicast address')
|
|
313
|
-
}
|
|
314
|
-
return new undici.Pool(origin, opts)
|
|
315
|
-
},
|
|
316
|
-
connect: {
|
|
317
|
-
lookup: cfg.proxy.disableSsrfProtection ? undefined : unicastLookup,
|
|
318
|
-
},
|
|
319
|
-
})
|
|
320
|
-
const proxyAgent =
|
|
321
|
-
cfg.proxy.maxRetries > 0
|
|
322
|
-
? new undici.RetryAgent(proxyAgentBase, {
|
|
323
|
-
statusCodes: [], // Only retry on socket errors
|
|
324
|
-
methods: ['GET', 'HEAD'],
|
|
325
|
-
maxRetries: cfg.proxy.maxRetries,
|
|
326
|
-
})
|
|
327
|
-
: proxyAgentBase
|
|
294
|
+
const proxyAgent = buildProxyAgent(cfg.proxy)
|
|
328
295
|
|
|
329
296
|
/**
|
|
330
297
|
* A fetch() function that protects against SSRF attacks, large responses &
|
package/src/index.ts
CHANGED
|
@@ -9,11 +9,8 @@ import http from 'node:http'
|
|
|
9
9
|
import { PlcClientError } from '@did-plc/lib'
|
|
10
10
|
import cors from 'cors'
|
|
11
11
|
import express from 'express'
|
|
12
|
-
// eslint-disable-next-line import/default
|
|
12
|
+
// eslint-disable-next-line import/default
|
|
13
13
|
import httpTerminator from 'http-terminator'
|
|
14
|
-
// eslint-disable-next-line import/no-named-as-default-member
|
|
15
|
-
const { createHttpTerminator } = httpTerminator
|
|
16
|
-
type HttpTerminator = ReturnType<typeof createHttpTerminator>
|
|
17
14
|
import { DAY, SECOND } from '@atproto/common'
|
|
18
15
|
import {
|
|
19
16
|
MethodHandler,
|
|
@@ -64,7 +61,7 @@ export class PDS {
|
|
|
64
61
|
public ctx: AppContext
|
|
65
62
|
public app: express.Application
|
|
66
63
|
public server?: http.Server
|
|
67
|
-
private terminator?: HttpTerminator
|
|
64
|
+
private terminator?: httpTerminator.HttpTerminator
|
|
68
65
|
private dbStatsInterval?: NodeJS.Timeout
|
|
69
66
|
private sequencerStatsInterval?: NodeJS.Timeout
|
|
70
67
|
|
|
@@ -145,21 +142,42 @@ export class PDS {
|
|
|
145
142
|
await this.ctx.sequencer.start()
|
|
146
143
|
const server = this.app.listen(this.ctx.cfg.service.port)
|
|
147
144
|
this.server = server
|
|
148
|
-
this.server.keepAliveTimeout =
|
|
149
|
-
this.terminator = createHttpTerminator({ server })
|
|
145
|
+
this.server.keepAliveTimeout = 90_000
|
|
146
|
+
this.terminator = httpTerminator.createHttpTerminator({ server })
|
|
150
147
|
await events.once(server, 'listening')
|
|
151
148
|
return server
|
|
152
149
|
}
|
|
153
150
|
|
|
154
151
|
async destroy(): Promise<void> {
|
|
155
|
-
await this.ctx.sequencer.destroy()
|
|
156
|
-
await this.terminator?.terminate()
|
|
157
|
-
await this.ctx.backgroundQueue.destroy()
|
|
158
|
-
await this.ctx.accountManager.close()
|
|
159
|
-
await this.ctx.redisScratch?.quit()
|
|
160
|
-
await this.ctx.proxyAgent.destroy()
|
|
161
152
|
clearInterval(this.dbStatsInterval)
|
|
162
153
|
clearInterval(this.sequencerStatsInterval)
|
|
154
|
+
|
|
155
|
+
// @TODO Use disposable stack when it becomes available (Node24+)
|
|
156
|
+
try {
|
|
157
|
+
await this.terminator?.terminate()
|
|
158
|
+
} finally {
|
|
159
|
+
try {
|
|
160
|
+
await this.ctx.backgroundQueue.destroy()
|
|
161
|
+
} finally {
|
|
162
|
+
try {
|
|
163
|
+
await this.ctx.sequencer.destroy()
|
|
164
|
+
} finally {
|
|
165
|
+
try {
|
|
166
|
+
await this.ctx.accountManager.close()
|
|
167
|
+
} finally {
|
|
168
|
+
try {
|
|
169
|
+
await this.ctx.redisScratch?.quit()
|
|
170
|
+
} finally {
|
|
171
|
+
await this.ctx.proxyAgent.destroy()
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async [Symbol.asyncDispose]() {
|
|
180
|
+
await this.destroy()
|
|
163
181
|
}
|
|
164
182
|
}
|
|
165
183
|
|
package/src/pipethrough.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { IncomingHttpHeaders, ServerResponse } from 'node:http'
|
|
2
2
|
import { PassThrough, Readable, finished } from 'node:stream'
|
|
3
3
|
import { Request } from 'express'
|
|
4
|
-
import { Dispatcher } from 'undici'
|
|
4
|
+
import { Agent, Dispatcher, Pool, interceptors } from 'undici'
|
|
5
5
|
import {
|
|
6
6
|
decodeStream,
|
|
7
7
|
getServiceEndpoint,
|
|
@@ -20,12 +20,49 @@ import {
|
|
|
20
20
|
excludeErrorResult,
|
|
21
21
|
parseReqNsid,
|
|
22
22
|
} from '@atproto/xrpc-server'
|
|
23
|
+
import { isUnicastIp, unicastLookup } from '@atproto-labs/fetch-node'
|
|
23
24
|
import { buildProxiedContentEncoding } from '@atproto-labs/xrpc-utils'
|
|
24
25
|
import { isAccessPrivileged } from './auth-scope.js'
|
|
26
|
+
import { ProxyConfig } from './config/config.js'
|
|
25
27
|
import { AppContext } from './context.js'
|
|
26
28
|
import { chat, com, tools } from './lexicons/index.js'
|
|
27
29
|
import { httpLogger } from './logger.js'
|
|
28
30
|
|
|
31
|
+
export function buildProxyAgent(cfg: ProxyConfig): Dispatcher {
|
|
32
|
+
const agent = new Agent({
|
|
33
|
+
allowH2: cfg.allowHTTP2,
|
|
34
|
+
headersTimeout: cfg.headersTimeout,
|
|
35
|
+
maxResponseSize: cfg.maxResponseSize,
|
|
36
|
+
bodyTimeout: cfg.bodyTimeout,
|
|
37
|
+
factory: cfg.disableSsrfProtection
|
|
38
|
+
? undefined
|
|
39
|
+
: (origin, opts) => {
|
|
40
|
+
const { protocol, hostname } =
|
|
41
|
+
origin instanceof URL ? origin : new URL(origin)
|
|
42
|
+
if (protocol !== 'https:') {
|
|
43
|
+
throw new Error(`Forbidden protocol "${protocol}"`)
|
|
44
|
+
}
|
|
45
|
+
if (isUnicastIp(hostname) === false) {
|
|
46
|
+
throw new Error('Hostname resolved to non-unicast address')
|
|
47
|
+
}
|
|
48
|
+
return new Pool(origin, opts)
|
|
49
|
+
},
|
|
50
|
+
connect: {
|
|
51
|
+
lookup: cfg.disableSsrfProtection ? undefined : unicastLookup,
|
|
52
|
+
},
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
return agent.compose(
|
|
56
|
+
cfg.maxRetries > 0
|
|
57
|
+
? interceptors.retry({
|
|
58
|
+
statusCodes: [], // Only retry on socket errors
|
|
59
|
+
methods: ['GET', 'HEAD'],
|
|
60
|
+
maxRetries: cfg.maxRetries,
|
|
61
|
+
})
|
|
62
|
+
: (dispatch) => dispatch,
|
|
63
|
+
)
|
|
64
|
+
}
|
|
65
|
+
|
|
29
66
|
export const proxyHandler = (ctx: AppContext): CatchallHandler => {
|
|
30
67
|
const performAuth = ctx.authVerifier.authorization<RpcPermissionMatch>({
|
|
31
68
|
authorize: (permissions, { params }) => permissions.assertRpc(params),
|
package/tests/_util.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { RequestListener, createServer } from 'node:http'
|
|
2
2
|
import { AddressInfo } from 'node:net'
|
|
3
|
-
|
|
3
|
+
// eslint-disable-next-line import/default
|
|
4
|
+
import httpTerminator from 'http-terminator'
|
|
4
5
|
import { ToolsOzoneModerationDefs, lexToJson } from '@atproto/api'
|
|
5
6
|
import { isCidString } from '@atproto/lex'
|
|
6
7
|
import { isCid, isPlainObject } from '@atproto/lex-data'
|
|
@@ -146,19 +147,11 @@ export const paginateAll = async <T extends { cursor?: string }>(
|
|
|
146
147
|
return results
|
|
147
148
|
}
|
|
148
149
|
|
|
149
|
-
export async function startServer(
|
|
150
|
-
return new Promise<{
|
|
151
|
-
origin: string
|
|
152
|
-
server: Server
|
|
153
|
-
stop: () => Promise<void>
|
|
154
|
-
}>((resolve, reject) => {
|
|
150
|
+
export async function startServer(listener: RequestListener) {
|
|
151
|
+
return new Promise<AsyncDisposable & { port: number }>((resolve, reject) => {
|
|
155
152
|
const onListen = () => {
|
|
156
153
|
const port = (server.address() as AddressInfo).port
|
|
157
|
-
resolve({
|
|
158
|
-
server,
|
|
159
|
-
origin: `http://localhost:${port}`,
|
|
160
|
-
stop: () => stopServer(server),
|
|
161
|
-
})
|
|
154
|
+
resolve({ port, [Symbol.asyncDispose]: () => terminator.terminate() })
|
|
162
155
|
cleanup()
|
|
163
156
|
}
|
|
164
157
|
const onError = (err: Error) => {
|
|
@@ -170,22 +163,12 @@ export async function startServer(app: Express) {
|
|
|
170
163
|
server.removeListener('error', onError)
|
|
171
164
|
}
|
|
172
165
|
|
|
173
|
-
const server =
|
|
166
|
+
const server = createServer(listener)
|
|
174
167
|
.listen(0)
|
|
175
168
|
.once('listening', onListen)
|
|
176
169
|
.once('error', onError)
|
|
177
|
-
})
|
|
178
|
-
}
|
|
179
170
|
|
|
180
|
-
|
|
181
|
-
return new Promise<void>((resolve, reject) => {
|
|
182
|
-
server.close((err) => {
|
|
183
|
-
if (err) {
|
|
184
|
-
reject(err)
|
|
185
|
-
} else {
|
|
186
|
-
resolve()
|
|
187
|
-
}
|
|
188
|
-
})
|
|
171
|
+
const terminator = httpTerminator.createHttpTerminator({ server })
|
|
189
172
|
})
|
|
190
173
|
}
|
|
191
174
|
|