@atproto/pds 0.4.211 → 0.4.213

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.
@@ -1,6 +1,7 @@
1
1
  import type * as AppBskyFeedDefs from './defs.js';
2
2
  export type QueryParams = {};
3
3
  export interface InputSchema {
4
+ feed?: string;
4
5
  interactions: AppBskyFeedDefs.Interaction[];
5
6
  }
6
7
  export interface OutputSchema {
@@ -1 +1 @@
1
- {"version":3,"file":"sendInteractions.d.ts","sourceRoot":"","sources":["../../../../../../src/lexicon/types/app/bsky/feed/sendInteractions.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,KAAK,eAAe,MAAM,WAAW,CAAA;AAMjD,MAAM,MAAM,WAAW,GAAG,EAAE,CAAA;AAE5B,MAAM,WAAW,WAAW;IAC1B,YAAY,EAAE,eAAe,CAAC,WAAW,EAAE,CAAA;CAC5C;AAED,MAAM,WAAW,YAAY;CAAG;AAEhC,MAAM,WAAW,YAAY;IAC3B,QAAQ,EAAE,kBAAkB,CAAA;IAC5B,IAAI,EAAE,WAAW,CAAA;CAClB;AAED,MAAM,WAAW,cAAc;IAC7B,QAAQ,EAAE,kBAAkB,CAAA;IAC5B,IAAI,EAAE,YAAY,CAAA;IAClB,OAAO,CAAC,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,CAAA;CACpC;AAED,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,MAAM,CAAA;IACd,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB;AAED,MAAM,MAAM,aAAa,GAAG,YAAY,GAAG,cAAc,CAAA"}
1
+ {"version":3,"file":"sendInteractions.d.ts","sourceRoot":"","sources":["../../../../../../src/lexicon/types/app/bsky/feed/sendInteractions.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,KAAK,eAAe,MAAM,WAAW,CAAA;AAMjD,MAAM,MAAM,WAAW,GAAG,EAAE,CAAA;AAE5B,MAAM,WAAW,WAAW;IAC1B,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,YAAY,EAAE,eAAe,CAAC,WAAW,EAAE,CAAA;CAC5C;AAED,MAAM,WAAW,YAAY;CAAG;AAEhC,MAAM,WAAW,YAAY;IAC3B,QAAQ,EAAE,kBAAkB,CAAA;IAC5B,IAAI,EAAE,WAAW,CAAA;CAClB;AAED,MAAM,WAAW,cAAc;IAC7B,QAAQ,EAAE,kBAAkB,CAAA;IAC5B,IAAI,EAAE,YAAY,CAAA;IAClB,OAAO,CAAC,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,CAAA;CACpC;AAED,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,MAAM,CAAA;IACd,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB;AAED,MAAM,MAAM,aAAa,GAAG,YAAY,GAAG,cAAc,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"sendInteractions.js","sourceRoot":"","sources":["../../../../../../src/lexicon/types/app/bsky/feed/sendInteractions.ts"],"names":[],"mappings":";;AAKA,mDAA4D;AAC5D,2CAIyB;AAGzB,MAAM,QAAQ,GAAG,eAAS,EACxB,QAAQ,GAAG,mBAAS,CAAA;AACtB,MAAM,EAAE,GAAG,gCAAgC,CAAA","sourcesContent":["/**\n * GENERATED CODE - DO NOT MODIFY\n */\nimport { type ValidationResult, BlobRef } from '@atproto/lexicon'\nimport { CID } from 'multiformats/cid'\nimport { validate as _validate } from '../../../../lexicons'\nimport {\n type $Typed,\n is$typed as _is$typed,\n type OmitKey,\n} from '../../../../util'\nimport type * as AppBskyFeedDefs from './defs.js'\n\nconst is$typed = _is$typed,\n validate = _validate\nconst id = 'app.bsky.feed.sendInteractions'\n\nexport type QueryParams = {}\n\nexport interface InputSchema {\n interactions: AppBskyFeedDefs.Interaction[]\n}\n\nexport interface OutputSchema {}\n\nexport interface HandlerInput {\n encoding: 'application/json'\n body: InputSchema\n}\n\nexport interface HandlerSuccess {\n encoding: 'application/json'\n body: OutputSchema\n headers?: { [key: string]: string }\n}\n\nexport interface HandlerError {\n status: number\n message?: string\n}\n\nexport type HandlerOutput = HandlerError | HandlerSuccess\n"]}
1
+ {"version":3,"file":"sendInteractions.js","sourceRoot":"","sources":["../../../../../../src/lexicon/types/app/bsky/feed/sendInteractions.ts"],"names":[],"mappings":";;AAKA,mDAA4D;AAC5D,2CAIyB;AAGzB,MAAM,QAAQ,GAAG,eAAS,EACxB,QAAQ,GAAG,mBAAS,CAAA;AACtB,MAAM,EAAE,GAAG,gCAAgC,CAAA","sourcesContent":["/**\n * GENERATED CODE - DO NOT MODIFY\n */\nimport { type ValidationResult, BlobRef } from '@atproto/lexicon'\nimport { CID } from 'multiformats/cid'\nimport { validate as _validate } from '../../../../lexicons'\nimport {\n type $Typed,\n is$typed as _is$typed,\n type OmitKey,\n} from '../../../../util'\nimport type * as AppBskyFeedDefs from './defs.js'\n\nconst is$typed = _is$typed,\n validate = _validate\nconst id = 'app.bsky.feed.sendInteractions'\n\nexport type QueryParams = {}\n\nexport interface InputSchema {\n feed?: string\n interactions: AppBskyFeedDefs.Interaction[]\n}\n\nexport interface OutputSchema {}\n\nexport interface HandlerInput {\n encoding: 'application/json'\n body: InputSchema\n}\n\nexport interface HandlerSuccess {\n encoding: 'application/json'\n body: OutputSchema\n headers?: { [key: string]: string }\n}\n\nexport interface HandlerError {\n status: number\n message?: string\n}\n\nexport type HandlerOutput = HandlerError | HandlerSuccess\n"]}
@@ -1,6 +1,7 @@
1
+ import { IncomingHttpHeaders } from 'node:http';
1
2
  import { Readable } from 'node:stream';
2
3
  import { Request } from 'express';
3
- import { CatchallHandler, HandlerPipeThroughBuffer, HandlerPipeThroughStream } from '@atproto/xrpc-server';
4
+ import { CatchallHandler, HandlerPipeThroughBuffer, HandlerPipeThroughStream, XRPCError as XRPCServerError } from '@atproto/xrpc-server';
4
5
  import { AppContext } from './context';
5
6
  export declare const proxyHandler: (ctx: AppContext) => CatchallHandler;
6
7
  export type PipethroughOptions = {
@@ -51,4 +52,19 @@ export declare function normalizeLxm(lxm: string): string;
51
52
  export declare const CHAT_BSKY_METHODS: LxmSet;
52
53
  export declare const PRIVILEGED_METHODS: LxmSet;
53
54
  export declare const PROTECTED_METHODS: LxmSet;
55
+ export declare class PipethroughUpstreamError extends XRPCServerError {
56
+ readonly upstream: {
57
+ statusCode: number;
58
+ headers: IncomingHttpHeaders;
59
+ };
60
+ constructor(upstream: {
61
+ statusCode: number;
62
+ headers: IncomingHttpHeaders;
63
+ }, payload: {
64
+ message?: string;
65
+ error?: string;
66
+ }, options?: ErrorOptions);
67
+ get headers(): Record<string, string>;
68
+ get error(): string | undefined;
69
+ }
54
70
  //# sourceMappingURL=pipethrough.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"pipethrough.d.ts","sourceRoot":"","sources":["../src/pipethrough.ts"],"names":[],"mappings":"AACA,OAAO,EAAe,QAAQ,EAAY,MAAM,aAAa,CAAA;AAC7D,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AAUjC,OAAO,EACL,eAAe,EACf,wBAAwB,EACxB,wBAAwB,EAMzB,MAAM,sBAAsB,CAAA;AAG7B,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAA;AAItC,eAAO,MAAM,YAAY,GAAI,KAAK,UAAU,KAAG,eAmF9C,CAAA;AAED,MAAM,MAAM,kBAAkB,GAAG;IAC/B;;;OAGG;IACH,GAAG,CAAC,EAAE,MAAM,CAAA;IAEZ;;;OAGG;IACH,GAAG,CAAC,EAAE,MAAM,CAAA;IAEZ;;;OAGG;IACH,GAAG,CAAC,EAAE,MAAM,CAAA;CACb,CAAA;AAED,wBAAsB,WAAW,CAC/B,GAAG,EAAE,UAAU,EACf,GAAG,EAAE,OAAO,EACZ,OAAO,CAAC,EAAE,kBAAkB,GAC3B,OAAO,CACR,wBAAwB,GAAG;IACzB,MAAM,EAAE,QAAQ,CAAA;IAChB,OAAO,EAAE,MAAM,CAAC,MAAM,EA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value: true });
3
- exports.PROTECTED_METHODS = exports.PRIVILEGED_METHODS = exports.CHAT_BSKY_METHODS = exports.LxmSet = exports.parseProxyHeader = exports.proxyHandler = void 0;
3
+ exports.PipethroughUpstreamError = exports.PROTECTED_METHODS = exports.PRIVILEGED_METHODS = exports.CHAT_BSKY_METHODS = exports.LxmSet = exports.parseProxyHeader = exports.proxyHandler = void 0;
4
4
  exports.pipethrough = pipethrough;
5
5
  exports.computeProxyTo = computeProxyTo;
6
6
  exports.parseProxyInfo = parseProxyInfo;
@@ -9,7 +9,6 @@ exports.asPipeThroughBuffer = asPipeThroughBuffer;
9
9
  exports.normalizeLxm = normalizeLxm;
10
10
  const node_stream_1 = require("node:stream");
11
11
  const common_1 = require("@atproto/common");
12
- const xrpc_1 = require("@atproto/xrpc");
13
12
  const xrpc_server_1 = require("@atproto/xrpc-server");
14
13
  const xrpc_utils_1 = require("@atproto-labs/xrpc-utils");
15
14
  const auth_scope_1 = require("./auth-scope");
@@ -25,7 +24,7 @@ const proxyHandler = (ctx) => {
25
24
  if (req.method !== 'GET' &&
26
25
  req.method !== 'HEAD' &&
27
26
  req.method !== 'POST') {
28
- throw new xrpc_server_1.XRPCError(xrpc_1.ResponseType.InvalidRequest, 'XRPC requests only supports GET and POST');
27
+ throw new xrpc_server_1.XRPCError(xrpc_server_1.ResponseType.InvalidRequest, 'XRPC requests only supports GET and POST');
29
28
  }
30
29
  const body = req.method === 'POST' ? req : undefined;
31
30
  if (body != null && !body.readable) {
@@ -193,9 +192,9 @@ async function pipethroughStream(ctx, dispatchOptions, successStreamFactory) {
193
192
  if (upstream.statusCode >= 400) {
194
193
  const passThrough = new node_stream_1.PassThrough();
195
194
  void tryParsingError(upstream.headers, passThrough).then((parsed) => {
196
- const xrpcError = new xrpc_1.XRPCError(upstream.statusCode === 500
197
- ? xrpc_1.ResponseType.UpstreamFailure
198
- : upstream.statusCode, parsed.error, parsed.message, Object.fromEntries(responseHeaders(upstream.headers, false)), { cause: dispatchOptions });
195
+ const xrpcError = new PipethroughUpstreamError(upstream, parsed, {
196
+ cause: dispatchOptions,
197
+ });
199
198
  reject(xrpcError);
200
199
  }, reject);
201
200
  return passThrough;
@@ -230,18 +229,15 @@ async function pipethroughRequest(ctx, dispatchOptions) {
230
229
  .catch(handleUpstreamRequestError);
231
230
  if (upstream.statusCode >= 400) {
232
231
  const parsed = await tryParsingError(upstream.headers, upstream.body);
233
- // Note "XRPCClientError" is used instead of "XRPCServerError" in order to
234
- // allow users of this function to capture & handle these errors (namely in
235
- // "app.bsky.feed.getPostThread").
236
- throw new xrpc_1.XRPCError(upstream.statusCode === 500
237
- ? xrpc_1.ResponseType.UpstreamFailure
238
- : upstream.statusCode, parsed.error, parsed.message, Object.fromEntries(responseHeaders(upstream.headers, false)), { cause: dispatchOptions });
232
+ throw new PipethroughUpstreamError(upstream, parsed, {
233
+ cause: dispatchOptions,
234
+ });
239
235
  }
240
236
  return upstream;
241
237
  }
242
238
  function handleUpstreamRequestError(err, message = 'Upstream service unreachable') {
243
239
  logger_1.httpLogger.error({ err }, message);
244
- throw new xrpc_server_1.XRPCError(xrpc_1.ResponseType.UpstreamFailure, message, undefined, {
240
+ throw new xrpc_server_1.XRPCError(xrpc_server_1.ResponseType.UpstreamFailure, message, undefined, {
245
241
  cause: err,
246
242
  });
247
243
  }
@@ -293,7 +289,7 @@ async function bufferUpstreamResponse(readable, contentEncoding) {
293
289
  catch (err) {
294
290
  if (!readable.destroyed)
295
291
  readable.destroy();
296
- throw new xrpc_server_1.XRPCError(xrpc_1.ResponseType.UpstreamFailure, err instanceof TypeError ? err.message : 'unable to decode request body', undefined, { cause: err });
292
+ throw new xrpc_server_1.XRPCError(xrpc_server_1.ResponseType.UpstreamFailure, err instanceof TypeError ? err.message : 'unable to decode request body', undefined, { cause: err });
297
293
  }
298
294
  }
299
295
  async function asPipeThroughBuffer(input) {
@@ -460,4 +456,25 @@ const safeString = (str) => {
460
456
  function logResponseError(err) {
461
457
  logger_1.httpLogger.warn({ err }, 'error forwarding upstream response');
462
458
  }
459
+ class PipethroughUpstreamError extends xrpc_server_1.XRPCError {
460
+ constructor(upstream, payload, options) {
461
+ const status = upstream.statusCode === 500
462
+ ? xrpc_server_1.ResponseType.UpstreamFailure
463
+ : upstream.statusCode;
464
+ super(status, payload.message, payload.error, options);
465
+ Object.defineProperty(this, "upstream", {
466
+ enumerable: true,
467
+ configurable: true,
468
+ writable: true,
469
+ value: upstream
470
+ });
471
+ }
472
+ get headers() {
473
+ return Object.fromEntries(responseHeaders(this.upstream.headers, false));
474
+ }
475
+ get error() {
476
+ return this.customErrorName ?? this.typeName;
477
+ }
478
+ }
479
+ exports.PipethroughUpstreamError = PipethroughUpstreamError;
463
480
  //# sourceMappingURL=pipethrough.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"pipethrough.js","sourceRoot":"","sources":["../src/pipethrough.ts"],"names":[],"mappings":";;;AAqIA,kCAgEC;AAKD,wCAcC;AAED,wCAcC;AA4JD,8CAGC;AAkED,kDAWC;AA8DD,oCAEC;AAnhBD,6CAA6D;AAG7D,4CAKwB;AAExB,wCAA0E;AAC1E,sDAS6B;AAC7B,yDAAsE;AACtE,6CAAiD;AAEjD,iDAAwC;AACxC,qCAAqC;AAE9B,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,IA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,cAAG,CAAC,wCAAwC,CAAC;QAClD,KAAK,cAAG,CAAC,yCAAyC,CAAC;QACnD,KAAK,cAAG,CAAC,yBAAyB,CAAC;QACnC,KAAK,cAAG,CAAC,4BAA4B,CAAC;QACtC,KAAK,cAAG,CAAC,4BAA4B,CAAC;QACtC,KAAK,cAAG,CAAC,6BAA6B,CAAC;QACvC,KAAK,cAAG,CAAC,4BAA4B,CAAC;QACtC,KAAK,cAAG,CAAC,wCAAwC,CAAC;QAClD,KAAK,cAAG,CAAC,0CAA0C,CAAC;QACpD,KAAK,cAAG,CAAC,kCAAkC;YACzC,OAAO;gBACL,SAAS,EAAE,iBAAiB;gBAC5B,WAAW,EAAE,GAAG,CAAC,GAAG,CAAC,UAAU;aAChC,CAAA;QACH,KAAK,cAAG,CAAC,gCAAgC;YACvC,OAAO;gBACL,SAAS,EAAE,iBAAiB;gBAC5B,WAAW,EAAE,GAAG,CAAC,GAAG,CAAC,aAAa;aACnC,CAAA;QACH;YACE,OAAO;gBACL,SAAS,EAAE,cAAc;gBACzB,WAAW,EAAE,GAAG,CAAC,GAAG,CAAC,WAAW;aACjC,CAAA;IACL,CAAC;AACH,CAAC,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,mBAAU,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,EAAE,oCAAoC,CAAC,CAAA;AAChE,CAAC","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 { ResponseType, XRPCError as XRPCClientError } from '@atproto/xrpc'\nimport {\n CatchallHandler,\n HandlerPipeThroughBuffer,\n HandlerPipeThroughStream,\n InternalServerError,\n InvalidRequestError,\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'\nimport { AppContext } from './context'\nimport { ids } from './lexicon/lexicons'\nimport { httpLogger } from './logger'\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, 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, 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 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 XRPCClientError(\n upstream.statusCode === 500\n ? ResponseType.UpstreamFailure\n : upstream.statusCode,\n parsed.error,\n parsed.message,\n Object.fromEntries(responseHeaders(upstream.headers, false)),\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)\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 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)\n\n if (upstream.statusCode >= 400) {\n const parsed = await tryParsingError(upstream.headers, upstream.body)\n\n // Note \"XRPCClientError\" is used instead of \"XRPCServerError\" in order to\n // allow users of this function to capture & handle these errors (namely in\n // \"app.bsky.feed.getPostThread\").\n throw new XRPCClientError(\n upstream.statusCode === 500\n ? ResponseType.UpstreamFailure\n : upstream.statusCode,\n parsed.error,\n parsed.message,\n Object.fromEntries(responseHeaders(upstream.headers, false)),\n { cause: dispatchOptions },\n )\n }\n\n return upstream\n}\n\nfunction handleUpstreamRequestError(\n err: unknown,\n message = 'Upstream service unreachable',\n): never {\n httpLogger.error({ err }, message)\n throw new XRPCServerError(ResponseType.UpstreamFailure, message, undefined, {\n cause: err,\n })\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 ids.ChatBskyActorDeleteAccount,\n ids.ChatBskyActorExportAccountData,\n ids.ChatBskyConvoDeleteMessageForSelf,\n ids.ChatBskyConvoGetConvo,\n ids.ChatBskyConvoGetConvoForMembers,\n ids.ChatBskyConvoGetLog,\n ids.ChatBskyConvoGetMessages,\n ids.ChatBskyConvoLeaveConvo,\n ids.ChatBskyConvoListConvos,\n ids.ChatBskyConvoMuteConvo,\n ids.ChatBskyConvoSendMessage,\n ids.ChatBskyConvoSendMessageBatch,\n ids.ChatBskyConvoUnmuteConvo,\n ids.ChatBskyConvoUpdateRead,\n])\n\nexport const PRIVILEGED_METHODS = new LxmSet([\n ...CHAT_BSKY_METHODS,\n ids.ComAtprotoServerCreateAccount,\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 ids.ComAtprotoAdminSendEmail,\n ids.ComAtprotoIdentityRequestPlcOperationSignature,\n ids.ComAtprotoIdentitySignPlcOperation,\n ids.ComAtprotoIdentityUpdateHandle,\n ids.ComAtprotoServerActivateAccount,\n ids.ComAtprotoServerConfirmEmail,\n ids.ComAtprotoServerCreateAppPassword,\n ids.ComAtprotoServerDeactivateAccount,\n ids.ComAtprotoServerGetAccountInviteCodes,\n ids.ComAtprotoServerGetSession,\n ids.ComAtprotoServerListAppPasswords,\n ids.ComAtprotoServerRequestAccountDelete,\n ids.ComAtprotoServerRequestEmailConfirmation,\n ids.ComAtprotoServerRequestEmailUpdate,\n ids.ComAtprotoServerRevokeAppPassword,\n ids.ComAtprotoServerUpdateEmail,\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 ids.ToolsOzoneTeamAddMember:\n case ids.ToolsOzoneTeamDeleteMember:\n case ids.ToolsOzoneTeamUpdateMember:\n case ids.ToolsOzoneTeamListMembers:\n case ids.ToolsOzoneCommunicationCreateTemplate:\n case ids.ToolsOzoneCommunicationDeleteTemplate:\n case ids.ToolsOzoneCommunicationUpdateTemplate:\n case ids.ToolsOzoneCommunicationListTemplates:\n case ids.ToolsOzoneModerationEmitEvent:\n case ids.ToolsOzoneModerationGetEvent:\n case ids.ToolsOzoneModerationGetRecord:\n case ids.ToolsOzoneModerationGetRepo:\n case ids.ToolsOzoneModerationQueryEvents:\n case ids.ToolsOzoneModerationQueryStatuses:\n case ids.ToolsOzoneModerationSearchRepos:\n case ids.ToolsOzoneModerationGetAccountTimeline:\n case ids.ToolsOzoneVerificationListVerifications:\n case ids.ToolsOzoneVerificationGrantVerifications:\n case ids.ToolsOzoneVerificationRevokeVerifications:\n case ids.ToolsOzoneSafelinkAddRule:\n case ids.ToolsOzoneSafelinkUpdateRule:\n case ids.ToolsOzoneSafelinkRemoveRule:\n case ids.ToolsOzoneSafelinkQueryEvents:\n case ids.ToolsOzoneSafelinkQueryRules:\n case ids.ToolsOzoneModerationListScheduledActions:\n case ids.ToolsOzoneModerationCancelScheduledActions:\n case ids.ToolsOzoneModerationScheduleAction:\n return {\n serviceId: 'atproto_labeler',\n serviceInfo: ctx.cfg.modService,\n }\n case ids.ComAtprotoModerationCreateReport:\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"]}
1
+ {"version":3,"file":"pipethrough.js","sourceRoot":"","sources":["../src/pipethrough.ts"],"names":[],"mappings":";;;AAqIA,kCAgEC;AAKD,wCAcC;AAED,wCAcC;AA6ID,8CAGC;AAkED,kDAWC;AA8DD,oCAEC;AApgBD,6CAA6D;AAG7D,4CAKwB;AAExB,sDAU6B;AAC7B,yDAAsE;AACtE,6CAAiD;AAEjD,iDAAwC;AACxC,qCAAqC;AAE9B,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,uBAAe,CACvB,0BAAY,CAAC,cAAc,EAC3B,0CAA0C,CAC3C,CAAA;YACH,CAAC;YAED,MAAM,IAAI,GAAG,GAAG,CAAC,MAAM,KAAK,MAAM,CAAC,CAAC,C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S,EAAE,cAAc;gBACzB,WAAW,EAAE,GAAG,CAAC,GAAG,CAAC,WAAW;aACjC,CAAA;IACL,CAAC;AACH,CAAC,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,mBAAU,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,EAAE,oCAAoC,CAAC,CAAA;AAChE,CAAC;AAED,MAAa,wBAAyB,SAAQ,uBAAe;IAC3D,YACW,QAGR,EACD,OAA6C,EAC7C,OAAsB;QAEtB,MAAM,MAAM,GACV,QAAQ,CAAC,UAAU,KAAK,GAAG;YACzB,CAAC,CAAC,0BAAY,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;QAZtD;;;;mBAAS,QAAQ;WAGhB;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;AAxBD,4DAwBC","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'\nimport { AppContext } from './context'\nimport { ids } from './lexicon/lexicons'\nimport { httpLogger } from './logger'\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, 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, 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 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)\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 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)\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 err: unknown,\n message = 'Upstream service unreachable',\n): never {\n httpLogger.error({ err }, message)\n throw new XRPCServerError(ResponseType.UpstreamFailure, message, undefined, {\n cause: err,\n })\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 ids.ChatBskyActorDeleteAccount,\n ids.ChatBskyActorExportAccountData,\n ids.ChatBskyConvoDeleteMessageForSelf,\n ids.ChatBskyConvoGetConvo,\n ids.ChatBskyConvoGetConvoForMembers,\n ids.ChatBskyConvoGetLog,\n ids.ChatBskyConvoGetMessages,\n ids.ChatBskyConvoLeaveConvo,\n ids.ChatBskyConvoListConvos,\n ids.ChatBskyConvoMuteConvo,\n ids.ChatBskyConvoSendMessage,\n ids.ChatBskyConvoSendMessageBatch,\n ids.ChatBskyConvoUnmuteConvo,\n ids.ChatBskyConvoUpdateRead,\n])\n\nexport const PRIVILEGED_METHODS = new LxmSet([\n ...CHAT_BSKY_METHODS,\n ids.ComAtprotoServerCreateAccount,\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 ids.ComAtprotoAdminSendEmail,\n ids.ComAtprotoIdentityRequestPlcOperationSignature,\n ids.ComAtprotoIdentitySignPlcOperation,\n ids.ComAtprotoIdentityUpdateHandle,\n ids.ComAtprotoServerActivateAccount,\n ids.ComAtprotoServerConfirmEmail,\n ids.ComAtprotoServerCreateAppPassword,\n ids.ComAtprotoServerDeactivateAccount,\n ids.ComAtprotoServerGetAccountInviteCodes,\n ids.ComAtprotoServerGetSession,\n ids.ComAtprotoServerListAppPasswords,\n ids.ComAtprotoServerRequestAccountDelete,\n ids.ComAtprotoServerRequestEmailConfirmation,\n ids.ComAtprotoServerRequestEmailUpdate,\n ids.ComAtprotoServerRevokeAppPassword,\n ids.ComAtprotoServerUpdateEmail,\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 ids.ToolsOzoneTeamAddMember:\n case ids.ToolsOzoneTeamDeleteMember:\n case ids.ToolsOzoneTeamUpdateMember:\n case ids.ToolsOzoneTeamListMembers:\n case ids.ToolsOzoneCommunicationCreateTemplate:\n case ids.ToolsOzoneCommunicationDeleteTemplate:\n case ids.ToolsOzoneCommunicationUpdateTemplate:\n case ids.ToolsOzoneCommunicationListTemplates:\n case ids.ToolsOzoneModerationEmitEvent:\n case ids.ToolsOzoneModerationGetEvent:\n case ids.ToolsOzoneModerationGetRecord:\n case ids.ToolsOzoneModerationGetRepo:\n case ids.ToolsOzoneModerationQueryEvents:\n case ids.ToolsOzoneModerationQueryStatuses:\n case ids.ToolsOzoneModerationSearchRepos:\n case ids.ToolsOzoneModerationGetAccountTimeline:\n case ids.ToolsOzoneVerificationListVerifications:\n case ids.ToolsOzoneVerificationGrantVerifications:\n case ids.ToolsOzoneVerificationRevokeVerifications:\n case ids.ToolsOzoneSafelinkAddRule:\n case ids.ToolsOzoneSafelinkUpdateRule:\n case ids.ToolsOzoneSafelinkRemoveRule:\n case ids.ToolsOzoneSafelinkQueryEvents:\n case ids.ToolsOzoneSafelinkQueryRules:\n case ids.ToolsOzoneModerationListScheduledActions:\n case ids.ToolsOzoneModerationCancelScheduledActions:\n case ids.ToolsOzoneModerationScheduleAction:\n return {\n serviceId: 'atproto_labeler',\n serviceInfo: ctx.cfg.modService,\n }\n case ids.ComAtprotoModerationCreateReport:\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.4.211",
3
+ "version": "0.4.213",
4
4
  "license": "MIT",
5
5
  "description": "Reference implementation of atproto Personal Data Server (PDS)",
6
6
  "keywords": [
@@ -48,23 +48,23 @@
48
48
  "zod": "^3.23.8",
49
49
  "@atproto-labs/fetch-node": "^0.2.0",
50
50
  "@atproto-labs/simple-store": "^0.3.0",
51
- "@atproto-labs/simple-store-redis": "^0.0.1",
52
51
  "@atproto-labs/simple-store-memory": "^0.1.4",
52
+ "@atproto-labs/simple-store-redis": "^0.0.1",
53
53
  "@atproto-labs/xrpc-utils": "^0.0.24",
54
- "@atproto/api": "^0.18.21",
54
+ "@atproto/api": "^0.19.1",
55
55
  "@atproto/aws": "^0.2.31",
56
+ "@atproto/common": "^0.5.14",
56
57
  "@atproto/crypto": "^0.4.5",
57
- "@atproto/common": "^0.5.13",
58
58
  "@atproto/identity": "^0.4.12",
59
- "@atproto/lex-cbor": "^0.0.13",
60
- "@atproto/lex-data": "^0.0.12",
61
- "@atproto/lexicon": "^0.6.1",
62
- "@atproto/oauth-provider": "^0.15.10",
63
- "@atproto/oauth-scopes": "^0.3.1",
59
+ "@atproto/lex-cbor": "^0.0.14",
60
+ "@atproto/lex-data": "^0.0.13",
61
+ "@atproto/lexicon": "^0.6.2",
62
+ "@atproto/oauth-provider": "^0.15.12",
63
+ "@atproto/oauth-scopes": "^0.3.2",
64
64
  "@atproto/repo": "^0.8.12",
65
- "@atproto/syntax": "^0.4.3",
65
+ "@atproto/syntax": "^0.5.0",
66
66
  "@atproto/xrpc": "^0.7.7",
67
- "@atproto/xrpc-server": "^0.10.14"
67
+ "@atproto/xrpc-server": "^0.10.15"
68
68
  },
69
69
  "devDependencies": {
70
70
  "@atproto/pds-entryway": "npm:@atproto/pds@0.3.0-entryway.3",
@@ -82,9 +82,9 @@
82
82
  "ts-node": "^10.8.2",
83
83
  "typescript": "^5.6.3",
84
84
  "ws": "^8.12.0",
85
- "@atproto/api": "^0.18.21",
86
- "@atproto/bsky": "^0.0.216",
87
- "@atproto/lex-cli": "^0.9.8",
85
+ "@atproto/api": "^0.19.1",
86
+ "@atproto/bsky": "^0.0.218",
87
+ "@atproto/lex-cli": "^0.9.9",
88
88
  "@atproto/oauth-client-browser-example": "^0.0.10"
89
89
  },
90
90
  "scripts": {
@@ -1,6 +1,5 @@
1
1
  import assert from 'node:assert'
2
2
  import { AtUri } from '@atproto/syntax'
3
- import { XRPCError } from '@atproto/xrpc'
4
3
  import { AppContext } from '../../../../context'
5
4
  import { Server } from '../../../../lexicon'
6
5
  import { ids } from '../../../../lexicon/lexicons'
@@ -14,7 +13,10 @@ import {
14
13
  } from '../../../../lexicon/types/app/bsky/feed/getPostThread'
15
14
  import { Record as PostRecord } from '../../../../lexicon/types/app/bsky/feed/post'
16
15
  import { $Typed } from '../../../../lexicon/util'
17
- import { computeProxyTo } from '../../../../pipethrough'
16
+ import {
17
+ PipethroughUpstreamError,
18
+ computeProxyTo,
19
+ } from '../../../../pipethrough'
18
20
  import {
19
21
  LocalRecords,
20
22
  LocalViewer,
@@ -40,11 +42,14 @@ export default function (server: Server, ctx: AppContext) {
40
42
  try {
41
43
  return await pipethroughReadAfterWrite(ctx, reqCtx, getPostThreadMunge)
42
44
  } catch (err) {
43
- if (err instanceof XRPCError && err.error === 'NotFound') {
45
+ if (
46
+ err instanceof PipethroughUpstreamError &&
47
+ err.error === 'NotFound'
48
+ ) {
44
49
  const { auth, params } = reqCtx
45
50
  const requester = auth.credentials.did
46
51
 
47
- const rev = err.headers && getRepoRev(err.headers)
52
+ const rev = getRepoRev(err.headers)
48
53
  if (!rev) throw err
49
54
 
50
55
  const uri = new AtUri(params.uri)
@@ -4947,6 +4947,10 @@ export const schemaDict = {
4947
4947
  type: 'object',
4948
4948
  required: ['interactions'],
4949
4949
  properties: {
4950
+ feed: {
4951
+ type: 'string',
4952
+ format: 'at-uri',
4953
+ },
4950
4954
  interactions: {
4951
4955
  type: 'array',
4952
4956
  items: {
@@ -18,6 +18,7 @@ const id = 'app.bsky.feed.sendInteractions'
18
18
  export type QueryParams = {}
19
19
 
20
20
  export interface InputSchema {
21
+ feed?: string
21
22
  interactions: AppBskyFeedDefs.Interaction[]
22
23
  }
23
24
 
@@ -9,13 +9,13 @@ import {
9
9
  streamToNodeBuffer,
10
10
  } from '@atproto/common'
11
11
  import { RpcPermissionMatch } from '@atproto/oauth-scopes'
12
- import { ResponseType, XRPCError as XRPCClientError } from '@atproto/xrpc'
13
12
  import {
14
13
  CatchallHandler,
15
14
  HandlerPipeThroughBuffer,
16
15
  HandlerPipeThroughStream,
17
16
  InternalServerError,
18
17
  InvalidRequestError,
18
+ ResponseType,
19
19
  XRPCError as XRPCServerError,
20
20
  excludeErrorResult,
21
21
  parseReqNsid,
@@ -301,15 +301,9 @@ async function pipethroughStream(
301
301
  const passThrough = new PassThrough()
302
302
 
303
303
  void tryParsingError(upstream.headers, passThrough).then((parsed) => {
304
- const xrpcError = new XRPCClientError(
305
- upstream.statusCode === 500
306
- ? ResponseType.UpstreamFailure
307
- : upstream.statusCode,
308
- parsed.error,
309
- parsed.message,
310
- Object.fromEntries(responseHeaders(upstream.headers, false)),
311
- { cause: dispatchOptions },
312
- )
304
+ const xrpcError = new PipethroughUpstreamError(upstream, parsed, {
305
+ cause: dispatchOptions,
306
+ })
313
307
 
314
308
  reject(xrpcError)
315
309
  }, reject)
@@ -356,18 +350,9 @@ async function pipethroughRequest(
356
350
  if (upstream.statusCode >= 400) {
357
351
  const parsed = await tryParsingError(upstream.headers, upstream.body)
358
352
 
359
- // Note "XRPCClientError" is used instead of "XRPCServerError" in order to
360
- // allow users of this function to capture & handle these errors (namely in
361
- // "app.bsky.feed.getPostThread").
362
- throw new XRPCClientError(
363
- upstream.statusCode === 500
364
- ? ResponseType.UpstreamFailure
365
- : upstream.statusCode,
366
- parsed.error,
367
- parsed.message,
368
- Object.fromEntries(responseHeaders(upstream.headers, false)),
369
- { cause: dispatchOptions },
370
- )
353
+ throw new PipethroughUpstreamError(upstream, parsed, {
354
+ cause: dispatchOptions,
355
+ })
371
356
  }
372
357
 
373
358
  return upstream
@@ -635,3 +620,29 @@ const safeString = (str: unknown): string | undefined => {
635
620
  function logResponseError(this: ServerResponse, err: unknown): void {
636
621
  httpLogger.warn({ err }, 'error forwarding upstream response')
637
622
  }
623
+
624
+ export class PipethroughUpstreamError extends XRPCServerError {
625
+ constructor(
626
+ readonly upstream: {
627
+ statusCode: number
628
+ headers: IncomingHttpHeaders
629
+ },
630
+ payload: { message?: string; error?: string },
631
+ options?: ErrorOptions,
632
+ ) {
633
+ const status =
634
+ upstream.statusCode === 500
635
+ ? ResponseType.UpstreamFailure
636
+ : upstream.statusCode
637
+
638
+ super(status, payload.message, payload.error, options)
639
+ }
640
+
641
+ get headers(): Record<string, string> {
642
+ return Object.fromEntries(responseHeaders(this.upstream.headers, false))
643
+ }
644
+
645
+ get error() {
646
+ return this.customErrorName ?? this.typeName
647
+ }
648
+ }